Archilyzer · Source

archilyzer

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

commit bf1353e556bb0f3770f65e95635cdb5e165aa45b
parent fde9a111c8a718f0b886d59c643abd54197ebef2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 12:04:12 -0400

umtool: /api/report/clips takes the worker token and mode "new" -- the editor's Find clips as one call

POST {mode: "new", slug, from, target?, scope? ("auto" default | "all" |
[from, to]), segment?, wordsPath?} (lib/report/clipsNew.mjs): a reactions
project for the same recording whose scope covers the chosen segment is
analyzed again as it is (created: false); else `slug` is scaffolded with
the reactions seed and the words copied in (created: true); then `clips
analyze` as one job -> {jobId, job, project, created, segments, segment,
scope, href, notes}. No Authorization header is the page (as before),
Bearer WORKER_TOKEN the editor, any other a 401 (agentAuth routeCaller).
GET ?project= also carries segments, segment and the chat's lag.

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

Diffstat:
Mcommon/lib/clips/reactions.d.mts | 8+++++++-
Mumtool/app/api/report/clips/route.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/e2e/create.spec.ts | 30++++++++++++++++++++++++++++++
Mumtool/lib/annotations/agentAuth.mjs | 16++++++++++++++++
Aumtool/lib/report/clipsNew.mjs | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/reactions-r36.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 363 insertions(+), 4 deletions(-)

diff --git a/common/lib/clips/reactions.d.mts b/common/lib/clips/reactions.d.mts @@ -1,4 +1,5 @@ -import type { Laugh, Moment, Params, Role, Speaker, Turn } from "./clips.mjs"; +import type { Laugh, Moment, Params, ReactionsChat, Role, Speaker, Turn } from "./clips.mjs"; +import type { Segment } from "./segments.mjs"; export const REACTIONS_FILE: string; export const REACTIONS_VERSION: 1; @@ -35,6 +36,11 @@ export type ReactionsDoc = { rolesChangedAt?: string; laughSource?: "model" | "text" | "text+energy"; scans?: Record<string, unknown>; + /** Release 36: the narrated-video spans auto-scope found, and which one the scope is (null: a scope by hand, or none). */ + segments?: Segment[]; + segment?: string | null; + /** Release 36: the chat replay's signal, or null when there is none. */ + chat?: ReactionsChat | null; }; export function reactionsFileOf(dir: string): string; diff --git a/umtool/app/api/report/clips/route.ts b/umtool/app/api/report/clips/route.ts @@ -1,5 +1,8 @@ import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; -import { projectRef } from "@/lib/projects"; +import { invalidateProjects, projectRef } from "@/lib/projects"; +import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs"; +import { ClipsNewError, planClipsNew } from "@/lib/report/clipsNew.mjs"; +import { clipEditorHref } from "@/lib/hrefs"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { clipsSteps } from "@/lib/report/reactions.mjs"; @@ -16,8 +19,14 @@ export const dynamic = "force-dynamic"; // // GET ?job=<id>[&since=&sinceEvent=] that job // GET ?project=<id> the project's reactions.json summary, and the job running, if any -// POST { project, mode?: "analyze" | "propose", from?: "<channel>/<id>", target?: seconds, host?: speaker } +// POST { project, mode?: "analyze" | "propose", from?: "<channel>/<id>", target?: seconds, host?: speaker, +// scope?: [from, to] | "auto" | "all", segment?: "s1" } → { jobId, job } +// POST { mode: "new", slug, from: "<channel>/<id>", target?, scope?: "auto" (default) | "all" | [from, to], +// segment?, wordsPath? } (release 36: the editor's Find clips) → { jobId, job, project, created, segments, +// segment, scope, href, notes } — a reactions project for the same recording whose scope covers the +// chosen one is analyzed again (`created: false`), else `slug` is scaffolded (lib/report/clipsNew.mjs) // ?cancel=<job> stop it +// A POST with no Authorization header is the app's page; `Bearer <WORKER_TOKEN>` the editor; any other: 401. export async function GET(request: Request) { const url = new URL(request.url); const headers = { "cache-control": "no-store" }; @@ -46,6 +55,9 @@ export async function GET(request: Request) { usedSeconds: Math.round(used.reduce((n, p) => n + (p.end - p.start), 0)), proposedAt: doc.proposedAt ?? null, rolesChangedAt: doc.rolesChangedAt ?? null, + segments: Array.isArray(doc.segments) ? doc.segments : null, + segment: doc.segment ?? null, + chat: doc.chat ? { source: doc.chat.source, lagS: doc.chat.lagS, lag: doc.chat.lag ?? null, messages: doc.chat.messages ?? null, bursts: doc.chat.bursts ?? null } : null, } : null, running: running && running.project === project.id && running.kind.startsWith("clips-") ? jobView(running) : null, @@ -56,6 +68,8 @@ export async function GET(request: Request) { export async function POST(request: Request) { const url = new URL(request.url); + const who = routeCaller(request.headers.get("authorization"), agentToken(), "/api/report/clips"); + if (!who.ok) return Response.json({ error: who.error }, { status: who.status }); const cancel = url.searchParams.get("cancel"); if (cancel) { const { cancelJob } = await import("@/lib/jobs"); @@ -63,6 +77,7 @@ export async function POST(request: Request) { } 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 }); + if (body.mode === "new") return startNew(body); const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); if (!kindMakesTakes(project.kind)) return Response.json({ error: "clips are found for a report video" }, { status: 400 }); @@ -75,11 +90,49 @@ export async function POST(request: Request) { ...(typeof body.from === "string" ? { from: body.from } : {}), ...(typeof body.target === "number" ? { target: body.target } : {}), ...(typeof body.host === "number" ? { host: body.host } : {}), + ...(Array.isArray(body.scope) || body.scope === "auto" || body.scope === "all" ? { scope: body.scope as [number, number | null] | "auto" | "all" } : {}), + ...(typeof body.segment === "string" ? { segment: body.segment } : {}), }); try { const job = startJob(plan.kind, plan.steps, { project: project.id }); - return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + return Response.json({ ok: true, jobId: job.id, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); } } + +/** `mode: "new"`: the project found or scaffolded, then `clips analyze` as one job. */ +async function startNew(body: Record<string, unknown>) { + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + let r: Awaited<ReturnType<typeof planClipsNew>>; + try { + r = await planClipsNew(body); + } catch (e) { + const status = e instanceof ClipsNewError ? e.status : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); + } + invalidateProjects(); + try { + const job = startJob(r.plan.kind, r.plan.steps, { project: r.project.id }); + return Response.json( + { + ok: true, + jobId: job.id, + job: jobView(job), + project: r.project.id, + created: r.created, + segments: r.segments, + segment: r.segment, + scope: r.scope, + href: clipEditorHref(r.project.id), + notes: r.notes, + }, + { headers: { "cache-control": "no-store" } }, + ); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e), project: r.project.id, created: r.created }, { status: 409 }); + } +} diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts @@ -48,6 +48,9 @@ const WRITTEN = [ "reports/videos/p5-song", "channels/synth-reacts", "p35-hl", + "channels/synth-two", + "p36-find", + "p36-find-again", ]; const clean = () => { for (const p of WRITTEN) rmSync(path.join(FIXTURE, p), { recursive: true, force: true }); @@ -261,6 +264,33 @@ test("Highlights from a recording: the clip finder proposes clips marked by the expect(summary.laughSource).toBe("text"); }); +test("Find clips from the editor (release 36): mode new with the worker token scaffolds the segment's project and analyzes it; asked again, the same project; a wrong token is refused", async ({ request }) => { + // A synthetic stream that reacts to two narrated videos, with its chat replay; no sound. + writeReactionCorpus(path.join(FIXTURE, "channels"), { channel: "synth-two", video: "two001", two: true, chat: true }); + const ask = (data: Record<string, unknown>, token = "umtool-e2e-token") => + request.post("/api/report/clips", { headers: { authorization: `Bearer ${token}` }, data }); + const wrong = await ask({ mode: "new", slug: "p36-find", from: "synth-two/two001" }, "not-the-token"); + expect(wrong.status()).toBe(401); + expect(existsSync(path.join(FIXTURE, "p36-find"))).toBe(false); + const r = await ask({ mode: "new", slug: "p36-find", from: "synth-two/two001", scope: "auto", segment: "s2", target: 120 }); + expect(r.ok()).toBe(true); + const made = await r.json(); + expect(made).toMatchObject({ project: "p36-find", created: true, segment: "s2", scope: [1500, 2390], href: "/projects/p36-find/clips" }); + expect(made.segments.map((s: { id: string }) => s.id)).toEqual(["s1", "s2"]); + const done = async (id: string) => (await (await request.get(`/api/report/clips?job=${id}`)).json()).state; + await expect.poll(() => done(made.jobId), { timeout: 60_000 }).toBe("done"); + const summary = (await (await request.get("/api/report/clips?project=p36-find")).json()).reactions; + expect(summary.segment).toBe("s2"); + expect(summary.segments.length).toBe(2); + expect(summary.chat.lagS).toBe(6); + expect(summary.used).toBeGreaterThan(0); + // Asked again for the same video's s2: that project, analyzed again (not a second one). + const again = await (await ask({ mode: "new", slug: "p36-find-again", from: "synth-two/two001", segment: "s2" })).json(); + expect(again).toMatchObject({ project: "p36-find", created: false }); + await expect.poll(() => done(again.jobId), { timeout: 60_000 }).toBe("done"); + expect(existsSync(path.join(FIXTURE, "p36-find-again"))).toBe(false); +}); + test("Video from a sweep report: the reports on disk are offered, and one becomes a project", async ({ page }) => { await page.goto(urls.createHref({ make: "video-report" })); const f = form(page, "video-report"); diff --git a/umtool/lib/annotations/agentAuth.mjs b/umtool/lib/annotations/agentAuth.mjs @@ -130,6 +130,22 @@ export function noteWriter(authorization, token) { } /** + * Who is calling an editor-facing route (release 36: /api/report/clips): the + * same rule as noteWriter. No Authorization header is the app's own page (as + * before); `Bearer <umtool's WORKER_TOKEN>` is the editor (or an agent); any + * other header is a 401. + * @param {string | null | undefined} authorization + * @param {string} token umtool's WORKER_TOKEN ("" for none) + * @param {string} [what] the route, for the refusal + * @returns {{ ok: true, by: "page" | "worker" } | { ok: false, status: 401, error: string }} + */ +export function routeCaller(authorization, token, what = "this route") { + const w = noteWriter(authorization, token); + if (w.ok) return { ok: true, by: w.by === "agent" ? "worker" : "page" }; + return { ok: false, status: 401, error: w.error.replace(/^notes:/, `${what}:`).replace("no agent can write here", "no editor can call it") }; +} + +/** * The POST: one op on a target's notes, by whoever the header proves. A refusal * is `{ status, body: { error } }`; a write `{ status: 200, body }` with what * writeNote returns. A stale token or a refused op THROWS (the route's diff --git a/umtool/lib/report/clipsNew.mjs b/umtool/lib/report/clipsNew.mjs @@ -0,0 +1,195 @@ +// "Find clips" from the editor (release 36 B5): `POST /api/report/clips +// {mode: "new", slug, from: "<channel>/<id>", target?, scope?, segment?, +// wordsPath?}` — a recording to a clip-finder project and its analysis, as +// ONE call. The editor's find-clips job (release 36 lane A) makes the words, +// the chat and the speakers first, then asks this. +// +// the scope "auto" (the default) is the narrated video auto-scope finds +// (lib/clips/segments.mjs): `segment` names one, else the +// longest; `[from, to]` is a scope by hand; "all" the whole +// a project already made for the same recording whose scope covers the +// chosen one (scopeOverlapsSegment) is analyzed AGAIN, as it +// is — its scope, its params, every clip the operator touched, +// ruled or locked kept (the proposal pass's rules) → +// `created: false`; else a new project `slug` is scaffolded +// with the reactions seed → `created: true` +// the words `wordsPath` (an absolute path to a words file, `{words: +// [{w, start, end}]}` as `pnpm ops transcribe {words: true, +// out}` writes) is copied in as <project>/words.json — into +// an existing project only when it has none +// the job `clips analyze` (the laugh scan, the voices, then a +// proposal pass), one step on the app's runner +// +// Plain ESM: the route calls it, and its tests run with bare node. +import { copyFile, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { PARAM_BOUNDS, cleanWords, normalizeScope } from "yt-dlp-transcript-common/lib/clips/clips.mjs"; +import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { pickSegment, scopeOverlapsSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs"; +import { REPORTS_ROOT } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { GLOBAL_CHANNELS_DIR } from "../projects/report.mjs"; +import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs"; +import { walkProjects } from "../projects/walk.mjs"; +import { ClipsError, WORDS_FILE, clipsSteps, loadRecording, recordingSegments } from "./reactions.mjs"; + +/** A refusal with the HTTP status the route answers. */ +export class ClipsNewError extends ClipsError { + /** @param {string} message @param {number} [status] */ + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +const WORDS_MAX_BYTES = 256 * 1024 * 1024; + +/** The request's fields, checked. */ +export function parseNewBody(body) { + const b = body && typeof body === "object" ? body : {}; + const slug = String(b.slug ?? "").trim().toLowerCase(); + if (!SLUG_RE.test(slug)) throw new ClipsNewError(`slug "${b.slug ?? ""}": lower-case letters, digits and dashes`); + const m = /^([^/]+)\/([^/]+)$/.exec(String(b.from ?? "")); + if (!m || !CHANNEL_SLUG_RE.test(m[1]) || !CHANNEL_SLUG_RE.test(m[2])) throw new ClipsNewError(`from "${b.from ?? ""}": <channel>/<videoId>`); + let target; + if (b.target !== undefined && b.target !== null && b.target !== "") { + target = Number(b.target); + const [lo, hi] = PARAM_BOUNDS.target; + if (!Number.isFinite(target) || target < lo || target > hi) throw new ClipsNewError(`target must be ${lo}..${hi} seconds`); + } + /** @type {"auto" | "all" | [number, number | null]} */ + let scope = "auto"; + if (b.scope === "all") scope = "all"; + else if (Array.isArray(b.scope)) { + try { + scope = normalizeScope(b.scope) ?? "all"; + } catch (e) { + throw new ClipsNewError(e instanceof Error ? e.message : String(e)); + } + } else if (b.scope !== undefined && b.scope !== null && b.scope !== "auto") throw new ClipsNewError(`scope: "auto", "all" or [from, to]`); + const segment = typeof b.segment === "string" && b.segment ? b.segment : null; + if (segment && !/^s\d+$/.test(segment)) throw new ClipsNewError(`segment "${segment}": s1, s2, …`); + if (segment && scope !== "auto") throw new ClipsNewError("segment goes with scope \"auto\""); + const wordsPath = typeof b.wordsPath === "string" && b.wordsPath ? b.wordsPath : null; + if (wordsPath && !path.isAbsolute(wordsPath)) throw new ClipsNewError("wordsPath must be an absolute path"); + return { slug, channel: m[1], video: m[2], target, scope, segment, wordsPath }; +} + +/** The words file, checked: a regular file holding words. */ +async function checkWords(file) { + const s = await stat(file).catch(() => null); + if (!s || !s.isFile()) throw new ClipsNewError(`wordsPath ${file}: no such file`, 404); + if (s.size > WORDS_MAX_BYTES) throw new ClipsNewError(`wordsPath ${file}: too large`); + let doc; + try { + doc = JSON.parse(await readFile(file, "utf8")); + } catch { + throw new ClipsNewError(`wordsPath ${file}: not JSON`); + } + const list = Array.isArray(doc) ? doc : Array.isArray(doc?.words) ? doc.words : null; + if (!list || !cleanWords(list).length) throw new ClipsNewError(`wordsPath ${file} holds no words ({ words: [{ w, start, end }] })`); +} + +/** + * The reactions projects already made for this recording whose scope covers + * `span` — the best cover first (the most overlap, then the latest pass). + */ +export async function projectsCovering({ reportsRoot, channel, video, span, duration }) { + const out = []; + for (const p of await walkProjects(reportsRoot)) { + if (!kindMakesTakes(p.kind)) continue; + const doc = await readReactions(p.dir); + if (!doc || doc.source?.channel !== channel || doc.source?.video !== video) continue; + const scope = doc.params?.scope ?? null; + if (!scopeOverlapsSegment(scope, span, duration)) continue; + const a = Array.isArray(scope) ? scope[0] : 0; + const b = Array.isArray(scope) && scope[1] !== null ? scope[1] : duration; + out.push({ project: p, overlap: Math.max(0, Math.min(b, span.to) - Math.max(a, span.from)), at: String(doc.proposedAt ?? "") }); + } + return out.sort((x, y) => y.overlap - x.overlap || (y.at > x.at ? 1 : y.at < x.at ? -1 : 0)).map((x) => x.project); +} + +/** + * Plan a `mode: "new"` request: the project (found or scaffolded), the job's + * steps, and what the editor is told. Scaffolds and copies the words; does + * not start the job (the route does, on lib/jobs.ts). + * @param {unknown} body + * @param {{ reportsRoot?: string, channelsDir?: string, sitesDir?: string }} [o] + */ +export async function planClipsNew(body, { reportsRoot = REPORTS_ROOT, channelsDir = GLOBAL_CHANNELS_DIR(), sitesDir = undefined } = {}) { + const req = parseNewBody(body); + let rec; + try { + rec = await loadRecording({ channelsDir, channel: req.channel, video: req.video }); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + throw new ClipsNewError(msg, /no video directory/.test(msg) ? 404 : 400); + } + const segments = recordingSegments(rec); + let span; + let segment = null; + if (req.scope === "auto") { + try { + segment = pickSegment(segments, req.segment); + } catch (e) { + throw new ClipsNewError(e instanceof Error ? e.message : String(e)); + } + span = segment ? { from: segment.from, to: segment.to } : { from: 0, to: rec.duration }; + } else if (req.scope === "all") span = { from: 0, to: rec.duration }; + else span = { from: req.scope[0], to: req.scope[1] ?? rec.duration }; + + const [existing] = await projectsCovering({ reportsRoot, channel: req.channel, video: req.video, span, duration: rec.duration }); + const notes = []; + let project; + let created; + if (existing) { + project = { id: existing.id, dir: existing.dir, kind: existing.kind }; + created = false; + notes.push(`${existing.id} already reads this part of ${req.channel}/${req.video}: analyzed again, its scope and the clips you touched kept`); + if (req.wordsPath) { + if (await stat(path.join(project.dir, WORDS_FILE)).then(() => true, () => false)) notes.push(`${WORDS_FILE} kept (the project has one)`); + else { + await checkWords(req.wordsPath); + await copyFile(req.wordsPath, path.join(project.dir, WORDS_FILE)); + notes.push(`${WORDS_FILE} copied in`); + } + } + } else { + if (req.wordsPath) await checkWords(req.wordsPath); + let r; + try { + r = await scaffoldReportVideo({ + root: reportsRoot, + slug: req.slug, + from: `${req.channel}/${req.video}`, + seed: "reactions", + channelsDir, + ...(sitesDir ? { sitesDir } : {}), + ...(req.target !== undefined ? { target: req.target } : {}), + ...(req.scope === "auto" ? { scope: "auto", ...(req.segment ? { segment: req.segment } : {}) } : req.scope === "all" ? {} : { scope: req.scope }), + }); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + throw new ClipsNewError(msg, /already exists/.test(msg) ? 409 : 400); + } + project = { id: r.id, dir: r.dir, kind: "report-video" }; + created = true; + notes.push(...r.notes); + if (req.wordsPath) { + await copyFile(req.wordsPath, path.join(r.dir, WORDS_FILE)); + notes.push(`${WORDS_FILE} copied in`); + } + } + const doc = await readReactions(project.dir); + const plan = clipsSteps(project, { mode: "analyze" }); + return { + project, + created, + segments, + // The segment chosen (auto-scope's); an existing project keeps its own scope. + segment: segment?.id ?? doc?.segment ?? null, + scope: doc?.params?.scope ?? null, + plan, + notes, + }; +} diff --git a/umtool/lib/report/reactions-r36.test.mjs b/umtool/lib/report/reactions-r36.test.mjs @@ -142,3 +142,62 @@ test("clips analyze with a chat replay: the lag cross-correlated with the laugh await rm(f.root, { recursive: true, force: true }); } }); + +test("mode new (the editor's Find clips): a project scaffolded for the chosen segment with the words copied in; asked again, the same project analyzed again", async () => { + const f = await fixture({ chat: true }); + const { planClipsNew, parseNewBody } = await import("./clipsNew.mjs"); + try { + const wordsPath = path.join(f.root, "words-out.json"); + const { twoVideoStream } = await import("yt-dlp-transcript-common/testing/clips/reactionStream.mjs"); + await writeFile(wordsPath, JSON.stringify({ path: "/x", words: twoVideoStream().words })); + const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir }; + const a = await planClipsNew({ mode: "new", slug: "find-b", from: "synth-reacts/react001", scope: "auto", segment: "s2", wordsPath, target: 120 }, opts); + assert.equal(a.created, true); + assert.equal(a.project.id, "find-b"); + assert.equal(a.segment, "s2"); + assert.deepEqual(a.scope, [1500, 2390]); + assert.deepEqual(a.segments.map((g) => g.id), ["s1", "s2"]); + assert.deepEqual(JSON.parse(await readFile(path.join(a.dir ?? a.project.dir, "words.json"), "utf8")).words.length, twoVideoStream().words.length); + assert.equal(a.plan.kind, "clips-analyze find-b"); + assert.deepEqual(a.plan.steps[0].argv.slice(5, 8), ["clips", "analyze", "find-b"]); + const doc = await readReactions(a.project.dir); + assert.ok(doc.chat, "the chat replay read"); + + // An operator's clip in it; then the editor asks again for the same video's s2: the SAME project, as it is. + const mf = path.join(a.project.dir, "video.manifest.json"); + const m = JSON.parse(await readFile(mf, "utf8")); + m.timeline[0].assist.by = "operator"; + await writeFile(mf, JSON.stringify(m, null, 2)); + const again = await planClipsNew({ mode: "new", slug: "find-b-2", from: "synth-reacts/react001", segment: "s2", wordsPath }, opts); + assert.equal(again.created, false); + assert.equal(again.project.id, "find-b"); + assert.ok(again.notes.some((n) => /words\.json kept/.test(n))); + assert.equal(JSON.parse(await readFile(mf, "utf8")).timeline[0].assist.by, "operator"); + // The other video is a new project; the default scope is auto (the longest: s1). + const b = await planClipsNew({ mode: "new", slug: "find-a", from: "synth-reacts/react001" }, opts); + assert.deepEqual([b.created, b.segment, b.scope], [true, "s1", [120, 1347]]); + // A slug already taken by another recording's project: 409. Refusals: 400 / 404. + await assert.rejects(planClipsNew({ mode: "new", slug: "find-a", from: "synth-reacts/react001", scope: [0, 60] }, opts), (e) => e.status === 409); + await assert.rejects(planClipsNew({ mode: "new", slug: "zz", from: "synth-reacts/nope" }, opts), (e) => e.status === 404); + await assert.rejects(planClipsNew({ mode: "new", slug: "zz", from: "synth-reacts/react001", segment: "s7" }, opts), (e) => e.status === 400 && /no segment s7/.test(e.message)); + assert.throws(() => parseNewBody({ slug: "Bad Slug", from: "a/b" }), /slug/); + assert.throws(() => parseNewBody({ slug: "ok", from: "../b" }), /from/); + assert.throws(() => parseNewBody({ slug: "ok", from: "a/b", wordsPath: "rel/words.json" }), /absolute/); + assert.throws(() => parseNewBody({ slug: "ok", from: "a/b", scope: [0, 10], segment: "s1" }), /segment goes with scope "auto"/); + assert.deepEqual(parseNewBody({ slug: "ok", from: "a/b", scope: [0, 10] }).scope, [0, 10]); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("the route's caller: no header is the page, umtool's WORKER_TOKEN the editor, anything else a 401", async () => { + const { routeCaller } = await import("../annotations/agentAuth.mjs"); + assert.deepEqual(routeCaller(null, "tok"), { ok: true, by: "page" }); + assert.deepEqual(routeCaller("Bearer tok", "tok"), { ok: true, by: "worker" }); + const wrong = routeCaller("Bearer nope", "tok", "/api/report/clips"); + assert.equal(wrong.ok, false); + assert.equal(wrong.status, 401); + assert.match(wrong.error, /^\/api\/report\/clips: that bearer token is not umtool's WORKER_TOKEN/); + assert.match(routeCaller("Bearer tok", "", "/api/report/clips").error, /holds no WORKER_TOKEN, so no editor can call it/); + assert.equal(routeCaller("Basic x", "tok").ok, false); +});