Archilyzer · Source

archilyzer

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

commit 3ac23a385d51d4c22009f8f33313aa3f4942d7cb
parent 50df6fe6a35522bf194fcee8b5e9fac7f5ad8984
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 15:53:45 -0400

Merge r36/clips-suggest: the optional clips-suggest generation task, labels + rank in the clip editor, Ask the assistant with Apply

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

Diffstat:
M.claude/commands/gen.md | 6++++++
MSETTINGS.md | 4+++-
Acommon/controller/clipsSuggest.ts | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/reportDraft.ts | 65++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Acommon/lib/clips/suggest.d.mts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/suggest.mjs | 474+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/suggest.test.ts | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.test.ts | 14++++++++++++++
Mcommon/lib/generationSettings.ts | 17++++++++++++-----
Acommon/lib/report/draft/tasks/clipsSuggest.test.ts | 25+++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/clipsSuggest.ts | 348+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/testing/README.md | 1+
Acommon/testing/clips/reactionProject.d.mts | 9+++++++++
Acommon/testing/clips/reactionProject.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 2++
Aeditor/app/api/ops/_clipsSuggest.test.ts | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 20+++++++++++++++++++-
Mmcp/src/generation.test.ts | 41++++++++++++++++++++++++++++++++++++++++-
Mmcp/src/generation.ts | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mplans/FACTS.md | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-36/clips-suggest.md | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msettings.json.example | 3++-
Aumtool/app/api/report/clip-suggest/route.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/notes/NoteThread.tsx | 18++++++++++++++----
Mumtool/components/projects/review/ClipEditor.tsx | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aumtool/components/projects/review/ClipSuggest.tsx | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/notes.md | 11+++++++++++
Mumtool/docs/report-video.md | 43+++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/clips-suggest.spec.ts | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/clips-suggest-fixture.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Mumtool/lib/annotations/shape.mjs | 56+++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/annotations/types.ts | 10++++++++--
Aumtool/lib/report/clipSuggest.mjs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipSuggest.test.mjs | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
37 files changed, 3236 insertions(+), 36 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/SETTINGS.md b/SETTINGS.md @@ -1007,6 +1007,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `youtube` | `"local"` | A media draft: the YouTube title and description. | | `social` | `"local"` | A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code. | | `frames` | `"api"` | A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model. | +| `clips-suggest` | `"local"` | The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`). | | `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. | #### `generation.models` @@ -1112,7 +1113,8 @@ Default: "youtube": "local", "social": "local", "verdicts": "local", - "frames": "api" + "frames": "api", + "clips-suggest": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/common/controller/clipsSuggest.ts b/common/controller/clipsSuggest.ts @@ -0,0 +1,232 @@ +// `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 { umtoolUrl } from "../lib/umtoolUrl"; +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` (lane A's reader, common/lib/umtoolUrl.ts); null when unset. */ +export const umtoolOrigin = (env: Readonly<Record<string, string | undefined>> = process.env): string | null => umtoolUrl(env); + +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.test.ts b/common/lib/report/draft/tasks/clipsSuggest.test.ts @@ -0,0 +1,25 @@ +// Release 36 lane D: how a labels pass batches the proposals. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { batchesOf, LOCAL_BATCH_MAX } from "./clipsSuggest"; +import type { SuggestInput } from "../../../clips/suggest.mjs"; + +const items = (n: number, words = 20): SuggestInput[] => + Array.from({ length: n }, (_, i) => ({ + id: `p${String(i + 1).padStart(3, "0")}`, + start: i * 30, + end: i * 30 + 12, + score: 0.5, + used: false, + kinds: ["laugh"], + lines: [{ role: "host", speaker: 0, text: Array.from({ length: words }, (_, k) => `w${k}`).join(" ") }], + })); + +test("batches: 30 a call on the API; at most 20 locally, and fewer when the prompt cap is reached", () => { + assert.deepEqual(batchesOf(items(70), "claude-sonnet-5-5").map((b) => b.length), [30, 30, 10]); + assert.equal(LOCAL_BATCH_MAX, 20); + assert.deepEqual(batchesOf(items(45), "qwen3:8b").map((b) => b.length), [20, 20, 5]); + const long = batchesOf(items(45, 600), "qwen3:8b"); + assert.ok(long.length > 3 && long.every((b) => b.length >= 1 && b.length < 20), JSON.stringify(long.map((b) => b.length))); + assert.deepEqual(long.flat().map((i) => i.id), items(45).map((i) => i.id)); +}); diff --git a/common/lib/report/draft/tasks/clipsSuggest.ts b/common/lib/report/draft/tasks/clipsSuggest.ts @@ -0,0 +1,348 @@ +// 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; +// A local model answers at most this many in one call (an 8B model loses ids in a long list). +export const LOCAL_BATCH_MAX = 20; +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; on a local model at most LOCAL_BATCH_MAX, fitted to the prompt cap. */ +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 && (cur.length >= LOCAL_BATCH_MAX || 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/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **The clip editor can ask an assistant to label and rank the clip finder's proposals — optionally.** A **Suggest** button in the clip editor's side column asks the model your generation settings choose (the local model, the Claude API, or a Claude Code session through `/gen`) to name each proposal in at most six words, say in one line what makes it land, and rank them; the labels show on every clip and unused proposal, and **Sort by the assistant's rank** orders both lists by them. Labels made before the clips were proposed again are marked stale, not hidden. Nothing in the cut changes: the labels are suggestions. Without a model, or with no labels, the clip editor works as before. From a shell: `pnpm ops report-draft '{"task":"clips-suggest","project":"<dir>","dryRun":true}'` shows how many proposals and what it would cost first. +- **Ask the assistant about a clip, and apply what it suggests with one click.** On a comment in the clip editor, **Ask the assistant** has the model read your comment, the clip's words and the clips around it, and reply in the thread (badged "agent"). When it suggests a concrete edit — new edges, a merge with the next clip, or leaving the clip out — the reply shows an **Apply** button; nothing changes until you click it, and Apply does exactly what the clip editor's own buttons do. The editor needs `UMTOOL_URL` set to post the reply. - **Find clips: the clip finder from one button on the video page.** A video page's **Find clips** runs the whole chain umtool's clip finder needs, as one job: it saves the source video, transcribes the recording, makes its word timings (kept beside the transcript as `words.json`, so a second project from the same recording reuses them), fetches the stream's chat replay (YouTube), finds who speaks when, and then asks umtool to find the narrated-video segments and propose the clips. Each step whose output is already on disk is skipped, and the job's log says which ran and which were skipped. When it is done the panel links the umtool project and lists the segments it found, each with **Find clips in this part**. A target length can be given. When the workers are paused or the backfill lane is held, the step that needs them stops with a sentence saying so, and **Run while paused** runs this one video past them. The button is off, with a line saying why, when the editor has no `UMTOOL_URL`. The same from a terminal: `pnpm ops find-clips --json '{"slug","id"}'` (a `dryRun` lists what each step would do). Needs a restart of the editor. - **Transcribe one video while the workers are paused.** With the transcription workers paused, the video page's Transcribe row offers **Transcribe now (workers paused)**: that one transcription runs on a worker the pause alone switched off, and the pause stays on — the worker is paused again when it finishes. A worker you drained, disabled by hand or that is marked degraded is never used, and the lanes stay held. `pnpm ops transcribe` and `transcribe-one` take `"whilePaused": true`. - **Fetch a stream's chat replay on its own.** Media tools → **Fetch live chat** on a video page (`pnpm ops fetch-chat`) fetches the video's live chat and nothing else, paced like every YouTube request and on the platform's download queue, into the chat cues the index and the clip finder read. A video on another platform says there is no chat fetcher for it, as does a chat already fetched or a video that was never live. 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", diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10942,3 +10942,51 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri (disabled + `find-clips off` line without umtoolUrl), then the record's project link and `segments found` with `Find clips in this part` each. The Transcribe row's `Transcribe now (workers paused)` shows while the pool is paused. Media tools → `Fetch live chat`. + +## Release 36 lane D: the assistant's labels, Ask the assistant (verified 2026-10-19, branch `r36/clips-suggest`) + +- **`<project>/clip-suggestions.json`** `{model, at, proposedAt (reactions.json's at the pass), promptVersion + "clips-suggest-1", items: {<proposalId>: {label (≤ 6 words, ≤ 60 chars), why (one line, ≤ 200), rank (1 = best), + score (the model's 1–10), start, end (the span labelled)}}}`, items in rank order. ONE writer: `writeSuggestions` + (`yt-dlp-transcript-common/lib/clips/suggest.mjs`, tmp + rename, checked by `parseSuggestionsDoc`); readers + `readSuggestions` (`{doc, error}`) and `suggestionsState(doc, reactions)` → `{stale, why, passNewer, staleIds, + missing}`: stale when reactions.json's `proposedAt` is later than the file's (passNewer: every label), or per item + when its proposal is gone or its span moved > 0.05 s. Rank is CODE's: by score, then the finder's score, then time; + a pass merges over the old file's current items. Never a clip, the manifest, reactions.json or notes.json. +- **The task**: `report-draft {task: "clips-suggest", project: <abs dir>, model?, maxUsd?, proposals?, note?, answers?, + dryRun?}` — `article` must be absent (the body's `article` is ""); `project` absolute, normalised, never under + `paths.transcriptsDir`, holding a reactions.json. Route `settings.generation.routes["clips-suggest"]` (presets: code + code, balanced local, api api, local local; an older file keeps its preset); model `modelFor` (routed to `code` + with no model: refused, unless `answers`). Cap: the NARRATION cap (`capOf`), plus the daily cap; ledger rows `task + "clips-suggest", article "", iteration 0`. Queue `draft:local` (GPU arbiter, ollama unloaded) or `draft:api` (also + a session's answers, model `claude-code`). Batches: 30 a call on the API, fitted to the 8k prompt cap locally. + Progress metric `entries`. Marker `@@report-draft {article: "", iteration: 0, task, project, status, summary, usd, + kind: "labels", suggestions {labelled, refused, failed, file}} | {kind: "ask", ask {note, clip, proposal, + dropped}}`. A batch whose answer is not `{items: […]}` is refused whole; a label over six words / a score outside + 1–10 / an id never asked is refused per item. No label at all → the job fails. The ops route's `dryRun: true` + answers `{ok, plan: {project, model, provider, promptVersion, wordsFrom, proposals, calls, estimate {inputTokens, + outputTokens, usd}, request {system, user, schema, ids}}}` (`planClipsSuggestJob`). Words: reactions + `source.words` (relative) else words.json, else the corpus cues spread (`wordsFromCues`). +- **An Ask** (`note`): the note (open, anchored `entry`) from notes.json, the clip and its neighbours from the manifest + (`askClipsOf`: `next` only when the next timeline entry is a clip of the same recording), the words ±20 s with + times and roles → `{reply, proposal {kind none|trim|merge|cut, from, to}}`; kept proposals (`parseAskAnswer`): a + trim ≥ 0.5 s moving each edge ≤ 30 s and not a no-op; a merge only with a next clip; a cut. The reply is POSTed + to `<UMTOOL_URL>/api/notes?project=<dir>` with `Bearer WORKER_TOKEN` (stamped agent); without UMTOOL_URL or the + token the ask is refused at enqueue. +- **A notes reply's `proposal`** (`umtool/lib/annotations/shape.mjs` `validateReplyProposal`): `{kind: "trim", clip, + from, to, basis?} | {kind: "merge", clip, with, basis?} | {kind: "cut", clip, basis?}` (basis `{cutStart, + cutEnd}`), accepted on `{op: "reply"}` from an AGENT only (an operator's is a NoteError, 400); kept by + `parseNotesDoc` (a malformed one makes the file unreadable). Applied only by the clip editor's **Apply** (trim → + `trim` op, merge → `merge`, cut → ruling `cut`), which then replies "Applied: …" as the operator; Apply is offered + while no operator reply follows the agent's. +- **umtool**: `/api/report/clip-suggest` (GET `?project=` → `{suggestions, error, state, hasReactions, route {route, + model, why}, editorError, job}`; GET `&job=`; POST `{project, mode "labels", proposals?} | {project, mode "ask", + note}` → `{jobId, job}`, 409 while one runs; POST `?cancel=&project=`), via `askEditor` + (lib/articles/generation.ts) with the WORKER_TOKEN. The followed job is `<project>/.clip-suggest-job.json` + `{jobId, mode, note?, at}` (forgotten when seen ended, or unknown to the editor). Module + `umtool/lib/report/clipSuggest.mjs`; UI `components/projects/review/ClipSuggest.tsx` (`data-suggest-*`, + `data-note-action="ask"`, `data-reply-proposal`, `data-apply-proposal`). NoteThread gained `actions` and + `afterReply` props. +- **MCP `generate`**: task `clips-suggest` with `project` (no article); routed to code with no model/via/answers, it + posts the plan (`dryRun`) and answers the request for the session to label; `answers` go straight to the editor (no + policy read). Test kit: `common/testing/clips/reactionProject.mjs`. diff --git a/plans/release-36/clips-suggest.md b/plans/release-36/clips-suggest.md @@ -0,0 +1,99 @@ +# Release 36 lane D — `r36/clips-suggest`: the assistant's labels, Ask the assistant (as shipped) + +The plan of record is [clip-finder-2.md](clip-finder-2.md), lane D: the clip finder's OPTIONAL AI pass. Lane B's +analysis ([clip-analysis-2.md](clip-analysis-2.md)) and lanes A and C were merged into this branch before its gates. +Rulings followed: the UI works with no model (with no labels file, generation off or no model the clip editor is as it +was; every edit a proposal names is a button the operator already had); the only model calls are through +`settings.generation`'s routing (a `report-draft` job in the editor); nothing a model returns edits a clip — the +operator's **Apply** does; comments are notes; synthetic fixtures only; the live projects read only. + +## What + +1. **The `clips-suggest` generation task** — `GENERATION_TASKS` + every preset (code code, balanced local, api api, + local local; an older settings file keeps its preset), dispatched in `common/controller/reportDraft.ts` beside + verdicts into its own controller `common/controller/clipsSuggest.ts`. A body names `project` (the reactions + project's absolute directory; never inside the corpus) instead of `article`. Per proposal the prompt carries its + words, each line HOST / SUBJECT / OTHER by the turns, and what the finder heard (laugh / chat / comment); the model + answers `{items: [{id, label, why, score 1–10}]}` and CODE ranks (so batches rank globally): 30 proposals a call on + the API, at most 20 and within the 8k prompt cap locally. A malformed answer is refused whole; a label over six + words, a score outside 1–10 or an id never asked is refused per item, never trimmed to fit. Output + `<project>/clip-suggestions.json` `{model, at, proposedAt, promptVersion, items: {<id>: {label, why, rank, score, + start, end}}}` through its one writer (`common/lib/clips/suggest.mjs`), merged over the old file's still-current + labels. Cap: the narration cap (`capOf`) and the daily cap; usage rows `task "clips-suggest"`. Lanes: `draft:local` + through the GPU arbiter (ollama unloaded) or `draft:api`. The `code` route: the ops route's `dryRun: true` answers + the plan (proposals, calls, the estimate, the request); the MCP's `generate` hands that request to the session + and takes its `answers` back, read and written exactly as a model's (`model: "claude-code"`). SETTINGS.md and + settings.json.example regenerated; `/gen` names the task. +2. **The clip editor** — `umtool/components/projects/review/ClipSuggest.tsx` (+ small additive hooks in + `ClipEditor.tsx`): a label on each clip and unused proposal (the why on hover, and under the selected clip with its + rank), **Sort by the assistant's rank** for both lists, **Suggest** (one editor job via + `/api/report/clip-suggest`, which asks the editor with the WORKER_TOKEN through `askEditor` — the TS client + `lib/articles/generation.ts`, not chain-run's private `editorCall`) with its progress (remembered in + `<project>/.clip-suggest-job.json` across a reload), Stop; a stale file (a later proposal pass) or item (its + proposal moved or went) is marked stale, never hidden. Routed to Claude Code, Suggest is disabled with the `/gen` + line. +3. **Ask the assistant** on a comment: the editor job reads the note (and its thread), the clip's words with times and + speakers ±20 s, and the clips either side; replies through umtool's `POST /api/notes` as the agent + (`UMTOOL_URL` — lane A's `umtoolUrl` — and WORKER_TOKEN; refused at the ask without them), with at most one + proposal in the reply's new `proposal` field (`{kind: "trim", clip, from, to} | {kind: "merge", clip, with} | + {kind: "cut", clip}`, `basis` the cut it read). notes.json takes a proposal only from an agent + (`validateReplyProposal`). The thread shows it with **Apply**, which runs the clip editor's own trim / merge / + Cut ruling and answers "Applied: …" (so it is not offered twice). The job never applies anything. +4. **Tests + docs** — below; `umtool/docs/report-video.md` ("The assistant's labels, and asking it about a clip"), + `umtool/docs/notes.md` (a reply's proposal), FACTS ("Release 36 lane D"), CHANGELOG. + +## Interfaces (exported) + +common `lib/clips/suggest.mjs` (+ `.d.mts`, package export): `SUGGESTIONS_FILE`, `readSuggestions`, +`writeSuggestions`, `parseSuggestionsDoc`, `suggestionsState`, `suggestItems`, `roleLines`, `suggestPrompt`, +`SUGGEST_ANSWER_SCHEMA`, `parseSuggestAnswer`, `suggestionsDocOf`, `askNoteOf`, `askClipsOf`, `askPrompt`, +`ASK_ANSWER_SCHEMA`, `parseAskAnswer`, `wordsOfFile`, `wordsFor`, constants. `lib/report/draft/tasks/clipsSuggest.ts`: +`CLIPS_SUGGEST_TASK`, `CODE_MODEL`, `LOCAL_BATCH_MAX`, `loadClipsProject`, `batchesOf`, `planClipsSuggest`, +`runClipsSuggest`, `loadAsk`, `runClipsAsk`, `ClipsSuggestRefusal`. `controller/clipsSuggest.ts`: +`enqueueClipsSuggest`, `planClipsSuggestJob`, `projectDirOf`, `postReplyToUmtool`, `umtoolOrigin`. reportDraft body +keys `project`, `proposals`, `note`, `answers` (and `dryRun` for this task). Test kit +`common/testing/clips/reactionProject.mjs` (`reactionProject`, `writeReactionProject`, `labelAnswer`). umtool +`lib/report/clipSuggest.mjs` (`suggestionsView`, `parseSuggestRequest`, `draftBodyOf`, `readSuggestJob`, +`writeSuggestJob`, `clearSuggestJob`, `suggestJobView`, `suggestRouteOf`), `lib/annotations/shape.mjs` +`validateReplyProposal` / `REPLY_PROPOSAL_KINDS`, types `ReplyProposal`, `NoteReply.proposal`; NoteThread props +`actions`, `afterReply`. MCP `generate` takes `project`, `proposals`, `answers`. + +## Commits + +| sha | what | +|---|---| +| `b1aa9162` | clips: the clips-suggest generation task (common, editor ops route, MCP, settings, test kit, unit tests) | +| `912d9e6a` | umtool: the assistant in the clip editor — labels, sort, Suggest, Ask, Apply; the reply's proposal | +| `c41c9f8b` | umtool e2e: clips-suggest.spec.ts (fixture, the editor stub's clips-suggest job) | +| `17429bf7` | merge main (lanes A and C) | +| `2cc98b85` | clips: local batches at most 20; the Ask uses lane A's umtoolUrl | +| `39c70272` | docs: report-video.md, notes.md, SETTINGS.md + settings.json.example regenerated, FACTS, CHANGELOG | +| (this) | plans: this record | + +## Gates (through the shared lock, from the worktree root, after the merge of main) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` — clean (at 2cc98b85's tree and before each commit). +- common `pnpm --filter yt-dlp-transcript-common test` — 4694 tests, 4690 pass, 2 skipped; the 2 that failed were + `settings.json.example` / `SETTINGS.md is what the schema generates`, fixed by `archilyzer settings example` and + green on the re-run (`lib/settingsSchema*.test.ts` + the new batching test: 25 / 25). New in common: 7 + (`lib/clips/suggest.test.ts` 5, `generationSettings.test.ts` +1, `tasks/clipsSuggest.test.ts` 1). +- editor `pnpm --filter editor test` — 353 / 353 (new: `app/api/ops/_clipsSuggest.test.ts` 7 — the body, API + labels + plan + ledger, a malformed answer refused, the cap and the daily cap, local through the arbiter with a + six-word refusal and the unload, the code route's answers, Ask posting a trim and applying nothing). +- mcp `pnpm --filter yt-dlp-transcript-mcp test` — 379 / 379 (+1 clips-suggest; one preset expectation gained the + route). +- `pnpm run test:scripts` — 1294 tests, 1290 pass, 4 skipped (new: `umtool/lib/report/clipSuggest.test.mjs` 4). +- umtool `pnpm --filter umtool test` — 45 / 45. +- `archilyzer docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check` — clean. +- e2e (umtool, `E2E_MODE=dev`, one run): `clips-suggest.spec.ts` + `clip-editor.spec.ts` — **2 passed, 0 failed, + 1.0 min** (14.7 s + 33.7 s). +- Read-only plan on the live `~/reports/nik-drop-clips` (no model, nothing written): 112 proposals, words from + words.json; ~13.7k input / ~6.7k output tokens — Sonnet 5.5 4 calls ≈ $0.09, Haiku 4.5 ≈ $0.05; the local model + (before the 20-a-call cap) 2 calls, now 6. + +## Found and left + +- The editor stub in umtool's e2e cannot reach umtool, so the spec posts the agent's reply itself (as clip-editor.spec + does); the reply's POST from the job is covered by the editor unit test's `postReply` and `postReplyToUmtool`'s shape. +- An Ask needs `UMTOOL_URL` on the editor (lane A's Find clips needs it too); the live unit does not set it yet. +- `~/reports/nik-drop-highlights` holds no reactions.json: the second-half project Find clips makes is the one to label. diff --git a/settings.json.example b/settings.json.example @@ -256,7 +256,8 @@ "youtube": "local", "social": "local", "verdicts": "local", - "frames": "api" + "frames": "api", + "clips-suggest": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/umtool/app/api/report/clip-suggest/route.ts b/umtool/app/api/report/clip-suggest/route.ts @@ -0,0 +1,121 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation"; +import { + SuggestRequestError, + clearSuggestJob, + draftBodyOf, + parseSuggestRequest, + readSuggestJob, + suggestJobView, + suggestRouteOf, + suggestionsView, + writeSuggestJob, +} from "@/lib/report/clipSuggest.mjs"; + +export const dynamic = "force-dynamic"; + +// THE ASSISTANT IN THE CLIP EDITOR (release 36 lane D) -- optional, every +// part of it: the labels (Suggest), and an answer to a comment (Ask the +// assistant). The model runs in the EDITOR, routed by settings.generation (a +// `report-draft` job, task `clips-suggest`); this route asks it with the +// shared WORKER_TOKEN (lib/articles/generation.ts askEditor), remembers the +// job for the page and follows it. It never writes the manifest or a clip. +// +// GET ?project=<id> the labels, their stale state, the route, the job being followed +// GET ?project=<id>&job=<jobId> that job (ended: forgotten) +// POST { project, mode?: "labels", proposals? } | { project, mode: "ask", note } → { jobId, job } +// POST ?cancel=<jobId>&project=<id> stop it +const headers = { "cache-control": "no-store" }; + +async function suggestProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the assistant's labels are a report video's" }, { status: 400, headers }) }; + return { project }; +} + +const failed = (e: unknown) => { + const status = e instanceof EditorError ? e.status : e instanceof SuggestRequestError ? 400 : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); +}; + +async function jobOf(dir: string, id: string) { + const rec = await readSuggestJob(dir); + const job = await readDraftJob(id, 40); + const view = suggestJobView(rec && rec.jobId === id ? rec : null, job); + if (view.ended) await clearSuggestJob(dir, id); + return view; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await suggestProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + const dir = r.project.dir; + const id = url.searchParams.get("job"); + if (id) { + try { + return Response.json(await jobOf(dir, id), { headers }); + } catch (e) { + return failed(e); + } + } + const view = await suggestionsView(dir); + // The route and the followed job need the editor; without one the labels still show. + const policy = await readPolicy().catch((e: unknown) => e as Error); + const rec = await readSuggestJob(dir); + let job = null; + if (rec) { + job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => { + // The editor no longer knows it (restarted): forget it. + if (e instanceof EditorError && e.status === 404) await clearSuggestJob(dir, rec.jobId); + return null; + }); + } + return Response.json( + { + ...view, + route: policy instanceof Error ? null : suggestRouteOf(policy.generation, dir), + editorError: policy instanceof Error ? policy.message : null, + job, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const r = await suggestProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + try { + await cancelDraftJob(cancel); + return Response.json({ cancelled: true }, { headers }); + } catch (e) { + return failed(e); + } + } + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const r = await suggestProject(body.project); + if ("error" in r) return r.error; + const dir = r.project.dir; + try { + const req = parseSuggestRequest(body); + const running = await readSuggestJob(dir); + if (running) { + const view = await jobOf(dir, running.jobId).catch(() => null); + if (view && !view.ended) return Response.json({ error: "the assistant is already working on this project", job: view }, { status: 409, headers }); + } + const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: draftBodyOf(dir, req) }); + const jobId = String(answer.jobId ?? ""); + if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers }); + await writeSuggestJob(dir, { jobId, mode: req.mode, ...(req.mode === "ask" ? { note: req.note } : {}), at: new Date().toISOString() }); + const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, mode: req.mode, status: "queued", ended: false, queue: null, progress: null, last: null, summary: null })); + return Response.json({ ok: true, jobId, job }, { headers }); + } catch (e) { + return failed(e); + } +} diff --git a/umtool/components/notes/NoteThread.tsx b/umtool/components/notes/NoteThread.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; -import type { Note, NoteOp } from "@/lib/annotations/types"; +import type { Note, NoteOp, NoteReply } from "@/lib/annotations/types"; // One note: its text, who wrote it, its status, the replies, and what can be // done to it. Shared by the timed notes, the row notes and the take notes. @@ -14,12 +14,18 @@ export function NoteThread({ write, busy, head, + actions, + afterReply, }: { note: Note; write: (op: NoteOp) => Promise<unknown>; busy: boolean; /** What the note is on, drawn before its text (a timestamp, an entry id). */ head?: React.ReactNode; + /** More of the note's actions, after Reply (release 36: the clip editor's Ask the assistant). */ + actions?: React.ReactNode; + /** Drawn under one reply (release 36: an agent reply's proposal and its Apply). */ + afterReply?: (reply: NoteReply, index: number) => React.ReactNode; }) { const [reply, setReply] = useState<string | null>(null); const open = note.status === "open"; @@ -52,6 +58,7 @@ export function NoteThread({ <button type="button" data-note-action="reply" disabled={busy} onClick={() => setReply((r) => (r === null ? "" : null))} className="ink-link disabled:opacity-40"> Reply </button> + {actions} {note.author === "operator" && ( <button type="button" data-note-action="delete" disabled={busy} onClick={() => void write({ op: "delete", id: note.id })} className="text-[var(--color-dim)] hover:text-text disabled:opacity-40"> Delete @@ -60,9 +67,12 @@ export function NoteThread({ </span> </div> {note.replies.map((r, i) => ( - <div key={i} data-note-reply={i} className="ml-4 flex flex-wrap items-baseline gap-1.5 text-[11px]"> - {r.author === "agent" && <span className={badgeVariants({ variant: "meter", size: "sm" })}>agent</span>} - <span className="whitespace-pre-wrap text-[var(--color-dim)]">{r.text}</span> + <div key={i}> + <div data-note-reply={i} className="ml-4 flex flex-wrap items-baseline gap-1.5 text-[11px]"> + {r.author === "agent" && <span className={badgeVariants({ variant: "meter", size: "sm" })}>agent</span>} + <span className="whitespace-pre-wrap text-[var(--color-dim)]">{r.text}</span> + </div> + {afterReply?.(r, i)} </div> ))} {reply !== null && ( diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -12,6 +12,9 @@ import { edgeClock, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints } import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes"; import { cn } from "@/lib/utils"; import { startTakeJob } from "../NewTakePanel"; +// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). +import type { ReplyProposal } from "@/lib/annotations/types"; +import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest"; // --------------------------------------------------------------------------- // THE CLIP EDITOR (release 35 C2): a person hops in on an assistant's clips. @@ -99,6 +102,10 @@ export default function ClipEditor({ const committed = cutOf(clip); const cut = draft ?? committed; const speakers = view.reactions?.speakers ?? []; + // The assistant (release 36 lane D): labels, a rank to sort by, Suggest, Ask. + const assistant = useClipSuggest(project); + const [byRank, setByRank] = useState(false); + const rankOf = (proposal: string | null | undefined) => assistant.labelOf(proposal)?.rank ?? Number.POSITIVE_INFINITY; // The page's address names the clip, so a reload (or a link) lands on it. useEffect(() => { @@ -292,6 +299,24 @@ export default function ClipEditor({ }, 1500); return () => clearInterval(t); }, [proposing, reload]); + // An agent reply's proposal, applied ON THE OPERATOR'S CLICK through the + // writer every other edit here uses (release 36 lane D). + const canApply = (p: ReplyProposal): string | null => { + const at = clips.findIndex((c) => c.id === p.clip); + if (at < 0) return `${p.clip} is no longer in the cut`; + if (p.kind === "merge" && clips[at + 1]?.id !== p.with) return `${p.with} is no longer the next clip`; + return null; + }; + const applyProposal = async (p: ReplyProposal): Promise<boolean> => { + await flush(); + const j = + p.kind === "trim" + ? await write({ op: "trim", clip: p.clip, cutStart: p.from, cutEnd: p.to }, `Applied: ${proposalWords(p)}`) + : p.kind === "merge" + ? await write({ op: "merge", clip: p.clip }, `Applied: ${proposalWords(p)}`) + : await write({ op: "ruling", clip: p.clip, verdict: "cut" }, `Applied: ${proposalWords(p)}`); + return !!j; + }; const rx = view.reactions; const rolesStale = rolesChanged || (!!rx?.rolesChangedAt && (!rx.proposedAt || rx.rolesChangedAt > rx.proposedAt)); const snap = () => { @@ -390,6 +415,7 @@ export default function ClipEditor({ {prov} </p> )} + <SuggestWhy item={assistant.labelOf(assist?.proposal)} /> {(quoteNow ?? clip.quote) && ( <p data-editor-quote="" className="m-0 max-w-[70ch] text-[13px] leading-snug text-text"> {quoteNow || clip.quote} @@ -539,7 +565,7 @@ export default function ClipEditor({ </div> {/* ---- comments and history ---------------------------------------- */} - <ClipNotes project={project} clipId={clip.id} /> + <ClipNotes project={project} clipId={clip.id} assistant={assistant} canApply={canApply} onApply={applyProposal} /> {edits.length > 0 && ( <details data-editor-history={edits.length} className="text-[12px] text-text-2"> <summary className="cursor-pointer text-muted">{plural(edits.length, "edit")} to this clip</summary> @@ -557,12 +583,13 @@ export default function ClipEditor({ {/* ---- the list, the proposals, the speakers, the take --------------- */} <aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-editor-side=""> + <SuggestPanel s={assistant} sorted={byRank} onSort={setByRank} /> <section> <h2 className="micro mb-1"> {plural(clips.length, "clip")} · {clips.filter((c) => c.ruling === "keep").length} kept · {clips.filter((c) => c.ruling === "cut").length} cut </h2> <ol className="m-0 list-none space-y-0.5 p-0" data-editor-list=""> - {clips.map((c) => { + {(byRank ? [...clips].sort((a, b) => rankOf(a.assist?.proposal) - rankOf(b.assist?.proposal)) : clips).map((c) => { const cc = cutOf(c); return ( <li key={c.id}> @@ -577,6 +604,7 @@ export default function ClipEditor({ <span className="num font-mono text-[11px] text-muted"> {edgeClock(cc.cutStart)} · {(cc.cutEnd - cc.cutStart).toFixed(0)} s </span> + <SuggestLabel item={assistant.labelOf(c.assist?.proposal)} /> <span className="ml-auto flex gap-1"> {c.assist?.by === "operator" && <span className={badgeVariants({ variant: "info", size: "sm" })}>you</span>} {c.ruling && <span className={rulingBadge(c.ruling)}>{c.ruling}</span>} @@ -597,15 +625,19 @@ export default function ClipEditor({ <p className="m-0 text-[12px] text-muted">Every proposal is in the cut.</p> ) : ( <ul className="m-0 list-none space-y-1 p-0"> - {view.reactions.proposals.map((p) => ( + {(byRank ? [...view.reactions.proposals].sort((a, b) => rankOf(a.id) - rankOf(b.id)) : view.reactions.proposals).map((p) => ( <li key={p.id} data-proposal={p.id} className="flex items-baseline gap-2 text-[12px] text-text-2"> <span className="font-mono text-[11.5px]">{p.id}</span> <span className="num font-mono text-[11px] text-muted"> {edgeClock(p.start)} · {(p.end - p.start).toFixed(0)} s{typeof p.score === "number" ? ` · ${p.score.toFixed(2)}` : ""} </span> - <span className="min-w-0 flex-1 truncate" title={p.why}> - {p.why} - </span> + {assistant.labelOf(p.id) ? ( + <SuggestLabel item={assistant.labelOf(p.id)} className="flex-1" /> + ) : ( + <span className="min-w-0 flex-1 truncate" title={p.why}> + {p.why} + </span> + )} <button type="button" data-bring-in={p.id} disabled={busy} onClick={() => bringIn(p)} className={buttonVariants({ size: "sm" })}> Bring in </button> @@ -1023,8 +1055,28 @@ function EdgeControl({ edge, value, onNudge, onSet, onPlayhead }: { edge: "in" | } /** The notes on one clip: its thread (an agent's replies too), resolve / reopen, a box for another. */ -function ClipNotes({ project, clipId }: { project: string; clipId: string }) { +function ClipNotes({ + project, + clipId, + assistant, + canApply, + onApply, +}: { + project: string; + clipId: string; + /** Release 36 lane D: Ask the assistant on a comment, and Apply its proposal. */ + assistant?: ClipSuggest; + canApply?: (p: ReplyProposal) => string | null; + onApply?: (p: ReplyProposal) => Promise<boolean>; +}) { const notes = useSharedNotes({ project }); + const reloadNotes = notes.reload; + // An Ask's reply lands in notes.json from the editor's job: read it again when a job ends. + useEffect(() => { + if (assistant?.ended) void reloadNotes(); + }, [assistant?.ended, reloadNotes]); + const askJob = assistant?.job && assistant.job.mode === "ask" ? assistant.job : null; + const askBlocked = assistant?.view?.route?.why ?? null; const [text, setText] = useState(""); const mine = notesOn(notes.notes, { kind: "entry", entry: clipId }).filter((n) => n.anchor.kind !== "moment"); const open = mine.filter((n) => n.status === "open").length; @@ -1037,7 +1089,45 @@ function ClipNotes({ project, clipId }: { project: string; clipId: string }) { <section data-clip-notes={clipId} data-open-notes={open} className="space-y-1.5 rounded-[3px] border border-seam bg-panel p-2.5"> <h2 className="micro m-0">Comments{mine.length ? ` — ${open} open of ${mine.length}` : ""}</h2> {mine.map((n) => ( - <NoteThread key={n.id} note={n} write={notes.write} busy={notes.busy} head={n.anchor.kind === "edit" ? <span className={badgeVariants({ variant: "info", size: "sm" })}>edit · {n.anchor.field}</span> : null} /> + <NoteThread + key={n.id} + note={n} + write={notes.write} + busy={notes.busy} + head={n.anchor.kind === "edit" ? <span className={badgeVariants({ variant: "info", size: "sm" })}>edit · {n.anchor.field}</span> : null} + actions={ + assistant?.view?.hasReactions && n.status === "open" && n.anchor.kind === "entry" ? ( + <button + type="button" + data-note-action="ask" + disabled={notes.busy || !!askBlocked || (!!askJob && !askJob.ended)} + title={askBlocked ?? "the assistant reads this comment, the clip's words and its neighbours, and replies here; an edit it proposes waits for your Apply"} + onClick={() => void assistant.start({ mode: "ask", note: n.id })} + className="ink-link disabled:opacity-40" + > + {askJob && askJob.note === n.id && !askJob.ended ? "Asking…" : "Ask the assistant"} + </button> + ) : null + } + afterReply={ + canApply && onApply + ? (r, i) => ( + <ReplyProposalRow + reply={r} + index={i} + replies={n.replies} + canApply={canApply} + busy={notes.busy} + onApply={(p) => + void onApply(p).then((ok) => { + if (ok) void notes.write({ op: "reply", id: n.id, text: `Applied: ${proposalWords(p)}` }); + }) + } + /> + ) + : undefined + } + /> ))} <div className="flex flex-wrap items-start gap-2"> <textarea @@ -1056,6 +1146,12 @@ function ClipNotes({ project, clipId }: { project: string; clipId: string }) { Add comment </button> </div> + {askJob && ( + <div className="text-[11.5px] text-text-2" data-ask-job={askJob.status}> + {askJob.ended ? (askJob.status === "done" ? (askJob.summary ?? "The assistant replied") : `The ask ${askJob.status}${askJob.last ? ` — ${askJob.last}` : ""}`) : `Asking the assistant${askJob.status === "queued" ? " — queued" : ""}…`} + </div> + )} + {assistant?.error && <div className="text-[12px] text-reject-text" data-ask-error="">{assistant.error}</div>} {notes.error && <div className="text-[12px] text-reject-text">{notes.error}</div>} </section> ); diff --git a/umtool/components/projects/review/ClipSuggest.tsx b/umtool/components/projects/review/ClipSuggest.tsx @@ -0,0 +1,260 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import type { NoteReply, ReplyProposal } from "@/lib/annotations/types"; +import { edgeClock } from "@/lib/report/clipEditorModel.mjs"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE ASSISTANT IN THE CLIP EDITOR (release 36 lane D): optional, every part. +// +// the labels clip-suggestions.json: a label on each clip and unused +// proposal (its why on hover, and under the selected clip), a +// rank the list can be sorted by; stale labels are marked +// Suggest one editor job (`report-draft` task `clips-suggest`, routed by +// settings.generation) that labels the proposals; its progress +// Ask on a comment: a job that answers it as the agent, with at most +// one edit the operator applies with Apply +// +// /api/report/clip-suggest is the only route. Nothing here edits a clip: an +// Apply goes through the clip editor's own writer, on the operator's click. +// --------------------------------------------------------------------------- + +export type SuggestionItem = { label: string; why: string; rank: number; score?: number; start?: number; end?: number }; +export type SuggestJob = { + id: string; + mode: "labels" | "ask"; + note?: string; + status: string; + ended: boolean; + queue: { key?: string; position?: number } | null; + progress: { metric: string; current: number; target: number } | null; + last: string | null; + summary: string | null; +}; +export type SuggestView = { + suggestions: { model: string; at: string; proposedAt?: string | null; items: Record<string, SuggestionItem> } | null; + error: string | null; + state: { stale: boolean; why: string | null; passNewer: boolean; staleIds: string[]; missing: string[] }; + hasReactions: boolean; + route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null; + editorError: string | null; + job: SuggestJob | null; +}; + +export type ClipSuggest = { + view: SuggestView | null; + job: SuggestJob | null; + error: string | null; + /** The label of a proposal, or null. */ + labelOf: (proposal: string | null | undefined) => (SuggestionItem & { id: string; stale: boolean }) | null; + start: (body: { mode: "labels"; proposals?: string[] } | { mode: "ask"; note: string }) => Promise<void>; + cancel: () => Promise<void>; + /** Bumped every time a job is seen to end (a page reloads what it wrote). */ + ended: number; +}; + +export function useClipSuggest(project: string): ClipSuggest { + const [view, setView] = useState<SuggestView | null>(null); + const [job, setJob] = useState<SuggestJob | null>(null); + const [error, setError] = useState<string | null>(null); + const [ended, setEnded] = useState(0); + const load = useCallback(async () => { + const r = await fetch(`/api/report/clip-suggest?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + if (!r) return; + const j = (await r.json().catch(() => null)) as (SuggestView & { error?: string }) | null; + if (!r.ok || !j) { + setError(j?.error ?? `HTTP ${r.status}`); + return; + } + setView(j); + setJob(j.job && !j.job.ended ? j.job : null); + }, [project]); + useEffect(() => { + void load(); + }, [load]); + const live = job && !job.ended ? job.id : null; + const mode = useRef<SuggestJob | null>(null); + mode.current = job; + useEffect(() => { + if (!live) return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/clip-suggest?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as SuggestJob; + setJob({ ...j, ...(mode.current?.note && !j.note ? { note: mode.current.note } : {}) }); + if (j.ended) { + setEnded((n) => n + 1); + await load(); + setJob(j); + } + }, 1500); + return () => clearInterval(t); + }, [live, project, load]); + const start = useCallback( + async (body: { mode: "labels"; proposals?: string[] } | { mode: "ask"; note: string }) => { + setError(null); + const r = await fetch("/api/report/clip-suggest", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); + const j = (await r.json().catch(() => ({}))) as { job?: SuggestJob; error?: string }; + if (j.job) setJob({ ...j.job, ...(body.mode === "ask" ? { note: body.note } : {}) }); + if (!r.ok) setError(j.error ?? `HTTP ${r.status}`); + }, + [project], + ); + const cancel = useCallback(async () => { + if (!job) return; + await fetch(`/api/report/clip-suggest?cancel=${encodeURIComponent(job.id)}&project=${encodeURIComponent(project)}`, { method: "POST" }).catch(() => null); + }, [job, project]); + const items = view?.suggestions?.items ?? null; + const staleIds = view?.state.staleIds; + const fileStale = !!view?.state.passNewer; + const labelOf = useCallback( + (proposal: string | null | undefined) => { + if (!proposal || !items?.[proposal]) return null; + return { id: proposal, ...items[proposal], stale: fileStale || !!staleIds?.includes(proposal) }; + }, + [items, staleIds, fileStale], + ); + return { view, job, error, labelOf, start, cancel, ended }; +} + +/** A clip's or a proposal's label: its words, its why on hover; marked when stale. */ +export function SuggestLabel({ item, className }: { item: (SuggestionItem & { id: string; stale: boolean }) | null; className?: string }) { + if (!item) return null; + return ( + <span + data-suggest-label={item.id} + data-suggest-rank={item.rank} + data-suggest-stale={item.stale ? "" : undefined} + title={`${item.why}${item.stale ? " (stale: the proposal changed since)" : ""}`} + className={cn("min-w-0 truncate text-[12px] text-text-2", item.stale && "italic text-muted", className)} + > + {item.label} + </span> + ); +} + +/** The selected clip's label and why, under its provenance. */ +export function SuggestWhy({ item }: { item: (SuggestionItem & { id: string; stale: boolean }) | null }) { + if (!item) return null; + return ( + <p data-suggest-why={item.id} className="m-0 text-[12.5px] text-text-2"> + <span className="font-medium text-text">{item.label}</span> · the assistant ranks it {item.rank} + {item.stale ? " · stale" : ""} · {item.why} + </p> + ); +} + +const jobLine = (j: SuggestJob) => { + const what = j.mode === "ask" ? "Asking the assistant" : "Labelling the proposals"; + if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `${j.mode === "ask" ? "The ask" : "Suggest"} ${j.status}${j.last ? ` — ${j.last}` : ""}`; + if (j.status === "queued") return `${what} — queued${j.queue?.position ? ` (${j.queue.position} in line on ${j.queue.key ?? "the draft queue"})` : ""}`; + return `${what}${j.progress ? ` — ${j.progress.current}/${j.progress.target} ${j.progress.metric}` : ""}${j.last ? ` · ${j.last}` : ""}`; +}; + +/** Suggest, its progress, the labels' state and the sort toggle — in the side column. */ +export function SuggestPanel({ s, sorted, onSort }: { s: ClipSuggest; sorted: boolean; onSort: (on: boolean) => void }) { + const v = s.view; + if (!v?.hasReactions) return null; + const n = v.suggestions ? Object.keys(v.suggestions.items).length : 0; + const running = !!s.job && !s.job.ended; + const blocked = v.route?.why ?? null; + return ( + <section data-suggest-panel={n} data-suggest-state={v.state.stale ? "stale" : n ? "fresh" : "none"} className="space-y-1"> + <h2 className="micro m-0">The assistant</h2> + <div className="flex flex-wrap items-center gap-2 text-[12px] text-text-2"> + <button + type="button" + data-suggest-button="" + disabled={running || !!blocked} + title={blocked ?? (v.route?.model ? `labels and a rank for every proposal, on ${v.route.model}; nothing in the cut changes` : "labels and a rank for every proposal; nothing in the cut changes")} + onClick={() => void s.start({ mode: "labels" })} + className={buttonVariants({ size: "sm" })} + > + {running && s.job?.mode === "labels" ? "Suggesting…" : n ? "Suggest again" : "Suggest"} + </button> + {running && ( + <button type="button" data-suggest-cancel="" onClick={() => void s.cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Stop + </button> + )} + {n > 0 && ( + <label className="inline-flex items-center gap-1"> + <input type="checkbox" data-suggest-sort="" checked={sorted} onChange={(e) => onSort(e.target.checked)} /> + Sort by the assistant&rsquo;s rank + </label> + )} + </div> + {n > 0 && v.suggestions && ( + <p className="m-0 text-[11.5px] text-muted" data-suggest-meta=""> + {n} labelled by {v.suggestions.model} · {new Date(v.suggestions.at).toLocaleString()} + </p> + )} + {v.state.stale && ( + <p className="m-0 text-[11.5px] text-doubt-text" data-suggest-stale-line=""> + Stale: {v.state.why}. + </p> + )} + {blocked && <p className="m-0 text-[11.5px] text-muted" data-suggest-blocked="">{blocked}</p>} + {s.job && ( + <p className="m-0 text-[11.5px] text-text-2" data-suggest-job={s.job.status} data-suggest-job-mode={s.job.mode}> + {jobLine(s.job)} + </p> + )} + {(s.error || v.error) && ( + <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-suggest-error=""> + {s.error ?? v.error} + </p> + )} + </section> + ); +} + +/** What an agent reply proposes, in words. */ +export function proposalWords(p: ReplyProposal): string { + if (p.kind === "trim") return `trim ${p.clip} to ${edgeClock(p.from)}–${edgeClock(p.to)} (${(p.to - p.from).toFixed(1)} s)`; + if (p.kind === "merge") return `merge ${p.clip} with ${p.with}`; + return `cut ${p.clip}`; +} + +/** + * Under an agent's reply that carries a proposal: Apply (the clip editor's own + * writer does it) while nobody has answered the reply since. `canApply`: why + * not, or null. + */ +export function ReplyProposalRow({ + reply, + index, + replies, + canApply, + busy, + onApply, +}: { + reply: NoteReply; + index: number; + replies: NoteReply[]; + canApply: (p: ReplyProposal) => string | null; + busy: boolean; + onApply: (p: ReplyProposal) => void; +}) { + const p = reply.proposal; + if (!p || reply.author !== "agent") return null; + const answered = replies.slice(index + 1).some((r) => r.author === "operator"); + const why = canApply(p); + return ( + <div data-reply-proposal={p.kind} className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2"> + <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span> + <span>{proposalWords(p)}</span> + {answered ? ( + <span className="text-muted" data-reply-proposal-answered="">answered</span> + ) : ( + <button type="button" data-apply-proposal={p.kind} disabled={busy || !!why} title={why ?? "do it now, through the clip editor (Undo on the Cut tab takes a merge back)"} onClick={() => onApply(p)} className={buttonVariants({ variant: "go", size: "sm" })}> + Apply + </button> + )} + {why && !answered && <span className="text-muted">{why}</span>} + </div> + ); +} diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md @@ -91,6 +91,17 @@ it (`common/publish/composeReports.test.ts` holds that), so a note is never publ "resolvedAt": "…", "resolvedBy": "agent" } ] } ``` +**A reply's proposal** (release 36, the clip editor's Ask the assistant): an +AGENT's reply may carry ONE edit of one clip it suggests — +`"proposal": {"kind": "trim", "clip": "r002", "from": 94.8, "to": 99, "basis": +{"cutStart": 88, "cutEnd": 99}}`, `{"kind": "merge", "clip", "with": <the next +clip>}` or `{"kind": "cut", "clip"}` (`basis`: the clip's cut when the agent read +it). `{op: "reply", id, text, proposal}` takes it only from an agent (the page's +own write with one is refused), checked by `validateReplyProposal` +(`lib/annotations/shape.mjs`); a file whose proposal is not that shape does not +parse. Nothing applies it but the operator's **Apply** in the clip editor, which +answers the reply "Applied: …". + `source` is filled on the first write. For an article it comes from `lib/articles/sources.mjs`: a draft whose `id` or file name is the report id (allowing a `polemic-` prefix either way; the workspace whose generator names the site wins a diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1204,6 +1204,49 @@ back. The writers are `lib/report/manifest.mjs` (`updateClip`, `restoreClip`, `splitClip`, `mergeClips`, `addClip`); the editor's operations are `lib/report/clipEditor.mjs` behind `/api/report/clip-editor`. +### The assistant's labels, and asking it about a clip (optional) + +Release 36: a model may help — never instead of you, and never by editing the +cut. With no model, generation routed elsewhere, or no labels file, the clip +editor is exactly as above. + +- **Suggest** (the side column's *The assistant*) starts the editor's + `report-draft` task `clips-suggest` on this project, routed by + `settings.generation.routes["clips-suggest"]` like any generation (the local + model through the GPU arbiter, or the Claude API under the narration cap and + the daily cap; routed to Claude Code, the button says to run `/gen` in a + session instead). Every proposal's words go in, each line marked HOST / + SUBJECT / OTHER by the turns, with what the finder heard (laugh, chat, + comment); back come a **label** (at most six words — a longer one is refused, + never cut down), a **why** (one line) and a score from 1 to 10, from which + code ranks them (1 = best). They land in `<project>/clip-suggestions.json` + `{model, at, proposedAt, promptVersion, items: {<proposalId>: {label, why, + rank, score, start, end}}}`, written whole by its one writer + (`yt-dlp-transcript-common/lib/clips/suggest.mjs`); a later pass keeps the + labels of proposals it did not ask about. The job's progress shows under the + button (and after a reload: `.clip-suggest-job.json`). +- **The labels** show on each clip and each unused proposal (the why on hover, + and under the selected clip with its rank). **Sort by the assistant's rank** + orders both lists by it; off, the cut's order. A label made before the last + proposal pass, or for a proposal that has moved or gone, is marked **stale** — + shown, never hidden; Suggest again to refresh them. +- **Ask the assistant** on a comment: the editor's job reads the comment (and + its thread), the clip's words with their times and speakers, ±20 s around it + and the clips either side, and replies in the thread as the agent (`POST + /api/notes` with the editor's `WORKER_TOKEN`; the editor needs `UMTOOL_URL`). + A reply may carry ONE proposal the clip editor can perform — a trim to new + edges (each moved at most 30 s), a merge with the next clip, or a cut — shown + under it with **Apply**. Nothing happens until you click it: Apply runs the + same trim / merge / Cut the buttons above do, and answers the reply + "Applied: …", so it is not offered twice. + +`/api/report/clip-suggest` is the page's route: GET the labels, their stale +state, the route and the job being followed; POST `{project, mode: "labels", +proposals?}` or `{project, mode: "ask", note}`. From a shell: `pnpm ops +report-draft '{"task": "clips-suggest", "project": "<dir>", "dryRun": true}'` +(the plan: proposals, calls, the cost estimate), then the same without +`dryRun`. + ## The look: captions, loudness, shorts (release 36) Three render keys and one clip key, all opt-in (absent or `null` is off, and the diff --git a/umtool/e2e/clips-suggest.spec.ts b/umtool/e2e/clips-suggest.spec.ts @@ -0,0 +1,128 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// The assistant in the clip editor (release 36 lane D) — optional, every +// part: the labels from clip-suggestions.json on each clip and unused +// proposal (the why under the selected clip), "Sort by the assistant's rank" +// reorders both lists, a later proposal pass marks the labels stale (shown, +// not hidden), Suggest starts the editor's `clips-suggest` job (the editor +// stub labels every proposal through common's writer) and shows its end; Ask +// the assistant on a comment sends the note to the editor; an agent's reply +// with a trim proposal shows Apply, and Apply performs the trim through the +// clip editor's writer — only then. Fixture: e2e/fixtures/clips-suggest-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/clips-suggest-fixture"; +const DIR = path.join(FIXTURE, "reports", "clips-suggest-fixture"); +const TOKEN = "umtool-e2e-token"; + +const json = (name: string) => { + try { + return JSON.parse(readFileSync(path.join(DIR, name), "utf8")); + } catch { + return null; + } +}; +type Clip = { id: string; cutStart?: number; cutEnd?: number; assist?: { by: string } }; +const clip = (id: string): Clip | null => (json("video.manifest.json")?.timeline ?? []).find((e: Clip & { type: string }) => e.type === "clip" && e.id === id) ?? null; +const stubRequests = (): { route: string; task?: string; project?: string; note?: string }[] => { + try { + return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")); + } catch { + return []; + } +}; + +test("the assistant's labels, the sort, stale, Suggest, Ask, and Apply on the operator's click", async ({ page, request }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 900 }); + await page.goto(`/projects/${PROJECT}/clips`); + const editor = page.locator("[data-clip-editor]"); + await expect(editor).toHaveAttribute("data-clip-editor", "r001"); + + // The labels: on each clip, on each unused proposal; the selected clip's why. + const panel = page.locator("[data-suggest-panel]"); + await expect(panel).toHaveAttribute("data-suggest-panel", "5"); + await expect(panel).toHaveAttribute("data-suggest-state", "fresh"); + await expect(page.locator('[data-editor-row="r001"] [data-suggest-label="p001"]')).toHaveText("the complete sentence"); + await expect(page.locator('[data-proposal="p005"] [data-suggest-label="p005"]')).toHaveText("a quiet chuckle"); + await expect(page.locator('[data-proposal="p005"] [data-suggest-label="p005"]')).toHaveAttribute("title", "Why p005 lands."); + await expect(page.locator('[data-suggest-why="p001"]')).toContainText("the complete sentence · the assistant ranks it 3 · Why p001 lands."); + + // Sort by the assistant's rank: both lists reorder; off again, the cut's order. + const rows = page.locator("[data-editor-list] [data-editor-row]"); + const proposals = page.locator("[data-editor-proposals] [data-proposal]"); + await expect(rows).toHaveText([/^r001/, /^r002/, /^r003/]); + await page.locator("[data-suggest-sort]").check(); + await expect(rows.first()).toHaveAttribute("data-editor-row", "r003"); + expect(await rows.evaluateAll((els) => els.map((e) => e.getAttribute("data-editor-row")))).toEqual(["r003", "r001", "r002"]); + expect(await proposals.evaluateAll((els) => els.map((e) => e.getAttribute("data-proposal")))).toEqual(["p005", "p004"]); + await page.locator("[data-suggest-sort]").uncheck(); + expect(await rows.evaluateAll((els) => els.map((e) => e.getAttribute("data-editor-row")))).toEqual(["r001", "r002", "r003"]); + + // A later proposal pass: the labels are marked stale, never hidden. + const reactions = json("reactions.json"); + writeFileSync(path.join(DIR, "reactions.json"), JSON.stringify({ ...reactions, proposedAt: "2026-02-01T00:00:00.000Z" })); + await page.reload(); + await expect(panel).toHaveAttribute("data-suggest-state", "stale"); + await expect(page.locator("[data-suggest-stale-line]")).toHaveText("Stale: the proposals were made again after these labels."); + await expect(page.locator('[data-editor-row="r001"] [data-suggest-label="p001"]')).toHaveAttribute("data-suggest-stale", ""); + + // Suggest: the editor's clips-suggest job on this project; its end shows, the labels are fresh. + await page.locator("[data-suggest-button]").click(); + await expect(page.locator("[data-suggest-job]")).toHaveAttribute("data-suggest-job", "done", { timeout: 20_000 }); + await expect(page.locator("[data-suggest-job]")).toHaveText("5 proposals labelled on qwen3:8b"); + await expect(panel).toHaveAttribute("data-suggest-state", "fresh"); + await expect(page.locator('[data-editor-row="r001"] [data-suggest-label="p001"]')).toHaveText("stub label p001"); + expect(stubRequests().filter((r) => r.route === "report-draft" && r.task === "clips-suggest").map((r) => [r.project, r.note ?? null])).toEqual([[DIR, null]]); + expect(json("clip-suggestions.json")?.items?.p005?.rank).toBe(1); + + // A comment on r002, and Ask the assistant: the note goes to the editor. + await page.locator('[data-editor-row="r002"]').click(); + await expect(editor).toHaveAttribute("data-clip-editor", "r002"); + await page.locator("[data-clip-note-input]").fill("start it half a second later"); + await page.locator("[data-clip-note-add]").click(); + const thread = page.locator('[data-clip-notes="r002"] [data-note-id]'); + await expect(thread).toHaveCount(1); + const noteId = (await thread.getAttribute("data-note-id"))!; + await thread.locator('[data-note-action="ask"]').click(); + await expect(page.locator("[data-ask-job]")).toHaveAttribute("data-ask-job", "done", { timeout: 20_000 }); + expect(stubRequests().filter((r) => r.task === "clips-suggest" && r.note).map((r) => [r.project, r.note])).toEqual([[DIR, noteId]]); + + // The agent's reply carries a trim (the reply the job posts, posted here: the stub cannot reach umtool). + const read = await (await request.get(`/api/notes?project=${encodeURIComponent(PROJECT)}`)).json(); + const replied = await request.post(`/api/notes?project=${encodeURIComponent(PROJECT)}`, { + headers: { authorization: `Bearer ${TOKEN}` }, + data: { token: read.token, op: { op: "reply", id: noteId, text: "Start it on the breath at 4.5 s.", proposal: { kind: "trim", clip: "r002", from: 4.5, to: 6, basis: { cutStart: 4, cutEnd: 6 } } } }, + }); + expect(replied.ok()).toBe(true); + // The page's own write may not carry one: a proposal is an agent's. + const forged = await request.post(`/api/notes?project=${encodeURIComponent(PROJECT)}`, { + data: { op: { op: "reply", id: noteId, text: "x", proposal: { kind: "cut", clip: "r002" } } }, + }); + expect(forged.status()).toBe(400); + await page.reload(); + await expect(editor).toHaveAttribute("data-clip-editor", "r002"); + const proposal = page.locator('[data-clip-notes="r002"] [data-reply-proposal="trim"]'); + await expect(proposal).toContainText("trim r002 to 0:04.5–0:06.0 (1.5 s)"); + // Nothing moved until the click. + expect([clip("r002")?.cutStart, clip("r002")?.cutEnd]).toEqual([4, 6]); + await proposal.locator('[data-apply-proposal="trim"]').click(); + await expect.poll(() => clip("r002")?.cutStart).toBe(4.5); + expect(clip("r002")?.cutEnd).toBe(6); + expect(clip("r002")?.assist?.by).toBe("operator"); + await expect(page.locator("[data-editor-status]")).toHaveText("Applied: trim r002 to 0:04.5–0:06.0 (1.5 s)"); + // The operator's "Applied" reply answers it: no second Apply. + await expect(proposal.locator("[data-reply-proposal-answered]")).toHaveCount(1); + await expect(proposal.locator("[data-apply-proposal]")).toHaveCount(0); + const notes = json("notes.json")?.notes ?? []; + expect(notes[0].replies.map((r: { author: string; text: string }) => [r.author, r.text])).toEqual([ + ["agent", "Start it on the breath at 4.5 s."], + ["operator", "Applied: trim r002 to 0:04.5–0:06.0 (1.5 s)"], + ]); +}); diff --git a/umtool/e2e/fixtures/clips-suggest-fixture.mjs b/umtool/e2e/fixtures/clips-suggest-fixture.mjs @@ -0,0 +1,88 @@ +// What clips-suggest.spec.ts reads and writes (release 36 lane D): the clip +// editor's three assistant clips on vid1 (the clip editor fixture's cut, +// copied under its own name so the two specs never edit one project), its +// reactions.json and words.json, every window cached — and the assistant's +// labels for the five proposals (clip-suggestions.json, as the editor's +// `clips-suggest` task writes it), ranked so the sort reorders both lists: +// +// p003 (r003) 1 · p005 (unused) 2 · p001 (r001) 3 · p004 (unused) 4 · p002 (r002) 5 +// +// The spec posts the agent's reply itself (the editor stub cannot reach +// umtool), as the clip-editor spec does. Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +export const SUGGEST_PROPOSED_AT = "2026-01-01T00:00:00.000Z"; + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o + */ +export function makeClipsSuggestFixture({ reports, manifest, cachedWindow, cues }) { + const dir = path.join(reports, "clips-suggest-fixture"); + const assist = (p, s, e, cs, ce, score, why) => ({ by: "assistant", proposal: p, score, why, original: { start: s, end: e, cutStart: cs, cutEnd: ce }, edits: [] }); + const clip = (id, s, e, cs, ce, p, score, why, quote) => ({ type: "clip", id, video: "vid1", start: s, end: e, cutStart: cs, cutEnd: ce, quote, assist: assist(p, s, e, cs, ce, score, why) }); + const doc = manifest("clips-suggest-fixture", "The Clips Suggest Fixture", { siteOrigin: "https://archive.example" }, [ + clip("r001", 0.5, 3.5, 1, 3, "p001", 0.8, "host laughs at the line", "This is a complete sentence."), + clip("r002", 4, 6.5, 4, 6, "p002", 0.7, "a comment", "And this one runs on"), + clip("r003", 6.5, 8.5, 6.5, 8.5, "p003", 0.6, "a short comment", "of that it finishes here."), + ]); + doc.render.fetchPad = 0; + write(dir, "video.manifest.json", doc); + + const words = []; + for (const [start, end, text] of cues) { + const ws = text.split(/\s+/).filter(Boolean); + const step = (end - start) / ws.length; + ws.forEach((w, i) => words.push({ w, start: +(start + i * step).toFixed(2), end: +(start + (i + 0.8) * step).toFixed(2) })); + } + write(dir, "words.json", { words }); + const proposals = [ + { id: "p001", start: 1, end: 3, score: 0.8, moments: ["m001"], used: true, clipId: "r001", why: "host laughs at the line" }, + { id: "p002", start: 4, end: 6, score: 0.7, moments: [], used: true, clipId: "r002", why: "a comment" }, + { id: "p003", start: 6.5, end: 8.5, score: 0.6, moments: [], used: true, clipId: "r003", why: "a short comment" }, + { id: "p004", start: 9, end: 12, score: 0.5, moments: [], used: false, clipId: null, why: "a long comment" }, + { id: "p005", start: 13, end: 15, score: 0.3, moments: [], used: false, clipId: null, why: "a chuckle" }, + ]; + write(dir, "reactions.json", { + version: 1, + source: { channel: "testchan", video: "vid1", duration: 21, words: "words.json", diarization: { generatedAt: "2026-01-01T00:00:00.000Z", engine: "sherpa-onnx" } }, + params: { target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75 }, + proposedAt: SUGGEST_PROPOSED_AT, + speakers: [ + { index: 0, role: "host", label: "Host", seconds: 9, turns: 4, how: "auto" }, + { index: 1, role: "subject", label: "Subject", seconds: 12, turns: 3, how: "auto" }, + ], + turns: [ + { start: 0, end: 2.2, speaker: 1 }, + { start: 2.4, end: 3.8, speaker: 0 }, + { start: 4, end: 6.2, speaker: 1 }, + { start: 6.4, end: 9, speaker: 0 }, + { start: 9.2, end: 15, speaker: 1 }, + { start: 15.2, end: 21, speaker: 0 }, + ], + laughs: [{ start: 2.6, end: 3.2, score: 0.71, speaker: 0 }], + moments: [{ id: "m001", t: 2.6, end: 3.2, kind: "laugh", score: 0.71, speaker: 0, text: "" }], + proposals, + }); + const ranks = { p003: 1, p005: 2, p001: 3, p004: 4, p002: 5 }; + const labels = { p001: "the complete sentence", p002: "a run-on line", p003: "how it finishes", p004: "the long comment", p005: "a quiet chuckle" }; + write(dir, "clip-suggestions.json", { + model: "qwen3:8b", + at: "2026-01-01T01:00:00.000Z", + proposedAt: SUGGEST_PROPOSED_AT, + promptVersion: "clips-suggest-1", + items: Object.fromEntries( + proposals + .map((p) => [p.id, { label: labels[p.id], why: `Why ${p.id} lands.`, rank: ranks[p.id], score: 11 - ranks[p.id] * 2, start: p.start, end: p.end }]) + .sort((a, b) => a[1].rank - b[1].rank), + ), + }); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4")); + return { dir }; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -23,6 +23,8 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { fileURLToPath } from "node:url"; import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs"; +import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; const PORT = portFor("EDITOR_STUB_PORT"); const CHANNELS = process.env.CHANNELS_DIR ?? ""; @@ -599,6 +601,49 @@ function cannedRun(job, body) { job.log.push(`${task}: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task, status, summary })}`); } +// A `clips-suggest` report-draft (release 36 lane D): labels for every +// proposal of body.project, written through common's one writer as the real +// task does ("stub label <id>", scored so the LAST proposal ranks first); an +// Ask (body.note) ends with no reply — the stub cannot reach umtool, so a spec +// posts the agent's reply itself. +function startClipsSuggest(body) { + if (typeof body.project !== "string" || !body.project.startsWith("/")) throw new Error('"project" is the reactions project\'s absolute directory'); + const id = `stub-suggest-${nextJob++}`; + const ask = typeof body.note === "string"; + const job = { id, article: null, n: 0, task: "clips-suggest", status: "queued", at: Date.now(), log: [`report-draft clips-suggest ${ask ? `ask ${body.note}` : "labels"} (stub)`], timers: [] }; + draftJobs.set(id, job); + job.timers.push( + setTimeout(() => { + job.status = "running"; + job.progress = { metric: "entries", initial: 0, current: 0, target: 1 }; + job.log.push("asking the stub model"); + }, 300), + ); + job.timers.push( + setTimeout(async () => { + try { + if (ask) { + job.log.push(`replied to ${body.note} (stub: no reply posted)`, `@@report-draft ${JSON.stringify({ article: "", iteration: 0, task: "clips-suggest", kind: "ask", status: "done", summary: `asked about ${body.note} (stub)` })}`); + } else { + const reactions = await readReactions(body.project); + if (!reactions) throw new Error(`${body.project} holds no reactions.json`); + const fresh = reactions.proposals.map((p, i) => ({ id: p.id, label: `stub label ${p.id}`, why: `The stub likes ${p.id}.`, score: Math.min(10, i + 1) })); + const prev = (await readSuggestions(body.project)).doc; + await writeSuggestions(body.project, suggestionsDocOf({ model: generation.models.local, at: new Date().toISOString(), reactions, fresh, prev })); + const summary = `${fresh.length} proposals labelled on ${generation.models.local}`; + job.log.push(summary, `@@report-draft ${JSON.stringify({ article: "", iteration: 0, task: "clips-suggest", kind: "labels", status: "done", summary, suggestions: { labelled: fresh.length, refused: 0, failed: 0 } })}`); + } + job.progress = { metric: "entries", initial: 0, current: 1, target: 1 }; + job.status = "done"; + } catch (err) { + job.log.push(String(err.message)); + job.status = "failed"; + } + }, 1500), + ); + return { jobId: id, iteration: 0 }; +} + function startCannedDraft(body, id) { const { task, article } = body; const n = body.iteration; @@ -808,6 +853,7 @@ function cancelDraft(id) { job.status = "cancelled"; job.log.push("cancelled"); job.child?.kill(); + if (job.task === "clips-suggest") return true; const it = readIt(job.article, job.n); if (job.task === "narrate" || MEDIA_RUN.has(job.task) || MEDIA_TASKS.has(job.task)) { patchIt(job.article, job.n, { steps: it.steps.map((s) => (s.jobId === id ? { ...s, status: "cancelled" } : s)) }); @@ -869,6 +915,14 @@ function generationRoute(req, res, url, auth) { return readBody(req, (body) => { requests.push({ route: "report-draft", ...(body ?? {}), authorization: auth }); record(); + // Release 36 lane D: the clip finder's labels (a project, not an article). + if (body?.task === "clips-suggest") { + try { + return json(res, 202, { ok: true, ...startClipsSuggest(body) }); + } catch (err) { + return json(res, 400, { ok: false, error: String(err.message) }); + } + } if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" }); if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" }); try { diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -36,6 +36,7 @@ import { makeBenchShellFixture } from "./bench-shell-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; +import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1816,6 +1817,8 @@ makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out" makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts). +makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs @@ -117,6 +117,42 @@ export function validateAnchor(raw) { } } +export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"]; + +/** + * An agent reply's proposal (release 36 lane D, "Ask the assistant"): ONE + * edit of one clip the clip editor can perform on the operator's click — + * { kind: "trim", clip, from, to, basis? } the clip's new cut, seconds on the recording + * { kind: "merge", clip, with, basis? } the clip and the next one, joined + * { kind: "cut", clip, basis? } the clip ruled out + * `basis` is the clip's cut when the agent read it ({ cutStart, cutEnd }). + * Never applied by whoever writes it. `{ proposal }` or `{ error }`. + * @param {unknown} raw + */ +export function validateReplyProposal(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "proposal is not an object" }; + const p = /** @type {Record<string, unknown>} */ (raw); + if (!REPLY_PROPOSAL_KINDS.includes(/** @type {string} */ (p.kind))) return { error: `proposal kind must be one of ${REPLY_PROPOSAL_KINDS.join(", ")}` }; + if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" }; + const fin = (v) => typeof v === "number" && Number.isFinite(v); + const out = { kind: p.kind, clip: p.clip }; + if (p.kind === "trim") { + if (!fin(p.from) || !fin(p.to) || p.from < 0 || p.to - p.from < 0.5) return { error: "a trim proposal needs from ≥ 0 and to at least half a second after it" }; + out.from = Math.round(p.from * 100) / 100; + out.to = Math.round(p.to * 100) / 100; + } + if (p.kind === "merge") { + if (!short(p.with, 128) || !ID.test(p.with)) return { error: "a merge proposal needs the next clip's id (with)" }; + out.with = p.with; + } + if (p.basis !== undefined) { + const b = /** @type {Record<string, unknown>} */ (p.basis); + if (!b || typeof b !== "object" || !fin(b.cutStart) || !fin(b.cutEnd)) return { error: "proposal basis is { cutStart, cutEnd }" }; + out.basis = { cutStart: b.cutStart, cutEnd: b.cutEnd }; + } + return { proposal: out }; +} + /** @returns {{ subject: Record<string, string> } | { error: string }} */ export function validateSubject(raw) { if (!raw || typeof raw !== "object") return { error: "subject is not an object" }; @@ -179,7 +215,13 @@ export function parseNotesDoc(raw) { const replies = []; for (const r of n.replies) { if (!r || !NOTE_AUTHORS.includes(r.author) || !isStr(r.text) || !isStr(r.at)) return { error: `${where}.replies` }; - replies.push({ author: r.author, text: r.text, at: r.at }); + const reply = { author: r.author, text: r.text, at: r.at }; + if (r.proposal !== undefined) { + const p = validateReplyProposal(r.proposal); + if ("error" in p) return { error: `${where}.replies: ${p.error}` }; + reply.proposal = p.proposal; + } + replies.push(reply); } const note = { id: n.id, status: n.status, author: n.author, text: n.text, at: n.at, updatedAt: n.updatedAt, anchor: a.anchor, replies }; if (isStr(n.resolvedAt)) note.resolvedAt = n.resolvedAt; @@ -227,7 +269,8 @@ function setStatus(note, status, by, now) { * { op: "add", text, anchor } a new open note * { op: "edit", id, text?, anchor? } rewrite it (its author only) * { op: "status", id, status } open | resolved | wontfix - * { op: "reply", id, text, resolve? } a threaded reply, optionally resolving + * { op: "reply", id, text, resolve?, proposal? } a threaded reply, optionally resolving; + * an AGENT's may carry one proposal (validateReplyProposal) * { op: "delete", id } remove the note * { op: "delete-reply", id, index } remove one reply * { op: "source", source } correct which file to edit @@ -268,7 +311,14 @@ export function applyOp(doc, op, by, now = new Date().toISOString()) { } case "reply": { const note = find(doc, op.id); - note.replies.push({ author: by, text: cleanText(op.text), at: now }); + const reply = { author: by, text: cleanText(op.text), at: now }; + if (op.proposal !== undefined && op.proposal !== null) { + if (by !== "agent") throw new NoteError("only an agent's reply carries a proposal: the operator applies it"); + const p = validateReplyProposal(op.proposal); + if ("error" in p) throw new NoteError(p.error); + reply.proposal = p.proposal; + } + note.replies.push(reply); note.updatedAt = now; if (op.resolve) setStatus(note, "resolved", by, now); return note; diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts @@ -44,7 +44,13 @@ export type Anchor = export type AnchorKind = Anchor["kind"]; -export type NoteReply = { author: NoteAuthor; text: string; at: string }; +/** An agent reply's one proposed edit of a clip (release 36 lane D): applied only by the operator's click. */ +export type ReplyProposal = + | { kind: "trim"; clip: string; from: number; to: number; basis?: { cutStart: number; cutEnd: number } } + | { kind: "merge"; clip: string; with: string; basis?: { cutStart: number; cutEnd: number } } + | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } }; + +export type NoteReply = { author: NoteAuthor; text: string; at: string; proposal?: ReplyProposal }; export type Note = { id: string; @@ -89,7 +95,7 @@ export type NoteOp = | { op: "add"; text: string; anchor: Anchor } | { op: "edit"; id: string; text?: string; anchor?: Anchor } | { op: "status"; id: string; status: NoteStatus } - | { op: "reply"; id: string; text: string; resolve?: boolean } + | { op: "reply"; id: string; text: string; resolve?: boolean; proposal?: ReplyProposal } | { op: "delete"; id: string } | { op: "delete-reply"; id: string; index: number } | { op: "source"; source: NotesSource }; diff --git a/umtool/lib/report/clipSuggest.mjs b/umtool/lib/report/clipSuggest.mjs @@ -0,0 +1,142 @@ +// THE ASSISTANT IN THE CLIP EDITOR, umtool's half (release 36 lane D): the +// labels file read for the page, the request a Suggest or an Ask sends the +// editor, and the editor job the page follows. +// +// clip-suggestions.json written by the EDITOR's `report-draft` task +// `clips-suggest` (its one writer, common's +// lib/clips/suggest.mjs); read here with its stale +// state — shown, marked, never hidden +// .clip-suggest-job.json the editor job the page is following, so a reload +// (or another tab) shows its progress; umtool's own +// file, cleared when the job is seen to end +// +// Everything is optional: with no labels file, no editor, generation routed +// to Claude Code or no model at all, the clip editor works as before. Nothing +// here calls a model, and nothing here writes the manifest or a clip. +import { readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { readSuggestions, suggestionsState } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; + +export const SUGGEST_TASK = "clips-suggest"; +export const SUGGEST_JOB_FILE = ".clip-suggest-job.json"; +const JOB_RE = /^[A-Za-z0-9_-]+$/; +const NOTE_RE = /^n_[a-z0-9]{4,32}$/; +const PROPOSAL_RE = /^[A-Za-z0-9._:-]{1,64}$/; +const RESULT_MARKER = "@@report-draft "; +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export class SuggestRequestError extends Error {} + +/** The labels and their state, for the page: `{ suggestions, error, state }`. */ +export async function suggestionsView(dir) { + const [{ doc, error }, reactions] = await Promise.all([readSuggestions(dir), readReactions(dir)]); + return { suggestions: doc, error, state: suggestionsState(doc, reactions), hasReactions: !!reactions }; +} + +/** + * A POST's body, judged: `{ mode: "labels", proposals? }` (Suggest) or + * `{ mode: "ask", note }` (Ask the assistant on one comment). + * @param {unknown} body + */ +export function parseSuggestRequest(body) { + if (!isObj(body)) throw new SuggestRequestError("a body is { project, mode, … }"); + const mode = body.mode ?? "labels"; + if (mode === "labels") { + if (body.note !== undefined) throw new SuggestRequestError("a note is an Ask's (mode: \"ask\")"); + if (body.proposals === undefined || body.proposals === null) return { mode }; + if (!Array.isArray(body.proposals) || !body.proposals.length || !body.proposals.every((p) => typeof p === "string" && PROPOSAL_RE.test(p))) { + throw new SuggestRequestError("proposals is a list of proposal ids"); + } + return { mode, proposals: [...new Set(body.proposals)] }; + } + if (mode === "ask") { + if (typeof body.note !== "string" || !NOTE_RE.test(body.note)) throw new SuggestRequestError("an Ask names the note it answers (n_…)"); + return { mode, note: body.note }; + } + throw new SuggestRequestError('mode is "labels" or "ask"'); +} + +/** The editor's `report-draft` body for a request on a project directory. */ +export function draftBodyOf(dir, req) { + return { + task: SUGGEST_TASK, + project: dir, + ...(req.mode === "ask" ? { note: req.note } : {}), + ...(req.proposals ? { proposals: req.proposals } : {}), + }; +} + +const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SUGGEST_JOB_FILE); + +/** The job the page follows, or null: `{ jobId, mode, note?, at }`. */ +export async function readSuggestJob(dir) { + try { + const j = JSON.parse(await readFile(jobFileOf(dir), "utf8")); + return isObj(j) && typeof j.jobId === "string" && JOB_RE.test(j.jobId) ? j : null; + } catch { + return null; + } +} + +/** Remember the job a Suggest or an Ask started (tmp + rename). */ +export async function writeSuggestJob(dir, rec) { + const file = jobFileOf(dir); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(rec)}\n`); + await rename(tmp, file); +} + +/** Forget it — only when it is still that job. */ +export async function clearSuggestJob(dir, jobId) { + const cur = await readSuggestJob(dir); + if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true }); +} + +/** The job's `@@report-draft` result in its log tail, or null. */ +export function suggestMarkerOf(tail) { + for (let i = (tail?.length ?? 0) - 1; i >= 0; i--) { + const at = String(tail[i]).indexOf(RESULT_MARKER); + if (at < 0) continue; + try { + return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length)); + } catch { + return null; + } + } + return null; +} + +export const ENDED = Object.freeze(["done", "failed", "cancelled", "interrupted"]); + +/** What the page shows of a job: its state, progress, last line, and its result once it ended. */ +export function suggestJobView(rec, job) { + const marker = suggestMarkerOf(job.tail); + const last = [...(job.tail ?? [])].reverse().find((l) => !String(l).includes(RESULT_MARKER)) ?? null; + return { + id: job.id, + mode: rec?.mode ?? marker?.kind ?? "labels", + ...(rec?.note ? { note: rec.note } : {}), + status: job.status, + ended: ENDED.includes(job.status), + queue: job.queue ?? null, + progress: job.progress ?? null, + last: last === null ? null : String(last).slice(0, 300), + summary: typeof marker?.summary === "string" ? marker.summary : null, + }; +} + +/** + * How the task is routed, for the button: `{ route, model, why }` from the + * policy's generation block, or null without one. `why` is set when the + * button cannot start a job here (routed to Claude Code). + */ +export function suggestRouteOf(generation, dir) { + if (!isObj(generation) || !isObj(generation.routes)) return null; + const route = generation.routes[SUGGEST_TASK] ?? null; + if (route === "code") { + return { route, model: null, why: `routed to Claude Code — in a session: /gen label the clips of ${dir}` }; + } + const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null; + return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no clips-suggest" }; +} diff --git a/umtool/lib/report/clipSuggest.test.mjs b/umtool/lib/report/clipSuggest.test.mjs @@ -0,0 +1,115 @@ +// Release 36 lane D: the assistant in the clip editor, umtool's half — the +// labels read with their stale state, the request a Suggest or an Ask sends, +// the job the page follows — and an agent reply's proposal in notes.json +// (only an agent's, validated, kept on read). +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 { writeReactionProject, labelAnswer, PROJECT_NOTE } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs"; +import { suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; +import { + SuggestRequestError, + clearSuggestJob, + draftBodyOf, + parseSuggestRequest, + readSuggestJob, + suggestJobView, + suggestMarkerOf, + suggestRouteOf, + suggestionsView, + writeSuggestJob, +} from "./clipSuggest.mjs"; +import { applyOp, emptyDoc, NoteError, parseNotesDoc, validateReplyProposal } from "../annotations/shape.mjs"; + +test("the labels for the page: none, fresh, then stale once the proposals are made again", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "umtool-suggest-")); + try { + const { reactions } = writeReactionProject(dir); + let v = await suggestionsView(dir); + assert.deepEqual(v, { suggestions: null, error: null, state: { stale: false, why: null, passNewer: false, staleIds: [], missing: [] }, hasReactions: true }); + await writeSuggestions(dir, suggestionsDocOf({ model: "qwen3:8b", at: "2026-10-19T02:00:00.000Z", reactions, fresh: labelAnswer(["p001", "p003"]).items })); + v = await suggestionsView(dir); + assert.equal(v.suggestions.items.p003.rank, 1); + assert.equal(v.state.stale, false); + assert.deepEqual(v.state.missing, ["p002", "p004", "p005"]); + await writeFile(path.join(dir, "reactions.json"), JSON.stringify({ ...reactions, proposedAt: "2026-10-20T00:00:00.000Z" })); + v = await suggestionsView(dir); + assert.equal(v.state.stale, true); + assert.equal(v.state.passNewer, true); + // A project the clip finder never ran on: no panel. + const empty = await mkdtemp(path.join(os.tmpdir(), "umtool-suggest-none-")); + assert.equal((await suggestionsView(empty)).hasReactions, false); + await rm(empty, { recursive: true, force: true }); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a request: labels (all, or some proposals) or an Ask on one note; the editor's body; the route's button", () => { + assert.deepEqual(parseSuggestRequest({ project: "x" }), { mode: "labels" }); + assert.deepEqual(parseSuggestRequest({ mode: "labels", proposals: ["p001", "p001", "p002"] }), { mode: "labels", proposals: ["p001", "p002"] }); + assert.deepEqual(parseSuggestRequest({ mode: "ask", note: PROJECT_NOTE }), { mode: "ask", note: PROJECT_NOTE }); + assert.throws(() => parseSuggestRequest({ mode: "ask" }), SuggestRequestError); + assert.throws(() => parseSuggestRequest({ mode: "labels", proposals: ["../x"] }), /proposal ids/); + assert.throws(() => parseSuggestRequest({ mode: "apply" }), /"labels" or "ask"/); + assert.deepEqual(draftBodyOf("/r/p", { mode: "ask", note: PROJECT_NOTE }), { task: "clips-suggest", project: "/r/p", note: PROJECT_NOTE }); + assert.deepEqual(draftBodyOf("/r/p", { mode: "labels", proposals: ["p002"] }), { task: "clips-suggest", project: "/r/p", proposals: ["p002"] }); + const generation = { routes: { "clips-suggest": "local" }, models: { api: "claude-sonnet-5-5", local: "qwen3:8b" } }; + assert.deepEqual(suggestRouteOf(generation, "/r/p"), { route: "local", model: "qwen3:8b", why: null }); + assert.deepEqual(suggestRouteOf({ ...generation, routes: { "clips-suggest": "code" } }, "/r/p"), { + route: "code", + model: null, + why: "routed to Claude Code — in a session: /gen label the clips of /r/p", + }); + assert.equal(suggestRouteOf(null, "/r/p"), null); +}); + +test("the followed job: remembered, shown with its progress and result, forgotten only when it is that job", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "umtool-suggest-job-")); + try { + assert.equal(await readSuggestJob(dir), null); + await writeSuggestJob(dir, { jobId: "job-1", mode: "ask", note: PROJECT_NOTE, at: "t" }); + assert.deepEqual(await readSuggestJob(dir), { jobId: "job-1", mode: "ask", note: PROJECT_NOTE, at: "t" }); + await clearSuggestJob(dir, "job-2"); + assert.ok(await readSuggestJob(dir)); + const tail = ["clips-suggest ask …", "replied to n_synth0001, proposing a trim to 94.8–99 s", '@@report-draft {"task":"clips-suggest","kind":"ask","status":"done","summary":"replied to n_synth0001 on r002"}']; + assert.equal(suggestMarkerOf(tail).kind, "ask"); + assert.deepEqual(suggestJobView(await readSuggestJob(dir), { id: "job-1", status: "done", queue: null, progress: null, tail }), { + id: "job-1", + mode: "ask", + note: PROJECT_NOTE, + status: "done", + ended: true, + queue: null, + progress: null, + last: "replied to n_synth0001, proposing a trim to 94.8–99 s", + summary: "replied to n_synth0001 on r002", + }); + await clearSuggestJob(dir, "job-1"); + assert.equal(await readSuggestJob(dir), null); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a reply's proposal: an agent's only, validated, kept when notes.json is read again", () => { + const doc = emptyDoc({ kind: "video-project", project: "p" }); + const note = applyOp(doc, { op: "add", text: "start it on the laugh", anchor: { kind: "entry", entry: "r002" } }, "operator"); + const trim = { kind: "trim", clip: "r002", from: 94.8, to: 99, basis: { cutStart: 88, cutEnd: 99 } }; + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "I did it", proposal: trim }, "operator"), NoteError); + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "x", proposal: { kind: "trim", clip: "r002", from: 99, to: 99.2 } }, "agent"), /half a second/); + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "x", proposal: { kind: "merge", clip: "r002" } }, "agent"), /the next clip's id/); + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "x", proposal: { kind: "delete", clip: "r002" } }, "agent"), /trim, merge, cut/); + applyOp(doc, { op: "reply", id: note.id, text: "Start on the laugh.", proposal: trim }, "agent"); + applyOp(doc, { op: "reply", id: note.id, text: "plain reply" }, "agent"); + const again = parseNotesDoc(JSON.parse(JSON.stringify(doc))); + assert.ok("doc" in again); + assert.deepEqual(again.doc.notes[0].replies.map((r) => r.proposal ?? null), [trim, null]); + // A hand-broken proposal makes the file unreadable rather than being dropped. + const broken = JSON.parse(JSON.stringify(doc)); + broken.notes[0].replies[0].proposal.to = "soon"; + assert.match(parseNotesDoc(broken).error, /replies: a trim proposal needs/); + assert.deepEqual(validateReplyProposal({ kind: "cut", clip: "r003", extra: 1 }), { proposal: { kind: "cut", clip: "r003" } }); +});