commit 46cca1692c4bcb8b7ee62600f1e84f970f074ddd
parent 9d8141d02c0fa9b40f1104342a0e189441a16643
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 15:18:46 -0400
clips: the clips-suggest generation task — labels, a why and a rank for the clip finder's proposals, and an answer to a comment on a clip
A report-draft task on a umtool reactions project (`project`, not an article),
routed by settings.generation like a media draft (api / local through the GPU
arbiter / code = a Claude Code session's answers via /gen and the MCP's
generate). Writes <project>/clip-suggestions.json through its one writer;
never a clip or the manifest. dryRun answers the plan and the estimate.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
17 files changed, 1917 insertions(+), 17 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md
@@ -42,6 +42,12 @@ each task. Use the archilyzer MCP tools only; run no script for it.
`settings.generation.verdicts.models` (the verdict bench's bar) — `generate` with task `verdicts`, the article and
that `model`. Never propose or rule a claim's verdict yourself, whatever the route; the proposals are the
operator's to approve or reject in umtool (Inbox → Review verdicts), never written by hand.
+ **And `clips-suggest`** (labels, a why and a rank for the clip finder's proposals in a umtool reactions project,
+ named by its directory — "label the clips of <dir>"): `generate` with task `clips-suggest` and `project`. Routed
+ to code, its answer is the request — the moments with their speakers' words — which you label in this session and
+ 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.
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/common/controller/clipsSuggest.ts b/common/controller/clipsSuggest.ts
@@ -0,0 +1,238 @@
+// `report-draft {"task": "clips-suggest", "project", "model"?, "maxUsd"?,
+// "proposals"?, "note"?, "answers"?, "dryRun"?}` — the clip finder's optional
+// AI pass (release 36 lane D) as an editor job. umtool's clip editor starts it
+// (Suggest, Ask the assistant) through `editorCall`; `pnpm ops report-draft`
+// and the MCP's `generate` do the same.
+//
+// project the reactions project's directory (absolute; it must hold a
+// reactions.json, and it is never inside the corpus)
+// labels (no `note`) → `<project>/clip-suggestions.json` (lib/clips/suggest.mjs)
+// note an Ask: that note's reply is posted to umtool's notes as the
+// agent's (`POST <UMTOOL_URL>/api/notes?project=<dir>`, Bearer
+// WORKER_TOKEN), with at most one proposal the operator applies
+// answers the `code` route: a Claude Code session's labels (the answer
+// a model would give, `{items: [{id, label, why, score}]}`), read
+// and written exactly as a model's — no model is called
+// dryRun (the ops route) the plan: how many proposals, calls, the
+// estimate, and the request a session answers; nothing written
+//
+// Routed by settings.generation.routes["clips-suggest"] like every task
+// (`modelFor`: a task routed to `code` needs a named model, or `answers`).
+// The lane is the model's provider's: `draft:local` (every ollama call
+// through the GPU arbiter; ollama unloaded when the job ends) or `draft:api`
+// (metered: the narration cap — a small media draft — and the daily cap, its
+// usage in the ledger as task `clips-suggest`). The log ends `@@report-draft
+// {article: "", iteration: 0, task: "clips-suggest", kind, project, status,
+// summary, usd, suggestions | ask}`.
+
+import path from "node:path";
+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 { diskCuesOf } from "../lib/report/convert-server";
+import { usageOf } from "../lib/report/draft/tasks/run";
+import {
+ CLIPS_SUGGEST_TASK,
+ CODE_MODEL,
+ ClipsSuggestRefusal,
+ loadAsk,
+ loadClipsProject,
+ planClipsSuggest,
+ runClipsAsk,
+ runClipsSuggest,
+ type ClipsAskOutcome,
+ type ClipsSuggestOutcome,
+ type SuggestPlan,
+} from "../lib/report/draft/tasks/clipsSuggest";
+import type { AskProposal } from "../lib/clips/suggest.mjs";
+import { getWorkerToken } from "../lib/workerToken";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft";
+
+export { CLIPS_SUGGEST_TASK, CODE_MODEL };
+
+/**
+ * Where umtool is, for an Ask's reply: `UMTOOL_URL`, trailing slashes dropped;
+ * null when unset. (Release 36 lane A adds the shared reader,
+ * common/lib/umtoolUrl.ts; this is its rule without the e2e file.)
+ */
+export function umtoolOrigin(env: Readonly<Record<string, string | undefined>> = process.env): string | null {
+ const url = env.UMTOOL_URL?.trim().replace(/\/+$/, "");
+ return url ? url : null;
+}
+
+export type ClipsSuggestJobDeps = ReportDraftDeps & {
+ // An Ask's reply, posted (default: umtool's /api/notes over HTTP).
+ postReply?: (r: { project: string; note: string; text: string; proposal: AskProposal | null }) => Promise<void>;
+ umtoolUrl?: string | null;
+ workerToken?: string;
+};
+
+/** The project directory a body names, checked: absolute, normalised, never inside the corpus. */
+export function projectDirOf(raw: string, paths: { transcriptsDir: string }): string {
+ if (!path.isAbsolute(raw)) throw new ClipsSuggestRefusal('"project" is the reactions project\'s absolute directory');
+ const dir = path.resolve(raw);
+ if (dir !== raw.replace(/\/+$/, "")) throw new ClipsSuggestRefusal('"project" is a plain absolute path (no "..", no "//")');
+ const corpus = path.resolve(paths.transcriptsDir);
+ if (dir === corpus || dir.startsWith(`${corpus}${path.sep}`)) throw new ClipsSuggestRefusal('"project" is a umtool project, never inside the corpus');
+ return dir;
+}
+
+/** POST the reply to umtool's notes as the agent's. */
+export async function postReplyToUmtool(
+ r: { project: string; note: string; text: string; proposal: AskProposal | null },
+ 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: the session's answers are `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 CODE_MODEL;
+ return modelFor(gen, CLIPS_SUGGEST_TASK, body.model);
+}
+
+/** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */
+export async function planClipsSuggestJob(body: ReportDraftBody, deps: Pick<ReportDraftDeps, "paths" | "settings">): Promise<SuggestPlan> {
+ const gen = (deps.settings ?? getSettings)().generation;
+ const dir = projectDirOf(body.project ?? "", deps.paths);
+ // A plan for a task routed to Claude Code is the request a session answers.
+ const route = gen.routes[CLIPS_SUGGEST_TASK];
+ const model = body.model ?? (route === "code" ? CODE_MODEL : modelFor(gen, CLIPS_SUGGEST_TASK));
+ return planClipsSuggest({ project: dir, model, ...(body.proposals?.length ? { proposals: body.proposals } : {}) }, { cuesOf: diskCuesOf(deps.paths.channelsDir) });
+}
+
+export async function enqueueClipsSuggest(body: ReportDraftBody, deps: ClipsSuggestJobDeps): Promise<ReportDraftEnqueued | Refused> {
+ const refuse = (error: string): Refused => ({ result: { ok: false as const, error } });
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ let dir: string;
+ let model: string;
+ try {
+ dir = projectDirOf(body.project ?? "", paths);
+ model = modelOfBody(body, gen);
+ // Refused at the ask, not at the job's turn: no reactions.json, no note.
+ await loadClipsProject(dir, {});
+ if (body.note) await loadAsk(dir, body.note);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const ask = !!body.note;
+ const umtool = deps.umtoolUrl === undefined ? umtoolOrigin() : deps.umtoolUrl;
+ const token = deps.workerToken ?? getWorkerToken();
+ if (ask && !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 === 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: { project: string; note: string; text: string; proposal: AskProposal | null }) => postReplyToUmtool(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(
+ `clips-suggest ${ask ? `ask ${body.note}` : "labels"} in ${dir} on ${model} (` +
+ (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter" : "a Claude Code session's answers") +
+ ")",
+ );
+ const taskDeps = {
+ llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined),
+ cuesOf: diskCuesOf(paths.channelsDir),
+ log: onLog,
+ progress: (done: number, total: number) => setProgress?.({ metric: "entries", initial: 0, target: Math.max(total, done), current: done }),
+ signal,
+ ...(deps.now ? { now: deps.now } : {}),
+ };
+ let out: ClipsSuggestOutcome | ClipsAskOutcome | null = null;
+ try {
+ out = ask
+ ? await runClipsAsk(
+ { project: dir, model, note: body.note!, ...(maxUsd !== undefined ? { maxUsd } : {}) },
+ { ...taskDeps, postReply: (r) => postReply({ project: dir, ...r }) },
+ )
+ : await runClipsSuggest(
+ {
+ project: dir,
+ model,
+ ...(body.proposals?.length ? { proposals: body.proposals } : {}),
+ ...(maxUsd !== undefined ? { maxUsd } : {}),
+ ...(body.answers !== undefined ? { answers: body.answers } : {}),
+ },
+ taskDeps,
+ );
+ } 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}`),
+ );
+ }
+ }
+ 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: CLIPS_SUGGEST_TASK,
+ model: m,
+ inputTokens: u.inputTokens,
+ outputTokens: u.outputTokens,
+ cacheReadTokens: u.cacheReadTokens ?? 0,
+ cacheWriteTokens: u.cacheWriteTokens ?? 0,
+ usd: Math.round(u.usd * 10_000) / 10_000,
+ };
+ });
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ const detail =
+ "labelled" in out
+ ? { kind: "labels", suggestions: { labelled: out.labelled, refused: out.refused.length, failed: out.failed.reduce((n, f) => n + f.ids.length, 0), file: out.file } }
+ : { kind: "ask", ask: { note: out.note, clip: out.clip, proposal: out.proposal, dropped: out.dropped } };
+ onLog(
+ `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: "", iteration: 0, task: CLIPS_SUGGEST_TASK, project: dir, status: out.status, summary: out.summary, usd: out.usd, ...detail })}`,
+ );
+ if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (out.status === "failed") throw new Error(out.summary);
+ },
+ });
+ if (!result.ok) return { result };
+ return { result, iteration: 0 };
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -133,6 +133,12 @@ export const REPORT_DRAFT_BODY_KEYS = [
"triage",
// release 29 M8: a `verdicts` job's claims (default: every unruled one).
"claims",
+ // release 36 lane D: a `clips-suggest` job's project directory, the
+ // proposals it labels, the note it answers, a session's answers.
+ "project",
+ "proposals",
+ "note",
+ "answers",
] as const;
// A seed's size: a board of a few hundred quotes, with room.
@@ -182,6 +188,13 @@ export type ReportDraftBody = {
triage?: { owner: string; k: number };
// A verdicts job's (release 29 M8): the claims to propose for.
claims?: string[];
+ // A clips-suggest job's (release 36 lane D, ./clipsSuggest.ts): the
+ // reactions project's directory, only these proposals, the note an Ask
+ // answers, a Claude Code session's answers (the `code` route).
+ project?: string;
+ proposals?: string[];
+ note?: string;
+ answers?: unknown;
};
// A Claude model the price table knows: one of its ids, or a dated id of one
@@ -204,7 +217,11 @@ 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;
- if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)');
+ // A clips-suggest job (release 36 lane D) is on a umtool project, not an article.
+ const onProject = task === "clips-suggest";
+ if (onProject) {
+ if (article !== undefined && article !== null && article !== "") fail('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];
if (v === undefined || v === null) return undefined;
@@ -224,7 +241,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string" && x.trim())) fail(`"${k}" is a list of names`);
return (arr as string[]).map((x) => x.trim());
};
- const out: ReportDraftBody = { task: task as ReportDraftTask, article: article as string };
+ const out: ReportDraftBody = { task: task as ReportDraftTask, article: onProject ? "" : (article as string) };
const set = <K extends keyof ReportDraftBody>(k: K, v: ReportDraftBody[K] | undefined) => {
if (v !== undefined) out[k] = v;
};
@@ -273,7 +290,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
for (const k of ["fetch", "dryRun"] as const) {
if (b[k] === undefined || b[k] === null) continue;
if (typeof b[k] !== "boolean") fail(`"${k}" is true or false`);
- if (out.task !== REFRESH_TASK) fail(`"${k}" is a refresh's`);
+ if (out.task !== REFRESH_TASK && !(k === "dryRun" && onProject)) fail(`"${k}" is a refresh's`);
out[k] = b[k] as boolean;
}
const ids = list("ids");
@@ -341,6 +358,34 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build"] as const).filter((k) => out[k] !== undefined);
if (extra.length) fail(`a verdicts job reads the article's current report: it takes no ${extra.join(", ")}`);
}
+ // The clip finder's AI pass (release 36 lane D): a project, not an article.
+ 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) {
+ 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;
+ const proposals = list("proposals");
+ if (proposals !== undefined) {
+ if (!proposals.length || !proposals.every((p) => /^[A-Za-z0-9._:-]{1,64}$/.test(p))) fail('"proposals" is a list of proposal ids');
+ out.proposals = [...new Set(proposals)];
+ }
+ 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: {"items": [{"id", "label", "why", "score"}]}');
+ if (JSON.stringify(b.answers).length > 200_000) fail('"answers" is at most 200,000 characters');
+ out.answers = b.answers;
+ }
+ if (out.note && (out.answers !== undefined || out.proposals)) fail('an Ask ("note") takes no "answers" or "proposals"');
+ if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"');
+ if (out.dryRun && (out.note || out.answers !== undefined)) fail('"dryRun" plans a labels pass: no "note" or "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 clips-suggest job reads its project: it takes no ${extra.join(", ")}`);
+ }
if (out.task === REFRESH_TASK) {
const extra = (["question", "channels", "from", "to", "feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy"] as const).filter((k) => out[k] !== undefined);
if (extra.length) fail(`a refresh takes its question and scope from the iteration it refreshes — not ${extra.join(", ")}`);
@@ -379,7 +424,7 @@ function kindOf(task: GenerationTask): Iteration["kind"] {
}
const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" =>
- isStepTask(task) ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep";
+ isStepTask(task) || task === "clips-suggest" ? "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;
@@ -499,6 +544,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
return refuse((e as Error).message);
}
}
+ if (body.task === "clips-suggest") {
+ if (body.dryRun) return refuse('a clips-suggest plan is planClipsSuggestJob\'s ("dryRun": true at the ops route)');
+ try {
+ const { enqueueClipsSuggest } = await import("./clipsSuggest");
+ return await enqueueClipsSuggest(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 {
@@ -703,7 +757,8 @@ async function runReportDraft(
case "triage":
case "verdicts":
case "frames":
- // A refresh, a triage, verdict proposals and a frame scan are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts), never this one.
+ 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.
throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
input =
diff --git a/common/lib/clips/suggest.d.mts b/common/lib/clips/suggest.d.mts
@@ -0,0 +1,61 @@
+import type { Word } from "./clips.mjs";
+
+export const SUGGESTIONS_FILE: string;
+export const SUGGEST_PROMPT_VERSION: string;
+export const SUGGEST_LABEL_MAX_WORDS: number;
+export const SUGGEST_LABEL_MAX_CHARS: number;
+export const SUGGEST_WHY_MAX: number;
+export const SUGGEST_LINES_MAX_CHARS: number;
+export const SUGGEST_API_BATCH: number;
+export const ASK_REPLY_MAX: number;
+export const ASK_REACH_S: number;
+export const ASK_TRIM_MAX_MOVE_S: number;
+export const ASK_PROPOSAL_KINDS: readonly ["none", "trim", "merge", "cut"];
+export const SUGGEST_SYSTEM: string;
+export const ASK_SYSTEM: string;
+export const SUGGEST_ANSWER_SCHEMA: object;
+export const ASK_ANSWER_SCHEMA: object;
+
+export type SuggestionItem = { label: string; why: string; rank: number; score?: number; start?: number; end?: number };
+export type SuggestionsDoc = { model: string; at: string; proposedAt?: string | null; promptVersion?: string; items: Record<string, SuggestionItem> };
+export type SuggestionsState = { stale: boolean; why: string | null; passNewer: boolean; staleIds: string[]; missing: string[] };
+
+export function suggestionsFileOf(dir: string): string;
+export function parseSuggestionsDoc(raw: unknown): { doc: SuggestionsDoc } | { error: string };
+export function readSuggestions(dir: string): Promise<{ doc: SuggestionsDoc | null; error: string | null }>;
+export function writeSuggestions(dir: string, doc: SuggestionsDoc): Promise<string>;
+export function suggestionsState(doc: SuggestionsDoc | null, reactions: { proposals?: unknown[]; proposedAt?: string } | null): SuggestionsState;
+
+export type RoleLine = { role: "host" | "subject" | "other" | null; speaker: number | null; text: string };
+export type SuggestInput = { id: string; start: number; end: number; score: number | null; used: boolean; kinds: string[]; lines: RoleLine[] };
+
+export function wordsOfFile(raw: unknown): Word[];
+export function wordsFor(o?: { words?: unknown[] | null; cues?: { start: number; end: number; text?: string }[] | null }): Word[];
+export function roleLines(o: { words: Word[]; turns: unknown; speakers: unknown }, a: number, b: number, max?: number): RoleLine[];
+export function suggestItems(reactions: any, words: Word[], o?: { ids?: string[] | null }): SuggestInput[];
+export function itemText(it: SuggestInput): string;
+export function suggestPrompt(items: SuggestInput[]): { system: string; user: string };
+
+export type SuggestAnswerItem = { id: string; label: string; why: string; score: number };
+export function parseSuggestAnswer(
+ raw: unknown,
+ ids: string[],
+): { ok: true; items: SuggestAnswerItem[]; refused: { id: string; error: string }[]; missing: string[] } | { ok: false; error: string };
+export function suggestionsDocOf(o: { model: string; at: string; reactions: any; fresh: SuggestAnswerItem[]; prev?: SuggestionsDoc | null }): SuggestionsDoc;
+
+export type AskNote = { id: string; clip: string; text: string; status: string; replies: { author: string; text: string }[] };
+export type AskClip = { id: string; video: string; channel: string | null; cutStart: number; cutEnd: number; quote: string };
+export type AskClips = { clip: AskClip; prev: AskClip | null; next: AskClip | null; nextAny: AskClip | null };
+export type AskBasis = { cutStart: number; cutEnd: number };
+export type AskProposal =
+ | { kind: "trim"; clip: string; from: number; to: number; basis: AskBasis }
+ | { kind: "merge"; clip: string; with: string; basis: AskBasis }
+ | { kind: "cut"; clip: string; basis: AskBasis };
+
+export function askNoteOf(notesDoc: unknown, noteId: string): { note: AskNote } | { error: string };
+export function askClipsOf(manifest: unknown, clipId: string): AskClips | { error: string };
+export function askPrompt(o: { note: AskNote; clips: AskClips; words: Word[]; turns: unknown; speakers: unknown }): { system: string; user: string };
+export function parseAskAnswer(
+ raw: unknown,
+ clips: AskClips,
+): { ok: true; reply: string; proposal: AskProposal | null; dropped: string | null } | { ok: false; error: string };
diff --git a/common/lib/clips/suggest.mjs b/common/lib/clips/suggest.mjs
@@ -0,0 +1,474 @@
+// THE ASSISTANT'S LABELS (release 36 lane D): an OPTIONAL pass over the clip
+// finder's proposals that names each one, says in a line what makes it land,
+// and ranks them — and the assistant's answer to a comment on one clip.
+//
+// <project>/clip-suggestions.json
+// { model, at, proposedAt, promptVersion,
+// items: { <proposalId>: { label, why, rank, score, start, end } } }
+//
+// `label` is at most six words ("the badge reveal"), `why` one plain line,
+// `rank` 1 = the best of the file, `score` the model's 1–10 the rank is made
+// from (code ranks, so a pass in batches still ranks globally), `start`/`end`
+// the span that was labelled. `proposedAt` is the reactions.json pass the
+// labels were made over: a later pass makes the file STALE (shown, marked,
+// never hidden), and an item whose proposal moved or went is stale on its own.
+//
+// What this module is: the pure parts — the prompt a proposal becomes (its
+// words, each line marked HOST / SUBJECT / OTHER by the turns, and what the
+// finder heard), the reading of a model's answer (a malformed one is refused,
+// never repaired into a label), the ranking, the stale rule — and the file's
+// reader and its one writer (tmp + rename). The model call is the editor's
+// `report-draft` task `clips-suggest`
+// (common/lib/report/draft/tasks/clipsSuggest.ts); nothing here calls one.
+// It NEVER edits a clip or the manifest: the operator's click does, in the
+// clip editor.
+//
+// Plain ESM with a .d.mts beside it.
+import { readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { cleanTurns, cleanWords, roleMap, wordsFromCues, wordsIn } from "./clips.mjs";
+
+export const SUGGESTIONS_FILE = "clip-suggestions.json";
+export const SUGGEST_PROMPT_VERSION = "clips-suggest-1";
+/** A label's most words. */
+export const SUGGEST_LABEL_MAX_WORDS = 6;
+/** A label's most characters (six long words). */
+export const SUGGEST_LABEL_MAX_CHARS = 60;
+/** A why's most characters (one line). */
+export const SUGGEST_WHY_MAX = 200;
+/** The most characters of one proposal's words a prompt carries. */
+export const SUGGEST_LINES_MAX_CHARS = 900;
+/** Proposals per call on the Claude API (a local model's batches are fitted to its prompt cap). */
+export const SUGGEST_API_BATCH = 30;
+/** An Ask's reply: its most characters. */
+export const ASK_REPLY_MAX = 1200;
+/** An Ask reads this many seconds either side of the clip. */
+export const ASK_REACH_S = 20;
+/** A proposed trim may move an edge at most this far. */
+export const ASK_TRIM_MAX_MOVE_S = 30;
+export const ASK_PROPOSAL_KINDS = Object.freeze(["none", "trim", "merge", "cut"]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (n) => Math.round(n * 100) / 100;
+const clock = (s) => {
+ const t = Math.max(0, Math.floor(s));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const x = String(t % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${x}` : `${m}:${x}`;
+};
+const ROLE_WORD = { host: "HOST", subject: "SUBJECT", other: "OTHER" };
+
+export const suggestionsFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SUGGESTIONS_FILE);
+
+// ---- the file ----------------------------------------------------------------------
+
+/** A suggestions doc, checked: `{ doc }` or `{ error }`. Items that are not the shape are an error for the file. */
+export function parseSuggestionsDoc(raw) {
+ if (!isObj(raw)) return { error: "not an object" };
+ if (typeof raw.model !== "string" || !raw.model) return { error: "model is not a model id" };
+ if (typeof raw.at !== "string" || !raw.at) return { error: "at is not a time" };
+ if (!isObj(raw.items)) return { error: "items is not an object" };
+ const items = {};
+ for (const [id, it] of Object.entries(raw.items)) {
+ if (!isObj(it) || typeof it.label !== "string" || typeof it.why !== "string" || !Number.isInteger(it.rank) || it.rank < 1) return { error: `items.${id} is not { label, why, rank }` };
+ items[id] = {
+ label: it.label,
+ why: it.why,
+ rank: it.rank,
+ ...(num(it.score) ? { score: it.score } : {}),
+ ...(num(it.start) ? { start: it.start } : {}),
+ ...(num(it.end) ? { end: it.end } : {}),
+ };
+ }
+ return {
+ doc: {
+ model: raw.model,
+ at: raw.at,
+ ...(typeof raw.proposedAt === "string" ? { proposedAt: raw.proposedAt } : raw.proposedAt === null ? { proposedAt: null } : {}),
+ ...(typeof raw.promptVersion === "string" ? { promptVersion: raw.promptVersion } : {}),
+ items,
+ },
+ };
+}
+
+/** `<project>/clip-suggestions.json` as `{ doc, error }`: doc null when there is none (error null) or it is not one (error set). */
+export async function readSuggestions(dir) {
+ let text;
+ try {
+ text = await readFile(suggestionsFileOf(dir), "utf8");
+ } catch (err) {
+ if (err && err.code === "ENOENT") return { doc: null, error: null };
+ return { doc: null, error: String(err?.message ?? err) };
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ return { doc: null, error: `${SUGGESTIONS_FILE} is not JSON: ${err.message}` };
+ }
+ const r = parseSuggestionsDoc(raw);
+ return "error" in r ? { doc: null, error: `${SUGGESTIONS_FILE}: ${r.error}` } : { doc: r.doc, error: null };
+}
+
+/** THE writer: whole, tmp + rename, so a reader never sees half a file. Checked first. */
+export async function writeSuggestions(dir, doc) {
+ const r = parseSuggestionsDoc(doc);
+ if ("error" in r) throw new Error(`not a suggestions doc: ${r.error}`);
+ const file = suggestionsFileOf(dir);
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(r.doc, null, 1)}\n`);
+ await rename(tmp, file);
+ return file;
+}
+
+/**
+ * Whether the labels still describe the proposals: the file is stale when
+ * reactions.json's proposal pass is newer than the one labelled; an item is
+ * stale when its proposal is gone or its span moved (> 0.05 s). Stale is SHOWN.
+ * @returns {{ stale: boolean, why: string | null, passNewer: boolean, staleIds: string[], missing: string[] }}
+ */
+export function suggestionsState(doc, reactions) {
+ if (!doc) return { stale: false, why: null, passNewer: false, staleIds: [], missing: [] };
+ const proposals = new Map((reactions?.proposals ?? []).filter((p) => isObj(p) && typeof p.id === "string").map((p) => [p.id, p]));
+ const staleIds = [];
+ for (const [id, it] of Object.entries(doc.items ?? {})) {
+ const p = proposals.get(id);
+ if (!p) staleIds.push(id);
+ else if (num(it.start) && num(it.end) && (Math.abs(it.start - p.start) > 0.05 || Math.abs(it.end - p.end) > 0.05)) staleIds.push(id);
+ }
+ const missing = [...proposals.keys()].filter((id) => !doc.items?.[id]);
+ const passNewer = typeof reactions?.proposedAt === "string" && (typeof doc.proposedAt !== "string" || reactions.proposedAt > doc.proposedAt);
+ const why = passNewer
+ ? "the proposals were made again after these labels"
+ : staleIds.length
+ ? `${staleIds.length} proposal${staleIds.length === 1 ? "" : "s"} changed since these labels`
+ : null;
+ return { stale: !!why, why, passNewer, staleIds, missing };
+}
+
+// ---- what a proposal is, in words --------------------------------------------------
+
+/** A words list from what a words file may hold (`{ words: [...] }` or a bare array; `w`, `word` or `text`). */
+export function wordsOfFile(raw) {
+ const list = Array.isArray(raw) ? raw : Array.isArray(raw?.words) ? raw.words : [];
+ return cleanWords(list.map((w) => (isObj(w) ? { ...w, w: String(w.w ?? w.word ?? w.text ?? "") } : w)));
+}
+
+/** The words of a recording a pass reads: the project's word timings, else the cues spread over their words. */
+export function wordsFor({ words = null, cues = null } = {}) {
+ if (Array.isArray(words) && words.length) return wordsOfFile(words);
+ return wordsFromCues(Array.isArray(cues) ? cues : []);
+}
+
+/**
+ * The words of [a, b] as lines, each marked by who speaks (the turn holding
+ * the word's middle; a word in no turn joins the line it follows), at most
+ * `max` characters in all.
+ * @returns {{ role: "host" | "subject" | "other" | null, speaker: number | null, text: string }[]}
+ */
+export function roleLines({ words, turns, speakers }, a, b, max = SUGGEST_LINES_MAX_CHARS) {
+ const roles = roleMap(Array.isArray(speakers) ? speakers.filter(isObj) : []);
+ const ts = cleanTurns(turns).filter((t) => t.end > a && t.start < b);
+ const lines = [];
+ let used = 0;
+ for (const w of wordsIn(words, a, b)) {
+ const mid = (w.start + w.end) / 2;
+ const t = ts.find((x) => x.start <= mid && mid <= x.end) ?? null;
+ const speaker = t ? t.speaker : (lines.at(-1)?.speaker ?? null);
+ const role = speaker === null ? null : (roles.get(speaker) ?? "other");
+ if (used + w.w.length + 1 > max) {
+ if (lines.length) lines.at(-1).text += " …";
+ break;
+ }
+ used += w.w.length + 1;
+ const last = lines.at(-1);
+ if (last && last.speaker === speaker) last.text += ` ${w.w}`;
+ else lines.push({ role, speaker, text: w.w });
+ }
+ return lines;
+}
+
+const lineText = (l) => `${l.role ? ROLE_WORD[l.role] ?? "OTHER" : "?"}: ${l.text}`;
+
+/**
+ * Every proposal of a reactions doc as the prompt reads it: its span, what the
+ * finder heard (the moments' kinds), the finder's score and why, and its lines.
+ * `ids`: only these proposals.
+ */
+export function suggestItems(reactions, words, { ids = null } = {}) {
+ const moments = new Map((reactions?.moments ?? []).filter(isObj).map((m) => [m.id, m]));
+ const want = ids ? new Set(ids) : null;
+ return (reactions?.proposals ?? [])
+ .filter((p) => isObj(p) && typeof p.id === "string" && num(p.start) && num(p.end) && p.end > p.start && (!want || want.has(p.id)))
+ .map((p) => ({
+ id: p.id,
+ start: p.start,
+ end: p.end,
+ score: num(p.score) ? p.score : null,
+ used: !!p.used,
+ kinds: [...new Set((p.moments ?? []).map((m) => moments.get(m)?.kind).filter((k) => typeof k === "string"))],
+ lines: roleLines({ words, turns: reactions?.turns, speakers: reactions?.speakers }, p.start, p.end),
+ }));
+}
+
+export const SUGGEST_SYSTEM =
+ "You read moments from a livestream in which a HOST reacts to a video (the SUBJECT speaks in the video). " +
+ "Each moment is a clip the clip finder proposed: its words, each line marked with who speaks (HOST, SUBJECT, OTHER), " +
+ 'and what the finder heard there ("laugh": someone laughed; "chat": the stream\'s chat laughed; "comment": the host spoke over the video). ' +
+ "For every moment give: label, at most six words naming it like a chapter title (for example: the badge reveal); " +
+ "why, one plain sentence on what makes it land (a joke, a telling line, a reaction) or why it falls flat; " +
+ "score, a whole number from 1 (skip it) to 10 (the best clip of the stream), judged on the clip alone. " +
+ "Use only what is in the words. Plain words, no quotation marks around the label, no hashtags, no emoji.";
+
+/** One moment as the prompt shows it. */
+export function itemText(it) {
+ const heard = it.kinds.length ? it.kinds.join(", ") : "nothing marked";
+ const lines = it.lines.length ? it.lines.map(lineText).join("\n") : "(no words)";
+ return `[${it.id}] ${clock(it.start)}–${clock(it.end)} (${Math.round(it.end - it.start)} s) · heard: ${heard}\n${lines}`;
+}
+
+/** The prompt for a batch of moments. */
+export function suggestPrompt(items) {
+ return {
+ system: SUGGEST_SYSTEM,
+ user: `${items.length} moment${items.length === 1 ? "" : "s"}. Answer every id once.\n\n${items.map(itemText).join("\n\n")}`,
+ };
+}
+
+export const SUGGEST_ANSWER_SCHEMA = Object.freeze({
+ type: "object",
+ properties: {
+ items: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "The moment's id, as given in brackets." },
+ label: { type: "string", description: "At most six words naming the moment." },
+ why: { type: "string", description: "One plain sentence." },
+ score: { type: "integer", description: "1 (skip it) to 10 (the best clip of the stream)." },
+ },
+ required: ["id", "label", "why", "score"],
+ },
+ },
+ },
+ required: ["items"],
+});
+
+const oneLine = (s) => String(s).replace(/\s+/g, " ").trim();
+const words = (s) => s.split(" ").filter(Boolean).length;
+
+/**
+ * A model's answer for a batch, read. `{ ok: false, error }` when it is not the
+ * shape at all (the batch is refused). Otherwise each asked id's label, or a
+ * refusal of that one item (a label over six words, an empty one, a score
+ * outside 1–10, an id never asked): REFUSED, never cut down to fit.
+ * @param {unknown} raw
+ * @param {string[]} ids the ids asked
+ * @returns {{ ok: true, items: { id: string, label: string, why: string, score: number }[], refused: { id: string, error: string }[], missing: string[] } | { ok: false, error: string }}
+ */
+export function parseSuggestAnswer(raw, ids) {
+ if (!isObj(raw) || !Array.isArray(raw.items)) return { ok: false, error: "the answer is not { items: [...] }" };
+ const asked = new Set(ids);
+ const seen = new Set();
+ const items = [];
+ const refused = [];
+ for (const it of raw.items) {
+ if (!isObj(it) || typeof it.id !== "string") {
+ refused.push({ id: "?", error: "an item without an id" });
+ continue;
+ }
+ const id = it.id.trim().replace(/^\[|\]$/g, "");
+ if (!asked.has(id)) {
+ refused.push({ id, error: "an id that was not asked" });
+ continue;
+ }
+ if (seen.has(id)) continue;
+ const label = typeof it.label === "string" ? oneLine(it.label).replace(/^["'“‘]+|["'”’.]+$/g, "") : "";
+ const why = typeof it.why === "string" ? oneLine(it.why) : "";
+ const score = typeof it.score === "number" ? it.score : typeof it.score === "string" && /^\d+(\.\d+)?$/.test(it.score.trim()) ? Number(it.score) : NaN;
+ let error = null;
+ if (!label) error = "an empty label";
+ else if (words(label) > SUGGEST_LABEL_MAX_WORDS) error = `a label of ${words(label)} words (at most ${SUGGEST_LABEL_MAX_WORDS})`;
+ else if (label.length > SUGGEST_LABEL_MAX_CHARS) error = `a label of ${label.length} characters`;
+ else if (!why) error = "no why";
+ else if (!Number.isFinite(score) || score < 1 || score > 10) error = `a score of ${JSON.stringify(it.score)} (1 to 10)`;
+ if (error) {
+ refused.push({ id, error });
+ continue;
+ }
+ seen.add(id);
+ items.push({ id, label, why: why.length > SUGGEST_WHY_MAX ? `${why.slice(0, SUGGEST_WHY_MAX - 1).replace(/\s+\S*$/, "")}…` : why, score: Math.round(score) });
+ }
+ const missing = ids.filter((id) => !seen.has(id) && !refused.some((r) => r.id === id));
+ return { ok: true, items, refused, missing };
+}
+
+/**
+ * The file a pass writes: the fresh labels over what the old file still holds
+ * CURRENT (an item whose proposal is gone or moved is dropped), every item
+ * ranked anew — by the model's score, then the finder's, then time.
+ * @param {{ model: string, at: string, reactions: any, fresh: { id: string, label: string, why: string, score: number }[], prev?: any }} o
+ */
+export function suggestionsDocOf({ model, at, reactions, fresh, prev = null }) {
+ const proposals = new Map((reactions?.proposals ?? []).filter((p) => isObj(p) && typeof p.id === "string").map((p) => [p.id, p]));
+ const merged = new Map();
+ const staleIds = new Set(prev ? suggestionsState(prev, reactions).staleIds : []);
+ for (const [id, it] of Object.entries(prev?.items ?? {})) {
+ if (!proposals.has(id) || staleIds.has(id) || !num(it.score)) continue;
+ merged.set(id, { label: it.label, why: it.why, score: it.score });
+ }
+ for (const f of fresh) if (proposals.has(f.id)) merged.set(f.id, { label: f.label, why: f.why, score: f.score });
+ const order = [...merged.entries()].sort(([a, x], [b, y]) => {
+ const pa = proposals.get(a);
+ const pb = proposals.get(b);
+ return y.score - x.score || (pb.score ?? 0) - (pa.score ?? 0) || pa.start - pb.start || a.localeCompare(b);
+ });
+ const items = {};
+ order.forEach(([id, it], i) => {
+ const p = proposals.get(id);
+ items[id] = { label: it.label, why: it.why, rank: i + 1, score: it.score, start: r2(p.start), end: r2(p.end) };
+ });
+ return {
+ model,
+ at,
+ proposedAt: typeof reactions?.proposedAt === "string" ? reactions.proposedAt : null,
+ promptVersion: SUGGEST_PROMPT_VERSION,
+ items,
+ };
+}
+
+// ---- Ask the assistant (a comment on one clip) -------------------------------------
+
+/** The note an Ask answers, from a notes doc: an open note anchored to one clip. */
+export function askNoteOf(notesDoc, noteId) {
+ const n = (isObj(notesDoc) && Array.isArray(notesDoc.notes) ? notesDoc.notes : []).find((x) => isObj(x) && x.id === noteId);
+ if (!n) return { error: `no note ${noteId}` };
+ if (!isObj(n.anchor) || n.anchor.kind !== "entry" || typeof n.anchor.entry !== "string") return { error: `note ${noteId} is not on a clip` };
+ return {
+ note: {
+ id: n.id,
+ clip: n.anchor.entry,
+ text: String(n.text ?? ""),
+ status: String(n.status ?? "open"),
+ replies: (Array.isArray(n.replies) ? n.replies : []).filter(isObj).map((r) => ({ author: String(r.author ?? ""), text: String(r.text ?? "") })),
+ },
+ };
+}
+
+const cutOf = (e) => ({ cutStart: num(e.cutStart) ? e.cutStart : e.start, cutEnd: num(e.cutEnd) ? e.cutEnd : e.end });
+
+/**
+ * The clip a note is on, its neighbours on the timeline (the next one only
+ * when it is a clip of the same recording — what a merge needs), from the
+ * manifest.
+ */
+export function askClipsOf(manifest, clipId) {
+ const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const i = timeline.findIndex((e) => isObj(e) && e.type === "clip" && e.id === clipId);
+ if (i < 0) return { error: `no clip ${clipId} in the cut` };
+ const clip = timeline[i];
+ if (!num(clip.start) || !num(clip.end)) return { error: `${clipId} has no span` };
+ const at = (e) => (isObj(e) && e.type === "clip" && num(e.start) && num(e.end) ? { id: e.id, video: e.video, channel: e.channel ?? null, ...cutOf(e), quote: typeof e.quote === "string" ? e.quote : "" } : null);
+ const prev = at(timeline[i - 1]);
+ const nx = at(timeline[i + 1]);
+ const same = (o) => o && o.video === clip.video && (o.channel ?? null) === (clip.channel ?? null);
+ return { clip: at(clip), prev: same(prev) ? prev : null, next: same(nx) ? nx : null, nextAny: nx };
+}
+
+export const ASK_SYSTEM =
+ "You help a person cut highlight clips from a livestream in which a HOST reacts to a video (the SUBJECT). " +
+ "The person left a comment on one clip. Read it, the clip's words (each line marked by speaker, with times in seconds on the recording), " +
+ "and the clips either side, and answer the comment in a few plain sentences. " +
+ "When a concrete edit would do what the comment asks, propose ONE: " +
+ '"trim" with from and to (the clip\'s new start and end, in seconds on the recording, on a pause between words), ' +
+ '"merge" (join it with the next clip), or "cut" (leave the clip out). Otherwise "none". ' +
+ "You only propose: the person applies it. Use only what is in the words.";
+
+const timedLines = ({ words, turns, speakers }, a, b) => {
+ const roles = roleMap(Array.isArray(speakers) ? speakers.filter(isObj) : []);
+ const ts = cleanTurns(turns).filter((t) => t.end > a && t.start < b);
+ const out = [];
+ for (const w of wordsIn(words, a, b)) {
+ const mid = (w.start + w.end) / 2;
+ const t = ts.find((x) => x.start <= mid && mid <= x.end) ?? null;
+ const speaker = t ? t.speaker : (out.at(-1)?.speaker ?? null);
+ const last = out.at(-1);
+ if (last && last.speaker === speaker && w.start - last.end < 1.2) {
+ last.text += ` ${w.w}`;
+ last.end = w.end;
+ } else out.push({ speaker, role: speaker === null ? null : (roles.get(speaker) ?? "other"), start: w.start, end: w.end, text: w.w });
+ }
+ return out.map((l) => `[${l.start.toFixed(1)}–${l.end.toFixed(1)}] ${l.role ? ROLE_WORD[l.role] ?? "OTHER" : "?"}: ${l.text}`);
+};
+
+/** The prompt an Ask sends. */
+export function askPrompt({ note, clips, words, turns, speakers }) {
+ const { clip, prev, next } = clips;
+ const from = Math.max(0, clip.cutStart - ASK_REACH_S);
+ const to = clip.cutEnd + ASK_REACH_S;
+ const thread = note.replies.length ? `\nThe thread so far:\n${note.replies.map((r) => `- ${r.author}: ${oneLine(r.text)}`).join("\n")}` : "";
+ const user = [
+ `The comment on clip ${clip.id} (${clip.cutStart.toFixed(1)}–${clip.cutEnd.toFixed(1)} s): ${oneLine(note.text)}${thread}`,
+ prev ? `The clip before: ${prev.id}, ${prev.cutStart.toFixed(1)}–${prev.cutEnd.toFixed(1)} s.` : "No clip of this recording comes before it.",
+ next ? `The next clip: ${next.id}, ${next.cutStart.toFixed(1)}–${next.cutEnd.toFixed(1)} s (a merge joins the two).` : "No clip of this recording follows it: a merge is not possible.",
+ `The words from ${from.toFixed(1)} to ${to.toFixed(1)} s (the clip is ${clip.cutStart.toFixed(1)}–${clip.cutEnd.toFixed(1)}):`,
+ timedLines({ words, turns, speakers }, from, to).join("\n") || "(no words)",
+ ].join("\n\n");
+ return { system: ASK_SYSTEM, user };
+}
+
+export const ASK_ANSWER_SCHEMA = Object.freeze({
+ type: "object",
+ properties: {
+ reply: { type: "string", description: "The answer to the comment, a few plain sentences." },
+ proposal: {
+ type: "object",
+ properties: {
+ kind: { type: "string", enum: [...ASK_PROPOSAL_KINDS] },
+ from: { type: "number", description: "A trim's new start, seconds on the recording (0 otherwise)." },
+ to: { type: "number", description: "A trim's new end, seconds on the recording (0 otherwise)." },
+ },
+ required: ["kind", "from", "to"],
+ },
+ },
+ required: ["reply", "proposal"],
+});
+
+/**
+ * An Ask's answer, read: the reply, and the proposal when it is one the clip
+ * editor can perform (a trim inside reach and at least half a second; a merge
+ * only with a next clip of the same recording). A proposal that is not is
+ * dropped with a reason (the reply still goes); a reply that is not text is
+ * refused.
+ * @returns {{ ok: true, reply: string, proposal: null | { 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} }, dropped: string | null } | { ok: false, error: string }}
+ */
+export function parseAskAnswer(raw, clips) {
+ if (!isObj(raw) || typeof raw.reply !== "string" || !raw.reply.trim()) return { ok: false, error: "the answer is not { reply, proposal }" };
+ const reply = raw.reply.trim().replace(/\n{3,}/g, "\n\n");
+ const clipped = reply.length > ASK_REPLY_MAX ? `${reply.slice(0, ASK_REPLY_MAX - 1).replace(/\s+\S*$/, "")}…` : reply;
+ const p = isObj(raw.proposal) ? raw.proposal : null;
+ const kind = p && typeof p.kind === "string" ? p.kind : "none";
+ const { clip, next } = clips;
+ const basis = { cutStart: clip.cutStart, cutEnd: clip.cutEnd };
+ let proposal = null;
+ let dropped = null;
+ if (kind === "trim") {
+ const from = Number(p.from);
+ const to = Number(p.to);
+ if (!Number.isFinite(from) || !Number.isFinite(to)) dropped = "a trim without from and to";
+ else if (to - from < 0.5) dropped = `a trim of ${(to - from).toFixed(2)} s (at least half a second)`;
+ else if (from < 0) dropped = "a trim before the recording";
+ else if (Math.abs(from - clip.cutStart) > ASK_TRIM_MAX_MOVE_S || Math.abs(to - clip.cutEnd) > ASK_TRIM_MAX_MOVE_S) dropped = `a trim moving an edge more than ${ASK_TRIM_MAX_MOVE_S} s`;
+ else if (Math.abs(from - clip.cutStart) < 0.05 && Math.abs(to - clip.cutEnd) < 0.05) dropped = "a trim that leaves the clip where it is";
+ else proposal = { kind: "trim", clip: clip.id, from: r2(from), to: r2(to), basis };
+ } else if (kind === "merge") {
+ if (!next) dropped = "a merge, with no next clip of this recording";
+ else proposal = { kind: "merge", clip: clip.id, with: next.id, basis };
+ } else if (kind === "cut") {
+ proposal = { kind: "cut", clip: clip.id, basis };
+ } else if (kind !== "none") dropped = `a proposal of kind ${JSON.stringify(kind)}`;
+ return { ok: true, reply: clipped, proposal, dropped };
+}
diff --git a/common/lib/clips/suggest.test.ts b/common/lib/clips/suggest.test.ts
@@ -0,0 +1,182 @@
+// Release 36 lane D: the assistant's labels and its answer to a comment — the
+// pure parts (lib/clips/suggest.mjs) over the synthetic reactions project.
+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 {
+ askClipsOf,
+ askNoteOf,
+ askPrompt,
+ parseAskAnswer,
+ parseSuggestAnswer,
+ readSuggestions,
+ roleLines,
+ suggestionsDocOf,
+ suggestionsState,
+ suggestItems,
+ suggestPrompt,
+ wordsOfFile,
+ writeSuggestions,
+} from "./suggest.mjs";
+import { labelAnswer, reactionProject, writeReactionProject, PROJECT_NOTE } from "../../testing/clips/reactionProject.mjs";
+
+const fixture = () => {
+ const p = reactionProject();
+ return { ...p, wordList: wordsOfFile(p.words) };
+};
+
+test("a proposal in words: each line marked by who speaks, what the finder heard, capped", () => {
+ const { reactions, wordList } = fixture();
+ const items = suggestItems(reactions, wordList);
+ assert.deepEqual(items.map((i) => i.id), ["p001", "p002", "p003", "p004", "p005"]);
+ const p001 = items[0]!;
+ assert.deepEqual(p001.kinds, ["laugh"]);
+ // 88–99: the subject talks to 95, the host laughs and talks after.
+ assert.deepEqual(p001.lines.map((l) => l.role), ["subject", "host"]);
+ assert.match(p001.lines[1]!.text, /^haha/);
+ assert.deepEqual(items.find((i) => i.id === "p005")!.kinds, ["chat"]);
+ // Only the ids asked.
+ assert.deepEqual(suggestItems(reactions, wordList, { ids: ["p003"] }).map((i) => i.id), ["p003"]);
+ // A long span is cut at the cap, with an ellipsis.
+ const long = roleLines({ words: wordList, turns: reactions.turns, speakers: reactions.speakers }, 0, 600, 80);
+ assert.ok(long.map((l) => l.text).join(" ").length <= 84);
+ assert.match(long.at(-1)!.text, /…$/);
+ const pr = suggestPrompt(items.slice(0, 2));
+ assert.match(pr.user, /\[p001\] 1:28–1:39 \(11 s\) · heard: laugh\nSUBJECT: n\d+/);
+ assert.match(pr.user, /\nHOST: haha/);
+ assert.match(pr.system, /at most six words/);
+});
+
+test("a model's answer: labels kept, a malformed answer refused, a label over six words refused (never cut down)", () => {
+ const ids = ["p001", "p002", "p003"];
+ assert.deepEqual(parseSuggestAnswer({ labels: [] }, ids), { ok: false, error: "the answer is not { items: [...] }" });
+ assert.equal(parseSuggestAnswer(null, ids).ok, false);
+ const r = parseSuggestAnswer(
+ {
+ items: [
+ { id: "p001", label: '"The badge reveal."', why: "The host\nloses it.", score: 9 },
+ { id: "[p002]", label: "a label with far too many words in it", why: "x", score: 5 },
+ { id: "p003", label: "flat", why: "Nothing lands.", score: 11 },
+ { id: "p009", label: "never asked", why: "x", score: 3 },
+ { id: "p001", label: "a second answer", why: "x", score: 1 },
+ ],
+ },
+ ids,
+ );
+ assert.ok(r.ok);
+ assert.deepEqual(r.items, [{ id: "p001", label: "The badge reveal", why: "The host loses it.", score: 9 }]);
+ assert.deepEqual(
+ r.refused.map((x) => [x.id, x.error]),
+ [
+ ["p002", "a label of 9 words (at most 6)"],
+ ["p003", "a score of 11 (1 to 10)"],
+ ["p009", "an id that was not asked"],
+ ],
+ );
+ assert.deepEqual(r.missing, []);
+ const partial = parseSuggestAnswer({ items: [{ id: "p001", label: "one", why: "w", score: 2 }] }, ids);
+ assert.ok(partial.ok);
+ assert.deepEqual(partial.missing, ["p002", "p003"]);
+});
+
+test("the file: ranked by the model's score; merged over the old file's current labels; stale when the proposals moved", async () => {
+ const { reactions } = fixture();
+ const at = "2026-10-19T01:00:00.000Z";
+ const first = suggestionsDocOf({ model: "qwen3:8b", at, reactions, fresh: labelAnswer(["p001", "p002", "p003", "p004", "p005"]).items });
+ // labelAnswer scores 2, 3, 4, 5, 6: the last is the best.
+ assert.deepEqual(Object.entries(first.items).map(([id, it]) => [id, it.rank]), [["p005", 1], ["p004", 2], ["p003", 3], ["p002", 4], ["p001", 5]]);
+ assert.equal(first.proposedAt, reactions.proposedAt);
+ assert.deepEqual(first.items.p001, { label: "the p001 moment", why: "Something happens in p001.", rank: 5, score: 2, start: 88, end: 99 });
+ assert.deepEqual(suggestionsState(first, reactions), { stale: false, why: null, passNewer: false, staleIds: [], missing: [] });
+
+ // A tie on the model's score goes to the finder's score.
+ const tie = suggestionsDocOf({ model: "m", at, reactions, fresh: ["p003", "p001"].map((id) => ({ id, label: id, why: "w", score: 5 })) });
+ assert.deepEqual(Object.keys(tie.items), ["p001", "p003"]);
+
+ // A later proposal pass: the file is stale; a proposal moved: that one is.
+ const later = { ...reactions, proposedAt: "2026-10-20T00:00:00.000Z" };
+ assert.deepEqual(suggestionsState(first, later), { stale: true, why: "the proposals were made again after these labels", passNewer: true, staleIds: [], missing: [] });
+ const moved = { ...reactions, proposals: reactions.proposals.map((p: { id: string; start: number }) => (p.id === "p002" ? { ...p, start: p.start + 2 } : p)).filter((p: { id: string }) => p.id !== "p005") };
+ assert.deepEqual(suggestionsState(first, moved), { stale: true, why: "2 proposals changed since these labels", passNewer: false, staleIds: ["p005", "p002"], missing: [] });
+
+ // Labelling only p003 again keeps the others' current labels and drops the stale ones.
+ const again = suggestionsDocOf({ model: "claude-sonnet-5-5", at, reactions: moved, fresh: [{ id: "p003", label: "now the best", why: "w", score: 10 }], prev: first });
+ assert.deepEqual(Object.keys(again.items), ["p003", "p004", "p001"]);
+ assert.equal(again.items.p003!.rank, 1);
+ assert.equal(again.model, "claude-sonnet-5-5");
+
+ // The writer refuses what is not the shape; the reader is lenient about absence, not about junk.
+ const dir = await mkdtemp(path.join(os.tmpdir(), "clip-suggest-"));
+ try {
+ assert.deepEqual(await readSuggestions(dir), { doc: null, error: null });
+ await assert.rejects(writeSuggestions(dir, { model: "m", at, items: { p001: { label: "x", why: "y", rank: 0 } } }), /not a suggestions doc/);
+ await writeSuggestions(dir, first);
+ assert.deepEqual((await readSuggestions(dir)).doc, first);
+ assert.match(await readFile(path.join(dir, "clip-suggestions.json"), "utf8"), /"promptVersion": "clips-suggest-1"/);
+ await writeFile(path.join(dir, "clip-suggestions.json"), "{");
+ assert.match(String((await readSuggestions(dir)).error), /not JSON/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("Ask: the note on a clip, the clip and its next one of the same recording, the prompt with times", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "clip-ask-"));
+ try {
+ const { manifest } = writeReactionProject(dir, { note: { clip: "r002", text: "start it where he laughs" } });
+ const notes = JSON.parse(await readFile(path.join(dir, "notes.json"), "utf8"));
+ const n = askNoteOf(notes, PROJECT_NOTE);
+ assert.ok("note" in n);
+ assert.equal(n.note.clip, "r002");
+ assert.deepEqual(askNoteOf(notes, "n_none0000"), { error: "no note n_none0000" });
+ const clips = askClipsOf(manifest, "r002");
+ assert.ok(!("error" in clips));
+ assert.deepEqual([clips.prev?.id, clips.clip.id, clips.next?.id], ["r001", "r002", "r003"]);
+ // A card between, or another recording: no merge.
+ const other = { ...manifest, timeline: [manifest.timeline[1], { ...manifest.timeline[2], video: "other" }] };
+ const o = askClipsOf(other, "r002");
+ assert.ok(!("error" in o) && o.next === null && o.nextAny?.id === "r003");
+ const { reactions, words } = reactionProject();
+ const pr = askPrompt({ note: n.note, clips, words: wordsOfFile(words), turns: reactions.turns, speakers: reactions.speakers });
+ assert.match(pr.user, /The comment on clip r002 \(88\.0–99\.0 s\): start it where he laughs/);
+ assert.match(pr.user, /The next clip: r003, 333\.0–344\.0 s/);
+ assert.match(pr.user, /\[95\.\d–\d+\.\d\] HOST: haha/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("Ask's answer: a trim within reach kept, one too far dropped, a merge only with a next clip, a malformed answer refused", () => {
+ const { manifest } = reactionProject();
+ const clips = askClipsOf(manifest, "r002");
+ assert.ok(!("error" in clips));
+ const basis = { cutStart: 88, cutEnd: 99 };
+ assert.deepEqual(parseAskAnswer({ reply: "Start at the laugh.", proposal: { kind: "trim", from: 94.6, to: 99 } }, clips), {
+ ok: true,
+ reply: "Start at the laugh.",
+ proposal: { kind: "trim", clip: "r002", from: 94.6, to: 99, basis },
+ dropped: null,
+ });
+ const far = parseAskAnswer({ reply: "x", proposal: { kind: "trim", from: 20, to: 99 } }, clips);
+ assert.ok(far.ok && far.proposal === null && /more than 30 s/.test(String(far.dropped)));
+ const same = parseAskAnswer({ reply: "x", proposal: { kind: "trim", from: 88, to: 99 } }, clips);
+ assert.ok(same.ok && same.proposal === null && /leaves the clip where it is/.test(String(same.dropped)));
+ assert.deepEqual(parseAskAnswer({ reply: "Join them.", proposal: { kind: "merge", from: 0, to: 0 } }, clips), {
+ ok: true,
+ reply: "Join them.",
+ proposal: { kind: "merge", clip: "r002", with: "r003", basis },
+ dropped: null,
+ });
+ const last = askClipsOf(manifest, "r003");
+ assert.ok(!("error" in last));
+ const noNext = parseAskAnswer({ reply: "Join them.", proposal: { kind: "merge" } }, last);
+ assert.ok(noNext.ok && noNext.proposal === null && /no next clip/.test(String(noNext.dropped)));
+ const cut = parseAskAnswer({ reply: "Leave it out.", proposal: { kind: "cut", from: 0, to: 0 } }, clips);
+ assert.ok(cut.ok && cut.proposal?.kind === "cut");
+ const none = parseAskAnswer({ reply: "It works.", proposal: { kind: "none", from: 0, to: 0 } }, clips);
+ assert.ok(none.ok && none.proposal === null && none.dropped === null);
+ assert.deepEqual(parseAskAnswer({ answer: "x" }, clips), { ok: false, error: "the answer is not { reply, proposal }" });
+ assert.equal(parseAskAnswer({ reply: " " }, clips).ok, false);
+});
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -151,3 +151,17 @@ test("the frame scan (release 30): its own route and settings; a file from befor
assert.equal(g.routes.frames, GENERATION_PRESETS[p].frames);
}
});
+
+test("the clip finder's labels (release 36 lane D): routed like a media draft; a file from before keeps its preset", () => {
+ assert.ok((GENERATION_TASKS as readonly string[]).includes("clips-suggest"));
+ assert.deepEqual(
+ (["code", "balanced", "api", "local"] as const).map((p) => GENERATION_PRESETS[p]["clips-suggest"]),
+ ["code", "local", "api", "local"],
+ );
+ for (const p of ["code", "balanced", "api", "local"] as const) {
+ const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "clips-suggest").map((t) => [t, GENERATION_PRESETS[p][t]]));
+ const g = sanitizeGeneration({ routes });
+ assert.equal(g.preset, p);
+ assert.equal(g.routes["clips-suggest"], GENERATION_PRESETS[p]["clips-suggest"]);
+ }
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -24,7 +24,12 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri
// `frames` (release 30, lane P): a frame scan's readings of a saved stream's
// frames by a vision model — no article, no iteration: a sidecar beside the
// video. `api` or `local`; `code` = none unless the job names a model.
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames"] as const;
+// `clips-suggest` (release 36 lane D): the clip finder's optional AI pass —
+// labels and a rank for a reactions project's proposals
+// (`<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;
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"];
@@ -36,12 +41,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" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code" },
// 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" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local" },
+ 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" },
} 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[];
@@ -215,6 +220,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
social: "A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code.",
frames:
"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`).",
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/clipsSuggest.ts b/common/lib/report/draft/tasks/clipsSuggest.ts
@@ -0,0 +1,346 @@
+// THE `clips-suggest` TASK (release 36 lane D): the clip finder's OPTIONAL
+// AI pass, in two kinds.
+//
+// labels every proposal of a reactions project (or the ones named) → a
+// label (≤ 6 words), a why (one line), a rank (1 = best) — into
+// `<project>/clip-suggestions.json` through its one writer
+// (lib/clips/suggest.mjs). The proposals go in batches (30 a call
+// on the Claude API; fitted to the prompt cap on a local model);
+// the model scores each 1–10 and CODE ranks them, so a pass in
+// batches still ranks the whole file. A batch whose answer is not
+// the shape is refused (its proposals stay unlabelled, named in
+// the log); a single label over six words is refused, never cut.
+// ask one comment (a note on a clip, notes.json): the note, the clip's
+// words labelled by speaker, ±20 s around it and the clips either
+// side → a reply, and at most one concrete proposal the clip editor
+// can perform (a trim {from, to}, a merge with the next clip, a
+// cut). The reply is handed to `postReply` (the controller posts it
+// to umtool's notes as the agent's); the proposal is NEVER applied
+// here — the operator's Apply does it.
+//
+// It never writes the manifest, a clip, notes.json or reactions.json. An API
+// model is held to `maxUsd` (each call's estimate checked against the spend so
+// far: past it the run ends `capped`, keeping what it labelled).
+//
+// The words: the project's word timings (reactions.json `source.words`, else
+// words.json), else the recording's cues from the corpus (`cuesOf`), spread
+// over their words.
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm";
+import type { CuesOf } from "../../convertShared";
+import { readReactions, type ReactionsDoc } from "../../../clips/reactions.mjs";
+import type { Word } from "../../../clips/clips.mjs";
+import {
+ ASK_ANSWER_SCHEMA,
+ askClipsOf,
+ askNoteOf,
+ askPrompt,
+ parseAskAnswer,
+ parseSuggestAnswer,
+ readSuggestions,
+ SUGGEST_ANSWER_SCHEMA,
+ SUGGEST_API_BATCH,
+ SUGGEST_PROMPT_VERSION,
+ suggestionsDocOf,
+ suggestItems,
+ suggestPrompt,
+ wordsFor,
+ wordsOfFile,
+ writeSuggestions,
+ type AskClips,
+ type AskNote,
+ type AskProposal,
+ type SuggestAnswerItem,
+ type SuggestInput,
+} from "../../../clips/suggest.mjs";
+import { PROMPT_CAP_TOKENS } from "../../../llm/ollama";
+
+export const CLIPS_SUGGEST_TASK = "clips-suggest" as const;
+/** The `model` a Claude Code session's answers are written under (the `code` route). */
+export const CODE_MODEL = "claude-code";
+const LOCAL_CAP = PROMPT_CAP_TOKENS - 400;
+const ANSWER_TOKENS_PER_ITEM = 60;
+const ASK_ANSWER_TOKENS = 500;
+
+export class ClipsSuggestRefusal extends Error {}
+
+export type ClipsSuggestDeps = {
+ llm: LlmConfig;
+ // The recording's cues, when the project holds no word timings.
+ cuesOf?: CuesOf;
+ // The model, stubbed (tests).
+ ask?: <T>(system: string, user: string, schema: object, model: string, maxTokens: number) => Promise<T>;
+ log?: (line: string) => void;
+ progress?: (done: number, total: number) => void;
+ signal?: AbortSignal;
+ now?: () => Date;
+ localCapTokens?: number;
+};
+
+export type ClipsProject = { dir: string; reactions: ReactionsDoc; words: Word[]; wordsFrom: string };
+
+const isRel = (p: unknown): p is string => typeof p === "string" && !!p && !path.isAbsolute(p) && !p.split(/[\\/]/).some((s) => s === ".." || s === "");
+
+/** A reactions project: its reactions.json (refused without one) and the words its pass reads. */
+export async function loadClipsProject(dir: string, deps: Pick<ClipsSuggestDeps, "cuesOf">): Promise<ClipsProject> {
+ const reactions = (await readReactions(dir)) as ReactionsDoc | null;
+ if (!reactions) throw new ClipsSuggestRefusal(`${dir} holds no reactions.json: the clip finder has not run there (umtool's Find the clips)`);
+ const rel = isRel(reactions.source?.words) ? reactions.source.words : "words.json";
+ try {
+ const words = wordsOfFile(JSON.parse(await readFile(path.join(dir, rel), "utf8")));
+ if (words.length) return { dir, reactions, words, wordsFrom: rel };
+ } catch {
+ // no word timings in the project: the cues
+ }
+ const { channel, video } = reactions.source ?? ({} as ReactionsDoc["source"]);
+ const cues = channel && video && deps.cuesOf ? await deps.cuesOf(channel, video).catch(() => null) : null;
+ return { dir, reactions, words: wordsFor({ cues: cues ? [...cues] : [] }), wordsFrom: cues?.length ? "cues" : "none" };
+}
+
+/** The batches a model is asked in: SUGGEST_API_BATCH on the API, fitted to the prompt cap on a local model. */
+export function batchesOf(items: SuggestInput[], model: string, localCap = LOCAL_CAP): SuggestInput[][] {
+ const out: SuggestInput[][] = [];
+ if (providerOf(model) === "api") {
+ for (let i = 0; i < items.length; i += SUGGEST_API_BATCH) out.push(items.slice(i, i + SUGGEST_API_BATCH));
+ return out;
+ }
+ let cur: SuggestInput[] = [];
+ for (const it of items) {
+ const next = [...cur, it];
+ if (cur.length && structuredPromptEstimate({ ...suggestPrompt(next), schema: SUGGEST_ANSWER_SCHEMA }) > localCap) {
+ out.push(cur);
+ cur = [it];
+ } else cur = next;
+ }
+ if (cur.length) out.push(cur);
+ return out;
+}
+
+const callEstimate = (system: string, user: string, schema: object, model: string, outTokens: number) => {
+ const input = structuredPromptEstimate({ system, user, schema });
+ const p = priceOf(model);
+ return { inputTokens: input, outputTokens: outTokens, usd: (input * p.input + outTokens * p.output) / 1e6 };
+};
+
+export type SuggestPlan = {
+ project: string;
+ model: string;
+ provider: "api" | "local" | "code";
+ promptVersion: string;
+ wordsFrom: string;
+ proposals: number;
+ calls: number;
+ estimate: { inputTokens: number; outputTokens: number; usd: number };
+ // The request a Claude Code session answers (the `code` route): the prompt and
+ // the answer's shape.
+ request: { system: string; user: string; schema: object; ids: string[] };
+};
+
+/** What a labels pass would ask, and roughly what it costs — nothing called, nothing written. */
+export async function planClipsSuggest(input: { project: string; model: string; proposals?: string[] }, deps: Pick<ClipsSuggestDeps, "cuesOf" | "localCapTokens">): Promise<SuggestPlan> {
+ const p = await loadClipsProject(input.project, deps);
+ const items = suggestItems(p.reactions, p.words, { ids: input.proposals?.length ? input.proposals : null });
+ const code = input.model === CODE_MODEL;
+ const batches = code ? [items] : batchesOf(items, input.model, deps.localCapTokens ?? LOCAL_CAP);
+ let est = { inputTokens: 0, outputTokens: 0, usd: 0 };
+ for (const b of batches) {
+ const pr = suggestPrompt(b);
+ const e = callEstimate(pr.system, pr.user, SUGGEST_ANSWER_SCHEMA, code ? "claude-sonnet-5-5" : input.model, b.length * ANSWER_TOKENS_PER_ITEM);
+ est = { inputTokens: est.inputTokens + e.inputTokens, outputTokens: est.outputTokens + e.outputTokens, usd: est.usd + (code ? 0 : e.usd) };
+ }
+ const all = suggestPrompt(items);
+ return {
+ project: input.project,
+ model: input.model,
+ provider: code ? "code" : providerOf(input.model),
+ promptVersion: SUGGEST_PROMPT_VERSION,
+ wordsFrom: p.wordsFrom,
+ proposals: items.length,
+ calls: code ? 0 : batches.length,
+ estimate: { ...est, usd: Math.round(est.usd * 10_000) / 10_000 },
+ request: { system: all.system, user: all.user, schema: SUGGEST_ANSWER_SCHEMA, ids: items.map((i) => i.id) },
+ };
+}
+
+export type ClipsSuggestOutcome = {
+ status: "done" | "capped" | "cancelled" | "failed";
+ project: string;
+ model: string;
+ labelled: number;
+ refused: { id: string; error: string }[];
+ failed: { ids: string[]; error: string }[];
+ file: string | null;
+ usd: number;
+ byModel: ReturnType<Meter["summary"]>["byModel"];
+ summary: string;
+};
+
+const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`;
+
+/**
+ * The labels pass: ask the model batch by batch (or take a Claude Code
+ * session's `answers`), then write the file once, merged over the labels of
+ * the old file that are still current.
+ */
+export async function runClipsSuggest(
+ input: { project: string; model: string; proposals?: string[]; maxUsd?: number; answers?: unknown },
+ deps: ClipsSuggestDeps,
+): Promise<ClipsSuggestOutcome> {
+ const log = deps.log ?? (() => {});
+ const now = () => deps.now?.() ?? new Date();
+ const p = await loadClipsProject(input.project, deps);
+ const items = suggestItems(p.reactions, p.words, { ids: input.proposals?.length ? input.proposals : null });
+ const meter = new Meter();
+ const fresh: SuggestAnswerItem[] = [];
+ const refused: ClipsSuggestOutcome["refused"] = [];
+ const failed: ClipsSuggestOutcome["failed"] = [];
+ let status: ClipsSuggestOutcome["status"] = "done";
+ if (!items.length) throw new ClipsSuggestRefusal(`${input.project}: reactions.json holds no proposals to label`);
+ log(`clips-suggest ${input.project} on ${input.model}: ${plural(items.length, "proposal")}, words from ${p.wordsFrom} (prompt ${SUGGEST_PROMPT_VERSION})`);
+ if (input.answers !== undefined) {
+ // The `code` route: a Claude Code session's answer, read as a model's is.
+ const r = parseSuggestAnswer(input.answers, items.map((i) => i.id));
+ if (!r.ok) throw new ClipsSuggestRefusal(`the session's answers are refused: ${r.error}`);
+ fresh.push(...r.items);
+ refused.push(...r.refused);
+ deps.progress?.(items.length, items.length);
+ } else {
+ 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 }));
+ const batches = batchesOf(items, input.model, deps.localCapTokens ?? LOCAL_CAP);
+ const api = providerOf(input.model) === "api";
+ let done = 0;
+ deps.progress?.(0, items.length);
+ for (const [bi, batch] of batches.entries()) {
+ if (deps.signal?.aborted) {
+ status = "cancelled";
+ break;
+ }
+ const pr = suggestPrompt(batch);
+ const outTokens = Math.min(8192, 256 + batch.length * ANSWER_TOKENS_PER_ITEM * 2);
+ if (api && input.maxUsd !== undefined) {
+ const next = callEstimate(pr.system, pr.user, SUGGEST_ANSWER_SCHEMA, input.model, batch.length * ANSWER_TOKENS_PER_ITEM).usd;
+ if (meter.usd + next > input.maxUsd) {
+ status = "capped";
+ log(`stopped at the cap: $${meter.usd.toFixed(4)} spent, the next batch (~$${next.toFixed(4)}) would pass $${input.maxUsd}`);
+ break;
+ }
+ }
+ const ids = batch.map((b) => b.id);
+ try {
+ const raw = await ask<unknown>(pr.system, pr.user, SUGGEST_ANSWER_SCHEMA, input.model, outTokens);
+ const r = parseSuggestAnswer(raw, ids);
+ if (!r.ok) throw new StructuredAnswerError(`${r.error}: ${JSON.stringify(raw ?? null).slice(0, 120)}`);
+ fresh.push(...r.items);
+ refused.push(...r.refused, ...r.missing.map((id) => ({ id, error: "not answered" })));
+ log(`batch ${bi + 1}/${batches.length}: ${plural(r.items.length, "label")}${r.refused.length + r.missing.length ? `, ${r.refused.length + r.missing.length} refused or missing` : ""}`);
+ for (const x of r.refused) log(` ${x.id}: refused — ${x.error}`);
+ } catch (err) {
+ if (deps.signal?.aborted) {
+ status = "cancelled";
+ break;
+ }
+ const error = (err as Error).message.slice(0, 300);
+ failed.push({ ids, error });
+ log(`batch ${bi + 1}/${batches.length} (${ids[0]}…${ids.at(-1)}): no labels — ${error}`);
+ }
+ done += batch.length;
+ deps.progress?.(done, items.length);
+ }
+ }
+ const usd = Math.round(meter.usd * 1e6) / 1e6;
+ let file: string | null = null;
+ if (fresh.length) {
+ const prev = (await readSuggestions(input.project)).doc;
+ // Read again at the write: a pass that ran meanwhile is what the labels are merged over.
+ const reactions = (await readReactions(input.project)) ?? p.reactions;
+ file = await writeSuggestions(input.project, suggestionsDocOf({ model: input.model, at: now().toISOString(), reactions, fresh, prev }));
+ }
+ if (!fresh.length && status === "done") status = "failed";
+ const summary =
+ `${plural(fresh.length, "proposal")} labelled on ${input.model}` +
+ (refused.length ? `, ${refused.length} refused` : "") +
+ (failed.length ? `, ${plural(failed.reduce((n, f) => n + f.ids.length, 0), "proposal")} in failed batches` : "") +
+ (status === "capped" ? ", stopped at the cap" : status === "cancelled" ? ", cancelled" : "") +
+ (usd ? ` · $${usd.toFixed(4)}` : "");
+ return { status, project: input.project, model: input.model, labelled: fresh.length, refused, failed, file, usd, byModel: meter.summary().byModel, summary };
+}
+
+export type ClipsAskOutcome = {
+ status: "done" | "cancelled";
+ project: string;
+ model: string;
+ note: string;
+ clip: string;
+ reply: string;
+ proposal: AskProposal | null;
+ dropped: string | null;
+ usd: number;
+ byModel: ReturnType<Meter["summary"]>["byModel"];
+ summary: string;
+};
+
+/** The note an Ask answers, and the clips it reads, from the project's files. */
+export async function loadAsk(dir: string, noteId: string): Promise<{ note: AskNote; clips: AskClips }> {
+ const read = async (name: string) => {
+ try {
+ return JSON.parse(await readFile(path.join(dir, name), "utf8")) as unknown;
+ } catch {
+ return null;
+ }
+ };
+ const n = askNoteOf(await read("notes.json"), noteId);
+ if ("error" in n) throw new ClipsSuggestRefusal(n.error);
+ const clips = askClipsOf(await read("video.manifest.json"), n.note.clip);
+ if ("error" in clips) throw new ClipsSuggestRefusal(clips.error);
+ return { note: n.note, clips };
+}
+
+/** An Ask: the reply and its proposal, handed to `postReply`. */
+export async function runClipsAsk(
+ input: { project: string; model: string; note: string; maxUsd?: number },
+ deps: ClipsSuggestDeps & { postReply: (r: { note: string; text: string; proposal: AskProposal | null }) => Promise<void> },
+): Promise<ClipsAskOutcome> {
+ const log = deps.log ?? (() => {});
+ const p = await loadClipsProject(input.project, deps);
+ const { note, clips } = await loadAsk(input.project, input.note);
+ const pr = askPrompt({ note, clips, words: p.words, turns: p.reactions.turns, speakers: p.reactions.speakers });
+ log(`clips-suggest ask ${input.note} on ${clips.clip.id} (${input.model}), words from ${p.wordsFrom}`);
+ const meter = new Meter();
+ if (providerOf(input.model) === "api" && input.maxUsd !== undefined) {
+ const e = callEstimate(pr.system, pr.user, ASK_ANSWER_SCHEMA, input.model, ASK_ANSWER_TOKENS).usd;
+ if (e > input.maxUsd) throw new ClipsSuggestRefusal(`the ask (~$${e.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 }));
+ const raw = await ask<unknown>(pr.system, pr.user, ASK_ANSWER_SCHEMA, input.model, 1024);
+ const r = parseAskAnswer(raw, clips);
+ if (!r.ok) throw new StructuredAnswerError(`${input.model}: ${r.error}: ${JSON.stringify(raw ?? null).slice(0, 120)}`);
+ if (r.dropped) log(`the proposal is not kept: ${r.dropped}`);
+ if (deps.signal?.aborted) {
+ return { status: "cancelled", project: input.project, model: input.model, note: note.id, clip: clips.clip.id, reply: r.reply, proposal: r.proposal, dropped: r.dropped, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" };
+ }
+ await deps.postReply({ note: note.id, text: r.reply, proposal: r.proposal });
+ const usd = Math.round(meter.usd * 1e6) / 1e6;
+ const what = r.proposal ? (r.proposal.kind === "trim" ? `a trim to ${r.proposal.from}–${r.proposal.to} s` : r.proposal.kind === "merge" ? `a merge with ${r.proposal.with}` : "a cut") : "no edit";
+ log(`replied to ${note.id}, proposing ${what}`);
+ return {
+ status: "done",
+ project: input.project,
+ model: input.model,
+ note: note.id,
+ clip: clips.clip.id,
+ reply: r.reply,
+ proposal: r.proposal,
+ dropped: r.dropped,
+ usd,
+ byModel: meter.summary().byModel,
+ summary: `replied to ${note.id} on ${clips.clip.id}, proposing ${what}${usd ? ` · $${usd.toFixed(4)}` : ""}`,
+ };
+}
diff --git a/common/package.json b/common/package.json
@@ -38,6 +38,7 @@
"./lib/clips/reactions.mjs": "./lib/clips/reactions.mjs",
"./lib/clips/scan.mjs": "./lib/clips/scan.mjs",
"./lib/clips/segments.mjs": "./lib/clips/segments.mjs",
+ "./lib/clips/suggest.mjs": "./lib/clips/suggest.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -31,6 +31,7 @@ transcript, channel or person goes in these fixtures, ever.
| `audio/fakeSpeakerEmbed.mjs` | Release 34 N2: a stand-in for `scripts/speaker-embed.py` with its command line and JSON (`node fakeSpeakerEmbed.mjs --emb <x> <request.json>`): the "embedding" is the long-term spectrum (32 log-spaced Goertzel bands, dB, mean-removed, L2-normalised) — deterministic, and it separates `VOICE_A` from `VOICE_B`. Not a speaker model: set `VOICE_MATCH_PYTHON` to `node` and `VOICE_MATCH_SCRIPT` to it for a run with no python or model. |
| `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). |
| `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/reactionProject.d.mts b/common/testing/clips/reactionProject.d.mts
@@ -0,0 +1,9 @@
+export const PROJECT_CHANNEL: string;
+export const PROJECT_VIDEO: string;
+export const PROJECT_NOTE: string;
+export const PROPOSED_AT: string;
+export const PROJECT_PROPOSALS: readonly { id: string; start: number; end: number; score: number; moments: string[]; used: boolean; clipId: string | null; why: string }[];
+
+export function reactionProject(o?: { proposedAt?: string }): { reactions: any; words: { words: { w: string; start: number; end: number }[] }; manifest: any };
+export function writeReactionProject(dir: string, o?: { proposedAt?: string; note?: { clip: string; text: string } | null }): { dir: string; reactions: any; manifest: any };
+export function labelAnswer(ids: string[], o?: { label?: (id: string, i: number) => string }): { items: { id: string; label: string; why: string; score: number }[] };
diff --git a/common/testing/clips/reactionProject.mjs b/common/testing/clips/reactionProject.mjs
@@ -0,0 +1,116 @@
+// A synthetic REACTIONS PROJECT for the assistant's tests (release 36 lane
+// D): what a umtool project holds after the clip finder ran — reactions.json
+// (two speakers over reactionStream()'s turns, five moments, five proposals:
+// three in the cut, two not), words.json (the stream's words), a
+// video.manifest.json whose clips are the three used proposals, and, when
+// asked, a notes.json with an open comment on a clip. Nothing in it is a
+// recording, a person or a transcript (reactionStream's filler words).
+//
+// r001 40–47 (p004, a comment) r002 88–99 (p001, a laugh) r003 333–344 (p002, a laugh)
+// not in the cut: p003 512–523 (a weak laugh), p005 170–178 (the chat laughs)
+//
+// reactionProject(o) the three documents, as plain data
+// writeReactionProject(dir,o) them on disk (and notes.json with `note`)
+// labelAnswer(ids, o) a model's answer for those ids, the way
+// SUGGEST_ANSWER_SCHEMA asks for it
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { HOST, SUBJECT, reactionStream } from "./reactionStream.mjs";
+
+export const PROJECT_CHANNEL = "synth-reacts";
+export const PROJECT_VIDEO = "react001";
+export const PROJECT_NOTE = "n_synth0001";
+export const PROPOSED_AT = "2026-10-19T00:00:00.000Z";
+
+export const PROJECT_PROPOSALS = Object.freeze([
+ { id: "p001", start: 88, end: 99, score: 0.82, moments: ["m001"], used: true, clipId: "r002", why: "the host laughs (0.80)" },
+ { id: "p002", start: 333, end: 344, score: 0.74, moments: ["m002"], used: true, clipId: "r003", why: "the host laughs (0.70)" },
+ { id: "p003", start: 512, end: 523, score: 0.31, moments: ["m003"], used: false, clipId: null, why: "a weak laugh" },
+ { id: "p004", start: 40, end: 47, score: 0.55, moments: ["m004"], used: true, clipId: "r001", why: "the host comments" },
+ { id: "p005", start: 170, end: 178, score: 0.4, moments: ["m005"], used: false, clipId: null, why: "chat laughs (12 messages)" },
+]);
+
+const MOMENTS = Object.freeze([
+ { id: "m001", t: 95, end: 97.5, kind: "laugh", score: 0.8, speaker: HOST, text: "haha" },
+ { id: "m002", t: 340, end: 342, kind: "laugh", score: 0.7, speaker: HOST, text: "haha" },
+ { id: "m003", t: 520, end: 521, kind: "laugh", score: 0.3, speaker: HOST, text: "haha" },
+ { id: "m004", t: 40, end: 44, kind: "comment", score: 0.5, speaker: HOST, text: "wow that's crazy." },
+ { id: "m005", t: 172, end: 176, kind: "chat", score: 0.4, speaker: null, text: "", messages: 12 },
+]);
+
+/**
+ * @param {{ proposedAt?: string }} [o]
+ */
+export function reactionProject({ proposedAt = PROPOSED_AT } = {}) {
+ const s = reactionStream();
+ const reactions = {
+ version: 1,
+ source: { channel: PROJECT_CHANNEL, video: PROJECT_VIDEO, duration: s.duration, words: "words.json", diarization: { generatedAt: "2026-10-18T00:00:00.000Z", engine: "sherpa-onnx" } },
+ params: { target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75, scope: null },
+ speakers: [
+ { index: HOST, role: "host", label: "Host", seconds: 60, turns: 7, how: "auto" },
+ { index: SUBJECT, role: "subject", label: "Subject", seconds: 540, turns: 8, how: "auto" },
+ ],
+ turns: s.turns,
+ laughs: [],
+ moments: MOMENTS.map((m) => ({ ...m })),
+ proposals: PROJECT_PROPOSALS.map((p) => ({ ...p, moments: [...p.moments] })),
+ madeAt: proposedAt,
+ proposedAt,
+ };
+ const clip = (id, p) => ({
+ type: "clip",
+ id,
+ channel: PROJECT_CHANNEL,
+ video: PROJECT_VIDEO,
+ start: p.start - 1.5,
+ end: p.end + 1.5,
+ cutStart: p.start,
+ cutEnd: p.end,
+ quote: "",
+ assist: { by: "assistant", proposal: p.id, score: p.score, why: p.why, original: { start: p.start - 1.5, end: p.end + 1.5, cutStart: p.start, cutEnd: p.end }, edits: [] },
+ });
+ const byId = Object.fromEntries(PROJECT_PROPOSALS.map((p) => [p.id, p]));
+ const manifest = {
+ slug: "synth-reaction-cut",
+ title: "A synthetic reaction cut",
+ provenance: { channelSlug: PROJECT_CHANNEL, siteOrigin: "" },
+ render: {},
+ timeline: [clip("r001", byId.p004), clip("r002", byId.p001), clip("r003", byId.p002)],
+ };
+ return { reactions, words: { words: s.words }, manifest };
+}
+
+/**
+ * The project on disk. `note`: an open comment (PROJECT_NOTE) on that clip,
+ * with that text.
+ * @param {string} dir
+ * @param {{ proposedAt?: string, note?: { clip: string, text: string } | null }} [o]
+ */
+export function writeReactionProject(dir, { proposedAt = PROPOSED_AT, note = null } = {}) {
+ const { reactions, words, manifest } = reactionProject({ proposedAt });
+ mkdirSync(dir, { recursive: true });
+ const put = (name, doc) => writeFileSync(path.join(dir, name), `${JSON.stringify(doc, null, 1)}\n`);
+ put("reactions.json", reactions);
+ put("words.json", words);
+ put("video.manifest.json", manifest);
+ if (note) {
+ put("notes.json", {
+ format: "umtool-notes",
+ version: 1,
+ subject: { kind: "video-project", project: path.basename(dir) },
+ notes: [{ id: PROJECT_NOTE, status: "open", author: "operator", text: note.text, at: proposedAt, updatedAt: proposedAt, anchor: { kind: "entry", entry: note.clip }, replies: [] }],
+ });
+ }
+ return { dir, reactions, manifest };
+}
+
+/**
+ * A model's answer for `ids`: a short label and a why each, scored so the
+ * first id ranks lowest (the rank is code's, by score).
+ * @param {string[]} ids
+ * @param {{ label?: (id: string, i: number) => string }} [o]
+ */
+export function labelAnswer(ids, { label = (id) => `the ${id} moment` } = {}) {
+ return { items: ids.map((id, i) => ({ id, label: label(id, i), why: `Something happens in ${id}.`, score: Math.min(10, 2 + i) })) };
+}
diff --git a/editor/app/api/ops/_clipsSuggest.test.ts b/editor/app/api/ops/_clipsSuggest.test.ts
@@ -0,0 +1,231 @@
+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 { labelAnswer, writeReactionProject, PROJECT_NOTE } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs";
+import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft";
+import { planClipsSuggestJob, projectDirOf, umtoolOrigin, type ClipsSuggestJobDeps } from "yt-dlp-transcript-common/controller/clipsSuggest";
+import { readSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs";
+import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage";
+import type { AskProposal } from "yt-dlp-transcript-common/lib/clips/suggest.mjs";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_clipsSuggest.test.ts"
+//
+// The `report-draft` task `clips-suggest` (release 36 lane D) end to end in
+// this process: the controller the ops route adapts, a synthetic reactions
+// project in a temp dir (common/testing/clips/reactionProject.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;
+
+// The ids a labels prompt asks, in its order.
+const idsOf = (text: string) => [...text.matchAll(/^\[(p\d+)\]/gm)].map((m) => m[1]!);
+const userOf = (body: { messages: { content: unknown }[] }) => JSON.stringify(body.messages[0]!.content).replace(/\\n/g, "\n");
+const labelTurn = (body: { messages: { content: unknown }[] }) => toolTurn("answer", labelAnswer(idsOf(userOf(body).replace(/^"/, ""))));
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "clips-suggest-"));
+ 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, "clips-suggest": "api" } });
+});
+
+after(async () => {
+ await api.close();
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const deps = (g: Partial<GenerationSettings> = {}, more: Partial<ClipsSuggestJobDeps> = {}) =>
+ ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }), ...more }) as ReportDraftDeps & ClipsSuggestJobDeps;
+
+const out = (o: Awaited<ReturnType<typeof enqueueReportDraft>>) => o.result as { ok: boolean; error: string };
+
+async function finished(out: Awaited<ReturnType<typeof enqueueReportDraft>>) {
+ assert.ok(out.result.ok, (out.result as { error?: string }).error);
+ const job = getRegistry().get(out.result.jobId)!;
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ return { job, done, log: await readFile(job.logPath, "utf8") };
+}
+
+test("the body: a project, not an article; the clips keys are its own; dryRun plans", () => {
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest" }), /"project" is the reactions project's absolute directory/);
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "rel/dir" }), /absolute directory/);
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest", article: "a", project: "/p" }), /not an article/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", project: "/p" }), /"project" is a clips-suggest job's/);
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", note: "n_x" }), /"note" is a note id/);
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", note: PROJECT_NOTE, proposals: ["p001"] }), /an Ask \("note"\) takes no/);
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", answers: { items: [] }, model: "m" }), /no "model"/);
+ assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", iteration: 2 }), /takes no iteration/);
+ assert.deepEqual(parseReportDraftBody({ task: "clips-suggest", project: "/p", proposals: "p001, p002", dryRun: true }), {
+ task: "clips-suggest",
+ article: "",
+ project: "/p",
+ proposals: ["p001", "p002"],
+ dryRun: true,
+ });
+ assert.throws(() => projectDirOf("/x/../y", paths), /plain absolute path/);
+ assert.throws(() => projectDirOf(path.join(paths.transcriptsDir, "reports", "x"), paths), /never inside the corpus/);
+ assert.equal(umtoolOrigin({ UMTOOL_URL: " http://localhost:3050/ " }), "http://localhost:3050");
+ assert.equal(umtoolOrigin({}), null);
+});
+
+test("labels on the API: batches asked, clip-suggestions.json written whole and ranked, the spend in the ledger; the plan first", async () => {
+ const dir = path.join(tmp, "api-project");
+ writeReactionProject(dir);
+ const plan = await planClipsSuggestJob(parseReportDraftBody({ task: "clips-suggest", project: dir, dryRun: true }), deps());
+ assert.equal(plan.model, "claude-sonnet-5-5");
+ assert.equal(plan.proposals, 5);
+ assert.equal(plan.calls, 1);
+ assert.equal(plan.wordsFrom, "words.json");
+ assert.ok(plan.estimate.usd > 0 && plan.estimate.inputTokens > 200);
+ assert.deepEqual(plan.request.ids, ["p001", "p002", "p003", "p004", "p005"]);
+
+ api.push(labelTurn);
+ const { job, done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps()));
+ assert.equal(done.status, "done", log);
+ assert.equal(job.queueKey, "draft:api");
+ assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"clips-suggest","project":"[^"]+api-project","status":"done","summary":"5 proposals labelled on claude-sonnet-5-5 · \$0\.\d+"/);
+ assert.ok(!log.includes(FAKE_KEY));
+ const { doc } = await readSuggestions(dir);
+ assert.equal(doc!.model, "claude-sonnet-5-5");
+ assert.deepEqual(Object.entries(doc!.items).map(([id, it]) => [id, (it as { rank: number }).rank, (it as { label: string }).label]), [
+ ["p005", 1, "the p005 moment"],
+ ["p004", 2, "the p004 moment"],
+ ["p003", 3, "the p003 moment"],
+ ["p002", 4, "the p002 moment"],
+ ["p001", 5, "the p001 moment"],
+ ]);
+ 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]), [["clips-suggest", "claude-sonnet-5-5", "", 0]]);
+ assert.ok(rows[0]!.usd > 0);
+ // It never touched the manifest or reactions.json.
+ assert.equal(JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")).timeline.length, 3);
+});
+
+test("a malformed answer is refused: no file, the job fails, the batch named", async () => {
+ const dir = path.join(tmp, "malformed-project");
+ writeReactionProject(dir);
+ api.push(toolTurn("answer", { labels: "everything is funny" }));
+ const { done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps()));
+ assert.equal(done.status, "failed", log);
+ assert.match(log, /batch 1\/1 \(p001…p005\): no labels — the answer is not \{ items: \[\.\.\.\] \}/);
+ assert.deepEqual(await readSuggestions(dir), { doc: null, error: null });
+});
+
+test("the cap: a run whose first batch would pass maxUsd stops capped and writes nothing; past the day's cap it is refused", async () => {
+ const dir = path.join(tmp, "cap-project");
+ writeReactionProject(dir);
+ const asked = api.requests.length;
+ const { done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir, maxUsd: 0.00001 }, deps()));
+ assert.equal(done.status, "done", log);
+ assert.match(log, /stopped at the cap/);
+ assert.equal(api.requests.length, asked);
+ assert.equal((await readSuggestions(dir)).doc, null);
+ // A cap over caps.max is refused at the ask.
+ const over = await enqueueReportDraft({ task: "clips-suggest", project: dir, maxUsd: 50 }, deps());
+ assert.ok(!out(over).ok && /over the settings' max/.test(out(over).error));
+ const usage = path.join(tmp, "spent.jsonl");
+ await appendGenerationUsage(usage, [{ at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }]);
+ const refused = await enqueueReportDraft({ task: "clips-suggest", project: dir }, { ...deps(), paths: { ...paths, generationUsageFile: usage } } as ReportDraftDeps);
+ assert.ok(!out(refused).ok && /daily cap/.test(out(refused).error));
+});
+test("labels on the local model: draft:local through the arbiter, batches fitted, a label over six words refused, ollama unloaded", async () => {
+ const dir = path.join(tmp, "local-project");
+ writeReactionProject(dir);
+ ol.push((body: { messages: { content: string }[] }) => {
+ const ids = idsOf(body.messages[1]!.content);
+ const a = labelAnswer(ids);
+ a.items[0]!.label = "a label with far too many words to keep";
+ return jsonReply(a);
+ });
+ const { job, done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps({ routes: { ...gen.routes, "clips-suggest": "local" } })));
+ assert.equal(done.status, "done", log);
+ assert.equal(job.queueKey, "draft:local");
+ assert.match(log, /p001: refused — a label of 9 words \(at most 6\)/);
+ assert.match(log, /unloaded qwen3:8b from ollama/);
+ const { doc } = await readSuggestions(dir);
+ assert.equal(doc!.model, "qwen3:8b");
+ assert.deepEqual(Object.keys(doc!.items).sort(), ["p002", "p003", "p004", "p005"]);
+ assert.ok(ol.unloads.includes("qwen3:8b"));
+ // A local run spends nothing on the ledger.
+ assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0);
+});
+
+test("the code route: no model is asked; a session's answers are read as a model's and written as claude-code's", async () => {
+ const dir = path.join(tmp, "code-project");
+ writeReactionProject(dir);
+ const code = { routes: { ...gen.routes, "clips-suggest": "code" as const } };
+ // Routed to code with no answers: refused at the ask, naming the route.
+ const refused = await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps(code));
+ assert.ok(!out(refused).ok && /routed to Claude Code/.test(out(refused).error));
+ // The plan is the request a session answers.
+ const plan = await planClipsSuggestJob(parseReportDraftBody({ task: "clips-suggest", project: dir, dryRun: true }), deps(code));
+ assert.equal(plan.provider, "code");
+ assert.equal(plan.calls, 0);
+ assert.match(plan.request.user, /\[p004\] 0:40–0:47/);
+ const asked = api.requests.length + ol.requests.length;
+ const { job, done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir, answers: labelAnswer(["p001", "p002"]) }, deps(code)));
+ assert.equal(done.status, "done", log);
+ assert.equal(job.queueKey, "draft:api");
+ assert.equal(api.requests.length + ol.requests.length, asked);
+ const { doc } = await readSuggestions(dir);
+ assert.equal(doc!.model, "claude-code");
+ assert.deepEqual(Object.keys(doc!.items), ["p002", "p001"]);
+ // Junk answers are refused.
+ const junk = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir, answers: { nope: true } }, deps(code)));
+ assert.equal(junk.done.status, "failed");
+ assert.match(junk.log, /the session's answers are refused/);
+});
+
+test("Ask the assistant: the note and the clip's words asked, the reply posted as the agent's with its proposal, nothing applied", async () => {
+ const dir = path.join(tmp, "ask-project");
+ writeReactionProject(dir, { note: { clip: "r002", text: "start it where he laughs" } });
+ // Without UMTOOL_URL the ask is refused (its reply has nowhere to go).
+ const nowhere = await enqueueReportDraft({ task: "clips-suggest", project: dir, note: PROJECT_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: "clips-suggest", 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 = "";
+ api.push((body: { messages: { content: unknown }[] }) => {
+ prompt = userOf(body);
+ return toolTurn("answer", { reply: "Start it on the laugh at 95 s.", proposal: { kind: "trim", from: 94.8, to: 99 } });
+ });
+ const posted: { project: string; note: string; text: string; proposal: AskProposal | null }[] = [];
+ const { done, log } = await finished(
+ await enqueueReportDraft({ task: "clips-suggest", project: dir, note: PROJECT_NOTE }, deps({}, { postReply: async (r) => void posted.push(r) })),
+ );
+ assert.equal(done.status, "done", log);
+ assert.match(prompt, /The comment on clip r002 \(88\.0–99\.0 s\): start it where he laughs/);
+ assert.match(prompt, /HOST: haha/);
+ assert.deepEqual(posted, [
+ { project: dir, note: PROJECT_NOTE, text: "Start it on the laugh at 95 s.", proposal: { kind: "trim", clip: "r002", from: 94.8, to: 99, basis: { cutStart: 88, cutEnd: 99 } } },
+ ]);
+ assert.match(log, /"kind":"ask","ask":\{"note":"n_synth0001","clip":"r002","proposal":\{"kind":"trim"/);
+ // The manifest is as it was: the operator's Apply does the trim.
+ const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ assert.deepEqual([m.timeline[1].cutStart, m.timeline[1].cutEnd], [88, 99]);
+});
diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
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 { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
import { jobResponse, ops, opsFail } from "../_lib";
import { refreshEditor, researchEditor } from "../_researchEditor";
@@ -51,7 +52,16 @@ export const dynamic = "force-dynamic";
// `draft:api`), then whether its flags reach `threshold` {strong, weak}.
// A run of reports/.triage/<owner>/<k>/ (triage.json, trace.jsonl);
// answers `{ ok, jobId, iteration: k, triage: {owner, k} }`. A sweep's
-// `triage: "<owner>/<k>"` names the triage it escalates.
+// `triage: "<owner>/<k>"` names the triage it escalates;
+// - "clips-suggest" (release 36 lane D, controller/clipsSuggest.ts): on a
+// umtool reactions project, `project` (its absolute directory) instead of
+// `article` — labels, a why and a rank for its proposals
+// (`clip-suggestions.json`; `proposals`: only these), or with `note` an
+// answer to that comment posted to umtool's notes as the agent's
+// (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 }`.
// `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
@@ -80,6 +90,14 @@ export async function POST(request: Request) {
return opsFail((e as Error).message);
}
}
+ if (body.task === "clips-suggest" && body.dryRun === true) {
+ try {
+ const plan = await planClipsSuggestJob(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
@@ -36,7 +36,7 @@ type Sent = { url: string; method: string; body?: unknown };
// An editor that serves the policy, the day's usage, a report-draft POST, a
// job that runs for `runPolls` polls and then ends `end`, and the iteration.
-function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean; task?: string; markerJson?: Record<string, unknown> } = {}) {
+function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean; task?: string; markerJson?: Record<string, unknown>; plan?: Record<string, unknown> } = {}) {
let policy = { ...POLICY, ...(opts.policy ?? {}) };
let polls = 0;
const runPolls = opts.runPolls ?? 0;
@@ -68,6 +68,7 @@ function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end
return { status: 200, body: { ok: true, changed: ["generation"], value: { generation: policy } } };
}
if (u.pathname === "/api/ops/generation-usage") return { status: 200, body: { ok: true, day: "2026-10-13", usd: 1.75, jobs: 2, daily: 20 } };
+ if (u.pathname === "/api/ops/report-draft" && opts.plan && (s.body as { dryRun?: boolean } | undefined)?.dryRun) return { status: 200, body: { ok: true, plan: opts.plan } };
if (u.pathname === "/api/ops/report-draft") return { status: 200, body: { ok: true, jobId: "job-1", iteration: 3 } };
if (u.pathname === "/api/ops/job/job-1") {
polls++;
@@ -147,6 +148,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async
verdicts: "api",
// The frame scan (release 30): routed like every task.
frames: "api",
+ // The clip finder's labels (release 36 lane D).
+ "clips-suggest": "api",
},
},
},
@@ -470,3 +473,39 @@ test("generate verdicts: never this session's — a code route with no model ref
assert.match(b.text, /Never set a claim's verdict yourself/);
assert.equal(done.sentOf("/api/ops/iterations").length, 0);
});
+
+test("generate clips-suggest: a project, not an article; routed to code, the editor's plan is this session's request; the answers go back to the editor", async () => {
+ assert.ok(GENERATE_TASKS.includes("clips-suggest"));
+ assert.match(String((validateGenerateArgs({ task: "clips-suggest", article: "a" }) as { error: string }).error), /names its project/);
+ assert.match(String((validateGenerateArgs({ task: "clips-suggest", project: "/r/p", iteration: 2 }) as { error: string }).error), /iteration is not a clips-suggest job's/);
+ assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", project: "/r/p" }) as { error: string }).error), /a clips-suggest job's/);
+ assert.match(String((validateGenerateArgs({ task: "clips-suggest", project: "/r/p", answers: { items: [] }, model: "m" }) as { error: string }).error), /no model/);
+ const plan = {
+ proposals: 2,
+ calls: 0,
+ wordsFrom: "words.json",
+ estimate: { inputTokens: 900, outputTokens: 120, usd: 0 },
+ request: { system: "You read moments from a livestream…", user: "2 moments. Answer every id once.\n\n[p001] 1:28–1:39 (11 s) · heard: laugh\nHOST: haha", ids: ["p001", "p002"] },
+ };
+ const code = editor({ policy: { routes: { ...POLICY.routes, "clips-suggest": "code" } }, plan });
+ const a = await generateTool({ task: "clips-suggest", project: "/r/p" }, code.deps as never);
+ assert.equal(a.isError, undefined, a.text);
+ assert.match(a.text, /^generate clips-suggest: routed to Claude Code \(preset balanced\) — label these 2 proposals in this session\./);
+ assert.match(a.text, /call generate with task "clips-suggest", project "\/r\/p", answers: \{"items"/);
+ assert.match(a.text, /Never write that file, the manifest or a clip yourself/);
+ assert.match(a.text, /\[p001\] 1:28–1:39 \(11 s\) · heard: laugh\nHOST: haha/);
+ assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "clips-suggest", project: "/r/p", dryRun: true }]);
+
+ const answers = { items: [{ id: "p001", label: "the laugh", why: "He loses it.", score: 8 }] };
+ const done = editor({
+ markerJson: { article: "", iteration: 0, task: "clips-suggest", project: "/r/p", kind: "labels", status: "done", summary: "1 proposal labelled on claude-code", usd: 0, suggestions: { labelled: 1, refused: 0, failed: 0 } },
+ });
+ const b = await generateTool({ task: "clips-suggest", project: "/r/p", answers, wait: true }, done.deps as never);
+ assert.equal(b.isError, false, b.text);
+ assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "clips-suggest", project: "/r/p", answers }]);
+ assert.equal(done.sentOf("/api/ops/settings").length, 0, "a session's answers need no policy read");
+ assert.match(b.text, /^generate clips-suggest: job job-1 ended \*\*done\*\* — 1 proposal labelled on claude-code/);
+ assert.match(b.text, /Project: \/r\/p · 1 labelled, 0 refused, 0 in failed batches/);
+ 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
@@ -236,6 +236,8 @@ 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 (args.project !== undefined || args.answers !== undefined || args.proposals !== undefined) return bad("project, proposals and answers are a clips-suggest 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 };
@@ -295,6 +297,86 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true;
return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
}
+// ─── clips-suggest (release 36 lane D): the clip finder's labels, on a umtool project ───
+
+const CLIPS_SUGGEST = "clips-suggest";
+const PROPOSAL_RE = /^[A-Za-z0-9._:-]{1,64}$/;
+
+function validateClipsSuggestArgs(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 clips-suggest job names its project: the reactions project's absolute directory (project)");
+ for (const k of ["article", "iteration", "copyOf", "question", "channels", "feedback", "from", "to", "cards", "entries", "force", "autonomy", "extractorModel"] as const) {
+ if (args[k] !== undefined) return bad(`${k} is not a clips-suggest job's (it reads its project)`);
+ }
+ const body: Body = { task: CLIPS_SUGGEST, project };
+ 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.proposals !== undefined) {
+ const v = args.proposals;
+ if (!Array.isArray(v) || !v.length || v.some((x) => typeof x !== "string" || !PROPOSAL_RE.test(x.trim()))) return bad("proposals is a non-empty list of proposal ids");
+ body.proposals = v.map((x: string) => x.trim());
+ }
+ if (args.answers !== undefined) {
+ if (!args.answers || typeof args.answers !== "object" || Array.isArray(args.answers)) return bad('answers is {"items": [{"id", "label", "why", "score"}]}');
+ 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 SuggestPlanView = {
+ proposals?: number;
+ calls?: number;
+ wordsFrom?: string;
+ estimate?: { inputTokens?: number; outputTokens?: number; usd?: number };
+ request?: { system?: string; user?: string; ids?: string[] };
+};
+
+// The `code` route: this session answers the request the editor's plan names.
+export function renderClipsSuggestRequest(project: string, plan: SuggestPlanView, preset: string): string {
+ const r = plan.request ?? {};
+ return [
+ `generate clips-suggest: routed to Claude Code (preset ${preset}) — label these ${plan.proposals ?? r.ids?.length ?? 0} proposals in this session.`,
+ `Words from ${plan.wordsFrom ?? "?"}. Read the moments below and give, for EVERY id, a label (at most six words), why (one plain sentence) and score (1–10).`,
+ `Then call generate with task "clips-suggest", project "${project}", answers: {"items": [{"id", "label", "why", "score"}, …]} and wait: true — ` +
+ "the editor reads your answers exactly as a model's (a label over six words is refused) and writes clip-suggestions.json. " +
+ "Never write that file, the manifest or a clip yourself; the labels never edit a clip.",
+ "",
+ "## The instructions",
+ r.system ?? "",
+ "",
+ "## The moments",
+ r.user ?? "",
+ ].join("\n");
+}
+
+function clipsSuggestSummary(f: Extract<Followed, { kind: "ended" }>, m: Marker): ToolAnswer {
+ const s = m.suggestions ?? {};
+ const lines = [
+ `generate clips-suggest: job ${f.job.id} ended **${f.job.status}** — ${m.summary ?? m.status ?? ""}`.trim(),
+ `Project: ${m.project ?? "?"} · ${s.labelled ?? 0} labelled, ${s.refused ?? 0} refused, ${s.failed ?? 0} in failed batches` + (m.usd ? ` · $${m.usd.toFixed(4)}` : ""),
+ "",
+ "The labels are suggestions: the operator sees them in umtool's clip editor (Sort by the assistant's rank) and keeps, cuts or brings in clips there. Nothing in the cut changed.",
+ ];
+ return { text: lines.join("\n"), isError: f.job.status !== "done" };
+}
+
type JobView = { id: string; status: string; kind?: string; detail?: string; queue?: { key: string; position: number; queued: number } };
type Followed =
| { kind: "ended"; job: JobView; tail: string[] }
@@ -355,6 +437,9 @@ type Marker = {
minutes?: number;
// A verdicts job's (release 29 M8): no iteration (0).
verdicts?: { proposed?: number; failed?: number; skipped?: number; promptVersion?: string };
+ // A clips-suggest job's (release 36 lane D): a project, no article.
+ project?: string;
+ suggestions?: { labelled?: number; refused?: number; failed?: number };
};
// What to do with verdict proposals: they are the operator's to rule.
@@ -488,6 +573,7 @@ async function summarise(
): Promise<ToolAnswer> {
const marker = resultMarkerOf(f.tail);
if (marker?.task === "verdicts") return verdictsSummary(f, marker);
+ if (marker?.task === CLIPS_SUGGEST) return clipsSuggestSummary(f, marker);
const article = marker?.article ?? hint.article;
const n = marker?.iteration ?? hint.iteration;
const task = marker?.task ?? hint.task ?? "report-draft";
@@ -560,7 +646,8 @@ export async function generateTool(
const task = String(body.task);
// Who runs it: the asked model, the asked route's model, else the policy's
// route — and a task routed to code is this session's, not the editor's.
- if (!body.model) {
+ // A session's clips-suggest answers run on no model: straight to the editor.
+ if (!body.model && body.answers === undefined) {
const read = await readPolicy(deps);
if (!read.ok) {
return {
@@ -570,7 +657,12 @@ export async function generateTool(
}
const p = read.policy;
if (req.via) body.model = p.models[req.via];
- else if (task === "verdicts" && p.routes[task] === "code") {
+ else if (task === CLIPS_SUGGEST && body.answers === undefined && p.routes[task] === "code") {
+ // The session labels them: the editor's plan is the request.
+ const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true });
+ if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true };
+ return { text: renderClipsSuggestRequest(String(body.project), (plan.body.plan ?? {}) as SuggestPlanView, 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 {
text:
@@ -596,18 +688,18 @@ 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 = String(body.article);
+ const article = task === CLIPS_SUGGEST ? "" : 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}` +
- (n ? `, ${task === "narrate" ? "narrating" : isStepTask(task) ? `drafting its ${task} on` : "making"} ${article} i${n}` : ` for ${article}`) +
+ (n ? `, ${task === "narrate" ? "narrating" : isStepTask(task) ? `drafting its ${task} on` : "making"} ${article} i${n}` : ` for ${article || String(body.project ?? "")}`) +
(body.model ? ` on ${String(body.model)}` : " on the policy's model") +
"." +
warnings.map((w) => `\n⚠ ${w}`).join("");
if (!req.wait) {
return {
text:
- `${head} It runs on the editor's draft queue. Follow it with generate (job: "${jobId}", article: "${article}"` +
+ `${head} It runs on the editor's draft queue. Follow it with generate (job: "${jobId}"${article ? `, article: "${article}"` : ""}` +
`${n ? `, iteration: ${n}` : ""}, wait: true), or get_job.`,
};
}
@@ -705,6 +797,16 @@ export const GENERATION_TOOLS = [
enum: [...AUTONOMIES],
description: "research: propose (every acquisition waits for the operator), limits (within the caps), auto (all through the editor) — default the settings'.",
},
+ 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.",
+ },
+ proposals: { type: "array", items: { type: "string" }, description: "clips-suggest: only these proposal ids." },
+ 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.',
+ },
wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." },
wait_seconds: {
type: "number",