// 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"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.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 = tmpPathFor(file); 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, * 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 }; }