Archilyzer · Source

archilyzer

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

commit bc37bc979f0ef52a94a10967925b3e5551631e45
parent a06da009e93a34df2c00429de6b2f0ea83b61650
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 01:46:35 -0500

Merge lane/claim-groups: claim groups in a cut -- manifest `groups` (contiguous clips inside one deck section, validated in structural(), kept by removals and moves), `umtool timeline groups ls|import|set|move|label|promote|remove` and a bulk `timeline order`, import as one undo point, promote to a level-2 marker; group bars on the Cut tab (drag a group, label inline) and lighter group seams on the Play strip; the propose-groups generation task, its output a review surface with Accept/Reject per group

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

Diffstat:
M.claude/commands/gen.md | 7+++++++
MOPERATING.md | 1+
MSETTINGS.md | 4+++-
Acommon/controller/proposeGroups.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/reportDraft.ts | 45++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/generationSettings.test.ts | 15+++++++++++++++
Mcommon/lib/generationSettings.ts | 17++++++++++++-----
Acommon/lib/report/draft/tasks/proposeGroups.test.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/proposeGroups.ts | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/groupProposals.d.mts | 28++++++++++++++++++++++++++++
Acommon/lib/report/groupProposals.mjs | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Aeditor/app/api/ops/_proposeGroups.test.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 17+++++++++++++++++
Mmcp/src/generation.test.ts | 28++++++++++++++++++++++++++++
Mmcp/src/generation.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Msettings.json.example | 3++-
Aumtool/app/api/report/group-proposals/route.ts | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/timeline/route.ts | 40+++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/TimelineEditor.tsx | 174++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/report/CutTab.tsx | 23++++++++++++++++++++---
Aumtool/components/projects/report/GroupProposalsPanel.tsx | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 4+++-
Mumtool/components/projects/review/ReelStrip.tsx | 19+++++++++++++++++--
Mumtool/docs/cli.md | 1+
Mumtool/docs/knobs.md | 27+++++++++++++++++++++++++++
Mumtool/e2e/create.spec.ts | 2+-
Aumtool/e2e/cut-groups.spec.ts | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/cut-editing-fixture.mjs | 32+++++++++++++++++++++++++++++---
Mumtool/e2e/fixtures/editor-stub.mjs | 55++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aumtool/e2e/group-proposals.spec.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/settings.spec.ts | 2+-
Mumtool/lib/create/policy.mjs | 1+
Aumtool/lib/report/claimGroups.mjs | 793+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/claimGroups.test.mjs | 300+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/groupProposals.mjs | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/groupProposals.test.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playCut.mjs | 31+++++++++++++++++++++++++++----
Mumtool/lib/report/playView.mjs | 5+++++
Mumtool/lib/report/sectionEdit.mjs | 2+-
Mumtool/lib/report/timelineCli.mjs | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
42 files changed, 3864 insertions(+), 43 deletions(-)

diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md @@ -55,6 +55,13 @@ each task. Use the archilyzer MCP tools only; run no script for it. (`answers: {"ops": [{"op", "id", "key", "value"}], "reply"}`); the editor checks them as a model's and writes `assist-proposals.json`. They are proposals: the operator applies them in umtool's Ask box. Never edit the manifest or that file yourself. + **And `propose-groups`** (claim groups for a umtool video project's cut — "propose claim groups for <dir>"): + `generate` with task `propose-groups`, `project` and optional `request` (words for the ask). Local in every preset + but `api`; routed to code, its answer is the request — the cut's clips by section — which you answer in this + session and send back with `generate` again (`answers: {"groups": [{"section", "claim", "ids", "why"}]}`: clips + standing together in one section that make one claim); the editor checks them as a model's and writes + `group-proposals.json`. They are proposals: the operator accepts or rejects each on umtool's Cut tab. Never edit + the manifest or that file yourself. 5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks for it. To move the balance itself, `generation_policy` with `preset` (code, balanced, api, local) or with `task` and `route` — only when the operator asks. diff --git a/OPERATING.md b/OPERATING.md @@ -617,6 +617,7 @@ pnpm ops report-draft --json '{"task":"revise-video","article":"example-article" pnpm ops report-draft --json '{"task":"narrate","article":"example-article","iteration":3}' --wait pnpm ops report-draft --json '{"task":"sweep","article":"example-article","copyOf":1,"model":"qwen3:8b"}' pnpm ops report-draft --json '{"task":"video-assist","project":"/abs/project/dir","request":"make the joins 0.15 s with less smear","dryRun":true}' +pnpm ops report-draft --json '{"task":"propose-groups","project":"/abs/project/dir"}' --wait pnpm ops job cancel <jobId> pnpm archilyzer reports iterations example-article umtool chain example-article 3 diff --git a/SETTINGS.md b/SETTINGS.md @@ -1080,6 +1080,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `frames` | `"api"` | A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model. | | `clips-suggest` | `"local"` | The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`). | | `video-assist` | `"local"` | The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words ("make the joins 0.15 s with less smear") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). | +| `propose-groups` | `"local"` | Claim groups proposed for a video project's cut (umtool's Cut tab: Propose groups): runs of clips inside a section that make one claim, each with its claim in words (`group-proposals.json` beside the manifest), each accepted or rejected by the operator — never applied by the proposal. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). | | `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. | #### `generation.models` @@ -1187,7 +1188,8 @@ Default: "verdicts": "local", "frames": "api", "clips-suggest": "local", - "video-assist": "local" + "video-assist": "local", + "propose-groups": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/common/controller/proposeGroups.ts b/common/controller/proposeGroups.ts @@ -0,0 +1,165 @@ +// `report-draft {"task": "propose-groups", "project", "request"?, "model"?, +// "maxUsd"?, "answers"?, "dryRun"?}` — claim groups proposed for a umtool +// video project's cut (lane L4) as an editor job. umtool's Cut tab (Propose +// groups) starts it through `editorCall`; `pnpm ops report-draft` and the +// MCP's `generate` do the same. +// +// project the video project's directory (absolute; it must hold a +// video.manifest.json) +// request optional words for the ask ("group the October clips by day") +// answers the `code` route: a Claude Code session's answer +// (`{groups: [{section, claim, ids, why}]}`), checked exactly as +// a model's — no model is called +// dryRun (the ops route) the plan: the prompt, its estimate; nothing written +// +// Out: `<project>/group-proposals.json` — PROPOSALS ONLY; nothing is applied +// (umtool's Accept writes a group through the manifest's structural writer). +// Routed by settings.generation.routes["propose-groups"] (local by default: +// `draft:local`, every ollama call through the GPU arbiter; ollama unloaded +// when the job ends) or the API (`draft:api`: the narration cap, the daily +// cap, its usage in the ledger as task `propose-groups`). The log ends +// `@@report-draft {article: "", iteration: 0, task: "propose-groups", +// project, status, summary, usd, groups: {at, proposed, refused, file}}`. + +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; +import { getSettings } from "../lib/settings"; +import { capFor } from "../lib/generationSettings"; +import { providerOf, unloadOllama } from "../lib/llm"; +import { usageOf } from "../lib/report/draft/tasks/run"; +import { + GROUPS_CODE_MODEL, + PROPOSE_GROUPS_TASK, + loadGroupsProject, + planProposeGroups, + runProposeGroups, + type ProposeGroupsOutcome, + type ProposeGroupsPlan, +} from "../lib/report/draft/tasks/proposeGroups"; +import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; +import { projectDirOf } from "./clipsSuggest"; +import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; + +export { GROUPS_CODE_MODEL, PROPOSE_GROUPS_TASK }; + +type Refused = { result: StreamActionResult & { ok: false } }; + +/** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */ +export async function planProposeGroupsJob(body: ReportDraftBody, deps: Pick<ReportDraftDeps, "paths" | "settings">): Promise<ProposeGroupsPlan> { + const gen = (deps.settings ?? getSettings)().generation; + const dir = projectDirOf(body.project ?? "", deps.paths); + const route = gen.routes[PROPOSE_GROUPS_TASK]; + const model = body.model ?? (route === "code" ? GROUPS_CODE_MODEL : modelFor(gen, PROPOSE_GROUPS_TASK)); + return planProposeGroups({ project: dir, model, ...(body.request ? { request: body.request } : {}) }, { llm: llmConfigOf(gen, deps.paths) }); +} + +export async function enqueueProposeGroups(body: ReportDraftBody, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | Refused> { + const refuse = (error: string): Refused => ({ result: { ok: false as const, error } }); + const paths = deps.paths; + const gen = (deps.settings ?? getSettings)().generation; + let dir: string; + let model: string; + try { + dir = projectDirOf(body.project ?? "", paths); + model = body.answers !== undefined ? GROUPS_CODE_MODEL : modelFor(gen, PROPOSE_GROUPS_TASK, body.model); + // Refused at the ask, not at the job's turn: no manifest. + await loadGroupsProject(dir); + } catch (e) { + return refuse((e as Error).message); + } + const provider = model === GROUPS_CODE_MODEL ? "code" : providerOf(model); + let maxUsd: number | undefined; + if (provider === "api") { + try { + maxUsd = capFor(gen.caps, "narration", body.maxUsd); + } catch (e) { + return refuse((e as Error).message); + } + const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); + if (refusal) return refuse(refusal); + } + const result = await runManagedFunction({ + kind: REPORT_DRAFT_JOB_KIND, + queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, + paths, + fn: async (onLog, signal, setProgress, ctx) => { + const g = (deps.settings ?? getSettings)().generation; + if (provider === "api") { + const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); + if (late) throw new Error(late); + } + onLog( + `propose-groups in ${dir} on ${model} (` + + (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter: it waits for a transcription" : "a Claude Code session's answer") + + ")", + ); + setProgress?.({ metric: "turns", initial: 0, target: 1, current: 0 }); + let out: ProposeGroupsOutcome | null = null; + try { + out = await runProposeGroups( + { + project: dir, + model, + ...(body.request ? { request: body.request } : {}), + ...(maxUsd !== undefined ? { maxUsd } : {}), + ...(body.answers !== undefined ? { answers: body.answers } : {}), + }, + { + llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined), + log: onLog, + signal, + ...(deps.now ? { now: deps.now } : {}), + }, + ); + } finally { + if (provider === "local") { + await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then( + () => onLog(`unloaded ${model} from ollama`), + (e) => onLog(`ollama unload failed: ${(e as Error).message}`), + ); + } + } + setProgress?.({ metric: "turns", initial: 0, target: 1, current: 1 }); + if (provider === "api") { + const at = deps.now?.() ?? new Date(); + const rows: GenerationUsageRow[] = Object.entries(out.byModel) + .filter(([, t]) => t.calls > 0) + .map(([m, t]) => { + const u = usageOf(t); + return { + at: at.toISOString(), + day: utcDay(at), + jobId: ctx.jobId, + article: "", + iteration: 0, + task: PROPOSE_GROUPS_TASK, + model: m, + inputTokens: u.inputTokens, + outputTokens: u.outputTokens, + cacheReadTokens: u.cacheReadTokens ?? 0, + cacheWriteTokens: u.cacheWriteTokens ?? 0, + usd: Math.round(u.usd * 10_000) / 10_000, + }; + }); + await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); + } + const p = out.proposals; + onLog( + `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ + article: "", + iteration: 0, + task: PROPOSE_GROUPS_TASK, + project: dir, + status: out.status, + summary: out.summary, + usd: out.usd, + groups: { at: p?.at ?? null, proposed: p?.groups.length ?? 0, refused: p?.refused.length ?? 0, file: out.file }, + })}`, + ); + if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); + if (out.status === "failed") throw new Error(out.summary); + }, + }); + if (!result.ok) return { result }; + return { result, iteration: 0 }; +} diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -227,11 +227,13 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod const article = b.article; // A clips-suggest job (release 36 lane D) and a video-assist job (release 38 // lane E) are on a umtool project, not an article. - const onProject = task === "clips-suggest" || task === "video-assist"; + // A propose-groups job (lane L4, ./proposeGroups.ts) is on a video project too. + const groups = task === "propose-groups"; + const onProject = task === "clips-suggest" || task === "video-assist" || groups; const assist = task === "video-assist"; if (onProject) { if (article !== undefined && article !== null && article !== "") { - fail(assist ? 'a video-assist job names its "project" (the video project\'s directory), not an article' : 'a clips-suggest job names its "project" (the reactions project\'s directory), not an article'); + fail(assist || groups ? `a ${task} job names its "project" (the video project's directory), not an article` : 'a clips-suggest job names its "project" (the reactions project\'s directory), not an article'); } } else if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)'); const int = (k: string) => { @@ -375,9 +377,32 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod const clipsGiven = clipsKeys.filter((k) => b[k] !== undefined && b[k] !== null); if (clipsGiven.length && !onProject) fail(`${clipsGiven.map((k) => `"${k}"`).join(", ")} ${clipsGiven.length === 1 ? "is" : "are"} a clips-suggest job's`); // The video assistant's (release 38 lane E). - const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null); + const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null && !(groups && k === "request")); if (assistGiven.length && !assist) fail(`${assistGiven.map((k) => `"${k}"`).join(", ")} ${assistGiven.length === 1 ? "is" : "are"} a video-assist job's`); - if (assist) { + if (groups) { + // Claim groups proposed for a video project's cut (lane L4): the project, + // optional words for the ask, a session's answer on the code route. + const project = b.project; + if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); + out.project = project as string; + if (b.proposals !== undefined && b.proposals !== null) fail('"proposals" is a clips-suggest job\'s'); + if (b.note !== undefined && b.note !== null) fail('a propose-groups job takes no "note": give its words as "request"'); + if (b.request !== undefined && b.request !== null) { + if (typeof b.request !== "string") fail('"request" is words for the ask'); + if (b.request.length > 2000) fail('"request" is at most 2,000 characters'); + const r = b.request.replace(/\s+/g, " ").trim(); + if (r) out.request = r; + } + if (b.answers !== undefined && b.answers !== null) { + if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"groups": [{"section", "claim", "ids", "why"}]}'); + if (JSON.stringify(b.answers).length > 200_000) fail('"answers" is at most 200,000 characters'); + out.answers = b.answers; + } + if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"'); + if (out.dryRun && out.answers !== undefined) fail('"dryRun" plans the ask: no "answers"'); + const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined); + if (extra.length) fail(`a propose-groups job reads its project: it takes no ${extra.join(", ")}`); + } else if (assist) { const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); out.project = project as string; @@ -468,7 +493,7 @@ function kindOf(task: GenerationTask): Iteration["kind"] { } const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" => - isStepTask(task) || task === "clips-suggest" || task === "video-assist" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep"; + isStepTask(task) || task === "clips-suggest" || task === "video-assist" || task === "propose-groups" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep"; export function expandHome(p: string): string { return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; @@ -597,6 +622,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep return refuse((e as Error).message); } } + if (body.task === "propose-groups") { + if (body.dryRun) return refuse('a propose-groups plan is planProposeGroupsJob\'s ("dryRun": true at the ops route)'); + try { + const { enqueueProposeGroups } = await import("./proposeGroups"); + return await enqueueProposeGroups(body, deps); + } catch (e) { + return refuse((e as Error).message); + } + } if (body.task === "video-assist") { if (body.dryRun) return refuse('a video-assist plan is planVideoAssistJob\'s ("dryRun": true at the ops route)'); try { @@ -812,6 +846,7 @@ async function runReportDraft( case "frames": case "clips-suggest": case "video-assist": + case "propose-groups": // A refresh, a triage, verdict proposals, a frame scan, the clip finder's labels and the video assistant are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts, ./videoAssist.ts), never this one. throw new Error(`a ${body.task} runs as its own job`); case "sweep": diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -181,3 +181,18 @@ test("the video assistant (release 38 lane E): local in every preset but api; a // A file that routes nothing: the default (balanced) — local. assert.equal(sanitizeGeneration({}).routes["video-assist"], "local"); }); + +test("claim groups for a cut (lane L4): local in every preset but api; a file from before keeps its preset", () => { + assert.ok((GENERATION_TASKS as readonly string[]).includes("propose-groups")); + assert.deepEqual( + (["code", "balanced", "api", "local"] as const).map((p) => GENERATION_PRESETS[p]["propose-groups"]), + ["local", "local", "api", "local"], + ); + for (const p of ["code", "balanced", "api", "local"] as const) { + const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "propose-groups").map((t) => [t, GENERATION_PRESETS[p][t]])); + const g = sanitizeGeneration({ routes }); + assert.equal(g.preset, p); + assert.equal(g.routes["propose-groups"], GENERATION_PRESETS[p]["propose-groups"]); + } + assert.equal(sanitizeGeneration({}).routes["propose-groups"], "local"); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -34,7 +34,12 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri // (`<project>/assist-proposals.json`) the operator applies. LOCAL in every // preset but `api` (the point is small edits with no Claude at hand); // `code` = a Claude Code session answers the request. -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist"] as const; +// `propose-groups` (lane L4, 2026-11-02): claim groups proposed for a video +// project's cut — runs of clips in a section that make one claim +// (`<project>/group-proposals.json`), each accepted or rejected by the +// operator in umtool's Cut tab. Routed as video-assist: local in every preset +// but `api`; `code` = a Claude Code session answers the request. +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist", "propose-groups"] as const; export type GenerationTask = (typeof GENERATION_TASKS)[number]; // The tasks every settings file since release 27 S6 routes. const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"]; @@ -46,12 +51,12 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number]; const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const; export const GENERATION_PRESETS = { - code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local" }, + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local", "propose-groups": "local" }, // A frame scan is on the API in `balanced`: a vision model is not a given // on the local card, and the cheap model's reads cost cents an hour. - balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local" }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local" }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api", "propose-groups": "api" }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local" }, } as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>; export type GenerationPreset = keyof typeof GENERATION_PRESETS; export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[]; @@ -229,6 +234,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { "The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`).", "video-assist": "The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words (\"make the joins 0.15 s with less smear\") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).", + "propose-groups": + "Claim groups proposed for a video project's cut (umtool's Cut tab: Propose groups): runs of clips inside a section that make one claim, each with its claim in words (`group-proposals.json` beside the manifest), each accepted or rejected by the operator — never applied by the proposal. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).", verdicts: "Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.", }; diff --git a/common/lib/report/draft/tasks/proposeGroups.test.ts b/common/lib/report/draft/tasks/proposeGroups.test.ts @@ -0,0 +1,164 @@ +// Lane L4: the `propose-groups` task on the fake ollama and the fake +// Anthropic — one ask, the answer checked (a kept group and every refusal), +// written as group-proposals.json; the code route's answer read as a +// model's; the manifest byte-identical after every run. +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../../../testing/llm/fakeAnthropic.mjs"; +import { jsonReply, startFakeOllama, PROMPT_CAP_TOKENS, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { checkGroupProposals, cutSections, markGroupProposals, readGroupProposals } from "../../groupProposals.mjs"; +import { GROUPS_CODE_MODEL, ProposeGroupsRefusal, groupsView, planProposeGroups, runProposeGroups } from "./proposeGroups"; +import type { LlmConfig } from "../../../llm"; + +let tmp: string; +let api: FakeAnthropic; +let ol: FakeOllama; +let llm: LlmConfig; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "propose-groups-")); + api = await startFakeAnthropic(); + ol = await startFakeOllama(); + llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }, ollama: { baseUrl: ol.url } }; +}); + +after(async () => { + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const clip = (id: string, i: number, extra: Record<string, unknown> = {}) => ({ type: "clip", id, channel: "c", video: "v1", start: 10 * i, end: 10 * i + 8, quote: `words of ${id}`, ...extra }); +/** §0 c01 c02 | §1 "Two" c03 card c04 | §2 "Three" c05 c06; g1 = c06. */ +function manifestOf() { + return { + slug: "s", + render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "c02", label: "Two" }, { after: "c04", label: "Three" }] } } }, + timeline: [ + clip("c01", 0, { onscreen: { title: "24 Oct 2020" } }), + clip("c02", 1), + clip("c03", 2), + { type: "card", id: "k1", heading: "a card" }, + clip("c04", 3), + clip("c05", 4), + clip("c06", 5), + ], + groups: [{ id: "g1", section: 2, claim: "Taken already", ids: ["c06"] }], + }; +} +async function project(name: string) { + const dir = path.join(tmp, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifestOf(), null, 2) + "\n"); + return dir; +} + +const ANSWER = { + groups: [ + { section: 0, claim: "She opens on the claim", ids: ["c02", "c01"], why: "both say it" }, + { section: 1, claim: "A card between does not break it", ids: ["c03", "c04"], why: "w" }, + { section: 2, claim: "Already grouped", ids: ["c05", "c06"], why: "w" }, + { section: 0, claim: "Not together", ids: ["c01", "c03"], why: "w" }, + { section: 1, claim: "Across a boundary", ids: ["c02", "c03"], why: "w" }, + { section: 2, claim: "x".repeat(161), ids: ["c05"], why: "w" }, + { section: 2, claim: "", ids: ["c05"], why: "w" }, + { section: 2, claim: "Unknown clip", ids: ["zz"], why: "w" }, + { section: 0, claim: "Twice", ids: ["c01"], why: "w" }, + { section: 2, claim: "Lone claim", ids: ["c05"], why: "its own" }, + ], +}; + +test("checkGroupProposals: a kept group and every refusal, in words; the sections read as umtool reads them", () => { + const m = manifestOf(); + const cut = cutSections(m); + assert.deepEqual([...cut.sectionOf.entries()], [["c01", 0], ["c02", 0], ["c03", 1], ["c04", 1], ["c05", 2], ["c06", 2]]); + assert.deepEqual(cut.labels, [null, "Two", "Three"]); + const r = checkGroupProposals(m, ANSWER); + assert.deepEqual(r.groups, [ + { section: 0, claim: "She opens on the claim", ids: ["c01", "c02"], why: "both say it" }, + { section: 1, claim: "A card between does not break it", ids: ["c03", "c04"], why: "w" }, + { section: 2, claim: "Lone claim", ids: ["c05"], why: "its own" }, + ]); + assert.deepEqual(r.refused.map((x) => x.why), [ + "c06 (g1) is in a group already", + "its clips are not together: c02 stands between c01 and c03", + "it spans §0 and §1: a group never crosses a section boundary", + "its claim is 161 characters (at most 160)", + "it has no claim", + "zz is not a clip of the cut", + "c01 is in another proposed group (the proposal \"She opens on the claim\")", + ]); + // Across a boundary, where nothing else refuses it first. + assert.deepEqual(checkGroupProposals(m, { groups: [{ claim: "x", ids: ["c04", "c05"] }] }).refused.map((x) => x.why), ["it spans §1 and §2: a group never crosses a section boundary"]); + // No markers: one section. + assert.equal(checkGroupProposals({ timeline: m.timeline }, { groups: [{ claim: "x", ids: ["c04", "c05"] }] }).groups[0]!.section, 0); +}); + +for (const [route, model] of [ + ["local", "qwen3:8b"], + ["api", "claude-sonnet-5-5"], +] as const) { + test(`on the ${route} model: one ask over the cut's view, the answer checked, group-proposals.json written, the manifest untouched`, async () => { + const dir = await project(route); + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + let prompt = ""; + if (route === "local") { + ol.push((body: { messages: { role: string; content: string }[] }) => { + prompt = body.messages.find((m) => m.role === "user")!.content; + return jsonReply(ANSWER); + }); + } else { + api.push((body: { messages: { content: unknown }[] }) => { + prompt = JSON.stringify(body.messages[0]!.content); + return toolTurn("answer", ANSWER); + }); + } + const out = await runProposeGroups({ project: dir, model, request: "by claim" }, { llm, now: () => new Date("2026-11-02T00:00:00.000Z") }); + assert.equal(out.status, "done"); + assert.match(out.summary, new RegExp(`^3 groups proposed, 7 refused on ${model}`)); + assert.ok(prompt.includes("§1 Two"), prompt.slice(0, 300)); + assert.ok(prompt.includes("c06: (taken: in g1)")); + assert.ok(prompt.includes('c01: [24 Oct 2020] \\"words of c01\\"') || prompt.includes('c01: [24 Oct 2020] "words of c01"')); + const { doc } = await readGroupProposals(dir); + assert.equal(doc!.model, model); + assert.equal(doc!.request, "by claim"); + assert.deepEqual(doc!.groups.map((g) => [g.id, g.status, g.ids.join(" ")]), [["p1", "proposed", "c01 c02"], ["p2", "proposed", "c03 c04"], ["p3", "proposed", "c05"]]); + assert.equal(doc!.refused.length, 7); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before, "nothing applied"); + const marked = markGroupProposals(doc!, { p1: { status: "accepted", group: "g2" }, p9: { status: "rejected" } }, "t"); + assert.deepEqual(marked.groups.map((g) => g.status), ["accepted", "proposed", "proposed"]); + assert.equal(marked.groups[0]!.group, "g2"); + }); +} + +test("the code route: a session's answer is checked as a model's, written as claude-code's; junk refused; no model asked", async () => { + const dir = await project("code"); + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + const asked = api.requests.length + ol.requests.length; + const out = await runProposeGroups({ project: dir, model: GROUPS_CODE_MODEL, answers: { groups: [{ section: 0, claim: "Two clips", ids: ["c01", "c02"], why: "" }] } }, { llm }); + assert.equal(out.status, "done"); + assert.equal(api.requests.length + ol.requests.length, asked); + const { doc } = await readGroupProposals(dir); + assert.equal(doc!.model, "claude-code"); + assert.deepEqual(doc!.groups.map((g) => g.claim), ["Two clips"]); + await assert.rejects(runProposeGroups({ project: dir, model: GROUPS_CODE_MODEL, answers: { nope: 1 } }, { llm }), /the session's answer is refused: the answer has no groups list/); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before); +}); + +test("refusals and the plan: no manifest, an API ask over its cap; the local view fitted to the prompt cap however long the cut", async () => { + await assert.rejects(runProposeGroups({ project: path.join(tmp, "none"), model: "qwen3:8b" }, { llm }), ProposeGroupsRefusal); + const dir = await project("cap"); + await assert.rejects(runProposeGroups({ project: dir, model: "claude-sonnet-5-5", maxUsd: 0.000001 }, { llm }), /is over its cap/); + const m = manifestOf() as { timeline: unknown[] }; + for (let i = 10; i <= 900; i++) m.timeline.push(clip(`r${i}`, i, { quote: "a long quote ".repeat(40) })); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m)); + const plan = await planProposeGroups({ project: dir, model: "qwen3:8b" }, { llm }); + assert.ok(plan.estimate.inputTokens <= PROMPT_CAP_TOKENS, String(plan.estimate.inputTokens)); + assert.equal(plan.estimate.usd, 0); + assert.ok(groupsView(m as Record<string, unknown>, { maxChars: 2000 }).text.length <= 2000); + const apiPlan = await planProposeGroups({ project: dir, model: "claude-sonnet-5-5" }, { llm }); + assert.ok(apiPlan.estimate.usd > 0); +}); diff --git a/common/lib/report/draft/tasks/proposeGroups.ts b/common/lib/report/draft/tasks/proposeGroups.ts @@ -0,0 +1,282 @@ +// THE `propose-groups` TASK (lane L4, 2026-11-02): claim groups proposed for +// a umtool video project's cut, as PROPOSALS the operator accepts or rejects. +// +// in a video project's directory (its video.manifest.json), optional +// words for the ask (`request`: "group the October clips by day"), +// and on the `code` route a Claude Code session's answer (`answers`, +// read exactly as a model's) +// ask ONE schema-bound ask (GROUPS_SCHEMA: `{groups: [{section, claim, +// ids, why}]}`) over the cut's compact view -- per section its +// clips in order with their deck title, date and quote, the clips +// already in a group marked taken -- fitted to the prompt cap on a +// local model; the same ask on the Claude API (one answer is the +// batch) +// check every group against the manifest as it is after the answer +// (groupProposals.mjs checkGroupProposals: clips of the cut, +// together, in one section, in no group yet, a claim of at most 160 +// characters) +// out `<project>/group-proposals.json`: the kept groups, each `proposed`, +// and the refused with their reasons. NOTHING IS APPLIED: umtool's +// Accept writes one group through the manifest's structural writer. +// +// It never writes the manifest or notes.json. An API model is held to +// `maxUsd` (the ask's estimate checked first). + +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; +import { + GROUPS_PROMPT_VERSION, + PROPOSED_CLAIM_MAX, + checkGroupProposals, + cutSections, + groupProposalsDocOf, + writeGroupProposals, + type GroupProposals, +} from "../../groupProposals.mjs"; +import { fitLocalAsk } from "./revise-report"; + +export const PROPOSE_GROUPS_TASK = "propose-groups" as const; +/** The `model` a Claude Code session's answer is written under (the `code` route). */ +export const GROUPS_CODE_MODEL = "claude-code"; +/** The ask's own words, at most. */ +export const GROUPS_REQUEST_MAX = 2000; +const ANSWER_TOKENS = 3000; +/** The view's budget on the API (a local model's is fitted to its cap). */ +const API_VIEW_CHARS = 60_000; + +export class ProposeGroupsRefusal extends Error {} + +export type ProposeGroupsDeps = { + llm: LlmConfig; + // The model, stubbed (tests). + ask?: <T>(system: string, user: string, schema: object, model: string, maxTokens: number) => Promise<T>; + log?: (line: string) => void; + signal?: AbortSignal; + now?: () => Date; +}; + +export type ProposeGroupsInput = { + project: string; + model: string; + request?: string; + maxUsd?: number; + answers?: unknown; +}; + +export const GROUPS_SCHEMA = Object.freeze({ + type: "object", + properties: { + groups: { + type: "array", + items: { + type: "object", + properties: { + section: { type: "integer" }, + claim: { type: "string" }, + ids: { type: "array", items: { type: "string" } }, + why: { type: "string" }, + }, + required: ["section", "claim", "ids", "why"], + }, + }, + }, + required: ["groups"], +}); + +/** A video project: its manifest (refused without one). */ +export async function loadGroupsProject(dir: string): Promise<{ dir: string; manifest: Record<string, unknown> }> { + let raw: string; + try { + raw = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + } catch { + throw new ProposeGroupsRefusal(`${dir} holds no video.manifest.json: claim groups are proposed for a video project's cut`); + } + try { + const manifest = JSON.parse(raw) as Record<string, unknown>; + if (!manifest || typeof manifest !== "object" || !Array.isArray(manifest.timeline)) throw new Error("no timeline"); + return { dir, manifest }; + } catch (e) { + throw new ProposeGroupsRefusal(`${dir}/video.manifest.json is not a cut (${(e as Error).message})`); + } +} + +type Entry = { id?: unknown; type?: unknown; kind?: unknown; title?: unknown; date?: unknown; quote?: unknown; onscreen?: { title?: unknown } }; +const str = (v: unknown) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); + +/** + * The cut as the model reads it, in at most `maxChars`: per section its + * clips in order -- id, deck title, date, the quote cut to `q` characters -- + * and the clips already in a group marked taken. The quotes are cut shorter + * until it fits; past that a section's clips are listed by id alone. + */ +export function groupsView(manifest: Record<string, unknown>, { maxChars = API_VIEW_CHARS }: { maxChars?: number } = {}): { text: string; clips: number } { + const cut = cutSections(manifest); + const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[]; + const byId = new Map<string, Entry>(); + for (const e of tl) if (typeof e?.id === "string" && !byId.has(e.id)) byId.set(e.id, e); + const sections = new Map<number, string[]>(); + for (const id of cut.order) { + const s = cut.sectionOf.get(id) ?? 0; + sections.set(s, [...(sections.get(s) ?? []), id]); + } + const render = (q: number, idsOnly: boolean) => { + const lines: string[] = []; + for (const [s, ids] of [...sections.entries()].sort((a, b) => a[0] - b[0])) { + lines.push(`§${s}${cut.labels[s] ? ` ${cut.labels[s]}` : s === 0 ? " (the opening)" : ""}`); + if (idsOnly) { + lines.push(` ${ids.map((id) => (cut.grouped.has(id) ? `${id}(taken)` : id)).join(" ")}`); + continue; + } + for (const id of ids) { + const e = byId.get(id) ?? {}; + if (cut.grouped.has(id)) { + lines.push(`- ${id}: (taken: in ${cut.grouped.get(id)})`); + continue; + } + const title = str(e.onscreen?.title) || str(e.title); + const quote = str(e.quote); + const head = [title, str(e.date)].filter(Boolean).join(" · "); + lines.push(`- ${id}:${head ? ` [${head}]` : ""}${quote ? ` "${quote.length > q ? `${quote.slice(0, q - 1)}…` : quote}"` : ""}`); + } + } + return lines.join("\n"); + }; + for (const q of [400, 240, 160, 100, 60, 30]) { + const text = render(q, false); + if (text.length <= maxChars) return { text, clips: cut.order.length }; + } + return { text: render(0, true).slice(0, Math.max(0, maxChars)), clips: cut.order.length }; +} + +const SYSTEM = [ + "You organise a video's cut for its editor. The cut is a list of short clips of one person speaking, in sections. You propose CLAIM GROUPS: runs of clips that stand next to each other in a section and together make one claim.", + "Rules: a group's ids are clips that stand together in the order shown (no other clip between them), all in one section; give its `section` number; never use a clip marked taken, and no clip in two groups.", + "Leave a clip that makes no claim with its neighbours out of every group; a group may be one clip when it is a claim of its own.", + `\`claim\` says what the clips claim, in a short line of plain words in the speaker's own register (at most ${PROPOSED_CLAIM_MAX} characters; quote her when a phrase says it best). \`why\` is one short sentence: why these clips are one claim.`, + "Do not reorder anything and do not invent ids.", +].join("\n"); + +const userOf = (request: string, view: string) => + `${request ? `THE EDITOR ASKS:\n${request}\n\n` : ""}THE CUT NOW:\n${view}\n\nAnswer with the claim groups.`; + +/** The prompt one ask sends: on a local model the view is fitted to its prompt cap. */ +export function groupsPrompt(o: { manifest: Record<string, unknown>; request: string; model: string; llm: LlmConfig }): { system: string; user: string; tokens: number } { + const build = (maxChars: number) => userOf(o.request, groupsView(o.manifest, { maxChars: maxChars - o.request.length - 120 }).text); + if (providerOf(o.model) === "local") { + const fitted = fitLocalAsk({ llm: o.llm, model: o.model, system: SYSTEM, schema: GROUPS_SCHEMA, build }); + return { system: SYSTEM, user: fitted.user, tokens: fitted.tokens }; + } + const user = build(API_VIEW_CHARS); + return { system: SYSTEM, user, tokens: structuredPromptEstimate({ system: SYSTEM, user, schema: GROUPS_SCHEMA }) }; +} + +export type ProposeGroupsPlan = { + project: string; + model: string; + provider: "api" | "local" | "code"; + promptVersion: string; + estimate: { inputTokens: number; outputTokens: number; usd: number }; + // The request a Claude Code session answers (the `code` route). + request: { system: string; user: string; schema: object }; +}; + +const CODE_PRICED = "claude-sonnet-5-5"; + +/** What one ask would send, and roughly what it costs — nothing called, nothing written. */ +export async function planProposeGroups(input: Omit<ProposeGroupsInput, "answers" | "maxUsd">, deps: Pick<ProposeGroupsDeps, "llm">): Promise<ProposeGroupsPlan> { + const { manifest } = await loadGroupsProject(input.project); + const code = input.model === GROUPS_CODE_MODEL; + const pr = groupsPrompt({ manifest, request: requestOf(input.request), model: code ? CODE_PRICED : input.model, llm: deps.llm }); + const p = priceOf(code ? CODE_PRICED : input.model); + const usd = code || providerOf(input.model) === "local" ? 0 : (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6; + return { + project: input.project, + model: input.model, + provider: code ? "code" : providerOf(input.model), + promptVersion: GROUPS_PROMPT_VERSION, + estimate: { inputTokens: pr.tokens, outputTokens: ANSWER_TOKENS, usd: Math.round(usd * 10_000) / 10_000 }, + request: { system: pr.system, user: pr.user, schema: GROUPS_SCHEMA }, + }; +} + +export type ProposeGroupsOutcome = { + status: "done" | "cancelled" | "failed"; + project: string; + model: string; + proposals: GroupProposals | null; + file: string | null; + usd: number; + byModel: ReturnType<Meter["summary"]>["byModel"]; + summary: string; +}; + +const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; + +function requestOf(r: string | undefined): string { + const t = (r ?? "").replace(/\s+/g, " ").trim(); + if (t.length > GROUPS_REQUEST_MAX) throw new ProposeGroupsRefusal(`a request is at most ${GROUPS_REQUEST_MAX} characters`); + return t; +} + +/** The answer's groups, or why it is not one. */ +export function parseGroupsAnswer(raw: unknown): { ok: true; groups: unknown[] } | { ok: false; error: string } { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "the answer is not { groups: [...] }" }; + const a = raw as { groups?: unknown }; + if (!Array.isArray(a.groups)) return { ok: false, error: "the answer has no groups list" }; + return { ok: true, groups: a.groups }; +} + +/** One ask (or a session's answer), checked, written as proposals. */ +export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeGroupsDeps): Promise<ProposeGroupsOutcome> { + const log = deps.log ?? (() => {}); + const now = () => deps.now?.() ?? new Date(); + const request = requestOf(input.request); + const { manifest } = await loadGroupsProject(input.project); + const meter = new Meter(); + const base = { project: input.project, model: input.model }; + const cancelled = (): ProposeGroupsOutcome => ({ ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }); + let raw: unknown; + if (input.answers !== undefined) { + log(`propose-groups ${input.project}: a Claude Code session's answer (prompt ${GROUPS_PROMPT_VERSION})`); + raw = input.answers; + } else { + const pr = groupsPrompt({ manifest, request, model: input.model, llm: deps.llm }); + log(`propose-groups ${input.project} on ${input.model}: one ask, ~${pr.tokens} prompt tokens (prompt ${GROUPS_PROMPT_VERSION})`); + if (providerOf(input.model) === "api" && input.maxUsd !== undefined) { + const p = priceOf(input.model); + const est = (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6; + if (est > input.maxUsd) throw new ProposeGroupsRefusal(`the ask (~$${est.toFixed(4)}) is over its cap of $${input.maxUsd}`); + } + const ask = + deps.ask ?? + (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) => + structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); + try { + raw = await ask<unknown>(pr.system, pr.user, GROUPS_SCHEMA, input.model, 4096); + } catch (e) { + if (deps.signal?.aborted) return cancelled(); + throw e; + } + } + const parsed = parseGroupsAnswer(raw); + if (!parsed.ok) { + if (input.answers !== undefined) throw new ProposeGroupsRefusal(`the session's answer is refused: ${parsed.error}`); + throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); + } + if (deps.signal?.aborted) return cancelled(); + // Checked against the manifest as it is NOW: a cut edited while the model thought is what the groups meet. + const fresh = (await loadGroupsProject(input.project)).manifest; + const checked = checkGroupProposals(fresh, { groups: parsed.groups }); + for (const g of checked.groups) log(` proposed: §${g.section} ${g.ids.join(" ")} — ${g.claim}`); + for (const r of checked.refused) log(` refused: ${JSON.stringify(r.group).slice(0, 120)} — ${r.why}`); + const proposals = groupProposalsDocOf({ at: now().toISOString(), model: input.model, request: request || null, checked }); + const file = await writeGroupProposals(input.project, proposals); + const usd = Math.round(meter.usd * 1e6) / 1e6; + const summary = + (checked.groups.length ? `${plural(checked.groups.length, "group")} proposed` : "no group proposed") + + (checked.refused.length ? `, ${checked.refused.length} refused` : "") + + ` on ${input.model}` + + (usd ? ` · $${usd.toFixed(4)}` : ""); + return { ...base, status: "done", proposals, file, usd, byModel: meter.summary().byModel, summary }; +} diff --git a/common/lib/report/groupProposals.d.mts b/common/lib/report/groupProposals.d.mts @@ -0,0 +1,28 @@ +// Types for ./groupProposals.mjs (lane L4): `<project>/group-proposals.json`. +export type GroupProposalStatus = "proposed" | "accepted" | "rejected" | "failed"; +export type CheckedGroup = { section: number; claim: string; ids: string[]; why?: string }; +export type RefusedGroup = { group: unknown; why: string }; +/** `group`: the claim group an accept made (its id in the manifest). */ +export type ProposedGroup = CheckedGroup & { id: string; status: GroupProposalStatus; at?: string; error?: string; group?: string }; +export type GroupProposals = { + version: 1; + promptVersion: string; + at: string; + model: string; + request?: string; + groups: ProposedGroup[]; + refused: RefusedGroup[]; +}; + +export const GROUP_PROPOSALS_NAME: string; +export const GROUPS_PROMPT_VERSION: string; +export const GROUP_PROPOSAL_STATUSES: readonly GroupProposalStatus[]; +export const PROPOSED_CLAIM_MAX: number; +export const PROPOSED_GROUPS_MAX: number; +export function cutSections(manifest: unknown): { order: string[]; sectionOf: Map<string, number>; labels: (string | null)[]; grouped: Map<string, string> }; +export function checkGroupProposals(manifest: unknown, answer: unknown): { groups: CheckedGroup[]; refused: RefusedGroup[] }; +export function groupProposalsDocOf(o: { at: string; model: string; request?: string | null; checked: { groups: CheckedGroup[]; refused: RefusedGroup[] } }): GroupProposals; +export function groupProposalsErrors(doc: unknown): string[]; +export function readGroupProposals(dir: string): Promise<{ doc: GroupProposals | null; error: string | null }>; +export function writeGroupProposals(dir: string, doc: GroupProposals): Promise<string>; +export function markGroupProposals(doc: GroupProposals, marks: Record<string, { status: GroupProposalStatus; error?: string; group?: string }>, at: string): GroupProposals; diff --git a/common/lib/report/groupProposals.mjs b/common/lib/report/groupProposals.mjs @@ -0,0 +1,229 @@ +// CLAIM-GROUP PROPOSALS (lane L4, 2026-11-02): `<project>/group-proposals.json`, +// beside a umtool video project's video.manifest.json. +// +// { "version": 1, "promptVersion": "propose-groups-1", "at": ISO, "model": "qwen3:8b", +// "request"?: "…", the operator's words for the ask, when given +// "groups": [ { "id": "p1", "section": 1, "claim": "…", "ids": ["ow1", "a01"], "why"?: "…", +// "status": "proposed" | "accepted" | "rejected" | "failed", "at"?: ISO, "error"?: "…" } ], +// "refused": [ { "group": {…}, "why": "…" } ] } +// +// Written whole by the editor's `propose-groups` task (a new ask replaces the +// file); each group's `status` marked by umtool's Accept and Reject. PROPOSALS +// ONLY: nothing here is applied by being here. Accept writes the group through +// umtool's structural writer (lib/report/manifest.mjs setGroup), which checks +// it again against the manifest as it is then (claimGroups.mjs validateGroups). +// +// checkGroupProposals is the task's check of a model's answer, PURE and +// self-contained (common never imports umtool): the cut's sections are read +// from `render.chrome.deck.markers` by umtool's own rule (sectionEdit.mjs +// sectionModel) -- a marker `{after}` opens the next section right after that +// clip, markers placed by where their clip stands; none, one section 0. +// +// Tmp + rename, so a reader never sees half a file. Plain ESM with a .d.mts. + +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const GROUP_PROPOSALS_NAME = "group-proposals.json"; +export const GROUPS_PROMPT_VERSION = "propose-groups-1"; +export const GROUP_PROPOSAL_STATUSES = Object.freeze(["proposed", "accepted", "rejected", "failed"]); +/** A claim's characters, at most (umtool claimGroups.mjs GROUP_CLAIM_MAX). */ +export const PROPOSED_CLAIM_MAX = 160; +/** Groups one answer may propose, at most. */ +export const PROPOSED_GROUPS_MAX = 200; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const isClip = (e) => !!e && (e.kind ?? e.type) === "clip"; +const fileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, GROUP_PROPOSALS_NAME); + +/** + * The cut as a proposal is checked against: its clips in order (each id + * once), each clip's section, the sections' labels, and the clips already in + * a group. + * + * @param {unknown} manifest + */ +export function cutSections(manifest) { + const m = isObj(manifest) ? manifest : {}; + const tl = Array.isArray(m.timeline) ? m.timeline : []; + const order = []; + const pos = new Map(); + tl.forEach((e, i) => { + if (isClip(e) && typeof e.id === "string" && !pos.has(e.id)) { + pos.set(e.id, i); + order.push(e.id); + } + }); + const chrome = isObj(m.render) && isObj(m.render.chrome) ? m.render.chrome : null; + const markers = chrome && isObj(chrome.deck) && Array.isArray(chrome.deck.markers) ? chrome.deck.markers : []; + const placed = []; + markers.forEach((mk, k) => { + const p = isObj(mk) ? pos.get(String(mk.after ?? "").trim()) : undefined; + if (p !== undefined) placed.push({ k, mk, pos: p }); + }); + placed.sort((a, b) => a.pos - b.pos || a.k - b.k); + const labels = [null, ...placed.map((p) => (typeof p.mk.label === "string" && p.mk.label.trim() ? p.mk.label.trim() : null))]; + const sectionOf = new Map(); + let s = 0; + let next = 0; + tl.forEach((e, i) => { + if (isClip(e) && !sectionOf.has(e.id)) sectionOf.set(e.id, s); + while (next < placed.length && placed[next].pos === i) { + next += 1; + s = next; + } + }); + const grouped = new Map(); + for (const g of Array.isArray(m.groups) ? m.groups : []) { + if (!isObj(g) || !Array.isArray(g.ids)) continue; + for (const id of g.ids) if (typeof id === "string") grouped.set(id, String(g.id ?? "a group")); + } + return { order, sectionOf, labels, grouped }; +} + +/** + * A model's (or a session's) answer, checked against the cut as it is now: + * a proposed group is kept only when its ids are clips of the cut, together + * (no other clip between them; a card does not count), in one section, in no + * group already and in no other kept proposal, and its claim is a sentence of + * at most 160 characters. Each other one is refused, in words. + * + * @param {unknown} manifest + * @param {unknown} answer `{ groups: [{ section?, claim, ids, why? }] }` + * @returns {{ groups: Array<{ section: number, claim: string, ids: string[], why?: string }>, refused: Array<{ group: unknown, why: string }> }} + */ +export function checkGroupProposals(manifest, answer) { + const cut = cutSections(manifest); + const at = new Map(cut.order.map((id, k) => [id, k])); + const list = isObj(answer) && Array.isArray(answer.groups) ? answer.groups : []; + const groups = []; + const refused = []; + const taken = new Map(); + const refuse = (group, why) => refused.push({ group, why }); + for (const g of list.slice(0, PROPOSED_GROUPS_MAX)) { + if (!isObj(g)) { + refuse(g, "a group is {section, claim, ids, why}"); + continue; + } + const claim = typeof g.claim === "string" ? g.claim.replace(/\s+/g, " ").trim() : ""; + if (!claim) { + refuse(g, "it has no claim"); + continue; + } + if ([...claim].length > PROPOSED_CLAIM_MAX) { + refuse(g, `its claim is ${[...claim].length} characters (at most ${PROPOSED_CLAIM_MAX})`); + continue; + } + const ids = Array.isArray(g.ids) ? [...new Set(g.ids.map((x) => String(x ?? "").trim()).filter(Boolean))] : []; + if (!ids.length) { + refuse(g, "it names no clip"); + continue; + } + const unknown = ids.filter((id) => !at.has(id)); + if (unknown.length) { + refuse(g, `${unknown.join(", ")} ${unknown.length === 1 ? "is not a clip" : "are not clips"} of the cut`); + continue; + } + const inGroup = ids.filter((id) => cut.grouped.has(id)); + if (inGroup.length) { + refuse(g, `${inGroup.map((id) => `${id} (${cut.grouped.get(id)})`).join(", ")} ${inGroup.length === 1 ? "is" : "are"} in a group already`); + continue; + } + const sorted = ids.slice().sort((a, b) => at.get(a) - at.get(b)); + const lo = at.get(sorted[0]); + const hi = at.get(sorted[sorted.length - 1]); + if (hi - lo + 1 !== sorted.length) { + const between = cut.order.slice(lo, hi + 1).filter((id) => !ids.includes(id)); + refuse(g, `its clips are not together: ${between.join(", ")} ${between.length === 1 ? "stands" : "stand"} between ${sorted[0]} and ${sorted[sorted.length - 1]}`); + continue; + } + const secs = [...new Set(sorted.map((id) => cut.sectionOf.get(id)))].sort((a, b) => a - b); + if (secs.length > 1) { + refuse(g, `it spans §${secs.join(" and §")}: a group never crosses a section boundary`); + continue; + } + const twice = ids.filter((id) => taken.has(id)); + if (twice.length) { + refuse(g, `${twice.join(", ")} ${twice.length === 1 ? "is" : "are"} in another proposed group (${[...new Set(twice.map((id) => taken.get(id)))].join(", ")})`); + continue; + } + const why = typeof g.why === "string" ? g.why.replace(/\s+/g, " ").trim().slice(0, 300) : ""; + const kept = { section: secs[0], claim, ids: sorted, ...(why ? { why } : {}) }; + const label = `the proposal "${claim.slice(0, 40)}"`; + for (const id of sorted) taken.set(id, label); + groups.push(kept); + } + if (list.length > PROPOSED_GROUPS_MAX) refuse({ more: list.length - PROPOSED_GROUPS_MAX }, `only the first ${PROPOSED_GROUPS_MAX} groups are read`); + return { groups, refused }; +} + +/** The file's document from one ask: the kept groups, each given an id and the status "proposed". */ +export function groupProposalsDocOf({ at, model, request = null, checked }) { + return { + version: 1, + promptVersion: GROUPS_PROMPT_VERSION, + at, + model, + ...(request ? { request: String(request).replace(/\s+/g, " ").trim().slice(0, 2000) } : {}), + groups: (checked?.groups ?? []).map((g, i) => ({ id: `p${i + 1}`, ...g, status: "proposed" })), + refused: (checked?.refused ?? []).map((r) => ({ group: r.group, why: r.why })), + }; +} + +/** The file's problems (empty: it can be read as proposals). */ +export function groupProposalsErrors(doc) { + if (!isObj(doc)) return ["not an object"]; + const errors = []; + if (doc.version !== 1) errors.push("version is not 1"); + if (typeof doc.model !== "string") errors.push("no model"); + if (!Array.isArray(doc.groups)) errors.push("no groups list"); + else + doc.groups.forEach((g, i) => { + if (!isObj(g) || typeof g.id !== "string" || typeof g.claim !== "string" || !Array.isArray(g.ids) || !Number.isInteger(g.section) || !GROUP_PROPOSAL_STATUSES.includes(g.status)) { + errors.push(`groups[${i}] is not { id, section, claim, ids, status }`); + } + }); + if (!Array.isArray(doc.refused)) errors.push("no refused list"); + return errors; +} + +/** `{ doc, error }`: the proposals, or null (no file, or one that is not proposals: `error` says why). */ +export async function readGroupProposals(dir) { + let raw; + try { + raw = await readFile(fileOf(dir), "utf8"); + } catch { + return { doc: null, error: null }; + } + try { + const doc = JSON.parse(raw); + const errors = groupProposalsErrors(doc); + return errors.length ? { doc: null, error: `${GROUP_PROPOSALS_NAME}: ${errors.join("; ")}` } : { doc, error: null }; + } catch (e) { + return { doc: null, error: `${GROUP_PROPOSALS_NAME}: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +/** Write the whole file (tmp + rename). Returns its path. */ +export async function writeGroupProposals(dir, doc) { + const errors = groupProposalsErrors(doc); + if (errors.length) throw new Error(`not group proposals: ${errors.join("; ")}`); + const file = fileOf(dir); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); + await rename(tmp, file); + return file; +} + +/** The doc with each group of `marks` (`{ [id]: { status, error?, group? } }`) marked at `at`; ids not there are ignored. */ +export function markGroupProposals(doc, marks, at) { + return { + ...doc, + groups: doc.groups.map((g) => { + const m = marks[g.id]; + if (!m) return g; + const { error: _e, ...rest } = g; + return { ...rest, status: m.status, at, ...(m.error ? { error: String(m.error).slice(0, 400) } : {}), ...(m.group ? { group: String(m.group) } : {}) }; + }), + }; +} diff --git a/common/package.json b/common/package.json @@ -55,6 +55,7 @@ "./lib/report/fxParams.mjs": "./lib/report/fxParams.mjs", "./lib/report/videoAssistOps.mjs": "./lib/report/videoAssistOps.mjs", "./lib/report/videoAssistProposals.mjs": "./lib/report/videoAssistProposals.mjs", + "./lib/report/groupProposals.mjs": "./lib/report/groupProposals.mjs", "./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs", "./lib/report/panels.mjs": "./lib/report/panels.mjs", "./lib/report/social.mjs": "./lib/report/social.mjs", diff --git a/editor/app/api/ops/_proposeGroups.test.ts b/editor/app/api/ops/_proposeGroups.test.ts @@ -0,0 +1,118 @@ +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; +import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs"; +import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; +import { planProposeGroupsJob } from "yt-dlp-transcript-common/controller/proposeGroups"; +import { readGroupProposals } from "yt-dlp-transcript-common/lib/report/groupProposals.mjs"; +import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import type { Paths } from "yt-dlp-transcript-common/lib/paths"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_proposeGroups.test.ts" +// +// The `report-draft` task `propose-groups` (lane L4) end to end in this +// process: the controller the ops route adapts, a synthetic deck cut in a temp +// dir, the fake Anthropic and ollama servers, a temp jobs dir and usage ledger. + +let tmp: string; +let api: FakeAnthropic; +let ol: FakeOllama; +let paths: Paths; +let gen: GenerationSettings; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "propose-groups-")); + api = await startFakeAnthropic(); + ol = await startFakeOllama(); + const keyFile = path.join(tmp, "anthropic.env"); + await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); + await chmod(keyFile, 0o600); + paths = { + jobsDir: path.join(tmp, ".jobs"), + transcriptsDir: path.join(tmp, "transcripts"), + channelsDir: path.join(tmp, "transcripts", "channels"), + generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), + ollamaUrl: ol.url, + } as Paths; + gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 }, routes: { ...GENERATION_PRESETS.balanced } }); +}); + +after(async () => { + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const deps = (g: Partial<GenerationSettings> = {}) => + ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }) }) as ReportDraftDeps; + +async function project(name: string) { + const dir = path.join(tmp, name); + await mkdir(dir, { recursive: true }); + const clip = (id: string, i: number) => ({ type: "clip", id, video: "v1", start: 10 * i, end: 10 * i + 8, quote: `words of ${id}` }); + const m = { slug: "s", render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "c02", label: "Two" }] } } }, timeline: ["c01", "c02", "c03", "c04"].map(clip) }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return dir; +} + +async function finished(o: Awaited<ReturnType<typeof enqueueReportDraft>>) { + assert.ok(o.result.ok, (o.result as { error?: string }).error); + const job = getRegistry().get(o.result.jobId)!; + void o.result.stream.cancel(); + const done = await o.result.done; + return { job, done, log: await readFile(job.logPath, "utf8") }; +} + +const ANSWER = { groups: [{ section: 0, claim: "The opening claim", ids: ["c01", "c02"], why: "w" }, { section: 1, claim: "Across", ids: ["c02", "c03"], why: "w" }] }; + +test("the body: a project, words optional, no note or scope", () => { + assert.throws(() => parseReportDraftBody({ task: "propose-groups" }), /"project" is the video project's absolute directory/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", article: "a", project: "/p" }), /a propose-groups job names its "project"/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", note: "n_abcd1234" }), /takes no "note"/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", scope: "all" }), /a video-assist job's/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", iteration: 2 }), /takes no iteration/); + assert.deepEqual(parseReportDraftBody({ task: "propose-groups", project: "/p", request: " by day ", dryRun: true }), { task: "propose-groups", article: "", project: "/p", request: "by day", dryRun: true }); +}); + +test("on the local model (the default route): draft:local, one ask, proposals written, ollama unloaded, the manifest untouched", async () => { + const dir = await project("local"); + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + assert.equal(gen.routes["propose-groups"], "local"); + ol.push(jsonReply(ANSWER)); + const { job, done, log } = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir }, deps())); + assert.equal(done.status, "done", log); + assert.equal(job.queueKey, "draft:local"); + assert.match(log, /proposed: §0 c01 c02 — The opening claim/); + assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"propose-groups","project":"[^"]+local","status":"done","summary":"1 group proposed, 1 refused on qwen3:8b"/); + assert.match(log, /unloaded qwen3:8b from ollama/); + const { doc } = await readGroupProposals(dir); + assert.deepEqual(doc!.groups.map((g) => [g.id, g.status, g.claim]), [["p1", "proposed", "The opening claim"]]); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before); +}); + +test("on the API: draft:api, a ledger row as task propose-groups; the code route: refused unanswered, planned, a session's answer on no model", async () => { + const dir = await project("api"); + api.push(toolTurn("answer", ANSWER)); + const { job, done, log } = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir }, deps({ routes: { ...gen.routes, "propose-groups": "api" } }))); + assert.equal(done.status, "done", log); + assert.equal(job.queueKey, "draft:api"); + const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.deepEqual(rows.map((r) => [r.task, r.model]), [["propose-groups", "claude-sonnet-5-5"]]); + const code = { routes: { ...gen.routes, "propose-groups": "code" as const } }; + const refused = await enqueueReportDraft({ task: "propose-groups", project: dir }, deps(code)); + assert.ok(!refused.result.ok && /routed to Claude Code/.test((refused.result as { error: string }).error)); + const plan = await planProposeGroupsJob(parseReportDraftBody({ task: "propose-groups", project: dir, dryRun: true }), deps(code)); + assert.equal(plan.provider, "code"); + assert.match(plan.request.user, /§1 Two/); + const asked = api.requests.length + ol.requests.length; + const r = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir, answers: { groups: [{ section: 1, claim: "Late", ids: ["c03", "c04"], why: "" }] } }, deps(code))); + assert.equal(r.done.status, "done", r.log); + assert.equal(api.requests.length + ol.requests.length, asked); + assert.equal((await readGroupProposals(dir)).doc!.model, "claude-code"); +}); diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -4,6 +4,7 @@ import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft, parseReportDraftBody } from import { planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh"; import { planClipsSuggestJob } from "yt-dlp-transcript-common/controller/clipsSuggest"; import { planVideoAssistJob } from "yt-dlp-transcript-common/controller/videoAssist"; +import { planProposeGroupsJob } from "yt-dlp-transcript-common/controller/proposeGroups"; import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; import { jobResponse, ops, opsFail } from "../_lib"; import { refreshEditor, researchEditor } from "../_researchEditor"; @@ -72,6 +73,14 @@ export const dynamic = "force-dynamic"; // umtool's Apply does that); `answers`: a Claude Code session's // `{ops, reply}` (the `code` route); `dryRun: true` answers `{ ok, plan }` // (the prompt, the estimate) and writes nothing. Answers +// `{ ok, jobId, iteration: 0 }`; +// - "propose-groups" (lane L4, controller/proposeGroups.ts): on a umtool +// video project, `project` (its absolute directory) and optional +// `request` (words for the ask) — ONE ask whose checked claim groups land +// in `<project>/group-proposals.json` as proposals (nothing applied; +// umtool's Accept does that, one group at a time); `answers`: a Claude +// Code session's `{groups: [{section, claim, ids, why}]}` (the `code` +// route); `dryRun: true` answers `{ ok, plan }`. Answers // `{ ok, jobId, iteration: 0 }`. // `model` defaults to settings.generation's route for the task (a task routed // to `code` needs one named). `extractorModel` is an API sweep's extractor @@ -109,6 +118,14 @@ export async function POST(request: Request) { return opsFail((e as Error).message); } } + if (body.task === "propose-groups" && body.dryRun === true) { + try { + const plan = await planProposeGroupsJob(parseReportDraftBody(body), deps); + return NextResponse.json({ ok: true, plan }); + } catch (e) { + return opsFail((e as Error).message); + } + } if (body.task === "video-assist" && body.dryRun === true) { try { const plan = await planVideoAssistJob(parseReportDraftBody(body), deps); diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -152,6 +152,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async "clips-suggest": "api", // The video assistant (release 38 lane E): api only in the api preset. "video-assist": "api", + // Claim groups for a cut (lane L4): api only in the api preset. + "propose-groups": "api", }, }, }, @@ -543,3 +545,29 @@ test("generate video-assist: a project and a request (or a note); routed to code assert.match(b.text, /Nothing in the cut changed/); assert.equal(done.sentOf("/api/ops/iterations").length, 0); }); + +test("generate propose-groups: a project (words optional); routed to code, the plan is this session's request; the answer goes back to the editor", async () => { + assert.ok(GENERATE_TASKS.includes("propose-groups")); + assert.match(String((validateGenerateArgs({ task: "propose-groups", article: "a" }) as { error: string }).error), /names its project/); + assert.match(String((validateGenerateArgs({ task: "propose-groups", project: "/r/p", scope: "all" }) as { error: string }).error), /scope is not a propose-groups job's/); + assert.match(String((validateGenerateArgs({ task: "propose-groups", project: "/r/p", answers: [] }) as { error: string }).error), /answers is \{"groups"/); + const plan = { estimate: { inputTokens: 900 }, request: { system: "You organise a video's cut…", user: "THE CUT NOW:\n§0 (the opening)\n- c01: \"words\"" } }; + const code = editor({ policy: { routes: { ...POLICY.routes, "propose-groups": "code" } }, plan }); + const a = await generateTool({ task: "propose-groups", project: "/r/p" }, code.deps as never); + assert.equal(a.isError, undefined, a.text); + assert.match(a.text, /^generate propose-groups: routed to Claude Code \(preset balanced\) — propose the claim groups for this cut in this session\./); + assert.match(a.text, /call generate with task "propose-groups", project "\/r\/p", answers: \{"groups": \[\.\.\.\]\}/); + assert.match(a.text, /- c01: "words"/); + assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "propose-groups", project: "/r/p", dryRun: true }]); + + const answers = { groups: [{ section: 0, claim: "One claim", ids: ["c01"], why: "" }] }; + const done = editor({ + markerJson: { article: "", iteration: 0, task: "propose-groups", project: "/r/p", status: "done", summary: "1 group proposed on claude-code", usd: 0, groups: { proposed: 1, refused: 0, file: "/r/p/group-proposals.json" } }, + }); + const b = await generateTool({ task: "propose-groups", project: "/r/p", answers, wait: true }, done.deps as never); + assert.equal(b.isError, false, b.text); + assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "propose-groups", project: "/r/p", answers }]); + assert.match(b.text, /^generate propose-groups: job job-1 ended \*\*done\*\* — 1 group proposed on claude-code/); + assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused/); + assert.match(b.text, /Nothing in the cut changed/); +}); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -238,6 +238,7 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; if (!GENERATE_TASKS.includes(task)) return bad(`task is one of ${GENERATE_TASKS.join(", ")}`); if (task === CLIPS_SUGGEST) return validateClipsSuggestArgs(args, waitSeconds); if (task === VIDEO_ASSIST) return validateVideoAssistArgs(args, waitSeconds); + if (task === PROPOSE_GROUPS) return validateProposeGroupsArgs(args, waitSeconds); if (args.project !== undefined || args.answers !== undefined || args.proposals !== undefined) return bad("project, proposals and answers are a clips-suggest job's"); if (args.request !== undefined || args.scope !== undefined || args.note !== undefined) return bad("request, scope and note are a video-assist job's"); const article = trimmed(args.article); @@ -397,6 +398,80 @@ function validateVideoAssistArgs(args: Record<string, unknown>, waitSeconds: num return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } }; } +// ─── propose-groups (lane L4): claim groups proposed for a umtool project's cut ─── + +const PROPOSE_GROUPS = "propose-groups"; + +function validateProposeGroupsArgs(args: Record<string, unknown>, waitSeconds: number): { ok: true; request: GenerateRequest } | { ok: false; error: string } { + const bad = (error: string) => ({ ok: false as const, error: `generate: ${error}` }); + const project = trimmed(args.project); + if (!project.startsWith("/")) return bad("a propose-groups job names its project: the video project's absolute directory (project)"); + for (const k of ["article", "iteration", "copyOf", "question", "channels", "feedback", "from", "to", "cards", "entries", "force", "autonomy", "extractorModel", "proposals", "scope", "note"] as const) { + if (args[k] !== undefined) return bad(`${k} is not a propose-groups job's (it reads its project)`); + } + const body: Body = { task: PROPOSE_GROUPS, project }; + if (args.request !== undefined) { + const r = trimmed(args.request); + if (r) body.request = r; + } + if (args.model !== undefined) { + const m = trimmed(args.model); + if (!m) return bad("model is text"); + body.model = m; + } + if (args.maxUsd !== undefined) { + if (typeof args.maxUsd !== "number" || !(args.maxUsd > 0)) return bad("maxUsd is a positive number of dollars"); + body.maxUsd = args.maxUsd; + } + if (args.answers !== undefined) { + if (!args.answers || typeof args.answers !== "object" || Array.isArray(args.answers)) return bad('answers is {"groups": [{"section", "claim", "ids", "why"}]}'); + if (body.model) return bad("answers are this session's: no model"); + body.answers = args.answers; + } + let via: "api" | "local" | undefined; + if (args.via !== undefined) { + const v = trimmed(args.via); + if (v !== "api" && v !== "local") return bad('via is "api" or "local"'); + if (body.model || body.answers) return bad("give model, via or answers — one"); + via = v; + } + if (args.wait !== undefined && typeof args.wait !== "boolean") return bad("wait is true or false"); + return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } }; +} + +type GroupsPlanView = { estimate?: { inputTokens?: number }; request?: { system?: string; user?: string } }; + +// The `code` route: this session proposes the groups the editor's plan describes. +export function renderProposeGroupsRequest(body: Body, plan: GroupsPlanView, preset: string): string { + const r = plan.request ?? {}; + return [ + `generate propose-groups: routed to Claude Code (preset ${preset}) — propose the claim groups for this cut in this session.`, + `Read the cut below and give the groups, each {"section", "claim", "ids", "why"}: clips standing together in one section that make one claim.`, + `Then call generate with task "propose-groups", project "${String(body.project)}"${body.request ? `, the same request ${JSON.stringify(String(body.request))}` : ""}, answers: {"groups": [...]} and wait: true — ` + + "the editor checks each group exactly as a model's (clips not together, across a section boundary or in a group already are refused, with the reason) and writes group-proposals.json. " + + "They are PROPOSALS: the operator accepts or rejects each in umtool (the Cut tab). Never write that file or the manifest yourself.", + "", + "## The instructions", + r.system ?? "", + "", + "## The cut", + r.user ?? "", + ].join("\n"); +} + +type GroupsMarker = { project?: string; groups?: { proposed?: number; refused?: number; file?: string | null } }; + +function proposeGroupsSummary(f: Extract<Followed, { kind: "ended" }>, m: Marker & GroupsMarker): ToolAnswer { + const g = m.groups ?? {}; + const lines = [ + `generate propose-groups: job ${f.job.id} ended **${f.job.status}** — ${m.summary ?? m.status ?? ""}`.trim(), + `Project: ${m.project ?? "?"} · ${g.proposed ?? 0} proposed, ${g.refused ?? 0} refused` + (m.usd ? ` · $${m.usd.toFixed(4)}` : ""), + "", + "These are proposals in group-proposals.json: the operator accepts or rejects each in umtool (the Cut tab's group proposals). Nothing in the cut changed.", + ]; + return { text: lines.join("\n"), isError: f.job.status !== "done" }; +} + type AssistPlanView = { scope?: string; estimate?: { inputTokens?: number }; request?: { system?: string; user?: string } }; // The `code` route: this session answers the request the editor's plan names. @@ -669,6 +744,7 @@ async function summarise( if (marker?.task === "verdicts") return verdictsSummary(f, marker); if (marker?.task === CLIPS_SUGGEST) return clipsSuggestSummary(f, marker); if (marker?.task === VIDEO_ASSIST) return videoAssistSummary(f, marker as Marker & AssistMarker); + if (marker?.task === PROPOSE_GROUPS) return proposeGroupsSummary(f, marker as Marker & GroupsMarker); const article = marker?.article ?? hint.article; const n = marker?.iteration ?? hint.iteration; const task = marker?.task ?? hint.task ?? "report-draft"; @@ -762,6 +838,11 @@ export async function generateTool( const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true }); if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true }; return { text: renderVideoAssistRequest(body, (plan.body.plan ?? {}) as AssistPlanView, p.preset) }; + } else if (task === PROPOSE_GROUPS && body.answers === undefined && p.routes[task] === "code") { + // The session proposes them: the editor's plan is the request. + const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true }); + if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true }; + return { text: renderProposeGroupsRequest(body, (plan.body.plan ?? {}) as GroupsPlanView, p.preset) }; } else if (task === "verdicts" && p.routes[task] === "code") { // Verdicts are not a session's to make: the bench's bar names the models. return { @@ -788,7 +869,7 @@ export async function generateTool( const jobId = typeof a.body.jobId === "string" ? a.body.jobId : ""; const n = typeof a.body.iteration === "number" ? a.body.iteration : undefined; if (!jobId) return { text: `generate: the editor accepted it and started no job (${JSON.stringify(a.body)})`, isError: true }; - const article = task === CLIPS_SUGGEST || task === VIDEO_ASSIST ? "" : String(body.article); + const article = task === CLIPS_SUGGEST || task === VIDEO_ASSIST || task === PROPOSE_GROUPS ? "" : String(body.article); const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : []; const head = `generate ${task}: queued as job ${jobId}` + @@ -900,20 +981,20 @@ export const GENERATION_TOOLS = [ project: { type: "string", description: - "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers. video-assist: the video project's absolute directory (its video.manifest.json).", + "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers. video-assist and propose-groups: the video project's absolute directory (its video.manifest.json); propose-groups proposes claim groups for its cut into group-proposals.json, which the operator accepts or rejects in umtool.", }, proposals: { type: "array", items: { type: "string" }, description: "clips-suggest: only these proposal ids." }, request: { type: "string", description: - 'video-assist: what to change on the video project, in words ("make the joins 0.15 s with less smear") — one ask whose checked edits land in the project\'s assist-proposals.json as proposals the operator applies in umtool. Routed to code: the answer is the request, which this session answers and returns as answers.', + 'video-assist: what to change on the video project, in words ("make the joins 0.15 s with less smear") — one ask whose checked edits land in the project\'s assist-proposals.json as proposals the operator applies in umtool. Routed to code: the answer is the request, which this session answers and returns as answers. propose-groups: optional words for the ask ("group the October clips by day").', }, scope: { type: "string", enum: ["look", "clips", "fx", "all"], description: "video-assist: what the ask may touch (default all)." }, note: { type: "string", description: "video-assist: a note on the whole project (n_…) whose text is the request; the proposals are posted to it as the agent's reply." }, answers: { type: "object", description: - 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]}; video-assist routed to code: {"ops": [{"op", "id", "key", "value"}], "reply"} — read as a model\'s answer, written by the editor.', + 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]}; video-assist routed to code: {"ops": [{"op", "id", "key", "value"}], "reply"}; propose-groups routed to code: {"groups": [{"section", "claim", "ids", "why"}]} — read as a model\'s answer, written by the editor.', }, wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." }, wait_seconds: { diff --git a/settings.json.example b/settings.json.example @@ -274,7 +274,8 @@ "verdicts": "local", "frames": "api", "clips-suggest": "local", - "video-assist": "local" + "video-assist": "local", + "propose-groups": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/umtool/app/api/report/group-proposals/route.ts b/umtool/app/api/report/group-proposals/route.ts @@ -0,0 +1,142 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { + GroupsRequestError, + acceptGroupProposal, + clearGroupsJob, + groupProposalsView, + groupsDraftBodyOf, + groupsJobView, + groupsRouteOf, + parseGroupsRequest, + readGroupsJob, + rejectGroupProposals, + writeGroupsJob, +} from "@/lib/report/groupProposals.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// CLAIM-GROUP PROPOSALS (lane L4) -- optional, every part of it. Propose +// groups starts the EDITOR's `report-draft` job, task `propose-groups`, +// routed by settings.generation (local by default); its proposals land in +// `<project>/group-proposals.json`. This route asks with the shared +// WORKER_TOKEN, follows the job, and ACCEPTS on the operator's click: one +// group written through the manifest's structural writer (setGroup), +// token-guarded (lib/report/groupProposals.mjs). Never applied otherwise. +// +// GET ?project=<id> { proposals, error, route, editorError, job, token } +// GET ?project=<id>&job=<jobId> that job (ended: forgotten) +// POST { project, op: "start", request? } → { jobId, job } +// POST { project, op: "accept", id, token, at? } → { accepted, group, token, proposals } | { failed, error } | 409 +// POST { project, op: "reject", id?, at? } → { rejected, proposals } +// POST ?cancel=<jobId>&project=<id> stop it +const headers = { "cache-control": "no-store" }; + +async function groupsProject(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: "claim groups are a report video's" }, { status: 400, headers }) }; + return { project }; +} + +const failed = (e: unknown) => { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers }); + const status = e instanceof EditorError ? e.status : e instanceof GroupsRequestError ? ((e as GroupsRequestError & { status?: number }).status ?? 400) : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); +}; + +async function jobOf(dir: string, id: string) { + const rec = await readGroupsJob(dir); + const job = await readDraftJob(id, 40); + const view = groupsJobView(rec && rec.jobId === id ? rec : null, job); + if (view.ended) await clearGroupsJob(dir, id); + return view; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await groupsProject(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 groupProposalsView(dir); + const policy = await readPolicy().catch((e: unknown) => e as Error); + const rec = await readGroupsJob(dir); + let job = null; + if (rec) { + job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => { + if (e instanceof EditorError && e.status === 404) await clearGroupsJob(dir, rec.jobId); + return null; + }); + } + return Response.json( + { + ...view, + route: policy instanceof Error ? null : groupsRouteOf(policy.generation, dir), + editorError: policy instanceof Error ? policy.message : null, + job, + token: await manifestToken(dir), + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/group-proposals"); + if (refused) return refused; + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const r = await groupsProject(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 groupsProject(body.project); + if ("error" in r) return r.error; + const dir = r.project.dir; + const at = typeof body.at === "string" ? body.at : null; + try { + if (body.op === "accept") { + const token = body.token === undefined || body.token === null ? null : String(body.token); + const { result, editNotes } = await withEditNotes(r.project, () => acceptGroupProposal(dir, { id: String(body.id ?? ""), token, at })); + return Response.json({ ok: true, ...result, editNotes }, { headers }); + } + if (body.op === "reject") { + const id = typeof body.id === "string" && body.id ? body.id : null; + return Response.json({ ok: true, ...(await rejectGroupProposals(dir, { id, at })) }, { headers }); + } + if (body.op !== undefined && body.op !== "start") return Response.json({ error: 'op is "start", "accept" or "reject"' }, { status: 400, headers }); + const req = parseGroupsRequest(body); + const running = await readGroupsJob(dir); + if (running) { + const view = await jobOf(dir, running.jobId).catch(() => null); + if (view && !view.ended) return Response.json({ error: "groups are already being proposed for this project", job: view }, { status: 409, headers }); + } + const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: groupsDraftBodyOf(dir, req) }); + const jobId = String(answer.jobId ?? ""); + if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers }); + await writeGroupsJob(dir, { jobId, ...(req.request ? { request: req.request } : {}), at: new Date().toISOString() }); + const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, status: "queued", ended: false, queue: null, last: null, summary: null })); + return Response.json({ ok: true, jobId, job }, { headers }); + } catch (e) { + return failed(e); + } +} diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -22,7 +22,14 @@ import { updateSection, updateTeaser, upsertPost, + labelGroup, + moveGroup, + orderEntries, + promoteGroup, + removeGroup, + setGroup, } from "@/lib/report/manifest.mjs"; +import { groupModel } from "@/lib/report/claimGroups.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { deckOn } from "umtool-report-to-video/deck"; import { VERDICTS, resolveFactcheck } from "umtool-report-to-video/factcheck"; @@ -58,6 +65,14 @@ export const dynamic = "force-dynamic"; // section-remove { marker } the section joins the one before it // section-set { marker, label?, color? } relabel / recolour a section // (each section op brings the take patches' markers along: lib/report/patchMarkers.mjs syncSectionMarkers) +// order { ids: [id…] } the named entries in that order, in the places they hold +// group-set { group: gid | null, ids: [id…], claim? } a claim group is these clips (null: a new one) +// group-label { group, claim } its claim, in words +// group-remove { group } ungroup (its clips stay) +// group-move { group, before: id | null } | { group, to } | { group, after: gid } the whole group +// group-promote { group, label? } the group opens a subsection (a level-2 marker) +// (lib/report/claimGroups.mjs: a clip moved out of its run leaves the group; moved alone into +// the middle of one, it joins it) // // Every op snapshots the manifest first (`revisions/<stamp>-auto-before-<op>`), // is checked by the build's own validators, and on a GENERATED manifest leaves @@ -87,6 +102,8 @@ export async function GET(request: Request) { deckOn: deckOn(render), // The deck's sections (its markers), for "move to section…" and the section bars. sections: deckOn(render) ? sectionsOf(r.manifest) : [], + // The claim groups (lib/report/claimGroups.mjs), in cut order: the group bars. + groups: groupModel(r.manifest), factcheck: (render.chrome as { factcheck?: unknown } | undefined)?.factcheck ?? null, factcheckResolved: resolveFactcheck(render), // The stamp's knobs (video knobs): their defaults, bounds and motions, the form's placeholders. @@ -166,8 +183,29 @@ export async function POST(request: Request) { return removeSection(dir, Number(body.marker), { token }); case "section-set": return updateSection(dir, Number(body.marker), Object.fromEntries(["label", "color", "level"].filter((k) => k in body).map((k) => [k, body[k]])), { token }); + case "order": + return orderEntries(dir, Array.isArray(body.ids) ? body.ids.map(String) : [], { token }); + case "group-set": + return setGroup(dir, typeof body.group === "string" && body.group ? body.group : null, Array.isArray(body.ids) ? body.ids.map(String) : [], { claim: typeof body.claim === "string" ? body.claim : null }, { token }); + case "group-label": + return labelGroup(dir, String(body.group ?? ""), String(body.claim ?? ""), { token }); + case "group-remove": + return removeGroup(dir, String(body.group ?? ""), { token }); + case "group-move": + return moveGroup( + dir, + String(body.group ?? ""), + "before" in body + ? { before: typeof body.before === "string" && body.before ? body.before : null } + : typeof body.after === "string" && body.after + ? { after: body.after } + : { to: Number(body.to) }, + { token }, + ); + case "group-promote": + return promoteGroup(dir, String(body.group ?? ""), { label: typeof body.label === "string" ? body.label : null }, { token }); default: - throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove or section-set"); + throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove, section-set, order, group-set, group-label, group-remove, group-move or group-promote"); } }; diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx @@ -22,6 +22,8 @@ import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from /** One section of a deck cut (lib/report/sectionEdit.mjs), as the timeline route sends it. */ // `level` 2: a subsection (a section to every op, drawn inside `within`, its section, on the deck). export type SectionInfo = { index: number; label: string | null; color: string | null; marker: number | null; clips: string[]; words: string; level?: number; within?: string | null }; +/** One claim group (lib/report/claimGroups.mjs groupModel), as the Cut tab draws its bar. */ +export type GroupInfo = { id: string; claim: string; ids: string[]; section: number; words: string; first: string; last: string; at: number; index: number; promoted: boolean; color?: string | null }; type Ctx = { project: string; @@ -30,6 +32,8 @@ type Ctx = { dragging: React.MutableRefObject<{ id: string; at: number } | null>; /** A section boundary being dragged (its marker), else null. */ draggingBar: React.MutableRefObject<number | null>; + /** A claim group being dragged (its id), else null: the whole group moves. */ + draggingGroup: React.MutableRefObject<string | null>; /** The deck's sections ([] without a deck): the row menu's "move to section…". */ sections: SectionInfo[]; /** Clips ticked for a multi-clip "move to section…". */ @@ -41,9 +45,10 @@ export const useTimeline = () => useContext(TimelineCtx); const rowOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-entry][data-at]") as HTMLLIElement | null) : null); const barOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-section-bar]") as HTMLLIElement | null) : null); +const groupBarOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-group-bar]") as HTMLLIElement | null) : null); const rowKey = (li: HTMLLIElement) => ({ id: li.dataset.entry ?? "", at: Number(li.dataset.at) }); -export function TimelineList({ project, count, children }: { project: string; count: number; children: React.ReactNode }) { +export function TimelineList({ project, count, groupCount = 0, children }: { project: string; count: number; groupCount?: number; children: React.ReactNode }) { const router = useRouter(); // The manifest's write token, in a ref as well as state: a key pressed before // the first read came back must wait for it, not send no token at all. @@ -53,6 +58,7 @@ export function TimelineList({ project, count, children }: { project: string; co const [over, setOver] = useState<number | null>(null); const dragging = useRef<{ id: string; at: number } | null>(null); const draggingBar = useRef<number | null>(null); + const draggingGroup = useRef<string | null>(null); // The entries in order (Add clip's "after"), as the route last said. const [entries, setEntries] = useState<{ id: string; type: string }[]>([]); const [sections, setSections] = useState<SectionInfo[]>([]); @@ -130,7 +136,7 @@ export function TimelineList({ project, count, children }: { project: string; co }; return ( - <TimelineCtx.Provider value={{ project, busy, run, dragging, draggingBar, sections, selected, toggle }}> + <TimelineCtx.Provider value={{ project, busy, run, dragging, draggingBar, draggingGroup, sections, selected, toggle }}> <div className="mb-1.5 flex flex-wrap items-center gap-2 text-[11px]"> <button type="button" data-testid="timeline-undo" disabled={busy} onClick={() => void run("undo", {})} className={buttonVariants({ size: "sm" })}> Undo last edit @@ -140,6 +146,7 @@ export function TimelineList({ project, count, children }: { project: string; co </button> <span className="text-[var(--color-dim)]"> drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move{sections.length > 1 ? "; drag a section bar onto a clip to move its boundary, a clip onto a bar to move it into that section" : ""} + {groupCount > 0 ? "; drag a claim group's ⠿ onto a row to move the whole group before it" : ""} </span> {sections.length > 0 && selected.size > 0 && ( <span data-testid="timeline-bulk" className="inline-flex flex-wrap items-center gap-1.5 rounded border border-[var(--color-sel)] px-1.5 py-0.5"> @@ -182,6 +189,15 @@ export function TimelineList({ project, count, children }: { project: string; co data-drop-at={over ?? ""} onKeyDown={onKeyDown} onDragOver={(e) => { + if (draggingGroup.current !== null) { + // A whole group lands before a row, or before another group's bar. + const gb = groupBarOf(e.target); + const li = rowOf(e.target); + if (!gb && !li) return; + e.preventDefault(); + if (li) setOver(rowKey(li).at); + return; + } if (draggingBar.current !== null) { // A boundary goes after a CLIP. const li = rowOf(e.target); @@ -205,11 +221,22 @@ export function TimelineList({ project, count, children }: { project: string; co onDrop={(e) => { const from = dragging.current; const marker = draggingBar.current; + const group = draggingGroup.current; const li = rowOf(e.target); const bar = barOf(e.target); + const gbar = groupBarOf(e.target); dragging.current = null; draggingBar.current = null; + draggingGroup.current = null; setOver(null); + if (group !== null) { + // The whole group, its clips together, before that row (or that group's first clip). + const before = gbar ? (gbar.dataset.groupFirst ?? null) : li ? rowKey(li).id : null; + if (!before || gbar?.dataset.groupBar === group) return; + e.preventDefault(); + void run("group-move", { group, before }); + return; + } if (marker !== null) { if (!li || li.dataset.kind !== "clip") return; e.preventDefault(); @@ -598,3 +625,146 @@ export function SectionBar({ section }: { section: SectionInfo }) { </li> ); } + +/** + * A claim group's bar, inside its section (lib/report/claimGroups.mjs): the + * claim -- click it to edit it in place (Enter saves, Escape leaves it) --, + * its clips, ⠿ to drag the WHOLE group onto a row (it lands before it, in that + * row's section), Promote (a level-2 marker at its first clip, titled with the + * claim: at most 24 characters) and Ungroup (its clips stay where they are). + */ +export function GroupBar({ group }: { group: GroupInfo }) { + const ctx = useContext(TimelineCtx); + const [editing, setEditing] = useState(false); + const [claim, setClaim] = useState(group.claim); + const [promoting, setPromoting] = useState(false); + const [title, setTitle] = useState(group.claim); + // Enter or Escape has decided: the blur that follows (the input leaving) does not save again. + const decided = useRef(false); + if (!ctx) return null; + const { busy, run, draggingGroup } = ctx; + const save = () => { + decided.current = true; + const c = claim.trim(); + if (!c || c === group.claim) { + setEditing(false); + setClaim(group.claim); + return; + } + void run("group-label", { group: group.id, claim: c }).then((ok) => ok && setEditing(false)); + }; + const tl = [...title.trim()].length; + const tint = group.color ? `color-mix(in srgb, ${group.color} 55%, transparent)` : "var(--color-line)"; + return ( + <li + data-group-bar={group.id} + data-group-first={group.first} + data-group-section={group.section} + data-group-promoted={group.promoted ? "1" : "0"} + className="ml-3 flex flex-wrap items-center gap-2 rounded-sm border-l-2 border-dashed bg-[var(--color-panel)] px-2 py-0.5 text-[11px]" + style={{ borderLeftColor: tint }} + > + <span + draggable={!busy} + data-group-handle={group.id} + title="drag onto a row: the whole group moves before it" + onDragStart={(e) => { + draggingGroup.current = group.id; + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setData("text/plain", `group:${group.id}`); + }} + onDragEnd={() => (draggingGroup.current = null)} + className="cursor-grab select-none text-[12px] leading-none text-[var(--color-dim)]" + > + ⠿ + </span> + <span className="font-mono text-[var(--color-dim)]">{group.id}</span> + {editing ? ( + <input + autoFocus + data-group-claim-input={group.id} + value={claim} + maxLength={160} + onChange={(e) => setClaim(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") save(); + if (e.key === "Escape") { + decided.current = true; + setEditing(false); + setClaim(group.claim); + } + }} + onBlur={() => { + if (!decided.current) save(); + }} + className="min-w-64 flex-1 rounded border border-[var(--color-sel)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none" + /> + ) : ( + <button + type="button" + data-group-claim={group.id} + disabled={busy} + onClick={() => { + decided.current = false; + setClaim(group.claim); + setEditing(true); + }} + title="the group's claim — click to edit it" + className="min-w-0 truncate text-left text-[var(--color-text)] hover:underline" + > + {group.claim} + </button> + )} + {group.promoted && ( + <span className="micro" data-group-subsection={group.id} title="a level-2 marker opens at its first clip: the render shows it as a subsection"> + subsection + </span> + )} + <span className="micro"> + {group.ids.length} clip{group.ids.length === 1 ? "" : "s"} + </span> + {!editing && !promoting && ( + <span className="ml-auto flex items-center gap-1"> + {!group.promoted && ( + <button type="button" data-group-promote={group.id} disabled={busy} onClick={() => (setTitle(group.claim), setPromoting(true))} className={buttonVariants({ variant: "quiet", size: "sm" })} title="open a subsection here, titled with the claim (a level-2 marker at its first clip)"> + promote + </button> + )} + <button type="button" data-group-ungroup={group.id} disabled={busy} onClick={() => void run("group-remove", { group: group.id })} className={buttonVariants({ variant: "quiet", size: "sm" })} title="ungroup: the clips stay where they are"> + ungroup + </button> + </span> + )} + {promoting && ( + <span data-group-promote-form={group.id} className="ml-auto inline-flex flex-wrap items-center gap-1"> + <input + autoFocus + data-group-promote-label={group.id} + value={title} + maxLength={60} + placeholder="the subsection's title" + onChange={(e) => setTitle(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") setPromoting(false); + if (e.key === "Enter" && tl > 0 && tl <= 24) void run("group-promote", { group: group.id, label: title.trim() }).then((ok) => ok && setPromoting(false)); + }} + className="w-56 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + <span className={`num font-mono ${tl > 24 ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}`}>{tl}/24</span> + <button + type="button" + data-group-promote-go={group.id} + disabled={busy || tl === 0 || tl > 24} + onClick={() => void run("group-promote", { group: group.id, label: title.trim() }).then((ok) => ok && setPromoting(false))} + className={buttonVariants({ variant: "go", size: "sm" })} + > + Open subsection + </button> + <button type="button" disabled={busy} onClick={() => setPromoting(false)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + </span> + )} + </li> + ); +} diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -16,10 +16,12 @@ import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { Fragment } from "react"; import { deckOn } from "umtool-report-to-video/deck"; import { sectionModel, sectionWords } from "@/lib/report/sectionEdit.mjs"; -import { RowControls, RowNotes, SectionBar, TimelineList, type SectionInfo } from "../TimelineEditor"; +import { GroupBar, RowControls, RowNotes, SectionBar, TimelineList, type GroupInfo, type SectionInfo } from "../TimelineEditor"; +import { groupModel } from "@/lib/report/claimGroups.mjs"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; import VoiceMatchPanel from "./VoiceMatchPanel"; import FetchWindowsPanel from "./FetchWindowsPanel"; +import GroupProposalsPanel from "./GroupProposalsPanel"; import BenchPrepPanel from "./BenchPrepPanel"; import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; @@ -146,6 +148,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor return { opening: model.sections.length > 1 ? words(model.sections[0]) : null, after, sectionOf: model.sections.length > 1 ? (model.sectionOf as Map<string, number>) : null }; })(); + // The claim groups (lib/report/claimGroups.mjs): a bar before each group's + // first clip, inside its section; its clips' rows indented under it. + const groupBars = (() => { + const model = sectionModel(m); + const list = (groupModel(m) as GroupInfo[]).map((g) => ({ ...g, color: (model.sections[g.section] as { color?: string | null } | undefined)?.color ?? null })); + const at = new Map<number, GroupInfo>(list.map((g) => [g.at, g])); + const of = new Map<string, string>(); + for (const g of list) for (const id of g.ids) of.set(id, g.id); + return { list, at, of }; + })(); + const renderRow = (e: (typeof entries)[number], at: number) => { // Anything that is not a CLIP renders generically. The timeline's // vocabulary is open -- one real manifest carries `scroll` and @@ -176,16 +189,18 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor // `endsSentence === null` means the source has no punctuation to // read, which is a different thing to say than "this cut is fine". const midSentence = e.endsSentence === false && !e.lockEnd && !e.lock; + const inGroup = groupBars.of.get(e.id); return ( <li data-entry={e.id} data-kind="clip" data-at={at} + data-group={inGroup} tabIndex={0} data-cached={e.cached ? "1" : "0"} data-fetched={e.fetched ? "1" : "0"} data-mid-sentence={midSentence ? "1" : "0"} - className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)]" + className={`rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)] ${inGroup ? "ml-6" : ""}`} > <div className="flex flex-wrap items-baseline gap-2 text-[12px]"> <RowControls id={e.id} at={at} kind="clip" /> @@ -423,10 +438,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor /> </div> )} - <TimelineList project={project.id} count={entries.length}> + <TimelineList project={project.id} count={entries.length} groupCount={groupBars.list.length}> {sectionBars.opening && <SectionBar section={sectionBars.opening} />} {entries.map((e, at) => ( <Fragment key={`${e.id}@${at}`}> + {groupBars.at.get(at) && <GroupBar key={`g:${groupBars.at.get(at)!.id}:${groupBars.at.get(at)!.claim}`} group={groupBars.at.get(at)!} />} {renderRow(e, at)} {sectionBars.after.get(at) && <SectionBar section={sectionBars.after.get(at)!} />} </Fragment> @@ -442,6 +458,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </div> </section> + {clips.length > 0 && <GroupProposalsPanel project={project.id} />} {/* --- the walk's ★ clips: the trailer's candidates ------------------- */} {candidates.length > 0 && ( <section diff --git a/umtool/components/projects/report/GroupProposalsPanel.tsx b/umtool/components/projects/report/GroupProposalsPanel.tsx @@ -0,0 +1,230 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi"; +import { jobLine, type Job } from "./AssistBox"; + +// --------------------------------------------------------------------------- +// CLAIM-GROUP PROPOSALS on the Cut tab (lane L4), optional in every part. +// Propose groups starts the editor's `propose-groups` job (routed by +// settings.generation: local by default, through the GPU arbiter); its +// PROPOSALS come back as rows -- a section, a claim, its clips, why -- each +// with Accept and Reject. Nothing is written until Accept, which writes that +// one group through the manifest's structural writer (an undo point first; +// /api/report/group-proposals, lib/report/groupProposals.mjs). With generation +// routed to Claude Code or no editor the button says why; `groups set` and +// `groups import` are the manual path. +// --------------------------------------------------------------------------- + +type Proposed = { + id: string; + section: number; + claim: string; + ids: string[]; + why?: string; + status: "proposed" | "accepted" | "rejected" | "failed"; + error?: string; + group?: string; + now?: string | null; +}; +type Proposals = { at: string; model: string; request?: string; groups: Proposed[]; refused: { group: unknown; why: string }[] }; +type View = { + proposals: Proposals | null; + error: string | null; + route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null; + editorError: string | null; + job: Job | null; + token: string | null; +}; + +const STATUS_WORD: Record<Proposed["status"], string> = { proposed: "proposed", accepted: "accepted", rejected: "rejected", failed: "not accepted" }; + +const routeWhy = (v: View | null): string | null => { + if (!v) return "reading…"; + if (!v.route) return `needs the editor${v.editorError ? ` (${v.editorError})` : ""}`; + return v.route.why; +}; + +export default function GroupProposalsPanel({ project }: { project: string }) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [job, setJob] = useState<Job | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [request, setRequest] = useState(""); + const load = useCallback(async () => { + const r = await fetch(`/api/report/group-proposals?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + if (!r) return; + const j = (await r.json().catch(() => null)) as (View & { error?: string }) | null; + if (!r.ok || !j) { + setError(j?.error ?? `HTTP ${r.status}`); + return; + } + setView(j); + if (j.job && !j.job.ended) setJob(j.job); + }, [project]); + useEffect(() => { + void load(); + // Another editor changed the cut: whether each proposal still fits is re-read. + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project === project) void load(); + }; + window.addEventListener(MANIFEST_CHANGED, on); + return () => window.removeEventListener(MANIFEST_CHANGED, on); + }, [load, project]); + const live = job && !job.ended ? job.id : null; + useEffect(() => { + if (!live) return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/group-proposals?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as Job; + setJob(j); + if (j.ended) await load(); + }, 1500); + return () => clearInterval(t); + }, [live, project, load]); + const post = async (body: Record<string, unknown>) => { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/report/group-proposals", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + return { ok: r.ok, status: r.status, json: j }; + } finally { + setBusy(false); + } + }; + const start = async () => { + setJob(null); + const r = await post({ op: "start", ...(request.trim() ? { request: request.trim() } : {}) }); + if (r.json.job) setJob(r.json.job as Job); + if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); + }; + const accept = async (id: string) => { + const r = await post({ op: "accept", id, token: view?.token ?? null, ...(view?.proposals ? { at: view.proposals.at } : {}) }); + if (r.status === 409) setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and accept again`); + else if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); + else if (r.json.failed) setError(`${id} not accepted: ${String(r.json.error ?? "")}`); + if (r.ok && r.json.accepted) { + announceManifestChanged(project); + router.refresh(); + } + await load(); + }; + const reject = async (id: string | null) => { + const r = await post({ op: "reject", ...(id ? { id } : {}), ...(view?.proposals ? { at: view.proposals.at } : {}) }); + if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); + await load(); + }; + const why = routeWhy(view); + const running = !!job && !job.ended; + const p = view?.proposals ?? null; + const waiting = p ? p.groups.filter((g) => g.status === "proposed" || g.status === "failed") : []; + return ( + <section data-testid="group-proposals" className="mt-3 space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]"> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">claim groups — proposed</h2> + <input + data-testid="propose-groups-request" + value={request} + maxLength={2000} + placeholder="words for the ask (optional): group the October clips by day" + onChange={(e) => setRequest(e.target.value)} + className="min-w-64 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + <button + type="button" + data-testid="propose-groups-start" + disabled={busy || running || !!why} + title={why ?? "ask the model to propose claim groups for this cut; nothing changes until you Accept one"} + onClick={() => void start()} + className={buttonVariants({ size: "sm" })} + > + Propose groups + </button> + {why && view && ( + <span data-testid="propose-groups-why" className="text-[11px] text-[var(--color-dim)]"> + {why} + </span> + )} + {view?.route && !why && ( + <span className="text-[11px] text-[var(--color-dim)]"> + {view.route.route === "local" ? `on the local model${view.route.model ? ` (${view.route.model})` : ""}, through the GPU` : `on the Claude API${view.route.model ? ` (${view.route.model})` : ""}`} · nothing changes until you Accept + </span> + )} + </div> + {job && ( + <p data-testid="propose-groups-job" data-job-status={job.status} className="m-0 text-[11.5px] text-[var(--color-dim)]"> + {jobLine(job)} + </p> + )} + {error && ( + <p role="alert" data-testid="propose-groups-error" className="m-0 text-[11.5px] text-[var(--color-bad)]"> + {error} + </p> + )} + {view?.error && <p className="m-0 text-[11.5px] text-[var(--color-bad)]">{view.error}</p>} + {p && ( + <div data-proposals-at={p.at} className="space-y-1"> + <p className="m-0 text-[11px] text-[var(--color-dim)]"> + {p.groups.length} proposed by {p.model} · {new Date(p.at).toLocaleString()} + {p.request ? ` · “${p.request}”` : ""} + </p> + {p.groups.length > 0 && ( + <ul className="m-0 list-none space-y-1 p-0"> + {p.groups.map((g) => ( + <li key={g.id} data-proposal={g.id} data-proposal-status={g.status} className={cn("flex flex-wrap items-baseline gap-2", g.status === "rejected" && "opacity-60")}> + <span className="font-mono text-[var(--color-dim)]">§{g.section}</span> + <span className={cn("text-[var(--color-text)]", g.status === "accepted" && "text-kept-text")}>{g.claim}</span> + <span className="font-mono text-[11px] text-[var(--color-dim)]">{g.ids.join(" ")}</span> + {g.status !== "proposed" && ( + <span className={badgeVariants({ variant: g.status === "accepted" ? "on" : g.status === "failed" ? "blocking" : "info", size: "sm" })}> + {STATUS_WORD[g.status]} + {g.group ? ` as ${g.group}` : ""} + </span> + )} + {(g.status === "proposed" || g.status === "failed") && ( + <> + <button type="button" data-proposal-accept={g.id} disabled={busy || !!g.now} title={g.now ?? "make it a claim group of the cut (an undo point first)"} onClick={() => void accept(g.id)} className={buttonVariants({ variant: "go", size: "sm" })}> + Accept + </button> + <button type="button" data-proposal-reject={g.id} disabled={busy} onClick={() => void reject(g.id)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Reject + </button> + </> + )} + {g.why && <span className="basis-full pl-6 text-[11px] text-[var(--color-dim)]">{g.why}</span>} + {g.now && (g.status === "proposed" || g.status === "failed") && ( + <span data-proposal-now={g.id} className="basis-full pl-6 text-[11px] text-[var(--color-dim)]"> + now: {g.now} + </span> + )} + {g.error && g.status === "failed" && !g.now && <span className="basis-full pl-6 text-[11px] text-[var(--color-bad)]">{g.error}</span>} + </li> + ))} + </ul> + )} + {p.refused.length > 0 && ( + <ul className="m-0 list-none space-y-0.5 p-0" data-proposals-refused={p.refused.length}> + {p.refused.map((r, i) => ( + <li key={i} className="text-[11px] text-[var(--color-dim)]"> + not proposed: {r.why} + </li> + ))} + </ul> + )} + {waiting.length > 1 && ( + <button type="button" data-proposal-reject-all="" disabled={busy} onClick={() => void reject(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Reject the rest + </button> + )} + </div> + )} + </section> + ); +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -130,6 +130,8 @@ export type PlayViewData = { sectionsDiffer?: boolean; counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] }; markers: { after: string; label: string; level?: 2 }[]; + /** The claim groups (lib/report/claimGroups.mjs): a lighter seam before each group's first clip. */ + groups?: { id: string; claim: string; ids: string[] }[]; leadIn: number; transition: number; blurRendered: boolean; @@ -799,7 +801,7 @@ export default function PlayCut({ const placed = stamps.map((x) => ({ ...x, landed: playTimeOfChrome(plan, x.landed) })); return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(placed, id) })); }, [schedule, view.counter, doc?.verdictLabels, plan]); - const seams = useMemo(() => seamsOf(view.entries.filter((e) => !skipIds.has(e.id)), view.markers), [view.entries, view.markers, skipIds]); + const seams = useMemo(() => seamsOf(view.entries.filter((e) => !skipIds.has(e.id)), view.markers, view.groups ?? []), [view.entries, view.markers, view.groups, skipIds]); const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]); const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]); diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -40,7 +40,8 @@ type PlayItem = ReturnType<typeof playPlan>["items"][number]; export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown; rejected?: { why: string } | null }; export type StripCounter = { id: string; label: string; steps: Array<{ t: number; n: number }> }; export type StripPin = { id: string; t: number; text: string; open: boolean }; -export type StripSeam = { before: string; index: number; date: string | null; label: string | null }; +/** A seam: where a section opens, or (`kind: "group"`) a claim group -- drawn lighter. */ +export type StripSeam = { before: string; index: number; date: string | null; label: string | null; kind?: "group"; group?: string }; export type StripSection = { index: number; label: string | null; color: string | null; count?: number; level?: 2; within?: string | null }; /** A structural edit the strip asks for: a drop, an Alt+arrow, or Move to…. */ export type StripEdit = @@ -140,6 +141,7 @@ export default function ReelStrip({ // ---- the seams' labels: "27 Feb 2025 §3 Leaves it open" where they fit ---- const seamLabels = useMemo(() => { const list = seams + .filter((s) => s.kind !== "group") .map((s) => { const it = items[s.index]; if (!it) return null; @@ -460,9 +462,22 @@ export default function ReelStrip({ </span> ))} - {/* the sections' seams, in the new section's colour */} + {/* the sections' seams, in the new section's colour; a claim group's lighter: the lower half, fainter (solid: a dashed line is a gap's join) */} {seams.map((s) => { const it = items[s.index]; + if (s.kind === "group") { + return it && inView(it.from, it.from) ? ( + <span + key={`g:${s.group}:${s.before}`} + aria-hidden + data-strip-group-seam={s.before} + data-strip-group={s.group} + title={s.label ? `claim group ${s.group}: ${s.label}` : `claim group ${s.group}`} + className="pointer-events-none absolute bottom-0 z-[2] h-1/2 w-px opacity-60" + style={{ left: pct(it.from), background: named ? colorOf(secs[s.index]) : "var(--text-2)" }} + /> + ) : null; + } return it && inView(it.from, it.from) ? ( <span key={s.before} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -68,6 +68,7 @@ Inbox cannot disagree about what is wrong with one. | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | +| `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) | | `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it | | `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) | | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -274,6 +274,33 @@ named (`lib/report/sectionEdit.mjs`; `patchMarkers.mjs` syncSectionMarkers, besi out of the clip instead (it must sit at one of the clip's edges; the clip keeps the rest, its quote re-read); a span in the middle is refused — split there first. A claim, the marks and the assistant's record stay with the clip. +## Claim groups (runs of clips that make one claim) + +`groups: [{id, section, claim, ids}]` beside the timeline: a run of clips inside ONE section that makes one claim +("One of the ladies: 'I'm not a man'" is `ow1 a01 b01`). Its clips stand together (no other clip between them; a card +does not break the run), it never crosses a section boundary, a clip is in at most one group, and `section` is the +index of the deck section its clips are in (a subsection counts) — each refused in words by the structural writers' +own check (`lib/report/claimGroups.mjs` validateGroups). **The render never reads `groups`**: a cut with groups builds +exactly as the same cut without, until a group is **promoted**. A manifest without the key is never given one. + +Every structural edit keeps them: a clip **removed** leaves its group (an emptied group goes); a clip **moved out of +its run** is detached; a clip moved **alone into the middle** of a group's run (strictly between two of its clips) +**joins** that group, and one moved to a run's edge joins nothing; a **whole group** moved into another group's +middle is refused; a split's second half stays in the group; `section` follows the markers, and a boundary dragged +into a group is refused. Each write is an undo point (**Undo last edit**, `umtool timeline <p> undo`). + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the groups | the Cut tab: a group's bar inside its section (claim, clips), its clips indented under it; Play's reel strip: a group's seam, lighter than a section's (the lower half, fainter) | `umtool timeline <p> groups [ls] [--json]` | `GET /api/report/timeline` (`groups`) | +| import a claim-groups file | — | `umtool timeline <p> groups import <file> [--skip-missing] [--drop-empty]` — `{sections: [{label, groups: [{claim, ids}]}]}` in ONE write: the cut re-ordered to the file, its groups the cut's (the old ones replaced), the markers re-anchored; a file section is the deck section of its name (case and dashes aside), else the one most of its clips are in now; a clip it does not name stays in its section, after the file's; refused for an id the cut lacks (`--skip-missing` leaves it out) or a section left with no clip (`--drop-empty` removes its marker); `undo` puts the cut back exactly | — | +| make or replace a group | the propose-groups review's **Accept** | `umtool timeline <p> groups set <gid\|-> <id…> [--claim C]` (the clips already together, in one section; `-` a new `g<n>`) | `POST /api/report/timeline {op: "group-set", group, ids, claim?}` | +| the claim | a bar's claim: click it, type, Enter (Escape leaves it) | `umtool timeline <p> groups label <gid> <claim…>` (at most 160) | `{op: "group-label", group, claim}` | +| move a whole group | drag a bar's ⠿ onto a row: the group lands before it, in that row's section | `umtool timeline <p> groups move <gid> --to <index>` (its place among the groups after the move: before the group there) · `--to after <gid>` | `{op: "group-move", group, before}` · `{…, to}` · `{…, after}` | +| ungroup | a bar's **ungroup** (the clips stay) | `umtool timeline <p> groups remove <gid>` | `{op: "group-remove", group}` | +| promote: the group opens a subsection | a bar's **promote**: the title (the claim, at most 24), **Open subsection** | `umtool timeline <p> groups promote <gid> [--label L]` — a level-2 marker at its first clip (`render.chrome.deck.markers[]`, `level: 2`), the one group edit the render sees; refused for the cut's first clip, where a section already opens, and in §0 (the cut's first marker must be a section) | `{op: "group-promote", group, label?}` | +| the cut's order in one write | — | `umtool timeline <p> order <file\|@file\|id…>` — the named entries take the places the named entries hold, in that order (name them all for the whole order); every clip keeps its section (an order across a boundary is refused: `place`, `section-move`); a JSON list, `{order}`, a claim-groups file or ids by spaces, commas or lines; one undo point | `{op: "order", ids}` | +| propose groups | the Cut tab's **Propose groups**: the proposals, each **Accept** / **Reject** — never applied without a press | `pnpm ops report-draft --json '{"task":"propose-groups","project":"/abs/project/dir","request":"…"}'` (`request` optional; routed by `settings.generation`, `propose-groups`; proposals land in `<project>/group-proposals.json`, contiguous runs in one section, none over a grouped clip; Accept writes through `groups set`) | `POST /api/report/group-proposals` | + ## The finale (the timeline in primary view) The cut's last clips with the footer's rail redrawn large across the top (every pip lit, the markers flagged, diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts @@ -78,7 +78,7 @@ test("the lines, grouped Research · Article · Video · Song; the policy chip l await expect(line(page, "video-report")).toContainText(/ · \d+ found/); const chip = page.locator("[data-policy-chip]"); await expect(chip).toHaveAttribute("data-policy-chip", "balanced"); - await expect(chip).toHaveText("Generation: balanced · Claude Code: sweeps · API: report revisions, research, frames · local: video revisions, drafts, verdicts, clip labels, the video assistant"); + await expect(chip).toHaveText("Generation: balanced · Claude Code: sweeps · API: report revisions, research, frames · local: video revisions, drafts, verdicts, clip labels, the video assistant, claim groups for a cut"); await expect(chip).toHaveAttribute("href", urls.generationPolicyHref()); const rail = page.locator("[data-app-rail]"); await expect(rail.locator("[data-rail-create]")).toHaveAttribute("aria-current", "page"); diff --git a/umtool/e2e/cut-groups.spec.ts b/umtool/e2e/cut-groups.spec.ts @@ -0,0 +1,170 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Claim groups on the Cut tab and on Play's reel strip (lane L4, +// lib/report/claimGroups.mjs): +// +// cut-groups-fixture the deck on; §0 c01 c02 c03 | §1 "Two" c04 … c08; +// g1 c01 c02, g2 c04 c05, g3 c06 c07 (c03, c08 in +// none). WRITES its manifest and revisions/; every test +// starts from the fixture's. +// +// The group bars inside the section bars, the claim edited in place, a group +// bar dragged onto a row (the whole group moves), a group dropped into +// another's middle refused in words, a clip dragged alone into a group's +// middle joining it, promote (a level-2 marker at its first clip), ungroup, +// Undo, and the strip's lighter group seams. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "cut-groups-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/cut-groups-fixture"; + +type Group = { id: string; section: number; claim: string; ids: string[] }; +type Marker = { after: string; label?: string; level?: number }; +const read = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string }[]; groups?: Group[]; render: { chrome: { deck: { markers?: Marker[] } } } }; +const order = () => read().timeline.map((e) => e.id).join(" "); +const groups = () => (read().groups ?? []).map((g) => `${g.id}@${g.section}:${g.ids.join(",")}`).join(" "); +const list = (page: Page) => + page.locator("[data-testid=timeline-list] > li").evaluateAll((els) => + els.map((e) => e.getAttribute("data-entry") ?? (e.hasAttribute("data-group-bar") ? `g:${e.getAttribute("data-group-bar")}` : `§${e.getAttribute("data-section-bar")}`)), + ); + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(90_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); +}); + +async function open(page: Page) { + await page.goto(urls.section(PROJECT, "timeline")); + await settled(page); +} +/** The list has its token and no write is in flight. */ +async function settled(page: Page) { + await expect(page.getByTestId("timeline-undo")).toBeEnabled({ timeout: 20_000 }); + await page.waitForLoadState("networkidle"); +} +const POLL = { timeout: 20_000 }; + +test("the Cut tab draws each group's bar inside its section, its clips under it", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await open(page); + await expect.poll(() => list(page)).toEqual(["§0", "g:g1", "c01", "c02", "c03", "§1", "g:g2", "c04", "c05", "g:g3", "c06", "c07", "c08"]); + const g2 = page.locator("li[data-group-bar='g2']"); + await expect(g2).toContainText("The second claim, said twice"); + await expect(g2).toContainText("2 clips"); + await expect(g2).toHaveAttribute("data-group-section", "1"); + await expect(page.locator("li[data-entry='c04'][data-kind]")).toHaveAttribute("data-group", "g2"); + await expect(page.locator("li[data-entry='c03'][data-kind]")).not.toHaveAttribute("data-group", /./); + // The bar is inside its section: indented past the section bar's edge, its clips past the bar's. + const x = async (sel: string) => (await page.locator(sel).boundingBox())!.x; + expect(await x("li[data-group-bar='g2']")).toBeGreaterThan(await x("li[data-section-bar='1']")); + expect(await x("li[data-entry='c04'][data-kind]")).toBeGreaterThan(await x("li[data-group-bar='g2']")); + await page.locator("li[data-section-bar='1']").scrollIntoViewIfNeeded(); + await page.screenshot({ path: test.info().outputPath("cut-groups-bars.png"), fullPage: true }); +}); + +test("a claim is edited in place: Enter saves it, Escape leaves it", async ({ page }) => { + await open(page); + await page.locator("[data-group-claim='g3']").click(); + const input = page.locator("[data-group-claim-input='g3']"); + await input.fill("A third, reworded"); + await input.press("Escape"); + await expect(page.locator("[data-group-claim='g3']")).toHaveText("A third"); + await page.locator("[data-group-claim='g3']").click(); + await input.fill("A third, reworded"); + await input.press("Enter"); + await expect.poll(() => read().groups?.find((g) => g.id === "g3")?.claim, POLL).toBe("A third, reworded"); + await expect(page.locator("[data-group-claim='g3']")).toHaveText("A third, reworded"); +}); + +test("a group bar dragged onto a row moves the whole group before it; into another group's middle is refused; Undo", async ({ page }) => { + // Tall enough that nothing scrolls between the press and the drop (a scroll mid-drag picks up another handle). + await page.setViewportSize({ width: 1366, height: 2200 }); + await open(page); + await page.locator("[data-group-handle='g3']").dragTo(page.locator("li[data-entry='c04'][data-kind]")); + await expect.poll(order, POLL).toBe("c01 c02 c03 c06 c07 c04 c05 c08"); + expect(groups()).toBe("g1@0:c01,c02 g2@1:c04,c05 g3@1:c06,c07"); + // The boundary stays where it was: g3 is in §1, before g2. + expect(read().render.chrome.deck.markers?.map((m) => m.after)).toEqual(["c03"]); + await expect.poll(() => list(page), POLL).toEqual(["§0", "g:g1", "c01", "c02", "c03", "§1", "g:g3", "c06", "c07", "g:g2", "c04", "c05", "c08"]); + await settled(page); + + const before = readFileSync(MANIFEST, "utf8"); + await page.locator("[data-group-handle='g1']").dragTo(page.locator("li[data-entry='c05'][data-kind]")); + await expect(page.getByTestId("timeline-error")).toContainText("g2 (\"The second claim, said twice\")'s clips are not together"); + expect(readFileSync(MANIFEST, "utf8")).toBe(before); + + await page.getByTestId("timeline-undo").click(); + await expect.poll(order, POLL).toBe("c01 c02 c03 c04 c05 c06 c07 c08"); +}); + +test("a clip dragged alone into the middle of a group joins it; out of its run, it leaves", async ({ page }) => { + await open(page); + await page.locator("[data-drag-handle='c08']").dragTo(page.locator("li[data-entry='c05'][data-kind]")); + await expect.poll(order, POLL).toBe("c01 c02 c03 c04 c08 c05 c06 c07"); + await expect.poll(groups, POLL).toBe("g1@0:c01,c02 g2@1:c04,c08,c05 g3@1:c06,c07"); + await expect(page.locator("li[data-entry='c08'][data-kind]")).toHaveAttribute("data-group", "g2"); + await expect(page.locator("li[data-group-bar='g2']")).toContainText("3 clips"); + await settled(page); + // c06 onto c03's row: out of g3's run (detached), at g1's edge (it joins nothing). + await page.locator("[data-drag-handle='c06']").dragTo(page.locator("li[data-entry='c03'][data-kind]")); + await expect.poll(order, POLL).toBe("c01 c02 c06 c03 c04 c08 c05 c07"); + await expect.poll(groups, POLL).toBe("g1@0:c01,c02 g2@1:c04,c08,c05 g3@1:c07"); + await expect(page.locator("li[data-entry='c06'][data-kind]")).not.toHaveAttribute("data-group", /./); +}); + +test("promote: the group opens a subsection titled with its claim; ungroup leaves its clips where they are", async ({ page }) => { + await open(page); + await page.locator("[data-group-promote='g3']").click(); + await expect(page.locator("[data-group-promote-label='g3']")).toHaveValue("A third"); + await page.locator("[data-group-promote-go='g3']").click(); + await expect.poll(() => read().render.chrome.deck.markers, POLL).toEqual([ + { after: "c03", label: "Two", color: "#ff5a5a" }, + { after: "c05", label: "A third", level: 2 }, + ]); + await expect(page.locator("[data-group-subsection='g3']")).toBeVisible(); + await settled(page); + await expect(page.locator("li[data-section-bar='2']")).toHaveAttribute("data-section-level", "2"); + // A claim over a marker's 24 characters cannot be the title: the button waits for a shorter one. + await page.locator("[data-group-promote='g2']").click(); + await expect(page.locator("[data-group-promote-go='g2']")).toBeDisabled(); + await page.locator("[data-group-promote-label='g2']").fill("Said twice"); + await expect(page.locator("[data-group-promote-go='g2']")).toBeEnabled(); + await page.keyboard.press("Escape"); + + await page.locator("[data-group-ungroup='g1']").click(); + await expect.poll(groups, POLL).toBe("g2@1:c04,c05 g3@2:c06,c07"); + expect(order()).toBe("c01 c02 c03 c04 c05 c06 c07 c08"); + await expect(page.locator("li[data-group-bar='g1']")).toHaveCount(0); +}); + +test("Play's reel strip draws a group's seam lighter than a section's", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT)); + await expect(page.locator("[data-play-cut]")).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); + // §1 opens at c04 (a section's seam); g3 at c06 (a group's); g1 opens the cut and g2 a section: no seam of their own. + await expect(page.locator("[data-strip-seam='c04']")).toHaveCount(1); + await expect(page.locator("[data-strip-group-seam]")).toHaveCount(1); + const seam = page.locator("[data-strip-group-seam='c06']"); + await expect(seam).toHaveAttribute("data-strip-group", "g3"); + const look = (sel: string) => + page.locator(sel).evaluate((el) => { + const s = getComputedStyle(el); + return { opacity: Number(s.opacity), height: el.getBoundingClientRect().height }; + }); + const sec = await look("[data-strip-seam='c04']"); + const grp = await look("[data-strip-group-seam='c06']"); + expect(grp.opacity).toBeLessThan(sec.opacity); + expect(grp.height).toBeLessThan(sec.height); + await page.locator("[data-play-strip]").screenshot({ path: test.info().outputPath("play-group-seams.png") }); +}); diff --git a/umtool/e2e/fixtures/cut-editing-fixture.mjs b/umtool/e2e/fixtures/cut-editing-fixture.mjs @@ -18,6 +18,13 @@ // …", the Ember mistake), draft-11, and draft-12 whose // build lock names a live pid -- RENDERING // (take-housekeeping.spec.ts) +// cut-groups-fixture claim groups (lane L4): the deck on, eight clips on +// vid1 -- §0 c01 c02 c03 | §1 "Two" c04 … c08 -- and +// three groups: g1 c01 c02 (opens the cut), g2 c04 +// c05 (opens §1), g3 c06 c07; c03 and c08 in none +// (cut-groups.spec.ts) +// group-proposals-fixture cut-sections-fixture's cut, no groups: the +// propose-groups review (group-proposals.spec.ts) // // Synthetic, like every fixture. import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; @@ -36,8 +43,8 @@ const MARKERS = [ { after: "c04", label: "Three", color: "#4fbf6a" }, ]; -const sixClips = () => - ["c01", "c02", "c03", "c04", "c05", "c06"].map((id, i) => ({ +const sixClips = (ids = ["c01", "c02", "c03", "c04", "c05", "c06"]) => + ids.map((id, i) => ({ type: "clip", id, video: "vid1", @@ -109,5 +116,24 @@ export function makeCutEditingFixture({ reports, manifest, deckManifest, cachedW ]) write(path.join(takes, "takes", id), "take.json", json(take(id, order, label))); // pid 1 is always alive; this host, so the lock reads as a render running now. write(path.join(takes, "takes", "draft-12"), ".building.json", JSON.stringify({ pid: 1, host: os.hostname(), startedAt: "2026-10-31T23:00:00.000Z", take: "draft-12", from: "draft-11" }) + "\n"); - return { sections, flash, trailer, takes }; + // ---- claim groups (lane L4) ---------------------------------------------------- + const groups = path.join(reports, "cut-groups-fixture"); + const gm = deckManifest("cut-groups-fixture", "The Cut Groups Fixture", sixClips(["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08"]).map((e) => ({ ...e, start: e.start / 2, end: e.start / 2 + 0.9, cite: e.start / 2 }))); + gm.render.chrome.deck.markers = [{ after: "c03", label: "Two", color: "#ff5a5a" }]; + gm.groups = [ + { id: "g1", section: 0, claim: "The opening claim", ids: ["c01", "c02"] }, + { id: "g2", section: 1, claim: "The second claim, said twice", ids: ["c04", "c05"] }, + { id: "g3", section: 1, claim: "A third", ids: ["c06", "c07"] }, + ]; + write(groups, "video.manifest.json", json(gm)); + mkdirSync(path.join(groups, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(groups, "out", "clips-raw", "vid1_0.00-9.00.mp4")); + + const proposals = path.join(reports, "group-proposals-fixture"); + const pm = deckManifest("group-proposals-fixture", "The Group Proposals Fixture", sixClips()); + pm.render.chrome.deck.markers = MARKERS.map((m) => ({ ...m })); + write(proposals, "video.manifest.json", json(pm)); + mkdirSync(path.join(proposals, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(proposals, "out", "clips-raw", "vid1_0.00-9.00.mp4")); + return { sections, flash, trailer, takes, groups, proposals }; } diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -28,6 +28,7 @@ import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs" import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs"; import { proposalsDocOf, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; +import { checkGroupProposals, cutSections, groupProposalsDocOf, writeGroupProposals } from "yt-dlp-transcript-common/lib/report/groupProposals.mjs"; const PORT = portFor("EDITOR_STUB_PORT"); const CHANNELS = process.env.CHANNELS_DIR ?? ""; @@ -139,10 +140,10 @@ const ARTICLES = process.env.ARTICLES_DIR ?? ""; const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? ""; // Release 38 lane E: video-assist is local in every preset but api, as the editor's. const PRESETS = { - code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", "video-assist": "local" }, - balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", "video-assist": "local" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", "video-assist": "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", "video-assist": "local" }, + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", "video-assist": "local", "propose-groups": "local" }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", "video-assist": "local", "propose-groups": "local" }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", "video-assist": "api", "propose-groups": "api" }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", "video-assist": "local", "propose-groups": "local" }, }; const generation = { preset: "balanced", @@ -897,6 +898,42 @@ function startVideoAssist(body) { return { jobId: id, iteration: 0 }; } +// A `propose-groups` report-draft (lane L4): a canned "model" proposes, in +// each section, its first two clips as one claim, and one group across the +// first boundary (which the check refuses); checked and written through +// common's own checker and writer, as the real task does. +function startProposeGroups(body) { + if (typeof body.project !== "string" || !body.project.startsWith("/")) throw new Error('"project" is the video project\'s absolute directory'); + const id = `stub-groups-${nextJob++}`; + const job = { id, article: null, n: 0, task: "propose-groups", status: "queued", at: Date.now(), log: ["report-draft propose-groups (stub)"], timers: [] }; + draftJobs.set(id, job); + job.timers.push(setTimeout(() => { job.status = "running"; job.log.push("asking the stub model"); }, 300)); + job.timers.push( + setTimeout(async () => { + try { + const manifest = JSON.parse(readFileSync(path.join(body.project, "video.manifest.json"), "utf8")); + const cut = cutSections(manifest); + const bySection = new Map(); + for (const c of cut.order) bySection.set(cut.sectionOf.get(c), [...(bySection.get(cut.sectionOf.get(c)) ?? []), c]); + const groups = [...bySection.entries()].filter(([, ids]) => ids.length >= 2).map(([section, ids]) => ({ section, claim: `Section ${section}: the opening claim, said twice`, ids: ids.slice(0, 2), why: "they say the same thing" })); + const s0 = bySection.get(0) ?? []; + const s1 = bySection.get(1) ?? []; + if (s0.length && s1.length) groups.push({ section: 0, claim: "Across the first boundary", ids: [s0[s0.length - 1], s1[0]], why: "w" }); + const checked = checkGroupProposals(manifest, { groups }); + const doc = groupProposalsDocOf({ at: new Date().toISOString(), model: generation.models.local, request: body.request ?? null, checked }); + await writeGroupProposals(body.project, doc); + const summary = `${doc.groups.length} group${doc.groups.length === 1 ? "" : "s"} proposed${doc.refused.length ? `, ${doc.refused.length} refused` : ""} on ${generation.models.local}`; + job.log.push(summary, `@@report-draft ${JSON.stringify({ article: "", iteration: 0, task: "propose-groups", project: body.project, status: "done", summary, usd: 0, groups: { at: doc.at, proposed: doc.groups.length, refused: doc.refused.length, file: null } })}`); + job.status = "done"; + } catch (err) { + job.log.push(String(err.message)); + job.status = "failed"; + } + }, 1500), + ); + return { jobId: id, iteration: 0 }; +} + function cancelDraft(id) { const job = draftJobs.get(id); if (!job || !["queued", "running"].includes(job.status)) return false; @@ -904,7 +941,7 @@ function cancelDraft(id) { job.status = "cancelled"; job.log.push("cancelled"); job.child?.kill(); - if (job.task === "clips-suggest" || job.task === "video-assist") return true; + if (job.task === "clips-suggest" || job.task === "video-assist" || job.task === "propose-groups") 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)) }); @@ -993,6 +1030,14 @@ function generationRoute(req, res, url, auth) { return json(res, 400, { ok: false, error: String(err.message) }); } } + // Lane L4: claim groups proposed for a cut (a project, not an article). + if (body?.task === "propose-groups") { + try { + return json(res, 202, { ok: true, ...startProposeGroups(body) }); + } catch (err) { + return json(res, 400, { ok: false, error: String(err.message) }); + } + } // Release 38 lane E: the video assistant (a project, not an article). if (body?.task === "video-assist") { try { diff --git a/umtool/e2e/group-proposals.spec.ts b/umtool/e2e/group-proposals.spec.ts @@ -0,0 +1,88 @@ +import { test, expect } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Claim-group proposals on the Cut tab (lane L4). Propose groups starts the +// editor's `propose-groups` job (the editor stub's canned model: each +// section's first two clips as one claim, and one group across the first +// boundary, which the check refuses -- written through common's own checker +// and writer); the proposals come back as rows; nothing in the manifest moves +// until Accept, which writes ONE group through the structural writer (an undo +// point first) and its bar appears in the cut; Reject marks and writes +// nothing. +// +// group-proposals-fixture the deck on; §0 c01 c02 | §1 "Two" c03 c04 | +// §2 "Three" c05 c06; no groups. WRITES its +// manifest, group-proposals.json and revisions/. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/group-proposals-fixture"; +const DIR = path.join(FIXTURE, "reports", "group-proposals-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); + +const read = (name: string) => { + try { + return JSON.parse(readFileSync(path.join(DIR, name), "utf8")); + } catch { + return null; + } +}; +const stubRequests = (): { route: string; task?: string; project?: string; request?: string }[] => { + try { + return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")); + } catch { + return []; + } +}; + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + for (const f of ["group-proposals.json", ".propose-groups-job.json"]) rmSync(path.join(DIR, f), { force: true }); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); +}); + +test("Propose groups: the rows, nothing written; Accept writes one group and its bar appears; Reject writes nothing; a refusal shown", async ({ page }) => { + test.setTimeout(120_000); + await page.goto(urls.section(PROJECT, "timeline")); + await expect(page.getByTestId("timeline-undo")).toBeEnabled(); + const panel = page.getByTestId("group-proposals"); + await expect(panel.getByTestId("propose-groups-start")).toBeEnabled(); + const before = readFileSync(MANIFEST, "utf8"); + + await panel.getByTestId("propose-groups-request").fill("by claim"); + await panel.getByTestId("propose-groups-start").click(); + await expect(panel.getByTestId("propose-groups-job")).toHaveAttribute("data-job-status", "done", { timeout: 20_000 }); + expect(stubRequests().filter((r) => r.route === "report-draft" && r.task === "propose-groups").map((r) => [r.project, r.request])).toEqual([[DIR, "by claim"]]); + await expect(panel.locator("[data-proposal]")).toHaveCount(3); + await expect(panel.locator("[data-proposal='p1']")).toContainText("c01 c02"); + await expect(panel.locator("[data-proposals-refused]")).toContainText("not proposed:"); + expect(readFileSync(MANIFEST, "utf8")).toBe(before); + expect(read("group-proposals.json").groups.map((g: { status: string }) => g.status)).toEqual(["proposed", "proposed", "proposed"]); + + // Accept p2: one group in the manifest, an undo point, its bar in the cut. + await panel.locator("[data-proposal-accept='p2']").click(); + await expect(panel.locator("[data-proposal='p2']")).toHaveAttribute("data-proposal-status", "accepted"); + const m = read("video.manifest.json"); + expect(m.groups).toEqual([{ id: "g1", section: 1, claim: "Section 1: the opening claim, said twice", ids: ["c03", "c04"] }]); + expect(m.timeline.map((e: { id: string }) => e.id)).toEqual(["c01", "c02", "c03", "c04", "c05", "c06"]); + await expect(page.locator("li[data-group-bar='g1']")).toBeVisible(); + + // Reject p3: marked, the manifest as it was. + const after = readFileSync(MANIFEST, "utf8"); + await panel.locator("[data-proposal-reject='p3']").click(); + await expect(panel.locator("[data-proposal='p3']")).toHaveAttribute("data-proposal-status", "rejected"); + expect(readFileSync(MANIFEST, "utf8")).toBe(after); + + // Undo (the Cut tab's) takes the accepted group back; p1 still fits the cut. + await page.getByTestId("timeline-undo").click(); + await expect.poll(() => read("video.manifest.json").groups ?? null).toBeNull(); + await expect(panel.locator("[data-proposal-accept='p1']")).toBeEnabled(); +}); diff --git a/umtool/e2e/settings.spec.ts b/umtool/e2e/settings.spec.ts @@ -50,7 +50,7 @@ test("/settings lists generation and system; both light Settings", async ({ page test("generation: presets write their routes, a route alone makes it custom, caps are the editor's to refuse; the key is a file", async ({ page }) => { await page.goto(urls.generationPolicyHref()); await expect(page.locator("[data-policy-summary]")).toHaveText( - "Generation: balanced · Claude Code: sweeps · API: report revisions, research, frames · local: video revisions, drafts, verdicts, clip labels, the video assistant", + "Generation: balanced · Claude Code: sweeps · API: report revisions, research, frames · local: video revisions, drafts, verdicts, clip labels, the video assistant, claim groups for a cut", ); const policy = page.getByRole("region", { name: "generation policy" }); await expect(policy).toHaveAttribute("data-policy-preset", "balanced"); diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs @@ -30,6 +30,7 @@ const TASK_WORD = { social: "social post drafts", "clips-suggest": "clip labels", "video-assist": "the video assistant", + "propose-groups": "claim groups for a cut", }; /** diff --git a/umtool/lib/report/claimGroups.mjs b/umtool/lib/report/claimGroups.mjs @@ -0,0 +1,793 @@ +// CLAIM GROUPS (lane L4, 2 Nov 2026): runs of clips inside a section that make +// ONE claim -- "One of the ladies: 'I'm not a man'" is ow1 a01 b01 -- kept in +// the manifest beside the timeline: +// +// "groups": [{ "id": "g7", "section": 1, "claim": "…", "ids": ["ow1", "a01", "b01"] }] +// +// The rules, each refused in words (validateGroups, one of structural()'s +// checks) rather than repaired silently: +// - a group's clips stand together: no other clip between them (a card +// between two of them does not break the run); +// - it sits in ONE section -- `section` is the index of the deck section +// its clips are in (sectionEdit.mjs sectionModel; a subsection counts as a +// section), never spanning a boundary; +// - a clip is in at most one group; an id names a clip of the cut. +// +// The render never reads them: a manifest with `groups` builds exactly as the +// same manifest without, until a group is PROMOTED (a level-2 marker at its +// first clip, titled with its claim). A manifest without `groups` is never +// touched by anything here. +// +// How the structure edits keep them (syncGroups, run by applyStructural after +// every structural mutation, so every writer -- the Cut tab, Play's strip, the +// CLI, a take's walk -- keeps the same rules): +// - a clip REMOVED from the cut leaves its group, and a group left with no +// clip goes (reanchorAfterRemove says so); +// - a clip MOVED out of its group's run (not landing inside or at the edge +// of the clips of its group that stayed) is detached from the group; +// - a clip moved ALONE into the MIDDLE of a group's run -- strictly between +// two of its clips -- JOINS that group (it stands inside the claim now; a +// move to the edge of a run joins nothing). We chose joining over +// refusing: a drag into a run is the gesture for "this belongs here too", +// and a refusal would leave no way to say it but `groups set`; +// - a WHOLE group moved (all its clips together: `groups move`, a group +// bar's drag) keeps its clips; landing in the middle of another group is +// refused ("…'s clips are not together"), never a merge; +// - `section` follows the markers after every edit. +// What moved is what the op says it moved (its result's `ids` or `id`), else +// what is not in the longest common subsequence of the clip order before and +// after. +// +// Pure: everything here mutates the manifest it is handed and returns words. +// manifest.mjs runs the writers inside a structural write (the lock, the token, +// the build's checks, the undo point). + +import { MARKER_LIMITS } from "umtool-report-to-video/marker-limits"; +import { addSectionIn, reanchorMarkers, sectionModel, sectionWords } from "./sectionEdit.mjs"; + +/** A claim's characters, at most (one sentence: the bar shows it whole). */ +export const GROUP_CLAIM_MAX = 160; +/** The keys a group carries, and nothing else. */ +export const GROUP_KEYS = Object.freeze(["id", "section", "claim", "ids"]); +const GROUP_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const isClip = (e) => !!e && (e.kind ?? e.type) === "clip"; +const quoted = (s, n = 48) => { + const t = String(s ?? ""); + return `"${t.length > n ? `${t.slice(0, n - 1)}…` : t}"`; +}; +/** `g7 ("One of the ladies…")` -- how a sentence names a group. */ +export const groupWords = (g) => `${g?.id ?? "a group"}${typeof g?.claim === "string" && g.claim ? ` (${quoted(g.claim)})` : ""}`; + +/** Does this manifest carry groups at all? (`[]` counts: the key is there.) */ +export const hasGroups = (m) => Array.isArray(m?.groups); + +/** The cut's clip ids in order, each once (a variant twin counts where it first stands, as sectionModel does). */ +export function clipOrder(m) { + const seen = new Set(); + const out = []; + for (const e of Array.isArray(m?.timeline) ? m.timeline : []) { + if (!isClip(e) || typeof e.id !== "string" || seen.has(e.id)) continue; + seen.add(e.id); + out.push(e.id); + } + return out; +} + +/** An id not yet a group's: `g<n>`. */ +export function freshGroupId(groups) { + const ids = new Set((groups ?? []).map((g) => g?.id)); + for (let n = 1; ; n += 1) if (!ids.has(`g${n}`)) return `g${n}`; +} + +/** + * Every reason the cut's groups are wrong, in sentences ([] without `groups`). + * One of structural()'s checks (manifest.mjs structureErrors): an edit is + * refused only for what it breaks. + * + * @param {Record<string, any>} m + * @returns {string[]} + */ +export function validateGroups(m) { + if (m?.groups === undefined) return []; + if (!Array.isArray(m.groups)) return ["groups must be a list of {id, section, claim, ids}"]; + const errors = []; + const order = clipOrder(m); + const pos = new Map(order.map((id, k) => [id, k])); + const model = sectionModel(m); + const owner = new Map(); + const ids = new Set(); + m.groups.forEach((g, k) => { + const W = `groups[${k}]`; + if (!isObj(g)) { + errors.push(`${W} must be {id, section, claim, ids}`); + return; + } + const name = typeof g.id === "string" ? groupWords(g) : W; + const extra = Object.keys(g).filter((x) => !GROUP_KEYS.includes(x)); + if (extra.length) errors.push(`${name}: unknown key${extra.length === 1 ? "" : "s"} ${extra.join(", ")} (a group is ${GROUP_KEYS.join(", ")})`); + if (typeof g.id !== "string" || !GROUP_ID_RE.test(g.id)) errors.push(`${W}.id must be letters, digits, - or _ (at most 64)`); + else if (ids.has(g.id)) errors.push(`group id ${g.id} is used twice`); + else ids.add(g.id); + if (typeof g.claim !== "string" || !g.claim.trim()) errors.push(`${name} needs its claim, in words`); + else if ([...g.claim].length > GROUP_CLAIM_MAX) errors.push(`${name}: a claim is at most ${GROUP_CLAIM_MAX} characters (this one is ${[...g.claim].length})`); + if (!Array.isArray(g.ids) || !g.ids.length) { + errors.push(`${name} needs its clips (ids, at least one)`); + return; + } + const mine = []; + for (const id of g.ids) { + if (typeof id !== "string" || !id) { + errors.push(`${name}: every id is a clip's id`); + continue; + } + if (!pos.has(id)) { + errors.push(`${name} names ${id}, which is not a clip of the cut`); + continue; + } + if (owner.has(id)) { + errors.push(`${id} is in two groups: ${owner.get(id)} and ${g.id}`); + continue; + } + owner.set(id, g.id); + mine.push(id); + } + if (!mine.length) return; + const at = mine.map((id) => pos.get(id)).sort((a, b) => a - b); + const lo = at[0]; + const hi = at[at.length - 1]; + if (hi - lo + 1 !== at.length) { + const between = order.slice(lo, hi + 1).filter((id) => !mine.includes(id)); + errors.push(`${name}'s clips are not together: ${between.join(", ")} stand${between.length === 1 ? "s" : ""} between ${order[lo]} and ${order[hi]}`); + return; + } + const secs = [...new Set(mine.map((id) => model.sectionOf.get(id)))].sort((a, b) => a - b); + if (secs.length > 1) { + errors.push(`${name} spans ${secs.map((s) => sectionWords(model.sections[s])).join(" and ")}: a group never crosses a section boundary`); + return; + } + if (g.section !== secs[0]) { + errors.push(`${name}'s section is ${JSON.stringify(g.section ?? null)}, but its clips are in ${sectionWords(model.sections[secs[0]])}`); + } + }); + return errors; +} + +/** + * The ids that kept their order: the longest common subsequence of two id + * lists, a group's clip counting a little more than a loose one -- so when a + * loose clip and a grouped one could each be the one that moved (a swap), the + * loose one moved. Past ~4 million cells nothing is called moved. + */ +function lcsKept(a, b, member) { + const n = a.length; + const m = b.length; + if (n * m > 4_000_000) return new Set(a); + const w = (id) => (member.has(id) ? 1001 : 1000); + const L = Array.from({ length: n + 1 }, () => new Float64Array(m + 1)); + for (let i = n - 1; i >= 0; i -= 1) { + for (let j = m - 1; j >= 0; j -= 1) L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + w(a[i]) : Math.max(L[i + 1][j], L[i][j + 1]); + } + const kept = new Set(); + for (let i = 0, j = 0; i < n && j < m; ) { + if (a[i] === b[j]) { + kept.add(a[i]); + i += 1; + j += 1; + } else if (L[i + 1][j] >= L[i][j + 1]) i += 1; + else j += 1; + } + return kept; +} + +/** + * After a structural edit: the groups follow the cut (the rules at the top). + * `before` is the clip order before the edit (clipOrder); `moved`, when the op + * says, the ids it moved (else the ones out of the longest common + * subsequence). `rebuilt`: the op wrote the groups itself (import, set, …): + * only `section` and the order of each group's ids are recomputed. Mutates + * `m`; returns one sentence per change. A manifest without `groups` is never + * touched. + * + * @param {Record<string, any>} m + * @param {string[]} before + * @param {{ moved?: Iterable<string> | null, rebuilt?: boolean }} [opts] + * @returns {string[]} + */ +export function syncGroups(m, before, { moved = null, rebuilt = false } = {}) { + if (!hasGroups(m)) return []; + const notes = []; + const order = clipOrder(m); + const pos = new Map(order.map((id, k) => [id, k])); + const valid = m.groups.filter((g) => isObj(g) && Array.isArray(g.ids)); + if (!rebuilt) { + const was = new Set(before); + let mv; + if (moved) { + mv = new Set([...moved].filter((id) => pos.has(id))); + } else { + const member = new Set(valid.flatMap((g) => g.ids)); + const kept = lcsKept(before.filter((id) => pos.has(id)), order.filter((id) => was.has(id)), member); + mv = new Set(order.filter((id) => was.has(id) && !kept.has(id))); + } + for (const id of order) if (!was.has(id)) mv.add(id); + // A clip that left the cut leaves its group (reanchorAfterRemove already said so for a removal). + for (const g of valid) { + const gone = g.ids.filter((id) => typeof id === "string" && !pos.has(id)); + if (gone.length) { + g.ids = g.ids.filter((id) => !gone.includes(id)); + notes.push(`group ${groupWords(g)}: ${gone.join(", ")} left the cut`); + } + } + const ownerOf = new Map(); + for (const g of valid) for (const id of g.ids) ownerOf.set(id, g); + // A whole group moved: every clip it has moved with the edit. + const wholeMoved = new Set(valid.filter((g) => g.ids.length && g.ids.every((id) => mv.has(id)))); + // JOIN: a clip moved alone that lands strictly between two clips of a group that stayed. + for (const id of order) { + if (!mv.has(id)) continue; + const own = ownerOf.get(id); + if (own && wholeMoved.has(own)) continue; + const p = pos.get(id); + for (const g of valid) { + if (g === own || wholeMoved.has(g)) continue; + const stay = g.ids.filter((x) => !mv.has(x)).map((x) => pos.get(x)); + if (stay.length < 2 || !(Math.min(...stay) < p && p < Math.max(...stay))) continue; + if (own) { + own.ids = own.ids.filter((x) => x !== id); + notes.push(`${id} left group ${groupWords(own)}`); + } + g.ids.push(id); + ownerOf.set(id, g); + notes.push(`${id} joined group ${groupWords(g)}: it was moved into the middle of its run`); + break; + } + } + // DETACH: a moved clip that is no longer with the clips of its group that stayed. + for (const g of valid) { + if (!g.ids.length) continue; + const at = (x) => pos.get(x); + const stay = g.ids.filter((x) => !mv.has(x)); + let keep; + if (!stay.length) { + // The whole group moved: its largest run of clips together is the group. + const runs = runsOf(g.ids.map(at).sort((a, b) => a - b)); + keep = new Set(runs.sort((a, b) => b.length - a.length)[0].map((k) => order[k])); + } else { + const s = stay.map(at).sort((a, b) => a - b); + let lo = s[0]; + let hi = s[s.length - 1]; + const mine = new Set(g.ids.map(at)); + // The stayed clips' span, grown by the moved ones that stand right at its edges. + while (mine.has(lo - 1)) lo -= 1; + while (mine.has(hi + 1)) hi += 1; + keep = new Set(g.ids.filter((x) => at(x) >= lo && at(x) <= hi)); + } + const off = g.ids.filter((x) => !keep.has(x)); + if (off.length) { + g.ids = g.ids.filter((x) => keep.has(x)); + notes.push(`${off.join(", ")} ${off.length === 1 ? "was" : "were"} moved out of group ${groupWords(g)}'s run: detached from it`); + } + } + } + // An emptied group goes; each group's ids in cut order; its section from the markers. + const model = sectionModel(m); + m.groups = m.groups.filter((g) => { + if (!isObj(g) || !Array.isArray(g.ids)) return true; + if (g.ids.length) return true; + notes.push(`group ${groupWords(g)} dropped: no clip of it is left`); + return false; + }); + for (const g of m.groups) { + if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.length) continue; + if (g.ids.every((id) => pos.has(id))) g.ids.sort((a, b) => pos.get(a) - pos.get(b)); + const first = g.ids.find((id) => pos.has(id)); + const s = first === undefined ? undefined : model.sectionOf.get(first); + if (s !== undefined) g.section = s; + } + return notes; +} + +/** Maximal runs of consecutive integers in a sorted list. */ +function runsOf(sorted) { + const runs = []; + for (const k of sorted) { + const r = runs[runs.length - 1]; + if (r && r[r.length - 1] === k - 1) r.push(k); + else runs.push([k]); + } + return runs; +} + +/** + * Clip `id` left the cut: it leaves its group, and a group with no clip left + * goes. Returns one sentence per change (reanchorAfterRemove's). + */ +export function dropFromGroups(m, id) { + if (!hasGroups(m)) return []; + const notes = []; + m.groups = m.groups.filter((g) => { + if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.includes(id)) return true; + g.ids = g.ids.filter((x) => x !== id); + if (g.ids.length) { + notes.push(`group ${groupWords(g)}: ${id} dropped from it`); + return true; + } + notes.push(`group ${groupWords(g)} dropped: ${id} was its only clip`); + return false; + }); + return notes; +} + +/** After a split of `firstId`: the second half is in the first half's group too. */ +export function followSplitGroups(m, firstId, secondId) { + if (!hasGroups(m)) return []; + const g = m.groups.find((x) => isObj(x) && Array.isArray(x.ids) && x.ids.includes(firstId)); + if (!g) return []; + g.ids.splice(g.ids.indexOf(firstId) + 1, 0, secondId); + return [`${secondId} is in group ${groupWords(g)}, as ${firstId} is`]; +} + +/** + * The groups as the Cut tab, the strip and `groups ls` show them, in cut + * order: `{ id, claim, ids, section, words (the section's), index, first, + * last, at (the first clip's index in the timeline), promoted }` -- + * `promoted` when a level-2 marker opens at its first clip (its claim a + * subsection's title). + * + * @param {Record<string, any>} m + */ +export function groupModel(m) { + if (!hasGroups(m)) return []; + const model = sectionModel(m); + const tl = Array.isArray(m.timeline) ? m.timeline : []; + const at = new Map(); + tl.forEach((e, i) => { + if (isClip(e) && !at.has(e.id)) at.set(e.id, i); + }); + const opensAt = new Map(model.sections.filter((s) => s.marker !== null).map((s) => [s.first, s])); + return m.groups + .filter((g) => isObj(g) && Array.isArray(g.ids) && g.ids.some((id) => at.has(id))) + .map((g) => { + const ids = g.ids.filter((id) => at.has(id)); + const first = ids.reduce((a, b) => (at.get(b) < at.get(a) ? b : a)); + const last = ids.reduce((a, b) => (at.get(b) > at.get(a) ? b : a)); + const s = model.sectionOf.get(first) ?? 0; + const opens = opensAt.get(first); + return { + id: String(g.id), + claim: typeof g.claim === "string" ? g.claim : "", + ids, + section: s, + words: sectionWords(model.sections[s] ?? model.sections[0]), + first, + last, + at: at.get(first), + promoted: !!opens && opens.level === 2 && opens.index === s, + }; + }) + .sort((a, b) => a.at - b.at) + .map((g, index) => ({ ...g, index })); +} + +// ---- the writers (each run inside a structural write by manifest.mjs) ----- +// +// Each returns `{ …, groupsWritten: true }` when it wrote the groups itself, +// so syncGroups only recomputes their sections after it. + +function needGroup(m, gid) { + const g = hasGroups(m) ? m.groups.find((x) => isObj(x) && x.id === gid) : null; + if (!g) throw new Error(`no group ${gid}${hasGroups(m) && m.groups.length ? ` (${m.groups.map((x) => x?.id).join(", ")})` : " (the cut has no groups)"}`); + return g; +} + +const claimOf = (v) => { + const c = typeof v === "string" ? v.trim().replace(/\s+/g, " ") : ""; + if (!c) throw new Error("a group needs its claim, in words"); + if ([...c].length > GROUP_CLAIM_MAX) throw new Error(`a claim is at most ${GROUP_CLAIM_MAX} characters (this one is ${[...c].length})`); + return c; +}; + +/** + * SET: group `gid` is clips `ids` now (a new group when there is none by that + * id, or `gid` null/"-": a fresh `g<n>`). The clips must already stand + * together in one section -- reorder first (`order`, `place`); a clip in + * another group leaves it (that group must stay together, or it is refused). + * + * @param {Record<string, any>} m + * @param {string | null} gid + * @param {string[]} ids + * @param {{ claim?: string | null }} [opts] + */ +export function setGroupIn(m, gid, ids, { claim = null } = {}) { + if (!hasGroups(m)) m.groups = []; + const want = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? "").trim()).filter(Boolean))]; + if (!want.length) throw new Error("name the group's clips"); + const order = clipOrder(m); + for (const id of want) if (!order.includes(id)) throw new Error(`${id} is not a clip of the cut`); + const fresh = !gid || gid === "-" ? freshGroupId(m.groups) : String(gid).trim(); + if (!GROUP_ID_RE.test(fresh)) throw new Error("a group id is letters, digits, - or _ (at most 64)"); + let g = m.groups.find((x) => isObj(x) && x.id === fresh); + const created = !g; + if (!g) { + g = { id: fresh, section: 0, claim: claimOf(claim), ids: [] }; + m.groups.push(g); + } else if (claim !== null && claim !== undefined) g.claim = claimOf(claim); + const notes = []; + for (const o of m.groups) { + if (o === g || !isObj(o) || !Array.isArray(o.ids)) continue; + const taken = o.ids.filter((x) => want.includes(x)); + if (!taken.length) continue; + o.ids = o.ids.filter((x) => !want.includes(x)); + notes.push(`${taken.join(", ")} left group ${groupWords(o)}`); + } + const was = g.ids.slice(); + g.ids = want; + m.groups = m.groups.filter((o) => { + if (o === g || !isObj(o) || !Array.isArray(o.ids) || o.ids.length) return true; + notes.push(`group ${groupWords(o)} dropped: no clip of it is left`); + return false; + }); + return { id: g.id, created, ids: g.ids.slice(), was, claim: g.claim, notes, groupsWritten: true }; +} + +/** LABEL: group `gid`'s claim. */ +export function labelGroupIn(m, gid, claim) { + const g = needGroup(m, gid); + const was = g.claim; + g.claim = claimOf(claim); + if (was === g.claim) throw new Error(`${gid}'s claim is already ${quoted(g.claim)}`); + return { id: g.id, claim: g.claim, was, groupsWritten: true }; +} + +/** REMOVE (ungroup): group `gid` goes; its clips stay where they are. */ +export function removeGroupIn(m, gid) { + const g = needGroup(m, gid); + m.groups = m.groups.filter((x) => x !== g); + return { id: g.id, removed: { ...g }, groupsWritten: true }; +} + +/** + * MOVE A WHOLE GROUP: its clips, together, to another place among the groups + * -- `to` its index among the groups AFTER the move (0 first: right before the + * group now at that index, in its section; the number of the others: after the + * last), or `after` another group (right after its last clip, in its section). + * The markers follow so every other clip keeps its section (sectionEdit.mjs + * placeIn); a section left with no clip is refused. + * + * @param {Record<string, any>} m + * @param {string} gid + * @param {{ to?: number | null, after?: string | null }} where + * @param {(m: Record<string, any>, ids: string[], o: { before: string | null, section: number | null }) => Record<string, any>} place sectionEdit.mjs placeIn + */ +export function moveGroupIn(m, gid, { to = null, after = null } = {}, place) { + needGroup(m, gid); + const all = groupModel(m); + const me = all.find((g) => g.id === gid); + if (!me) throw new Error(`group ${gid} names no clip of the cut`); + const others = all.filter((g) => g.id !== gid); + const tl = m.timeline; + const after1 = (clipId) => { + // The entry right after `clipId` that is not one of the group's own. + const i = tl.findIndex((e) => e?.id === clipId); + const next = tl.slice(i + 1).find((e) => !me.ids.includes(e?.id)); + return next ? next.id : null; + }; + let before; + let section; + let words; + if (after !== null && after !== undefined && after !== "") { + const o = others.find((g) => g.id === after); + if (!o) throw new Error(after === gid ? `${gid} cannot go after itself` : `no other group ${after}`); + before = after1(o.last); + section = o.section; + words = `after ${groupWords(o)}`; + } else { + const k = Number(to); + if (!Number.isInteger(k) || k < 0 || k > others.length) throw new Error(`--to is a group's place, 0–${others.length} (\`groups ls\` lists them)`); + if (k === others.length) { + const o = others[others.length - 1]; + if (!o) throw new Error("there is no other group to move it among"); + before = after1(o.last); + section = o.section; + words = `after ${groupWords(o)}, the last`; + } else { + const o = others[k]; + before = o.first; + section = o.section; + words = `before ${groupWords(o)}`; + } + } + const r = place(m, me.ids, { before, section: deckSections(m) ? section : null }); + return { id: gid, ids: me.ids, words, section: r.section, before: r.before, reanchored: r.reanchored ?? [], from: me.index }; +} + +const deckSections = (m) => isObj(m?.render?.chrome); + +/** + * PROMOTE: the group opens a SUBSECTION -- a level-2 marker right before its + * first clip (after the clip before it), titled with its claim (`label`, when + * the claim is longer than a marker's label may be). The render changes from + * here on: the rail gets the subsection's tick, the section title its + * "Section › claim". Refused when no clip comes before it, when a section + * already opens there, and by the deck's own checks (the cut's first marker + * must be a section: a group in §0 opens none). + * + * @param {Record<string, any>} m + * @param {string} gid + * @param {{ label?: string | null }} [opts] + */ +export function promoteGroupIn(m, gid, { label = null } = {}) { + const g = needGroup(m, gid); + const me = groupModel(m).find((x) => x.id === gid); + if (!me) throw new Error(`group ${gid} names no clip of the cut`); + const text = typeof label === "string" && label.trim() ? label.trim() : String(g.claim ?? "").trim(); + if ([...text].length > MARKER_LIMITS.label) { + throw new Error(`${groupWords(g)}: a marker's label is at most ${MARKER_LIMITS.label} characters and ${label ? "this one" : "the claim"} is ${[...text].length} — give the subsection a shorter title (--label)`); + } + const tl = m.timeline; + const i = tl.findIndex((e) => e?.id === me.first); + const prev = [...tl.slice(0, i)].reverse().find(isClip); + if (!prev) throw new Error(`${groupWords(g)} opens the cut: no clip before it for a marker to follow`); + if (me.promoted) throw new Error(`${groupWords(g)} already opens a subsection`); + const model = sectionModel(m); + const opens = model.sections.find((s) => s.marker !== null && s.first === me.first); + if (opens) throw new Error(`${groupWords(g)} already opens ${sectionWords(opens)}: a marker is there`); + const r = addSectionIn(m, prev.id, { label: text, level: 2 }); + return { id: gid, marker: r.marker, after: prev.id, label: text, opens: me.first, within: sectionWords(model.sections[me.section]) }; +} + +// ---- import (the shape of a claim-groups.json) and order -------------------- + +const norm = (s) => String(s ?? "").normalize("NFKC").toLowerCase().replace(/[‐-―]/g, "-").replace(/\s+/g, " ").trim(); + +/** + * A claim-groups file: `{ sections: [{ label, groups: [{ claim, ids[] }] }] }`. + * Checked, never repaired: the shape, every claim, every id once. + * + * @param {unknown} doc + * @returns {{ sections: Array<{ label: string | null, groups: Array<{ claim: string, ids: string[] }> }> }} + */ +export function parseGroupsDoc(doc) { + if (!isObj(doc) || !Array.isArray(doc.sections)) throw new Error("a groups file is {sections: [{label, groups: [{claim, ids}]}]}"); + const seen = new Map(); + const sections = doc.sections.map((s, k) => { + if (!isObj(s) || !Array.isArray(s.groups)) throw new Error(`sections[${k}] is {label, groups: [{claim, ids}]}`); + const label = typeof s.label === "string" && s.label.trim() ? s.label.trim() : null; + const groups = s.groups.map((g, j) => { + const W = `sections[${k}].groups[${j}]`; + if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.length) throw new Error(`${W} is {claim, ids: [clip ids]}`); + let claim; + try { + claim = claimOf(g.claim); + } catch (e) { + throw new Error(`${W}: ${e instanceof Error ? e.message : e}`); + } + const ids = g.ids.map((x) => String(x ?? "").trim()); + for (const id of ids) { + if (!id) throw new Error(`${W}: an empty id`); + if (seen.has(id)) throw new Error(`${id} is named twice in the file (${seen.get(id)} and ${W})`); + seen.set(id, W); + } + return { claim, ids }; + }); + return { label, groups }; + }); + return { sections }; +} + +/** + * IMPORT a claim-groups file in ONE edit: the timeline re-ordered to the + * file's, its groups the cut's groups (the old ones replaced), the markers + * re-anchored around the new order. + * + * Each of the file's sections is one of the deck's: the section of the same + * name (case and dashes aside), else -- a file section the deck has no name + * for ("As a woman" inside the opening) -- the section most of its clips are + * in now, kept in order between its neighbours. Several file sections may be + * one deck section; they never come out of order (refused). A clip the file + * does not name stays in its section, after the file's clips. Refused unless + * told otherwise: an id the cut does not have (`skipMissing`: left out, and + * said), a section left with no clip (`dropEmpty`: its marker removed, and + * said; the opening, which has no marker, is never dropped). + * + * @param {Record<string, any>} m + * @param {unknown} doc + * @param {{ skipMissing?: boolean, dropEmpty?: boolean }} [opts] + */ +export function importGroupsIn(m, doc, { skipMissing = false, dropEmpty = false } = {}) { + const file = parseGroupsDoc(doc); + const tl = Array.isArray(m.timeline) ? m.timeline : (m.timeline = []); + const present = new Set(clipOrder(m)); + const named = file.sections.flatMap((s) => s.groups.flatMap((g) => g.ids)); + const missing = named.filter((id) => !present.has(id)); + if (missing.length && !skipMissing) { + throw new Error(`the file names ${missing.length} clip${missing.length === 1 ? "" : "s"} the cut does not have: ${missing.join(", ")} — pass --skip-missing to leave ${missing.length === 1 ? "it" : "them"} out`); + } + const notes = []; + if (missing.length) notes.push(`left out (not clips of the cut): ${missing.join(", ")}`); + const model = sectionModel(m); + const deck = model.sections; + // ---- each file section to a deck section ---- + const live = file.sections.map((s) => ({ ...s, groups: s.groups.map((g) => ({ ...g, ids: g.ids.filter((id) => present.has(id)) })).filter((g) => g.ids.length) })); + const byLabel = (label, from) => (label === null ? -1 : deck.findIndex((d, k) => k >= from && d.label !== null && norm(d.label) === norm(label))); + const mapped = live.map(() => /** @type {number | null} */ (null)); + let floor = 0; + live.forEach((s, k) => { + if (!s.groups.length) return; + const hit = byLabel(s.label, floor); + if (hit < 0) { + const earlier = byLabel(s.label, 0); + if (earlier < 0) return; + const prevK = mapped.findLastIndex((x) => x !== null && x > earlier); + throw new Error(`the file's sections are out of the cut's order: "${s.label}" (${sectionWords(deck[earlier])}) comes after "${live[prevK]?.label}" (${sectionWords(deck[mapped[prevK]])})`); + } + mapped[k] = hit; + floor = hit; + }); + live.forEach((s, k) => { + if (!s.groups.length || mapped[k] !== null) return; + const lo = mapped.slice(0, k).reduce((a, x) => (x === null ? a : x), 0); + const hiK = mapped.findIndex((x, j) => j > k && x !== null); + const hi = hiK < 0 ? deck.length - 1 : mapped[hiK]; + const count = new Map(); + for (const g of s.groups) for (const id of g.ids) count.set(model.sectionOf.get(id), (count.get(model.sectionOf.get(id)) ?? 0) + 1); + const most = [...count.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0][0]; + const at = Math.min(hi, Math.max(lo, most)); + mapped[k] = at; + notes.push(`"${s.label ?? `section ${k + 1}`}" → ${sectionWords(deck[at])}: the deck has no section of that name; ${at === most ? "most of its clips are there" : "the nearest in order to where its clips are"}`); + }); + // ---- each deck section's clips: the file's (in its order), then the ones it does not name ---- + const fileIds = new Set(named.filter((id) => present.has(id))); + const into = deck.map(() => /** @type {string[]} */ ([])); + live.forEach((s, k) => { + for (const g of s.groups) into[mapped[k]].push(...g.ids); + }); + const unnamed = clipOrder(m).filter((id) => !fileIds.has(id)); + for (const id of unnamed) into[model.sectionOf.get(id)].push(id); + if (unnamed.length) notes.push(`not in the file, kept at the end of their sections: ${unnamed.join(", ")}`); + const empty = deck.filter((d) => !into[d.index].length); + if (empty.some((d) => d.index === 0)) throw new Error(`the opening (§0) would have no clip: the file's first section is ${sectionWords(deck[mapped.find((x) => x !== null) ?? 0])} — the opening has no marker to remove`); + if (empty.length && !dropEmpty) { + throw new Error(`the file leaves ${empty.map((d) => sectionWords(d)).join(", ")} with no clip (the file has no section of that name, and puts its clips in others) — pass --drop-empty to remove ${empty.length === 1 ? "its marker" : "their markers"}`); + } + // ---- the new timeline: the clips in that order, a card after the clip it followed ---- + const newClips = into.flat(); + const byId = new Map(); + const cardsAfter = new Map(); + let lead = []; + let lastClip = null; + for (const e of tl) { + if (isClip(e) && !byId.has(e.id)) { + byId.set(e.id, [e]); + lastClip = e.id; + } else if (isClip(e)) byId.get(e.id).push(e); + else if (lastClip === null) lead.push(e); + else cardsAfter.set(lastClip, [...(cardsAfter.get(lastClip) ?? []), e]); + } + const before = tl.map((e) => e?.id).join("\n"); + const next = [...lead]; + for (const id of newClips) next.push(...byId.get(id), ...(cardsAfter.get(id) ?? [])); + tl.splice(0, tl.length, ...next); + // ---- the markers: each kept section opens after the last clip of the kept one before it ---- + const markers = m.render?.chrome?.deck?.markers; + const moved = []; + if (Array.isArray(markers)) { + const kept = deck.filter((d) => into[d.index].length); + for (let k = 1; k < kept.length; k += 1) { + const mk = markers[kept[k].marker]; + const after = into[kept[k - 1].index][into[kept[k - 1].index].length - 1]; + if (mk.after !== after) { + moved.push(`marker ${kept[k].marker}${mk.label ? ` ("${mk.label}")` : ""} moved from after ${mk.after} to after ${after}`); + mk.after = after; + } + } + const drop = new Set(empty.map((d) => markers[d.marker])); + for (const d of empty) notes.push(`${sectionWords(d)} removed: the file has no section of that name and puts all its clips in others`); + m.render.chrome.deck.markers = markers.filter((mk) => !drop.has(mk)); + } + // ---- the groups: the file's, in its order ---- + const old = hasGroups(m) ? m.groups.length : 0; + const groups = []; + for (const s of live) for (const g of s.groups) groups.push({ id: `g${groups.length + 1}`, section: 0, claim: g.claim, ids: g.ids }); + m.groups = groups; + const skippedGroups = file.sections.reduce((n, s) => n + s.groups.length, 0) - groups.length; + if (skippedGroups) notes.push(`${skippedGroups} group${skippedGroups === 1 ? "" : "s"} left out: none of ${skippedGroups === 1 ? "its" : "their"} clips is in the cut`); + return { + groups: groups.length, + replaced: old, + // Each file section's deck section, numbered as the cut is now (after any section dropped). + sections: live.map((s, k) => ({ label: s.label, section: mapped[k] === null ? null : mapped[k] - empty.filter((d) => d.index < mapped[k]).length, groups: s.groups.length })), + moved: before !== tl.map((e) => e?.id).join("\n"), + missing, + dropped: empty.map((d) => ({ index: d.index, label: d.label })), + reanchored: moved, + notes, + groupsWritten: true, + }; +} + +/** + * ORDER: the named entries take the places the named entries hold now, in the + * order given; every other entry stays where it is (name them all for the + * whole order). Each clip keeps its section -- the markers are re-anchored -- + * so an order that puts a clip among another section's is refused (move it + * across with `place` or `section-move`). The groups follow (syncGroups). + * + * @param {Record<string, any>} m + * @param {string[]} ids + */ +export function orderIn(m, ids) { + const tl = Array.isArray(m.timeline) ? m.timeline : []; + const want = (Array.isArray(ids) ? ids : []).map((x) => String(x ?? "").trim()).filter(Boolean); + if (!want.length) throw new Error("order needs the entries' ids, in their new order"); + const seen = new Set(); + for (const id of want) { + if (seen.has(id)) throw new Error(`${id} is named twice`); + seen.add(id); + const n = tl.filter((e) => e?.id === id).length; + if (!n) throw new Error(`no timeline entry with id ${id}`); + if (n > 1) throw new Error(`${id} is in the timeline ${n} times — order one twin with \`timeline move\``); + } + const slots = []; + tl.forEach((e, i) => { + if (seen.has(e?.id)) slots.push(i); + }); + const byId = new Map(tl.map((e) => [e?.id, e])); + const before = tl.map((e) => e?.id).join("\n"); + const next = tl.slice(); + slots.forEach((slot, k) => { + next[slot] = byId.get(want[k]); + }); + const model = sectionModel(m); + let reanchored = []; + if (Array.isArray(m.render?.chrome?.deck?.markers) && model.sections.length > 1) { + // Every clip in its own section: the sections must still follow one another. + let prev = 0; + let prevId = null; + for (const e of next) { + if (!isClip(e)) continue; + const s = model.sectionOf.get(e.id); + if (s < prev) { + throw new Error(`${e.id} (${sectionWords(model.sections[s])}) would stand after ${prevId} (${sectionWords(model.sections[prev])}): order keeps every clip in its section — move it across with place or section-move`); + } + prev = s; + prevId = e.id; + } + tl.splice(0, tl.length, ...next); + reanchored = reanchorMarkers(m, model, new Map(model.sectionOf)); + } else { + tl.splice(0, tl.length, ...next); + } + if (before === tl.map((e) => e?.id).join("\n") && !reanchored.length) throw new Error("that is the order the cut already has"); + // `named`, not `ids`: what moved is what the order changed (syncGroups' common subsequence), not every id named. + return { named: want, count: want.length, of: tl.length, reanchored }; +} + +/** + * An order as a file or the words of a command: a JSON list of ids, `{order: + * […]}`, `{timeline: [{id}…]}`, a claim-groups file (its ids in order), or ids + * separated by spaces, commas or lines. + * + * @param {string} text + * @returns {string[]} + */ +export function parseOrderText(text) { + const t = String(text ?? "").trim(); + if (!t) return []; + if (/^[[{]/.test(t)) { + let j; + try { + j = JSON.parse(t); + } catch (e) { + throw new Error(`not JSON (${e instanceof Error ? e.message : e})`); + } + if (Array.isArray(j)) return j.map(String); + if (isObj(j) && Array.isArray(j.order)) return j.order.map(String); + if (isObj(j) && Array.isArray(j.timeline)) return j.timeline.map((e) => String(isObj(e) ? e.id : e)); + if (isObj(j) && Array.isArray(j.sections)) return parseGroupsDoc(j).sections.flatMap((s) => s.groups.flatMap((g) => g.ids)); + throw new Error("an order is a list of ids, {order: […]}, {timeline: [{id}…]} or a claim-groups file"); + } + return t.split(/[\s,]+/).filter(Boolean); +} diff --git a/umtool/lib/report/claimGroups.test.mjs b/umtool/lib/report/claimGroups.test.mjs @@ -0,0 +1,300 @@ +// Claim groups (claimGroups.mjs, lane L4) through umtool's writers: the +// validator's sentences, a manifest without groups left exactly as it was, +// every structural edit keeping the groups (a removal drops the clip, a move +// out of the run detaches it, a move alone into the middle joins, a whole +// group into another's middle is refused), the writers (set, label, remove, +// move, promote, import, order), one undo point each, and the CLI. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { clipOrder, groupModel, parseOrderText, syncGroups, validateGroups } from "./claimGroups.mjs"; +import { seamsOf } from "./playCut.mjs"; +import { groupLines, groupsView, timelineCommand } from "./timelineCli.mjs"; +import { + MANIFEST_NAME, + StructureRefused, + importGroups, + labelGroup, + manifestToken, + moveEntry, + moveGroup, + moveSectionBoundary, + orderEntries, + placeEntries, + promoteGroup, + removeEntry, + removeGroup, + setGroup, + undoStructural, + addSection, +} from "./manifest.mjs"; + +const clip = (id, i) => ({ type: "clip", id, video: "v1", start: 10 * i, end: 10 * i + 8 }); +const IDS = ["a", "b", "c", "d", "e", "f", "g", "h"]; +/** §0 a b c d | §1 "Two" e f g h; g1 = a b c, g2 = e f. */ +const cut = ({ groups = true, markers = [{ after: "d", label: "Two", color: "#7fdc9a" }] } = {}) => ({ + slug: "s", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: markers ? { markers } : {} } }, + timeline: IDS.map(clip), + ...(groups + ? { + groups: [ + { id: "g1", section: 0, claim: "The first claim", ids: ["a", "b", "c"] }, + { id: "g2", section: 1, claim: "The second", ids: ["e", "f"] }, + ], + } + : {}), +}); +async function project(manifest) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-groups-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return dir; +} +const raw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8"); +const read = async (dir) => JSON.parse(await raw(dir)); +const order = async (dir) => (await read(dir)).timeline.map((e) => e.id).join(" "); +const groupsOf = async (dir) => (await read(dir)).groups.map((g) => `${g.id}@${g.section}:${g.ids.join(",")}`).join(" "); + +test("validateGroups: none is fine; each rule a sentence", () => { + assert.deepEqual(validateGroups(cut({ groups: false })), []); + assert.deepEqual(validateGroups(cut()), []); + const m = cut(); + m.groups = [ + { id: "g1", section: 0, claim: "x", ids: ["a", "c"] }, + { id: "g1", section: 1, claim: "", ids: ["d", "e"] }, + { id: "g3", section: 1, claim: "y", ids: ["zz", "a"], extra: 1 }, + { id: "g4", section: 0, claim: "z", ids: ["g"] }, + ]; + const errors = validateGroups(m); + assert.ok(errors.some((e) => /g1 \("x"\)'s clips are not together: b stands between a and c/.test(e)), errors.join("\n")); + assert.ok(errors.includes("group id g1 is used twice")); + assert.ok(errors.some((e) => /needs its claim/.test(e))); + assert.ok(errors.some((e) => /spans §0 \(the opening\) and §1 \(Two\): a group never crosses a section boundary/.test(e))); + assert.ok(errors.some((e) => /unknown key extra/.test(e))); + assert.ok(errors.some((e) => /names zz, which is not a clip of the cut/.test(e))); + assert.ok(errors.some((e) => /a is in two groups: g1 and g3/.test(e))); + assert.ok(errors.some((e) => /g4 \("z"\)'s section is 0, but its clips are in §1 \(Two\)/.test(e))); + assert.deepEqual(validateGroups({ ...cut(), groups: {} }), ["groups must be a list of {id, section, claim, ids}"]); +}); + +test("a manifest without groups is written as before: no groups key appears", async () => { + const dir = await project(cut({ groups: false })); + await moveEntry(dir, "b", 6); + await removeEntry(dir, "c"); + const m = await read(dir); + assert.equal("groups" in m, false); + assert.equal(syncGroups(m, clipOrder(m)).length, 0); +}); + +test("a removal drops the clip from its group, and the group with its last clip", async () => { + const dir = await project(cut()); + const r = await removeEntry(dir, "b"); + assert.ok(r.reanchored.includes('group g1 ("The first claim"): b dropped from it')); + await removeEntry(dir, "e"); + const r2 = await removeEntry(dir, "f"); + assert.ok(r2.reanchored.includes('group g2 ("The second") dropped: f was its only clip')); + assert.equal(await groupsOf(dir), "g1@0:a,c"); +}); + +test("a clip moved out of its run is detached; moved alone into the middle of one, it joins; to its edge, nothing", async () => { + const dir = await project(cut()); + const r = await moveEntry(dir, "a", 7); + assert.equal(await order(dir), "b c d e f g h a"); + assert.deepEqual(r.groupNotes, ['a was moved out of group g1 ("The first claim")\'s run: detached from it']); + assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:e,f"); + // h to the middle of g2 (between e and f): it joins. + const j = await moveEntry(dir, "h", 4); + assert.equal(await order(dir), "b c d e h f g a"); + assert.ok(j.groupNotes.some((x) => /h joined group g2/.test(x))); + assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:e,h,f"); + // a right after f (the run's edge): it stays out. + await moveEntry(dir, "a", 6); + assert.equal(await order(dir), "b c d e h f a g"); + assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:e,h,f"); + // A clip moved within its own run stays in it. + const w = await placeEntries(dir, ["f"], { before: "e", section: 1 }); + assert.equal(w.groupNotes, undefined); + assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:f,e,h"); +}); + +test("a section boundary dragged into a group is refused in words; one at its edge is fine", async () => { + const dir = await project(cut()); + const before = await raw(dir); + await assert.rejects(moveSectionBoundary(dir, 0, "a"), (e) => e instanceof StructureRefused && /g1 \("The first claim"\) spans §0 \(the opening\) and §1 \(Two\)/.test(e.message)); + assert.equal(await raw(dir), before); + await moveSectionBoundary(dir, 0, "c"); + // d is §1 now; the groups' sections follow the markers. + assert.equal(await groupsOf(dir), "g1@0:a,b,c g2@1:e,f"); + await assert.rejects(addSection(dir, "e", { label: "Mid" }), /g2 \("The second"\) spans/); +}); + +test("groups move: the whole group, before a group, after one, or before a row; into another's middle is refused", async () => { + const dir = await project(cut()); + const r = await moveGroup(dir, "g2", { to: 0 }); + assert.equal(await order(dir), "e f a b c d g h"); + assert.equal(r.words, 'before g1 ("The first claim")'); + // The markers follow so every other clip keeps its section; g2 is in §0 now. + assert.equal((await read(dir)).render.chrome.deck.markers[0].after, "d"); + assert.equal(await groupsOf(dir), "g1@0:a,b,c g2@0:e,f"); + await moveGroup(dir, "g2", { after: "g1" }); + assert.equal(await order(dir), "a b c e f d g h"); + // Before a row (a bar dropped on it): in that row's section. + await moveGroup(dir, "g1", { before: "h" }); + assert.equal(await order(dir), "e f d g a b c h"); + assert.equal(await groupsOf(dir), "g1@1:a,b,c g2@0:e,f"); + // Into the middle of another group: refused, nothing written. + const before = await raw(dir); + await assert.rejects(moveGroup(dir, "g2", { before: "b" }), (e) => e instanceof StructureRefused && /g1 \("The first claim"\)'s clips are not together/.test(e.message)); + assert.equal(await raw(dir), before); +}); + +test("groups set, label, remove: a fresh id, clips taken from another group, refused when not together", async () => { + const dir = await project(cut()); + await assert.rejects(setGroup(dir, null, ["g", "h"], {}), /needs its claim/); + const r = await setGroup(dir, null, ["g", "h"], { claim: "A third" }); + assert.equal(r.id, "g3"); + assert.equal(r.created, true); + await assert.rejects(setGroup(dir, null, ["d", "f"], { claim: "No" }), /not together/); + // Taking b, g1's middle clip, would leave a and c apart: refused. + await assert.rejects(setGroup(dir, null, ["b"], { claim: "B" }), (e) => e instanceof StructureRefused && /g1 \("The first claim"\)'s clips are not together/.test(e.message)); + // c leaves g1 for a new group with d (g1 stays together: a b). + await setGroup(dir, "g9", ["c", "d"], { claim: "Two clips" }); + assert.equal(await groupsOf(dir), "g1@0:a,b g2@1:e,f g3@1:g,h g9@0:c,d"); + await labelGroup(dir, "g2", " The second, reworded "); + assert.equal((await read(dir)).groups.find((g) => g.id === "g2").claim, "The second, reworded"); + await assert.rejects(labelGroup(dir, "g2", "x".repeat(161)), /at most 160/); + await removeGroup(dir, "g3"); + assert.equal(await groupsOf(dir), "g1@0:a,b g2@1:e,f g9@0:c,d"); + assert.equal(await order(dir), IDS.join(" ")); +}); + +test("promote: a level-2 marker at the group's first clip, titled with its claim; the long, the opening and §0 refused", async () => { + const dir = await project(cut()); + await assert.rejects(promoteGroup(dir, "g2", {}), /no clip before|already opens/); + await setGroup(dir, null, ["g", "h"], { claim: "Third: a claim far too long for a marker" }); + await assert.rejects(promoteGroup(dir, "g3", {}), /a marker's label is at most 24 characters and the claim is 40 — give the subsection a shorter title \(--label\)/); + const r = await promoteGroup(dir, "g3", { label: "Third" }); + assert.equal(r.after, "f"); + assert.deepEqual((await read(dir)).render.chrome.deck.markers, [ + { after: "d", label: "Two", color: "#7fdc9a" }, + { after: "f", label: "Third", level: 2 }, + ]); + assert.equal(await groupsOf(dir), "g1@0:a,b,c g2@1:e,f g3@2:g,h"); + assert.equal(groupModel(await read(dir)).find((g) => g.id === "g3").promoted, true); + await assert.rejects(promoteGroup(dir, "g3", { label: "Again" }), /already opens a subsection/); + // g1 opens the cut; a group inside §0 would make the cut's first marker a subsection. + await assert.rejects(promoteGroup(dir, "g1", {}), /opens the cut/); + await setGroup(dir, "g1", ["b", "c"]); + await assert.rejects(promoteGroup(dir, "g1", {}), /the cut's first marker opens a section/); +}); + +const FILE = { + sections: [ + { label: "Lead", groups: [{ claim: "Opens", ids: ["c", "a"] }, { claim: "Then", ids: ["b", "d"] }] }, + { label: "two", groups: [{ claim: "Second section", ids: ["h", "e"] }, { claim: "Gone", ids: ["zz"] }] }, + ], +}; + +test("import: the cut re-ordered to the file, its groups the cut's, in ONE undoable write", async () => { + const dir = await project(cut({ groups: false })); + const before = await raw(dir); + await assert.rejects(importGroups(dir, FILE), /names 1 clip the cut does not have: zz — pass --skip-missing/); + const r = await importGroups(dir, FILE, { skipMissing: true }); + assert.equal(r.groups, 3); + // "Lead" has no deck section of its name: its clips are in the opening. "two" is "Two". + assert.deepEqual(r.sections.map((s) => [s.label, s.section]), [["Lead", 0], ["two", 1], ]); + assert.ok(r.notes.some((x) => /"Lead" → §0 \(the opening\): the deck has no section of that name; most of its clips are there/.test(x))); + assert.ok(r.notes.some((x) => /not in the file, kept at the end of their sections: f, g/.test(x))); + assert.ok(r.notes.some((x) => /1 group left out/.test(x))); + assert.equal(await order(dir), "c a b d h e f g"); + assert.equal(await groupsOf(dir), "g1@0:c,a g2@0:b,d g3@1:h,e"); + const view = groupsView(await read(dir)); + assert.deepEqual(view.sections.map((s) => s.groups.map((g) => g.claim)), [["Opens", "Then"], ["Second section"]]); + assert.match(groupLines(view).join("\n"), /§1 Two\n {2}g3 {3}Second section {2}\[h e\]\n {2}ungrouped: f g\n3 groups/); + // Undo: the cut exactly as it was, byte for byte. + await undoStructural(dir); + assert.equal(await raw(dir), before); +}); + +test("import: a section the file leaves empty is refused, or its marker removed with --drop-empty; out of order refused", async () => { + const dir = await project(cut({ groups: false, markers: [{ after: "b", label: "Mid" }, { after: "d", label: "Two" }] })); + const doc = { sections: [{ label: "Open", groups: [{ claim: "x", ids: ["a", "b", "c", "d"] }] }, { label: "Two", groups: [{ claim: "y", ids: ["e", "f", "g", "h"] }] }] }; + await assert.rejects(importGroups(dir, doc), /leaves §1 \(Mid\) with no clip .* --drop-empty/); + const r = await importGroups(dir, doc, { dropEmpty: true }); + assert.deepEqual(r.dropped, [{ index: 1, label: "Mid" }]); + assert.deepEqual((await read(dir)).render.chrome.deck.markers, [{ after: "d", label: "Two" }]); + const flipped = { sections: [{ label: "Two", groups: [{ claim: "y", ids: ["e"] }] }, { label: "Mid", groups: [{ claim: "x", ids: ["a"] }] }] }; + const dir2 = await project(cut({ groups: false, markers: [{ after: "b", label: "Mid" }, { after: "d", label: "Two" }] })); + await assert.rejects(importGroups(dir2, flipped), /out of the cut's order: "Mid" \(§1 \(Mid\)\) comes after "Two"/); + await assert.rejects(importGroups(dir2, { sections: [{ label: "x", groups: [{ claim: "y", ids: ["a", "a"] }] }] }), /a is named twice/); +}); + +test("order: the named entries in the places they hold; a clip across a boundary refused; the groups follow", async () => { + const dir = await project(cut()); + await orderEntries(dir, ["c", "b", "a"]); + assert.equal(await order(dir), "c b a d e f g h"); + assert.equal(await groupsOf(dir), "g1@0:c,b,a g2@1:e,f"); + await assert.rejects(orderEntries(dir, ["e", "d"]), /e \(§1 \(Two\)\) would stand after|d \(§0 \(the opening\)\)|would stand after/); + // The whole order: g pulled between e and f joins g2 (it moved, they did not). + const r = await orderEntries(dir, ["c", "b", "a", "d", "e", "g", "f", "h"]); + assert.ok(r.groupNotes.some((x) => /g joined group g2/.test(x))); + assert.equal(await groupsOf(dir), "g1@0:c,b,a g2@1:e,g,f"); + assert.equal((await read(dir)).render.chrome.deck.markers[0].after, "d"); + assert.deepEqual(parseOrderText("a, b\nc"), ["a", "b", "c"]); + assert.deepEqual(parseOrderText('{"order": ["x"]}'), ["x"]); + assert.deepEqual(parseOrderText(JSON.stringify(FILE)), ["c", "a", "b", "d", "h", "e", "zz"]); +}); + +test("Play's seams: a group's lighter seam before its first clip, none where a section opens; without groups, as before", () => { + const m = cut(); + const entries = m.timeline.map((e) => ({ id: e.id, type: "clip" })); + const markers = m.render.chrome.deck.markers; + assert.deepEqual(seamsOf(entries, markers), seamsOf(entries, markers, [])); + const s = seamsOf(entries, markers, [...m.groups, { id: "g3", claim: "Late", ids: ["g", "h"] }]); + assert.deepEqual(s.map((x) => [x.before, x.kind ?? "section", x.label]), [ + ["e", "section", "Two"], + ["g", "group", "Late"], + ]); +}); + +test("umtool timeline <p> groups: import, ls --json in the file's shape, move, promote, undo", async () => { + const root = await mkdtemp(path.join(tmpdir(), "umtool-groups-cli-")); + const dir = path.join(root, "p"); + await (await import("node:fs/promises")).mkdir(dir); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify({ ...cut({ groups: false }), title: "P" }, null, 2) + "\n"); + const file = path.join(root, "claim-groups.json"); + await writeFile(file, JSON.stringify(FILE)); + const out = []; + const err = []; + const run = (...args) => timelineCommand(["p", ...args], { root, out: (s) => out.push(s), err: (s) => err.push(s) }); + assert.equal(await run("groups", "import", file), 1); + assert.match(err.join("\n"), /--skip-missing/); + assert.equal(await run("groups", "import", file, "--skip-missing"), 0, err.join("\n")); + assert.match(out.join("\n"), /imported 3 groups, the cut re-ordered to the file/); + assert.match(out.join("\n"), /undo point: revisions\/.*auto-before-groups-import/); + out.length = 0; + assert.equal(await run("groups", "ls", "--json"), 0); + const j = JSON.parse(out.join("\n")); + assert.deepEqual(j.sections.map((s) => s.groups.map((g) => [g.claim, g.ids])), [[["Opens", ["c", "a"]], ["Then", ["b", "d"]]], [["Second section", ["h", "e"]]]]); + out.length = 0; + assert.equal(await run("groups", "move", "g2", "--to", "0"), 0, err.join("\n")); + assert.match(out.join("\n"), /moved group g2 \(b d\) before g1/); + assert.equal(await run("groups", "move", "g2", "--to", "after", "g1"), 0, err.join("\n")); + out.length = 0; + assert.equal(await run("groups", "promote", "g2", "--label", "Then"), 1); + assert.match(err.join("\n"), /the cut's first marker opens a section/); + assert.equal(await run("groups", "label", "g3", "Second,", "said", "again"), 0, err.join("\n")); + assert.equal(await run("groups", "set", "-", "f", "g", "--claim", "Late"), 0, err.join("\n")); + out.length = 0; + assert.equal(await run("groups", "promote", "g4"), 0, err.join("\n")); + assert.match(out.join("\n"), /group g4 opens a subsection of §1 \(Two\): marker 1 after e, "Late"/); + assert.equal(await run("order", "a", "c"), 0, err.join("\n")); + const tok = await manifestToken(dir); + assert.ok(tok); +}); diff --git a/umtool/lib/report/groupProposals.mjs b/umtool/lib/report/groupProposals.mjs @@ -0,0 +1,159 @@ +// CLAIM-GROUP PROPOSALS, umtool's half (lane L4): Propose groups' request to +// the editor, the job the Cut tab follows, the proposals file read for the +// page, and ACCEPT -- the one place a proposed group becomes a write. +// +// group-proposals.json written by the EDITOR's `report-draft` task +// `propose-groups` (common lib/report/groupProposals.mjs); +// each group's status marked here (accepted / rejected / failed) +// .propose-groups-job.json the editor job the page follows, so a reload shows it; +// umtool's own file, cleared when the job is seen to end +// +// Accept writes ONE group through the manifest's structural writer +// (manifest.mjs setGroup: an undo point first, the build's checks with +// claimGroups.mjs validateGroups among them), token-guarded. A stale token is +// a 409 (reload); a refusal marks that proposal `failed` with the build's +// words. Reject marks it and writes nothing else. Nothing is ever applied by +// being proposed. +import { readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { checkGroupProposals, markGroupProposals, readGroupProposals, writeGroupProposals } from "yt-dlp-transcript-common/lib/report/groupProposals.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { StaleToken, manifestToken, setGroup } from "./manifest.mjs"; +import { assistJobView } from "./videoAssist.mjs"; + +export const GROUPS_TASK = "propose-groups"; +export const GROUPS_JOB_FILE = ".propose-groups-job.json"; +export const GROUPS_REQUEST_MAX = 2000; +const JOB_RE = /^[A-Za-z0-9_-]+$/; +const PROPOSAL_ID_RE = /^p\d{1,4}$/; +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export class GroupsRequestError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +/** A start's words, judged: `{ request? }`. */ +export function parseGroupsRequest(body) { + if (!isObj(body)) throw new GroupsRequestError("a body is { project, request? }"); + const request = typeof body.request === "string" ? body.request.replace(/\s+/g, " ").trim() : ""; + if (request.length > GROUPS_REQUEST_MAX) throw new GroupsRequestError(`a request is at most ${GROUPS_REQUEST_MAX} characters`); + return { request }; +} + +/** The editor's `report-draft` body for a project directory. */ +export const groupsDraftBodyOf = (dir, req) => ({ task: GROUPS_TASK, project: dir, ...(req.request ? { request: req.request } : {}) }); + +const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, GROUPS_JOB_FILE); + +/** The job the page follows, or null: `{ jobId, request?, at }`. */ +export async function readGroupsJob(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; + } +} + +export async function writeGroupsJob(dir, rec) { + const file = jobFileOf(dir); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(rec)}\n`); + await rename(tmp, file); +} + +export async function clearGroupsJob(dir, jobId) { + const cur = await readGroupsJob(dir); + if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true }); +} + +/** What the page shows of a job (the video assistant's view of one: its state, its last line, its result). */ +export const groupsJobView = (rec, job) => assistJobView(rec, job); + +/** How the task is routed, for the button: `{ route, model, why }`, `why` set when it cannot start a job here. */ +export function groupsRouteOf(generation, dir) { + if (!isObj(generation) || !isObj(generation.routes)) return null; + const route = generation.routes[GROUPS_TASK] ?? null; + if (route === "code") return { route, model: null, why: `routed to Claude Code — in a session: /gen propose-groups on ${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 propose-groups (an older editor)" }; +} + +/** + * The proposals for the page: each group with whether it would still be + * accepted by the cut as it is (`now: null` when it would, else the reason). + * @param {string} dir + */ +export async function groupProposalsView(dir) { + const [{ doc, error }, manifest] = await Promise.all([readGroupProposals(dir), readManifest(dir)]); + if (!doc) return { proposals: null, error }; + const groups = doc.groups.map((g) => { + if (g.status !== "proposed" && g.status !== "failed") return { ...g, now: null }; + const r = checkGroupProposals(manifest ?? {}, { groups: [g] }); + return { ...g, now: r.refused[0]?.why ?? null }; + }); + return { proposals: { ...doc, groups }, error: null }; +} + +const waiting = (g) => g.status === "proposed" || g.status === "failed"; + +/** + * ACCEPT proposal `id`: the group written through setGroup (a fresh g<n>, + * the claim as proposed). `token` is the manifest's as the page read it + * (null: unguarded); `at` the proposals the page saw (a newer ask's file is + * a 409). + * + * @param {string} dir + * @param {{ id: string, token?: string | null, at?: string | null, now?: string | null }} o + */ +export async function acceptGroupProposal(dir, { id, token = null, at = null, now = null }) { + if (typeof id !== "string" || !PROPOSAL_ID_RE.test(id)) throw new GroupsRequestError("id is a proposal's id (p1, p2, …)"); + const { doc, error } = await readGroupProposals(dir); + if (!doc) throw new GroupsRequestError(error ?? "no proposals to accept", 404); + if (at && doc.at !== at) throw new GroupsRequestError("these proposals were replaced by a newer ask — read them again", 409); + const g = doc.groups.find((x) => x.id === id); + if (!g) throw new GroupsRequestError(`no proposal ${id}`, 404); + if (!waiting(g)) throw new GroupsRequestError(`${id} is ${g.status} already`); + const cur = await manifestToken(dir); + if (token !== null && cur !== token) throw new StaleToken(token, cur); + const stamp = now ?? new Date().toISOString(); + // Checked again against the cut as it is: a clip grouped since is never taken from its group. + const still = checkGroupProposals((await readManifest(dir)) ?? {}, { groups: [g] }).refused[0]?.why ?? null; + if (still) { + const next = markGroupProposals(doc, { [id]: { status: "failed", error: still } }, stamp); + await writeGroupProposals(dir, next); + return { failed: id, error: still, token: cur, proposals: next }; + } + try { + const r = await setGroup(dir, null, g.ids, { claim: g.claim }, { token: cur }); + const next = markGroupProposals(doc, { [id]: { status: "accepted", group: r.id } }, stamp); + await writeGroupProposals(dir, next); + return { accepted: id, group: r.id, token: r.token ?? (await manifestToken(dir)), proposals: next, result: r }; + } catch (e) { + if (e instanceof StaleToken) throw e; + const msg = e instanceof Error ? (Array.isArray(e.errors) ? e.errors.join("; ") : e.message) : String(e); + const next = markGroupProposals(doc, { [id]: { status: "failed", error: msg } }, stamp); + await writeGroupProposals(dir, next); + return { failed: id, error: msg, token: cur, proposals: next }; + } +} + +/** + * REJECT proposal `id` (or every one still waiting, `id` null): marked, nothing else written. + * @param {string} dir + * @param {{ id?: string | null, at?: string | null, now?: string | null }} [o] + */ +export async function rejectGroupProposals(dir, { id = null, at = null, now = null } = {}) { + if (id !== null && (typeof id !== "string" || !PROPOSAL_ID_RE.test(id))) throw new GroupsRequestError("id is a proposal's id (p1, p2, …)"); + const { doc, error } = await readGroupProposals(dir); + if (!doc) throw new GroupsRequestError(error ?? "no proposals to reject", 404); + if (at && doc.at !== at) throw new GroupsRequestError("these proposals were replaced by a newer ask — read them again", 409); + const marks = Object.fromEntries(doc.groups.filter((g) => (id ? g.id === id : true) && waiting(g)).map((g) => [g.id, { status: "rejected" }])); + if (!Object.keys(marks).length) throw new GroupsRequestError(id ? `${id} is not waiting (accepted or rejected already)` : "nothing is waiting"); + const next = markGroupProposals(doc, marks, now ?? new Date().toISOString()); + await writeGroupProposals(dir, next); + return { rejected: Object.keys(marks), proposals: next }; +} diff --git a/umtool/lib/report/groupProposals.test.mjs b/umtool/lib/report/groupProposals.test.mjs @@ -0,0 +1,71 @@ +// Claim-group proposals, umtool's half (lane L4): Accept writes ONE group +// through setGroup (an undo point, the build's checks) and marks it with the +// group's id; a proposal the cut no longer takes is marked failed with the +// build's words; Reject marks and writes nothing; the view says which still fit. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, readdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { checkGroupProposals, groupProposalsDocOf, readGroupProposals, writeGroupProposals } from "yt-dlp-transcript-common/lib/report/groupProposals.mjs"; +import { MANIFEST_NAME, StaleToken, manifestToken, setGroup } from "./manifest.mjs"; +import { acceptGroupProposal, groupProposalsView, groupsDraftBodyOf, groupsRouteOf, parseGroupsRequest, rejectGroupProposals } from "./groupProposals.mjs"; + +const clip = (id, i) => ({ type: "clip", id, video: "v1", start: 10 * i, end: 10 * i + 8 }); +const cut = () => ({ + slug: "s", + render: { width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "c02", label: "Two" }] } } }, + timeline: ["c01", "c02", "c03", "c04"].map(clip), +}); +async function project() { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-proposals-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(cut(), null, 2) + "\n"); + const m = cut(); + const checked = checkGroupProposals(m, { groups: [{ section: 0, claim: "One", ids: ["c01", "c02"] }, { section: 1, claim: "Two", ids: ["c03", "c04"] }] }); + await writeGroupProposals(dir, groupProposalsDocOf({ at: "2026-11-02T00:00:00.000Z", model: "qwen3:8b", checked })); + return dir; +} +const manifest = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + +test("Accept: one group through setGroup, an undo point, the proposal marked with its group; Reject writes nothing", async () => { + const dir = await project(); + const r = await acceptGroupProposal(dir, { id: "p2", token: await manifestToken(dir), at: "2026-11-02T00:00:00.000Z" }); + assert.equal(r.accepted, "p2"); + assert.equal(r.group, "g1"); + assert.deepEqual((await manifest(dir)).groups, [{ id: "g1", section: 1, claim: "Two", ids: ["c03", "c04"] }]); + assert.ok((await readdir(path.join(dir, "revisions"))).some((n) => n.includes("auto-before-groups-set"))); + const { doc } = await readGroupProposals(dir); + assert.deepEqual(doc.groups.map((g) => [g.id, g.status, g.group ?? null]), [["p1", "proposed", null], ["p2", "accepted", "g1"]]); + await assert.rejects(acceptGroupProposal(dir, { id: "p2" }), /p2 is accepted already/); + await assert.rejects(acceptGroupProposal(dir, { id: "p1", at: "2020-01-01T00:00:00.000Z" }), /replaced by a newer ask/); + await assert.rejects(acceptGroupProposal(dir, { id: "p1", token: "stale" }), StaleToken); + const text = await readFile(path.join(dir, MANIFEST_NAME), "utf8"); + const j = await rejectGroupProposals(dir, { id: "p1" }); + assert.deepEqual(j.rejected, ["p1"]); + assert.equal(await readFile(path.join(dir, MANIFEST_NAME), "utf8"), text); + await assert.rejects(rejectGroupProposals(dir, {}), /nothing is waiting/); +}); + +test("a proposal the cut no longer takes: the view says why, and Accept marks it failed in the build's words", async () => { + const dir = await project(); + await setGroup(dir, null, ["c02"], { claim: "Taken by hand" }); + const v = await groupProposalsView(dir); + assert.match(v.proposals.groups[0].now, /c02 \(g1\) is in a group already/); + assert.equal(v.proposals.groups[1].now, null); + const r = await acceptGroupProposal(dir, { id: "p1" }); + assert.equal(r.failed, "p1"); + assert.match(r.error, /c02 is in two groups|in a group/); + assert.equal((await readGroupProposals(dir)).doc.groups[0].status, "failed"); + assert.deepEqual((await manifest(dir)).groups.map((g) => g.id), ["g1"]); +}); + +test("the start's body and the route's words", () => { + assert.deepEqual(parseGroupsRequest({ request: " by day " }), { request: "by day" }); + assert.deepEqual(groupsDraftBodyOf("/p", { request: "" }), { task: "propose-groups", project: "/p" }); + assert.throws(() => parseGroupsRequest({ request: "x".repeat(2001) }), /at most 2000/); + assert.match(groupsRouteOf({ routes: { "propose-groups": "code" } }, "/p").why, /routed to Claude Code/); + assert.deepEqual(groupsRouteOf({ routes: { "propose-groups": "local" }, models: { local: "qwen3:8b" } }, "/p"), { route: "local", model: "qwen3:8b", why: null }); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -65,6 +65,21 @@ import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; import { syncPatchMarkers, syncSectionMarkers } from "./patchMarkers.mjs"; import { + clipOrder, + dropFromGroups, + followSplitGroups, + hasGroups, + importGroupsIn, + labelGroupIn, + moveGroupIn, + orderIn, + promoteGroupIn, + removeGroupIn, + setGroupIn, + syncGroups, + validateGroups, +} from "./claimGroups.mjs"; +import { DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish, } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; @@ -984,6 +999,8 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no // A section boundary after the clip stays after the WHOLE of it: the // marker follows the second half, or that half opens the next section. const reanchored = followSplitMarkers(m, e.id, b.id); + // Its claim group holds the second half too. + reanchored.push(...followSplitGroups(m, e.id, b.id)); return { id: e.id, second: b.id, entries: [e, b], reanchored }; })); } @@ -1821,6 +1838,8 @@ function structureErrors(manifest) { ...validateAssist(manifest), // A clip inserted with a `blur` (the clip editor's New clip) is checked as the build checks it. ...validateClipBlurEntries(manifest), + // Claim groups (claimGroups.mjs): each one's clips together, in one section. + ...validateGroups(manifest), ]; } @@ -1872,7 +1891,20 @@ export function applyStructural(manifest, mutate) { // problem the build would name (somebody's hand edit) can still be // re-ordered, and the problem is still the build's to report. const already = new Set(structureErrors(manifest)); + const order = clipOrder(manifest); const result = mutate(manifest); + // The claim groups follow the edit (claimGroups.mjs syncGroups): a clip moved + // out of its run is detached, one moved into the middle of a run joins it, + // `section` follows the markers. What moved is what the op says it moved. + if (hasGroups(manifest)) { + const r = /** @type {Record<string, any>} */ (result && typeof result === "object" ? result : {}); + const moved = Array.isArray(r.ids) ? r.ids.map(String) : typeof r.id === "string" ? [r.id] : null; + const notes = syncGroups(manifest, order, { moved, rebuilt: r.groupsWritten === true }); + if (result && typeof result === "object") { + delete r.groupsWritten; + if (notes.length) r.groupNotes = [...(Array.isArray(r.groupNotes) ? r.groupNotes : []), ...notes]; + } + } const errors = structureErrors(manifest).filter((e) => !already.has(e)); if (errors.length) throw new StructureRefused(errors); applySectionEnter(manifest.timeline); @@ -1932,6 +1964,8 @@ export function removeIn(m, id, at = null, { reanchor = true } = {}) { export function reanchorAfterRemove(m, removed, i) { const id = removed?.id; const notes = []; + // Its claim group (claimGroups.mjs): the clip leaves it; a group left with no clip goes. + if (id) notes.push(...dropFromGroups(m, id)); const chrome = m?.render?.chrome; if (!id || !chrome || typeof chrome !== "object") return notes; const tl = m.timeline ?? []; @@ -2364,6 +2398,133 @@ export function sectionsOf(manifest) { return sectionModel(manifest).sections.map((s) => ({ ...s, words: sectionWords(s) })); } +// ---- claim groups (claimGroups.mjs; lane L4) --------------------------------- +// +// Runs of clips inside a section that make one claim (`groups` beside the +// timeline). Each writer is a structural write -- an undo point first, the +// build's checks (validateGroups among them) -- and the ones that move clips +// or markers go through sectionWrite, so the take patches' markers follow. +// The render never reads `groups`; only a promote changes it (a marker). +// `umtool timeline <p> groups …`, the Cut tab's group bars. + +/** + * SET: group `gid` is clips `ids` (a new group when there is none by that id; + * `gid` null or "-" makes a fresh `g<n>`, which needs its claim). + * + * @param {string} dir + * @param {string | null} gid + * @param {string[]} ids + * @param {{ claim?: string | null }} spec + * @param {{ token?: string | null }} [opts] + */ +export async function setGroup(dir, gid, ids, { claim = null } = {}, { token = null } = {}) { + return structural(dir, "groups-set", token, (m) => setGroupIn(m, gid, ids, { claim })); +} + +/** + * LABEL: group `gid`'s claim, in words. + * @param {string} dir + * @param {string} gid + * @param {string} claim + * @param {{ token?: string | null }} [opts] + */ +export async function labelGroup(dir, gid, claim, { token = null } = {}) { + return structural(dir, "groups-label", token, (m) => labelGroupIn(m, gid, claim)); +} + +/** + * UNGROUP: group `gid` goes; its clips stay where they stand. + * @param {string} dir + * @param {string} gid + * @param {{ token?: string | null }} [opts] + */ +export async function removeGroup(dir, gid, { token = null } = {}) { + return structural(dir, "groups-remove", token, (m) => removeGroupIn(m, gid)); +} + +/** + * MOVE A WHOLE GROUP among the groups: `to` its place after the move, or + * `after` another group; or `before` an entry (a group bar dropped on a row: + * before that entry, in its section; null: the end). Its clips go together + * (placeIn), every other clip keeping its section. Each move is its own undo + * point. + * + * @param {string} dir + * @param {string} gid + * @param {{ to?: number | null, after?: string | null, before?: string | null }} where + * @param {{ token?: string | null }} [opts] + */ +export async function moveGroup(dir, gid, { to = null, after = null, before = undefined } = {}, { token = null } = {}) { + return sectionWrite( + dir, + "groups-move", + token, + (m) => { + if (before === undefined) return moveGroupIn(m, gid, { to, after }, placeIn); + const g = (Array.isArray(m.groups) ? m.groups : []).find((x) => x?.id === gid); + if (!g) throw new Error(`no group ${gid}`); + const ids = clipOrder(m).filter((id) => g.ids.includes(id)); + const b = before === null || before === "" ? null : String(before); + if (b !== null && ids.includes(b)) throw new Error(`${b} is one of ${gid}'s own clips: drop the group outside its run`); + const tl = m.timeline; + const at = b === null ? tl.length : tl.findIndex((e) => e?.id === b); + if (at < 0) throw new Error(`no timeline entry with id ${b}`); + // The section of the clip it lands before (else after): where a drop on a row goes. + const clip = (e) => !!e && (e.kind ?? e.type) === "clip" && !ids.includes(e.id); + const model = sectionModel(m); + const next = tl.slice(at).find(clip); + const prev = [...tl.slice(0, at)].reverse().find(clip); + const s = next ? model.sectionOf.get(next.id) : prev ? model.sectionOf.get(prev.id) : null; + const r = placeIn(m, ids, { before: b, section: isObj(m.render?.chrome) ? s ?? null : null }); + return { id: gid, ids, words: b ? `before ${b}` : "at the end", section: r.section, before: r.before, reanchored: r.reanchored ?? [] }; + }, + { snapshotEvery: 0 }, + ); +} + +/** + * PROMOTE: the group opens a subsection, a level-2 marker at its first clip + * titled with its claim (`label` when the claim is longer than a marker's 24). + * The one group edit the render sees. + * + * @param {string} dir + * @param {string} gid + * @param {{ label?: string | null }} spec + * @param {{ token?: string | null }} [opts] + */ +export async function promoteGroup(dir, gid, { label = null } = {}, { token = null } = {}) { + return sectionWrite(dir, "groups-promote", token, (m) => promoteGroupIn(m, gid, { label }), { snapshotEvery: 0 }); +} + +/** + * IMPORT a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) + * in ONE write: the timeline re-ordered to it, its groups the cut's, the + * markers re-anchored (claimGroups.mjs importGroupsIn). One undo point of its + * own: `undo` puts the cut back as it was. + * + * @param {string} dir + * @param {unknown} doc + * @param {{ skipMissing?: boolean, dropEmpty?: boolean }} o + * @param {{ token?: string | null }} [opts] + */ +export async function importGroups(dir, doc, o = {}, { token = null } = {}) { + return sectionWrite(dir, "groups-import", token, (m) => importGroupsIn(m, doc, o), { snapshotEvery: 0 }); +} + +/** + * ORDER (bulk): the named entries take the places the named entries hold, in + * the order given; every clip keeps its section (the markers re-anchored); the + * groups follow. Through structural(), never replaceManifest: one undo point, + * the build's checks. + * + * @param {string} dir + * @param {string[]} ids + * @param {{ token?: string | null }} [opts] + */ +export async function orderEntries(dir, ids, { token = null } = {}) { + return sectionWrite(dir, "order", token, (m) => orderIn(m, ids), { snapshotEvery: 0 }); +} + // ---- flash-forward (UI notes 2026-10-30, item 2) ---------------------------- /** diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -377,11 +377,17 @@ export function dateRamp(entries) { * `after` clip. Each seam names the first date after it (the first dated * clip from there on) and the marker's label when a marker made it. * + * A claim group (lib/report/claimGroups.mjs) that does not open a section + * opens a GROUP seam before its first clip -- `kind: "group"`, its claim the + * label -- which the strip draws lighter than a section's. Without `groups` + * the seams are exactly the sections'. + * * @param {Array<{ id: string, type: string, section?: unknown, dateLabel?: string | null }>} entries the cut's, in order * @param {Array<{ after: string, label?: string }>} [markers] render.chrome.deck.markers - * @returns {Array<{ before: string, index: number, date: string | null, label: string | null }>} + * @param {Array<{ id: string, claim?: string, ids: string[] }>} [groups] the manifest's claim groups + * @returns {Array<{ before: string, index: number, date: string | null, label: string | null, kind?: "group", group?: string }>} */ -export function seamsOf(entries, markers = []) { +export function seamsOf(entries, markers = [], groups = []) { const list = entries ?? []; /** @type {Map<number, string | null>} */ const at = new Map(); @@ -396,14 +402,31 @@ export function seamsOf(entries, markers = []) { const i = list.findIndex((e) => e.id === m?.after); if (i >= 0 && i + 1 < list.length) at.set(i + 1, typeof m.label === "string" && m.label ? m.label : (at.get(i + 1) ?? null)); } - return [...at.entries()] + const dateAt = (i) => list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null; + const seams = [...at.entries()] .sort((a, b) => a[0] - b[0]) .map(([i, label]) => ({ before: list[i].id, index: i, - date: list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null, + date: dateAt(i), label, })); + if (!Array.isArray(groups) || !groups.length) return seams; + // A group's seam: before its first clip in the cut, where no section's is. + const index = new Map(); + list.forEach((e, i) => { + if (!index.has(e.id)) index.set(e.id, i); + }); + /** @type {Array<{ before: string, index: number, date: string | null, label: string | null, kind?: "group", group?: string }>} */ + const out = [...seams]; + for (const g of groups) { + const firsts = (Array.isArray(g?.ids) ? g.ids : []).map((id) => index.get(id)).filter((i) => i !== undefined); + if (!firsts.length) continue; + const i = Math.min(...firsts); + if (i === 0 || at.has(i)) continue; + out.push({ before: list[i].id, index: i, date: dateAt(i), label: typeof g.claim === "string" && g.claim ? g.claim : null, kind: "group", group: String(g.id) }); + } + return out.sort((a, b) => a.index - b.index); } /** diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -155,9 +155,14 @@ export async function playView(project, { take = null, bare = false } = {}) { index: x.index, label: x.label, color: x.color, marker: x.marker, count: x.clips.length, ...(x.level === 2 ? { level: 2, within: x.within ?? null } : {}), })); + // The claim groups (lib/report/claimGroups.mjs): the strip's lighter seams, from the cut played. + const groups = (Array.isArray(selected.groups) ? selected.groups : []) + .filter((g) => g && typeof g.id === "string" && Array.isArray(g.ids)) + .map((g) => ({ id: g.id, claim: typeof g.claim === "string" ? g.claim : "", ids: g.ids.filter((x) => typeof x === "string") })); return { project: project.id, title: text(manifest.title) || project.id, + groups, sections, sectionOf: Object.fromEntries(model.sectionOf), sectionsDiffer, diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs @@ -128,7 +128,7 @@ export const sectionWords = (s) => { * clip id to its section; the timeline is in section order already. Refuses a * section left with no clip. Returns one sentence per marker that moved. */ -function reanchorMarkers(m, model, membership) { +export function reanchorMarkers(m, model, membership) { const tl = m.timeline; const markers = deckMarkers(m) ?? []; const lastIn = new Map(); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -24,6 +24,10 @@ // umtool timeline <project> split <id> <second> // umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start]) // [--move] [--quote Q] [--id ID] +// umtool timeline <project> order <file|@file|id…> +// umtool timeline <project> groups [ls] | import <file> [--skip-missing] [--drop-empty] +// | set <gid|-> <id…> [--claim C] | move <gid> (--to <index> | --to after <gid>) +// | label <gid> <claim…> | promote <gid> [--label L] | remove <gid> // // An insert's attribution (--title, --date, --quote, --cite, --cite-url) is a // second write, through updateClip -- the writer `umtool window` and the @@ -70,6 +74,13 @@ import { removeWrongSpeaker, REMOVED_FILE, removePost, + importGroups, + labelGroup, + moveGroup, + orderEntries, + promoteGroup, + removeGroup, + setGroup, undoStructural, updateClip, updateTeaser, @@ -77,6 +88,8 @@ import { } from "./manifest.mjs"; import { REJECT_REASON_IDS, rejectionOf } from "./rejectReasons.mjs"; +import { groupModel, parseOrderText } from "./claimGroups.mjs"; +import { sectionModel } from "./sectionEdit.mjs"; export const TIMELINE_USAGE = [ "usage: umtool timeline <project> [ls] [--json] the cut: index, id, type, video, start–end, date title", @@ -114,6 +127,23 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start])", " [--move] [--quote Q] [--id ID] a tight copy of the span elsewhere, with the clip's attribution", " and locks, as repeatOf the clip (--move: the span leaves the clip, which keeps the rest)", + " umtool timeline <project> order <file|@file|id…> the cut's order in one write: the named entries take the", + " places the named entries hold, in that order (name them all for the whole order); every", + " clip keeps its section (an order across a boundary is refused); a JSON list, {order}, a", + " claim-groups file or ids by spaces, commas or lines; one undo point", + " umtool timeline <project> groups [ls] [--json] the claim groups, by section: id, claim, clips", + " umtool timeline <project> groups import <file> [--skip-missing] [--drop-empty] a claim-groups file", + " ({sections: [{label, groups: [{claim, ids}]}]}) in ONE write: the cut re-ordered to it, its", + " groups the cut's, the markers following; a file section is the deck section of its name, else", + " the one most of its clips are in; refused for an id the cut lacks (--skip-missing) or a section", + " left empty (--drop-empty removes its marker); `undo` puts the cut back", + " umtool timeline <project> groups set <gid|-> <id…> [--claim C] a group is these clips (already together, one", + " section); `-` a new g<n>. groups label <gid> <claim…> · groups remove <gid> (its clips stay)", + " umtool timeline <project> groups move <gid> --to <index>|--to after <gid> the whole group, its clips together,", + " to that place among the groups (before the group there, in its section) or after a group", + " umtool timeline <project> groups promote <gid> [--label L] the group opens a subsection: a level-2 marker at", + " its first clip titled with its claim (--label when it is over 24); the render sees only this", + " A clip moved out of its group's run leaves the group; moved alone into the middle of a run, it joins it", " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo]", " a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),", " each write with an undo point of the take's own; the project's manifest is untouched", @@ -123,8 +153,9 @@ export const TIMELINE_USAGE = [ ].join("\n"); const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"]; -const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward"]; -const VALUED = new Set(["--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level"]); +const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups"]; +const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"]; +const VALUED = new Set(["--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo"]; @@ -359,7 +390,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => const { words, flags } = splitTimelineArgs(args); const json = flags.has("--json"); try { - const [projectArg, verb = "ls", ...rest] = words; + const [projectArg, verb0 = "ls", ...rest] = words; + let verb = verb0; if (!projectArg || flags.has("--help")) { err(TIMELINE_USAGE); return 2; @@ -381,6 +413,16 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => return 0; } + if (verb === "groups" && (rest[0] ?? "ls") === "ls") { + const view = groupsView(manifest); + if (json) { + out(JSON.stringify({ project: project.id, token: await manifestToken(project.dir), ...view }, null, 2)); + return 0; + } + for (const line of groupLines(view)) out(line); + return 0; + } + if (verb === "ls") { const rows = timelineRows(manifest); if (json) { @@ -552,6 +594,68 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => ({ result, editNotes } = await write(async (token) => (await runClipEditorOp(project, { op: "split", clip: id, at: second, token })).result)); break; } + case "order": { + if (!rest.length) throw new CliError("order needs the ids in their new order, or a file of them (@file)"); + let text = rest.join(" "); + if (rest.length === 1) { + const f = rest[0].startsWith("@") ? rest[0].slice(1) : rest[0]; + const file = path.resolve(f); + const read = await readFile(file, "utf8").catch(() => null); + if (read !== null) text = read; + else if (rest[0].startsWith("@")) throw new CliError(`cannot read ${file}`); + } + let ids; + try { + ids = parseOrderText(text); + } catch (e) { + throw new CliError(`order: ${e instanceof Error ? e.message : e}`); + } + ({ result, editNotes } = await write((token) => orderEntries(project.dir, ids, { token }))); + break; + } + case "groups": { + const sub = rest[0]; + if (!GROUP_VERBS.includes(sub)) throw new CliError(`unknown: timeline groups ${sub} — ${GROUP_VERBS.join(", ")}`); + verb = `groups ${sub}`; + const args = rest.slice(1); + if (sub === "import") { + const file = need(args[0], "a claim-groups file ({sections: [{label, groups: [{claim, ids}]}]})"); + const doc = await jsonArg(file.startsWith("@") ? file : `@${file}`, "groups import"); + ({ result, editNotes } = await write((token) => importGroups(project.dir, doc, { skipMissing: flags.has("--skip-missing"), dropEmpty: flags.has("--drop-empty") }, { token }))); + } else if (sub === "set") { + const gid = need(args[0], "a group id (`-` for a new one)"); + const ids = args.slice(1); + if (!ids.length) throw new CliError("groups set needs the group's clips: groups set <gid|-> <id…> [--claim C]"); + const claim = typeof flags.get("--claim") === "string" ? String(flags.get("--claim")) : null; + ({ result, editNotes } = await write((token) => setGroup(project.dir, gid === "-" ? null : gid, ids, { claim }, { token }))); + } else if (sub === "move") { + const gid = need(args[0], "a group id (`groups ls` lists them)"); + const to = flags.get("--to"); + const afterGid = to === "after" ? args[1] : typeof flags.get("--after") === "string" ? String(flags.get("--after")) : null; + if (to === "after" && !afterGid) throw new CliError("groups move <gid> --to after <gid>: name the group it goes after"); + let where; + if (afterGid) where = { after: afterGid }; + else { + const n = Number(to); + if (typeof to !== "string" || to === "" || !Number.isInteger(n)) throw new CliError("groups move needs --to <index> (its place among the groups after the move) or --to after <gid>"); + where = { to: n }; + } + ({ result, editNotes } = await write((token) => moveGroup(project.dir, gid, where, { token }))); + } else if (sub === "label") { + const gid = need(args[0], "a group id"); + const claim = args.slice(1).join(" ") || (typeof flags.get("--claim") === "string" ? String(flags.get("--claim")) : ""); + if (!claim.trim()) throw new CliError("groups label <gid> <claim…>: the claim, in words"); + ({ result, editNotes } = await write((token) => labelGroup(project.dir, gid, claim, { token }))); + } else if (sub === "promote") { + const gid = need(args[0], "a group id"); + const label = typeof flags.get("--label") === "string" ? String(flags.get("--label")) : null; + ({ result, editNotes } = await write((token) => promoteGroup(project.dir, gid, { label }, { token }))); + } else if (sub === "remove") { + const gid = need(args[0], "a group id"); + ({ result, editNotes } = await write((token) => removeGroup(project.dir, gid, { token }))); + } + break; + } case "flash-forward": { const id = need(rest[0], "a clip id"); const span = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(need(rest[1], "the span: <from>-<to> in source seconds")); @@ -581,6 +685,9 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } out(summaryOf(verb, result, attribution)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); + // The claim groups following the edit (claimGroups.mjs syncGroups), and an import's words. + for (const line of result.groupNotes ?? []) out(` groups: ${line}`); + for (const line of result.notes ?? []) out(` ${line}`); // The take patches beside the manifest follow the same removal (patchMarkers.mjs). for (const p of result.patches ?? []) { for (const line of p.notes ?? []) out(` ${p.file}: ${line}`); @@ -668,8 +775,57 @@ export function sectionLines(sections) { }); } +/** + * The groups as `groups ls` shows them: by section, each group's id, claim and + * clips, and the clips no group holds. + * + * @param {Record<string, any>} manifest + */ +export function groupsView(manifest) { + const model = sectionModel(manifest); + const groups = groupModel(manifest); + const grouped = new Set(groups.flatMap((g) => g.ids)); + const sections = model.sections.map((s) => ({ + index: s.index, + label: s.label, + ...(s.level === 2 ? { level: 2, within: s.within ?? null } : {}), + groups: groups.filter((g) => g.section === s.index).map((g) => ({ id: g.id, claim: g.claim, ids: g.ids, ...(g.promoted ? { promoted: true } : {}) })), + ungrouped: s.clips.filter((id) => !grouped.has(id)), + })); + return { groups: groups.length, hasGroups: Array.isArray(manifest?.groups), sections }; +} + +/** `groups ls`, as lines. */ +export function groupLines(view) { + if (!view.hasGroups) return ["no claim groups yet — `groups import <file>` or `groups set - <id…> --claim C`"]; + const lines = []; + for (const s of view.sections) { + if (!s.groups.length && !s.ungrouped.length) continue; + lines.push(`§${s.index} ${s.level === 2 ? "› " : ""}${s.label ?? (s.index === 0 ? "(the opening)" : "(no label)")}`); + for (const g of s.groups) lines.push(` ${g.id.padEnd(4)} ${g.promoted ? "▸ " : ""}${g.claim} [${g.ids.join(" ")}]`); + if (s.ungrouped.length) lines.push(` ungrouped: ${s.ungrouped.join(" ")}`); + } + lines.push(`${view.groups} group${view.groups === 1 ? "" : "s"}`); + return lines; +} + function summaryOf(verb, r, attribution) { switch (verb) { + case "order": + return `ordered ${r.count} of ${r.of} entries`; + case "groups import": + return `imported ${r.groups} group${r.groups === 1 ? "" : "s"}${r.replaced ? ` (replacing ${r.replaced})` : ""}${r.moved ? ", the cut re-ordered to the file" : ", the order unchanged"}` + + r.sections.map((s) => `\n ${s.label ?? "(no label)"} → §${s.section} (${s.groups} group${s.groups === 1 ? "" : "s"})`).join(""); + case "groups set": + return `${r.created ? "new group" : "group"} ${r.id}: ${r.ids.join(" ")} — ${r.claim}`; + case "groups label": + return `group ${r.id}: ${r.claim}`; + case "groups remove": + return `ungrouped ${r.id} (${r.removed.ids.join(" ")} stay where they are)`; + case "groups move": + return `moved group ${r.id} (${r.ids.join(" ")}) ${r.words}${r.section !== null && r.section !== undefined ? ` in §${r.section}` : ""}`; + case "groups promote": + return `group ${r.id} opens a subsection of ${r.within}: marker ${r.marker} after ${r.after}, "${r.label}" (it opens on ${r.opens})`; case "section-move": return `moved ${r.ids.join(", ")} to the ${r.position} of §${r.section}${r.label ? ` (${r.label})` : ""}`; case "section-add":