commit d586e438eb06a743d61a4c15750472f815cdd194
parent ddb9b58eb7e2f9757321e0f5ebc28a59a33f8a11
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 18:57:52 -0400
Merge r38/video-assist: the local video assistant (look/slide/room/clip/fx ops, video-assist task, Ask box, Preview join)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# editor/CHANGELOG.md
# plans/FACTS.md
Diffstat:
63 files changed, 4718 insertions(+), 319 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md
@@ -48,6 +48,13 @@ each task. Use the archilyzer MCP tools only; run no script for it.
send back with `generate` again (`answers: {"items": [{"id", "label", "why", "score"}]}`, at most six words a
label); the editor reads them as a model's answer and writes `clip-suggestions.json`. Never write that file, a
clip or the manifest yourself: the labels are suggestions the operator sorts by in the clip editor.
+ **And `video-assist`** (a small change to a umtool video project in words — "make the joins 0.15 s with less
+ smear on <dir>"): `generate` with task `video-assist`, `project` and `request` (or `note`, a note on the whole
+ project). It is local in every preset but `api`; routed to code, its answer is the request — the project's look,
+ clips and declared composition params — which you answer in this session and send back with `generate` again
+ (`answers: {"ops": [{"op", "id", "key", "value"}], "reply"}`); the editor checks them as a model's and writes
+ `assist-proposals.json`. They are proposals: the operator applies them in umtool's Ask box. Never edit the
+ manifest or that file yourself.
5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks
for it. To move the balance itself, `generation_policy` with `preset` (code, balanced, api, local) or with
`task` and `route` — only when the operator asks.
diff --git a/OPERATING.md b/OPERATING.md
@@ -281,6 +281,7 @@ pnpm ops report-draft --json '{"task":"revise-report","article":"example-article
pnpm ops report-draft --json '{"task":"revise-video","article":"example-article","iteration":2,"feedback":"Trim the opening clip."}' --wait
pnpm ops report-draft --json '{"task":"narrate","article":"example-article","iteration":3}' --wait
pnpm ops report-draft --json '{"task":"sweep","article":"example-article","copyOf":1,"model":"qwen3:8b"}'
+pnpm ops report-draft --json '{"task":"video-assist","project":"/abs/project/dir","request":"make the joins 0.15 s with less smear","dryRun":true}'
pnpm ops job cancel <jobId>
pnpm archilyzer reports iterations example-article
umtool chain example-article 3
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -984,7 +984,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). |
@@ -1019,6 +1019,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`
@@ -1125,7 +1126,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/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts
@@ -345,10 +345,11 @@ export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput):
// then says nothing was proposed); a cancel is rethrown.
export async function localOpsBatch(
h: TaskHandle,
- o: { model: string; system: string; what: string; build: (maxChars: number) => string; apply: (ops: unknown[]) => Promise<unknown> },
+ o: { model: string; system: string; what: string; build: (maxChars: number) => string; apply: (ops: unknown[]) => Promise<unknown>; schema?: object },
): Promise<void> {
const { deps } = h;
- const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema: OPS_SCHEMA, build: o.build });
+ const schema = o.schema ?? OPS_SCHEMA;
+ const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema, build: o.build });
h.log(`one ops batch over the ${o.what} (~${fitted.tokens} of ${fitted.cap} prompt tokens)`);
const t0 = Date.now();
const asked = await structuredAnswer<{ ops?: unknown[] }>({
@@ -356,7 +357,7 @@ export async function localOpsBatch(
model: o.model,
system: o.system,
user: fitted.user,
- schema: OPS_SCHEMA,
+ schema,
meter: h.meter,
signal: deps.signal,
}).catch((e: unknown) => {
diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts
@@ -33,8 +33,26 @@ export const VIDEO_OPS_TEXT = [
'- {"op":"trim","id":"<clip id>","start":S,"end":E} a clip\'s in/out seconds, within 3 s of its current ones',
'- {"op":"add_clip","citation":"<citation id from the report>","after":"<entry id>"} a clip for a cited moment not in the cut',
'- {"op":"title","text":"..."} / {"op":"subtitle","text":"..."}',
+ // Release 38: the look (the video assistant's look ops, checked by the look's own rules).
+ '- {"op":"look","key":"transition","value":0.15} the join between clips in seconds (0 = hard cuts); key transitionStyle (fade, fadeblack, fadewhite, dissolve, blurslide), qr (true/false), loudness (a LUFS target, higher = louder; null = as recorded), captions (true/false), headerHeight / footerHeight (pixels, 0 = off)',
+ '- {"op":"slide","key":"blur","value":0.3} the blur slide: key travel, blur (the smear) or grain',
+ '- {"op":"room","key":"maxS","value":2} room at the clips\' edges: key tail / head (true/false), maxS (seconds the sound may run past a cut), minGap',
].join("\n");
+// OPS_SCHEMA and the look ops' key and value (release 38).
+export const VIDEO_OPS_SCHEMA = {
+ ...OPS_SCHEMA,
+ properties: {
+ ops: {
+ ...OPS_SCHEMA.properties.ops,
+ items: {
+ ...OPS_SCHEMA.properties.ops.items,
+ properties: { ...OPS_SCHEMA.properties.ops.items.properties, key: { type: "string" }, value: { type: ["number", "string", "boolean", "null"] } },
+ },
+ },
+ },
+};
+
const shortQuote = (q: string, words = 12) => {
const w = q.split(/\s+/).filter(Boolean);
return w.length > words ? `${w.slice(0, words - 4).join(" ")} …` : q;
@@ -94,7 +112,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
.join("\n");
const view = () => `${cutView(manifest)}\n\nREPORT CITATIONS (add_clip takes these ids):\n${cites}`;
const applyOps = (ops: unknown[]) => {
- const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest });
+ const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest, feedback });
manifest = r.manifest;
applied.push(...r.applied);
refused.push(...r.refused);
@@ -110,7 +128,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
{
name: "apply_ops",
description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the cut after.",
- inputSchema: OPS_SCHEMA,
+ inputSchema: VIDEO_OPS_SCHEMA,
run: async (inp: { ops?: unknown }) => {
const r = applyOps(Array.isArray(inp?.ops) ? inp.ops : []);
return (
@@ -135,6 +153,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
model,
system: `${LOCAL_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT.replace("objects for apply_ops", "objects in the `ops` list")}`,
what: "cut",
+ schema: VIDEO_OPS_SCHEMA,
build: (maxChars) => {
const budget = maxChars - feedback.length - 400;
const cut = trimmedCutView(manifest, { maxChars: Math.floor(budget * 0.7), feedback });
@@ -185,7 +204,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
model,
system,
user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nAnswer with the ops batch that carries out the feedback.`,
- schema: OPS_SCHEMA,
+ schema: VIDEO_OPS_SCHEMA,
meter: h.meter,
signal: deps.signal,
}).catch((e: unknown) => {
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/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -119,7 +119,7 @@ test("unknown ops and entries are refused with a reason", () => {
assert.deepEqual(
r.refused.map((x) => x.why),
[
- 'no op "spin" — the ops are drop, move, heading, narration, trim, add_clip, title, subtitle',
+ 'no op "spin" — the ops are drop, move, heading, narration, trim, add_clip, title, subtitle, look, slide, room',
'no entry "nope" in the cut',
"an entry cannot move after itself",
],
@@ -147,3 +147,29 @@ test("trimmed cut view (Q3): the named chapter in full, every entry still listed
assert.ok(v.text.length < full.length);
assert.equal(trimmedCutView(manifest, { maxChars: 1e6 }).short.length, 0);
});
+
+test("the look ops (release 38): look, slide and room through the look's own rules; a bad value refused with the build's sentence", () => {
+ const r = applyVideoOps(
+ manifest,
+ [
+ { op: "look", key: "transition", value: 0.15 },
+ { op: "slide", key: "blur", value: 0.3 },
+ { op: "room", key: "tail", value: 2 },
+ { op: "look", key: "transition", value: 9 },
+ { op: "look", key: "chrome", value: {} },
+ ],
+ { report, feedback: "quicker joins, less smear, keep 2 s after the last word" },
+ );
+ const render = r.manifest.render as { transition: number; slide: unknown; room: unknown };
+ assert.equal(render.transition, 0.15);
+ assert.deepEqual(render.slide, { blur: 0.3 });
+ assert.deepEqual(render.room, { tail: true, maxS: 2 });
+ assert.deepEqual(r.applied.map((a) => a.index), [0, 1, 2]);
+ // The slide's knobs warn on a cut whose join is not a blur slide.
+ assert.match(r.applied[1]!.warnings![0]!, /the slide's knobs show once the join style is blur slide/);
+ assert.deepEqual(
+ r.refused.map((x) => x.why),
+ ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide)'],
+ );
+ assert.equal((manifest.render as { transition: number }).transition, 0.4, "the input is not touched");
+});
diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts
@@ -9,6 +9,9 @@
// trim {id, start, end} a clip's in/out, within the fetched window ±3 s
// add_clip {citation, after?} a clip for a video citation of the report not in the cut
// title {text} / subtitle {text}
+// look {key, value} a look setting (release 38: the video assistant's ops,
+// slide {key, value} ../videoAssistOps.mjs — checked by the look's own rules,
+// room {key, value} common lib/report/look.mjs, as umtool's updateRender is)
//
// The rules, in code:
// - A narration passes ./grounding.ts's hard checks, or the op is refused
@@ -23,8 +26,9 @@
// Pure: the manifest in, a new one out.
import { checkNarration, groundingInputOf, type GroundingInput } from "./grounding";
+import { checkAssistOps } from "../videoAssistOps.mjs";
-export const VIDEO_OP_NAMES = ["drop", "move", "heading", "narration", "trim", "add_clip", "title", "subtitle"] as const;
+export const VIDEO_OP_NAMES = ["drop", "move", "heading", "narration", "trim", "add_clip", "title", "subtitle", "look", "slide", "room"] as const;
export const TRIM_SLACK_SECONDS = 3;
@@ -63,6 +67,8 @@ export type VideoOpsContext = {
parent?: VideoManifest;
// Grounding's input; default: from the report.
grounding?: GroundingInput;
+ // The operator's words: a look op may name more seconds than a step allows.
+ feedback?: string;
};
export type VideoOpsResult = { manifest: VideoManifest; applied: AppliedVideoOp[]; refused: RefusedVideoOp[] };
@@ -173,6 +179,16 @@ export function applyVideoOps(input: VideoManifest, ops: readonly unknown[], ctx
parentClips.set(cid, e);
break;
}
+ case "look":
+ case "slide":
+ case "room": {
+ // The video assistant's look ops (release 38): the look's own rules decide.
+ const r = checkAssistOps(manifest, [op], { request: ctx.feedback ?? "", scope: "look" });
+ if (r.refused.length) refuse(r.refused[0]!.why);
+ manifest.render = r.manifest.render;
+ if (r.ops[0]?.warning) warnings = [r.ops[0].warning];
+ break;
+ }
case "title":
case "subtitle": {
const t = str(op.text, "text").trim();
diff --git a/common/lib/report/fxParams.d.mts b/common/lib/report/fxParams.d.mts
@@ -0,0 +1,24 @@
+// Types for ./fxParams.mjs (release 38 lane E): the compositions' declared params.
+
+export type ParamKind = "seconds" | "number" | "int" | "px" | "enum" | "bool" | "text";
+export type CompositionParam = {
+ readonly key: string;
+ readonly label: string;
+ readonly kind: ParamKind;
+ readonly min?: number;
+ readonly max?: number;
+ readonly values?: readonly string[];
+ readonly maxLength?: number;
+ readonly default: unknown;
+};
+type Render = Record<string, unknown> | null | undefined;
+
+export const COMPOSITION_PARAMS: Readonly<Record<string, readonly CompositionParam[]>>;
+export const COMPOSITION_IDS: readonly string[];
+export function compositionOn(render: Render, id: string): boolean;
+export function compositionsOn(render: Render): string[];
+export function settingsPathOf(id: string): string[];
+export function paramOf(id: string, key: string): CompositionParam | null;
+export function paramValue(render: Render, id: string, key: string): unknown;
+export function paramValueError(p: CompositionParam, value: unknown): string | null;
+export function chromeWithParam(render: Render, id: string, key: string, value: unknown): Record<string, unknown> | null;
diff --git a/common/lib/report/fxParams.mjs b/common/lib/report/fxParams.mjs
@@ -0,0 +1,176 @@
+// THE COMPOSITIONS' TUNABLE PARAMS (release 38 lane E): the HyperFrames
+// regions a report cut can carry (report-to-video deck.mjs, stats.mjs, fx.mjs)
+// declare here the settings a person -- or the video assistant -- may change
+// by name, each with its bounds. Only a DECLARED param can be the target of a
+// video-assist `fx` op; nothing else under `render.chrome` is reachable that
+// way, and never free HTML.
+//
+// composition id where its settings live on when
+// deck render.chrome.deck the deck is (chrome.engine "hyperframes", layout "deck")
+// stats render.chrome.stats the deck is, and chrome.stats is an object
+// fx.<effect> render.chrome.fx.<effect> that effect is an object (fx.mjs FX_KEYS)
+//
+// A param is `{ key, label, kind, min?, max?, values?, maxLength?, default }`:
+// `key` a dot path inside the composition's settings, `kind` one of seconds /
+// number / int / px / enum / bool / text. The bounds are the composition's own
+// validator's (deck.mjs validateChrome, stats.mjs validateStats, fx.mjs
+// validateFx) -- report-to-video's fx-params.test.mjs holds each declaration
+// to its validator, at both bounds and just past them, so the two cannot
+// drift. The writer (umtool updateChrome, validateChrome on the whole render)
+// still has the last word at Apply: a param whose value is fine alone but
+// clashes with another setting is refused there, with the validator's reason.
+//
+// The modules re-export their own slice (DECK_PARAMS, STATS_PARAMS,
+// FX_PARAMS). Settings that move the layout as a whole (the deck's height,
+// the footage scale, the QR's size, the pips' sizes) are left out: each is
+// bounded by another and is a Media-tab decision, not a tweak.
+//
+// PURE. Plain ESM with a .d.mts beside it.
+
+const P = (key, label, kind, more) => Object.freeze({ key, label, kind, ...more });
+const sec = (key, label, min, max, def) => P(key, label, "seconds", { min, max, default: def });
+const numP = (key, label, min, max, def) => P(key, label, "number", { min, max, default: def });
+const intP = (key, label, min, max, def) => P(key, label, "int", { min, max, default: def });
+const oneOf = (key, label, values, def) => P(key, label, "enum", { values: Object.freeze(values), default: def });
+const bool = (key, label, def) => P(key, label, "bool", { default: def });
+const text = (key, label, maxLength, def) => P(key, label, "text", { maxLength, default: def });
+
+const CORNERS = ["top-left", "top-right", "bottom-left", "bottom-right"];
+
+/** Every composition's declared params, by composition id. */
+export const COMPOSITION_PARAMS = Object.freeze({
+ deck: Object.freeze([
+ sec("motion.in", "the deck's slide in", 0, 2, 0.45),
+ sec("motion.out", "the deck's slide out", 0, 2, 0.3),
+ sec("motion.pip", "the timeline pip's move", 0, 3, 0.7),
+ numP("title.size", "the clip title's size", 24, 96, 54),
+ intP("title.maxChars", "the clip title's length", 10, 120, 48),
+ bool("qr.show", "the deck's QR code", true),
+ oneOf("subtitle.dateFormat", "the subtitle's date", ["long", "iso"], "long"),
+ oneOf("background", "the deck's background", ["panel", "flush"], "panel"),
+ oneOf("overCards", "the deck over cards", ["hide", "show"], "hide"),
+ sec("posts.seconds", "how long a post is up", 0.5, 10, 4),
+ sec("posts.hold", "the freeze under a post", 0, 10, 2.5),
+ ]),
+ stats: Object.freeze([
+ oneOf("position", "the stats panel's corner", CORNERS, "bottom-left"),
+ bool("name", "the stats panel's name", true),
+ ]),
+ "fx.kineticQuote": Object.freeze([
+ oneOf("position", "the kinetic quote's place", ["bottom", "top"], "bottom"),
+ numP("size", "the kinetic quote's size", 24, 96, 54),
+ intP("maxWords", "the kinetic quote's words a page", 3, 30, 12),
+ ]),
+ "fx.redact": Object.freeze([
+ oneOf("position", "the redaction's place", ["bottom", "top"], "bottom"),
+ numP("size", "the redaction's size", 24, 96, 44),
+ intP("maxWords", "the redaction's words a page", 3, 30, 14),
+ ]),
+ "fx.odometer": Object.freeze([
+ oneOf("position", "the odometer's corner", CORNERS, "top-right"),
+ text("label", "the odometer's label", 24, "times"),
+ oneOf("at", "when the odometer rolls", ["phrase", "start"], "phrase"),
+ ]),
+ "fx.scrubber": Object.freeze([
+ oneOf("position", "the date rail's edge", ["top", "bottom"], "top"),
+ bool("thumbs", "the date rail's thumbnails", true),
+ ]),
+ "fx.glitch": Object.freeze([
+ oneOf("on", "where the glitch tears", ["year", "every"], "year"),
+ sec("seconds", "the glitch's length", 0.2, 1.5, 0.5),
+ bool("stamp", "the glitch's date stamp", true),
+ ]),
+ "fx.thenNow": Object.freeze([
+ sec("seconds", "the THEN/NOW wipe's length", 0.3, 2, 0.6),
+ oneOf("dates", "the THEN/NOW dates", ["date", "year"], "date"),
+ ]),
+ "fx.receipts": Object.freeze([
+ oneOf("position", "the receipts' side", ["right", "left"], "right"),
+ numP("width", "the receipts' width (of the footage)", 0.2, 0.6, 0.36),
+ ]),
+ "fx.zoom": Object.freeze([numP("width", "the zoom card's width (of the footage)", 0.3, 0.9, 0.56)]),
+ "fx.punchIn": Object.freeze([
+ numP("scale", "the punch-in's scale", 1.05, 2, 1.2),
+ sec("hold", "the punch-in's hold", 0.2, 6, 1.4),
+ oneOf("anchor", "where the punch-in aims", ["upper", "center"], "upper"),
+ bool("auto", "punch in on laughs", true),
+ ]),
+ "fx.whip": Object.freeze([oneOf("on", "where the whip pans", ["every", "year"], "every")]),
+});
+
+export const COMPOSITION_IDS = Object.freeze(Object.keys(COMPOSITION_PARAMS));
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+const deckOnOf = (render) => {
+ const c = render?.chrome;
+ return isObj(c) && c.engine === "hyperframes" && c.layout === "deck";
+};
+
+/** Is this composition drawn by the cut? */
+export function compositionOn(render, id) {
+ if (!COMPOSITION_IDS.includes(id)) return false;
+ if (id === "deck") return deckOnOf(render);
+ if (id === "stats") return deckOnOf(render) && isObj(render.chrome.stats);
+ const fx = render?.chrome?.fx;
+ return isObj(fx) && isObj(fx[id.slice(3)]);
+}
+
+/** The compositions this cut draws, in COMPOSITION_IDS order. */
+export const compositionsOn = (render) => COMPOSITION_IDS.filter((id) => compositionOn(render, id));
+
+/** Where a composition's settings live under `render.chrome`, as a path. */
+export const settingsPathOf = (id) => (id === "deck" ? ["deck"] : id === "stats" ? ["stats"] : ["fx", id.slice(3)]);
+
+/** The declared param `key` of composition `id`, or null. */
+export function paramOf(id, key) {
+ return (COMPOSITION_PARAMS[id] ?? []).find((p) => p.key === key) ?? null;
+}
+
+const at = (o, keys) => keys.reduce((v, k) => (isObj(v) ? v[k] : undefined), o);
+
+/** A param's value in this render: as written, else its default. */
+export function paramValue(render, id, key) {
+ const p = paramOf(id, key);
+ if (!p) return undefined;
+ const v = at(render?.chrome, [...settingsPathOf(id), ...key.split(".")]);
+ return v === undefined || v === null ? p.default : v;
+}
+
+/** Why `value` is not a value of the declared param (null: it is). */
+export function paramValueError(p, value) {
+ const fin = typeof value === "number" && Number.isFinite(value);
+ switch (p.kind) {
+ case "seconds":
+ case "number":
+ case "px":
+ return fin && value >= p.min && value <= p.max ? null : `${p.label} is ${p.kind === "seconds" ? "seconds" : "a number"} from ${p.min} to ${p.max}`;
+ case "int":
+ return fin && Number.isInteger(value) && value >= p.min && value <= p.max ? null : `${p.label} is a whole number from ${p.min} to ${p.max}`;
+ case "enum":
+ return p.values.includes(value) ? null : `${p.label} is one of ${p.values.join(", ")}`;
+ case "bool":
+ return typeof value === "boolean" ? null : `${p.label} is true or false`;
+ case "text":
+ return typeof value === "string" && value.trim().length <= p.maxLength ? null : `${p.label} is a text of at most ${p.maxLength} characters`;
+ default:
+ return `${p.label} cannot be set here`;
+ }
+}
+
+/**
+ * `render.chrome` with one declared param set (a copy; null when the
+ * composition is not drawn by this cut or the param is not declared). The
+ * composition writer (updateChrome) validates the result as a whole.
+ */
+export function chromeWithParam(render, id, key, value) {
+ if (!compositionOn(render, id) || !paramOf(id, key)) return null;
+ const chrome = structuredClone(render.chrome);
+ let o = chrome;
+ for (const k of [...settingsPathOf(id), ...key.split(".").slice(0, -1)]) {
+ if (!isObj(o[k])) o[k] = {};
+ o = o[k];
+ }
+ o[key.split(".").at(-1)] = value;
+ return chrome;
+}
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -0,0 +1,48 @@
+// Types for ./look.mjs (release 38 lane E): the look's rules — one set of
+// checks for umtool's updateRender, the build and the video assistant.
+
+type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>;
+type Render = Record<string, unknown> | null | undefined;
+
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide";
+export const LOOK_KEYS: readonly LookKey[];
+export const BAND_MAX: number;
+export const TRANSITION_MAX: number;
+export const TRANSITION_DEFAULT: number;
+
+export const TRANSITION_STYLES: readonly string[];
+export function transitionStyleOf(render: Render): string;
+export type Slide = { travel: number; blur: number; grain: number };
+export const SLIDE_DEFAULTS: Readonly<Slide>;
+export const SLIDE_BOUNDS: Readonly<Record<keyof Slide, readonly [number, number]>>;
+export function slideOf(render: Render): Slide;
+export function validateTransitionStyle(manifest: unknown): string[];
+export function validateSlide(manifest: unknown): string[];
+
+export const ROOM: Readonly<{ minGap: number; maxS: number; fade: number; pad: number; detectDb: number; detectD: number }>;
+export const ROOM_EDGES: readonly ("tail" | "head")[];
+export const ROOM_BOUNDS: Readonly<{ minGap: readonly [number, number]; maxS: readonly [number, number] }>;
+export function roomOn(render: Render): boolean;
+export function clipRoom(entry: unknown, render: Render): { tail: boolean; head: boolean; minGap: number; maxS: number } | null;
+export function validateRoom(manifest: unknown): string[];
+
+export const CAPTION_STYLES: readonly string[];
+export const CAPTION_SIZES: readonly string[];
+export const CAPTION_LABEL_MAX: number;
+export const LOUDNESS_MIN: number;
+export const LOUDNESS_MAX: number;
+export const VERTICAL_RATIO: number;
+export const VERTICAL_TOLERANCE: number;
+export const DEFAULT_SOURCE_ASPECT: number;
+export function captionsOn(render: Render): boolean;
+export function loudnessOn(render: Render): boolean;
+export function loudnessTargetOf(render: Render): number | null;
+export function validateCaptions(manifest: unknown): string[];
+export function validateLoudness(manifest: unknown): string[];
+export function verticalErrors(v: unknown, who?: string): string[];
+export function validateVertical(manifest: unknown): string[];
+export function validateLook(manifest: unknown): string[];
+
+export function lookErrors(manifest: unknown): string[];
+export function applyLookPatch(manifest: Manifest, patch: Record<string, unknown>): { render: Record<string, unknown>; errors: string[] };
+export function lookOf(render: unknown): Record<string, unknown>;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -0,0 +1,350 @@
+// THE LOOK'S RULES (release 38 lane E): the render keys a person sets for a
+// cut with no deck -- `headerHeight`, `footerHeight`, `qr`, `transition`,
+// `transitionStyle`, `loudness`, `captions`, `room`, `slide` -- and the ONE set
+// of checks every writer and reader of them runs:
+//
+// umtool's updateRender (lib/report/manifest.mjs: applyLookPatch, then lookErrors)
+// the build and the lint (report-to-video look.mjs / room.mjs / transition.mjs re-export these)
+// the video assistant (./videoAssistOps.mjs: a proposed look op is checked here first)
+//
+// They lived in report-to-video until release 38 moved them here so the
+// editor's `video-assist` task (which cannot import umtool) refuses exactly
+// what the writer and the build refuse. Moved, not copied: the render modules
+// re-export every name, so nothing that imported them changed.
+//
+// PURE: no fs, no ffmpeg. Plain ESM with a .d.mts beside it.
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const q = (v) => JSON.stringify(v);
+const round2 = (n) => Number(Number(n).toFixed(2));
+
+/** The render keys the Look panel writes, in its order. */
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide"]);
+
+/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
+export const BAND_MAX = 240;
+/** `transition`: seconds, 0 (a hard cut) to this. */
+export const TRANSITION_MAX = 3;
+/** The join's length when a cut sets none (the build's default). */
+export const TRANSITION_DEFAULT = 0.5;
+
+// ---------------------------------------------------------------------------
+// The join's style (`render.transitionStyle`) and the blur slide's knobs
+// (`render.slide`) -- report-to-video/transition.mjs draws them.
+// ---------------------------------------------------------------------------
+
+export const TRANSITION_STYLES = Object.freeze(["fade", "fadeblack", "fadewhite", "dissolve", "blurslide"]);
+
+/** The style a plain join uses (`render.transitionStyle`, default "fade"). */
+export const transitionStyleOf = (render) => render?.transitionStyle ?? "fade";
+
+// The push's knobs (`render.slide`): travel = fraction of the width the
+// pictures move; blur = motion-smear strength (0 none, 1 = a frame's travel);
+// grain = noise strength on the seam's frames (0 none).
+export const SLIDE_DEFAULTS = Object.freeze({ travel: 0.08, blur: 0.5, grain: 2 });
+export const SLIDE_BOUNDS = Object.freeze({ travel: Object.freeze([0, 0.5]), blur: Object.freeze([0, 2]), grain: Object.freeze([0, 20]) });
+
+/** The push's knobs, the defaults filled in. */
+export function slideOf(render) {
+ const s = render?.slide && typeof render.slide === "object" ? render.slide : {};
+ const out = {};
+ for (const k of Object.keys(SLIDE_DEFAULTS)) out[k] = Number.isFinite(s[k]) ? s[k] : SLIDE_DEFAULTS[k];
+ return out;
+}
+
+/** @param {{ render?: { transitionStyle?: unknown } }} manifest */
+export function validateTransitionStyle(manifest) {
+ const s = manifest?.render?.transitionStyle;
+ const slide = validateSlide(manifest);
+ if (s === undefined || s === null) return slide;
+ return typeof s === "string" && TRANSITION_STYLES.includes(s)
+ ? slide
+ : [`render.transitionStyle: ${JSON.stringify(s)} is not one of ${TRANSITION_STYLES.join(", ")}`, ...slide];
+}
+
+/** `render.slide`: absent, or an object of the push's knobs within bounds. */
+export function validateSlide(manifest) {
+ const s = manifest?.render?.slide;
+ if (s === undefined || s === null) return [];
+ if (typeof s !== "object" || Array.isArray(s)) return ["render.slide must be an object {travel?, blur?, grain?}"];
+ const errs = [];
+ for (const [k, v] of Object.entries(s)) {
+ const b = SLIDE_BOUNDS[k];
+ if (!b) errs.push(`render.slide.${k} is not a key (travel, blur, grain)`);
+ else if (!Number.isFinite(v) || v < b[0] || v > b[1]) errs.push(`render.slide.${k} must be a number from ${b[0]} to ${b[1]}`);
+ }
+ return errs;
+}
+
+// ---------------------------------------------------------------------------
+// Room at a clip's edges (`render.room`, a clip's `room`) -- report-to-video/
+// room.mjs says what it does to the sound and the picture.
+// ---------------------------------------------------------------------------
+
+export const ROOM = Object.freeze({
+ /** A gap between two words this long (s) is the silence the sound stops at. */
+ minGap: 0.35,
+ /** The sound never runs more than this (s) past the cut's end. */
+ maxS: 2.5,
+ /** The fade at the silence point, and the fade in at a muted head (s). */
+ fade: 0.06,
+ /** Muted picture past D, so the fade is done before the join begins (s). */
+ pad: 0.1,
+ /** silencedetect, when there are no words: noise floor (dB) and least length (s). */
+ detectDb: -35,
+ detectD: 0.3,
+});
+export const ROOM_EDGES = Object.freeze(["tail", "head"]);
+/** `render.room.minGap` and `render.room.maxS`: seconds, within these. */
+export const ROOM_BOUNDS = Object.freeze({ minGap: Object.freeze([0.1, 2]), maxS: Object.freeze([0, 10]) });
+const MIN_GAP = ROOM_BOUNDS.minGap;
+const MAX_S = ROOM_BOUNDS.maxS;
+
+/** Does the cut's render block turn room on for either edge? */
+export const roomOn = (render) => isObj(render?.room) && (render.room.tail === true || render.room.head === true);
+
+/**
+ * One clip's room: `{tail, head, minGap, maxS}` with at least one edge on, or
+ * null. The clip's `room` (false, or per-edge booleans) beats the cut's.
+ */
+export function clipRoom(entry, render) {
+ const r = isObj(render?.room) ? render.room : null;
+ const c = entry?.room;
+ if (c === false) return null;
+ const edge = (k) => (isObj(c) && typeof c[k] === "boolean" ? c[k] : r?.[k] === true);
+ const tail = edge("tail");
+ const head = edge("head");
+ if (!tail && !head) return null;
+ return {
+ tail,
+ head,
+ minGap: num(r?.minGap) ? r.minGap : ROOM.minGap,
+ maxS: num(r?.maxS) ? r.maxS : ROOM.maxS,
+ };
+}
+
+/** `render.room` and every clip's `room`: each problem in a sentence naming the key. */
+export function validateRoom(manifest) {
+ const render = manifest?.render ?? {};
+ const errors = [];
+ const room = render.room;
+ if (room !== undefined && room !== null) {
+ if (!isObj(room)) errors.push(`render.room must be an object ({tail: true, head: true}) or absent, not ${q(room)}`);
+ else {
+ for (const k of Object.keys(room)) {
+ if (!["tail", "head", "minGap", "maxS"].includes(k)) errors.push(`render.room.${k} is not a setting here (tail, head, minGap, maxS)`);
+ }
+ for (const k of ROOM_EDGES) {
+ if (room[k] !== undefined && typeof room[k] !== "boolean") errors.push(`render.room.${k} must be true or false, not ${q(room[k])}`);
+ }
+ if (room.minGap !== undefined && (!num(room.minGap) || room.minGap < MIN_GAP[0] || room.minGap > MIN_GAP[1])) {
+ errors.push(`render.room.minGap must be seconds from ${MIN_GAP[0]} to ${MIN_GAP[1]}, not ${q(room.minGap)}`);
+ }
+ if (room.maxS !== undefined && (!num(room.maxS) || room.maxS < MAX_S[0] || room.maxS > MAX_S[1])) {
+ errors.push(`render.room.maxS must be seconds from ${MAX_S[0]} to ${MAX_S[1]}, not ${q(room.maxS)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.room does not combine with render.montage (a montage cuts to its phrases)");
+ }
+ }
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.room === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).room`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has room at its edges`);
+ else if (e.room === false || e.room === null) return;
+ else if (!isObj(e.room)) errors.push(`${who} must be false or {tail?, head?}, not ${q(e.room)}`);
+ else {
+ for (const [k, v] of Object.entries(e.room)) {
+ if (!ROOM_EDGES.includes(k)) errors.push(`${who}.${k} is not a setting here (tail, head)`);
+ else if (typeof v !== "boolean") errors.push(`${who}.${k} must be true or false, not ${q(v)}`);
+ }
+ }
+ });
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// Captions, loudness and a clip's vertical crop -- report-to-video/look.mjs
+// draws them.
+// ---------------------------------------------------------------------------
+
+export const CAPTION_STYLES = Object.freeze(["speakers"]);
+export const CAPTION_SIZES = Object.freeze(["m", "l"]);
+export const CAPTION_LABEL_MAX = 40;
+
+export const LOUDNESS_MIN = -30;
+export const LOUDNESS_MAX = -8;
+
+export const VERTICAL_RATIO = 9 / 16;
+/** How far a crop's shape may be from 9:16 (relative): the build fits it exactly. */
+export const VERTICAL_TOLERANCE = 0.03;
+export const DEFAULT_SOURCE_ASPECT = 16 / 9;
+
+export const captionsOn = (render) => isObj(render?.captions);
+export const loudnessOn = (render) => isObj(render?.loudness) && num(render.loudness.target);
+/** The target in LUFS, or null when the cut sets none. */
+export const loudnessTargetOf = (render) => (loudnessOn(render) ? render.loudness.target : null);
+
+/** `render.captions`: its keys and values, and what it does not combine with. */
+export function validateCaptions(manifest) {
+ const render = manifest?.render ?? {};
+ const c = render.captions;
+ if (c === undefined || c === null) return [];
+ if (!isObj(c)) return [`render.captions must be an object ({style: "speakers"}) or absent, not ${q(c)}`];
+ const errors = [];
+ for (const k of Object.keys(c)) {
+ if (!["style", "labels", "size"].includes(k)) errors.push(`render.captions.${k} is not a setting here (the settings are style, labels, size)`);
+ }
+ if (!CAPTION_STYLES.includes(c.style)) errors.push(`render.captions.style must be "speakers", not ${q(c.style)}`);
+ if (c.size !== undefined && !CAPTION_SIZES.includes(c.size)) errors.push(`render.captions.size must be "m" or "l", not ${q(c.size)}`);
+ if (c.labels !== undefined && c.labels !== null) {
+ if (!isObj(c.labels)) errors.push(`render.captions.labels must be an object ({host, subject}), not ${q(c.labels)}`);
+ else {
+ for (const [k, v] of Object.entries(c.labels)) {
+ if (k !== "host" && k !== "subject") errors.push(`render.captions.labels.${k} is not a role here (host, subject)`);
+ else if (v !== null && (typeof v !== "string" || v.length > CAPTION_LABEL_MAX)) {
+ errors.push(`render.captions.labels.${k} must be a short text (up to ${CAPTION_LABEL_MAX} characters), or null`);
+ }
+ }
+ }
+ }
+ if (isObj(render.chrome)) errors.push("render.captions does not combine with render.chrome (the deck draws its own words: render.chrome.fx.kineticQuote)");
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.captions does not combine with render.montage (a montage re-times its clips)");
+ return errors;
+}
+
+/** `render.loudness`: `{target}` in LUFS. */
+export function validateLoudness(manifest) {
+ const render = manifest?.render ?? {};
+ const l = render.loudness;
+ if (l === undefined || l === null) return [];
+ if (!isObj(l)) return [`render.loudness must be an object ({target: -16}) or absent, not ${q(l)}`];
+ const errors = [];
+ for (const k of Object.keys(l)) if (k !== "target") errors.push(`render.loudness.${k} is not a setting here (the setting is target)`);
+ if (!num(l.target) || l.target < LOUDNESS_MIN || l.target > LOUDNESS_MAX) {
+ errors.push(`render.loudness.target must be a number from ${LOUDNESS_MIN} to ${LOUDNESS_MAX} LUFS, not ${q(l.target)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.loudness does not combine with render.montage (a montage levels with render.montage.loudness)");
+ return errors;
+}
+
+/** One clip's `vertical` (null when it has none): its errors, prefixed by `who`. */
+export function verticalErrors(v, who = "vertical") {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect") errors.push(`${who}.${k} is not a setting here (crop, aspect)`);
+ if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) {
+ errors.push(`${who}.aspect must be the source's width / height (a number from 0.2 to 5), not ${q(v.aspect)}`);
+ }
+ const c = v.crop;
+ if (!Array.isArray(c) || c.length !== 4 || !c.every(num)) {
+ errors.push(`${who}.crop must be [x, y, w, h], four fractions of the source picture`);
+ return errors;
+ }
+ const [x, y, w, h] = c;
+ const E = 1e-3;
+ if (w <= 0 || h <= 0) errors.push(`${who}.crop's width and height must be above 0`);
+ if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${who}.crop must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`);
+ if (w > 0 && h > 0) {
+ const aspect = num(v.aspect) ? v.aspect : DEFAULT_SOURCE_ASPECT;
+ const shape = (w * aspect) / h;
+ if (Math.abs(shape / VERTICAL_RATIO - 1) > VERTICAL_TOLERANCE) {
+ errors.push(`${who}.crop must be 9:16 on the source (w × aspect / h ≈ 0.5625; this one is ${shape.toFixed(4)})`);
+ }
+ }
+ return errors;
+}
+
+/** Every clip's `vertical`. */
+export function validateVertical(manifest) {
+ const errors = [];
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.vertical === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).vertical`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has a vertical crop`);
+ else errors.push(...verticalErrors(e.vertical, who));
+ });
+ return errors;
+}
+
+/** All of the look's keys: the build's validators and the lint call this. */
+export function validateLook(manifest) {
+ // render.room and a clip's room (release 36 lane E) are part of the look.
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)];
+}
+
+// ---------------------------------------------------------------------------
+// A patch of the look, applied: what updateRender writes, and what the video
+// assistant checks a proposed op against before anything is written.
+// ---------------------------------------------------------------------------
+
+/** Every reason this manifest's look cannot be built (the join's style and the slide, then the rest). */
+export const lookErrors = (manifest) => [...validateTransitionStyle(manifest), ...validateLook(manifest)];
+
+/**
+ * A patch of LOOK_KEYS applied to a render block: `null` removes a key (the
+ * build's default again); `qr: true` turns the code back on (removes a
+ * `false`; an object of settings is kept), `qr: false` turns it off; the
+ * heights and the join's length are checked here, everything else by the
+ * build's own validators against the manifest as it would be.
+ *
+ * Pure: returns `{ render, errors }` -- the new render block (a copy) and
+ * every sentence that refuses it (empty: it can be written).
+ *
+ * @param {{ render?: Record<string, unknown>, timeline?: unknown[] } & Record<string, unknown>} manifest
+ * @param {Record<string, unknown>} patch
+ * @returns {{ render: Record<string, unknown>, errors: string[] }}
+ */
+export function applyLookPatch(manifest, patch) {
+ const base = isObj(manifest?.render) ? manifest.render : {};
+ if (!isObj(patch)) return { render: { ...base }, errors: ["the patch must be an object of render keys"] };
+ const errors = [];
+ for (const k of Object.keys(patch)) {
+ if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here");
+ else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`);
+ }
+ if (errors.length) return { render: { ...base }, errors };
+ const render = { ...base };
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null) {
+ delete render[k];
+ continue;
+ }
+ switch (k) {
+ case "headerHeight":
+ case "footerHeight":
+ if (!(Number.isInteger(v) && v >= 0 && v <= BAND_MAX)) errors.push(`render.${k} must be a whole number of pixels from 0 to ${BAND_MAX}`);
+ else render[k] = v;
+ break;
+ case "qr":
+ if (v === false) render.qr = false;
+ else if (v === true) {
+ if (render.qr === false) delete render.qr;
+ } else errors.push("render.qr must be true (on) or false (off)");
+ break;
+ case "transition":
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > TRANSITION_MAX) errors.push(`render.transition must be a number of seconds from 0 (a hard cut) to ${TRANSITION_MAX}`);
+ else render.transition = round2(v);
+ break;
+ case "transitionStyle":
+ if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
+ else render.transitionStyle = v;
+ break;
+ default:
+ // loudness, captions, room, slide: stored as given; the build's validators below say what is wrong.
+ render[k] = v;
+ }
+ }
+ errors.push(...lookErrors({ ...manifest, render }));
+ return { render, errors };
+}
+
+/** The look keys of a render block as written (absent keys left out). */
+export function lookOf(render) {
+ const r = isObj(render) ? render : {};
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k];
+ return out;
+}
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/package.json b/common/package.json
@@ -48,6 +48,10 @@
"./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
+ "./lib/report/look.mjs": "./lib/report/look.mjs",
+ "./lib/report/fxParams.mjs": "./lib/report/fxParams.mjs",
+ "./lib/report/videoAssistOps.mjs": "./lib/report/videoAssistOps.mjs",
+ "./lib/report/videoAssistProposals.mjs": "./lib/report/videoAssistProposals.mjs",
"./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs",
"./lib/report/panels.mjs": "./lib/report/panels.mjs",
"./lib/report/social.mjs": "./lib/report/social.mjs",
diff --git a/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/CHANGELOG.md b/editor/CHANGELOG.md
@@ -4,6 +4,8 @@
- **A forum thread's fetch resumes where it stopped instead of reading the thread again.** A forum channel now keeps two places: how far it has caught up with the newest posts, and where its walk back through the older pages stands. **Fetch posts** reads from the last page down to the newest post it already holds, then jumps straight to the older pages it has yet to read — a run capped at a few pages ("Latest N pages") no longer loses the older place, and a page whose posts are all held is stepped past without counting against the cap. Pages that shifted because posts were deleted are still read without a gap. **Full re-walk** (it replaces "Re-fetch full history" on a forum channel) asks first, with the page count and how long it takes at the channel's pace, then reads every page from the last to page 1: edited posts are updated, and posts no page shows any more are counted in the log and kept. The panel's status line says where both stand — "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)". The older place is checked against the pages the archive holds at every run, so a channel whose place was overwritten by the old single resume point heals on its next fetch. A page that reads empty — as one can just after a browser check clears — is loaded once more before the fetch stops on it. **Retry after a block** (the Forum session section) makes Fetch posts wait out a browser check that will not clear or a refused page — 30 minutes, then try again, up to 12 tries, say — and never retries a captcha or a login; `pnpm ops fetch-posts` takes `"retryOnBlock": {"minutes": 30, "max": 12}` (or `true` for the saved setting). Needs a restart of the editor.
- **Is a Wayback page's original still up? The channel page says, and can ask the Wayback Machine to save one now.** A Wayback pages channel's page has **Originals**: **Check originals** asks each record's original address at its own site — never the Wayback Machine — once per address, a few seconds apart, and the page lists every original that is gone (404 or 410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page) with "the only copy" linking its Wayback copy; a suspended account or a document no longer shared reads as unavailable, and anything else (a wall, an outage, a redirect to another site) as an error, never as gone. Gone records read as deleted wherever a deleted post does. **Save Page Now** — "Ask the Wayback Machine to capture this now" — takes any address, or a record whose original is still up (**Capture now**): archive.org captures the page, the job waits for it, and the new capture is imported into the channel. It needs your archive.org S3 keys (`ARCHIVE_ORG_S3_ACCESS` and `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or in the mode-600 file `archiveOrg.s3KeyFile` names); without them the button is off and says why, and the keys are never logged. From a terminal: `pnpm ops check-post-availability`, `pnpm ops save-page-now` (`dryRun` first). Needs a restart of the editor.
- **find-copy finds a copy of a gone page a report cites.** `pnpm ops find-copy` with `"pages": true` checks each page a report cites at its own site; for one that is gone it imports the Wayback capture nearest the citation's date into the Wayback pages channel you name (`"channel"`) or the one whose targets cover it, and its result names the record the citation should now cite. A page still up is left (save it now instead), and a cited page record whose original is gone keeps its stored capture. `"dryRun": true` asks the same questions and imports nothing. The report is not rewritten.
+- **Ask for a small change to a report video in words, on the local model, and apply it with one click.** The Build tab's Look panel and the clip editor's side column have an **Ask** box: "make the joins 0.15 s with less smear", "louder", "no QR", "keep 2 s after the last word", "cut the first 3 seconds of r014". The assistant answers with proposed edits shown as a list of changes ("join 0.22 s → 0.15 s", "smear 0.5 → 0.3"), each with **Apply**, plus **Apply all** and **Dismiss**; nothing changes until you apply, and each edit is checked again and written by the same code the Look panel and the clip editor use. A change it cannot make, or a value out of range, is listed with the reason instead. It runs on the local model by default (in every preset but `api`), so it works without Claude Code; it waits while a transcription has the GPU, and the box says so. A note on the whole project can be asked too: the reply comes back on the note with an **Apply all**. **Preview join** renders the first few joins in the saved look and plays them in place. It can change the look, the blur slide, the room at the clips' edges, a clip's edges or room, and a set of declared deck and effect settings (`pnpm ops report-draft` task `video-assist`; the MCP's `generate`).
+- **The Look panel has the blur slide's and the room's numbers.** With the join set to blur slide, **Travel**, **Smear** and **Grain** are fields; with room at the clips' edges on, **Tail up to, s** (how far the sound may run past a cut) and **Silence gap, s**. Video revisions of an article can now change the look, the slide and the room too.
- **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor.
- **Scan a Wayback pages channel, then choose what to import.** A channel whose config names `wayback.targets` (a page, a prefix, a host or a domain, with optional dates) has a **Captures** tab: **Scan now** lists what the Wayback Machine holds of them — one row per distinct version of each page, with when it was first and last seen — without fetching a single page, at archive.org's pace, at most 50,000 rows a run; **Continue scan** picks up where a run stopped, and a later scan marks what is **new**. Filter by year, path and text, then **Import selected** or **Import all in range** (asked to confirm above 50): one import job per capture, one at a time. Rows already imported are marked and skipped. The same over HTTP: `pnpm ops wayback-scan --json '{"slug":"<slug>"}'` and `pnpm ops wayback-import --json '{"slug":"<slug>","year":"2014"}'` (both take `dryRun`); offline, `pnpm archilyzer wayback scan <slug>`. With `wayback.auto: true` the download lane imports the captures later scans add, at the same pace; it is off unless a channel turns it on.
- **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model.
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/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -150,6 +150,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async
frames: "api",
// The clip finder's labels (release 36 lane D).
"clips-suggest": "api",
+ // The video assistant (release 38 lane E): api only in the api preset.
+ "video-assist": "api",
},
},
},
@@ -509,3 +511,35 @@ test("generate clips-suggest: a project, not an article; routed to code, the edi
assert.match(b.text, /Nothing in the cut changed/);
assert.equal(done.sentOf("/api/ops/iterations").length, 0);
});
+
+test("generate video-assist: a project and a request (or a note); routed to code, the plan is this session's request; the answer goes back to the editor", async () => {
+ assert.ok(GENERATE_TASKS.includes("video-assist"));
+ assert.match(String((validateGenerateArgs({ task: "video-assist", article: "a" }) as { error: string }).error), /names its project/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p" }) as { error: string }).error), /needs its request/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", note: "n_abcd1234" }) as { error: string }).error), /not both/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", scope: "everything" }) as { error: string }).error), /scope is look, clips, fx or all/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", iteration: 2 }) as { error: string }).error), /iteration is not a video-assist job's/);
+ assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", request: "x" }) as { error: string }).error), /a video-assist job's/);
+ const plan = { scope: "all", estimate: { inputTokens: 700 }, request: { system: "You adjust a video project's settings…", user: "THE REQUEST:\nno QR\n\nTHE PROJECT NOW:\n- qr = true" } };
+ const code = editor({ policy: { routes: { ...POLICY.routes, "video-assist": "code" } }, plan });
+ const a = await generateTool({ task: "video-assist", project: "/r/p", request: "no QR" }, code.deps as never);
+ assert.equal(a.isError, undefined, a.text);
+ assert.match(a.text, /^generate video-assist: routed to Claude Code \(preset balanced\) — answer this request on the project in this session \(scope all\)\./);
+ assert.match(a.text, /call generate with task "video-assist", project "\/r\/p", the same request "no QR", answers: \{"ops": \[\.\.\.\], "reply": "\.\.\."\}/);
+ assert.match(a.text, /Never write that file or the manifest yourself/);
+ assert.match(a.text, /- qr = true/);
+ assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "video-assist", project: "/r/p", request: "no QR", dryRun: true }]);
+
+ const answers = { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." };
+ const done = editor({
+ markerJson: { article: "", iteration: 0, task: "video-assist", project: "/r/p", status: "done", summary: "1 edit proposed (QR code on → off) on claude-code", usd: 0, assist: { proposed: 1, refused: 0, diff: ["QR code on → off"] } },
+ });
+ const b = await generateTool({ task: "video-assist", project: "/r/p", request: "no QR", answers, wait: true }, done.deps as never);
+ assert.equal(b.isError, false, b.text);
+ assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "video-assist", project: "/r/p", request: "no QR", answers }]);
+ assert.equal(done.sentOf("/api/ops/settings").length, 0, "a session's answer needs no policy read");
+ assert.match(b.text, /^generate video-assist: job job-1 ended \*\*done\*\* — 1 edit proposed \(QR code on → off\) on claude-code/);
+ assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused\n- QR code on → off/);
+ assert.match(b.text, /Nothing in the cut changed/);
+ assert.equal(done.sentOf("/api/ops/iterations").length, 0);
+});
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -237,7 +237,9 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true;
const task = trimmed(args.task);
if (!GENERATE_TASKS.includes(task)) return bad(`task is one of ${GENERATE_TASKS.join(", ")}`);
if (task === CLIPS_SUGGEST) return validateClipsSuggestArgs(args, waitSeconds);
+ if (task === VIDEO_ASSIST) return validateVideoAssistArgs(args, waitSeconds);
if (args.project !== undefined || args.answers !== undefined || args.proposals !== undefined) return bad("project, proposals and answers are a clips-suggest job's");
+ if (args.request !== undefined || args.scope !== undefined || args.note !== undefined) return bad("request, scope and note are a video-assist job's");
const article = trimmed(args.article);
if (!ARTICLE_RE.test(article)) return bad("article is an article id (a lowercase slug: a-z, 0-9, -)");
const body: Body = { task, article };
@@ -340,6 +342,98 @@ function validateClipsSuggestArgs(args: Record<string, unknown>, waitSeconds: nu
return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
}
+// ─── video-assist (release 38 lane E): the video assistant, on a umtool project ───
+
+const VIDEO_ASSIST = "video-assist";
+const NOTE_RE = /^n_[a-z0-9]{4,32}$/;
+
+function validateVideoAssistArgs(args: Record<string, unknown>, waitSeconds: number): { ok: true; request: GenerateRequest } | { ok: false; error: string } {
+ const bad = (error: string) => ({ ok: false as const, error: `generate: ${error}` });
+ const project = trimmed(args.project);
+ if (!project.startsWith("/")) return bad("a video-assist job names its project: the video project's absolute directory (project)");
+ for (const k of ["article", "iteration", "copyOf", "question", "channels", "feedback", "from", "to", "cards", "entries", "force", "autonomy", "extractorModel", "proposals"] as const) {
+ if (args[k] !== undefined) return bad(`${k} is not a video-assist job's (it reads its project)`);
+ }
+ const body: Body = { task: VIDEO_ASSIST, project };
+ if (args.request !== undefined) {
+ const r = trimmed(args.request);
+ if (!r) return bad("request is what to change, in words");
+ body.request = r;
+ }
+ if (args.note !== undefined) {
+ const n = trimmed(args.note);
+ if (!NOTE_RE.test(n)) return bad("note is a note id (n_…)");
+ body.note = n;
+ }
+ if (!body.request && !body.note) return bad("a video-assist job needs its request (what to change), or the note whose text is one");
+ if (body.request && body.note) return bad("give request or note, not both");
+ if (args.scope !== undefined) {
+ const sc = trimmed(args.scope);
+ if (!["look", "clips", "fx", "all"].includes(sc)) return bad("scope is look, clips, fx or all");
+ body.scope = sc;
+ }
+ if (args.model !== undefined) {
+ const m = trimmed(args.model);
+ if (!m) return bad("model is text");
+ body.model = m;
+ }
+ if (args.maxUsd !== undefined) {
+ if (typeof args.maxUsd !== "number" || !(args.maxUsd > 0)) return bad("maxUsd is a positive number of dollars");
+ body.maxUsd = args.maxUsd;
+ }
+ if (args.answers !== undefined) {
+ if (!args.answers || typeof args.answers !== "object" || Array.isArray(args.answers)) return bad('answers is {"ops": [{"op", "id", "key", "value"}], "reply"}');
+ if (body.model) return bad("answers are this session's: no model");
+ body.answers = args.answers;
+ }
+ let via: "api" | "local" | undefined;
+ if (args.via !== undefined) {
+ const v = trimmed(args.via);
+ if (v !== "api" && v !== "local") return bad('via is "api" or "local"');
+ if (body.model || body.answers) return bad("give model, via or answers — one");
+ via = v;
+ }
+ if (args.wait !== undefined && typeof args.wait !== "boolean") return bad("wait is true or false");
+ return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
+}
+
+type AssistPlanView = { scope?: string; estimate?: { inputTokens?: number }; request?: { system?: string; user?: string } };
+
+// The `code` route: this session answers the request the editor's plan names.
+export function renderVideoAssistRequest(body: Body, plan: AssistPlanView, preset: string): string {
+ const r = plan.request ?? {};
+ const said = body.note ? `note ${String(body.note)}` : `request ${JSON.stringify(String(body.request ?? ""))}`;
+ return [
+ `generate video-assist: routed to Claude Code (preset ${preset}) — answer this request on the project in this session (scope ${plan.scope ?? "all"}).`,
+ `Read the project's settings below and give the ops that carry out the request, each {"op", "id", "key", "value"}, and a one-sentence reply.`,
+ `Then call generate with task "video-assist", project "${String(body.project)}", the same ${said}${body.scope ? `, scope "${String(body.scope)}"` : ""}, answers: {"ops": [...], "reply": "..."} and wait: true — ` +
+ "the editor checks your ops exactly as a model's (a value outside its bounds is refused, with the reason) and writes assist-proposals.json. " +
+ "They are PROPOSALS: the operator applies them in umtool (the Look panel's Ask box). Never write that file or the manifest yourself.",
+ "",
+ "## The instructions",
+ r.system ?? "",
+ "",
+ "## The project",
+ r.user ?? "",
+ ].join("\n");
+}
+
+type AssistMarker = { project?: string; assist?: { proposed?: number; refused?: number; diff?: string[]; note?: string } };
+
+function videoAssistSummary(f: Extract<Followed, { kind: "ended" }>, m: Marker & AssistMarker): ToolAnswer {
+ const a = m.assist ?? {};
+ const lines = [
+ `generate video-assist: job ${f.job.id} ended **${f.job.status}** — ${m.summary ?? m.status ?? ""}`.trim(),
+ `Project: ${m.project ?? "?"} · ${a.proposed ?? 0} proposed, ${a.refused ?? 0} refused` + (m.usd ? ` · $${m.usd.toFixed(4)}` : ""),
+ ...(a.diff ?? []).map((d) => `- ${d}`),
+ "",
+ "These are proposals in assist-proposals.json: the operator applies them in umtool (the Build tab's Look panel, Ask box: Apply / Dismiss" +
+ (a.note ? `; the reply on note ${a.note} carries an Apply too` : "") +
+ "). Nothing in the cut changed.",
+ ];
+ return { text: lines.join("\n"), isError: f.job.status !== "done" };
+}
+
type SuggestPlanView = {
proposals?: number;
calls?: number;
@@ -574,6 +668,7 @@ async function summarise(
const marker = resultMarkerOf(f.tail);
if (marker?.task === "verdicts") return verdictsSummary(f, marker);
if (marker?.task === CLIPS_SUGGEST) return clipsSuggestSummary(f, marker);
+ if (marker?.task === VIDEO_ASSIST) return videoAssistSummary(f, marker as Marker & AssistMarker);
const article = marker?.article ?? hint.article;
const n = marker?.iteration ?? hint.iteration;
const task = marker?.task ?? hint.task ?? "report-draft";
@@ -662,6 +757,11 @@ export async function generateTool(
const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true });
if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true };
return { text: renderClipsSuggestRequest(String(body.project), (plan.body.plan ?? {}) as SuggestPlanView, p.preset) };
+ } else if (task === VIDEO_ASSIST && body.answers === undefined && p.routes[task] === "code") {
+ // The session answers it: the editor's plan is the request.
+ const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true });
+ if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true };
+ return { text: renderVideoAssistRequest(body, (plan.body.plan ?? {}) as AssistPlanView, p.preset) };
} else if (task === "verdicts" && p.routes[task] === "code") {
// Verdicts are not a session's to make: the bench's bar names the models.
return {
@@ -688,7 +788,7 @@ export async function generateTool(
const jobId = typeof a.body.jobId === "string" ? a.body.jobId : "";
const n = typeof a.body.iteration === "number" ? a.body.iteration : undefined;
if (!jobId) return { text: `generate: the editor accepted it and started no job (${JSON.stringify(a.body)})`, isError: true };
- const article = task === CLIPS_SUGGEST ? "" : String(body.article);
+ const article = task === CLIPS_SUGGEST || task === VIDEO_ASSIST ? "" : String(body.article);
const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : [];
const head =
`generate ${task}: queued as job ${jobId}` +
@@ -800,12 +900,20 @@ export const GENERATION_TOOLS = [
project: {
type: "string",
description:
- "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers.",
+ "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers. video-assist: the video project's absolute directory (its video.manifest.json).",
},
proposals: { type: "array", items: { type: "string" }, description: "clips-suggest: only these proposal ids." },
+ request: {
+ type: "string",
+ description:
+ 'video-assist: what to change on the video project, in words ("make the joins 0.15 s with less smear") — one ask whose checked edits land in the project\'s assist-proposals.json as proposals the operator applies in umtool. Routed to code: the answer is the request, which this session answers and returns as answers.',
+ },
+ scope: { type: "string", enum: ["look", "clips", "fx", "all"], description: "video-assist: what the ask may touch (default all)." },
+ note: { type: "string", description: "video-assist: a note on the whole project (n_…) whose text is the request; the proposals are posted to it as the agent's reply." },
answers: {
type: "object",
- description: 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]} — read as a model\'s answer, written by the editor.',
+ description:
+ 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]}; video-assist routed to code: {"ops": [{"op", "id", "key", "value"}], "reply"} — read as a model\'s answer, written by the editor.',
},
wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." },
wait_seconds: {
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -11276,3 +11276,48 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
`<dir>/<threadId>/page-<N>.html` (`page-<N>.<status>.html` served in its place while it exists) with no pause
(`common/social/forumFixtureLoader.ts`); `editor/e2e/servers.ts` sets it per slot to `test-transcripts/.forum-fixture`.
`common/social/__fixtures__/fakeForumThread.ts` is a thread that grows, loses posts and writes those pages.
+
+## Release 38 lane E: the video assistant — look rules, ops, proposals, join preview (verified 2026-10-20, branch `r38/video-assist`)
+
+- **The look's rules live in common now**: `common/lib/report/look.mjs` holds `LOOK_KEYS`, `applyLookPatch(manifest,
+ patch) → {render, errors}` (what umtool's `updateRender` writes with), `lookErrors`, and the validators that were in
+ report-to-video — `validateTransitionStyle`/`validateSlide` (+ `TRANSITION_STYLES`, `SLIDE_DEFAULTS`, `SLIDE_BOUNDS`,
+ now exported), `validateRoom`/`clipRoom`/`roomOn` (+ `ROOM`, `ROOM_EDGES`, `ROOM_BOUNDS` {minGap [0.1,2], maxS
+ [0,10]}), `validateCaptions`/`validateLoudness`/`verticalErrors`/`validateVertical`/`validateLook` and their
+ constants. `report-to-video/{look,room,transition}.mjs` RE-EXPORT every moved name, so no importer changed; umtool
+ `lib/report/manifest.mjs` re-exports `LOOK_KEYS` and `lookOf`. Moved, not copied: the editor (which cannot import
+ umtool) checks a proposed look op with the writer's own function.
+- **Composition params** (`common/lib/report/fxParams.mjs`): `COMPOSITION_PARAMS[id]` for `deck`
+ (`render.chrome.deck`), `stats`, `fx.<effect>` — `{key (dot path in the settings), label, kind
+ (seconds|number|int|px|enum|bool|text), min/max | values | maxLength, default}`. `deck.mjs` `DECK_PARAMS`,
+ `stats.mjs` `STATS_PARAMS`, `fx.mjs` `FX_PARAMS` (by effect) are the slices. `report-to-video/fx-params.test.mjs`
+ holds every declaration to `validateChrome` at its bounds and just past them. Layout-coupled settings (deck height,
+ footageScale, qr.size, pip sizes) are NOT declared.
+- **The ops** (`common/lib/report/videoAssistOps.mjs`): `look | slide | room | clip_edges | clip_room | fx`. The
+ model writes ONE shape `{op, id, key, value}` (`ASSIST_OPS_SCHEMA`: four required keys an op — a strict tool requires
+ every key); `normalizeAssistOp` turns it into the checker's (`{op:"slide", blur:0.3}`). `checkAssistOps(manifest,
+ ops, {request, scope}) → {ops: [{op, diff, apply, warning?}], refused: [{index, op, why}], diff, manifest}` applies
+ each op to a COPY in turn. `apply` = `{writer: "render", patch}` | `{writer: "clip", body}` (runClipEditorOp
+ `trim`/`room`) | `{writer: "chrome", id, param, value}`. A clip's window: its extent (start–end) when it has a cut,
+ else its edges ± `render.fetchPad` (0 when absent); an edge moves ≤ 3 s (`EDGE_SLACK_SECONDS`) unless the request
+ names more seconds (`secondsNamedIn`: "6 seconds", "2.5 s"). A room op's numeric `tail` = tail on + `maxS`.
+- **`<project>/assist-proposals.json`** (`common/lib/report/videoAssistProposals.mjs`): `{version: 1, promptVersion:
+ "video-assist-1", at, model, request, scope, note?, reply?, ops: [{id: "a<n>", op, diff, warning?, status:
+ proposed|applied|dismissed|failed, at?, error?}], refused: [{op, why}], diff}`. Written whole by the editor's task (a
+ new ask replaces it); statuses marked by umtool (`lib/report/videoAssist.mjs` `applyAssistOps`/`dismissAssistOps`).
+ Never applied by being there. umtool's own `.video-assist-job.json` is the followed job.
+- **Task `video-assist`** (`GENERATION_TASKS`; presets: `local` in code/balanced/local, `api` in api — the `code`
+ preset routes it LOCAL). `report-draft` body: `project` (absolute), `request` | `note` (a `whole`-anchored note's
+ text), `scope` (look|clips|fx|all), `answers` (code route), `dryRun` (the ops route: `planVideoAssistJob`). Its own
+ job (`common/controller/videoAssist.ts`), `draft:local` / `draft:api`, narration cap, ledger task `video-assist`;
+ marker `{article: "", iteration: 0, task: "video-assist", project, status, summary, usd, assist: {at, proposed,
+ refused, diff, file, note?}}`. A note's reply is posted to umtool's notes with proposal `{kind: "assist", at, ops}`
+ (a new `ReplyProposal` kind; umtool `lib/annotations/shape.mjs`).
+- **`videoOps.ts`** (revise-video) gained `look`, `slide`, `room` (through `checkAssistOps`, scope look);
+ `VIDEO_OPS_SCHEMA` = `OPS_SCHEMA` + `key`/`value`; `localOpsBatch` takes an optional `schema`.
+- **Join preview**: `build-video.mjs <manifest> --join-preview [--join-from <clip>]` → `out/join-preview.mp4` +
+ `out/join-preview.json` (`{version, madeAt, clips, look}`), work in `out/join-preview-work/`; no chapters, YouTube
+ text or thumbnail; in the heavy slot (`takesHeavySlot`). `report-to-video/join-preview.mjs`
+ `joinPreviewTimeline`: 4 consecutive clips, each the last 3 s of its cut (the last clip its first 3 s), cards out,
+ windows untouched; refused for a deck, a montage, hard cuts. umtool `/api/report/join-preview` (a `join preview
+ <project>` job on lib/jobs.ts).
diff --git a/plans/release-38/video-assist.md b/plans/release-38/video-assist.md
@@ -0,0 +1,168 @@
+# Release 38 lane E — `r38/video-assist`: the local video assistant (as shipped)
+
+The operator, 2026-10-20: "A feature to iterate on the video with hyperframes using qwen, such that I can request
+little things like changing transition time on local AI even when Claude Code is not available." This lane makes a
+request in words ("make the joins 0.15 s with less smear") a set of checked, proposed edits of a video project that
+the operator applies with a click — on the local model by default. Rulings followed: every model step optional and
+routed by `settings.generation` (local / api / code); every op the assistant can propose is also a field (the Look
+panel's slide and room numbers are new); nothing is applied without the operator's Apply, and Apply writes through
+the manifest's own writers, token-guarded; never free HTML, never a raw manifest write; synthetic fixtures only; no
+real network or model call in any test.
+
+## What
+
+1. **The look's rules moved to common** (`common/lib/report/look.mjs`, + `.d.mts`): `LOOK_KEYS`, `applyLookPatch`
+ (the body of umtool's `updateRender`, now pure), `lookErrors`, `lookOf`, and the validators and bounds that lived in
+ report-to-video (`validateTransitionStyle`/`validateSlide`, `validateRoom`/`clipRoom`/`roomOn`,
+ `validateCaptions`/`validateLoudness`/`verticalErrors`/`validateVertical`/`validateLook`; `SLIDE_BOUNDS` and
+ `ROOM_BOUNDS` exported). `report-to-video/{look,room,transition}.mjs` re-export every moved name; `updateRender`
+ calls `applyLookPatch`. Moved, not copied — the editor's task checks a look op with the writer's own function.
+2. **Declared composition params** (`common/lib/report/fxParams.mjs`): `COMPOSITION_PARAMS` for `deck`, `stats` and
+ each `fx.<effect>` — timings, sizes, positions, toggles, the odometer's label — each with the bounds its validator
+ holds it to; `DECK_PARAMS` / `STATS_PARAMS` / `FX_PARAMS` re-exported by `deck.mjs` / `stats.mjs` / `fx.mjs`;
+ `fx-params.test.mjs` holds every declaration to `validateChrome` at both bounds and just past them.
+3. **The ops** (`common/lib/report/videoAssistOps.mjs`, extending nothing: its own module, `.mjs` so umtool's plain-node
+ libs and the editor's TS both import it): `look`, `slide`, `room`, `clip_edges`, `clip_room`, `fx`, each checked
+ against the manifest as the ops before it left it, each with a diff line and the writer that performs it
+ (`checkAssistOps`); the model's one shape `{op, id, key, value}` (`ASSIST_OPS_SCHEMA`, four required keys — a strict
+ API tool requires every key) normalised to the checker's; `assistView` — the compact view trimmed to a budget, the
+ clips the request names first; `secondsNamedIn` (the 3 s slack widens to what the request names).
+4. **The proposals file** (`common/lib/report/videoAssistProposals.mjs`): `<project>/assist-proposals.json`
+ `{version, promptVersion, at, model, request, scope, note?, reply?, ops[{id, op, diff, warning?, status}],
+ refused[{op, why}], diff[]}` — written whole by the task, its statuses marked by umtool.
+5. **Task `video-assist`** (`GENERATION_TASKS`; local in every preset but `api`, the `code` preset included; field
+ docs; MCP `GENERATE_TASKS` derived): `common/lib/report/draft/tasks/videoAssist.ts` (one schema-bound ask, local
+ fitted to the prompt cap by `fitLocalAsk`, the API the same ask; the code route's `answers` read as a model's;
+ the ops checked against the manifest as it is after the answer; proposals written; never applied) and
+ `common/controller/videoAssist.ts` (its own `report-draft` job: `draft:local` through the GPU arbiter — the log and
+ the box say it waits for a transcription — ollama unloaded after; `draft:api` with the narration and daily caps and
+ a ledger row; `note`: a whole-project note's text is the request, the proposals posted back to it as the agent's
+ reply with `proposal {kind: "assist", at, ops}`). `reportDraft.ts` parses `request` / `scope` (and shares
+ `project` / `note` / `answers` with clips-suggest); the ops route's `dryRun` answers `planVideoAssistJob`.
+6. **MCP** (`mcp/src/generation.ts`): `generate` takes `task: "video-assist"` with `project` and `request` | `note`,
+ `scope`; routed to code it returns the editor's plan as this session's request and takes `answers` back;
+ `/gen` (`.claude/commands/gen.md`) says so.
+7. **umtool**: `lib/report/videoAssist.mjs` (the request, the followed job, `proposalsView` — each waiting op
+ re-checked, "now: …" when the manifest no longer allows it — `applyAssistOps` and `dismissAssistOps`);
+ `/api/report/video-assist` (GET view / job; POST ask, `action: "apply"` (token, ids, `at`) under `withEditNotes`,
+ `action: "dismiss"`, cancel); `components/projects/report/AssistBox.tsx` — the Ask box (status line: the route, the
+ GPU wait, or why not), the diff list with **Apply** / **Apply all** / **Dismiss**, applied and refused marked,
+ **Preview join**, and **Notes on the project** with **Ask the assistant** and the reply's **Apply all**; in the
+ Look panel (scope all, with the preview and the notes) and the clip editor's side column (a request naming no clip
+ is sent as about the selected one). `ReplyProposal` gains `kind: "assist"` (`lib/annotations/shape.mjs`,
+ `types.ts`); the clip editor never applies one.
+8. **The Look panel's owed fields**: the blur slide's **Travel**, **Smear**, **Grain** (shown for a blur slide), and
+ with the tail on **Tail up to, s** (`room.maxS`) and **Silence gap, s** (`room.minGap`) — written only off their
+ defaults.
+9. **Preview join**: `build-video.mjs --join-preview [--join-from <clip>]` (`report-to-video/join-preview.mjs`
+ `joinPreviewTimeline`: four consecutive clips, the last 3 s of each cut — the last clip its first 3 s — cards out,
+ windows untouched) → `out/join-preview.mp4` + `out/join-preview.json`, its own work dir, no chapters / YouTube text
+ / thumbnail, in the heavy slot; umtool `lib/report/joinPreview.mjs` + `/api/report/join-preview` (a job on the
+ app's runner), played under the box, marked stale when the look changed.
+10. **revise-video** gains `look` / `slide` / `room` (`videoOps.ts` through `checkAssistOps`, scope look;
+ `VIDEO_OPS_SCHEMA`; `localOpsBatch` takes the schema) — the article path keeps its iteration model.
+
+## Files
+
+common: `lib/report/look.mjs` + `.d.mts` (new), `lib/report/fxParams.mjs` + `.d.mts` (new),
+`lib/report/videoAssistOps.mjs` + `.d.mts` (new), `lib/report/videoAssistProposals.mjs` + `.d.mts` (new),
+`lib/report/videoAssistOps.test.ts` (new), `lib/report/draft/tasks/videoAssist.ts` + `.test.ts` (new),
+`lib/report/draft/videoOps.ts`, `lib/report/draft/tasks/revise-video.ts`, `lib/report/draft/tasks/revise-report.ts`
+(`localOpsBatch` schema), `controller/videoAssist.ts` (new), `controller/reportDraft.ts`, `lib/generationSettings.ts`
++ `.test.ts`, `testing/clips/assistProject.mjs` + `.d.mts` (new), `testing/README.md`, `package.json` (exports).
+editor: `app/api/ops/report-draft/route.ts`, `app/api/ops/_videoAssist.test.ts` (new), `CHANGELOG.md`. mcp:
+`src/generation.ts`, `src/generation.test.ts`. report-to-video: `look.mjs`, `room.mjs`, `transition.mjs` (re-exports),
+`deck.mjs`, `stats.mjs`, `fx.mjs` (params slices), `join-preview.mjs` + `.test.mjs` (new), `fx-params.test.mjs` (new),
+`build-video.mjs` (`--join-preview`), `package.json` (`./join-preview`). umtool: `lib/report/manifest.mjs`
+(`updateRender` over `applyLookPatch`), `lib/report/videoAssist.mjs` + `.test.mjs` (new), `lib/report/joinPreview.mjs`
+(new), `app/api/report/video-assist/route.ts` (new), `app/api/report/join-preview/route.ts` (new),
+`components/projects/report/AssistBox.tsx` (new), `components/projects/report/LookPanel.tsx`,
+`components/projects/review/ClipEditor.tsx`, `components/projects/review/ClipSuggest.tsx`,
+`lib/annotations/shape.mjs`, `lib/annotations/types.ts`, `lib/create/policy.mjs`, `e2e/video-assist.spec.ts` (new),
+`e2e/fixtures/video-assist-fixture.mjs` (new), `e2e/fixtures/make-fixture.mjs`, `e2e/fixtures/editor-stub.mjs`,
+`docs/report-video.md`. Root: `.claude/commands/gen.md`, `OPERATING.md`, `SETTINGS.md`, `settings.json.example` (regenerated),
+`plans/FACTS.md` ("Release 38 lane E").
+
+## Commits
+
+| sha | what |
+|---|---|
+| `e4542507` | common: the look's rules move to common/lib/report/look.mjs; compositions declare their tunable params (+ fx-params.test.mjs) |
+| `f9662056` | common: task video-assist — the ops, the proposals file, the task and its job, reportDraft, generation settings, the editor's dry run; the test kit's project and 29-request table; tests |
+| `5e9936d3` | common: revise-video takes the look ops (look, slide, room) |
+| `53fab519` | mcp: generate video-assist (project + request / note; the code route's request and answers); /gen |
+| `30bdc4bb` | umtool: the Ask box, Apply / Apply all / Dismiss, Preview join (build-video --join-preview), the Look panel's slide and room fields, notes' assist proposal; e2e video-assist.spec.ts; docs |
+| `276f002a` | plans: FACTS ("Release 38 lane E"); CHANGELOG |
+| `d3e009c1` | common: videoOps' refusal names the look ops (an existing test's expectation) |
+| `dd5f4237` | docs: the video-assist dry run in OPERATING's recipes; the ops syntax in umtool's docs |
+| (this commit) | plans: this record |
+
+## Gates
+
+All through the session's lock (`r31-locked.sh`; the e2e through `r31-locked6.sh`), from the worktree root. The
+machine sat under the lock's memory floor for most of the afternoon (available memory 0.7–3 GB while other lanes and a
+transcription ran), so the runs were queued detached and waited on in short loops.
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before the commits (one umtool error —
+ `dismissAssistOps`' untyped options — fixed first; umtool re-checked clean).
+- common: 4764 (4762 pass, 2 skipped; measured at the branch's start) → **4784 / 4782 pass / 0 fail / 2 skipped**
+ (+20: videoAssistOps 12, the task 6, generation settings 1, videoOps 1).
+- editor unit: 356 → **361: 360 pass, 1 fail** — the one is `remote-listing/route.test.ts` ("a listing is a job whose
+ last line is the diff…": the log read before its `@@remote-listing` line landed, under the machine's load; not this
+ lane's code); that file alone afterwards **2 / 2 pass**. +5: `_videoAssist.test.ts`.
+- mcp: 379 (release 37's record) → **380 / 380** (+1: generate video-assist).
+- test:scripts: 1316 (1312 pass, 4 skipped; release 37's record) → **1326 / 1322 pass / 0 fail / 4 skipped** (+10:
+ fx-params 3, join-preview 2, umtool videoAssist 5).
+- umtool unit (`pnpm --filter umtool test`): **45 / 45** (none of this lane's tests are there: umtool's `.mjs` tests run
+ in test:scripts).
+- Docs: `docs env --check` 0, `docs files --check` 0, `docs cli --check` 0, `settings example --check` 0 (after
+ `docs files` and `settings example` regenerated SETTINGS.md and settings.json.example for the new route).
+- e2e (umtool, `pnpm --filter umtool run e2e video-assist.spec.ts clip-look.spec.ts`, prebuild stamped
+ `93df78d7b655` at `d3e009c1`): **2 / 2 passed** (35 s; video-assist 13.6 s, clip-look — the Look panel's existing
+ spec, a short rendered — 6.9 s), first run.
+
+## Decisions
+
+- **One module of its own** for the ops (`common/lib/report/videoAssistOps.mjs`, not an extension of `videoOps.ts`):
+ plain ESM so umtool's node libs (Apply) and the editor's TS task import the same checker; `videoOps.ts` calls it for
+ revise-video's look ops.
+- **The look's validators MOVED to common** (re-exported by report-to-video), not copied: the editor cannot import
+ umtool, and the brief's "the SAME validators updateRender uses" leaves no other honest way.
+- **The composition params are declared in common** (`fxParams.mjs`) and re-exported by `deck.mjs` / `stats.mjs` /
+ `fx.mjs` as their slices — the editor needs them too; a drift test holds each declaration to `validateChrome`. The
+ layout-coupled settings (deck height, footage scale, QR size, pip sizes) are not declared; `validateChrome` still
+ has the last word at Apply. An `fx` op only tunes a composition the cut already draws (it never turns one on).
+- **The model's op shape is `{op, id, key, value}`** (four required keys): the default API model is a strict tool
+ user, where every schema key is required — a flat schema of every op's fields would force junk into each op.
+- **"≤ 3 s from current unless the request says more"**: the step widens to the largest number of seconds the
+ request names ("6 seconds", "2.5 s"); a bare number ("start at 516") does not widen it.
+- **A clip's source window**: its extent (start–end) when it has a cut; else its edges ± `render.fetchPad` (0 when the
+ cut sets none).
+- **"room tail 2"** is `{tail: true, maxS: 2}`: a room edge is a boolean, `maxS` is its seconds; a number for the
+ tail turns it on up to that, and a number alone (maxS / minGap) on a cut with no room turns the tail on with it.
+- **The `code` preset routes `video-assist` local** (the brief: local in every preset but `api`); its field doc and
+ the preset's doc say so.
+- **Scope**: both Ask boxes ask with `all`; the clip editor's box sends a request that names no clip as about the
+ selected one ("… (on clip r002)"). `scope` stays a body field for the CLI and the MCP.
+- **Preview join** is `build-video --join-preview` (four clips, the last 3 s of each cut and the first 3 s of the
+ last), not `--only` (one segment has no join); its own work dir and file, so the cut's `out/` is never touched.
+ Refused for a deck cut (its joins are under the deck), a montage and hard cuts.
+- **A project-level note** is a `whole`-anchored note; the video project had no surface for one, so the Look panel's
+ box lists them (Notes on the project, with Add note). The reply's proposal is a new `ReplyProposal` kind `assist`
+ `{at, ops}`; its Apply all applies the waiting ops of THOSE proposals only while they are the latest (`at`).
+- **Apply** re-checks every op against the manifest as it is; an op the manifest no longer allows fails with the reason
+ and the rest go on; a stale token stops the batch (409) with what was applied kept and marked.
+- **The task re-reads the manifest after the answer** and checks the ops against that, so an edit made while the model
+ thought is what the ops meet.
+
+## Not done / owed
+
+- **Live, after merge** (the orchestrator's): the editor and umtool restarts; a dry run then a real ask on the Nik Drop
+ project ("make the joins 0.15 s with less smear") on local Qwen, applied, and a Preview join — commands in the
+ report.
+- The Build tab's other specs (`piece.spec.ts`, `visual-audit.spec.ts`) now render the Ask box under the Look panel;
+ not run here (two specs a run) — the orchestrator's full umtool suite covers them.
+- `fx` ops reach only the declared params (no layout-coupled deck settings, no `render.palette`, no kinetic-quote
+ voices) and never turn an effect on; widening that is a declaration per param plus its drift test.
+- The join preview is not offered for a deck cut (its joins are drawn under the deck; `--chrome-preview` is that
+ path).
diff --git a/settings.json.example b/settings.json.example
@@ -258,7 +258,8 @@
"social": "local",
"verdicts": "local",
"frames": "api",
- "clips-suggest": "local"
+ "clips-suggest": "local",
+ "video-assist": "local"
},
"models": {
"api": "claude-sonnet-5-5",
diff --git a/umtool/app/api/report/join-preview/route.ts b/umtool/app/api/report/join-preview/route.ts
@@ -0,0 +1,82 @@
+import { stat } from "node:fs/promises";
+import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
+import { rangeResponse } from "@/lib/report/serve.mjs";
+import { joinPreviewFile, joinPreviewSteps, readJoinPreview } from "@/lib/report/joinPreview.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE JOIN PREVIEW (release 38 lane E): `<project>/out/join-preview.mp4`, the
+// first few joins of the cut in its current look (build-video.mjs
+// --join-preview, in the heavy slot), as ONE job on the app's runner
+// (lib/jobs.ts) -- the Look panel's Preview join.
+//
+// GET ?project=<id> { preview, running }
+// GET ?project=<id>&file=1 the mp4 (ranges)
+// GET ?job=<id>[&since=&sinceEvent=] that job
+// POST { project, from? } make it (from that clip, else the first)
+// ?cancel=<job> stop it
+const headers = { "cache-control": "no-store" };
+const isPreviewJob = (kind: string) => /^join preview /.test(kind);
+
+async function reportProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a join preview is a report video's" }, { status: 400, headers }) };
+ return { project };
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const jobId = url.searchParams.get("job");
+ if (jobId) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const r = await reportProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ if (url.searchParams.get("file")) {
+ const abs = joinPreviewFile(r.project.dir);
+ const st = await stat(abs).catch(() => null);
+ if (!st?.isFile()) return new Response("no join preview", { status: 404 });
+ return rangeResponse(request, {
+ abs,
+ size: st.size,
+ headers: { "content-type": "video/mp4", "accept-ranges": "bytes", "cache-control": "private, no-store" },
+ });
+ }
+ const manifest = await readManifest(r.project.dir);
+ const running = runningJob();
+ return Response.json(
+ {
+ preview: await readJoinPreview(r.project.dir, manifest),
+ running: running && running.project === r.project.id && isPreviewJob(running.kind) ? jobView(running) : null,
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await reportProject(body.project);
+ if ("error" in r) return r.error;
+ const manifest = await readManifest(r.project.dir);
+ if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers });
+ const from = body.from === undefined || body.from === null || body.from === "" ? null : String(body.from);
+ if (from && !clipsOf(manifest).some((e: { id: string }) => e.id === from)) return Response.json({ error: `no clip with id ${from}` }, { status: 400, headers });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ try {
+ const job = startJob(`join preview ${r.project.id}`, joinPreviewSteps(r.project, from), { project: r.project.id });
+ return Response.json({ ok: true, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers });
+ }
+}
diff --git a/umtool/app/api/report/video-assist/route.ts b/umtool/app/api/report/video-assist/route.ts
@@ -0,0 +1,139 @@
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
+import {
+ AssistRequestError,
+ applyAssistOps,
+ assistJobView,
+ assistRouteOf,
+ clearAssistJob,
+ dismissAssistOps,
+ draftBodyOf,
+ parseAssistRequest,
+ proposalsView,
+ readAssistJob,
+ writeAssistJob,
+} from "@/lib/report/videoAssist.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE VIDEO ASSISTANT (release 38 lane E) -- optional, every part of it. An
+// Ask (a request in words, or a note on the whole project) starts the
+// EDITOR's `report-draft` job, task `video-assist`, routed by
+// settings.generation (local by default, through the GPU arbiter); its
+// proposals land in `<project>/assist-proposals.json`. This route asks with
+// the shared WORKER_TOKEN (lib/articles/generation.ts askEditor), follows the
+// job, and APPLIES on the operator's click: each op re-checked and written
+// through the manifest's writers (lib/report/videoAssist.mjs), token-guarded.
+//
+// GET ?project=<id> { proposals, error, route, editorError, job, token }
+// GET ?project=<id>&job=<jobId> that job (ended: forgotten)
+// POST { project, request | note, scope? } → { jobId, job }
+// POST { project, action: "apply", ids?, token, at? } → { applied, failed, token, proposals } | 409
+// POST { project, action: "dismiss", ids?, at? } → { dismissed, proposals }
+// POST ?cancel=<jobId>&project=<id> stop it
+const headers = { "cache-control": "no-store" };
+
+async function assistProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the assistant works on a report video's cut" }, { status: 400, headers }) };
+ return { project };
+}
+
+const failed = (e: unknown) => {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers });
+ const status = e instanceof EditorError ? e.status : e instanceof AssistRequestError ? ((e as AssistRequestError & { status?: number }).status ?? 400) : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+};
+
+async function jobOf(dir: string, id: string) {
+ const rec = await readAssistJob(dir);
+ const job = await readDraftJob(id, 40);
+ const view = assistJobView(rec && rec.jobId === id ? rec : null, job);
+ if (view.ended) await clearAssistJob(dir, id);
+ return view;
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await assistProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ const dir = r.project.dir;
+ const id = url.searchParams.get("job");
+ if (id) {
+ try {
+ return Response.json(await jobOf(dir, id), { headers });
+ } catch (e) {
+ return failed(e);
+ }
+ }
+ const view = await proposalsView(dir);
+ // The route and the followed job need the editor; without one the proposals still show.
+ const policy = await readPolicy().catch((e: unknown) => e as Error);
+ const rec = await readAssistJob(dir);
+ let job = null;
+ if (rec) {
+ job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => {
+ if (e instanceof EditorError && e.status === 404) await clearAssistJob(dir, rec.jobId);
+ return null;
+ });
+ }
+ return Response.json(
+ {
+ ...view,
+ route: policy instanceof Error ? null : assistRouteOf(policy.generation, dir),
+ editorError: policy instanceof Error ? policy.message : null,
+ job,
+ token: await manifestToken(dir),
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) {
+ const r = await assistProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ try {
+ await cancelDraftJob(cancel);
+ return Response.json({ cancelled: true }, { headers });
+ } catch (e) {
+ return failed(e);
+ }
+ }
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await assistProject(body.project);
+ if ("error" in r) return r.error;
+ const dir = r.project.dir;
+ const ids = Array.isArray(body.ids) ? body.ids.map(String) : null;
+ const at = typeof body.at === "string" ? body.at : null;
+ try {
+ if (body.action === "apply") {
+ const token = body.token === undefined || body.token === null ? null : String(body.token);
+ const { result, editNotes } = await withEditNotes(r.project, () => applyAssistOps(r.project, { ids, token, at }));
+ return Response.json({ ok: true, ...result, editNotes }, { headers });
+ }
+ if (body.action === "dismiss") return Response.json({ ok: true, ...(await dismissAssistOps(dir, { ids, at })) }, { headers });
+ if (body.action !== undefined && body.action !== "ask") return Response.json({ error: 'action is "ask", "apply" or "dismiss"' }, { status: 400, headers });
+ const req = parseAssistRequest(body);
+ const running = await readAssistJob(dir);
+ if (running) {
+ const view = await jobOf(dir, running.jobId).catch(() => null);
+ if (view && !view.ended) return Response.json({ error: "the assistant is already working on this project", job: view }, { status: 409, headers });
+ }
+ const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: draftBodyOf(dir, req) });
+ const jobId = String(answer.jobId ?? "");
+ if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers });
+ await writeAssistJob(dir, { jobId, ...(req.note ? { note: req.note } : { request: req.request }), scope: req.scope, at: new Date().toISOString() });
+ const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, status: "queued", ended: false, queue: null, last: null, summary: null }));
+ return Response.json({ ok: true, jobId, job }, { headers });
+ } catch (e) {
+ return failed(e);
+ }
+}
diff --git a/umtool/components/projects/report/AssistBox.tsx b/umtool/components/projects/report/AssistBox.tsx
@@ -0,0 +1,462 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedNotes } from "@/components/notes/NotesProvider";
+import { NoteThread } from "@/components/notes/NoteThread";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// THE ASK BOX (release 38 lane E): the video assistant, optional in every
+// part. A request in words ("make the joins 0.15 s with less smear") starts
+// the editor's `video-assist` job (routed by settings.generation: local by
+// default, through the GPU arbiter); its PROPOSALS come back as a diff list
+// -- Apply all, Apply one, Dismiss -- and nothing is written until Apply,
+// which re-checks each op and writes through the manifest's own writers
+// (/api/report/video-assist, lib/report/videoAssist.mjs). A note on the whole
+// project can be asked too: the assistant replies on it, with an Apply.
+// Preview join renders the first joins in the current look (the heavy slot).
+// With generation routed elsewhere or no editor the box says so; the panel it
+// sits in is the manual path.
+// ---------------------------------------------------------------------------
+
+type Scope = "look" | "clips" | "fx" | "all";
+type ProposedOp = { id: string; op: Record<string, unknown>; diff: string; warning?: string; status: "proposed" | "applied" | "dismissed" | "failed"; error?: string; now?: string | null; diffNow?: string | null };
+type Proposals = { at: string; model: string; request: string; scope: string; note?: string; reply?: string; ops: ProposedOp[]; refused: { op: Record<string, unknown>; why: string }[] };
+type Job = { id: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; last: string | null; summary: string | null; note?: string; request?: string };
+type View = {
+ proposals: Proposals | null;
+ error: string | null;
+ route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null;
+ editorError: string | null;
+ job: Job | null;
+ token: string | null;
+};
+type Preview = { size: number; mtimeMs: number; stale: boolean; record: { clips?: string[] } | null } | null;
+type PreviewJob = { id: string; state: string; error: string | null };
+
+const routeLine = (v: View): string => {
+ if (!v.route) return `The assistant needs the editor${v.editorError ? ` (${v.editorError})` : ""}. Every setting here is a field you can change by hand.`;
+ if (v.route.why) return `${v.route.why}. Every setting here is a field you can change by hand.`;
+ if (v.route.route === "local") return `On the local model${v.route.model ? ` (${v.route.model})` : ""}, through the GPU: it waits while a transcription runs. Nothing changes until you Apply.`;
+ return `On the Claude API${v.route.model ? ` (${v.route.model})` : ""}. Nothing changes until you Apply.`;
+};
+
+const jobLine = (j: Job): string => {
+ if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `The ask ${j.status}${j.last ? ` — ${j.last}` : ""}`;
+ if (j.status === "queued") {
+ const gpu = j.queue?.key === "draft:local";
+ return `Queued${j.queue?.position ? ` (${j.queue.position} in line)` : ""}${gpu ? " — waiting for the GPU (a transcription runs first)" : ""}`;
+ }
+ return `Asking the assistant${j.last ? ` · ${j.last}` : ""}`;
+};
+
+const STATUS_WORD: Record<ProposedOp["status"], string> = { proposed: "proposed", applied: "applied", dismissed: "dismissed", failed: "not applied" };
+
+export function useAssist(project: string) {
+ const [view, setView] = useState<View | null>(null);
+ const [job, setJob] = useState<Job | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [ended, setEnded] = useState(0);
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (!r) return;
+ const j = (await r.json().catch(() => null)) as (View & { error?: string }) | null;
+ if (!r.ok || !j) {
+ setError(j?.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setView(j);
+ if (j.job && !j.job.ended) setJob(j.job);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ const live = job && !job.ended ? job.id : null;
+ useEffect(() => {
+ if (!live) return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as Job;
+ setJob(j);
+ if (j.ended) {
+ setEnded((n) => n + 1);
+ await load();
+ }
+ }, 1500);
+ return () => clearInterval(t);
+ }, [live, project, load]);
+ const post = useCallback(
+ async (body: Record<string, unknown>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/report/video-assist", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ return { ok: r.ok, status: r.status, json: j };
+ } finally {
+ setBusy(false);
+ }
+ },
+ [project],
+ );
+ const ask = useCallback(
+ async (body: { request: string; scope: Scope } | { note: string; scope: Scope }) => {
+ // The last ask's line goes: what shows next is this one's.
+ setJob(null);
+ const r = await post(body);
+ if (r.json.job) setJob(r.json.job as Job);
+ if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ return r.ok;
+ },
+ [post],
+ );
+ const apply = useCallback(
+ async (ids: string[] | null, at?: string) => {
+ const r = await post({ action: "apply", token: view?.token ?? null, ...(ids ? { ids } : {}), ...(at ? { at } : {}) });
+ if (r.status === 409) {
+ await load();
+ setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and apply again`);
+ return false;
+ }
+ if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ await load();
+ return r.ok && Array.isArray(r.json.applied) && (r.json.applied as unknown[]).length > 0;
+ },
+ [post, view?.token, load],
+ );
+ const dismiss = useCallback(
+ async (ids: string[] | null) => {
+ const r = await post({ action: "dismiss", ...(ids ? { ids } : {}), ...(view?.proposals ? { at: view.proposals.at } : {}) });
+ if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ await load();
+ },
+ [post, view?.proposals, load],
+ );
+ const cancel = useCallback(async () => {
+ if (!job) return;
+ await fetch(`/api/report/video-assist?cancel=${encodeURIComponent(job.id)}&project=${encodeURIComponent(project)}`, { method: "POST" }).catch(() => null);
+ }, [job, project]);
+ return { view, job, error, busy, ended, load, ask, apply, dismiss, cancel };
+}
+
+/** The proposals as a diff list: Apply one, Apply all, Dismiss. */
+function ProposalList({ p, busy, onApply, onDismiss }: { p: Proposals; busy: boolean; onApply: (ids: string[] | null) => void; onDismiss: () => void }) {
+ const waiting = p.ops.filter((o) => o.status === "proposed" || o.status === "failed");
+ const applicable = waiting.filter((o) => !o.now);
+ return (
+ <section data-assist-proposals={p.ops.length} data-assist-at={p.at} className="space-y-1.5 rounded-[3px] border border-seam bg-panel-2 px-2.5 py-2">
+ <p className="m-0 text-[11.5px] text-muted" data-assist-request="">
+ “{p.request}” — {p.model} · {new Date(p.at).toLocaleString()}
+ </p>
+ {p.reply && (
+ <p className="m-0 text-[12px] text-text-2" data-assist-reply="">
+ {p.reply}
+ </p>
+ )}
+ {p.ops.length === 0 && <p className="m-0 text-[12px] text-muted">No edit proposed.</p>}
+ {p.ops.length > 0 && (
+ <ul className="m-0 list-none space-y-1 p-0">
+ {p.ops.map((o) => (
+ <li key={o.id} data-assist-op={o.id} data-assist-status={o.status} className={cn("flex flex-wrap items-baseline gap-2 text-[12.5px]", o.status === "dismissed" && "opacity-60")}>
+ <span className={cn("font-mono text-text", o.status === "applied" && "text-kept-text")}>{o.status === "proposed" && o.diffNow && o.diffNow !== o.diff ? o.diffNow : o.diff}</span>
+ {o.status !== "proposed" && <span className={badgeVariants({ variant: o.status === "applied" ? "on" : o.status === "failed" ? "blocking" : "info", size: "sm" })}>{STATUS_WORD[o.status]}</span>}
+ {(o.status === "proposed" || o.status === "failed") && (
+ <button type="button" data-assist-apply={o.id} disabled={busy || !!o.now} title={o.now ?? "write it now, through the look's (or the clip's) own writer"} onClick={() => onApply([o.id])} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Apply
+ </button>
+ )}
+ {o.warning && <span className="text-[11.5px] text-doubt-text">{o.warning}</span>}
+ {o.now && (o.status === "proposed" || o.status === "failed") && (
+ <span className="text-[11.5px] text-muted" data-assist-now="">
+ now: {o.now}
+ </span>
+ )}
+ {o.error && o.status === "failed" && !o.now && <span className="text-[11.5px] text-reject-text">{o.error}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {p.refused.length > 0 && (
+ <ul className="m-0 list-none space-y-0.5 p-0" data-assist-refused-list="">
+ {p.refused.map((r, i) => (
+ <li key={i} data-assist-refused="" className="text-[11.5px] text-muted">
+ not proposed: {r.why}
+ </li>
+ ))}
+ </ul>
+ )}
+ {waiting.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2 pt-0.5">
+ <button type="button" data-assist-apply-all="" disabled={busy || !applicable.length} onClick={() => onApply(null)} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Apply all
+ </button>
+ <button type="button" data-assist-dismiss="" disabled={busy} onClick={onDismiss} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Dismiss
+ </button>
+ </div>
+ )}
+ </section>
+ );
+}
+
+/** Preview join: the first joins in the look as saved (a render in the heavy slot), played here. */
+function JoinPreview({ project, version }: { project: string; version: string }) {
+ const [preview, setPreview] = useState<Preview>(null);
+ const [job, setJob] = useState<PreviewJob | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/join-preview?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { preview: Preview; running: PreviewJob | null };
+ setPreview(j.preview);
+ if (j.running) setJob(j.running);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load, version]);
+ const running = job?.state === "running";
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/join-preview?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as PreviewJob;
+ setJob(j);
+ if (j.state !== "running") await load();
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, load]);
+ const start = async () => {
+ setError(null);
+ const r = await fetch("/api/report/join-preview", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: PreviewJob; error?: string };
+ if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`);
+ else setJob(j.job);
+ };
+ return (
+ <div className="space-y-1.5" data-join-preview={preview ? (preview.stale ? "stale" : "fresh") : "none"}>
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" data-assist-preview="" disabled={running} onClick={() => void start()} className={buttonVariants({ size: "sm" })} title="the first joins of the cut, a few seconds either side, in the look as saved (a render, in the machine's heavy slot)">
+ {running ? "Rendering the preview…" : preview ? "Preview join again" : "Preview join"}
+ </button>
+ {running && (
+ <button type="button" onClick={() => void fetch(`/api/report/join-preview?cancel=${job!.id}`, { method: "POST" })} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Stop
+ </button>
+ )}
+ {preview?.stale && <span className="text-[11.5px] text-doubt-text">the look changed since this preview</span>}
+ {job && !running && job.state !== "done" && <span className="text-[11.5px] text-reject-text">preview {job.state}{job.error ? `: ${job.error}` : ""}</span>}
+ {error && (
+ <span role="alert" className="text-[11.5px] text-reject-text">
+ {error}
+ </span>
+ )}
+ </div>
+ {preview && (
+ <video
+ data-assist-preview-video=""
+ key={preview.mtimeMs}
+ src={`/api/report/join-preview?project=${encodeURIComponent(project)}&file=1&v=${preview.mtimeMs}`}
+ controls
+ loop
+ className="max-h-[240px] w-full max-w-[480px] rounded-[3px] border border-seam bg-ground"
+ />
+ )}
+ </div>
+ );
+}
+
+/** The project-level notes, each with Ask the assistant; an agent reply's proposals with Apply all. */
+function ProjectNotes({ project, a, scope, apply }: { project: string; a: ReturnType<typeof useAssist>; scope: Scope; apply: (ids: string[] | null, at?: string) => Promise<boolean> }) {
+ const notes = useSharedNotes({ project });
+ const reloadNotes = notes.reload;
+ useEffect(() => {
+ if (a.ended) void reloadNotes();
+ }, [a.ended, reloadNotes]);
+ const [text, setText] = useState("");
+ const whole = notes.notes.filter((n) => n.anchor.kind === "whole");
+ const blocked = a.view?.route?.why ?? (a.view && !a.view.route ? "the assistant needs the editor" : null);
+ const asking = a.job && !a.job.ended ? a.job.note : null;
+ const p = a.view?.proposals ?? null;
+ const add = async () => {
+ if (!text.trim()) return;
+ const n = await notes.write({ op: "add", text, anchor: { kind: "whole" } });
+ if (n) setText("");
+ };
+ return (
+ <section data-assist-notes={whole.length} className="space-y-1.5">
+ <h3 className="micro m-0">Notes on the project{whole.length ? ` — ${whole.filter((n) => n.status === "open").length} open` : ""}</h3>
+ {whole.map((n) => (
+ <NoteThread
+ key={n.id}
+ note={n}
+ write={notes.write}
+ busy={notes.busy}
+ actions={
+ n.status === "open" ? (
+ <button
+ type="button"
+ data-note-action="assist"
+ disabled={notes.busy || a.busy || !!blocked || !!asking}
+ title={blocked ?? "the assistant reads this note as a request and replies here; what it proposes waits for your Apply"}
+ onClick={() => void a.ask({ note: n.id, scope })}
+ className="ink-link disabled:opacity-40"
+ >
+ {asking === n.id ? "Asking…" : "Ask the assistant"}
+ </button>
+ ) : null
+ }
+ afterReply={(r) => {
+ const pr = r.proposal;
+ if (!pr || pr.kind !== "assist" || r.author !== "agent") return null;
+ const current = !!p && p.at === pr.at;
+ const waiting = current ? p!.ops.filter((o) => o.status === "proposed" && !o.now).length : 0;
+ return (
+ <div data-reply-proposal="assist" className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2">
+ <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span>
+ <span>
+ {pr.ops} edit{pr.ops === 1 ? "" : "s"}
+ </span>
+ {!current ? (
+ <span className="text-muted">a newer ask replaced these</span>
+ ) : waiting ? (
+ <button
+ type="button"
+ data-apply-proposal="assist"
+ disabled={a.busy}
+ onClick={() =>
+ void apply(null, pr.at).then((ok) => {
+ if (ok) void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" });
+ })
+ }
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ >
+ Apply all
+ </button>
+ ) : (
+ <span className="text-muted">nothing waiting</span>
+ )}
+ </div>
+ );
+ }}
+ />
+ ))}
+ <div className="flex flex-wrap items-start gap-2">
+ <textarea
+ data-assist-note-input=""
+ value={text}
+ rows={1}
+ onChange={(e) => setText(e.target.value)}
+ placeholder="a note on the whole project — for you or the assistant"
+ className="min-w-[14rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal"
+ />
+ <button type="button" data-assist-note-add="" disabled={notes.busy || !text.trim()} onClick={() => void add()} className={buttonVariants({ size: "sm" })}>
+ Add note
+ </button>
+ </div>
+ </section>
+ );
+}
+
+/**
+ * The Ask box. `scope`: what an ask may touch here (the Look panel: the look;
+ * the clip editor: the clips). `onApplied`: the page re-reads what Apply
+ * wrote. `version`: changes when the page wrote the manifest itself (the box
+ * re-reads its token). `subject`: the clip the page has selected -- a request
+ * that names no clip is sent as about it ("… (on clip r002)").
+ */
+export default function AssistBox({
+ project,
+ scope,
+ placeholder,
+ onApplied,
+ version = 0,
+ subject,
+ preview = false,
+ notes = false,
+}: {
+ project: string;
+ scope: Scope;
+ placeholder?: string;
+ onApplied?: () => void;
+ version?: number | string;
+ subject?: string;
+ preview?: boolean;
+ notes?: boolean;
+}) {
+ const a = useAssist(project);
+ const [text, setText] = useState("");
+ const { load } = a;
+ const first = useRef(true);
+ useEffect(() => {
+ if (first.current) {
+ first.current = false;
+ return;
+ }
+ void load();
+ }, [version, load]);
+ const v = a.view;
+ const blocked = !v ? "reading…" : (v.route?.why ?? (!v.route ? "no editor" : null));
+ const running = !!a.job && !a.job.ended;
+ const submit = async () => {
+ if (!text.trim()) return;
+ // A clip id is letters, digits, ".", "_" and "-": only the dot needs escaping.
+ const id = subject ? subject.replace(/\./g, "\\.") : "";
+ const named = !!subject && new RegExp(`(^|[^A-Za-z0-9_-])${id}([^A-Za-z0-9_-]|$)`).test(text);
+ const request = subject && !named ? `${text.trim()} (on clip ${subject})` : text;
+ if (await a.ask({ request, scope })) setText("");
+ };
+ const apply = async (ids: string[] | null, at = v?.proposals?.at) => {
+ const ok = await a.apply(ids, at);
+ if (ok) onApplied?.();
+ return ok;
+ };
+ return (
+ <div data-assist-box={scope} data-assist-route={v?.route?.route ?? "none"} className="space-y-2">
+ <div className="flex flex-wrap items-start gap-2">
+ <textarea
+ data-assist-input=""
+ value={text}
+ rows={2}
+ disabled={!!blocked || running}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void submit();
+ }}
+ placeholder={placeholder ?? "ask in words — “make the joins 0.15 s with less smear”"}
+ className="min-w-[16rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal disabled:opacity-60"
+ />
+ <button type="button" data-assist-ask="" disabled={!!blocked || running || a.busy || !text.trim()} onClick={() => void submit()} className={buttonVariants({ variant: text.trim() ? "go" : "outline", size: "md" })}>
+ {running ? "Asking…" : "Ask"}
+ </button>
+ {running && (
+ <button type="button" data-assist-cancel="" onClick={() => void a.cancel()} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Stop
+ </button>
+ )}
+ </div>
+ {v && (
+ <p className="m-0 text-[11.5px] text-muted" data-assist-status="">
+ {routeLine(v)}
+ </p>
+ )}
+ {a.job && (
+ <p className="m-0 text-[11.5px] text-text-2" data-assist-job={a.job.status}>
+ {jobLine(a.job)}
+ </p>
+ )}
+ {(a.error || v?.error) && (
+ <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-assist-error="">
+ {a.error ?? v?.error}
+ </p>
+ )}
+ {v?.proposals && <ProposalList p={v.proposals} busy={a.busy} onApply={(ids) => void apply(ids)} onDismiss={() => void a.dismiss(null)} />}
+ {preview && <JoinPreview project={project} version={`${version}:${a.ended}`} />}
+ {notes && <ProjectNotes project={project} a={a} scope={scope} apply={apply} />}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -4,6 +4,8 @@ import { useCallback, useEffect, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { Field, Input, Select } from "@/components/ui/field";
import { Panel } from "@/components/ui/panel";
+import { ROOM, ROOM_BOUNDS, SLIDE_BOUNDS, SLIDE_DEFAULTS } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import AssistBox from "./AssistBox";
// THE LOOK (release 36 lane C): the render keys a person sets for a cut with
// no deck -- the header, the timeline footer, the QR, the crossfade's length
@@ -12,6 +14,11 @@ import { Panel } from "@/components/ui/panel";
// /api/report/render (lib/report/manifest.mjs updateRender, the build's own
// checks). Nothing here calls a model. A deck cut keeps its own settings
// (the Media tab); a montage levels with render.montage.
+// Release 38 lane E: the blur slide's knobs (travel, smear, grain) and the
+// room's numbers (how far the tail may run, the silence that ends it) are
+// fields too, so every op the video assistant can propose is one here; the
+// assistant's Ask box (AssistBox: optional, its proposals applied only on
+// Apply) and Preview join sit under the fields.
type Look = {
headerHeight?: number;
@@ -22,6 +29,7 @@ type Look = {
loudness?: { target: number } | null;
captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null;
room?: { tail?: boolean; head?: boolean; minGap?: number; maxS?: number } | null;
+ slide?: { travel?: number; blur?: number; grain?: number } | null;
};
type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null };
@@ -41,6 +49,11 @@ type Draft = {
size: "m" | "l";
roomTail: boolean;
roomHead: boolean;
+ roomMaxS: string;
+ roomMinGap: string;
+ travel: string;
+ smear: string;
+ grain: string;
};
function draftOf(l: Look): Draft {
@@ -59,9 +72,20 @@ function draftOf(l: Look): Draft {
size: l.captions?.size ?? "m",
roomTail: l.room?.tail === true,
roomHead: l.room?.head === true,
+ roomMaxS: String(l.room?.maxS ?? ROOM.maxS),
+ roomMinGap: String(l.room?.minGap ?? ROOM.minGap),
+ travel: String(l.slide?.travel ?? SLIDE_DEFAULTS.travel),
+ smear: String(l.slide?.blur ?? SLIDE_DEFAULTS.blur),
+ grain: String(l.slide?.grain ?? SLIDE_DEFAULTS.grain),
};
}
+const SLIDE_KEYS = [
+ ["travel", "travel"],
+ ["blur", "smear"],
+ ["grain", "grain"],
+] as const;
+
/** The patch that takes the saved look to the draft: only what changed, `null` to remove a key. */
function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
const p: Record<string, unknown> = {};
@@ -84,10 +108,29 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
// Room at the clips' edges (release 36 lane E): its settings kept as written.
const was0 = was.room ?? null;
const on = d.roomTail || d.roomHead;
- const next = on ? { ...(was0 ?? {}), tail: d.roomTail, head: d.roomHead } : null;
- const same = (was0?.tail === true) === d.roomTail && (was0?.head === true) === d.roomHead;
+ // The numbers (release 38): written only when they differ from the build's defaults.
+ const nums: Record<string, number> = {};
+ const maxS = Number(d.roomMaxS);
+ const minGap = Number(d.roomMinGap);
+ if (maxS !== ROOM.maxS || was0?.maxS !== undefined) nums.maxS = maxS;
+ if (minGap !== ROOM.minGap || was0?.minGap !== undefined) nums.minGap = minGap;
+ const { maxS: _m, minGap: _g, ...edges } = was0 ?? {};
+ const next = on ? { ...edges, tail: d.roomTail, head: d.roomHead, ...nums } : null;
+ const same =
+ (was0?.tail === true) === d.roomTail &&
+ (was0?.head === true) === d.roomHead &&
+ (!on || ((was0?.maxS ?? ROOM.maxS) === maxS && (was0?.minGap ?? ROOM.minGap) === minGap));
if (!same) p.room = next;
}
+ // The blur slide's knobs (release 38): only the ones off their defaults are written.
+ {
+ const cur = { travel: Number(d.travel), blur: Number(d.smear), grain: Number(d.grain) };
+ const had = { ...SLIDE_DEFAULTS, ...(was.slide ?? {}) };
+ if (SLIDE_KEYS.some(([k]) => cur[k] !== had[k])) {
+ const next = Object.fromEntries(SLIDE_KEYS.filter(([k]) => cur[k] !== SLIDE_DEFAULTS[k]).map(([k]) => [k, cur[k]]));
+ p.slide = Object.keys(next).length ? next : null;
+ }
+ }
return p;
}
@@ -97,6 +140,8 @@ export default function LookPanel({ project }: { project: string }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
+ // Bumped when this panel writes the manifest, so the Ask box re-reads its token.
+ const [version, setVersion] = useState(0);
const load = useCallback(async () => {
const r = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" });
@@ -139,6 +184,7 @@ export default function LookPanel({ project }: { project: string }) {
}
setView({ ...view, look: j.look ?? {}, token: j.token ?? null, errors: [] });
setDraft(draftOf(j.look ?? {}));
+ setVersion((n) => n + 1);
setStatus("Saved — the next render uses it");
} finally {
setBusy(false);
@@ -197,6 +243,40 @@ export default function LookPanel({ project }: { project: string }) {
{check("roomTail", "Tail: sound to the first silence, then muted", "data-look-room-tail", Number(draft.transition) === 0)}
{check("roomHead", "Head: muted lead-in", "data-look-room-head", Number(draft.transition) === 0)}
{Number(draft.transition) === 0 && <span className="text-[12px] text-muted">no join to make room for</span>}
+ {(draft.roomTail || draft.roomHead) && Number(draft.transition) !== 0 && (
+ <span className="flex flex-wrap items-end gap-3">
+ <Field label="Tail up to, s">
+ <Input data-look-room-max="" type="number" min={ROOM_BOUNDS.maxS[0]} max={ROOM_BOUNDS.maxS[1]} step={0.1} value={draft.roomMaxS} disabled={busy || !draft.roomTail} onChange={(e) => set({ roomMaxS: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ <Field label="Silence gap, s">
+ <Input data-look-room-gap="" type="number" min={ROOM_BOUNDS.minGap[0]} max={ROOM_BOUNDS.minGap[1]} step={0.05} value={draft.roomMinGap} disabled={busy || !draft.roomTail} onChange={(e) => set({ roomMinGap: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ </span>
+ )}
+ </div>
+ )}
+ {draft.style === "blurslide" && Number(draft.transition) !== 0 && (
+ <div className="mt-3 flex flex-wrap items-end gap-4" data-look-slide="">
+ <span className="text-[12.5px] text-text-2">Blur slide</span>
+ {SLIDE_KEYS.map(([k, word]) => {
+ const field = k === "blur" ? "smear" : k;
+ const [lo, hi] = SLIDE_BOUNDS[k];
+ return (
+ <Field key={k} label={word[0]!.toUpperCase() + word.slice(1)}>
+ <Input
+ {...{ [`data-look-slide-${word}`]: "" }}
+ type="number"
+ min={lo}
+ max={hi}
+ step={k === "grain" ? 1 : k === "travel" ? 0.01 : 0.1}
+ value={draft[field]}
+ disabled={busy}
+ onChange={(e) => set({ [field]: e.target.value } as Partial<Draft>)}
+ className="w-[5.5em]"
+ />
+ </Field>
+ );
+ })}
</div>
)}
<div className="mt-3 space-y-2">
@@ -247,6 +327,11 @@ export default function LookPanel({ project }: { project: string }) {
) : null}
</span>
</div>
+ {/* --- the assistant (release 38): optional; its proposals wait for Apply */}
+ <div className="mt-4 border-t border-seam pt-3" data-look-assist="">
+ <h3 className="micro m-0 mb-2">Ask the assistant</h3>
+ <AssistBox project={project} scope="all" version={version} onApplied={() => void load().catch((e) => setError(e instanceof Error ? e.message : String(e)))} preview notes />
+ </div>
</Panel>
);
}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -13,6 +13,7 @@ import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Spe
import { cn } from "@/lib/utils";
import { ROOM, roomShade } from "umtool-report-to-video/room";
import { startTakeJob } from "../NewTakePanel";
+import AssistBox from "../report/AssistBox";
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional).
import type { ReplyProposal } from "@/lib/annotations/types";
import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest";
@@ -313,12 +314,15 @@ export default function ClipEditor({
// An agent reply's proposal, applied ON THE OPERATOR'S CLICK through the
// writer every other edit here uses (release 36 lane D).
const canApply = (p: ReplyProposal): string | null => {
+ // The video assistant's proposals (release 38) are applied in its Ask box, not here.
+ if (p.kind === "assist") return "apply it in the assistant's box";
const at = clips.findIndex((c) => c.id === p.clip);
if (at < 0) return `${p.clip} is no longer in the cut`;
if (p.kind === "merge" && clips[at + 1]?.id !== p.with) return `${p.with} is no longer the next clip`;
return null;
};
const applyProposal = async (p: ReplyProposal): Promise<boolean> => {
+ if (p.kind === "assist") return false;
await flush();
const j =
p.kind === "trim"
@@ -628,6 +632,18 @@ export default function ClipEditor({
{/* ---- the list, the proposals, the speakers, the take --------------- */}
<aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-editor-side="">
<SuggestPanel s={assistant} sorted={byRank} onSort={setByRank} />
+ {/* Release 38: the video assistant — a request in words, its proposals applied only on Apply. */}
+ <section data-editor-assist="">
+ <h2 className="micro m-0 mb-1">Ask the assistant</h2>
+ <AssistBox
+ project={project}
+ scope="all"
+ subject={clip.id}
+ version={view.token ?? ""}
+ onApplied={() => void reload().catch((e) => setError(e instanceof Error ? e.message : String(e)))}
+ placeholder={`ask in words — “cut the first 2 s”, “no room on this clip”, “quicker joins”`}
+ />
+ </section>
<section>
<h2 className="micro mb-1">
{plural(clips.length, "clip")} · {clips.filter((c) => c.ruling === "keep").length} kept · {clips.filter((c) => c.ruling === "cut").length} cut
diff --git a/umtool/components/projects/review/ClipSuggest.tsx b/umtool/components/projects/review/ClipSuggest.tsx
@@ -214,6 +214,7 @@ export function SuggestPanel({ s, sorted, onSort }: { s: ClipSuggest; sorted: bo
/** What an agent reply proposes, in words. */
export function proposalWords(p: ReplyProposal): string {
+ if (p.kind === "assist") return `${p.ops} edit${p.ops === 1 ? "" : "s"} of the look or the cut (the Ask box)`;
if (p.kind === "trim") return `trim ${p.clip} to ${edgeClock(p.from)}–${edgeClock(p.to)} (${(p.to - p.from).toFixed(1)} s)`;
if (p.kind === "merge") return `merge ${p.clip} with ${p.with}`;
return `cut ${p.clip}`;
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1268,9 +1268,12 @@ head: true}` (lane B's seed, with lane E's join and room).
**The Look panel** (the Build tab, `/api/report/render`) sets them by hand:
**Header**, **Timeline footer**, **QR code**, the length **Between clips** (0 is
a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve,
-blur slide), **Room at the clips' edges** (Tail, Head — below),
-**Loudness** (as recorded, −16 LUFS, or a custom target) and **Speaker
-captions** with each role's name and the size. **Save the look** writes only
+blur slide), **Room at the clips' edges** (Tail, Head, and with the tail on
+**Tail up to, s** — `maxS` — and **Silence gap, s** — `minGap`; below), the
+**Blur slide**'s **Travel**, **Smear** (`slide.blur`) and **Grain** when the
+join is a blur slide, **Loudness** (as recorded, −16 LUFS, or a custom target)
+and **Speaker captions** with each role's name and the size — so every edit
+the video assistant can propose is also a field here (release 38). **Save the look** writes only
what changed (`lib/report/manifest.mjs` `updateRender`: token-guarded, the
build's own checks, atomic; `null` puts a key back to the build's default). It
never touches `render.chrome` (the deck's own settings, the Media tab); a deck
@@ -1356,6 +1359,76 @@ own time. `render.slide` = `{travel: 0.08, blur: 0.5, grain: 2}` by default
length is `render.transition` (the seed's 0.22 s). A dip, a THEN/NOW wipe and a
whip keep their own look. With room at both edges the slide runs over muted picture.
+## The video assistant: Ask, Apply, Preview join (release 38)
+
+"Make the joins 0.15 s with less smear" — a small change to a cut in words,
+on the local model when Claude Code is not at hand. Optional in every part:
+with generation routed elsewhere, or no editor, the box says so, and the Look
+panel above it is the same panel.
+
+**The Ask box** sits under the Look panel's fields (the Build tab) and in the
+clip editor's side column (where a request that names no clip is sent as about
+the selected one: "… (on clip r002)"). An ask is one editor job, `report-draft`
+task **`video-assist`** (`common/controller/videoAssist.ts`), routed by
+`settings.generation.routes["video-assist"]` — **local in every preset but
+`api`**: on `draft:local`, through the GPU arbiter, so it waits while a
+transcription runs (the box says so), and ollama is unloaded after; on the API
+the narration cap and the daily cap hold it and its usage is a ledger row;
+`code` = a Claude Code session answers the request (`/gen`, the MCP's
+`generate`). The task asks once, schema-bound — `{ops: [{op, id, key, value}],
+reply}` — over the project's compact view: the look now, the blur slide's
+knobs, the room, the clips with their cuts and the window each may move in,
+and the declared params of the compositions the cut draws, trimmed to the
+prompt cap (the clips the request names first).
+
+**The ops** (`common/lib/report/videoAssistOps.mjs`), each checked against the
+manifest as it is, with its diff line:
+
+| Op | What | Checked by |
+|---|---|---|
+| `look` | a LOOK_KEYS render key (`transition`, `transitionStyle`, `qr`, `loudness`, `captions`, `headerHeight`, …) | `applyLookPatch` — the same function `updateRender` writes with (common `lib/report/look.mjs`, whose validators the build and the lint call too) |
+| `slide` | `travel` / `blur` (the smear) / `grain` | within `SLIDE_BOUNDS` (0–0.5, 0–2, 0–20) |
+| `room` | `tail` / `head` (on or off), `maxS` (how far the tail runs, 0–10 s), `minGap` (0.1–2 s); a number for the tail turns it on up to that ("keep 2 s after the last word") | `ROOM_BOUNDS`, `validateRoom` |
+| `clip_edges` | a clip's cut, `start` / `end` in seconds on its recording | inside the clip's source window (its extent; a clip with no cut, its edges widened by `fetchPad`), at least 0.5 s, and an edge moves at most 3 s unless the request names more seconds |
+| `clip_room` | one clip's room: `tail` / `head`, `off` (none), `reset` (the cut's again) | `validateRoom` |
+| `fx` | a composition's DECLARED param (`deck`, `stats`, `fx.<effect>`): e.g. the deck's `motion.in`, the glitch's `seconds` | its declaration's bounds (`common/lib/report/fxParams.mjs`; `fx-params.test.mjs` holds each to `validateChrome`); never free HTML |
+
+An op the checks refuse is not proposed: it is listed with its reason
+("render.transition must be a number of seconds from 0 (a hard cut) to 3").
+The job writes **`<project>/assist-proposals.json`** — the request, the model,
+the kept ops with their diff lines, the refused with their reasons — and
+**nothing else**: no manifest, no clip, no note.
+
+**Apply** (one op, or **Apply all**) re-checks each op against the manifest as
+it is then and writes it through the manifest's own writer — `updateRender` for
+the look, the slide and the room; the clip editor's `trim` and `room` for a
+clip (an assistant's clip becomes the operator's, as any trim makes it);
+`updateChrome` for a composition's param — token-guarded, the token carried
+from one write to the next (`/api/report/video-assist`,
+`lib/report/videoAssist.mjs`). A token that went stale stops it (reload); an op
+the manifest no longer allows fails with the reason (the list says so before
+the click: "now: …"). **Dismiss** marks the waiting ops and writes nothing
+else. An applied op is marked applied.
+
+**A note on the whole project** (the box's **Notes on the project**): **Ask the
+assistant** sends the note's text as the request; the proposals are posted back
+to it as the agent's reply, carrying an **Apply all** while they are the
+latest.
+
+**Preview join** renders the first four joins of the cut in the look as saved —
+each clip cut to the last 3 s of its cut (the last clip, its first 3 s), every
+other entry left out, the windows untouched so the fetched media is reused —
+to `out/join-preview.mp4` (and `out/join-preview.json`, what it was made
+from), and plays it under the box; it says when the look has changed since. A
+job on umtool's runner (`/api/report/join-preview`), `build-video.mjs
+<manifest> --join-preview [--join-from <clip>]` inside the heavy slot; the
+cut's own `out/` files (its segments, chapters, YouTube text) are not touched.
+Not for a deck cut, a montage or hard cuts.
+
+From a terminal: `pnpm ops report-draft --json '{"task": "video-assist", "project":
+"<dir>", "request": "quicker joins", "dryRun": true}'` (the prompt and its
+estimate), then without `dryRun`.
+
## Operator notes, timed notes and the generated-manifest guard
Notes on a project live in `<project>/notes.json` (shape and CLI:
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -25,6 +25,8 @@ import { fileURLToPath } from "node:url";
import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs";
+import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
+import { proposalsDocOf, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
const PORT = portFor("EDITOR_STUB_PORT");
const CHANNELS = process.env.CHANNELS_DIR ?? "";
@@ -134,11 +136,12 @@ function writeWindow(dir, name, seconds) {
// startCannedDraft) — every isStepTask step answered.
const ARTICLES = process.env.ARTICLES_DIR ?? "";
const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? "";
+// Release 38 lane E: video-assist is local in every preset but api, as the editor's.
const PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code" },
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", "video-assist": "local" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", "video-assist": "local" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", "video-assist": "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", "video-assist": "local" },
};
const generation = {
preset: "balanced",
@@ -846,6 +849,53 @@ function finishRefresh(job, parent, p) {
job.log.push(`refresh: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task: "refresh", status: "done", summary, refresh: patch.refresh })}`);
}
+// A `video-assist` report-draft (release 38 lane E): a canned "model" reads
+// the request's words (0.15 → the join, "smear" → the slide's blur, "QR" →
+// off, "louder" → -14 LUFS, "5 seconds" → a join the checks refuse) and the
+// ops are checked and written through common's own checker and writer, as
+// the real task does; a note's Ask (body.note) reads its text from
+// notes.json and posts no reply (the stub cannot reach umtool).
+const ASSIST_CANNED = [
+ [/0\.15/, { op: "look", id: "", key: "transition", value: 0.15 }],
+ [/smear/i, { op: "slide", id: "", key: "blur", value: 0.3 }],
+ [/\bqr\b/i, { op: "look", id: "", key: "qr", value: false }],
+ [/louder/i, { op: "look", id: "", key: "loudness", value: -14 }],
+ [/5 seconds/i, { op: "look", id: "", key: "transition", value: 5 }],
+];
+function startVideoAssist(body) {
+ if (typeof body.project !== "string" || !body.project.startsWith("/")) throw new Error('"project" is the video project\'s absolute directory');
+ let request = typeof body.request === "string" ? body.request : "";
+ if (typeof body.note === "string") {
+ const notes = JSON.parse(readFileSync(path.join(body.project, "notes.json"), "utf8"));
+ const n = (notes.notes ?? []).find((x) => x.id === body.note);
+ if (!n) throw new Error(`no note ${body.note}`);
+ request = n.text;
+ }
+ if (!request.trim()) throw new Error("the assistant needs a request");
+ const id = `stub-assist-${nextJob++}`;
+ const job = { id, article: null, n: 0, task: "video-assist", status: "queued", at: Date.now(), log: [`report-draft video-assist (stub)`], timers: [] };
+ draftJobs.set(id, job);
+ job.timers.push(setTimeout(() => { job.status = "running"; job.log.push("asking the stub model"); }, 300));
+ job.timers.push(
+ setTimeout(async () => {
+ try {
+ const manifest = JSON.parse(readFileSync(path.join(body.project, "video.manifest.json"), "utf8"));
+ const ops = ASSIST_CANNED.filter(([re]) => re.test(request)).map(([, op]) => op);
+ const checked = checkAssistOps(manifest, ops, { request, scope: body.scope ?? "all" });
+ const doc = proposalsDocOf({ at: new Date().toISOString(), model: generation.models.local, request, scope: body.scope ?? "all", note: body.note ?? null, reply: ops.length ? "Done as asked." : "Nothing I can change for that.", checked });
+ await writeAssistProposals(body.project, doc);
+ const summary = `${doc.ops.length} edit${doc.ops.length === 1 ? "" : "s"} proposed${doc.ops.length ? ` (${doc.diff.join("; ")})` : ""}${doc.refused.length ? `, ${doc.refused.length} refused` : ""} on ${generation.models.local}`;
+ job.log.push(summary, `@@report-draft ${JSON.stringify({ article: "", iteration: 0, task: "video-assist", project: body.project, status: "done", summary, usd: 0, assist: { at: doc.at, proposed: doc.ops.length, refused: doc.refused.length, diff: doc.diff } })}`);
+ job.status = "done";
+ } catch (err) {
+ job.log.push(String(err.message));
+ job.status = "failed";
+ }
+ }, 1500),
+ );
+ return { jobId: id, iteration: 0 };
+}
+
function cancelDraft(id) {
const job = draftJobs.get(id);
if (!job || !["queued", "running"].includes(job.status)) return false;
@@ -853,7 +903,7 @@ function cancelDraft(id) {
job.status = "cancelled";
job.log.push("cancelled");
job.child?.kill();
- if (job.task === "clips-suggest") return true;
+ if (job.task === "clips-suggest" || job.task === "video-assist") return true;
const it = readIt(job.article, job.n);
if (job.task === "narrate" || MEDIA_RUN.has(job.task) || MEDIA_TASKS.has(job.task)) {
patchIt(job.article, job.n, { steps: it.steps.map((s) => (s.jobId === id ? { ...s, status: "cancelled" } : s)) });
@@ -923,6 +973,14 @@ function generationRoute(req, res, url, auth) {
return json(res, 400, { ok: false, error: String(err.message) });
}
}
+ // Release 38 lane E: the video assistant (a project, not an article).
+ if (body?.task === "video-assist") {
+ try {
+ return json(res, 202, { ok: true, ...startVideoAssist(body) });
+ } catch (err) {
+ return json(res, 400, { ok: false, error: String(err.message) });
+ }
+ }
if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" });
if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" });
try {
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -37,6 +37,7 @@ import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs";
+import { makeVideoAssistFixture } from "./video-assist-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1819,6 +1820,8 @@ makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out"
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// Release 38 lane E: the video assistant's Ask box, Apply and Dismiss on the Look panel (video-assist.spec.ts).
+makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
diff --git a/umtool/e2e/fixtures/video-assist-fixture.mjs b/umtool/e2e/fixtures/video-assist-fixture.mjs
@@ -0,0 +1,18 @@
+// What video-assist.spec.ts reads and writes (release 38 lane E): the clip
+// editor's three clips (clip-editor-fixture.mjs, copied under its own name so
+// no two specs edit one project), with a quick blur slide as its look — the
+// cut the Ask box proposes edits of. The editor stub's canned "model"
+// (editor-stub.mjs startVideoAssist) answers from the request's words.
+// Synthetic, like every fixture.
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { makeClipEditorFixture } from "./clip-editor-fixture.mjs";
+
+/** @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o */
+export function makeVideoAssistFixture(o) {
+ makeClipEditorFixture({ ...o, name: "video-assist-fixture", title: "The Video Assist Fixture" });
+ const file = path.join(o.reports, "video-assist-fixture", "video.manifest.json");
+ const doc = JSON.parse(readFileSync(file, "utf8"));
+ doc.render = { ...doc.render, transition: 0.22, transitionStyle: "blurslide", qr: false, headerHeight: 0 };
+ writeFileSync(file, JSON.stringify(doc, null, 2) + "\n");
+}
diff --git a/umtool/e2e/video-assist.spec.ts b/umtool/e2e/video-assist.spec.ts
@@ -0,0 +1,118 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The video assistant (release 38 lane E) on the Build tab's Look panel. An
+// Ask ("make the joins 0.15 s with less smear") starts the editor's
+// `video-assist` job (the editor stub's canned model answers through common's
+// own checker and writer); its proposals come back as a diff list; nothing in
+// the manifest moves until Apply, which writes through updateRender; the
+// panel's fields read the new look. A second ask ("louder, and 5 seconds
+// between clips") shows its refusal with the reason, and Dismiss changes
+// nothing but the marks. A note on the whole project, asked, is the request
+// too; the agent's reply carries an Apply. Fixture:
+// e2e/fixtures/video-assist-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/video-assist-fixture";
+const DIR = path.join(FIXTURE, "reports", "video-assist-fixture");
+const TOKEN = "umtool-e2e-token";
+
+const json = (name: string) => {
+ try {
+ return JSON.parse(readFileSync(path.join(DIR, name), "utf8"));
+ } catch {
+ return null;
+ }
+};
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const render = () => json("video.manifest.json")?.render ?? {};
+const stubRequests = (): { route: string; task?: string; project?: string; request?: string; note?: string }[] => {
+ try {
+ return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8"));
+ } catch {
+ return [];
+ }
+};
+
+test("Ask on the Look panel: the diff, Apply through the look's writer, a refusal shown, Dismiss writes nothing; a project note asked", async ({ page, request }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await page.goto(urls.section(PROJECT, "build"));
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "");
+ const box = page.locator('[data-assist-box="all"]');
+ await expect(box).toHaveAttribute("data-assist-route", "local");
+ await expect(box.locator("[data-assist-status]")).toContainText("On the local model (qwen3:8b), through the GPU: it waits while a transcription runs.");
+ // The manual path is right there: the slide's knobs are fields.
+ await expect(page.locator("[data-look-slide-smear]")).toHaveValue("0.5");
+
+ // ---- an ask: the proposals, nothing applied ---------------------------------
+ const before = manifestText();
+ await box.locator("[data-assist-input]").fill("make the joins 0.15 s with less smear");
+ await box.locator("[data-assist-ask]").click();
+ await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 });
+ expect(stubRequests().filter((r) => r.route === "report-draft" && r.task === "video-assist").map((r) => [r.project, r.request])).toEqual([[DIR, "make the joins 0.15 s with less smear"]]);
+ const list = box.locator("[data-assist-proposals]");
+ await expect(list).toHaveAttribute("data-assist-proposals", "2");
+ await expect(list.locator('[data-assist-op="a1"]')).toContainText("join 0.22 s → 0.15 s");
+ await expect(list.locator('[data-assist-op="a2"]')).toContainText("smear 0.5 → 0.3");
+ await expect(list.locator("[data-assist-reply]")).toHaveText("Done as asked.");
+ expect(manifestText()).toBe(before);
+
+ // ---- Apply one, then the rest: through updateRender; the panel reads it back
+ await list.locator('[data-assist-apply="a1"]').click();
+ await expect(list.locator('[data-assist-op="a1"]')).toHaveAttribute("data-assist-status", "applied");
+ expect(render().transition).toBe(0.15);
+ expect(render().slide).toBeUndefined();
+ await expect(page.locator("[data-look-transition]")).toHaveValue("0.15");
+ await list.locator("[data-assist-apply-all]").click();
+ await expect(list.locator('[data-assist-op="a2"]')).toHaveAttribute("data-assist-status", "applied");
+ expect(render().slide).toEqual({ blur: 0.3 });
+ await expect(page.locator("[data-look-slide-smear]")).toHaveValue("0.3");
+ expect(json("assist-proposals.json")?.ops?.map((o: { status: string }) => o.status)).toEqual(["applied", "applied"]);
+ await expect(list.locator("[data-assist-apply-all]")).toHaveCount(0);
+
+ // ---- a second ask: one proposed, one refused with the reason; Dismiss ----
+ await box.locator("[data-assist-input]").fill("louder, and 5 seconds between clips");
+ await box.locator("[data-assist-ask]").click();
+ await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 });
+ await expect(list).toHaveAttribute("data-assist-proposals", "1");
+ await expect(list.locator('[data-assist-op="a1"]')).toContainText("loudness as recorded → -14 LUFS");
+ await expect(list.locator("[data-assist-refused]")).toHaveText("not proposed: render.transition must be a number of seconds from 0 (a hard cut) to 3");
+ const applied = manifestText();
+ await list.locator("[data-assist-dismiss]").click();
+ await expect(list.locator('[data-assist-op="a1"]')).toHaveAttribute("data-assist-status", "dismissed");
+ expect(manifestText()).toBe(applied);
+ expect(render().loudness).toBeUndefined();
+
+ // ---- a note on the whole project, asked: its text is the request ----------
+ await box.locator("[data-assist-note-input]").fill("no QR, please");
+ await box.locator("[data-assist-note-add]").click();
+ const thread = box.locator("[data-assist-notes] [data-note-id]");
+ await expect(thread).toHaveCount(1);
+ const noteId = (await thread.getAttribute("data-note-id"))!;
+ await thread.locator('[data-note-action="assist"]').click();
+ await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 });
+ expect(stubRequests().filter((r) => r.task === "video-assist" && r.note).map((r) => [r.project, r.note])).toEqual([[DIR, noteId]]);
+ // The QR is already off in this cut: the checks say so (nothing proposed).
+ await expect(list).toHaveAttribute("data-assist-proposals", "0");
+ await expect(list.locator("[data-assist-refused]")).toHaveText("not proposed: QR code is already that");
+
+ // The agent's reply with an assist proposal (posted here: the stub cannot reach umtool) shows its Apply only while current.
+ const at = json("assist-proposals.json").at as string;
+ const read = await (await request.get(`/api/notes?project=${encodeURIComponent(PROJECT)}`)).json();
+ const replied = await request.post(`/api/notes?project=${encodeURIComponent(PROJECT)}`, {
+ headers: { authorization: `Bearer ${TOKEN}` },
+ data: { token: read.token, op: { op: "reply", id: noteId, text: "No edit proposed.", proposal: { kind: "assist", at, ops: 1 } } },
+ });
+ expect(replied.ok()).toBe(true);
+ await page.reload();
+ const reply = page.locator('[data-assist-notes] [data-reply-proposal="assist"]');
+ await expect(reply).toContainText("1 edit");
+ await expect(reply).toContainText("nothing waiting");
+});
diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs
@@ -117,7 +117,7 @@ export function validateAnchor(raw) {
}
}
-export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"];
+export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut", "assist"];
/**
* An agent reply's proposal (release 36 lane D, "Ask the assistant"): ONE
@@ -126,6 +126,9 @@ export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"];
* { kind: "merge", clip, with, basis? } the clip and the next one, joined
* { kind: "cut", clip, basis? } the clip ruled out
* `basis` is the clip's cut when the agent read it ({ cutStart, cutEnd }).
+ * Release 38 lane E, the video assistant on a note on the whole project:
+ * { kind: "assist", at, ops } the proposals in assist-proposals.json
+ * made at `at` (their Apply is the Ask box's)
* Never applied by whoever writes it. `{ proposal }` or `{ error }`.
* @param {unknown} raw
*/
@@ -133,8 +136,13 @@ export function validateReplyProposal(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "proposal is not an object" };
const p = /** @type {Record<string, unknown>} */ (raw);
if (!REPLY_PROPOSAL_KINDS.includes(/** @type {string} */ (p.kind))) return { error: `proposal kind must be one of ${REPLY_PROPOSAL_KINDS.join(", ")}` };
- if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" };
const fin = (v) => typeof v === "number" && Number.isFinite(v);
+ if (p.kind === "assist") {
+ if (!short(p.at, 40) || !p.at || Number.isNaN(Date.parse(/** @type {string} */ (p.at)))) return { error: "an assist proposal names its proposals' time (at)" };
+ if (!Number.isInteger(p.ops) || /** @type {number} */ (p.ops) < 1 || /** @type {number} */ (p.ops) > 40) return { error: "an assist proposal counts its ops (1 to 40)" };
+ return { proposal: { kind: "assist", at: p.at, ops: p.ops } };
+ }
+ if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" };
const out = { kind: p.kind, clip: p.clip };
if (p.kind === "trim") {
if (!fin(p.from) || !fin(p.to) || p.from < 0 || p.to - p.from < 0.5) return { error: "a trim proposal needs from ≥ 0 and to at least half a second after it" };
diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts
@@ -48,7 +48,9 @@ export type AnchorKind = Anchor["kind"];
export type ReplyProposal =
| { kind: "trim"; clip: string; from: number; to: number; basis?: { cutStart: number; cutEnd: number } }
| { kind: "merge"; clip: string; with: string; basis?: { cutStart: number; cutEnd: number } }
- | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } };
+ | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } }
+ /** Release 38 lane E: the video assistant's proposals (assist-proposals.json, made at `at`), applied in the Ask box. */
+ | { kind: "assist"; at: string; ops: number };
export type NoteReply = { author: NoteAuthor; text: string; at: string; proposal?: ReplyProposal };
diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs
@@ -29,6 +29,7 @@ const TASK_WORD = {
youtube: "YouTube drafts",
social: "social post drafts",
"clips-suggest": "clip labels",
+ "video-assist": "the video assistant",
};
/**
diff --git a/umtool/lib/report/joinPreview.mjs b/umtool/lib/report/joinPreview.mjs
@@ -0,0 +1,58 @@
+// THE JOIN PREVIEW, umtool's half (release 38 lane E): `<project>/out/join-
+// preview.mp4`, the first few joins of the cut in its current look
+// (report-to-video/join-preview.mjs; build-video.mjs `--join-preview`, which
+// runs in the machine's heavy slot), as ONE job on the app's runner
+// (lib/jobs.ts: one at a time, a log, Cancel) -- the Look panel's and the Ask
+// box's Preview join. Its record (`out/join-preview.json`) says what it was
+// made from, so the page can say when the look has moved since.
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD } from "umtool-report-to-video/join-preview";
+import { PIPELINE_DIR } from "./driver.mjs";
+
+/** A preview is a few seconds of four clips: minutes at most. */
+export const JOIN_PREVIEW_TIMEOUT_MS = 15 * 60_000;
+const CLIP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/;
+
+const outOf = (dir) => path.join(/* turbopackIgnore: true */ dir, "out");
+export const joinPreviewFile = (dir) => path.join(/* turbopackIgnore: true */ outOf(dir), JOIN_PREVIEW_FILE);
+
+/**
+ * The job's one step: build-video `--join-preview` (from `from`, else the
+ * first clip), NDJSON progress. No path or argv from a client.
+ * @param {{ dir: string }} project
+ * @param {string | null} [from]
+ */
+export function joinPreviewSteps(project, from = null) {
+ if (from !== null && !CLIP_ID.test(from)) throw new Error(`not a clip id: ${from}`);
+ return [
+ {
+ cwd: PIPELINE_DIR,
+ env: {},
+ label: `preview the joins${from ? ` from ${from}` : ""}`,
+ argv: [
+ "node", path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"),
+ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
+ "--out", outOf(project.dir),
+ "--join-preview", ...(from ? ["--join-from", from] : []), "--progress", "ndjson",
+ ],
+ ndjson: true,
+ timeoutMs: JOIN_PREVIEW_TIMEOUT_MS,
+ },
+ ];
+}
+
+/**
+ * The preview on disk, or null: `{ size, mtimeMs, record, stale }` --
+ * `stale` when the look (lookOf the render) is not what it was made with.
+ * @param {string} dir
+ * @param {any} [manifest]
+ */
+export async function readJoinPreview(dir, manifest = null) {
+ const st = await stat(joinPreviewFile(dir)).catch(() => null);
+ if (!st?.isFile()) return null;
+ const record = await readFile(path.join(/* turbopackIgnore: true */ outOf(dir), JOIN_PREVIEW_RECORD), "utf8").then(JSON.parse, () => null);
+ const stale = !!manifest && !!record && JSON.stringify(record.look ?? {}) !== JSON.stringify(lookOf(manifest.render ?? {}));
+ return { size: st.size, mtimeMs: Math.round(st.mtimeMs), record, stale };
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -33,9 +33,9 @@ import { isCalendarDate } from "umtool-report-to-video/attribution";
import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck";
import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
-import { validateLook, verticalErrors } from "umtool-report-to-video/look";
+import { verticalErrors } from "umtool-report-to-video/look";
+import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { validateRoom } from "umtool-report-to-video/room";
-import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition";
import { applySectionEnter } from "./sections.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { validateNarration } from "umtool-report-to-video/narration";
@@ -936,17 +936,10 @@ export class ChromeRefused extends Error {
// checks against the render as it will be, then written atomically.
// ---------------------------------------------------------------------------
-/** The render keys the Look panel writes, in its order. */
-export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide"]);
-
-/** The look keys of a render block as written (absent keys left out). */
-export function lookOf(render) {
- const r = isObj(render) ? render : {};
- /** @type {Record<string, unknown>} */
- const out = {};
- for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k];
- return out;
-}
+// LOOK_KEYS, lookOf and the patch's rules are the look's (common
+// lib/report/look.mjs, release 38): the video assistant checks a proposed op
+// with the same function this writer writes with.
+export { LOOK_KEYS, lookOf };
/** The build's sentences for a refused look, thrown whole so a route can return each one. */
export class RenderRefused extends Error {
@@ -958,12 +951,12 @@ export class RenderRefused extends Error {
}
}
-const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
-
/**
* Patch the look. Each key of `patch` is one of LOOK_KEYS; `null` removes the
* key (the build's default again). `qr: true` turns the code back on (removes
* a `false`; an object of settings is kept), `qr: false` turns it off.
+ * The rules are applyLookPatch's (common lib/report/look.mjs), against the
+ * manifest as it is inside the lock.
*
* @param {string} dir
* @param {Record<string, unknown>} patch
@@ -972,49 +965,16 @@ const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
*/
export async function updateRender(dir, patch, { token = null } = {}) {
if (!isObj(patch)) throw new RenderRefused(["the patch must be an object of render keys"]);
- const errors = [];
- for (const k of Object.keys(patch)) {
- if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here");
- else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`);
+ {
+ // The keys alone, before the lock: a patch naming no look key is refused without reading the file.
+ const keys = applyLookPatch({}, Object.fromEntries(Object.keys(patch).map((k) => [k, null])));
+ if (keys.errors.length) throw new RenderRefused(keys.errors);
}
- if (errors.length) throw new RenderRefused(errors);
return withManifestLock(async () => {
const current = await manifestToken(dir);
if (token !== null && current !== token) throw new StaleToken(token, current);
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
- const render = { ...(isObj(manifest.render) ? manifest.render : {}) };
- for (const [k, v] of Object.entries(patch)) {
- if (v === null) {
- delete render[k];
- continue;
- }
- switch (k) {
- case "headerHeight":
- case "footerHeight":
- if (!intIn(v, 0, 240)) errors.push(`render.${k} must be a whole number of pixels from 0 to 240`);
- else render[k] = v;
- break;
- case "qr":
- if (v === false) render.qr = false;
- else if (v === true) {
- if (render.qr === false) delete render.qr;
- } else errors.push("render.qr must be true (on) or false (off)");
- break;
- case "transition":
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 3) errors.push("render.transition must be a number of seconds from 0 (a hard cut) to 3");
- else render.transition = round2(v);
- break;
- case "transitionStyle":
- if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
- else render.transitionStyle = v;
- break;
- default:
- // loudness, captions, room: stored as given; the build's validators below say what is wrong.
- render[k] = v;
- }
- }
- const next = { ...manifest, render };
- errors.push(...validateTransitionStyle(next), ...validateLook(next));
+ const { render, errors } = applyLookPatch(manifest, patch);
if (errors.length) throw new RenderRefused(errors);
manifest.render = render;
const nextToken = await writeManifestAtomic(dir, manifest);
diff --git a/umtool/lib/report/videoAssist.mjs b/umtool/lib/report/videoAssist.mjs
@@ -0,0 +1,238 @@
+// THE VIDEO ASSISTANT, umtool's half (release 38 lane E): the Ask box's
+// request to the editor, the job the page follows, the proposals file read
+// for the page, and APPLY -- the one place a proposed op becomes a write.
+//
+// assist-proposals.json written by the EDITOR's `report-draft` task
+// `video-assist` (common lib/report/videoAssistProposals.mjs);
+// its ops' status marked here (applied / dismissed / failed)
+// .video-assist-job.json the editor job the page follows, so a reload shows it;
+// umtool's own file, cleared when the job is seen to end
+//
+// Apply re-checks each op against the manifest AS IT IS (common
+// videoAssistOps.mjs checkAssistOps -- the look's rules, the clip's window,
+// the declared params), then writes through the manifest's own writers:
+// updateRender (the look, the slide, the room), the clip editor's
+// runClipEditorOp (trim, room), updateChrome (a composition's param) -- each
+// token-guarded, the token carried from one write to the next. A stale token
+// stops it (409: reload); a refusal fails that op only, with its reason.
+// Never a raw manifest write, never free HTML. Dismiss marks ops and writes
+// nothing else.
+//
+// Everything is optional: with no editor, no model, or generation routed to
+// Claude Code, the Look panel and the clip editor are the same as before.
+import { readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
+import { chromeWithParam } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+import { markProposals, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { StaleToken, manifestToken, updateChrome, updateRender } from "./manifest.mjs";
+import { runClipEditorOp } from "./clipEditor.mjs";
+
+export const ASSIST_TASK = "video-assist";
+export const ASSIST_JOB_FILE = ".video-assist-job.json";
+export const ASSIST_SCOPES = Object.freeze(["look", "clips", "fx", "all"]);
+export const ASSIST_REQUEST_MAX = 2000;
+const JOB_RE = /^[A-Za-z0-9_-]+$/;
+const NOTE_RE = /^n_[a-z0-9]{4,32}$/;
+const OP_ID_RE = /^a\d{1,3}$/;
+const RESULT_MARKER = "@@report-draft ";
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+export class AssistRequestError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+/**
+ * A POST's ask, judged: `{ request, scope? }` (the Ask box) or `{ note, scope? }`
+ * (Ask the assistant on a note on the whole project).
+ * @param {unknown} body
+ */
+export function parseAssistRequest(body) {
+ if (!isObj(body)) throw new AssistRequestError("a body is { project, request | note, scope? }");
+ const scope = body.scope === undefined || body.scope === null ? "all" : String(body.scope);
+ if (!ASSIST_SCOPES.includes(scope)) throw new AssistRequestError(`scope is ${ASSIST_SCOPES.join(", ")}`);
+ if (body.note !== undefined && body.note !== null) {
+ if (typeof body.note !== "string" || !NOTE_RE.test(body.note)) throw new AssistRequestError("a note's Ask names the note (n_…)");
+ if (body.request !== undefined && body.request !== null) throw new AssistRequestError("give a request or a note, not both");
+ return { note: body.note, scope };
+ }
+ const request = typeof body.request === "string" ? body.request.replace(/\s+/g, " ").trim() : "";
+ if (!request) throw new AssistRequestError("say what to change");
+ if (request.length > ASSIST_REQUEST_MAX) throw new AssistRequestError(`a request is at most ${ASSIST_REQUEST_MAX} characters`);
+ return { request, scope };
+}
+
+/** The editor's `report-draft` body for an ask on a project directory. */
+export function draftBodyOf(dir, req) {
+ return { task: ASSIST_TASK, project: dir, ...(req.note ? { note: req.note } : { request: req.request }), ...(req.scope && req.scope !== "all" ? { scope: req.scope } : {}) };
+}
+
+const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ASSIST_JOB_FILE);
+
+/** The job the page follows, or null: `{ jobId, request?, note?, scope, at }`. */
+export async function readAssistJob(dir) {
+ try {
+ const j = JSON.parse(await readFile(jobFileOf(dir), "utf8"));
+ return isObj(j) && typeof j.jobId === "string" && JOB_RE.test(j.jobId) ? j : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Remember the job an Ask started (tmp + rename). */
+export async function writeAssistJob(dir, rec) {
+ const file = jobFileOf(dir);
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(rec)}\n`);
+ await rename(tmp, file);
+}
+
+/** Forget it — only when it is still that job. */
+export async function clearAssistJob(dir, jobId) {
+ const cur = await readAssistJob(dir);
+ if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true });
+}
+
+export const ENDED = Object.freeze(["done", "failed", "cancelled", "interrupted"]);
+
+/** The job's `@@report-draft` result in its log tail, or null. */
+export function assistMarkerOf(tail) {
+ for (let i = (tail?.length ?? 0) - 1; i >= 0; i--) {
+ const at = String(tail[i]).indexOf(RESULT_MARKER);
+ if (at < 0) continue;
+ try {
+ return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length));
+ } catch {
+ return null;
+ }
+ }
+ return null;
+}
+
+/** What the page shows of a job: its state, where it waits, its last line, and its result once it ended. */
+export function assistJobView(rec, job) {
+ const marker = assistMarkerOf(job.tail);
+ const last = [...(job.tail ?? [])].reverse().find((l) => !String(l).includes(RESULT_MARKER)) ?? null;
+ return {
+ id: job.id,
+ ...(rec?.note ? { note: rec.note } : {}),
+ ...(rec?.request ? { request: rec.request } : {}),
+ status: job.status,
+ ended: ENDED.includes(job.status),
+ queue: job.queue ?? null,
+ last: last === null ? null : String(last).slice(0, 300),
+ summary: typeof marker?.summary === "string" ? marker.summary : null,
+ };
+}
+
+/**
+ * How the task is routed, for the box: `{ route, model, why }` from the
+ * policy's generation block, or null without one. `why` is set when the box
+ * cannot start a job here (routed to Claude Code, or no route).
+ */
+export function assistRouteOf(generation, dir) {
+ if (!isObj(generation) || !isObj(generation.routes)) return null;
+ const route = generation.routes[ASSIST_TASK] ?? null;
+ if (route === "code") return { route, model: null, why: `routed to Claude Code — in a session: /gen on ${dir}: <what to change>` };
+ const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null;
+ return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no video-assist" };
+}
+
+/**
+ * The proposals for the page: each op with whether it would still apply to
+ * the manifest as it is (`now: null` when it would, else the reason).
+ * @param {string} dir
+ */
+export async function proposalsView(dir) {
+ const [{ doc, error }, manifest] = await Promise.all([readAssistProposals(dir), readManifest(dir)]);
+ if (!doc) return { proposals: null, error };
+ const ops = doc.ops.map((o) => {
+ if (o.status !== "proposed" && o.status !== "failed") return { ...o, now: null };
+ const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope });
+ return { ...o, now: r.refused[0]?.why ?? null, diffNow: r.ops[0]?.diff ?? null };
+ });
+ return { proposals: { ...doc, ops }, error: null };
+}
+
+/**
+ * Apply proposed ops (`ids`, or every one still proposed) in the file's
+ * order, each re-checked against the manifest as the ones before it left it.
+ * `token` is the manifest's as the page read it (null: unguarded — the CLI).
+ * `at`, when given, is the proposals the caller saw: a newer ask's file is a
+ * 409, not a silent apply of other ops.
+ *
+ * @param {{ id: string, dir: string, kind: string }} project
+ * @param {{ ids?: string[] | null, token?: string | null, at?: string | null, now?: string | null }} [o]
+ * @returns {Promise<{ applied: string[], failed: { id: string, error: string }[], token: string | null, proposals: unknown }>}
+ */
+export async function applyAssistOps(project, { ids = null, token = null, at = null, now = null } = {}) {
+ const dir = project.dir;
+ const { doc, error } = await readAssistProposals(dir);
+ if (!doc) throw new AssistRequestError(error ?? "no proposals to apply", 404);
+ if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409);
+ if (ids && !ids.every((id) => typeof id === "string" && OP_ID_RE.test(id))) throw new AssistRequestError("ids is a list of op ids (a1, a2, …)");
+ const wanted = doc.ops.filter((o) => (ids ? ids.includes(o.id) : o.status === "proposed") && (o.status === "proposed" || o.status === "failed"));
+ if (!wanted.length) throw new AssistRequestError(ids ? "those ops are not waiting (applied or dismissed already)" : "nothing is waiting to apply");
+ let cur = await manifestToken(dir);
+ if (token !== null && cur !== token) throw new StaleToken(token, cur);
+ const stamp = now ?? new Date().toISOString();
+ /** @type {Record<string, { status: "applied" | "failed", error?: string }>} */
+ const marks = {};
+ const applied = [];
+ const failed = [];
+ for (const o of wanted) {
+ const manifest = await readManifest(dir);
+ const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope });
+ if (r.refused.length) {
+ marks[o.id] = { status: "failed", error: r.refused[0].why };
+ failed.push({ id: o.id, error: r.refused[0].why });
+ continue;
+ }
+ const a = r.ops[0].apply;
+ try {
+ if (a.writer === "render") cur = (await updateRender(dir, a.patch, { token: cur })).token;
+ else if (a.writer === "chrome") {
+ const chrome = chromeWithParam(manifest.render, a.id, a.param, a.value);
+ cur = (await updateChrome(dir, chrome, { token: cur })).token;
+ } else {
+ const res = await runClipEditorOp(project, { ...a.body, token: cur });
+ cur = res?.view?.token ?? (await manifestToken(dir));
+ }
+ marks[o.id] = { status: "applied" };
+ applied.push(o.id);
+ } catch (e) {
+ // Another writer got in between: stop, say so; what was applied stays applied.
+ if (e instanceof StaleToken) {
+ await writeAssistProposals(dir, markProposals(doc, marks, stamp));
+ throw e;
+ }
+ const msg = e instanceof Error ? (Array.isArray(e.errors) ? e.errors.join("; ") : e.message) : String(e);
+ marks[o.id] = { status: "failed", error: msg };
+ failed.push({ id: o.id, error: msg });
+ }
+ }
+ const next = markProposals(doc, marks, stamp);
+ await writeAssistProposals(dir, next);
+ return { applied, failed, token: cur, proposals: next };
+}
+
+/**
+ * Dismiss ops (`ids`, or every one still waiting): marked, nothing else written.
+ * @param {string} dir
+ * @param {{ ids?: string[] | null, at?: string | null, now?: string | null }} [o]
+ */
+export async function dismissAssistOps(dir, { ids = null, at = null, now = null } = {}) {
+ const { doc, error } = await readAssistProposals(dir);
+ if (!doc) throw new AssistRequestError(error ?? "no proposals to dismiss", 404);
+ if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409);
+ const marks = Object.fromEntries(
+ doc.ops.filter((o) => (ids ? ids.includes(o.id) : true) && (o.status === "proposed" || o.status === "failed")).map((o) => [o.id, { status: "dismissed" }]),
+ );
+ const next = markProposals(doc, marks, now ?? new Date().toISOString());
+ await writeAssistProposals(dir, next);
+ return { dismissed: Object.keys(marks), proposals: next };
+}
diff --git a/umtool/lib/report/videoAssist.test.mjs b/umtool/lib/report/videoAssist.test.mjs
@@ -0,0 +1,139 @@
+// The video assistant in umtool (release 38 lane E): the Ask's request, the
+// job the page follows, and APPLY — each proposed op re-checked and written
+// through the manifest's own writers (updateRender, the clip editor's trim and
+// room, updateChrome), token-guarded; Dismiss writes nothing but the marks.
+// Synthetic (common/testing/clips/assistProject.mjs).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { assistDeckManifest, assistManifest } from "yt-dlp-transcript-common/testing/clips/assistProject.mjs";
+import { writeReactionProject } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs";
+import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
+import { proposalsDocOf, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
+import { MANIFEST_NAME, StaleToken, manifestToken, updateRender } from "./manifest.mjs";
+import {
+ AssistRequestError,
+ applyAssistOps,
+ assistJobView,
+ assistRouteOf,
+ dismissAssistOps,
+ draftBodyOf,
+ parseAssistRequest,
+ proposalsView,
+} from "./videoAssist.mjs";
+
+const AT = "2026-10-20T00:00:00.000Z";
+
+async function project({ deck = false, ops }) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-assist-"));
+ writeReactionProject(dir);
+ const manifest = deck ? assistDeckManifest() : assistManifest();
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
+ const checked = checkAssistOps(manifest, ops, { request: "the request" });
+ await writeAssistProposals(dir, proposalsDocOf({ at: AT, model: "qwen3:8b", request: "the request", checked }));
+ return { id: "reports/assist", dir, kind: "report" };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+
+test("an Ask's request: words or a note, a scope; the editor's body", () => {
+ assert.deepEqual(parseAssistRequest({ request: " quicker joins " }), { request: "quicker joins", scope: "all" });
+ assert.deepEqual(parseAssistRequest({ note: "n_abcd1234", scope: "look" }), { note: "n_abcd1234", scope: "look" });
+ assert.throws(() => parseAssistRequest({ request: " " }), AssistRequestError);
+ assert.throws(() => parseAssistRequest({ request: "x", scope: "everything" }), /scope is look, clips, fx, all/);
+ assert.throws(() => parseAssistRequest({ note: "n_abcd1234", request: "x" }), /not both/);
+ assert.deepEqual(draftBodyOf("/r/p", { request: "quicker joins", scope: "all" }), { task: "video-assist", project: "/r/p", request: "quicker joins" });
+ assert.deepEqual(draftBodyOf("/r/p", { note: "n_abcd1234", scope: "look" }), { task: "video-assist", project: "/r/p", note: "n_abcd1234", scope: "look" });
+ assert.deepEqual(assistRouteOf({ routes: { "video-assist": "local" }, models: { local: "qwen3:8b" } }, "/r/p"), { route: "local", model: "qwen3:8b", why: null });
+ assert.match(assistRouteOf({ routes: { "video-assist": "code" }, models: {} }, "/r/p").why, /routed to Claude Code — in a session: \/gen on \/r\/p/);
+ const v = assistJobView({ jobId: "j1", request: "quicker" }, { id: "j1", status: "done", tail: ["one ask", '@@report-draft {"task":"video-assist","status":"done","summary":"1 edit proposed"}'] });
+ assert.deepEqual([v.ended, v.summary, v.last, v.request], [true, "1 edit proposed", "one ask", "quicker"]);
+});
+
+test("Apply all: each op re-checked and written by its own writer, in order, the token carried; the ops marked applied", async () => {
+ const p = await project({
+ ops: [
+ { op: "look", id: "", key: "transition", value: 0.15 },
+ { op: "slide", id: "", key: "blur", value: 0.3 },
+ { op: "clip_edges", id: "r002", key: "start", value: 90 },
+ { op: "clip_room", id: "r003", key: "off", value: true },
+ ],
+ });
+ try {
+ const token = await manifestToken(p.dir);
+ const r = await applyAssistOps(p, { token, now: AT });
+ assert.deepEqual(r.applied, ["a1", "a2", "a3", "a4"]);
+ assert.deepEqual(r.failed, []);
+ assert.equal(r.token, await manifestToken(p.dir));
+ const m = await read(p.dir);
+ assert.equal(m.render.transition, 0.15);
+ assert.deepEqual(m.render.slide, { blur: 0.3 });
+ const r002 = m.timeline.find((e) => e.id === "r002");
+ assert.deepEqual([r002.cutStart, r002.cutEnd], [90, 99]);
+ assert.equal(r002.assist.by, "operator", "the clip editor's writer: an edit of an assistant's clip is the operator's");
+ assert.equal(m.timeline.find((e) => e.id === "r003").room, false);
+ const { doc } = await readAssistProposals(p.dir);
+ assert.deepEqual(doc.ops.map((o) => [o.id, o.status, o.at]), [["a1", "applied", AT], ["a2", "applied", AT], ["a3", "applied", AT], ["a4", "applied", AT]]);
+ await assert.rejects(applyAssistOps(p, {}), /nothing is waiting to apply/);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("Apply one; a stale token is a 409 before anything is written; newer proposals are refused by `at`", async () => {
+ const p = await project({ ops: [{ op: "look", id: "", key: "qr", value: false }, { op: "look", id: "", key: "loudness", value: -14 }] });
+ try {
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(applyAssistOps(p, { token: "123" }), StaleToken);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
+ await assert.rejects(applyAssistOps(p, { at: "2026-01-01T00:00:00.000Z" }), (e) => e instanceof AssistRequestError && e.status === 409);
+ const r = await applyAssistOps(p, { ids: ["a2"], token: await manifestToken(p.dir) });
+ assert.deepEqual(r.applied, ["a2"]);
+ const m = await read(p.dir);
+ assert.deepEqual([m.render.qr, m.render.loudness], [undefined, { target: -14 }]);
+ assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["proposed", "applied"]);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("an op the manifest no longer allows fails at Apply with the reason; the view says so before", async () => {
+ const p = await project({ ops: [{ op: "clip_edges", id: "r001", key: "end", value: 48 }, { op: "look", id: "", key: "transition", value: 0.15 }] });
+ try {
+ // Somebody narrowed r001's window meanwhile, and set the join themselves.
+ const m = await read(p.dir);
+ m.timeline[0].end = 47.5;
+ await writeFile(path.join(p.dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n");
+ await updateRender(p.dir, { transition: 0.15 });
+ const v = await proposalsView(p.dir);
+ assert.match(v.proposals.ops[0].now, /outside the clip's source window \(38\.5–47\.5 s\)/);
+ assert.match(v.proposals.ops[1].now, /join is already that/);
+ const r = await applyAssistOps(p, {});
+ assert.deepEqual(r.applied, []);
+ assert.deepEqual(r.failed.map((f) => f.id), ["a1", "a2"]);
+ assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["failed", "failed"]);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("a composition's param through updateChrome; Dismiss changes nothing but the marks", async () => {
+ const p = await project({ deck: true, ops: [{ op: "fx", id: "deck", key: "motion.in", value: 0.6 }, { op: "fx", id: "fx.glitch", key: "seconds", value: 0.8 }] });
+ try {
+ const r = await applyAssistOps(p, { ids: ["a1"] });
+ assert.deepEqual(r.applied, ["a1"]);
+ const m = await read(p.dir);
+ assert.deepEqual(m.render.chrome.deck, { qr: { show: false }, motion: { in: 0.6 } });
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ const d = await dismissAssistOps(p.dir, { at: AT });
+ assert.deepEqual(d.dismissed, ["a2"]);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before, "Dismiss writes no manifest");
+ assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["applied", "dismissed"]);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -165,6 +165,8 @@ import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage
import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { blurSlideEdges, validateTransitionStyle, xfadeTransitionOf } from "./transition.mjs";
+import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD, joinPreviewTimeline } from "./join-preview.mjs";
+import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
// The look of a highlights cut (release 36 lane C): render.captions,
// render.loudness, a clip's vertical crop and the short made from it -- pure,
// in look.mjs. Every hook below runs only when its key is set.
@@ -5144,6 +5146,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
if (e.type !== "clip") throw new Error(`${opts.short} is a ${e.type ?? "non-clip"} entry: a short is made from a clip`);
manifest.render = shortRender(manifest.render ?? {});
}
+ // A join preview (release 38, join-preview.mjs): the first few joins of
+ // the cut, each clip shortened to a few seconds at the join, in the cut's look.
+ if (opts.joinPreview) {
+ if (only || fetchOnly) throw new Error("--join-preview builds the joins: not with --only, --short or --fetch-only");
+ manifest.timeline = joinPreviewTimeline(manifest, { from: opts.joinPreview.from ?? null });
+ EMIT("note", { message: `join preview: ${manifest.timeline.map((e) => e.id).join(", ")}` });
+ }
for (const message of rulingsLines(ruled)) EMIT("note", { message });
const { render, provenance } = manifest;
// A `src` clip's file and cues, checked and measured before anything else.
@@ -5220,6 +5229,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const dirs = variantPaths(outRoot, manifest.slug, variant);
// A short's work is its own: the cut's segments are never overwritten by one.
if (opts.short) dirs.dir = path.join(outRoot, "shorts-work");
+ // A join preview's too: its own work dir and file, the cut's out/ untouched.
+ if (opts.joinPreview) {
+ dirs.dir = path.join(outRoot, "join-preview-work");
+ dirs.final = path.join(outRoot, JOIN_PREVIEW_FILE);
+ }
const outDir = dirs.dir;
// Where media may already be on disk. The channels tree is the one the clip
// bench reads for this project (sources.mjs channelsDirFor): the manifest's
@@ -5829,6 +5843,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// shortest=1), and a hang means an unbounded -loop 1.
if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build");
+ // A join preview ends here: no chapters, no YouTube text, no thumbnail --
+ // those are the cut's. A record beside it says what it was made from.
+ if (opts.joinPreview) {
+ await pruneFrames();
+ const record = { version: 1, madeAt: new Date().toISOString(), clips: manifest.timeline.map((e) => e.id), look: lookOf(render) };
+ await replaceFile(path.join(outRoot, JOIN_PREVIEW_RECORD), JSON.stringify(record, null, 2) + "\n");
+ EMIT("done", { out: final, failures: [], joinPreview: true });
+ return { out: final, failures };
+ }
+
const muxed = opts.noChapters
? null
: await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
@@ -5975,6 +5999,7 @@ async function main() {
console.error(
"usage: build-video.mjs <manifest.json> [--out <dir>] [--variant sourced|full]\n" +
" [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" +
+ " [--join-preview [--join-from <id>]] (the first few joins, a few seconds each side: out/join-preview.mp4)\n" +
" [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" +
" [--progress ndjson] [--continue-on-error] [--no-reuse]\n" +
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
@@ -6023,6 +6048,7 @@ async function main() {
final: argv.includes("--final"),
draftsUnreviewed: argv.includes("--drafts-unreviewed"),
short: flag("--short") ?? null,
+ joinPreview: argv.includes("--join-preview") ? { from: flag("--join-from") ?? null } : null,
};
try {
Object.assign(opts, chromeFlags(argv));
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -15,6 +15,7 @@
// No ffmpeg, no fs, no network. If a function here needs one, it belongs in
// build-video.mjs or compose-chrome.mjs instead.
import { createHash } from "node:crypto";
+import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
import { attributionParts, deckSubtitle } from "./attribution.mjs";
import {
@@ -74,6 +75,14 @@ export const DECK_DEFAULTS = Object.freeze({
}),
});
+/**
+ * The deck's TUNABLE params (release 38): the settings the video assistant's
+ * `fx` op may set by name, each with the bounds validateChrome holds it to
+ * (declared in common lib/report/fxParams.mjs; fx-params.test.mjs keeps the
+ * two in step).
+ */
+export const DECK_PARAMS = COMPOSITION_PARAMS.deck;
+
/** Where a clip's deck QR links (`qr.links`): the archive at the clip, or the original. */
export const QR_LINKS = Object.freeze(["site", "original"]);
diff --git a/umtool/report-to-video/fx-params.test.mjs b/umtool/report-to-video/fx-params.test.mjs
@@ -0,0 +1,79 @@
+// The compositions' declared params (release 38 lane E, common
+// lib/report/fxParams.mjs) held to the validators that build them: every
+// declared param is accepted at its bounds and its default and refused just
+// past them, so a declaration cannot promise the video assistant a value the
+// deck's own check refuses.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { COMPOSITION_PARAMS, chromeWithParam, compositionOn } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+import { DECK_PARAMS, validateChrome } from "./deck.mjs";
+import { STATS_PARAMS } from "./stats.mjs";
+import { FX_KEYS, FX_PARAMS } from "./fx.mjs";
+
+// Each composition on, with the one setting validateChrome needs beside it.
+const ON = {
+ deck: {},
+ stats: { stats: {} },
+ "fx.kineticQuote": { fx: { kineticQuote: {} } },
+ "fx.redact": { fx: { redact: {} } },
+ "fx.odometer": { fx: { odometer: {} } },
+ "fx.scrubber": { fx: { scrubber: {} } },
+ "fx.glitch": { fx: { glitch: {} } },
+ "fx.thenNow": { fx: { thenNow: { pairs: [{ then: "c1", now: "c2" }] } } },
+ "fx.receipts": { fx: { receipts: {} } },
+ "fx.zoom": { fx: { zoom: {} } },
+ "fx.punchIn": { fx: { punchIn: {} } },
+ "fx.whip": { fx: { whip: {} } },
+};
+const renderOf = (id) => ({ width: 1920, height: 1080, fps: 30, transition: 0.5, chrome: { engine: "hyperframes", layout: "deck", deck: {}, ...ON[id] } });
+const errorsWith = (id, key, value) => {
+ const render = renderOf(id);
+ const chrome = chromeWithParam(render, id, key, value);
+ assert.ok(chrome, `${id}.${key}: chromeWithParam gave nothing`);
+ const { chrome: _c, ...rest } = render;
+ return validateChrome(chrome, rest);
+};
+
+test("the modules re-export their slice of the declarations", () => {
+ assert.equal(DECK_PARAMS, COMPOSITION_PARAMS.deck);
+ assert.equal(STATS_PARAMS, COMPOSITION_PARAMS.stats);
+ assert.deepEqual(Object.keys(FX_PARAMS).sort(), Object.keys(COMPOSITION_PARAMS).filter((k) => k.startsWith("fx.")).map((k) => k.slice(3)).sort());
+ for (const k of Object.keys(FX_PARAMS)) assert.ok(FX_KEYS.includes(k), `${k} is an effect`);
+ for (const id of Object.keys(COMPOSITION_PARAMS)) assert.ok(ON[id], `${id} has a fixture here`);
+});
+
+test("every declared param: its default and both bounds build; just past them, the validator refuses", () => {
+ for (const [id, params] of Object.entries(COMPOSITION_PARAMS)) {
+ assert.ok(compositionOn(renderOf(id), id), `${id} is on in its fixture`);
+ for (const p of params) {
+ const where = `${id}.${p.key}`;
+ assert.deepEqual(errorsWith(id, p.key, p.default), [], `${where} default`);
+ if (p.kind === "enum") {
+ for (const v of p.values) assert.deepEqual(errorsWith(id, p.key, v), [], `${where} = ${v}`);
+ assert.ok(errorsWith(id, p.key, "nope").length, `${where} = "nope" is refused`);
+ } else if (p.kind === "bool") {
+ for (const v of [true, false]) assert.deepEqual(errorsWith(id, p.key, v), [], `${where} = ${v}`);
+ assert.ok(errorsWith(id, p.key, "yes").length, `${where} = "yes" is refused`);
+ } else if (p.kind === "text") {
+ assert.deepEqual(errorsWith(id, p.key, "x".repeat(p.maxLength)), [], `${where} at its length`);
+ assert.ok(errorsWith(id, p.key, "x".repeat(p.maxLength + 1)).length, `${where} past its length is refused`);
+ } else {
+ const eps = p.kind === "int" ? 1 : 0.01;
+ assert.deepEqual(errorsWith(id, p.key, p.min), [], `${where} = min ${p.min}`);
+ assert.deepEqual(errorsWith(id, p.key, p.max), [], `${where} = max ${p.max}`);
+ assert.ok(errorsWith(id, p.key, p.min - eps).length, `${where} below min is refused`);
+ assert.ok(errorsWith(id, p.key, p.max + eps).length, `${where} above max is refused`);
+ }
+ }
+ }
+});
+
+test("a composition the cut does not draw has nothing to set", () => {
+ const plain = { width: 1920, height: 1080 };
+ assert.equal(compositionOn(plain, "deck"), false);
+ assert.equal(chromeWithParam(plain, "deck", "motion.in", 0.3), null);
+ assert.equal(compositionOn(renderOf("deck"), "fx.glitch"), false);
+ assert.equal(chromeWithParam(renderOf("deck"), "deck", "height", 300), null, "an undeclared param");
+});
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -29,6 +29,8 @@
// way round -- and it imports nothing of the montage's (montage.mjs imports
// deck.mjs), so the few date and phrase helpers it needs are its own.
+import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+
/** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */
export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]);
@@ -62,6 +64,16 @@ export const FX_DEFAULTS = Object.freeze({
whip: Object.freeze({ on: "every" }),
});
+/**
+ * Each effect's TUNABLE params (release 38), keyed by effect: the settings the
+ * video assistant's `fx` op may set by name ("fx.<effect>"), with the bounds
+ * validateFx holds them to (declared in common lib/report/fxParams.mjs;
+ * fx-params.test.mjs keeps the two in step).
+ */
+export const FX_PARAMS = Object.freeze(
+ Object.fromEntries(Object.entries(COMPOSITION_PARAMS).filter(([id]) => id.startsWith("fx.")).map(([id, ps]) => [id.slice(3), ps])),
+);
+
/** The motion every effect shares, in seconds. */
export const FX_MOTION = Object.freeze({
word: 0.14, // a word coming in
diff --git a/umtool/report-to-video/join-preview.mjs b/umtool/report-to-video/join-preview.mjs
@@ -0,0 +1,51 @@
+// A JOIN PREVIEW (release 38 lane E): a few seconds either side of the first
+// few joins of a cut, in the cut's own look -- the quick render the video
+// assistant's Ask box and the Look panel play to judge a join's length,
+// style, slide and room before a full build. `build-video.mjs <manifest>
+// --join-preview [--join-from <clip id>]` writes out/join-preview.mp4 (and
+// out/join-preview.json, what it was made from) through the heavy slot, as a
+// full build does; nothing of the cut's own out/ files is touched.
+//
+// The cut: JOIN_PREVIEW_CLIPS consecutive clips (from `from`, else the first),
+// every other entry left out; each clip keeps the last JOIN_PREVIEW_SECONDS
+// of its cut (so its tail -- where room and the join act -- is its own), the
+// last one the first JOIN_PREVIEW_SECONDS. The windows are untouched, so the
+// media already fetched for the cut is what the preview cuts from.
+//
+// PURE: the manifest in, a timeline out.
+
+export const JOIN_PREVIEW_CLIPS = 4;
+export const JOIN_PREVIEW_SECONDS = 3;
+export const JOIN_PREVIEW_FILE = "join-preview.mp4";
+export const JOIN_PREVIEW_RECORD = "join-preview.json";
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (n) => Math.round(n * 100) / 100;
+
+/**
+ * The preview's timeline, or a thrown reason it cannot be made.
+ *
+ * @param {{ render?: Record<string, unknown>, timeline?: Record<string, unknown>[] }} manifest
+ * @param {{ from?: string | null, clips?: number, seconds?: number }} [o]
+ */
+export function joinPreviewTimeline(manifest, { from = null, clips = JOIN_PREVIEW_CLIPS, seconds = JOIN_PREVIEW_SECONDS } = {}) {
+ const render = manifest?.render ?? {};
+ if (render.chrome !== undefined && render.chrome !== null) throw new Error("a join preview is a plain cut's: this one is drawn under the deck (a full build or --chrome-preview shows its joins)");
+ if (render.montage !== undefined && render.montage !== null) throw new Error("a join preview is a plain cut's: a montage cuts to its phrases");
+ if (!(fin(render.transition) ? render.transition > 0 : true)) throw new Error("this cut has hard cuts (render.transition 0): there is no join to preview");
+ const all = (manifest?.timeline ?? []).filter((e) => e?.type === "clip");
+ const at = from ? all.findIndex((e) => e.id === from) : 0;
+ if (at < 0) throw new Error(`no clip ${from} in the cut`);
+ const picked = all.slice(at, at + clips);
+ if (picked.length < 2) throw new Error("a join preview needs two clips after it starts");
+ return picked.map((e, i) => {
+ const a = fin(e.cutStart) && fin(e.cutEnd) ? e.cutStart : e.start;
+ const b = fin(e.cutStart) && fin(e.cutEnd) ? e.cutEnd : e.end;
+ if (!fin(a) || !fin(b) || b - a <= seconds) return { ...e };
+ const last = i === picked.length - 1;
+ const cut = last ? { cutStart: r2(a), cutEnd: r2(a + seconds) } : { cutStart: r2(b - seconds), cutEnd: r2(b) };
+ // A mute mark stays: before the shortened cut it mutes all of it, as it
+ // mutes that stretch of the full cut; past it, nothing, as in the cut.
+ return { ...e, ...cut };
+ });
+}
diff --git a/umtool/report-to-video/join-preview.test.mjs b/umtool/report-to-video/join-preview.test.mjs
@@ -0,0 +1,35 @@
+// The join preview's cut (release 38 lane E, join-preview.mjs).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { JOIN_PREVIEW_SECONDS, joinPreviewTimeline } from "./join-preview.mjs";
+
+const clip = (id, a, b, extra = {}) => ({ type: "clip", id, channel: "ch", video: "v1", start: a - 1.5, end: b + 1.5, cutStart: a, cutEnd: b, ...extra });
+const M = (timeline, render = {}) => ({ render: { transition: 0.22, transitionStyle: "blurslide", ...render }, timeline });
+
+test("four clips from the first: each keeps the last seconds of its cut, the last its first seconds; cards left out", () => {
+ const tl = [{ type: "card", id: "t0" }, clip("a", 10, 20), clip("b", 30, 32), clip("c", 40, 50, { muteFrom: 41 }), clip("d", 60, 70), clip("e", 80, 90)];
+ const out = joinPreviewTimeline(M(tl));
+ assert.deepEqual(out.map((e) => [e.id, e.cutStart, e.cutEnd, e.start, e.end]), [
+ ["a", 20 - JOIN_PREVIEW_SECONDS, 20, 8.5, 21.5],
+ ["b", 30, 32, 28.5, 33.5],
+ ["c", 47, 50, 38.5, 51.5],
+ ["d", 60, 63, 58.5, 71.5],
+ ]);
+ assert.equal(out[2].muteFrom, 41, "a mute mark before the shortened cut stays (it mutes all of it, as in the cut)");
+ // From a named clip.
+ assert.deepEqual(joinPreviewTimeline(M(tl), { from: "c" }).map((e) => e.id), ["c", "d", "e"]);
+ // A clip with no cut fields is shortened the same way, inside its edges.
+ const plain = joinPreviewTimeline(M([{ type: "clip", id: "x", start: 0, end: 10 }, { type: "clip", id: "y", start: 20, end: 30 }]));
+ assert.deepEqual(plain.map((e) => [e.cutStart, e.cutEnd]), [[7, 10], [20, 23]]);
+});
+
+test("refused: a deck, a montage, hard cuts, fewer than two clips, an unknown clip", () => {
+ const tl = [clip("a", 10, 20), clip("b", 30, 40)];
+ assert.throws(() => joinPreviewTimeline(M(tl, { chrome: { engine: "hyperframes", layout: "deck" } })), /plain cut's: this one is drawn under the deck/);
+ assert.throws(() => joinPreviewTimeline(M(tl, { montage: {} })), /a montage cuts to its phrases/);
+ assert.throws(() => joinPreviewTimeline(M(tl, { transition: 0 })), /no join to preview/);
+ assert.throws(() => joinPreviewTimeline(M(tl), { from: "b" }), /needs two clips/);
+ assert.throws(() => joinPreviewTimeline(M(tl), { from: "zz" }), /no clip zz/);
+});
diff --git a/umtool/report-to-video/look.mjs b/umtool/report-to-video/look.mjs
@@ -23,17 +23,36 @@
// other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn)
// Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR.
-import { validateRoom } from "./room.mjs";
+// The checks (captions, loudness, the vertical crop, room) and their bounds
+// are the look's rules (common lib/report/look.mjs, release 38): re-exported
+// here, so the writer, the build and the video assistant refuse the same things.
+import { DEFAULT_SOURCE_ASPECT, VERTICAL_RATIO, loudnessTargetOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
+
+export {
+ CAPTION_LABEL_MAX,
+ CAPTION_SIZES,
+ CAPTION_STYLES,
+ DEFAULT_SOURCE_ASPECT,
+ LOUDNESS_MAX,
+ LOUDNESS_MIN,
+ VERTICAL_RATIO,
+ VERTICAL_TOLERANCE,
+ captionsOn,
+ loudnessOn,
+ loudnessTargetOf,
+ validateCaptions,
+ validateLoudness,
+ validateLook,
+ validateVertical,
+ verticalErrors,
+} from "yt-dlp-transcript-common/lib/report/look.mjs";
-export const CAPTION_STYLES = Object.freeze(["speakers"]);
-export const CAPTION_SIZES = Object.freeze(["m", "l"]);
export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]);
export const CAPTION_COLOURS = Object.freeze({ host: "#FFC840", subject: "#6FD3FF", other: "#F6F1E6" });
/** ASS alignment (numpad): host bottom-left, subject bottom-right, other bottom-centre. */
export const CAPTION_ALIGN = Object.freeze({ host: 1, subject: 3, other: 2 });
/** The font, vendored in fonts/ (IBM Plex Sans, OFL): libass is pointed at that directory. */
export const CAPTION_FONT = "IBM Plex Sans";
-export const CAPTION_LABEL_MAX = 40;
/** Words a line: at least (unless a speaker change or the clip's end forces fewer), at most. */
export const CAPTION_MIN_WORDS = 2;
export const CAPTION_MAX_WORDS = 6;
@@ -42,115 +61,14 @@ export const CAPTION_PAUSE = 0.45;
/** How long a line stays up after its last word (s), never past the next line. */
export const CAPTION_HOLD = 0.3;
-export const LOUDNESS_MIN = -30;
-export const LOUDNESS_MAX = -8;
/** A short's target when the cut sets none. */
export const SHORT_LOUDNESS = -16;
export const SHORT_WIDTH = 1080;
export const SHORT_HEIGHT = 1920;
-export const VERTICAL_RATIO = 9 / 16;
-/** How far a crop's shape may be from 9:16 (relative): the build fits it exactly. */
-export const VERTICAL_TOLERANCE = 0.03;
-export const DEFAULT_SOURCE_ASPECT = 16 / 9;
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const num = (v) => typeof v === "number" && Number.isFinite(v);
-const q = (v) => JSON.stringify(v);
-
-export const captionsOn = (render) => isObj(render?.captions);
-export const loudnessOn = (render) => isObj(render?.loudness) && num(render.loudness.target);
-/** The target in LUFS, or null when the cut sets none. */
-export const loudnessTargetOf = (render) => (loudnessOn(render) ? render.loudness.target : null);
-
-/** `render.captions`: its keys and values, and what it does not combine with. */
-export function validateCaptions(manifest) {
- const render = manifest?.render ?? {};
- const c = render.captions;
- if (c === undefined || c === null) return [];
- if (!isObj(c)) return [`render.captions must be an object ({style: "speakers"}) or absent, not ${q(c)}`];
- const errors = [];
- for (const k of Object.keys(c)) {
- if (!["style", "labels", "size"].includes(k)) errors.push(`render.captions.${k} is not a setting here (the settings are style, labels, size)`);
- }
- if (!CAPTION_STYLES.includes(c.style)) errors.push(`render.captions.style must be "speakers", not ${q(c.style)}`);
- if (c.size !== undefined && !CAPTION_SIZES.includes(c.size)) errors.push(`render.captions.size must be "m" or "l", not ${q(c.size)}`);
- if (c.labels !== undefined && c.labels !== null) {
- if (!isObj(c.labels)) errors.push(`render.captions.labels must be an object ({host, subject}), not ${q(c.labels)}`);
- else {
- for (const [k, v] of Object.entries(c.labels)) {
- if (k !== "host" && k !== "subject") errors.push(`render.captions.labels.${k} is not a role here (host, subject)`);
- else if (v !== null && (typeof v !== "string" || v.length > CAPTION_LABEL_MAX)) {
- errors.push(`render.captions.labels.${k} must be a short text (up to ${CAPTION_LABEL_MAX} characters), or null`);
- }
- }
- }
- }
- if (isObj(render.chrome)) errors.push("render.captions does not combine with render.chrome (the deck draws its own words: render.chrome.fx.kineticQuote)");
- if (render.montage !== undefined && render.montage !== null) errors.push("render.captions does not combine with render.montage (a montage re-times its clips)");
- return errors;
-}
-
-/** `render.loudness`: `{target}` in LUFS. */
-export function validateLoudness(manifest) {
- const render = manifest?.render ?? {};
- const l = render.loudness;
- if (l === undefined || l === null) return [];
- if (!isObj(l)) return [`render.loudness must be an object ({target: -16}) or absent, not ${q(l)}`];
- const errors = [];
- for (const k of Object.keys(l)) if (k !== "target") errors.push(`render.loudness.${k} is not a setting here (the setting is target)`);
- if (!num(l.target) || l.target < LOUDNESS_MIN || l.target > LOUDNESS_MAX) {
- errors.push(`render.loudness.target must be a number from ${LOUDNESS_MIN} to ${LOUDNESS_MAX} LUFS, not ${q(l.target)}`);
- }
- if (render.montage !== undefined && render.montage !== null) errors.push("render.loudness does not combine with render.montage (a montage levels with render.montage.loudness)");
- return errors;
-}
-
-/** One clip's `vertical` (null when it has none): its errors, prefixed by `who`. */
-export function verticalErrors(v, who = "vertical") {
- if (v === undefined || v === null) return [];
- if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`];
- const errors = [];
- for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect") errors.push(`${who}.${k} is not a setting here (crop, aspect)`);
- if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) {
- errors.push(`${who}.aspect must be the source's width / height (a number from 0.2 to 5), not ${q(v.aspect)}`);
- }
- const c = v.crop;
- if (!Array.isArray(c) || c.length !== 4 || !c.every(num)) {
- errors.push(`${who}.crop must be [x, y, w, h], four fractions of the source picture`);
- return errors;
- }
- const [x, y, w, h] = c;
- const E = 1e-3;
- if (w <= 0 || h <= 0) errors.push(`${who}.crop's width and height must be above 0`);
- if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${who}.crop must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`);
- if (w > 0 && h > 0) {
- const aspect = num(v.aspect) ? v.aspect : DEFAULT_SOURCE_ASPECT;
- const shape = (w * aspect) / h;
- if (Math.abs(shape / VERTICAL_RATIO - 1) > VERTICAL_TOLERANCE) {
- errors.push(`${who}.crop must be 9:16 on the source (w × aspect / h ≈ 0.5625; this one is ${shape.toFixed(4)})`);
- }
- }
- return errors;
-}
-
-/** Every clip's `vertical`. */
-export function validateVertical(manifest) {
- const errors = [];
- (manifest?.timeline ?? []).forEach((e, i) => {
- if (e?.vertical === undefined) return;
- const who = `timeline[${i}] (${e?.id ?? "?"}).vertical`;
- if (e?.type !== "clip") errors.push(`${who}: only a clip has a vertical crop`);
- else errors.push(...verticalErrors(e.vertical, who));
- });
- return errors;
-}
-
-/** All of the look's keys: the build's validators and the lint call this. */
-export function validateLook(manifest) {
- // render.room and a clip's room (room.mjs, release 36 lane E) are part of the look.
- return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)];
-}
// ---------------------------------------------------------------------------
// The vertical crop.
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -34,6 +34,7 @@
"./montage-rulings": "./montage-rulings.mjs",
"./lint": "./lint.mjs",
"./local-media": "./local-media.mjs",
+ "./join-preview": "./join-preview.mjs",
"./look": "./look.mjs",
"./mute": "./mute.mjs",
"./narration": "./narration.mjs",
diff --git a/umtool/report-to-video/room.mjs b/umtool/report-to-video/room.mjs
@@ -36,90 +36,16 @@
// fetch pad) clamps it -- the build says so, and the lint warns when the
// room can reach past the window.
-export const ROOM = Object.freeze({
- /** A gap between two words this long (s) is the silence the sound stops at. */
- minGap: 0.35,
- /** The sound never runs more than this (s) past the cut's end. */
- maxS: 2.5,
- /** The fade at the silence point, and the fade in at a muted head (s). */
- fade: 0.06,
- /** Muted picture past D, so the fade is done before the join begins (s). */
- pad: 0.1,
- /** silencedetect, when there are no words: noise floor (dB) and least length (s). */
- detectDb: -35,
- detectD: 0.3,
-});
-export const ROOM_EDGES = Object.freeze(["tail", "head"]);
-const MIN_GAP = [0.1, 2];
-const MAX_S = [0, 10];
+// ROOM, its edges, its bounds and validateRoom / roomOn / clipRoom are the
+// look's rules (common lib/report/look.mjs, release 38): re-exported here, so
+// the writer, the build and the video assistant refuse the same things.
+import { ROOM, clipRoom } from "yt-dlp-transcript-common/lib/report/look.mjs";
+
+export { ROOM, ROOM_BOUNDS, ROOM_EDGES, clipRoom, roomOn, validateRoom } from "yt-dlp-transcript-common/lib/report/look.mjs";
-const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const num = (v) => typeof v === "number" && Number.isFinite(v);
-const q = (v) => JSON.stringify(v);
const r3 = (n) => Math.round(n * 1000) / 1000;
-/** Does the cut's render block turn room on for either edge? */
-export const roomOn = (render) => isObj(render?.room) && (render.room.tail === true || render.room.head === true);
-
-/**
- * One clip's room: `{tail, head, minGap, maxS}` with at least one edge on, or
- * null. The clip's `room` (false, or per-edge booleans) beats the cut's.
- */
-export function clipRoom(entry, render) {
- const r = isObj(render?.room) ? render.room : null;
- const c = entry?.room;
- if (c === false) return null;
- const edge = (k) => (isObj(c) && typeof c[k] === "boolean" ? c[k] : r?.[k] === true);
- const tail = edge("tail");
- const head = edge("head");
- if (!tail && !head) return null;
- return {
- tail,
- head,
- minGap: num(r?.minGap) ? r.minGap : ROOM.minGap,
- maxS: num(r?.maxS) ? r.maxS : ROOM.maxS,
- };
-}
-
-/** `render.room` and every clip's `room`: each problem in a sentence naming the key. */
-export function validateRoom(manifest) {
- const render = manifest?.render ?? {};
- const errors = [];
- const room = render.room;
- if (room !== undefined && room !== null) {
- if (!isObj(room)) errors.push(`render.room must be an object ({tail: true, head: true}) or absent, not ${q(room)}`);
- else {
- for (const k of Object.keys(room)) {
- if (!["tail", "head", "minGap", "maxS"].includes(k)) errors.push(`render.room.${k} is not a setting here (tail, head, minGap, maxS)`);
- }
- for (const k of ROOM_EDGES) {
- if (room[k] !== undefined && typeof room[k] !== "boolean") errors.push(`render.room.${k} must be true or false, not ${q(room[k])}`);
- }
- if (room.minGap !== undefined && (!num(room.minGap) || room.minGap < MIN_GAP[0] || room.minGap > MIN_GAP[1])) {
- errors.push(`render.room.minGap must be seconds from ${MIN_GAP[0]} to ${MIN_GAP[1]}, not ${q(room.minGap)}`);
- }
- if (room.maxS !== undefined && (!num(room.maxS) || room.maxS < MAX_S[0] || room.maxS > MAX_S[1])) {
- errors.push(`render.room.maxS must be seconds from ${MAX_S[0]} to ${MAX_S[1]}, not ${q(room.maxS)}`);
- }
- if (render.montage !== undefined && render.montage !== null) errors.push("render.room does not combine with render.montage (a montage cuts to its phrases)");
- }
- }
- (manifest?.timeline ?? []).forEach((e, i) => {
- if (e?.room === undefined) return;
- const who = `timeline[${i}] (${e?.id ?? "?"}).room`;
- if (e?.type !== "clip") errors.push(`${who}: only a clip has room at its edges`);
- else if (e.room === false || e.room === null) return;
- else if (!isObj(e.room)) errors.push(`${who} must be false or {tail?, head?}, not ${q(e.room)}`);
- else {
- for (const [k, v] of Object.entries(e.room)) {
- if (!ROOM_EDGES.includes(k)) errors.push(`${who}.${k} is not a setting here (tail, head)`);
- else if (typeof v !== "boolean") errors.push(`${who}.${k} must be true or false, not ${q(v)}`);
- }
- }
- });
- return errors;
-}
-
/** Timed words, in time order (any of the transcribers' keys for the text is fine; only times are read). */
function timed(words) {
return (Array.isArray(words) ? words : [])
diff --git a/umtool/report-to-video/stats.mjs b/umtool/report-to-video/stats.mjs
@@ -15,6 +15,8 @@
// PURE, like factcheck.mjs: validation, the defaults, the schedule. No fs, no
// ffmpeg. deck.mjs imports this file -- never the other way round.
+import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+
/** Where the stats sit in the footage box. */
export const STATS_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]);
@@ -31,6 +33,9 @@ export const STATS_LABELS = Object.freeze({ stack: "Stack", stackBB: "Big blinds
*/
export const STATS_DEFAULTS = Object.freeze({ position: "bottom-left", fields: STATS_FIELDS, name: true });
+/** The stats panel's TUNABLE params (release 38; common lib/report/fxParams.mjs): what the video assistant's `fx` op may set. */
+export const STATS_PARAMS = COMPOSITION_PARAMS.stats;
+
/** How long the panel takes to come in and go out, in seconds. */
export const STATS_MOTION = Object.freeze({ in: 0.3, out: 0.25 });
diff --git a/umtool/report-to-video/transition.mjs b/umtool/report-to-video/transition.mjs
@@ -12,24 +12,21 @@
// five taps spaced by the moment's speed (most at the start, none as it lands),
// and the frames nearest the seam take a light temporal grain. One xfade
// custom expression (`pushExpr`) plus the grain on each clip's edge.
-export const TRANSITION_STYLES = Object.freeze(["fade", "fadeblack", "fadewhite", "dissolve", "blurslide"]);
+//
+// The style list, the slide's knobs and their checks are the look's rules
+// (common lib/report/look.mjs, release 38): re-exported here, so the writer,
+// the build and the video assistant refuse the same things.
+import { slideOf, transitionStyleOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
-/** The style a plain join uses (`render.transitionStyle`, default "fade"). */
-export const transitionStyleOf = (render) => render?.transitionStyle ?? "fade";
-
-// The push's knobs (`render.slide`): travel = fraction of the width the
-// pictures move; blur = motion-smear strength (0 none, 1 = a frame's travel);
-// grain = noise strength on the seam's frames (0 none).
-export const SLIDE_DEFAULTS = Object.freeze({ travel: 0.08, blur: 0.5, grain: 2 });
-const SLIDE_BOUNDS = Object.freeze({ travel: [0, 0.5], blur: [0, 2], grain: [0, 20] });
-
-/** The push's knobs, the defaults filled in. */
-export function slideOf(render) {
- const s = render?.slide && typeof render.slide === "object" ? render.slide : {};
- const out = {};
- for (const k of Object.keys(SLIDE_DEFAULTS)) out[k] = Number.isFinite(s[k]) ? s[k] : SLIDE_DEFAULTS[k];
- return out;
-}
+export {
+ SLIDE_BOUNDS,
+ SLIDE_DEFAULTS,
+ TRANSITION_STYLES,
+ slideOf,
+ transitionStyleOf,
+ validateSlide,
+ validateTransitionStyle,
+} from "yt-dlp-transcript-common/lib/report/look.mjs";
/**
* The push as an xfade custom expression, for a join `D` seconds long at `fps`.
@@ -89,27 +86,3 @@ export function blurSlideEdges(d, D, render, { tail = false, head = false } = {}
if (head) parts.push(`lt(t,${w.toFixed(3)})`);
return `noise=alls=${Math.round(grain)}:allf=t+u:enable='${parts.join("+")}'`;
}
-
-/** @param {{ render?: { transitionStyle?: unknown } }} manifest */
-export function validateTransitionStyle(manifest) {
- const s = manifest?.render?.transitionStyle;
- const slide = validateSlide(manifest);
- if (s === undefined || s === null) return slide;
- return typeof s === "string" && TRANSITION_STYLES.includes(s)
- ? slide
- : [`render.transitionStyle: ${JSON.stringify(s)} is not one of ${TRANSITION_STYLES.join(", ")}`, ...slide];
-}
-
-/** `render.slide`: absent, or an object of the push's knobs within bounds. */
-export function validateSlide(manifest) {
- const s = manifest?.render?.slide;
- if (s === undefined || s === null) return [];
- if (typeof s !== "object" || Array.isArray(s)) return ["render.slide must be an object {travel?, blur?, grain?}"];
- const errs = [];
- for (const [k, v] of Object.entries(s)) {
- const b = SLIDE_BOUNDS[k];
- if (!b) errs.push(`render.slide.${k} is not a key (travel, blur, grain)`);
- else if (!Number.isFinite(v) || v < b[0] || v > b[1]) errs.push(`render.slide.${k} must be a number from ${b[0]} to ${b[1]}`);
- }
- return errs;
-}