commit c7345edfba0e02537a2440e921e417eb6509b6db
parent 0b7c6e9ac09942b501f788a4e5410db39bd46152
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 00:26:35 -0500
umtool: claim-group proposals on the Cut tab (lane L4) -- Propose groups (words for the ask optional) starts the editor's `propose-groups` job through the shared WORKER_TOKEN and follows it (.propose-groups-job.json; disabled with the reason when routed to Claude Code or no editor answers); each proposal a row -- its section, claim, clips, why, whether the cut still takes it -- with Accept and Reject, never applied without a press. Accept checks it again against the cut as it is (a clip grouped since is never taken from its group: marked failed with the reason), then writes ONE group through setGroup (an undo point, validateGroups), marks the proposal accepted with the group's id and announces the manifest change so its bar appears; Reject marks it and writes nothing (lib/report/groupProposals.mjs, /api/report/group-proposals, GroupProposalsPanel.tsx). The editor stub answers a propose-groups report-draft through common's checker and writer (each section's first two clips, one group across the first boundary, refused); e2e/group-proposals.spec.ts on reports/group-proposals-fixture; the generation chip names "claim groups for a cut" (create and settings specs)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 745 insertions(+), 7 deletions(-)
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/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -21,6 +21,7 @@ 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";
@@ -457,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/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/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/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 });
+});