Archilyzer · Source

archilyzer

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

commit 9ff8a0872b62a8595c91c00f39395e17cc9f1345
parent f447488a36287853c29d5d515fd3e4880b34e045
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 14:43:54 -0400

common: task video-assist — checked look/clip/composition ops proposed into assist-proposals.json

videoAssistOps.mjs: look, slide, room, clip_edges, clip_room, fx — each checked
against the manifest as the ops before it left it (the look's own rules, the
clip's source window and a 3 s step, the declared params), with a diff line and
the writer that performs it; the model's one shape {op, id, key, value}. The task
asks once, schema-bound, over the compact view (local fitted to the prompt cap;
the API the same ask; the code route's answers read as a model's) and writes
proposals only. Its own report-draft job: draft:local through the GPU arbiter by
default (local in every preset but api), draft:api metered with a ledger row; a
whole-project note's text as the request, the reply posted back with an assist
proposal. The ops route's dryRun plans it. Synthetic project and a 29-request
table in the test kit; tests on the fake ollama and the fake Anthropic.

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

Diffstat:
MSETTINGS.md | 6++++--
Mcommon/controller/reportDraft.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Acommon/controller/videoAssist.ts | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.test.ts | 16++++++++++++++++
Mcommon/lib/generationSettings.ts | 19+++++++++++++------
Acommon/lib/report/draft/tasks/videoAssist.test.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/videoAssist.ts | 249+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/videoAssistOps.d.mts | 34++++++++++++++++++++++++++++++++++
Acommon/lib/report/videoAssistOps.mjs | 522+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/videoAssistOps.test.ts | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/videoAssistProposals.d.mts | 35+++++++++++++++++++++++++++++++++++
Acommon/lib/report/videoAssistProposals.mjs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 1+
Acommon/testing/clips/assistProject.d.mts | 14++++++++++++++
Acommon/testing/clips/assistProject.mjs | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/_videoAssist.test.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 21++++++++++++++++++++-
Msettings.json.example | 3++-
18 files changed, 1890 insertions(+), 16 deletions(-)

diff --git a/SETTINGS.md b/SETTINGS.md @@ -973,7 +973,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | Key | Default | Description | |---|---|---| -| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. | +| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task but the video assistant's, which stays local), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. | | `routes` | object — see below | Where each task runs: `code`, `api` or `local` (below). | | `models` | object — see below | The model each route runs (below). | | `caps` | object — see below | The spend caps in USD (below). | @@ -1008,6 +1008,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `social` | `"local"` | A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code. | | `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`). | | `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` @@ -1114,7 +1115,8 @@ Default: "social": "local", "verdicts": "local", "frames": "api", - "clips-suggest": "local" + "clips-suggest": "local", + "video-assist": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -139,6 +139,10 @@ export const REPORT_DRAFT_BODY_KEYS = [ "proposals", "note", "answers", + // release 38 lane E: a `video-assist` job's request and scope (it shares + // "project", "note" and "answers" with clips-suggest). + "request", + "scope", ] as const; // A seed's size: a board of a few hundred quotes, with room. @@ -195,6 +199,10 @@ export type ReportDraftBody = { proposals?: string[]; note?: string; answers?: unknown; + // A video-assist job's (release 38 lane E, ./videoAssist.ts): what to + // change, in words, and what it may touch (look | clips | fx | all). + request?: string; + scope?: string; }; // A Claude model the price table knows: one of its ids, or a dated id of one @@ -217,10 +225,14 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod const task = b.task; if (typeof task !== "string" || !TASKS.includes(task as ReportDraftTask)) fail(`"task" is one of ${TASKS.join(", ")}`); const article = b.article; - // A clips-suggest job (release 36 lane D) is on a umtool project, not an article. - const onProject = task === "clips-suggest"; + // 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"; + const assist = task === "video-assist"; if (onProject) { - if (article !== undefined && article !== null && article !== "") fail('a clips-suggest job names its "project" (the reactions project\'s directory), not an article'); + 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'); + } } 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) => { const v = b[k]; @@ -362,7 +374,39 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod const clipsKeys = ["project", "proposals", "note", "answers"] as const; 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`); - if (onProject) { + // The video assistant's (release 38 lane E). + const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null); + if (assistGiven.length && !assist) fail(`${assistGiven.map((k) => `"${k}"`).join(", ")} ${assistGiven.length === 1 ? "is" : "are"} a video-assist job's`); + 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; + if (b.proposals !== undefined && b.proposals !== null) fail('"proposals" is a clips-suggest job\'s'); + if (b.request !== undefined && b.request !== null) { + if (typeof b.request !== "string" || !b.request.trim()) fail('"request" is what to change, in words'); + if (b.request.length > 2000) fail('"request" is at most 2,000 characters'); + out.request = b.request.replace(/\s+/g, " ").trim(); + } + if (b.scope !== undefined && b.scope !== null) { + if (!["look", "clips", "fx", "all"].includes(String(b.scope))) fail('"scope" is look, clips, fx or all'); + out.scope = String(b.scope); + } + if (b.note !== undefined && b.note !== null) { + if (typeof b.note !== "string" || !/^n_[a-z0-9]{4,32}$/.test(b.note)) fail('"note" is a note id (n_…)'); + out.note = b.note; + } + if (b.answers !== undefined && b.answers !== null) { + if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"ops": [{"op", "id", "key", "value"}], "reply"}'); + if (JSON.stringify(b.answers).length > 100_000) fail('"answers" is at most 100,000 characters'); + out.answers = b.answers; + } + if (!out.request && !out.note) fail('a video-assist job needs its "request" (what to change), or the "note" whose text is one'); + if (out.request && out.note) fail('give "request" or "note", not both: a note\'s text is its request'); + 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 video-assist job reads its project: it takes no ${extra.join(", ")}`); + } else if (onProject) { const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the reactions project\'s absolute directory'); out.project = project as string; @@ -424,7 +468,7 @@ function kindOf(task: GenerationTask): Iteration["kind"] { } const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" => - isStepTask(task) || task === "clips-suggest" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep"; + isStepTask(task) || task === "clips-suggest" || task === "video-assist" ? "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; @@ -553,6 +597,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep 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 { + const { enqueueVideoAssist } = await import("./videoAssist"); + return await enqueueVideoAssist(body, deps); + } catch (e) { + return refuse((e as Error).message); + } + } if (body.task === REFRESH_TASK) { if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)'); try { @@ -758,7 +811,8 @@ async function runReportDraft( case "verdicts": case "frames": case "clips-suggest": - // A refresh, a triage, verdict proposals, a frame scan and the clip finder's labels are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts), never this one. + case "video-assist": + // 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": input = diff --git a/common/controller/videoAssist.ts b/common/controller/videoAssist.ts @@ -0,0 +1,226 @@ +// `report-draft {"task": "video-assist", "project", "request" | "note", +// "scope"?, "model"?, "maxUsd"?, "answers"?, "dryRun"?}` — the video +// assistant (release 38 lane E) as an editor job. umtool's Ask box (the Build +// tab's Look panel, the clip editor's side column, a project-level note) +// 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, and it is never inside the corpus) +// request what to change, in words (or `note`: a project-level note's +// text is the request, and the proposals are posted to it as the +// agent's reply with an Apply — `POST <UMTOOL_URL>/api/notes`) +// scope look | clips | fx | all (default): what the ask may touch +// answers the `code` route: a Claude Code session's answer +// (`{ops: [{op, id, key, value}], reply}`), checked exactly as a +// model's — no model is called +// dryRun (the ops route) the plan: the prompt, its estimate; nothing written +// +// Out: `<project>/assist-proposals.json` — PROPOSALS ONLY; nothing is applied. +// Routed by settings.generation.routes["video-assist"] (local by default: +// `draft:local`, every ollama call through the GPU arbiter, so it waits behind +// a transcription; ollama unloaded when the job ends) or the API (`draft:api`: +// the narration cap, the daily cap, its usage in the ledger as task +// `video-assist`). The log ends `@@report-draft {article: "", iteration: 0, +// task: "video-assist", project, status, summary, usd, assist}`. + +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 { + ASSIST_CODE_MODEL, + VIDEO_ASSIST_TASK, + VideoAssistRefusal, + loadAssistProject, + noteReplyOf, + noteRequestOf, + planVideoAssist, + runVideoAssist, + scopeOf, + type VideoAssistOutcome, + type VideoAssistPlan, +} from "../lib/report/draft/tasks/videoAssist"; +import { getWorkerToken } from "../lib/workerToken"; +import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; +import { projectDirOf, umtoolOrigin } from "./clipsSuggest"; +import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; + +export { ASSIST_CODE_MODEL, VIDEO_ASSIST_TASK }; + +/** An Ask on a note: the reply posted to umtool's notes as the agent's, with the proposals' Apply. */ +export type AssistNoteReply = { project: string; note: string; text: string; proposal: { kind: "assist"; at: string; ops: number } | null }; + +export type VideoAssistJobDeps = ReportDraftDeps & { + postReply?: (r: AssistNoteReply) => Promise<void>; + umtoolUrl?: string | null; + workerToken?: string; +}; + +/** POST the reply to umtool's notes as the agent's. */ +export async function postAssistReplyToUmtool(r: AssistNoteReply, o: { umtoolUrl: string; workerToken: string; fetch?: typeof fetch }): Promise<void> { + const f = o.fetch ?? fetch; + const res = await f(`${o.umtoolUrl}/api/notes?project=${encodeURIComponent(r.project)}`, { + method: "POST", + headers: { authorization: `Bearer ${o.workerToken}`, "content-type": "application/json" }, + body: JSON.stringify({ op: { op: "reply", id: r.note, text: r.text, ...(r.proposal ? { proposal: r.proposal } : {}) } }), + }); + if (!res.ok) { + const j = (await res.json().catch(() => ({}))) as { error?: string }; + throw new Error(`umtool refused the reply (${res.status}): ${j.error ?? res.statusText}`); + } +} + +type Refused = { result: StreamActionResult & { ok: false } }; + +/** The model a job runs on: a session's answer is `claude-code`'s; else the asked one, else the route's. */ +function modelOfBody(body: ReportDraftBody, gen: ReturnType<typeof getSettings>["generation"]): string { + if (body.answers !== undefined) return ASSIST_CODE_MODEL; + return modelFor(gen, VIDEO_ASSIST_TASK, body.model); +} + +async function requestOf(body: ReportDraftBody, dir: string): Promise<string> { + if (body.note) return noteRequestOf(dir, body.note); + if (!body.request) throw new VideoAssistRefusal("the assistant needs a request (or a note): say what to change"); + return body.request; +} + +/** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */ +export async function planVideoAssistJob(body: ReportDraftBody, deps: Pick<ReportDraftDeps, "paths" | "settings">): Promise<VideoAssistPlan> { + const gen = (deps.settings ?? getSettings)().generation; + const dir = projectDirOf(body.project ?? "", deps.paths); + const route = gen.routes[VIDEO_ASSIST_TASK]; + const model = body.model ?? (route === "code" ? ASSIST_CODE_MODEL : modelFor(gen, VIDEO_ASSIST_TASK)); + return planVideoAssist({ project: dir, model, request: await requestOf(body, dir), scope: scopeOf(body.scope) }, { llm: llmConfigOf(gen, deps.paths) }); +} + +export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssistJobDeps): 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; + let request: string; + try { + dir = projectDirOf(body.project ?? "", paths); + model = modelOfBody(body, gen); + // Refused at the ask, not at the job's turn: no manifest, no note, no request. + await loadAssistProject(dir); + request = await requestOf(body, dir); + } catch (e) { + return refuse((e as Error).message); + } + const scope = scopeOf(body.scope); + const onNote = !!body.note; + const umtool = deps.umtoolUrl === undefined ? umtoolOrigin() : deps.umtoolUrl; + const token = deps.workerToken ?? getWorkerToken(); + if (onNote && !deps.postReply) { + if (!umtool) return refuse("UMTOOL_URL is not set on the editor: the assistant's reply is posted to umtool's notes"); + if (!token) return refuse("WORKER_TOKEN is not set on the editor: umtool takes the assistant's reply with it"); + } + const provider = model === ASSIST_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 postReply = deps.postReply ?? ((r: AssistNoteReply) => postAssistReplyToUmtool(r, { umtoolUrl: umtool!, workerToken: token })); + 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( + `video-assist${onNote ? ` on ${body.note}` : ""} 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: VideoAssistOutcome | null = null; + try { + out = await runVideoAssist( + { + project: dir, + model, + request, + scope, + ...(body.note ? { note: body.note } : {}), + ...(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: VIDEO_ASSIST_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}`)); + } + if (onNote && out.status === "done" && out.proposals) { + const p = out.proposals; + await postReply({ project: dir, note: body.note!, text: noteReplyOf(p), proposal: p.ops.length ? { kind: "assist", at: p.at, ops: p.ops.length } : null }); + onLog(`replied to ${body.note}`); + } + const p = out.proposals; + onLog( + `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ + article: "", + iteration: 0, + task: VIDEO_ASSIST_TASK, + project: dir, + status: out.status, + summary: out.summary, + usd: out.usd, + assist: { at: p?.at ?? null, proposed: p?.ops.length ?? 0, refused: p?.refused.length ?? 0, diff: p?.diff ?? [], file: out.file, ...(body.note ? { note: body.note } : {}) }, + })}`, + ); + 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/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -165,3 +165,19 @@ test("the clip finder's labels (release 36 lane D): routed like a media draft; a assert.equal(g.routes["clips-suggest"], GENERATION_PRESETS[p]["clips-suggest"]); } }); + +test("the video assistant (release 38 lane E): local in every preset but api; a file from before keeps its preset", () => { + assert.ok((GENERATION_TASKS as readonly string[]).includes("video-assist")); + assert.deepEqual( + (["code", "balanced", "api", "local"] as const).map((p) => GENERATION_PRESETS[p]["video-assist"]), + ["local", "local", "api", "local"], + ); + for (const p of ["code", "balanced", "api", "local"] as const) { + const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "video-assist").map((t) => [t, GENERATION_PRESETS[p][t]])); + const g = sanitizeGeneration({ routes }); + assert.equal(g.preset, p); + assert.equal(g.routes["video-assist"], GENERATION_PRESETS[p]["video-assist"]); + } + // A file that routes nothing: the default (balanced) — local. + assert.equal(sanitizeGeneration({}).routes["video-assist"], "local"); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -29,7 +29,12 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri // (`<project>/clip-suggestions.json`), and an answer to a comment on a clip — // no article, no iteration. Routed like a media draft; `code` = a Claude Code // session answers the request (`/gen`, the MCP's `generate`). -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest"] as const; +// `video-assist` (release 38 lane E): "make the joins 0.15 s" on a video +// project — proposed look / clip / composition edits +// (`<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; 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"]; @@ -41,12 +46,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" }, + 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" }, // 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" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "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" }, + 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" }, } 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[]; @@ -144,7 +149,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { preset: - "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.", + "The balance knob: `code` (Claude Code does every task but the video assistant's, which stays local), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.", routes: "Where each task runs: `code`, `api` or `local` (below).", models: "The model each route runs (below).", caps: "The spend caps in USD (below).", @@ -222,6 +227,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { "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": "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`).", 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/videoAssist.test.ts b/common/lib/report/draft/tasks/videoAssist.test.ts @@ -0,0 +1,124 @@ +// Release 38 lane E: the `video-assist` task on the fake ollama and the fake +// Anthropic — every request of the table asked once on each, the answer +// checked and written as proposals; nothing applied. +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } 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 { ASSIST_NOTE, ASSIST_REQUESTS, answerOf, writeAssistProject } from "../../../../testing/clips/assistProject.mjs"; +import { readAssistProposals } from "../../videoAssistProposals.mjs"; +import { ASSIST_CODE_MODEL, VideoAssistRefusal, noteReplyOf, noteRequestOf, planVideoAssist, runVideoAssist } from "./videoAssist"; +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(), "video-assist-")); + 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 userOfOllama = (body: { messages: { role: string; content: string }[] }) => body.messages.find((m) => m.role === "user")!.content; + +for (const [route, model] of [ + ["local", "qwen3:8b"], + ["api", "claude-sonnet-5-5"], +] as const) { + test(`every request of the table on the ${route} model: one ask, the ops checked, assist-proposals.json written, the manifest untouched`, async () => { + for (const [i, row] of ASSIST_REQUESTS.entries()) { + const dir = path.join(tmp, `${route}-${i}`); + const { manifest } = writeAssistProject(dir, { deck: !!row.deck }); + 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 = userOfOllama(body); + return jsonReply(answerOf(row)); + }); + } else { + api.push((body: { messages: { content: unknown }[] }) => { + prompt = JSON.stringify(body.messages[0]!.content); + return toolTurn("answer", answerOf(row)); + }); + } + const out = await runVideoAssist({ project: dir, model, request: row.request, scope: row.scope ?? "all" }, { llm, now: () => new Date("2026-10-20T00:00:00.000Z") }); + assert.equal(out.status, "done", row.request); + assert.ok(prompt.includes(`THE REQUEST:${route === "api" ? "\\n" : "\n"}${row.request}`), `${row.request}: the request is in the prompt`); + const { doc } = await readAssistProposals(dir); + assert.ok(doc, row.request); + assert.deepEqual(doc!.diff, row.diff, row.request); + assert.deepEqual(doc!.ops.map((o) => o.status), row.diff.map(() => "proposed")); + assert.equal(doc!.refused.length, row.refused.length, `${row.request}: ${JSON.stringify(doc!.refused)}`); + doc!.refused.forEach((r, k) => assert.match(r.why, row.refused[k]!, row.request)); + assert.equal(doc!.model, model); + assert.equal(doc!.request, row.request); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before, `${row.request}: nothing applied`); + assert.ok(manifest); + } + if (route === "local") { + // Every local ask fitted under the GPU's prompt cap (the fake refuses one over it). + assert.ok(ol.requests.every((b: { format?: unknown }) => !!b.format), "schema-bound"); + } + }); +} + +test("the local view is fitted to the prompt cap however long the cut", async () => { + const dir = path.join(tmp, "long"); + const { manifest } = writeAssistProject(dir); + for (let i = 5; i <= 400; i++) manifest.timeline.push({ type: "clip", id: `r${i}`, channel: "c", video: "v", start: i * 60, end: i * 60 + 30, cutStart: i * 60 + 5, cutEnd: i * 60 + 25, quote: "words ".repeat(30) }); + await import("node:fs/promises").then((fs) => fs.writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest))); + const plan = await planVideoAssist({ project: dir, model: "qwen3:8b", request: "end r333 a second later" }, { llm }); + assert.ok(plan.estimate.inputTokens <= PROMPT_CAP_TOKENS, String(plan.estimate.inputTokens)); + assert.match(plan.request.user, /- r333: cut 19985–20005 s/); + assert.match(plan.request.user, /- r399 \(not shown in full\)/); + assert.equal(plan.estimate.usd, 0); + const api = await planVideoAssist({ project: dir, model: "claude-sonnet-5-5", request: "quicker joins" }, { llm }); + assert.ok(api.estimate.usd > 0); +}); + +test("the code route: a session's answer is checked as a model's, written as claude-code's; junk is refused", async () => { + const dir = path.join(tmp, "code"); + writeAssistProject(dir); + const asked = api.requests.length + ol.requests.length; + const out = await runVideoAssist({ project: dir, model: ASSIST_CODE_MODEL, request: "no QR", answers: { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." } }, { llm }); + assert.equal(out.status, "done"); + assert.equal(api.requests.length + ol.requests.length, asked, "no model asked"); + const { doc } = await readAssistProposals(dir); + assert.equal(doc!.model, "claude-code"); + assert.deepEqual(doc!.diff, ["QR code on → off"]); + assert.equal(doc!.reply, "QR off."); + await assert.rejects(runVideoAssist({ project: dir, model: ASSIST_CODE_MODEL, request: "x", answers: { nope: 1 } }, { llm }), /the session's answer is refused: the answer has no ops list/); +}); + +test("refusals at the ask: no manifest, no request, an API ask over its cap; a note's text is a request only on the whole project", async () => { + await assert.rejects(runVideoAssist({ project: path.join(tmp, "none"), model: "qwen3:8b", request: "x" }, { llm }), /holds no video\.manifest\.json/); + const dir = path.join(tmp, "refusals"); + writeAssistProject(dir, { note: "make the joins quicker" }); + await assert.rejects(runVideoAssist({ project: dir, model: "qwen3:8b", request: " " }, { llm }), VideoAssistRefusal); + await assert.rejects(runVideoAssist({ project: dir, model: "claude-sonnet-5-5", request: "quicker joins", maxUsd: 0.000001 }, { llm }), /is over its cap/); + assert.equal(await noteRequestOf(dir, ASSIST_NOTE), "make the joins quicker"); + await assert.rejects(noteRequestOf(dir, "n_absent00"), /no note n_absent00/); +}); + +test("a note's reply: the proposals in words, the refusals, where to apply", () => { + const text = noteReplyOf({ + version: 1, promptVersion: "video-assist-1", at: "t", model: "m", request: "r", scope: "all", reply: "Quicker joins.", + ops: [{ id: "a1", op: { op: "look" }, diff: "join 0.22 s → 0.15 s", status: "proposed" }], + refused: [{ op: {}, why: "render.transition must be a number of seconds from 0 (a hard cut) to 3" }], + diff: ["join 0.22 s → 0.15 s"], + }); + assert.equal(text, "Quicker joins.\nProposed 1 edit — Apply below or in the Build tab's Look panel:\n• join 0.22 s → 0.15 s\n• not done: render.transition must be a number of seconds from 0 (a hard cut) to 3"); +}); diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts @@ -0,0 +1,249 @@ +// THE `video-assist` TASK (release 38 lane E): "make the joins 0.15 s with +// less smear" on a video project, as PROPOSALS the operator applies. +// +// in a video project's directory (its video.manifest.json), a request in +// words, a scope (look | clips | fx | all: what the view shows and the +// ops may touch), and on the `code` route a Claude Code session's +// answer (`answers`, read exactly as a model's) +// ask ONE schema-bound ask (videoAssistOps ASSIST_OPS_SCHEMA: `{ops: +// [{op, id, key, value}], reply}`) over the project's compact view -- +// the look, the slide, the room, the clips with their edges and +// windows, the declared params of the compositions it draws +// (assistView) -- fitted to the prompt cap on a local model; the +// same ask on the Claude API (no tool loop: one answer is the batch) +// check every op against the manifest (checkAssistOps: the look's rules, +// the clip's window and the 3 s slack, the declared params) +// out `<project>/assist-proposals.json` (videoAssistProposals.mjs): the +// kept ops with their diff lines, the refused with their reasons. +// NOTHING IS APPLIED: umtool's Apply does that, op by op, through +// the manifest's writers. +// +// It never writes the manifest, notes.json or a clip. 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 { ASSIST_OPS_SCHEMA, ASSIST_OPS_TEXT, ASSIST_SCOPES, assistView, checkAssistOps, type AssistScope } from "../../videoAssistOps.mjs"; +import { ASSIST_PROMPT_VERSION, proposalsDocOf, writeAssistProposals, type AssistProposals } from "../../videoAssistProposals.mjs"; +import { fitLocalAsk } from "./revise-report"; + +export const VIDEO_ASSIST_TASK = "video-assist" as const; +/** The `model` a Claude Code session's answer is written under (the `code` route). */ +export const ASSIST_CODE_MODEL = "claude-code"; +/** A request's length, at most. */ +export const ASSIST_REQUEST_MAX = 2000; +const ANSWER_TOKENS = 700; +/** The view's budget on the API (a local model's is fitted to its cap). */ +const API_VIEW_CHARS = 24_000; + +export class VideoAssistRefusal extends Error {} + +export type VideoAssistDeps = { + 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 VideoAssistInput = { + project: string; + model: string; + request: string; + scope?: AssistScope; + note?: string; + maxUsd?: number; + answers?: unknown; +}; + +export const scopeOf = (s: unknown): AssistScope => ((ASSIST_SCOPES as readonly string[]).includes(String(s)) ? (s as AssistScope) : "all"); + +/** A video project: its manifest (refused without one). */ +export async function loadAssistProject(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 VideoAssistRefusal(`${dir} holds no video.manifest.json: the assistant works on 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 VideoAssistRefusal(`${dir}/video.manifest.json is not a cut (${(e as Error).message})`); + } +} + +/** A project-level note's text, as the request (an Ask on a note). */ +export async function noteRequestOf(dir: string, noteId: string): Promise<string> { + let doc: unknown = null; + try { + doc = JSON.parse(await readFile(path.join(dir, "notes.json"), "utf8")); + } catch { + throw new VideoAssistRefusal(`${dir} has no notes.json: no note ${noteId}`); + } + const notes = (doc as { notes?: unknown[] })?.notes; + const n = Array.isArray(notes) ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown } } | undefined) : undefined; + if (!n) throw new VideoAssistRefusal(`no note ${noteId} in ${dir}/notes.json`); + if (n.anchor?.kind !== "whole") throw new VideoAssistRefusal(`${noteId} is on a part of the project: the assistant answers a note on the whole project (a clip's note is the clip editor's Ask)`); + if (n.status !== "open") throw new VideoAssistRefusal(`${noteId} is resolved`); + const text = typeof n.text === "string" ? n.text.trim() : ""; + if (!text) throw new VideoAssistRefusal(`${noteId} has no text`); + return text.slice(0, ASSIST_REQUEST_MAX); +} + +const SYSTEM = (scope: AssistScope) => + [ + "You adjust a video project's settings for its editor. You read the project's settings now and a request in plain words, and answer with the edit operations that carry it out — nothing else changes.", + "Rules: use only the operations and keys below; give the new value (\"quicker joins\" → a shorter transition than now; \"louder\" → a higher loudness target than now; \"less\" or \"more\" of something → a value a clear step from the current one, within its bounds).", + "If the request asks for something no operation can do, or a value outside the bounds shown, give no op for it and say so in `reply`.", + scope === "all" ? "" : `Only ${scope === "look" ? "the look, the slide and the room" : scope === "clips" ? "the clips' edges and room" : "the compositions' params"} may change.`, + "`reply` is one short plain sentence for the editor: what you changed, or why not.", + "", + ASSIST_OPS_TEXT, + ] + .filter(Boolean) + .join("\n"); + +const userOf = (request: string, view: string) => `THE REQUEST:\n${request}\n\nTHE PROJECT NOW:\n${view}\n\nAnswer with the ops that carry out the request, and the reply.`; + +/** The prompt one ask sends: on a local model the view is fitted to its prompt cap. */ +export function assistPrompt(o: { manifest: unknown; request: string; scope: AssistScope; model: string; llm: LlmConfig }): { system: string; user: string; tokens: number } { + const system = SYSTEM(o.scope); + const build = (maxChars: number) => userOf(o.request, assistView(o.manifest, { maxChars: maxChars - o.request.length - 120, request: o.request, scope: o.scope }).text); + if (providerOf(o.model) === "local") { + const fitted = fitLocalAsk({ llm: o.llm, model: o.model, system, schema: ASSIST_OPS_SCHEMA, build }); + return { system, user: fitted.user, tokens: fitted.tokens }; + } + const user = build(API_VIEW_CHARS); + return { system, user, tokens: structuredPromptEstimate({ system, user, schema: ASSIST_OPS_SCHEMA }) }; +} + +export type VideoAssistPlan = { + project: string; + model: string; + provider: "api" | "local" | "code"; + promptVersion: string; + scope: AssistScope; + estimate: { inputTokens: number; outputTokens: number; usd: number }; + // The request a Claude Code session answers (the `code` route). + request: { system: string; user: string; schema: object }; +}; + +/** What one ask would send, and roughly what it costs — nothing called, nothing written. */ +export async function planVideoAssist(input: Omit<VideoAssistInput, "answers" | "maxUsd" | "note">, deps: Pick<VideoAssistDeps, "llm">): Promise<VideoAssistPlan> { + const { manifest } = await loadAssistProject(input.project); + const scope = scopeOf(input.scope); + const code = input.model === ASSIST_CODE_MODEL; + const pr = assistPrompt({ manifest, request: input.request, scope, model: code ? "claude-sonnet-5-5" : input.model, llm: deps.llm }); + const p = priceOf(code ? "claude-sonnet-5-5" : 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: ASSIST_PROMPT_VERSION, + scope, + estimate: { inputTokens: pr.tokens, outputTokens: ANSWER_TOKENS, usd: Math.round(usd * 10_000) / 10_000 }, + request: { system: pr.system, user: pr.user, schema: ASSIST_OPS_SCHEMA }, + }; +} + +export type VideoAssistOutcome = { + status: "done" | "cancelled" | "failed"; + project: string; + model: string; + request: string; + scope: AssistScope; + proposals: AssistProposals | null; + file: string | null; + usd: number; + byModel: ReturnType<Meter["summary"]>["byModel"]; + summary: string; +}; + +const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; + +/** The answer's ops and reply, or why it is not one. */ +export function parseAssistAnswer(raw: unknown): { ok: true; ops: unknown[]; reply: string } | { ok: false; error: string } { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "the answer is not { ops: [...] }" }; + const a = raw as { ops?: unknown; reply?: unknown }; + if (!Array.isArray(a.ops)) return { ok: false, error: "the answer has no ops list" }; + if (a.ops.length > 40) return { ok: false, error: `${a.ops.length} ops is more than one request needs (at most 40)` }; + return { ok: true, ops: a.ops, reply: typeof a.reply === "string" ? a.reply : "" }; +} + +/** One ask (or a session's answer), checked, written as proposals. */ +export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistDeps): Promise<VideoAssistOutcome> { + const log = deps.log ?? (() => {}); + const now = () => deps.now?.() ?? new Date(); + const request = input.request.replace(/\s+/g, " ").trim(); + if (!request) throw new VideoAssistRefusal("the assistant needs a request: say what to change"); + if (request.length > ASSIST_REQUEST_MAX) throw new VideoAssistRefusal(`a request is at most ${ASSIST_REQUEST_MAX} characters`); + const scope = scopeOf(input.scope); + const { manifest } = await loadAssistProject(input.project); + const meter = new Meter(); + const base = { project: input.project, model: input.model, request, scope }; + let raw: unknown; + if (input.answers !== undefined) { + log(`video-assist ${input.project}: a Claude Code session's answer (prompt ${ASSIST_PROMPT_VERSION})`); + raw = input.answers; + } else { + const pr = assistPrompt({ manifest, request, scope, model: input.model, llm: deps.llm }); + log(`video-assist ${input.project} on ${input.model} (${scope}): one ask, ~${pr.tokens} prompt tokens (prompt ${ASSIST_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 VideoAssistRefusal(`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, ASSIST_OPS_SCHEMA, input.model, 2048); + } catch (e) { + if (deps.signal?.aborted) return { ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }; + throw e; + } + } + const parsed = parseAssistAnswer(raw); + if (!parsed.ok) { + if (input.answers !== undefined) throw new VideoAssistRefusal(`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 { ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }; + // Checked against the manifest as it is NOW: a cut edited while the model thought is what the ops meet. + const fresh = (await loadAssistProject(input.project)).manifest; + const checked = checkAssistOps(fresh, parsed.ops, { request, scope }); + for (const k of checked.ops) log(` proposed: ${k.diff}${k.warning ? ` (${k.warning})` : ""}`); + for (const r of checked.refused) log(` refused: ${JSON.stringify(r.op).slice(0, 120)} — ${r.why}`); + const proposals = proposalsDocOf({ + at: now().toISOString(), + model: input.model, + request, + scope, + ...(input.note ? { note: input.note } : {}), + reply: parsed.reply || null, + checked, + }); + const file = await writeAssistProposals(input.project, proposals); + const usd = Math.round(meter.usd * 1e6) / 1e6; + const summary = + (checked.ops.length ? `${plural(checked.ops.length, "edit")} proposed (${checked.diff.join("; ")})` : "no edit 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 }; +} + +/** The reply an Ask on a note posts: the proposals in words, and where they are applied. */ +export function noteReplyOf(p: AssistProposals): string { + const kept = p.ops.map((o) => `• ${o.diff}${o.warning ? ` (${o.warning})` : ""}`); + const refused = p.refused.map((r) => `• not done: ${r.why}`); + const head = kept.length ? `Proposed ${plural(kept.length, "edit")} — Apply below or in the Build tab's Look panel:` : "No edit proposed."; + return [p.reply ? p.reply : "", head, ...kept, ...refused].filter(Boolean).join("\n").slice(0, 3800); +} diff --git a/common/lib/report/videoAssistOps.d.mts b/common/lib/report/videoAssistOps.d.mts @@ -0,0 +1,34 @@ +// Types for ./videoAssistOps.mjs (release 38 lane E): the video assistant's checked ops. + +export type AssistOpName = "look" | "slide" | "room" | "clip_edges" | "clip_room" | "fx"; +export type AssistScope = "look" | "clips" | "fx" | "all"; +export type AssistOp = { op: AssistOpName } & Record<string, unknown>; + +/** How a kept op is performed: the look's writer, the clip editor's, or the composition's. */ +export type AssistApply = + | { writer: "render"; patch: Record<string, unknown> } + | { writer: "clip"; body: { op: "trim"; clip: string; cutStart: number; cutEnd: number } | { op: "room"; clip: string; room: false | { tail?: boolean; head?: boolean } | null } } + | { writer: "chrome"; id: string; param: string; value: unknown }; + +export type CheckedAssistOp = { op: AssistOp; diff: string; apply: AssistApply; warning?: string }; +export type RefusedAssistOp = { index: number; op: unknown; why: string }; + +export const ASSIST_OP_NAMES: readonly AssistOpName[]; +export const ASSIST_SCOPES: readonly AssistScope[]; +export const EDGE_SLACK_SECONDS: number; +export const MIN_CUT_SECONDS: number; +export function secondsNamedIn(request: string): number; +export function lookWords(key: string, value: unknown, render?: Record<string, unknown>): string; +export function clipWindow( + entry: Record<string, unknown>, + render?: Record<string, unknown>, +): { cut: { start: number; end: number }; window: { start: number; end: number }; hasCut: boolean }; +export function checkAssistOps( + manifest: unknown, + ops: readonly unknown[], + o?: { request?: string; scope?: string }, +): { ops: CheckedAssistOp[]; refused: RefusedAssistOp[]; diff: string[]; manifest: Record<string, unknown> }; +export function assistView(manifest: unknown, o?: { maxChars?: number; request?: string; scope?: string }): { text: string; clips: { shown: string[]; short: string[] } }; +export const ASSIST_OPS_TEXT: string; +export function normalizeAssistOp(raw: unknown): unknown; +export const ASSIST_OPS_SCHEMA: Readonly<Record<string, unknown>>; diff --git a/common/lib/report/videoAssistOps.mjs b/common/lib/report/videoAssistOps.mjs @@ -0,0 +1,522 @@ +// THE VIDEO ASSISTANT'S OPS (release 38 lane E): "make the joins 0.15 s with +// less smear" as checked edits of a video project's manifest. A model (or a +// Claude Code session, or nobody: every op is also a field of the Look panel +// or the clip editor) proposes them; code checks each against the manifest +// as it is; the operator applies them. Nothing here writes a file. +// +// look {key, value} a LOOK_KEYS render key (common look.mjs), checked by applyLookPatch +// slide {travel?, blur?, grain?} the blur slide's knobs, within SLIDE_BOUNDS +// room {tail?, head?, maxS?, minGap?} room at the clips' edges, within ROOM_BOUNDS +// clip_edges {id, start?, end?} a clip's cut, in source seconds: inside the clip's source +// window and at most EDGE_SLACK_SECONDS from where it is, +// unless the request itself names more seconds +// clip_room {id, tail?, head?, off?, reset?} one clip's room (off: none; reset: the cut's again) +// fx {id, param, value} a DECLARED param of a composition the cut draws +// (./fxParams.mjs) -- never free HTML +// +// Each op is applied in turn to a COPY of the manifest, so a later op is +// checked against the earlier ones; a refused op refuses itself only, with its +// reason. Each kept op carries a diff line ("join 0.22 s → 0.15 s") and the +// writer that performs it (`apply`): umtool's updateRender for the look, the +// clip editor's writer (runClipEditorOp trim / room) for a clip, updateChrome +// for a composition. umtool re-checks an op against the manifest at Apply +// time (checkAssistOps on it again), so a proposal made against an older +// manifest is applied to the current one or refused -- never written blind. +// +// PURE. Plain ESM with a .d.mts beside it. + +import { + LOOK_KEYS, + LOUDNESS_MAX, + LOUDNESS_MIN, + ROOM, + ROOM_BOUNDS, + SLIDE_BOUNDS, + SLIDE_DEFAULTS, + TRANSITION_DEFAULT, + TRANSITION_MAX, + TRANSITION_STYLES, + applyLookPatch, + clipRoom, + validateRoom, +} from "./look.mjs"; +import { COMPOSITION_PARAMS, chromeWithParam, compositionOn, compositionsOn, paramOf, paramValue, paramValueError } from "./fxParams.mjs"; + +export const ASSIST_OP_NAMES = Object.freeze(["look", "slide", "room", "clip_edges", "clip_room", "fx"]); +export const ASSIST_SCOPES = Object.freeze(["look", "clips", "fx", "all"]); +/** A clip's edge moves at most this far (s) in one op, unless the request names more seconds. */ +export const EDGE_SLACK_SECONDS = 3; +/** The shortest cut a clip may have (the clip editor's writer refuses less). */ +export const MIN_CUT_SECONDS = 0.5; + +const SCOPE_OF = Object.freeze({ look: "look", slide: "look", room: "look", clip_edges: "clips", clip_room: "clips", fx: "fx" }); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r2 = (n) => Math.round(n * 100) / 100; +const s2 = (n) => r2(n).toFixed(2).replace(/\.?0+$/, "") || "0"; + +class Refusal extends Error {} +const refuse = (why) => { + throw new Refusal(why); +}; + +/** A number from what a model wrote ("0.15", "0.15 s", 0.15). */ +function numOf(v, what) { + if (fin(v)) return v; + if (typeof v === "string") { + const m = /^\s*(-?\d+(?:\.\d+)?)\s*(?:s|sec|secs|seconds?|lufs|px)?\s*$/i.exec(v); + if (m) return Number(m[1]); + } + return refuse(`${what} must be a number`); +} + +const boolOf = (v, what) => { + if (typeof v === "boolean") return v; + if (v === "on" || v === "true") return true; + if (v === "off" || v === "false") return false; + return refuse(`${what} must be true or false`); +}; + +/** The most seconds the request names ("the first 5 seconds", "2.5 s"), or 0. */ +export function secondsNamedIn(request) { + let most = 0; + for (const m of String(request ?? "").matchAll(/(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)\b/gi)) most = Math.max(most, Number(m[1])); + return most; +} + +// --------------------------------------------------------------------------- +// What each setting is called in a diff line. +// --------------------------------------------------------------------------- + +const STYLE_WORDS = Object.freeze({ fade: "crossfade", fadeblack: "dip to black", fadewhite: "dip to white", dissolve: "dissolve", blurslide: "blur slide" }); + +/** A look key's value as a person reads it. */ +export function lookWords(key, value, render = {}) { + switch (key) { + case "transition": + return value === undefined || value === null ? `${s2(TRANSITION_DEFAULT)} s` : Number(value) === 0 ? "a hard cut" : `${s2(Number(value))} s`; + case "transitionStyle": + return STYLE_WORDS[value ?? "fade"] ?? String(value); + case "headerHeight": + case "footerHeight": + return value === 0 ? "off" : value === undefined || value === null ? "on" : `${value} px`; + case "qr": + return value === false ? "off" : "on"; + case "loudness": + return isObj(value) && fin(value.target) ? `${s2(value.target)} LUFS` : "as recorded"; + case "captions": + return isObj(value) ? `on${value.size === "l" ? " (large)" : ""}` : "off"; + case "room": { + const r = isObj(value) ? value : {}; + const edges = ["tail", "head"].filter((k) => r[k] === true); + return edges.length ? edges.join(" + ") : "off"; + } + case "slide": { + const s = { ...SLIDE_DEFAULTS, ...(isObj(value) ? value : {}) }; + return `travel ${s2(s.travel)}, smear ${s2(s.blur)}, grain ${s2(s.grain)}`; + } + default: + return JSON.stringify(value ?? null); + } +} + +const LOOK_LABEL = Object.freeze({ + transition: "join", + transitionStyle: "join style", + headerHeight: "header", + footerHeight: "timeline footer", + qr: "QR code", + loudness: "loudness", + captions: "speaker captions", + room: "room at the edges", + slide: "blur slide", +}); +const SLIDE_LABEL = Object.freeze({ travel: "slide travel", blur: "smear", grain: "grain" }); +const ROOM_LABEL = Object.freeze({ tail: "room tail", head: "room head", maxS: "room tail up to", minGap: "room's silence gap" }); + +const onOff = (b) => (b ? "on" : "off"); +const arrow = (label, from, to) => `${label} ${from} → ${to}`; + +// --------------------------------------------------------------------------- +// One op, normalised and checked against the manifest as it is. +// --------------------------------------------------------------------------- + +/** A clip's cut and the window it may move in. */ +export function clipWindow(entry, render = {}) { + const hasCut = fin(entry.cutStart) && fin(entry.cutEnd); + const cut = { start: hasCut ? entry.cutStart : entry.start, end: hasCut ? entry.cutEnd : entry.end }; + // A clip with a cut moves inside its extent (start–end, what was reviewed + // and fetched); one without inside its edges widened by the fetch pad. + const pad = hasCut ? 0 : fin(render.fetchPad) ? render.fetchPad : 0; + const lo = Math.max(0, (fin(entry.start) ? entry.start : cut.start) - pad); + const hi = (fin(entry.end) ? entry.end : cut.end) + pad; + return { cut, window: { start: r2(lo), end: r2(hi) }, hasCut }; +} + +const clipOf = (manifest, id) => { + if (typeof id !== "string" || !id) refuse("a clip op names its clip (id)"); + const e = (manifest.timeline ?? []).find((x) => x?.id === id); + if (!e) refuse(`no clip "${id}" in the cut`); + if (e.type !== "clip") refuse(`"${id}" is a ${e.type ?? "non-clip"} entry, not a clip`); + return e; +}; + +/** A look key's patch value from what a model wrote. */ +function lookValueOf(key, value, render) { + if (value === null) return null; + switch (key) { + case "transition": + return numOf(value, "the join's length"); + case "headerHeight": + case "footerHeight": + if (typeof value === "boolean") return value ? null : 0; + return numOf(value, `the ${LOOK_LABEL[key]}'s height`); + case "qr": + return boolOf(value, "the QR code"); + case "loudness": + if (value === false || value === "off") return null; + if (isObj(value)) return { target: numOf(value.target, "the loudness target") }; + return { target: numOf(value, "the loudness target") }; + case "captions": + if (value === true || value === "on") return isObj(render.captions) ? render.captions : { style: "speakers" }; + if (value === false || value === "off") return null; + return value; + case "room": + if (value === false || value === "off") return null; + if (isObj(value)) return { ...(isObj(render.room) ? render.room : {}), ...value }; + return value; + case "slide": + if (isObj(value)) return { ...(isObj(render.slide) ? render.slide : {}), ...value }; + return value; + default: + return value; + } +} + +/** + * One op against `manifest` (mutated: the op's effect is applied to it). + * Returns `{ op, diff, apply }` or throws a Refusal. + */ +function checkOne(manifest, raw, ctx) { + const op = isObj(raw) ? raw : refuse("an op is an object"); + const name = op.op; + if (!ASSIST_OP_NAMES.includes(name)) refuse(`no op "${String(name)}" — the ops are ${ASSIST_OP_NAMES.join(", ")}`); + if (ctx.scope !== "all" && SCOPE_OF[name] !== ctx.scope) refuse(`a ${name} op is outside what was asked about (${ctx.scope})`); + const render = isObj(manifest.render) ? manifest.render : {}; + const montage = render.montage !== undefined && render.montage !== null; + const lookPatch = (patch, diff, norm, label) => { + const r = applyLookPatch(manifest, patch); + if (r.errors.length) refuse(r.errors.join("; ")); + if (JSON.stringify(r.render) === JSON.stringify(render)) refuse(`${label} is already that`); + manifest.render = r.render; + return { op: norm, diff, apply: { writer: "render", patch } }; + }; + switch (name) { + case "look": { + const key = typeof op.key === "string" ? op.key.trim() : ""; + if (!LOOK_KEYS.includes(key)) refuse(`"${key}" is not a look setting (${LOOK_KEYS.join(", ")})`); + if (montage && (key === "loudness" || key === "captions" || key === "room")) refuse(`a montage has no ${LOOK_LABEL[key]} of the look's (render.montage sets its own)`); + const value = lookValueOf(key, op.value, render); + const after = value === null ? undefined : value; + const diff = arrow(LOOK_LABEL[key], lookWords(key, render[key], render), lookWords(key, after, render)); + return lookPatch({ [key]: value }, diff, { op: "look", key, value }, LOOK_LABEL[key]); + } + case "slide": { + const given = Object.keys(SLIDE_BOUNDS).filter((k) => op[k] !== undefined && op[k] !== null); + if (!given.length) refuse("a slide op sets travel, blur (the smear) or grain"); + const was = { ...SLIDE_DEFAULTS, ...(isObj(render.slide) ? render.slide : {}) }; + const next = { ...(isObj(render.slide) ? render.slide : {}) }; + const parts = []; + for (const k of given) { + const v = numOf(op[k], SLIDE_LABEL[k]); + const [lo, hi] = SLIDE_BOUNDS[k]; + if (v < lo || v > hi) refuse(`${SLIDE_LABEL[k]} ${s2(v)} is outside ${lo}–${hi}`); + next[k] = r2(v); + if (r2(v) !== r2(was[k])) parts.push(arrow(SLIDE_LABEL[k], s2(was[k]), s2(v))); + } + if (!parts.length) refuse(`the blur slide is already ${given.map((k) => `${SLIDE_LABEL[k]} ${s2(was[k])}`).join(", ")}`); + const style = render.transitionStyle ?? "fade"; + const r = lookPatch({ slide: next }, parts.join(", "), { op: "slide", ...Object.fromEntries(given.map((k) => [k, next[k]])) }, "the blur slide"); + // The knobs move a blur slide only: say so rather than let it look like it worked. + return style === "blurslide" ? r : { ...r, warning: `the join is a ${STYLE_WORDS[style] ?? style}: the slide's knobs show once the join style is blur slide` }; + } + case "room": { + if (montage) refuse("a montage has no room at the edges (it cuts to its phrases)"); + const was = isObj(render.room) ? render.room : {}; + const next = { ...was }; + const parts = []; + for (const k of ["tail", "head"]) { + if (op[k] === undefined || op[k] === null) continue; + // "keep 2 s after the last word": a number for the tail is the tail on, up to that. + if (k === "tail" && typeof op[k] !== "boolean" && op.maxS === undefined) { + const n = numOf(op[k], "the room's tail"); + next.tail = true; + op.maxS = n; + } else next[k] = boolOf(op[k], ROOM_LABEL[k]); + if ((was[k] === true) !== next[k]) parts.push(arrow(ROOM_LABEL[k], onOff(was[k] === true), onOff(next[k]))); + } + for (const k of ["maxS", "minGap"]) { + if (op[k] === undefined || op[k] === null) continue; + const v = numOf(op[k], ROOM_LABEL[k]); + const [lo, hi] = ROOM_BOUNDS[k]; + if (v < lo || v > hi) refuse(`${ROOM_LABEL[k]} ${s2(v)} s is outside ${lo}–${hi} s`); + next[k] = r2(v); + const before = fin(was[k]) ? was[k] : ROOM[k]; + if (r2(before) !== r2(v)) parts.push(arrow(ROOM_LABEL[k], `${s2(before)} s`, `${s2(v)} s`)); + } + if (!parts.length) refuse("the room is already that"); + if (next.tail !== true && next.head !== true && (next.maxS !== undefined || next.minGap !== undefined) && op.tail === undefined && op.head === undefined) { + // A number for an edge that is off would do nothing: turn the tail on with it. + next.tail = true; + op.tail = true; + parts.unshift(arrow(ROOM_LABEL.tail, "off", "on")); + } + const norm = { op: "room", ...Object.fromEntries(["tail", "head", "maxS", "minGap"].filter((k) => op[k] !== undefined && op[k] !== null).map((k) => [k, next[k]])) }; + const r = lookPatch({ room: next }, parts.join(", "), norm, "the room"); + return (render.transition ?? TRANSITION_DEFAULT) === 0 ? { ...r, warning: "the cut has hard cuts (join 0 s): room needs a join to make room for" } : r; + } + case "clip_edges": { + const e = clipOf(manifest, op.id); + const { cut, window } = clipWindow(e, render); + const start = op.start === undefined || op.start === null ? cut.start : r2(numOf(op.start, "the clip's in")); + const end = op.end === undefined || op.end === null ? cut.end : r2(numOf(op.end, "the clip's out")); + if (start === cut.start && end === cut.end) refuse(`${e.id} is already cut ${s2(cut.start)}–${s2(cut.end)} s`); + if (!(end - start >= MIN_CUT_SECONDS)) refuse(`${e.id}: a cut is at least ${MIN_CUT_SECONDS} s (${s2(start)}–${s2(end)})`); + if (start < window.start - 0.005 || end > window.end + 0.005) { + refuse(`${e.id}: ${s2(start)}–${s2(end)} s is outside the clip's source window (${s2(window.start)}–${s2(window.end)} s) — widen it in the clip editor first`); + } + const slack = Math.max(EDGE_SLACK_SECONDS, ctx.namedSeconds); + const moved = Math.max(Math.abs(start - cut.start), Math.abs(end - cut.end)); + if (moved > slack + 0.005) { + refuse(`${e.id}: moves an edge ${s2(moved)} s; one op moves an edge at most ${s2(slack)} s (name the seconds in the request, or drag it in the clip editor)`); + } + const parts = []; + if (start !== cut.start) parts.push(arrow(`${e.id} in`, `${s2(cut.start)} s`, `${s2(start)} s`)); + if (end !== cut.end) parts.push(arrow(`${e.id} out`, `${s2(cut.end)} s`, `${s2(end)} s`)); + // The manifest as it would be: the clip editor's trim (a cut inside the extent, or the edges themselves). + if (fin(e.cutStart) && fin(e.cutEnd)) { + e.cutStart = start; + e.cutEnd = end; + } else { + e.start = start; + e.end = end; + } + return { op: { op: "clip_edges", id: e.id, start, end }, diff: parts.join(", "), apply: { writer: "clip", body: { op: "trim", clip: e.id, cutStart: start, cutEnd: end } } }; + } + case "clip_room": { + const e = clipOf(manifest, op.id); + if (montage) refuse("a montage has no room at the edges (it cuts to its phrases)"); + const words = (room) => { + const r = clipRoom({ room }, render); + return room === undefined || room === null ? `the cut's (${r ? ["tail", "head"].filter((k) => r[k]).join(" + ") : "none"})` : room === false ? "none" : r ? ["tail", "head"].filter((k) => r[k]).join(" + ") : "none"; + }; + let room; + if (op.reset === true) room = null; + else if (op.off === true) room = false; + else { + const was = isObj(e.room) ? e.room : {}; + room = { ...was }; + for (const k of ["tail", "head"]) if (op[k] !== undefined && op[k] !== null) room[k] = boolOf(op[k], `${e.id}'s room ${k}`); + if (!Object.keys(room).length) refuse("a clip_room op sets tail, head, off or reset"); + } + const before = e.room; + if (JSON.stringify(before ?? null) === JSON.stringify(room)) refuse(`${e.id}'s room is already ${words(room)}`); + const errors = validateRoom({ timeline: [{ ...e, room: room ?? undefined }] }); + if (errors.length) refuse(errors.join("; ")); + if (room === null) delete e.room; + else e.room = room; + const norm = { op: "clip_room", id: e.id, ...(room === null ? { reset: true } : room === false ? { off: true } : room) }; + return { op: norm, diff: arrow(`${e.id} room`, words(before), words(room ?? undefined)), apply: { writer: "clip", body: { op: "room", clip: e.id, room } } }; + } + case "fx": { + const id = typeof op.id === "string" ? op.id.trim() : ""; + const param = typeof op.param === "string" ? op.param.trim() : ""; + if (!COMPOSITION_PARAMS[id]) refuse(`"${id}" is not a composition (${Object.keys(COMPOSITION_PARAMS).join(", ")})`); + if (!compositionOn(render, id)) refuse(`this cut does not draw ${id}${id === "deck" ? "" : " (turn it on in the Media tab first)"}`); + const p = paramOf(id, param); + if (!p) refuse(`${id} has no param "${param}" (it declares ${COMPOSITION_PARAMS[id].map((x) => x.key).join(", ")})`); + let value = op.value; + if (p.kind === "bool" && typeof value !== "boolean") value = boolOf(value, p.label); + if ((p.kind === "seconds" || p.kind === "number" || p.kind === "int" || p.kind === "px") && typeof value === "string") value = numOf(value, p.label); + if (typeof value === "number" && p.kind !== "int") value = r2(value); + const bad = paramValueError(p, value); + if (bad) refuse(bad); + const was = paramValue(render, id, param); + if (JSON.stringify(was) === JSON.stringify(value)) refuse(`${p.label} is already ${JSON.stringify(value)}`); + const unit = p.kind === "seconds" ? " s" : ""; + const say = (v) => (typeof v === "boolean" ? onOff(v) : typeof v === "number" ? `${s2(v)}${unit}` : String(v)); + manifest.render = { ...render, chrome: chromeWithParam(render, id, param, value) }; + return { op: { op: "fx", id, param, value }, diff: arrow(p.label, say(was), say(value)), apply: { writer: "chrome", id, param, value } }; + } + default: + return refuse(`no op "${String(name)}"`); + } +} + +/** + * Check a batch of ops against a manifest. Each op is checked against the + * manifest as the ops before it left it. + * + * @param {unknown} manifest the project's video.manifest.json + * @param {readonly unknown[]} ops + * @param {{ request?: string, scope?: string }} [o] + * @returns {{ ops: { op: object, diff: string, apply: object, warning?: string }[], refused: { index: number, op: unknown, why: string }[], diff: string[], manifest: object }} + */ +export function checkAssistOps(manifest, ops, { request = "", scope = "all" } = {}) { + const m = structuredClone(isObj(manifest) ? manifest : {}); + if (!Array.isArray(m.timeline)) m.timeline = []; + const ctx = { scope: ASSIST_SCOPES.includes(scope) ? scope : "all", namedSeconds: secondsNamedIn(request) }; + const kept = []; + const refused = []; + for (const [index, raw] of (Array.isArray(ops) ? ops : []).entries()) { + try { + kept.push(checkOne(m, normalizeAssistOp(structuredClone(raw)), ctx)); + } catch (e) { + if (!(e instanceof Refusal)) throw e; + refused.push({ index, op: raw, why: e.message }); + } + } + return { ops: kept, refused, diff: kept.map((k) => k.diff), manifest: m }; +} + +// --------------------------------------------------------------------------- +// What the model reads: the look, the slide, the room, the clips, the +// declared params -- trimmed to a character budget. +// --------------------------------------------------------------------------- + +const shortWords = (q, n = 10) => { + const w = String(q ?? "").split(/\s+/).filter(Boolean); + return w.length > n ? `${w.slice(0, n).join(" ")} …` : w.join(" "); +}; + +/** + * The project as the assistant reads it. `scope` leaves out what was not asked + * about; the clips the request names come first; a clip past the budget is + * listed by its id alone, so an op may still name it. + * + * @param {unknown} manifest + * @param {{ maxChars?: number, request?: string, scope?: string }} [o] + * @returns {{ text: string, clips: { shown: string[], short: string[] } }} + */ +export function assistView(manifest, { maxChars = 6000, request = "", scope = "all" } = {}) { + const m = isObj(manifest) ? manifest : {}; + const render = isObj(m.render) ? m.render : {}; + const want = (s) => scope === "all" || scope === s; + const out = []; + if (want("look")) { + const slide = { ...SLIDE_DEFAULTS, ...(isObj(render.slide) ? render.slide : {}) }; + const room = isObj(render.room) ? render.room : {}; + out.push( + "THE LOOK NOW (look ops: key = value):", + `- transition = ${fin(render.transition) ? render.transition : TRANSITION_DEFAULT} (the join between clips, seconds; 0 = a hard cut; up to ${TRANSITION_MAX})`, + `- transitionStyle = ${render.transitionStyle ?? "fade"} (one of ${TRANSITION_STYLES.join(", ")}; fade = crossfade, blurslide = a quick blurred push)`, + `- headerHeight = ${render.headerHeight ?? "default"}, footerHeight = ${render.footerHeight ?? "default"} (pixels; 0 = off)`, + `- qr = ${render.qr === false ? "false" : "true"} (the QR code on each clip)`, + `- loudness = ${isObj(render.loudness) ? render.loudness.target : "null (as recorded)"} (target LUFS, ${LOUDNESS_MIN} to ${LOUDNESS_MAX}; higher is louder)`, + `- captions = ${isObj(render.captions) ? "true" : "false"} (speaker captions)`, + `SLIDE (slide op; used when transitionStyle is blurslide): travel = ${slide.travel} (${SLIDE_BOUNDS.travel.join("–")}), blur = ${slide.blur} (the smear, ${SLIDE_BOUNDS.blur.join("–")}), grain = ${slide.grain} (${SLIDE_BOUNDS.grain.join("–")})`, + `ROOM (room op): tail = ${room.tail === true} (the sound runs on to the first silence after the cut), head = ${room.head === true} (a muted lead-in), maxS = ${fin(room.maxS) ? room.maxS : ROOM.maxS} (seconds the tail may run past the cut's end, ${ROOM_BOUNDS.maxS.join("–")}), minGap = ${fin(room.minGap) ? room.minGap : ROOM.minGap} (the silence that ends it, ${ROOM_BOUNDS.minGap.join("–")})`, + ); + } + if (want("fx")) { + const on = compositionsOn(render); + if (on.length) { + out.push("COMPOSITIONS (fx ops: id, param = value now [bounds]):"); + for (const id of on) { + const ps = COMPOSITION_PARAMS[id].map((p) => { + const b = p.kind === "enum" ? p.values.join("|") : p.kind === "bool" ? "true|false" : p.kind === "text" ? `≤${p.maxLength} chars` : `${p.min}–${p.max}`; + return `${p.key} = ${JSON.stringify(paramValue(render, id, p.key))} [${b}]`; + }); + out.push(`- ${id}: ${ps.join("; ")}`); + } + } else if (scope === "fx") out.push("COMPOSITIONS: none (this cut draws no deck and no effects)"); + } + const clips = (m.timeline ?? []).filter((e) => isObj(e) && e.type === "clip"); + const shown = []; + const short = []; + if (want("clips") && clips.length) { + const head = out.join("\n").length + 200; + let left = maxChars - head; + const named = (id) => new RegExp(`(^|[^A-Za-z0-9_-])${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^A-Za-z0-9_-]|$)`, "i").test(request); + const order = [...clips].sort((a, b) => Number(named(b.id)) - Number(named(a.id))); + const lines = new Map(); + const idLine = (e) => `- ${e.id} (not shown in full)`; + left -= clips.reduce((n, e) => n + idLine(e).length + 1, 0); + for (const e of order) { + const { cut, window } = clipWindow(e, render); + const r = clipRoom(e, render); + const label = e.onscreen?.title ?? e.title ?? e.assist?.why ?? ""; + const line = + `- ${e.id}: cut ${s2(cut.start)}–${s2(cut.end)} s (${s2(cut.end - cut.start)} s; may move within ${s2(window.start)}–${s2(window.end)})` + + `${e.room === false ? ", room off" : isObj(e.room) ? `, room ${r ? ["tail", "head"].filter((k) => r[k]).join("+") || "none" : "none"}` : ""}` + + `${label ? ` ${JSON.stringify(shortWords(label, 8))}` : ""}${e.quote ? ` quote: ${JSON.stringify(shortWords(e.quote))}` : ""}`; + const extra = line.length - idLine(e).length; + if (extra <= left) { + left -= extra; + lines.set(e.id, line); + shown.push(e.id); + } else short.push(e.id); + } + out.push(`CLIPS (clip_edges / clip_room ops, by id; seconds on the recording):`); + for (const e of clips) out.push(lines.get(e.id) ?? idLine(e)); + } + return { text: out.join("\n"), clips: { shown, short } }; +} + +/** The ops, as the model is told them: one shape, `{op, id, key, value}`. */ +export const ASSIST_OPS_TEXT = [ + 'Operations: objects {"op", "id", "key", "value"} in the `ops` list ("id" is "" when the op names no clip or composition).', + "Change only what the request asks for, one op a setting; give the NEW value, never a step or a difference.", + '- {"op":"look","id":"","key":"transition","value":0.15} the join between clips, seconds (0 = hard cuts)', + '- {"op":"look","id":"","key":"transitionStyle","value":"fade"} one of fade, fadeblack, fadewhite, dissolve, blurslide', + '- {"op":"look","id":"","key":"qr","value":false} the QR code on (true) or off (false); key headerHeight / footerHeight: pixels, 0 = off', + '- {"op":"look","id":"","key":"loudness","value":-14} the loudness target in LUFS (higher = louder; null = as recorded)', + '- {"op":"look","id":"","key":"captions","value":true} speaker captions on or off', + '- {"op":"slide","id":"","key":"blur","value":0.3} the blur slide: key travel (how far it pushes), blur (the smear) or grain', + '- {"op":"room","id":"","key":"maxS","value":2} room at the clips\' edges: key tail (true/false: the sound runs to the first silence), head (true/false: a muted lead-in), maxS (the most seconds the tail runs past the cut), minGap', + '- {"op":"clip_edges","id":"<clip id>","key":"start","value":S} a clip\'s cut: key start or end, in seconds on its recording', + '- {"op":"clip_room","id":"<clip id>","key":"off","value":true} one clip\'s room: key tail or head (true/false), off (no room for it) or reset (the cut\'s again)', + '- {"op":"fx","id":"<composition>","key":"<param>","value":V} a listed composition param, within its bounds', +].join("\n"); + +/** The schema the answer is held to: `{ ops: [{op, id, key, value}], reply }` -- four keys an op, so a strict tool (every key required) is still one plain shape. */ +export const ASSIST_OPS_SCHEMA = Object.freeze({ + type: "object", + properties: { + ops: { + type: "array", + items: { + type: "object", + properties: { + op: { type: "string", enum: [...ASSIST_OP_NAMES] }, + id: { type: "string" }, + key: { type: "string" }, + value: { type: ["number", "string", "boolean", "null"] }, + }, + required: ["op", "id", "key", "value"], + }, + }, + reply: { type: "string" }, + }, + required: ["ops", "reply"], +}); + +/** + * An op in the model's one shape (`{op, id, key, value}`) as the checker's + * own: `{op:"slide", key:"blur", value:0.3}` → `{op:"slide", blur:0.3}`. An op + * already in the checker's shape is left as it is. + */ +export function normalizeAssistOp(raw) { + if (!isObj(raw)) return raw; + const { op, id, key, value } = raw; + const k = typeof key === "string" ? key.trim() : ""; + if (op === "look" || !k) return raw; + if (op === "fx") return raw.param !== undefined ? raw : { op, id, param: k, value }; + if (["slide", "room", "clip_edges", "clip_room"].includes(op) && raw[k] === undefined) { + const out = { op, [k]: value }; + if (op === "clip_edges" || op === "clip_room") out.id = id; + return out; + } + return raw; +} diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts @@ -0,0 +1,196 @@ +// Release 38 lane E: the video assistant's ops — the look's shared rules, +// each op's bounds and refusals, its diff line, and the request table. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { LOOK_KEYS, SLIDE_BOUNDS, applyLookPatch, lookErrors, validateLook, validateTransitionStyle } from "./look.mjs"; +import { ASSIST_OPS_SCHEMA, assistView, checkAssistOps, clipWindow, normalizeAssistOp, secondsNamedIn } from "./videoAssistOps.mjs"; +import { COMPOSITION_PARAMS, chromeWithParam, compositionsOn, paramValue, paramValueError } from "./fxParams.mjs"; +import { markProposals, proposalsDocOf, proposalsErrors, readAssistProposals, writeAssistProposals } from "./videoAssistProposals.mjs"; +import { ASSIST_REQUESTS, assistDeckManifest, assistManifest } from "../../testing/clips/assistProject.mjs"; + +test("the look's rules: one patch function — keys refused, null removes, qr on/off, bounds, then the build's validators", () => { + const m = assistManifest(); + assert.deepEqual(applyLookPatch(m, { chrome: {} }).errors, ["render.chrome is the deck's: set it from the deck's settings (updateChrome), not here"]); + assert.match(applyLookPatch(m, { fps: 25 }).errors[0]!, /render\.fps is not a look setting/); + assert.equal(applyLookPatch(m, { loudness: null }).render.loudness, undefined); + assert.equal(applyLookPatch(m, { qr: false }).render.qr, false); + assert.equal(applyLookPatch({ render: { qr: false } }, { qr: true }).render.qr, undefined); + assert.deepEqual(applyLookPatch(m, { transition: 0.157 }).render.transition, 0.16, "2 dp"); + assert.match(applyLookPatch(m, { transition: 3.5 }).errors[0]!, /from 0 \(a hard cut\) to 3/); + assert.match(applyLookPatch(m, { headerHeight: 241 }).errors[0]!, /from 0 to 240/); + // What it does not check itself, the build's validators do — the same sentences. + const bad = applyLookPatch(m, { slide: { blur: 9 } }); + assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } })); + assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } })); + assert.deepEqual(lookErrors(m), []); + assert.equal(LOOK_KEYS.length, 9); +}); + +test("the request table: every request → the model's ops → the diff lines kept and the reasons refused", () => { + assert.ok(ASSIST_REQUESTS.length >= 20); + for (const row of ASSIST_REQUESTS) { + const r = checkAssistOps(row.deck ? assistDeckManifest() : assistManifest(), row.answer, { request: row.request, scope: row.scope ?? "all" }); + assert.deepEqual(r.diff, row.diff, row.request); + assert.equal(r.refused.length, row.refused.length, `${row.request}: ${JSON.stringify(r.refused)}`); + r.refused.forEach((x, i) => assert.match(x.why, row.refused[i]!, row.request)); + } +}); + +test("each kept op carries its writer: the look's, the clip editor's, the composition's", () => { + const m = assistManifest(); + const r = checkAssistOps(m, [ + { op: "look", id: "", key: "transition", value: 0.15 }, + { op: "slide", id: "", key: "blur", value: 0.3 }, + { op: "room", id: "", key: "maxS", value: 2 }, + { op: "clip_edges", id: "r002", key: "start", value: 90 }, + { op: "clip_room", id: "r003", key: "off", value: true }, + ]); + assert.deepEqual( + r.ops.map((o) => o.apply), + [ + { writer: "render", patch: { transition: 0.15 } }, + { writer: "render", patch: { slide: { blur: 0.3 } } }, + { writer: "render", patch: { room: { tail: true, head: true, maxS: 2 } } }, + { writer: "clip", body: { op: "trim", clip: "r002", cutStart: 90, cutEnd: 99 } }, + { writer: "clip", body: { op: "room", clip: "r003", room: false } }, + ], + ); + assert.deepEqual(r.ops.map((o) => o.op), [ + { op: "look", key: "transition", value: 0.15 }, + { op: "slide", blur: 0.3 }, + { op: "room", maxS: 2 }, + { op: "clip_edges", id: "r002", start: 90, end: 99 }, + { op: "clip_room", id: "r003", off: true }, + ]); + // The manifest as the ops left it (the input is never touched). + assert.equal(r.manifest.render && (r.manifest.render as { transition: number }).transition, 0.15); + assert.equal(m.render.transition, 0.22); + const deck = checkAssistOps(assistDeckManifest(), [{ op: "fx", id: "fx.glitch", key: "seconds", value: 0.8 }], { scope: "fx" }); + assert.deepEqual(deck.ops[0]!.apply, { writer: "chrome", id: "fx.glitch", param: "seconds", value: 0.8 }); + assert.deepEqual(deck.diff, ["the glitch's length 0.5 s → 0.8 s"]); +}); + +test("ops read one after another: a later op sees the earlier ones; a second identical op is 'already that'", () => { + const r = checkAssistOps(assistManifest(), [ + { op: "look", id: "", key: "transitionStyle", value: "fade" }, + { op: "slide", id: "", key: "grain", value: 0 }, + { op: "look", id: "", key: "transitionStyle", value: "fade" }, + ]); + assert.deepEqual(r.diff, ["join style blur slide → crossfade", "grain 2 → 0"]); + assert.match(r.ops[1]!.warning!, /the join is a crossfade: the slide's knobs show once the join style is blur slide/); + assert.deepEqual(r.refused.map((x) => x.why), ["join style is already that"]); +}); + +test("room: a number for the tail is the tail on up to that; numbers alone turn the tail on; hard cuts warn", () => { + const plain = { render: { transition: 0.4 }, timeline: [] }; + const a = checkAssistOps(plain, [{ op: "room", id: "", key: "tail", value: 2 }]); + assert.deepEqual(a.diff, ["room tail off → on, room tail up to 2.5 s → 2 s"]); + assert.deepEqual(a.ops[0]!.op, { op: "room", tail: true, maxS: 2 }); + const b = checkAssistOps(plain, [{ op: "room", id: "", key: "minGap", value: 0.5 }]); + assert.deepEqual(b.diff, ["room tail off → on, room's silence gap 0.35 s → 0.5 s"]); + const c = checkAssistOps({ render: { transition: 0 }, timeline: [] }, [{ op: "room", id: "", key: "head", value: true }]); + assert.match(c.ops[0]!.warning!, /hard cuts/); + assert.match(checkAssistOps(plain, [{ op: "room", id: "", key: "maxS", value: 11 }]).refused[0]!.why, /outside 0–10 s/); + assert.match(checkAssistOps({ render: { montage: { phrase: "x" } }, timeline: [] }, [{ op: "room", id: "", key: "tail", value: true }]).refused[0]!.why, /a montage has no room/); +}); + +test("slide: each knob within SLIDE_BOUNDS, refused past them with the bound", () => { + for (const [k, [lo, hi]] of Object.entries(SLIDE_BOUNDS)) { + const m = assistManifest(); + assert.equal(checkAssistOps(m, [{ op: "slide", id: "", key: k, value: hi }]).ops.length, 1, `${k} at ${hi}`); + assert.match(checkAssistOps(m, [{ op: "slide", id: "", key: k, value: hi + 1 }]).refused[0]!.why, new RegExp(`outside ${lo}–${hi}`)); + } + assert.match(checkAssistOps(assistManifest(), [{ op: "slide", id: "", key: "speed", value: 1 }]).refused[0]!.why, /sets travel, blur \(the smear\) or grain/); +}); + +test("clip edges: inside the source window, at most 3 s a step unless the request names more, never under half a second", () => { + const m = assistManifest(); + assert.deepEqual(clipWindow(m.timeline[0]!), { cut: { start: 40, end: 47 }, window: { start: 38.5, end: 48.5 }, hasCut: true }); + // A clip without a cut moves inside its edges, widened by the fetch pad. + assert.deepEqual(clipWindow({ start: 10, end: 20 }, { fetchPad: 3 }).window, { start: 7, end: 23 }); + assert.deepEqual(secondsNamedIn("cut the first 6 seconds, then 2.5 s more"), 6); + assert.equal(secondsNamedIn("start at 516"), 0); + assert.match(checkAssistOps(m, [{ op: "clip_edges", id: "r001", key: "end", value: 40.2 }]).refused[0]!.why, /a cut is at least 0\.5 s/); + assert.match(checkAssistOps(m, [{ op: "clip_edges", id: "zz", key: "end", value: 40 }]).refused[0]!.why, /no clip "zz" in the cut/); + assert.match(checkAssistOps(m, [{ op: "clip_edges", id: "", key: "end", value: 40 }]).refused[0]!.why, /names its clip/); + const card = { render: {}, timeline: [{ type: "card", id: "c1" }] }; + assert.match(checkAssistOps(card, [{ op: "clip_room", id: "c1", key: "off", value: true }]).refused[0]!.why, /"c1" is a card entry, not a clip/); +}); + +test("fx: only a declared param of a composition the cut draws, within its declared bounds", () => { + const deck = assistDeckManifest(); + assert.deepEqual(compositionsOn(deck.render), ["deck", "fx.glitch"]); + assert.deepEqual(compositionsOn(assistManifest().render), []); + assert.equal(paramValue(deck.render, "deck", "motion.in"), 0.45); + assert.equal(paramValueError(COMPOSITION_PARAMS.deck!.find((p) => p.key === "background")!, "neon"), "the deck's background is one of panel, flush"); + assert.match(checkAssistOps(deck, [{ op: "fx", id: "fx.zoom", key: "width", value: 0.5 }]).refused[0]!.why, /does not draw fx\.zoom \(turn it on in the Media tab first\)/); + assert.match(checkAssistOps(deck, [{ op: "fx", id: "page", key: "html", value: "<b>" }]).refused[0]!.why, /"page" is not a composition/); + const set = chromeWithParam(deck.render, "deck", "motion.in", 0.6) as { deck: { motion: { in: number }; qr: unknown } }; + assert.deepEqual(set.deck, { qr: { show: false }, motion: { in: 0.6 } }); + assert.deepEqual((deck.render.chrome as { deck: unknown }).deck, { qr: { show: false } }, "a copy"); + // Booleans and enums as a model may write them. + assert.deepEqual(checkAssistOps(deck, [{ op: "fx", id: "fx.glitch", key: "stamp", value: "off" }]).diff, ["the glitch's date stamp on → off"]); +}); + +test("scope: an op outside what was asked is refused; the view shows only the scope", () => { + const m = assistDeckManifest(); + assert.match(checkAssistOps(m, [{ op: "look", id: "", key: "qr", value: false }], { scope: "clips" }).refused[0]!.why, /a look op is outside what was asked about \(clips\)/); + const look = assistView(m, { scope: "look" }).text; + assert.match(look, /THE LOOK NOW/); + assert.doesNotMatch(look, /CLIPS|COMPOSITIONS/); + const fx = assistView(m, { scope: "fx" }).text; + assert.match(fx, /- deck: motion\.in = 0\.45 \[0–2\]/); + assert.match(fx, /- fx\.glitch: on = "year" \[year\|every\]; seconds = 0\.5 \[0\.2–1\.5\]/); + assert.doesNotMatch(fx, /THE LOOK NOW/); +}); + +test("the view: the clips the request names first; past the budget a clip is its id alone", () => { + const m = assistManifest(); + for (let i = 5; i <= 60; i++) m.timeline.push({ type: "clip", id: `r${String(i).padStart(3, "0")}`, channel: "c", video: "v", start: i * 100, end: i * 100 + 20, cutStart: i * 100 + 2, cutEnd: i * 100 + 18, quote: "a quote of a good many words that runs on and on for a while" }); + const v = assistView(m, { maxChars: 3000, request: "trim r057 a bit", scope: "all" }); + assert.ok(v.text.length <= 3200, String(v.text.length)); + assert.ok(v.clips.shown.includes("r057")); + assert.ok(v.clips.short.length > 10); + assert.match(v.text, /- r060 \(not shown in full\)/); + assert.match(v.text, /- r057: cut 5702–5718 s \(16 s; may move within 5700–5720\)/); +}); + +test("the model's one shape normalised; the schema keeps four keys an op (a strict tool requires every key)", () => { + assert.deepEqual(normalizeAssistOp({ op: "slide", id: "", key: "blur", value: 0.3 }), { op: "slide", blur: 0.3 }); + assert.deepEqual(normalizeAssistOp({ op: "clip_edges", id: "r1", key: "end", value: 9 }), { op: "clip_edges", end: 9, id: "r1" }); + assert.deepEqual(normalizeAssistOp({ op: "fx", id: "deck", key: "motion.in", value: 1 }), { op: "fx", id: "deck", param: "motion.in", value: 1 }); + assert.deepEqual(normalizeAssistOp({ op: "slide", blur: 0.3 }), { op: "slide", blur: 0.3 }); + const item = (ASSIST_OPS_SCHEMA as { properties: { ops: { items: { properties: object; required: string[] } } } }).properties.ops.items; + assert.deepEqual(Object.keys(item.properties), ["op", "id", "key", "value"]); + assert.deepEqual(item.required, ["op", "id", "key", "value"]); +}); + +test("the proposals file: one ask's doc, read back, marked; a file that is not proposals is said so", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "assist-proposals-")); + try { + assert.deepEqual(await readAssistProposals(dir), { doc: null, error: null }); + const checked = checkAssistOps(assistManifest(), [ + { op: "look", id: "", key: "transition", value: 0.15 }, + { op: "look", id: "", key: "transition", value: 9 }, + ]); + const doc = proposalsDocOf({ at: "2026-10-20T00:00:00.000Z", model: "qwen3:8b", request: "quicker", checked, reply: " Shorter\njoins. " }); + assert.deepEqual(doc.ops, [{ id: "a1", op: { op: "look", key: "transition", value: 0.15 }, diff: "join 0.22 s → 0.15 s", status: "proposed" }]); + assert.equal(doc.refused.length, 1); + assert.equal(doc.reply, "Shorter joins."); + await writeAssistProposals(dir, doc); + assert.deepEqual((await readAssistProposals(dir)).doc, doc); + const marked = markProposals(doc, { a1: { status: "applied" } }, "2026-10-20T00:01:00.000Z"); + assert.deepEqual(marked.ops[0]!.status, "applied"); + assert.equal(marked.ops[0]!.at, "2026-10-20T00:01:00.000Z"); + await writeFile(path.join(dir, "assist-proposals.json"), '{"version": 2}'); + assert.match((await readAssistProposals(dir)).error!, /assist-proposals\.json: version is not 1/); + assert.ok(proposalsErrors({ version: 1, request: "x", ops: [{ id: "a1" }], refused: [] }).some((e) => /ops\[0\]/.test(e))); + await assert.rejects(writeAssistProposals(dir, { version: 1 } as never), /not proposals/); + assert.match(await readFile(path.join(dir, "assist-proposals.json"), "utf8"), /"version": 2/, "a refused write leaves the file"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/report/videoAssistProposals.d.mts b/common/lib/report/videoAssistProposals.d.mts @@ -0,0 +1,35 @@ +// Types for ./videoAssistProposals.mjs (release 38 lane E): `<project>/assist-proposals.json`. +import type { AssistOp, CheckedAssistOp, RefusedAssistOp } from "./videoAssistOps.mjs"; + +export type AssistOpStatus = "proposed" | "applied" | "dismissed" | "failed"; +export type ProposedOp = { id: string; op: AssistOp; diff: string; warning?: string; status: AssistOpStatus; at?: string; error?: string }; +export type AssistProposals = { + version: 1; + promptVersion: string; + at: string; + model: string; + request: string; + scope: string; + note?: string; + reply?: string; + ops: ProposedOp[]; + refused: { op: unknown; why: string }[]; + diff: string[]; +}; + +export const ASSIST_PROPOSALS_NAME: string; +export const ASSIST_PROMPT_VERSION: string; +export const ASSIST_OP_STATUSES: readonly AssistOpStatus[]; +export function proposalsDocOf(o: { + at: string; + model: string; + request: string; + scope?: string; + note?: string | null; + reply?: string | null; + checked: { ops: CheckedAssistOp[]; refused: RefusedAssistOp[] }; +}): AssistProposals; +export function proposalsErrors(doc: unknown): string[]; +export function readAssistProposals(dir: string): Promise<{ doc: AssistProposals | null; error: string | null }>; +export function writeAssistProposals(dir: string, doc: AssistProposals): Promise<string>; +export function markProposals(doc: AssistProposals, marks: Record<string, { status: AssistOpStatus; error?: string }>, at: string): AssistProposals; diff --git a/common/lib/report/videoAssistProposals.mjs b/common/lib/report/videoAssistProposals.mjs @@ -0,0 +1,111 @@ +// THE VIDEO ASSISTANT'S PROPOSALS FILE (release 38 lane E): +// `<project>/assist-proposals.json`, beside the project's video.manifest.json. +// +// { "version": 1, "promptVersion": "video-assist-1", "at": ISO, "model": "qwen3:8b", +// "request": "make the joins 0.15 s with less smear", "scope": "look", "note"?: "n_…", +// "reply"?: "…", a sentence the model added (shown, never applied) +// "ops": [ { "id": "a1", "op": {…}, "diff": "join 0.22 s → 0.15 s", "warning"?: "…", +// "status": "proposed" | "applied" | "dismissed" | "failed", "at"?: ISO, "error"?: "…" } ], +// "refused": [ { "op": {…}, "why": "…" } ], +// "diff": [ "join 0.22 s → 0.15 s", … ] } +// +// Written whole by the editor's `video-assist` task (one ask's proposals: a +// new ask replaces the file), and its ops' `status` marked by umtool's Apply +// and Dismiss. PROPOSALS ONLY: nothing in this file is applied by being here; +// Apply re-checks each op against the manifest as it is then (umtool +// lib/report/videoAssist.mjs) and writes through the manifest's writers. +// +// 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 ASSIST_PROPOSALS_NAME = "assist-proposals.json"; +export const ASSIST_PROMPT_VERSION = "video-assist-1"; +export const ASSIST_OP_STATUSES = Object.freeze(["proposed", "applied", "dismissed", "failed"]); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const fileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ASSIST_PROPOSALS_NAME); + +/** + * The file's document from one ask: the checked ops (videoAssistOps.mjs + * checkAssistOps), each given an id and the status "proposed". + */ +export function proposalsDocOf({ at, model, request, scope = "all", note = null, reply = null, checked }) { + const ops = (checked?.ops ?? []).map((k, i) => ({ + id: `a${i + 1}`, + op: k.op, + diff: k.diff, + ...(k.warning ? { warning: k.warning } : {}), + status: "proposed", + })); + return { + version: 1, + promptVersion: ASSIST_PROMPT_VERSION, + at, + model, + request, + scope, + ...(note ? { note } : {}), + ...(reply ? { reply: String(reply).replace(/\s+/g, " ").trim().slice(0, 600) } : {}), + ops, + refused: (checked?.refused ?? []).map((r) => ({ op: r.op, why: r.why })), + diff: ops.map((o) => o.diff), + }; +} + +/** The file's problems (empty: it can be read as proposals). */ +export function proposalsErrors(doc) { + if (!isObj(doc)) return ["not an object"]; + const errors = []; + if (doc.version !== 1) errors.push("version is not 1"); + if (typeof doc.request !== "string") errors.push("no request"); + if (!Array.isArray(doc.ops)) errors.push("no ops list"); + else + doc.ops.forEach((o, i) => { + if (!isObj(o) || typeof o.id !== "string" || !isObj(o.op) || typeof o.diff !== "string" || !ASSIST_OP_STATUSES.includes(o.status)) errors.push(`ops[${i}] is not { id, op, diff, 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 readAssistProposals(dir) { + let raw; + try { + raw = await readFile(fileOf(dir), "utf8"); + } catch { + return { doc: null, error: null }; + } + try { + const doc = JSON.parse(raw); + const errors = proposalsErrors(doc); + return errors.length ? { doc: null, error: `${ASSIST_PROPOSALS_NAME}: ${errors.join("; ")}` } : { doc, error: null }; + } catch (e) { + return { doc: null, error: `${ASSIST_PROPOSALS_NAME}: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +/** Write the whole file (tmp + rename). Returns its path. */ +export async function writeAssistProposals(dir, doc) { + const errors = proposalsErrors(doc); + if (errors.length) throw new Error(`not 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 op of `marks` (`{ [id]: { status, error? } }`) marked at `at`; ids not there are ignored. */ +export function markProposals(doc, marks, at) { + return { + ...doc, + ops: doc.ops.map((o) => { + const m = marks[o.id]; + if (!m) return o; + const { error: _e, ...rest } = o; + return { ...rest, status: m.status, at, ...(m.error ? { error: String(m.error).slice(0, 400) } : {}) }; + }), + }; +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -32,6 +32,7 @@ transcript, channel or person goes in these fixtures, ever. | `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). | | `clips/reactionStream.mjs` | Release 35: a synthetic reaction stream (`reactionStream()`: a host interjecting over a narrated video — turns, words, cues, laugh windows; `reactionAudio()` its sound; `writeReactionCorpus(dir, o)` a channel on disk). Release 36: `twoVideoStream()` (an intro, video A by speaker 1, the host between, video B by speaker 2 with a pause and a stray cluster, an outro — what auto-scope reads), `reactionChat(o)` (a chat replay: a steady trickle and a burst of laugh tokens `lag` s after each laugh, `chatOnly` bursts), and `writeReactionCorpus`'s `two`, `chat` (live_chat.cues.json) and `meta` (keys into metadata.info.json) options. The "narration" is numbered filler words. | | `clips/reactionProject.mjs` | Release 36 lane D: a synthetic reactions PROJECT over `reactionStream()` — `reactionProject()` (reactions.json with a host and a subject, five moments of every kind, five proposals: three in the cut, two not; words.json; a video.manifest.json of the three clips), `writeReactionProject(dir, {note})` (them on disk, and a notes.json with an open comment on a clip), `labelAnswer(ids)` (a model's answer for the clip finder's labels, in `SUGGEST_ANSWER_SCHEMA`'s shape). | +| `clips/assistProject.mjs` | Release 38 lane E: the video assistant's project — `assistManifest()` (the reactions project's three clips plus `r004`, a clip with a wide window, under a look: a 0.22 s blur slide, room at both edges, −16 LUFS, no header or footer), `assistDeckManifest()` (the same under the deck with the glitch on), `writeAssistProject(dir, {deck, note})` (on disk; `note`: a note on the whole project, `ASSIST_NOTE`), and `ASSIST_REQUESTS` — 29 requests in words, what a model answers (`{op, id, key, value}`) and the diff lines kept and the reasons refused (`answerOf(row)` is the answer in the schema's shape). | | `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | | `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | diff --git a/common/testing/clips/assistProject.d.mts b/common/testing/clips/assistProject.d.mts @@ -0,0 +1,14 @@ +// Types for ./assistProject.mjs (release 38 lane E): the video assistant's synthetic project and request table. +export const ASSIST_NOTE: string; +export const ASSIST_AT: string; +export const ASSIST_LOOK: Readonly<Record<string, unknown>>; + +export type AssistManifest = { render: Record<string, any>; timeline: Record<string, any>[] } & Record<string, any>; +export function assistManifest(): AssistManifest; +export function assistDeckManifest(): AssistManifest; + +export type AssistModelOp = { op: string; id: string; key: string; value: unknown }; +export type AssistRequestRow = { request: string; scope?: "look" | "clips" | "fx" | "all"; deck?: boolean; answer: AssistModelOp[]; diff: string[]; refused: RegExp[] }; +export const ASSIST_REQUESTS: readonly AssistRequestRow[]; +export function answerOf(row: AssistRequestRow): { ops: AssistModelOp[]; reply: string }; +export function writeAssistProject(dir: string, o?: { deck?: boolean; note?: string | null }): { dir: string; manifest: AssistManifest }; diff --git a/common/testing/clips/assistProject.mjs b/common/testing/clips/assistProject.mjs @@ -0,0 +1,103 @@ +// A synthetic video project for the video assistant (release 38 lane E): the +// reactions project's cut (reactionProject.mjs) with a look on it -- a quick +// blur slide, room at both edges, the loudness evened -- and a fourth clip +// with a wide window; a deck variant with an effect on; and the REQUEST TABLE, +// what a person asks for in words, what a model answers (in the ops' one +// shape, `{op, id, key, value}`) and what the checks make of it. +// +// Synthetic, like everything in the kit: no real project, recording or person. + +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { reactionProject } from "./reactionProject.mjs"; + +export const ASSIST_NOTE = "n_assist0001"; +export const ASSIST_AT = "2026-10-20T00:00:00.000Z"; + +/** The look the plain cut starts with. */ +export const ASSIST_LOOK = Object.freeze({ + headerHeight: 0, + footerHeight: 0, + transition: 0.22, + transitionStyle: "blurslide", + loudness: Object.freeze({ target: -16 }), + room: Object.freeze({ tail: true, head: true }), +}); + +/** The plain cut (no deck): r001–r003 from the reactions project, and r004, a clip whose window is wide. */ +export function assistManifest() { + const { manifest } = reactionProject(); + const m = structuredClone(manifest); + m.render = { width: 1920, height: 1080, fps: 30, ...structuredClone(ASSIST_LOOK) }; + m.timeline.push({ type: "clip", id: "r004", channel: m.timeline[0].channel, video: m.timeline[0].video, start: 500, end: 530, cutStart: 510, cutEnd: 520, quote: "" }); + return m; +} + +/** The same cut under a deck, with the glitch on. */ +export function assistDeckManifest() { + const m = assistManifest(); + const { captions: _c, ...render } = m.render; + m.render = { ...render, transitionStyle: "fade", chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } }, fx: { glitch: {} } } }; + return m; +} + +const op = (o, id, key, value) => ({ op: o, id, key, value }); + +/** + * The request table: `{ request, scope?, deck?, answer, diff, refused }` -- + * `answer` the model's `{ops, reply}`, `diff` the diff lines kept (in order), + * `refused` a pattern each refusal's reason matches (in order). + */ +export const ASSIST_REQUESTS = Object.freeze([ + { request: "make the joins 0.15 s", answer: [op("look", "", "transition", 0.15)], diff: ["join 0.22 s → 0.15 s"], refused: [] }, + { request: "quicker joins", answer: [op("look", "", "transition", 0.12)], diff: ["join 0.22 s → 0.12 s"], refused: [] }, + { request: "no QR", answer: [op("look", "", "qr", false)], diff: ["QR code on → off"], refused: [] }, + { request: "louder", answer: [op("look", "", "loudness", -14)], diff: ["loudness -16 LUFS → -14 LUFS"], refused: [] }, + { request: "smear less", answer: [op("slide", "", "blur", 0.3)], diff: ["smear 0.5 → 0.3"], refused: [] }, + { request: "keep 2 s after the last word", answer: [op("room", "", "maxS", 2)], diff: ["room tail up to 2.5 s → 2 s"], refused: [] }, + { request: "cut the first 3 seconds of r002", scope: "clips", answer: [op("clip_edges", "r002", "start", 91)], diff: ["r002 in 88 s → 91 s"], refused: [] }, + { request: "make the joins 5 seconds long", answer: [op("look", "", "transition", 5)], diff: [], refused: [/render\.transition must be a number of seconds from 0 \(a hard cut\) to 3/] }, + { request: "hard cuts, no joins", answer: [op("look", "", "transition", 0)], diff: ["join 0.22 s → a hard cut"], refused: [] }, + { request: "dip to black between clips", answer: [op("look", "", "transitionStyle", "fadeblack")], diff: ["join style blur slide → dip to black"], refused: [] }, + { request: "the slide travels too far", answer: [op("slide", "", "travel", 0.04)], diff: ["slide travel 0.08 → 0.04"], refused: [] }, + { request: "no grain on the slide", answer: [op("slide", "", "grain", 0)], diff: ["grain 2 → 0"], refused: [] }, + { request: "turn on speaker captions", answer: [op("look", "", "captions", true)], diff: ["speaker captions off → on"], refused: [] }, + { request: "even out the volume at -18", answer: [op("look", "", "loudness", -18)], diff: ["loudness -16 LUFS → -18 LUFS"], refused: [] }, + { request: "leave the sound as recorded", answer: [op("look", "", "loudness", null)], diff: ["loudness -16 LUFS → as recorded"], refused: [] }, + { request: "no muted lead-in", answer: [op("room", "", "head", false)], diff: ["room head on → off"], refused: [] }, + { request: "no room on r003", scope: "clips", answer: [op("clip_room", "r003", "off", true)], diff: ["r003 room the cut's (tail + head) → none"], refused: [] }, + { request: "end r001 a second later", scope: "clips", answer: [op("clip_edges", "r001", "end", 48)], diff: ["r001 out 47 s → 48 s"], refused: [] }, + { request: "start r001 at 30", scope: "clips", answer: [op("clip_edges", "r001", "start", 30)], diff: [], refused: [/outside the clip's source window \(38\.5–48\.5 s\)/] }, + { request: "tighten r004 to start at 516", scope: "clips", answer: [op("clip_edges", "r004", "start", 516)], diff: [], refused: [/moves an edge 6 s; one op moves an edge at most 3 s/] }, + { request: "cut the first 6 seconds of r004", scope: "clips", answer: [op("clip_edges", "r004", "start", 516)], diff: ["r004 in 510 s → 516 s"], refused: [] }, + { request: "a bigger header", answer: [op("look", "", "headerHeight", 56)], diff: ["header off → 56 px"], refused: [] }, + { request: "make the joins 0.15 s with less smear", answer: [op("look", "", "transition", 0.15), op("slide", "", "blur", 0.3)], diff: ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"], refused: [] }, + { request: "tighten r002 a little", scope: "look", answer: [op("clip_edges", "r002", "end", 98)], diff: [], refused: [/a clip_edges op is outside what was asked about \(look\)/] }, + { request: "add a spinning logo", answer: [{ op: "html", id: "", key: "", value: "<div>" }], diff: [], refused: [/no op "html"/] }, + { request: "glitch the deck", scope: "fx", answer: [op("fx", "deck", "motion.in", 0.6)], diff: [], refused: [/this cut does not draw deck/] }, + { request: "slow the deck's slide in", deck: true, scope: "fx", answer: [op("fx", "deck", "motion.in", 0.6)], diff: ["the deck's slide in 0.45 s → 0.6 s"], refused: [] }, + { request: "a longer glitch, 3 seconds", deck: true, scope: "fx", answer: [op("fx", "fx.glitch", "seconds", 3)], diff: [], refused: [/the glitch's length is seconds from 0\.2 to 1\.5/] }, + { request: "a taller deck", deck: true, scope: "fx", answer: [op("fx", "deck", "height", 300)], diff: [], refused: [/deck has no param "height"/] }, +]); + +/** The model's answer for a row: `{ops, reply}` in the schema's shape. */ +export const answerOf = (row) => ({ ops: row.answer, reply: "" }); + +/** + * The project on disk: its manifest (plain, or the deck variant), and with + * `note` a notes.json holding an open comment on the whole project. + * @param {string} dir + * @param {{ deck?: boolean, note?: string | null }} [o] + */ +export function writeAssistProject(dir, { deck = false, note = null } = {}) { + const manifest = deck ? assistDeckManifest() : assistManifest(); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + if (note) { + writeFileSync( + path.join(dir, "notes.json"), + `${JSON.stringify({ version: 1, subject: { kind: "video-project", project: path.basename(dir) }, notes: [{ id: ASSIST_NOTE, status: "open", author: "operator", text: note, at: ASSIST_AT, updatedAt: ASSIST_AT, anchor: { kind: "whole" }, replies: [] }] }, null, 1)}\n`, + ); + } + return { dir, manifest }; +} diff --git a/editor/app/api/ops/_videoAssist.test.ts b/editor/app/api/ops/_videoAssist.test.ts @@ -0,0 +1,160 @@ +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, 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 { ASSIST_NOTE, writeAssistProject } from "yt-dlp-transcript-common/testing/clips/assistProject.mjs"; +import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; +import { planVideoAssistJob, type AssistNoteReply, type VideoAssistJobDeps } from "yt-dlp-transcript-common/controller/videoAssist"; +import { readAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.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/_videoAssist.test.ts" +// +// The `report-draft` task `video-assist` (release 38 lane E) end to end in +// this process: the controller the ops route adapts, a synthetic video +// project in a temp dir (common/testing/clips/assistProject.mjs), 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(), "video-assist-")); + 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> = {}, more: Partial<VideoAssistJobDeps> = {}) => + ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }), ...more }) as ReportDraftDeps & VideoAssistJobDeps; + +const out = (o: Awaited<ReturnType<typeof enqueueReportDraft>>) => o.result as { ok: boolean; error: string }; + +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") }; +} + +test("the body: a project and a request (or a note), a scope; never an article", () => { + assert.throws(() => parseReportDraftBody({ task: "video-assist", request: "x" }), /"project" is the video project's absolute directory/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p" }), /needs its "request"/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", note: "n_abcd1234" }), /not both/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", article: "a", project: "/p", request: "x" }), /not an article/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", scope: "everything" }), /"scope" is look, clips, fx or all/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", proposals: ["p1"] }), /a clips-suggest job's/); + assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", request: "x" }), /"request" is a video-assist job's/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", iteration: 2 }), /takes no iteration/); + assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", answers: { ops: [] }, model: "m" }), /no "model"/); + assert.deepEqual(parseReportDraftBody({ task: "video-assist", project: "/p", request: " quicker joins ", scope: "look", dryRun: true }), { + task: "video-assist", + article: "", + project: "/p", + request: "quicker joins", + scope: "look", + dryRun: true, + }); +}); + +test("on the local model (the default route): draft:local through the arbiter, one schema-bound ask, proposals written, ollama unloaded, no ledger row", async () => { + const dir = path.join(tmp, "local"); + writeAssistProject(dir); + assert.equal(gen.routes["video-assist"], "local"); + ol.push(jsonReply({ ops: [{ op: "look", id: "", key: "transition", value: 0.15 }, { op: "slide", id: "", key: "blur", value: 0.3 }], reply: "Quicker, less smear." })); + const { job, done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "make the joins 0.15 s with less smear" }, deps())); + assert.equal(done.status, "done", log); + assert.equal(job.queueKey, "draft:local"); + assert.match(log, /through the GPU arbiter: it waits for a transcription/); + assert.match(log, /proposed: join 0\.22 s → 0\.15 s/); + assert.match(log, /unloaded qwen3:8b from ollama/); + assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"video-assist","project":"[^"]+local","status":"done","summary":"2 edits proposed \(join 0\.22 s → 0\.15 s; smear 0\.5 → 0\.3\) on qwen3:8b"/); + const { doc } = await readAssistProposals(dir); + assert.deepEqual(doc!.diff, ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"]); + assert.ok(ol.unloads.includes("qwen3:8b")); + assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0); + const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + assert.equal(m.render.transition, 0.22, "nothing applied"); +}); + +test("on the API: draft:api, the narration cap, a ledger row as task video-assist", async () => { + const dir = path.join(tmp, "api"); + writeAssistProject(dir); + api.push(toolTurn("answer", { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." })); + const { job, done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR" }, deps({ routes: { ...gen.routes, "video-assist": "api" } }))); + assert.equal(done.status, "done", log); + assert.equal(job.queueKey, "draft:api"); + assert.match(log, /the Claude API, cap \$1\)/); + const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.deepEqual(rows.map((r) => [r.task, r.model, r.article, r.iteration]), [["video-assist", "claude-sonnet-5-5", "", 0]]); + assert.deepEqual((await readAssistProposals(dir)).doc!.diff, ["QR code on → off"]); +}); + +test("the code route: refused with no answer; the plan is the request; a session's answer runs on no model", async () => { + const dir = path.join(tmp, "code"); + writeAssistProject(dir); + const code = { routes: { ...gen.routes, "video-assist": "code" as const } }; + const refused = await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR" }, deps(code)); + assert.ok(!out(refused).ok && /routed to Claude Code/.test(out(refused).error)); + const plan = await planVideoAssistJob(parseReportDraftBody({ task: "video-assist", project: dir, request: "no QR", dryRun: true }), deps(code)); + assert.equal(plan.provider, "code"); + assert.match(plan.request.user, /THE REQUEST:\nno QR/); + assert.match(plan.request.user, /- qr = true/); + const asked = api.requests.length + ol.requests.length; + const { done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR", answers: { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "" } }, deps(code))); + assert.equal(done.status, "done", log); + assert.equal(api.requests.length + ol.requests.length, asked); + assert.equal((await readAssistProposals(dir)).doc!.model, "claude-code"); +}); + +test("Ask on a note on the whole project: its text is the request; the reply posted as the agent's with an assist proposal; nothing applied", async () => { + const dir = path.join(tmp, "note"); + writeAssistProject(dir, { note: "quicker joins please" }); + const nowhere = await enqueueReportDraft({ task: "video-assist", project: dir, note: ASSIST_NOTE }, deps({}, { umtoolUrl: null, workerToken: "t" })); + assert.ok(!out(nowhere).ok && /UMTOOL_URL is not set/.test(out(nowhere).error)); + const missing = await enqueueReportDraft({ task: "video-assist", project: dir, note: "n_absent00" }, deps({}, { umtoolUrl: "http://x", workerToken: "t" })); + assert.ok(!out(missing).ok && /no note n_absent00/.test(out(missing).error)); + let prompt = ""; + ol.push((body: { messages: { role: string; content: string }[] }) => { + prompt = body.messages.find((m) => m.role === "user")!.content; + return jsonReply({ ops: [{ op: "look", id: "", key: "transition", value: 0.12 }], reply: "Joins at 0.12 s." }); + }); + const posted: AssistNoteReply[] = []; + const { done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, note: ASSIST_NOTE }, deps({}, { postReply: async (r) => void posted.push(r) }))); + assert.equal(done.status, "done", log); + assert.match(prompt, /THE REQUEST:\nquicker joins please/); + const { doc } = await readAssistProposals(dir); + assert.equal(doc!.note, ASSIST_NOTE); + assert.deepEqual(posted, [ + { project: dir, note: ASSIST_NOTE, text: "Joins at 0.12 s.\nProposed 1 edit — Apply below or in the Build tab's Look panel:\n• join 0.22 s → 0.12 s", proposal: { kind: "assist", at: doc!.at, ops: 1 } }, + ]); + const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + assert.equal(m.render.transition, 0.22); +}); diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -3,6 +3,7 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft"; 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 { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; import { jobResponse, ops, opsFail } from "../_lib"; import { refreshEditor, researchEditor } from "../_researchEditor"; @@ -61,7 +62,17 @@ export const dynamic = "force-dynamic"; // (UMTOOL_URL, WORKER_TOKEN); `answers`: a Claude Code session's labels // (the `code` route), written as a model's; `dryRun: true` answers // `{ ok, plan }` (the proposals, calls, the estimate, the request) and -// writes nothing. Answers `{ ok, jobId, iteration: 0 }`. +// writes nothing. Answers `{ ok, jobId, iteration: 0 }`; +// - "video-assist" (release 38 lane E, controller/videoAssist.ts): on a +// umtool video project, `project` (its absolute directory) and `request` +// (what to change, in words; or `note`, a note on the whole project whose +// text is the request — the proposals are posted to it as the agent's +// reply), `scope` look | clips | fx | all — ONE ask whose checked ops land +// in `<project>/assist-proposals.json` as proposals (nothing applied; +// 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 }`. // `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 // (a Claude model id; default settings.generation.models.extractor). An API job's cap is `maxUsd`, else the task's @@ -98,6 +109,14 @@ export async function POST(request: Request) { return opsFail((e as Error).message); } } + if (body.task === "video-assist" && body.dryRun === true) { + try { + const plan = await planVideoAssistJob(parseReportDraftBody(body), deps); + return NextResponse.json({ ok: true, plan }); + } catch (e) { + return opsFail((e as Error).message); + } + } const out = await enqueueReportDraft(body, deps); if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result); void out.result.stream.cancel(); diff --git a/settings.json.example b/settings.json.example @@ -257,7 +257,8 @@ "social": "local", "verdicts": "local", "frames": "api", - "clips-suggest": "local" + "clips-suggest": "local", + "video-assist": "local" }, "models": { "api": "claude-sonnet-5-5",