Archilyzer · Source

archilyzer

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

commit 67cec86206475d0225b34ac94846786e70f02f52
parent 796b4c59cb30b8f8b826a48cd876e95d9b65bb31
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 23:42:03 -0400

umtool: stand-ins for refused montage windows -- `umtool fallback` and Use stand-in / Restore on the clip deck (release 35 O1, slice 4)

A montage clip whose window a recorded fetch run says the editor refused
(a failed window in the job's log -- not a rate limit, our drive or our cut --
or the editor's unresolved) and is still not on disk is switched to its
phrase-scan instance's first public alternate: YouTube, then Odysee /
cornbreadman, then the rest; never a recording refused itself. On the clip:
the alternate's channel, video and cut, the clip's own margins, note "from the
YouTube upload: the Rumble copy refused (403)", and fallbackFrom with every
field it replaced -- Restore puts them back, key order and all. The write is
replaceManifest (lock, auto snapshot for Undo, atomic); the montage ruling
(moveMontageRuling, the rulings' one writer) and the voice-match row move to
the new moment key and back. An older phrase-scan.json with no alternates is
scanned again over its own settings through the cue-text cache.
The clip deck's head is now MontageFetchTools: Fetch windows, then the
stand-ins it offers once the jobs end. The e2e stub gains the fetch-windows
door (editor-stub-fetch-windows.mjs: a vrefuse* id is the 403) and
montage-ops.spec.ts walks dry run -> start -> refused -> Use stand-in ->
fetch again -> Restore.

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

Diffstat:
Aumtool/app/api/report/stand-ins/route.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 4++++
Mumtool/components/projects/ClipDeckPage.tsx | 6+++---
Aumtool/components/projects/report/MontageFetchTools.tsx | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/editor-stub-fetch-windows.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 16++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/montage-ops-fixture.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/montage-ops.spec.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/montageRulings.mjs | 23+++++++++++++++++++++++
Aumtool/lib/report/standIns.mjs | 310+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/standIns.test.mjs | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/standInsCli.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 1029 insertions(+), 3 deletions(-)

diff --git a/umtool/app/api/report/stand-ins/route.ts b/umtool/app/api/report/stand-ins/route.ts @@ -0,0 +1,44 @@ +import { projectRef } from "@/lib/projects"; +import { editorConfig } from "@/lib/report/fetchWindows.mjs"; +import { applyStandIns, restoreStandIn, standInPlan } from "@/lib/report/standIns.mjs"; + +export const dynamic = "force-dynamic"; + +// STAND-INS (release 35 O1): the clip deck's "Use stand-in" and "Restore", and +// `umtool fallback` from a terminal (lib/report/standIns.mjs for both). A +// montage clip whose window the editor refused (fetch-runs.json) and is not on +// disk is switched to its instance's first public alternate — on the clip +// (`fallbackFrom`), its ruling and voice-match row moved with it — and back. +// +// GET ?project=<id> the candidates, the switched, the refused with none +// POST { project, clips?: [id…] } switch them (every candidate when none are named) +// POST { project, restore: <clipId> } put one back as it was +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + try { + return Response.json(await standInPlan(project, { cfg: editorConfig() }), { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); + } +} + +export async function POST(request: Request) { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + try { + if (typeof b.restore === "string" && b.restore) { + return Response.json({ restored: await restoreStandIn(project, b.restore) }, { headers }); + } + const clips = Array.isArray(b.clips) ? b.clips.map(String) : null; + const res = await applyStandIns(project, { clips, cfg: editorConfig() }); + return Response.json({ switched: res.switched, none: res.plan.none }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -54,6 +54,7 @@ // the clip deck's montage rulings (release 34) // umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of // the editor as one fetch-windows batch (release 35) +// umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] stand-ins for refused windows // umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] // [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass) // umtool voice-match <project> [--reference auto|rulings|recordings] [--instances F] [--dry] [--json] @@ -732,6 +733,8 @@ function usage() { " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]", " the clip windows asked of the editor as one fetch-windows batch (one paced job per platform);", " each run recorded in <project>/fetch-runs.json", + " umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] [--json]", + " stand-ins for refused montage windows: the instance's public alternate (YouTube first), on the clip", " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]", " how often each phrase was said, by year, in one pass (the phrase finder's search)", " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]", @@ -776,6 +779,7 @@ const COMMANDS = { rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), // Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs. fetch: async () => process.exit(await (await import("../lib/report/fetchCli.mjs")).fetchCommand(argv.slice(argv.indexOf("fetch") + 1))), + fallback: async () => process.exit(await (await import("../lib/report/standInsCli.mjs")).fallbackCommand(argv.slice(argv.indexOf("fallback") + 1))), // The phrase finder (release 34): lib/phrase-finder/cli.mjs. phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))), // Who is speaking, per montage clip (release 34): lib/report/voiceMatch.mjs. diff --git a/umtool/components/projects/ClipDeckPage.tsx b/umtool/components/projects/ClipDeckPage.tsx @@ -6,7 +6,7 @@ import type { ProjectRef } from "@/lib/project-types"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import ClipDeck from "./review/ClipDeck"; import VoiceMatchPanel from "./report/VoiceMatchPanel"; -import FetchWindowsPanel from "./report/FetchWindowsPanel"; +import MontageFetchTools from "./report/MontageFetchTools"; import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; @@ -41,7 +41,7 @@ export default async function ClipDeckPage({ project, show }: { project: Project : view.cards.every((c) => view.rulings[c.key]) ? "all" : "unruled"; - // Fetch windows (release 35): every kept clip's window, asked of the editor. + // Fetch windows and the stand-ins for refused windows (release 35). const fetchBody = await projectFetchBody(project) .then(async ({ body, skipped }) => ({ items: body.items.length, skipped: skipped.length, lastRun: lastStartedRun(await readFetchRuns(project.dir)) })) .catch(() => null); @@ -54,7 +54,7 @@ export default async function ClipDeckPage({ project, show }: { project: Project back={back} takesHref={takesHref(project.id)} voicePanel={<VoiceMatchPanel project={project.id} summary={voiceMatchSummary(await readVoiceMatch(project.dir))} reload />} - fetchPanel={fetchBody ? <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} /> : null} + fetchPanel={fetchBody ? <MontageFetchTools project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} /> : null} /> </BenchFrame> ); diff --git a/umtool/components/projects/report/MontageFetchTools.tsx b/umtool/components/projects/report/MontageFetchTools.tsx @@ -0,0 +1,109 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import FetchWindowsPanel from "./FetchWindowsPanel"; + +// --------------------------------------------------------------------------- +// The clip deck's fetch tools (release 35 O1): "Fetch windows", and under it +// the STAND-INS — every montage clip whose window the editor refused (a Rumble +// embed lookup answering 403 on every try, a recording gone) and is not on +// disk, offered its instance's first public alternate (YouTube first). "Use +// stand-in" switches the clip (recorded on it, its ruling and voice score moved +// with it); "Restore" puts it back. Then Fetch windows again asks for the new +// windows. lib/report/standIns.mjs; `umtool fallback` is the same from a terminal. +// --------------------------------------------------------------------------- + +type Alt = { slug: string; videoId: string; start: number; platform: string | null }; +type Plan = { + candidates: { clipId: string; channel: string; video: string; refusal: { class: string; message: string }; alternate: Alt }[]; + switched: { clipId: string; channel: string; video: string; from: { channel: string; video: string; reason: string } }[]; + none: { clipId: string; refusal: { class: string; message: string }; why: string }[]; + source: string; +}; + +const NAMES: Record<string, string> = { youtube: "YouTube", rumble: "Rumble", odysee: "Odysee" }; +const pname = (p: string | null) => (p ? (NAMES[p] ?? p) : "other"); + +export default function MontageFetchTools(props: React.ComponentProps<typeof FetchWindowsPanel>) { + const { project } = props; + const [plan, setPlan] = useState<Plan | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + const load = useCallback(async () => { + const r = await fetch(`/api/report/stand-ins?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const j = await r.json().catch(() => ({})); + if (!r.ok) setError(j.error ?? `HTTP ${r.status}`); + else setPlan(j as Plan); + }, [project]); + + useEffect(() => { + void load(); + }, [load]); + + async function post(body: Record<string, unknown>) { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/report/stand-ins", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, ...body }), + cache: "no-store", + }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + // The cards are the server's: read them again with the switched clip. + window.location.reload(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setBusy(false); + } + } + + return ( + <div data-montage-fetch="" className="space-y-1.5"> + <FetchWindowsPanel {...props} onSettled={() => void load()} /> + {plan && (plan.candidates.length > 0 || plan.switched.length > 0 || plan.none.length > 0) && ( + <div data-stand-ins="" className="max-w-[560px] space-y-1 rounded-[4px] border border-seam bg-panel px-3 py-2 text-[12px] text-text-2"> + {plan.candidates.map((c) => ( + <div key={c.clipId} data-stand-in={c.clipId} className="flex flex-wrap items-center gap-2"> + <span> + {c.clipId}: the {c.channel} copy refused ({/\b403\b/.test(c.refusal.message) ? "403" : c.refusal.class}) — the {pname(c.alternate.platform)} upload says it ({c.alternate.slug}/{c.alternate.videoId} @{c.alternate.start.toFixed(1)}) + </span> + <button type="button" data-action="use-stand-in" data-clip={c.clipId} disabled={busy} onClick={() => void post({ clips: [c.clipId] })} className={buttonVariants({ size: "sm" })}> + Use stand-in + </button> + </div> + ))} + {plan.candidates.length > 1 && ( + <button type="button" data-action="use-all-stand-ins" disabled={busy} onClick={() => void post({})} className={buttonVariants({ variant: "outline", size: "sm" })}> + Use all {plan.candidates.length} stand-ins + </button> + )} + {plan.switched.map((s) => ( + <div key={s.clipId} data-stand-in-switched={s.clipId} className="flex flex-wrap items-center gap-2"> + <span> + {s.clipId}: from {s.channel}/{s.video} — the {s.from.channel} copy refused ({s.from.reason}) + </span> + <button type="button" data-action="restore-stand-in" data-clip={s.clipId} disabled={busy} onClick={() => void post({ restore: s.clipId })} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Restore + </button> + </div> + ))} + {plan.none.map((n) => ( + <p key={n.clipId} data-stand-in-none={n.clipId} className="m-0 text-muted"> + {n.clipId}: refused ({n.refusal.class}) — {n.why} + </p> + ))} + </div> + )} + {error && ( + <span role="alert" data-stand-in-error="" className="text-[12px] text-reject-text"> + {error} + </span> + )} + </div> + ); +} diff --git a/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs b/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs @@ -0,0 +1,102 @@ +// The editor's fetch-windows door, stubbed (release 35 O1, montage-ops.spec.ts). +// +// POST /api/ops/fetch-windows {items, requestedBy, manifest?, storedUrl?, dryRun?} +// dryRun -> {ok, dryRun: true, groups: [{platform, queueKey, items}], cached, inFlight, unresolved} +// else -> {ok, dryRun: false, groups, cached, inFlight, unresolved, refused, jobs: [{platform, +// queueKey, jobId, items}], jobIds}: one job per platform +// GET /api/ops/job/<id> queued, then running, then done (or failed when a window failed) +// GET /api/jobs/<id>/log the job's log (ungated, as the editor's is): one line per window, +// ` ✗ <slug>/<id> <from>–<to> (<clipId>): network — … 403 …` for a refused one +// +// A window already on disk (<CHANNELS_DIR>/<slug>/data/<id>/clips/<from>-<to>.mp4, or one that holds +// it) is cached. A video id starting `vrefuse` is the Rumble embed lookup answering 403: its window +// fails. Every other window is written (a real mp4, the stub's writeWindow) when its job finishes. +// The platform is the record's (transcript.cues.json), else rumble for a slug with "rumble" in it. +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; + +const fwJobs = new Map(); +let next = 1; + +function platformOf(channels, slug, id) { + try { + const p = JSON.parse(readFileSync(path.join(channels, slug, "data", id, "transcript.cues.json"), "utf8")).platform; + if (p) return String(p); + } catch {} + return slug.includes("rumble") ? "rumble" : "youtube"; +} + +function onDisk(channels, it) { + const dir = path.join(channels, it.slug, "data", it.id, "clips"); + if (!existsSync(dir)) return false; + return readdirSync(dir).some((n) => { + const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\.mp4$/.exec(n); + return m && Number(m[1]) <= it.from + 0.02 && Number(m[2]) >= it.to - 0.02; + }); +} + +const label = (it) => `${it.slug}/${it.id} ${it.from.toFixed(2)}–${it.to.toFixed(2)}${it.clipId ? ` (${it.clipId})` : ""}`; + +/** + * @returns {boolean} whether it answered + */ +export function fetchWindowsRoute(req, res, url, { channels, json, readBody, writeWindow, record }) { + if (req.method === "POST" && url.pathname === "/api/ops/fetch-windows") { + readBody(req, (body) => { + record({ route: "fetch-windows", ...(body ?? {}) }); + if (!body?.requestedBy || !Array.isArray(body.items) || !body.items.length) return json(res, 400, { ok: false, error: "items and requestedBy are required" }); + const cached = []; + const groups = new Map(); + for (const it of body.items) { + if (onDisk(channels, it)) { + cached.push(it); + continue; + } + const platform = platformOf(channels, it.slug, it.id); + if (!groups.has(platform)) groups.set(platform, { platform, queueKey: `clips:${platform}`, items: [] }); + groups.get(platform).items.push(it); + } + const base = { groups: [...groups.values()], cached, inFlight: [], unresolved: [] }; + if (body.dryRun) return json(res, 200, { ok: true, dryRun: true, ...base }); + const jobs = base.groups.map((g) => { + const jobId = `stub-fw-${next++}`; + fwJobs.set(jobId, { id: jobId, platform: g.platform, items: g.items, status: "queued", polls: 0, log: [`Fetch windows: ${g.items.length} window(s) for ${body.requestedBy}${body.manifest ? ` · ${body.manifest}` : ""}`] }); + return { platform: g.platform, queueKey: g.queueKey, jobId, items: g.items.length }; + }); + return json(res, 200, { ok: true, dryRun: false, ...base, refused: [], jobs, jobIds: jobs.map((j) => j.jobId), ...(jobs.length === 1 ? { jobId: jobs[0].jobId } : {}) }); + }); + return true; + } + const status = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && status && fwJobs.has(status[1])) { + req.resume(); + const j = fwJobs.get(status[1]); + j.polls += 1; + if (j.polls === 1) j.status = "running"; + else if (j.status === "running") finish(j, channels, writeWindow); + return json(res, 200, { ok: true, job: { id: j.id, kind: "fetch-windows", status: j.status, ...(j.status === "running" ? { progress: { done: 0, total: j.items.length } } : {}) } }), true; + } + const log = /^\/api\/jobs\/([^/]+)\/log$/.exec(url.pathname); + if (req.method === "GET" && log && fwJobs.has(log[1])) { + req.resume(); + const j = fwJobs.get(log[1]); + const content = j.log.join("\n") + "\n"; + return json(res, 200, { content, nextOffset: content.length, status: j.status === "running" || j.status === "queued" ? j.status : "archived" }), true; + } + return false; +} + +function finish(j, channels, writeWindow) { + let failed = 0; + for (const it of j.items) { + if (String(it.id).startsWith("vrefuse")) { + failed += 1; + j.log.push(` ✗ ${label(it)}: network — ERROR: [Rumble] ${it.id}: Unable to download JSON metadata: HTTP Error 403: Forbidden`); + continue; + } + writeWindow(path.join(channels, it.slug, "data", it.id, "clips"), `${it.from.toFixed(2)}-${it.to.toFixed(2)}.mp4`, Math.max(1, Math.round(it.to - it.from))); + j.log.push(` ↓ ${label(it)}: fetched`); + } + j.log.push(`Fetch windows: ${j.items.length - failed} fetched, 0 cached, ${failed} failed.`); + j.status = failed ? "failed" : "done"; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -22,6 +22,7 @@ import path from "node:path"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { fileURLToPath } from "node:url"; +import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs"; const PORT = portFor("EDITOR_STUB_PORT"); const CHANNELS = process.env.CHANNELS_DIR ?? ""; @@ -1015,10 +1016,24 @@ function generationRoute(req, res, url, auth) { return null; } +// Release 35 O1: the fetch-windows door (editor-stub-fetch-windows.mjs). +const fwCtx = { + channels: CHANNELS, + json, + readBody: (req, then) => readBody(req, then), + writeWindow: (dir, name, seconds) => writeWindow(dir, name, seconds), + record: (r) => { + requests.push(r); + record(); + }, +}; + const server = http.createServer((req, res) => { const url = new URL(req.url ?? "/", `http://127.0.0.1:${PORT}`); if (url.pathname === "/health") return json(res, 200, { ok: true }); + // A job's log is ungated on the editor (GET /api/jobs/<id>/log). + if (url.pathname.startsWith("/api/jobs/") && fetchWindowsRoute(req, res, url, fwCtx)) return; // The recurring reports' clock (R5): the instant the next report-schedule // asks run at, and whether the next tick's window is quiet. {} resets. @@ -1046,6 +1061,7 @@ const server = http.createServer((req, res) => { return json(res, 401, { error: "missing bearer token" }); } + if ((url.pathname === "/api/ops/fetch-windows" || url.pathname.startsWith("/api/ops/job/")) && fetchWindowsRoute(req, res, url, fwCtx)) return; if (url.pathname.startsWith("/api/ops/") && generationRoute(req, res, url, auth) !== null) return; // THE OPS DOOR, stubbed alongside the media one. diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -30,6 +30,7 @@ import { makeDeleteFixture } from "./delete-fixture.mjs"; import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; import { makeReviewPlayerFixture } from "./review-player-fixture.mjs"; import { makeClipDeckFixture } from "./clip-deck-fixture.mjs"; +import { makeMontageOpsFixture } from "./montage-ops-fixture.mjs"; import { makeBenchShellFixture } from "./bench-shell-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; @@ -1804,6 +1805,8 @@ makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out makeReviewPlayerFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 34 N1: the montage clip deck, six instances ruled by ear (clip-deck.spec.ts). makeClipDeckFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Release 35 O1: Fetch windows, a refused window and its stand-in (montage-ops.spec.ts). +makeMontageOpsFixture({ reports, channels: CHANNELS, manifest }); // P4b: the bench shell's own clips, and the Media tab's fields with their draft files. makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). diff --git a/umtool/e2e/fixtures/montage-ops-fixture.mjs b/umtool/e2e/fixtures/montage-ops-fixture.mjs @@ -0,0 +1,70 @@ +// What montage-ops.spec.ts walks (release 35 O1): a two-clip montage seeded +// from a phrase, nothing on disk, for the editor stub to fetch +// (editor-stub-fetch-windows.mjs): +// +// s01 opsrumble/vok1 the stub fetches it +// s02 opsrumble/vrefuse1 the stub refuses it (the Rumble embed lookup, 403); +// its instance's alternate is opsyt/yalt1 at 210 s (YouTube) +// +// s02 is ruled keep, so the spec sees the ruling move with the stand-in and back. +// Its own project and its own channels: the spec writes the manifest, the +// rulings and fetch-runs.json, and the stub writes windows under the channels. +// Synthetic, like every fixture. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +/** + * @param {{ reports: string, channels: string, manifest: Function }} o + */ +export function makeMontageOpsFixture({ reports, channels, manifest }) { + const record = (slug, id, platform, uploadDate, start, text) => + write(path.join(channels, slug, "data", id), "transcript.cues.json", { + title: `Ops fixture ${id}`, + uploadDate, + platform, + channel: "Ops Fixture", + webpageUrl: `https://example.invalid/${id}`, + duration: 600, + cues: [ + { start: start - 3, end: start, text: "and here we go again" }, + { start, end: start + 3, text }, + { start: start + 3, end: start + 6, text: "moving on" }, + ], + }); + record("opsrumble", "vok1", "rumble", "20230102", 100, "kind of a slow news day today folks"); + record("opsrumble", "vrefuse1", "rumble", "20230103", 200, "honestly a slow news day out there people"); + record("opsyt", "yalt1", "youtube", "20230103", 210, "honestly a slow news day out there people"); + + const dir = path.join(reports, "montage-ops-fixture"); + const clip = (n, channel, video, at, date) => ({ + type: "clip", id: `s0${n}`, channel, video, start: at - 2.5, end: at + 5.5, cutStart: at, cutEnd: at + 3, cite: at, + quote: "a slow news day", onscreen: { title: "slow news day", subtitle: date }, + montage: { n, of: 2, date: date === "2 Jan 2023" ? "20230102" : "20230103", platform: "rumble", match: "slow news day", speakerCheck: false }, + }); + const doc = manifest("montage-ops-fixture", "The Montage Ops Fixture", { siteOrigin: "https://archive.example", channelSlug: "opsrumble" }, [ + clip(1, "opsrumble", "vok1", 100, "2 Jan 2023"), + clip(2, "opsrumble", "vrefuse1", 200, "3 Jan 2023"), + ]); + doc.render.fetchPad = 0; + doc.render.transition = 0; + write(dir, "video.manifest.json", doc); + const inst = (videoId, start, date, alternates) => ({ + slug: "opsrumble", videoId, platform: "rumble", source: "vtt", date, title: `Ops fixture ${videoId}`, duration: 600, + start, end: start + 3, cueFirst: 1, cueLast: 1, match: "slow news day", context: "a slow news day", speakerCheck: false, availability: null, alternates, + }); + write(dir, "phrase-scan.json", { + phrase: String.raw`slow[\s,]+news`, channels: ["opsyt"], prefer: "opsrumble", exclude: null, scanned: 3, hits: 3, + instances: [ + inst("vok1", 100, "20230102", []), + inst("vrefuse1", 200, "20230103", [{ slug: "opsyt", videoId: "yalt1", start: 210, end: 213, platform: "youtube", availability: null }]), + ], + dropped: [], + }); + write(dir, "montage-rulings.json", { version: 1, rulings: { "opsrumble/vrefuse1@200.00": { verdict: "keep", reason: "", at: "2026-10-18T21:00:00.000Z" } } }); + return { dir }; +} diff --git a/umtool/e2e/montage-ops.spec.ts b/umtool/e2e/montage-ops.spec.ts @@ -0,0 +1,95 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Montage operations in the app (release 35 O1), on the clip deck, against the +// editor stub (e2e/fixtures/editor-stub-fetch-windows.mjs): Fetch windows' dry +// run (the groups per platform) -> Start (one job, followed to its end) -> the +// window the stub refused (the Rumble embed lookup, 403) named -> Use stand-in +// (the instance's YouTube alternate, on the clip, its ruling moved) -> Fetch +// windows again asks for the stand-in's window -> Restore puts the clip back +// exactly. Fixture: e2e/fixtures/montage-ops-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/montage-ops-fixture"; +const DIR = path.join(FIXTURE, "reports", "montage-ops-fixture"); +const read = (f: string) => JSON.parse(readFileSync(path.join(DIR, f), "utf8")); +const requests = () => + (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as Record<string, unknown>[]).filter( + (r) => r.route === "fetch-windows" && r.requestedBy === `umtool:${PROJECT}`, + ); + +test("Fetch windows, a refused window, Use stand-in, Fetch again, Restore — on the clip deck", async ({ page }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 900 }); + const before = readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); + const asked = requests().length; + + await page.goto(urls.clipDeckHref(PROJECT)); + const panel = page.locator("[data-fetch-windows]"); + await expect(panel.locator("[data-fetch-items]")).toHaveAttribute("data-fetch-items", "2"); + + // The dry run: both windows on the Rumble queue, nothing on disk. + await panel.locator('[data-action="fetch-windows"]').click(); + const plan = panel.locator("[data-fetch-plan]"); + await expect(plan.locator('[data-fetch-group="rumble"]')).toHaveText("rumble: 2 windows to fetch"); + await expect(plan.locator("[data-fetch-cached]")).toHaveText("0 already on disk"); + const dry = requests().slice(asked); + expect(dry).toHaveLength(1); + expect(dry[0]).toMatchObject({ + dryRun: true, + storedUrl: "fallback", + manifest: path.join(DIR, "video.manifest.json"), + items: [ + { slug: "opsrumble", id: "vok1", from: 97.5, to: 105.5, clipId: "s01", pad: 3, reason: "The Montage Ops Fixture montage" }, + { slug: "opsrumble", id: "vrefuse1", from: 197.5, to: 205.5, clipId: "s02", pad: 3, reason: "The Montage Ops Fixture montage" }, + ], + }); + + // Start: one job, followed to its end; the refused window named. + await plan.locator('[data-action="fetch-start"]').click(); + const job = panel.locator("[data-fetch-job]"); + await expect(job).toHaveCount(1); + await expect(job).toHaveAttribute("data-fetch-job-status", "failed", { timeout: 30_000 }); + await expect(panel.locator('[data-fetch-failed="s02"]')).toContainText("network — ERROR: [Rumble] vrefuse1: Unable to download JSON metadata: HTTP Error 403: Forbidden"); + const runs = read("fetch-runs.json").runs as { dryRun: boolean; jobIds: string[]; jobs?: Record<string, { status: string; failed: { clipId: string }[] }> }[]; + expect(runs.map((r) => r.dryRun)).toEqual([true, false]); + const started = runs[1]; + expect(started.jobs?.[started.jobIds[0]]?.failed.map((f) => f.clipId)).toEqual(["s02"]); + + // The stand-in: the instance's YouTube alternate. + const offer = page.locator('[data-stand-in="s02"]'); + await expect(offer).toContainText("s02: the opsrumble copy refused (403) — the YouTube upload says it (opsyt/yalt1 @210.0)"); + await offer.locator('[data-action="use-stand-in"]').click(); + await expect(page.locator('[data-stand-in-switched="s02"]')).toContainText("s02: from opsyt/yalt1 — the opsrumble copy refused (403)", { timeout: 15_000 }); + const switched = read("video.manifest.json").timeline[1]; + expect(switched).toMatchObject({ + channel: "opsyt", + video: "yalt1", + start: 207.5, + end: 215.5, + cutStart: 210, + cutEnd: 213, + note: "from the YouTube upload: the Rumble copy refused (403)", + fallbackFrom: { channel: "opsrumble", video: "vrefuse1", start: 197.5, end: 205.5, cutStart: 200, cutEnd: 203, reason: "403" }, + }); + expect(Object.keys(read("montage-rulings.json").rulings)).toEqual(["opsyt/yalt1@210.00"]); + + // Fetch windows again: s01 is on disk now, the stand-in's window goes on the YouTube queue. + await panel.locator('[data-action="fetch-windows"]').click(); + await expect(plan.locator('[data-fetch-group="youtube"]')).toHaveText("youtube: 1 window to fetch"); + await expect(plan.locator("[data-fetch-cached]")).toHaveText("1 already on disk"); + expect(requests().at(-1)).toMatchObject({ dryRun: true, items: [{ clipId: "s01" }, { slug: "opsyt", id: "yalt1", from: 207.5, to: 215.5, clipId: "s02" }] }); + await plan.locator('[data-action="fetch-dismiss"]').click(); + + // Restore: the clip exactly as it was, its ruling back; the stand-in offered again. + await page.locator('[data-stand-in-switched="s02"] [data-action="restore-stand-in"]').click(); + await expect(page.locator('[data-stand-in="s02"]')).toBeVisible({ timeout: 15_000 }); + expect(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).toBe(before); + expect(Object.keys(read("montage-rulings.json").rulings)).toEqual(["opsrumble/vrefuse1@200.00"]); +}); diff --git a/umtool/lib/report/montageRulings.mjs b/umtool/lib/report/montageRulings.mjs @@ -145,6 +145,29 @@ export async function setMontageRuling(projectDir, key, ruling, { now = new Date }); } +/** + * Move a moment's ruling to another key, as it is (release 35: a clip switched + * to a stand-in is the same instance at another moment, and Restore moves it + * back). Nothing is written when `from` has no ruling or `to` already has one + * (that ruling is somebody's and is kept). Returns whether it moved. + * @param {string} projectDir + * @param {string} from + * @param {string} to + */ +export async function moveMontageRuling(projectDir, from, to) { + if (!isMomentKey(from) || !isMomentKey(to)) throw new Error("not a moment key (<channel>/<video>@<seconds>)"); + if (from === to) return false; + const file = montageRulingsFileOf(projectDir); + return withRulingsLock(async () => { + const doc = await readForWrite(file); + if (!doc.rulings[from] || doc.rulings[to]) return false; + doc.rulings[to] = doc.rulings[from]; + delete doc.rulings[from]; + await writeDoc(file, doc); + return true; + }); +} + /** Many rulings in one write (the import). Keys already ruled are skipped unless `overwrite`. */ export async function setMontageRulings(projectDir, entries, { now = new Date(), overwrite = false } = {}) { const checked = entries.map(({ key, ruling }) => { diff --git a/umtool/lib/report/standIns.mjs b/umtool/lib/report/standIns.mjs @@ -0,0 +1,310 @@ +// STAND-INS (release 35 O1): a montage clip whose window the editor REFUSED — +// a Rumble embed lookup that answers 403 on every try, a recording gone from +// its platform — cut from another upload of the same moment instead. +// +// A clip is a candidate when all three hold: +// - its window is still missing on disk (the bench's own cache check, the +// corpus's clips/ included); +// - the editor refused it: a fetch-windows job of a run recorded in +// fetch-runs.json failed that window (its log's `✗` line — not a rate +// limit, our own drive or our own cut), or the editor could not resolve it; +// - its instance in phrase-scan.json has an alternate that is public (or not +// known to be otherwise) and was not refused itself. An older scan with no +// `alternates` is scanned again (phraseScanMany over the same settings, +// through the cue-text cache) to find them. +// The first alternate wins: YouTube, then Odysee / cornbreadman, then the rest. +// +// THE SWITCH IS ON THE CLIP, AND IT IS REVERSIBLE. The clip takes the +// alternate's channel, video and moment (the cut is the alternate's phrase, the +// window keeps the clip's own margins), and records where it came from: +// fallbackFrom: {channel, video, start, end, cutStart, cutEnd, cite, note, +// platform, reason} +// with `note` "from the YouTube upload: the Rumble copy refused (403)". Restore +// puts every one of those fields back. Its montage ruling and its voice-match +// row are keyed by the moment (clipMomentKey), so both move to the new key and +// back. The manifest is written through replaceManifest (the lock, the auto +// snapshot the Cut tab's Undo takes back, the atomic write). +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { momentKey, clipMomentKey } from "umtool-report-to-video/montage-rulings"; +import { phraseScanMany } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; +import { readVoiceMatch, writeVoiceMatch } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { manifestToken, replaceManifest, StaleToken } from "./manifest.mjs"; +import { moveMontageRuling } from "./montageRulings.mjs"; +import { projectCache } from "./serve.mjs"; +import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; +import { phraseTextCacheDir } from "../phrase-finder/scan.mjs"; +import { followRun, lastStartedRun, readFetchRuns } from "./fetchWindows.mjs"; + +export const PHRASE_SCAN_FILE = "phrase-scan.json"; +/** Failure classes that say nothing about the recording: never a reason for a stand-in. */ +export const NOT_A_REFUSAL = new Set(["rate_limit", "unreachable", "cut-failed", "cancelled", "cancel"]); +/** An alternate whose availability is one of these may stand in. */ +export const STAND_IN_AVAILABILITY = new Set(["public", "unknown"]); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const r2 = (x) => Number(Number(x).toFixed(2)); +const PLATFORM_NAMES = { youtube: "YouTube", rumble: "Rumble", odysee: "Odysee", twitch: "Twitch", kick: "Kick", bitchute: "BitChute" }; +export const platformName = (p) => (p ? (PLATFORM_NAMES[String(p).toLowerCase()] ?? String(p).charAt(0).toUpperCase() + String(p).slice(1)) : "other"); + +/** YouTube first, then Odysee / cornbreadman, then anything else. */ +export const alternateRank = (a) => (a?.platform === "youtube" ? 0 : a?.platform === "odysee" || a?.slug === "cornbreadman" ? 1 : 2); + +/** + * The alternates that may stand in, best first. `refused` is a set of + * `<slug>/<videoId>` the editor already refused. + * @param {{ slug: string, videoId: string, start: number, end: number, platform: string | null, availability: string | null }[]} alternates + * @param {{ refused?: Set<string>, not?: { slug: string, videoId: string } | null }} [opts] + */ +export function eligibleAlternates(alternates, { refused = new Set(), not = null } = {}) { + return (Array.isArray(alternates) ? alternates : []) + .map((a, k) => ({ a, k })) + .filter(({ a }) => isObj(a) && a.slug && a.videoId && Number.isFinite(Number(a.start)) && Number.isFinite(Number(a.end))) + .filter(({ a }) => a.availability == null || STAND_IN_AVAILABILITY.has(String(a.availability))) + .filter(({ a }) => !refused.has(`${a.slug}/${a.videoId}`) && !(not && a.slug === not.slug && a.videoId === not.videoId)) + .sort((x, y) => alternateRank(x.a) - alternateRank(y.a) || x.k - y.k) + .map(({ a }) => a); +} + +/** "403" when the editor's words say so, else the failure's class. */ +export const refusalWords = (r) => (/\b403\b/.test(String(r?.message ?? "")) ? "403" : String(r?.class ?? "refused")); + +/** + * The clip cut from `alt` instead. Pure. The cut is the alternate's phrase; the + * window keeps the clip's own margins either side of its cut. + * @param {Record<string, any>} clip + * @param {{ slug: string, videoId: string, start: number, end: number, platform: string | null }} alt + * @param {{ manifest?: Record<string, any> | null, refusal?: { class?: string, message?: string } | null, fromPlatform?: string | null }} [opts] + */ +export function standInClip(clip, alt, { manifest = null, refusal = null, fromPlatform = null } = {}) { + const channel = clip.channel ?? manifest?.provenance?.channelSlug ?? null; + const cutStart = Number.isFinite(Number(clip.cutStart)) ? Number(clip.cutStart) : Number(clip.start); + const cutEnd = Number.isFinite(Number(clip.cutEnd)) ? Number(clip.cutEnd) : Number(clip.end); + const before = Math.max(0, cutStart - Number(clip.start)); + const after = Math.max(0, Number(clip.end) - cutEnd); + const was = fromPlatform ?? clip.montage?.platform ?? null; + const words = refusalWords(refusal); + const next = { + ...clip, + channel: alt.slug, + video: alt.videoId, + start: r2(Math.max(0, Number(alt.start) - before)), + end: r2(Number(alt.end) + after), + cutStart: r2(alt.start), + cutEnd: r2(alt.end), + ...(clip.cite !== undefined ? { cite: r2(alt.start) } : {}), + note: `from the ${platformName(alt.platform)} upload: the ${platformName(was)} copy refused (${words})`, + fallbackFrom: { + channel, + ...(clip.channel ? {} : { ownChannel: false }), + video: clip.video, + start: clip.start, + end: clip.end, + cutStart: clip.cutStart ?? null, + cutEnd: clip.cutEnd ?? null, + cite: clip.cite ?? null, + note: clip.note ?? null, + platform: was, + reason: words, + }, + }; + if (isObj(clip.montage)) next.montage = { ...clip.montage, platform: alt.platform ?? null }; + return next; +} + +/** + * The clip as it was before its stand-in. Pure; a clip with no `fallbackFrom` + * comes back unchanged. + * @param {Record<string, any>} clip + */ +export function restoredClip(clip) { + const f = clip?.fallbackFrom; + if (!isObj(f)) return clip; + const { fallbackFrom: _f, ...rest } = clip; + const out = { ...rest, video: f.video, start: f.start, end: f.end }; + // A clip that named no channel of its own took the manifest's, and goes back to naming none. + if (f.ownChannel === false) delete out.channel; + else out.channel = f.channel; + for (const k of ["cutStart", "cutEnd", "cite", "note"]) { + if (f[k] === null || f[k] === undefined) delete out[k]; + else out[k] = f[k]; + } + if (isObj(clip.montage)) { + out.montage = { ...clip.montage, platform: f.platform ?? null }; + } + return out; +} + +/** + * Every window the editor refused, by clip id — the newest word on each: + * failed windows of the recorded runs' ended jobs, and the editor's unresolved. + * @param {{ runs: any[] }} doc fetch-runs.json + * @returns {Map<string, { slug: string, id: string, class: string, message: string, jobId: string | null, at: string }>} + */ +export function refusedWindows(doc) { + const out = new Map(); + for (const run of doc?.runs ?? []) { + for (const u of run.summary?.unresolved ?? []) { + if (u.clipId) out.set(u.clipId, { slug: u.slug, id: u.id, class: "unresolved", message: u.error, jobId: null, at: run.at }); + } + for (const [jobId, j] of Object.entries(run.jobs ?? {})) { + for (const f of j?.failed ?? []) { + if (!f.clipId || NOT_A_REFUSAL.has(f.class)) continue; + out.set(f.clipId, { slug: f.slug, id: f.id, class: f.class, message: f.message, jobId, at: j.at ?? run.at }); + } + } + } + return out; +} + +const instanceKey = (i) => momentKey({ channel: i.slug, video: i.videoId, at: i.start }); + +/** + * The phrase scan's instances by moment key, alternates and all. An older scan + * with no `alternates` is scanned again over its own settings (`rescan: true`). + * @returns {Promise<{ byKey: Map<string, any>, source: "scan" | "rescan" | "none", why?: string }>} + */ +export async function instancesByKey(projectDir, { channelsDir, cacheDir = phraseTextCacheDir(), rescan = true } = {}) { + let scan; + try { + scan = JSON.parse(await readFile(path.join(projectDir, PHRASE_SCAN_FILE), "utf8")); + } catch { + return { byKey: new Map(), source: "none", why: `no ${PHRASE_SCAN_FILE} beside the manifest` }; + } + const listed = [...(scan.instances ?? []), ...(scan.skippedByCap ?? [])]; + const hasAlternates = listed.some((i) => Array.isArray(i?.alternates)); + if (hasAlternates || !rescan) { + return { byKey: new Map(listed.map((i) => [instanceKey(i), i])), source: "scan" }; + } + if (!scan.phrase || !Array.isArray(scan.channels)) return { byKey: new Map(), source: "none", why: `${PHRASE_SCAN_FILE} names no phrase and channels to scan again` }; + const [again] = await phraseScanMany({ + channelsDir, + channels: scan.channels, + prefer: scan.prefer ?? null, + exclude: scan.exclude ?? null, + phrases: [{ id: "p", phrase: scan.phrase }], + cacheDir, + }); + return { byKey: new Map(again.instances.map((i) => [instanceKey(i), i])), source: "rescan" }; +} + +/** + * What can be switched, what is switched, and what cannot be helped. + * @param {{ id: string, dir: string }} project + * @param {{ cfg?: { url: string, token: string, fetch?: typeof fetch } | null, cacheDir?: string, rescan?: boolean }} [opts] + */ +export async function standInPlan(project, { cfg = null, cacheDir = phraseTextCacheDir(), rescan = true } = {}) { + const manifest = JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8")); + let runs = await readFetchRuns(project.dir); + // Jobs still running when last asked: ask once more (best effort). + const last = lastStartedRun(runs); + if (cfg?.token && last) { + await followRun(cfg, project.dir, last).catch(() => null); + runs = await readFetchRuns(project.dir); + } + const refused = refusedWindows(runs); + const refusedVideos = new Set([...refused.values()].map((r) => `${r.slug}/${r.id}`)); + const cache = await projectCache(project, manifest); + const clips = (manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip"); + const switched = clips.filter((c) => isObj(c.fallbackFrom)).map((c) => ({ clipId: c.id, channel: c.channel, video: c.video, from: c.fallbackFrom })); + const wanted = clips.filter((c) => !isObj(c.fallbackFrom) && refused.has(c.id) && !cache.isFetched(c)); + const out = { project: project.id, candidates: [], switched, none: [], refused: refused.size, source: "none", why: null }; + if (!wanted.length) return out; + const shadowExists = await hasShadowChannels(project.dir); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists }); + const inst = await instancesByKey(project.dir, { channelsDir, cacheDir, rescan }); + out.source = inst.source; + out.why = inst.why ?? null; + for (const c of wanted) { + const r = refused.get(c.id); + const key = clipMomentKey(c, manifest); + const i = key ? inst.byKey.get(key) : null; + const channel = c.channel ?? manifest.provenance?.channelSlug ?? null; + const alts = i ? eligibleAlternates(i.alternates, { refused: refusedVideos, not: { slug: channel, videoId: c.video } }) : []; + if (!alts.length) { + out.none.push({ clipId: c.id, refusal: r, why: !i ? inst.why ?? "its instance is not in the phrase scan" : "no public alternate that was not refused too" }); + continue; + } + out.candidates.push({ clipId: c.id, key, channel, video: c.video, refusal: r, alternate: alts[0], others: alts.slice(1) }); + } + return out; +} + +/** Write the manifest with `edit(manifest)` applied, through replaceManifest (one retry on a stale read). */ +async function rewrite(dir, op, edit) { + for (let attempt = 0; ; attempt++) { + const token = await manifestToken(dir); + const manifest = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const result = edit(manifest); + if (!result) return null; + try { + await replaceManifest(dir, manifest, { token, op }); + return result; + } catch (e) { + if (e instanceof StaleToken && attempt === 0) continue; + throw e; + } + } +} + +/** Move a voice-match row to another key (as it is), when the target has none. */ +async function moveVoiceRow(dir, from, to) { + const doc = await readVoiceMatch(dir); + if (!doc || !from || !to || from === to || !doc.clips[from] || doc.clips[to]) return false; + doc.clips[to] = doc.clips[from]; + delete doc.clips[from]; + await writeVoiceMatch(dir, doc); + return true; +} + +/** + * Switch the candidates (all, or the clip ids given) to their stand-ins. + * @param {{ id: string, dir: string }} project + * @param {{ clips?: string[] | null, cfg?: any, cacheDir?: string, rescan?: boolean }} [opts] + */ +export async function applyStandIns(project, { clips = null, cfg = null, cacheDir = phraseTextCacheDir(), rescan = true } = {}) { + const plan = await standInPlan(project, { cfg, cacheDir, rescan }); + const chosen = plan.candidates.filter((c) => !clips || clips.includes(c.clipId)); + if (clips) { + const unknown = clips.filter((id) => !plan.candidates.some((c) => c.clipId === id)); + if (unknown.length) throw new Error(`no stand-in for ${unknown.join(", ")} (not refused, already on disk, already switched, or no public alternate)`); + } + if (!chosen.length) return { switched: [], plan }; + const moves = []; + await rewrite(project.dir, "stand-in", (m) => { + for (const c of chosen) { + const k = (m.timeline ?? []).findIndex((e) => isObj(e) && e.id === c.clipId); + if (k < 0) continue; + const before = m.timeline[k]; + const next = standInClip(before, c.alternate, { manifest: m, refusal: c.refusal }); + m.timeline[k] = next; + moves.push({ clipId: c.clipId, from: clipMomentKey(before, m), to: clipMomentKey(next, m), alternate: c.alternate }); + } + return moves; + }); + for (const mv of moves) { + mv.ruling = mv.from && mv.to ? await moveMontageRuling(project.dir, mv.from, mv.to) : false; + mv.voice = await moveVoiceRow(project.dir, mv.from, mv.to); + } + return { switched: moves, plan }; +} + +/** + * Put a switched clip back as it was; its ruling and voice row move back. + * @param {{ id: string, dir: string }} project + * @param {string} clipId + */ +export async function restoreStandIn(project, clipId) { + const mv = await rewrite(project.dir, "restore-stand-in", (m) => { + const k = (m.timeline ?? []).findIndex((e) => isObj(e) && e.id === clipId); + if (k < 0) throw new Error(`no clip ${clipId}`); + const before = m.timeline[k]; + if (!isObj(before.fallbackFrom)) throw new Error(`${clipId} has no stand-in to restore`); + const next = restoredClip(before); + m.timeline[k] = next; + return { clipId, from: clipMomentKey(before, m), to: clipMomentKey(next, m) }; + }); + mv.ruling = mv.from && mv.to ? await moveMontageRuling(project.dir, mv.from, mv.to) : false; + mv.voice = await moveVoiceRow(project.dir, mv.from, mv.to); + return mv; +} diff --git a/umtool/lib/report/standIns.test.mjs b/umtool/lib/report/standIns.test.mjs @@ -0,0 +1,162 @@ +// Stand-ins (release 35 O1): a montage clip whose window the editor refused is +// switched to its instance's first public alternate, on the clip, reversibly; +// its ruling and its voice-match row move with it, and back. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { alternateRank, applyStandIns, eligibleAlternates, refusedWindows, restoreStandIn, restoredClip, standInClip, standInPlan } from "./standIns.mjs"; +import { fallbackCommand } from "./standInsCli.mjs"; + +const write = async (file, doc) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n"); +}; +const clip = (id, channel, video, cutStart, extra = {}) => ({ + type: "clip", id, channel, video, start: cutStart - 2.5, end: cutStart + 5.5, cutStart, cutEnd: cutStart + 3, cite: cutStart, + quote: "kind of a slow news day today", onscreen: { title: "slow news day", subtitle: "2 Jan 2023" }, + montage: { n: 1, of: 3, date: "20230102", platform: channel.includes("rumble") ? "rumble" : "youtube", match: "slow news day", speakerCheck: false }, + ...extra, +}); +const ALT_YT = { slug: "syt", videoId: "yalt", start: 210, end: 213, platform: "youtube", availability: null }; +const ALT_ODY = { slug: "cornbreadman", videoId: "c1", start: 50, end: 53, platform: "odysee", availability: "public" }; + +test("the ranking: YouTube, then Odysee / cornbreadman, then the rest; public or unknown only; never one refused", () => { + const alts = [ + { slug: "x", videoId: "k1", start: 1, end: 2, platform: "kick", availability: null }, + ALT_ODY, + { slug: "syt", videoId: "gone", start: 1, end: 2, platform: "youtube", availability: "deleted" }, + ALT_YT, + { slug: "syt", videoId: "y403", start: 1, end: 2, platform: "youtube", availability: "unknown" }, + ]; + assert.deepEqual(eligibleAlternates(alts, { refused: new Set(["syt/y403"]) }).map((a) => a.videoId), ["yalt", "c1", "k1"]); + assert.equal(alternateRank({ slug: "cornbreadman", platform: "rumble" }), 1); +}); + +test("standInClip / restoredClip: the alternate's moment with the clip's own margins; everything put back exactly", () => { + const before = clip("s02", "srumble", "vrefuse", 200, { note: "also in syt/yalt" }); + const next = standInClip(before, ALT_YT, { refusal: { class: "network", message: "HTTP Error 403: Forbidden" } }); + assert.equal(next.channel, "syt"); + assert.equal(next.video, "yalt"); + assert.deepEqual([next.start, next.end, next.cutStart, next.cutEnd, next.cite], [207.5, 215.5, 210, 213, 210]); + assert.equal(next.note, "from the YouTube upload: the Rumble copy refused (403)"); + assert.equal(next.montage.platform, "youtube"); + assert.deepEqual(next.fallbackFrom, { channel: "srumble", video: "vrefuse", start: 197.5, end: 205.5, cutStart: 200, cutEnd: 203, cite: 200, note: "also in syt/yalt", platform: "rumble", reason: "403" }); + assert.equal(JSON.stringify(restoredClip(next)), JSON.stringify(before), "key order and all"); + // A clip with no note: the note goes again on Restore. + const bare = clip("s03", "srumble", "v3", 10); + assert.equal(JSON.stringify(restoredClip(standInClip(bare, ALT_ODY, { refusal: { class: "unavailable", message: "gone" } }))), JSON.stringify(bare)); + assert.match(standInClip(bare, ALT_ODY, { refusal: { class: "unavailable", message: "gone" } }).note, /the Odysee upload: the Rumble copy refused \(unavailable\)/); +}); + +test("refusedWindows: the newest word per clip; a rate limit or our own drive is not a refusal", () => { + const doc = { + runs: [ + { at: "1", summary: { unresolved: [{ clipId: "s05", slug: "a", id: "b", error: "the recording is deleted" }] }, jobs: {} }, + { at: "2", jobs: { J1: { status: "failed", failed: [ + { clipId: "s02", slug: "srumble", id: "vrefuse", class: "network", message: "HTTP Error 403" }, + { clipId: "s01", slug: "srumble", id: "v1", class: "rate_limit", message: "429" }, + { clipId: "s04", slug: "srumble", id: "v4", class: "unreachable", message: "drive" }, + ] } } }, + ], + }; + const r = refusedWindows(doc); + assert.deepEqual([...r.keys()].sort(), ["s02", "s05"]); + assert.equal(r.get("s02").jobId, "J1"); + assert.equal(r.get("s05").class, "unresolved"); +}); + +async function project(root, { scanAlternates = true } = {}) { + const dir = path.join(root, "reports", "synth-reel"); + const channelsDir = path.join(root, "channels"); + // The corpus: a Rumble stream refused, its YouTube twin with the same words. + const cues = (start, text) => ({ uploadDate: "20230102", duration: 1000, cues: [{ start, end: start + 3, text }] }); + await write(path.join(channelsDir, "srumble", "data", "v1", "transcript.cues.json"), { ...cues(100, "kind of a slow news day today folks"), platform: "rumble", title: "monday show" }); + await write(path.join(channelsDir, "srumble", "data", "vrefuse", "transcript.cues.json"), { ...cues(200, "honestly a slow news day out there people"), platform: "rumble", title: "tuesday show", uploadDate: "20230103" }); + await write(path.join(channelsDir, "syt", "data", "yalt", "transcript.cues.json"), { ...cues(210, "honestly a slow news day out there people"), platform: "youtube", title: "tuesday show", uploadDate: "20230103", duration: 1005 }); + await write(path.join(channelsDir, "srumble", "data", "v3", "transcript.cues.json"), { ...cues(10, "what a slow news week"), platform: "rumble", title: "wed", uploadDate: "20230104" }); + // s01's window is on disk. + await write(path.join(channelsDir, "srumble", "data", "v1", "clips", "97.50-105.50.mp4"), ""); + const manifest = { + schemaVersion: 1, slug: "synth-reel", title: "Synth reel", + provenance: { siteOrigin: "https://archive.example", channelSlug: "srumble", channelsDir }, + render: { fetchPad: 0, transition: 0 }, + timeline: [clip("s01", "srumble", "v1", 100), clip("s02", "srumble", "vrefuse", 200), clip("s03", "srumble", "v3", 10)], + }; + await write(path.join(dir, "video.manifest.json"), manifest); + const inst = (slug, videoId, start, alternates) => ({ slug, videoId, start, end: start + 3, date: "20230103", platform: "rumble", ...(scanAlternates ? { alternates } : {}) }); + await write(path.join(dir, "phrase-scan.json"), { + phrase: String.raw`slow[\s,]+news`, channels: ["syt"], prefer: "srumble", exclude: null, scanned: 4, hits: 4, + instances: [inst("srumble", "v1", 100, []), inst("srumble", "vrefuse", 200, [ALT_YT]), inst("srumble", "v3", 10, [])], + dropped: [], + }); + await write(path.join(dir, "fetch-runs.json"), { + runs: [{ at: "2026-10-18T22:00:00.000Z", bodyHash: "h", dryRun: false, items: 3, jobIds: ["J1"], summary: { jobs: [{ jobId: "J1", platform: "rumble", items: 3 }], unresolved: [] }, jobs: { J1: { status: "failed", platform: "rumble", at: "x", failed: [ + { clipId: "s02", slug: "srumble", id: "vrefuse", from: 197.5, to: 205.5, class: "network", message: "ERROR: [Rumble] vrefuse: HTTP Error 403: Forbidden" }, + { clipId: "s03", slug: "srumble", id: "v3", from: 7.5, to: 15.5, class: "network", message: "HTTP Error 403: Forbidden" }, + ] } } }], + }); + await write(path.join(dir, "montage-rulings.json"), { version: 1, rulings: { "srumble/vrefuse@200.00": { verdict: "keep", reason: "", at: "2026-10-18T21:00:00.000Z" } } }); + await write(path.join(dir, "voice-match.json"), { version: 1, clips: { "srumble/vrefuse@200.00": { score: 0.7, label: "likely", speechSeconds: 2 } } }); + return { id: "synth-reel", dir, channelsDir, manifest }; +} + +test("the plan, the switch and Restore: on the clip, the ruling and the voice row moved and back, Undo-able", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-standins-")); + try { + const p = await project(root); + const plan = await standInPlan(p, { cacheDir: path.join(root, "cache") }); + assert.deepEqual(plan.candidates.map((c) => [c.clipId, c.alternate.videoId]), [["s02", "yalt"]]); + assert.deepEqual(plan.none.map((n) => n.clipId), ["s03"], "refused, no alternate"); + assert.equal(plan.source, "scan"); + + const res = await applyStandIns(p, { cacheDir: path.join(root, "cache") }); + assert.deepEqual(res.switched.map((s) => [s.clipId, s.from, s.to, s.ruling, s.voice]), [["s02", "srumble/vrefuse@200.00", "syt/yalt@210.00", true, true]]); + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.equal(m.timeline[1].video, "yalt"); + assert.equal(m.timeline[1].fallbackFrom.video, "vrefuse"); + assert.equal(m.timeline[1].note, "from the YouTube upload: the Rumble copy refused (403)"); + assert.deepEqual(m.timeline[0], p.manifest.timeline[0], "the others untouched"); + const rulings = JSON.parse(await readFile(path.join(p.dir, "montage-rulings.json"), "utf8")).rulings; + assert.deepEqual(Object.keys(rulings), ["syt/yalt@210.00"]); + assert.deepEqual(Object.keys(JSON.parse(await readFile(path.join(p.dir, "voice-match.json"), "utf8")).clips), ["syt/yalt@210.00"]); + assert.ok((await readdir(path.join(p.dir, "revisions"))).some((f) => f.includes("auto-before-stand-in")), "the Cut tab's Undo can take it back"); + + const after = await standInPlan(p, { cacheDir: path.join(root, "cache") }); + assert.deepEqual(after.switched.map((s) => s.clipId), ["s02"]); + assert.equal(after.candidates.length, 0); + + const back = await restoreStandIn(p, "s02"); + assert.deepEqual([back.from, back.to, back.ruling, back.voice], ["syt/yalt@210.00", "srumble/vrefuse@200.00", true, true]); + const m2 = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.equal(JSON.stringify(m2), JSON.stringify(p.manifest), "the manifest exactly as it was"); + assert.deepEqual(Object.keys(JSON.parse(await readFile(path.join(p.dir, "montage-rulings.json"), "utf8")).rulings), ["srumble/vrefuse@200.00"]); + await assert.rejects(restoreStandIn(p, "s01"), /no stand-in to restore/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("an older phrase-scan.json with no alternates is scanned again to find them; the CLI's dry run, switch and restore", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-standins-")); + try { + const p = await project(root, { scanAlternates: false }); + const lines = []; + const run = (args) => fallbackCommand(args, { root: path.join(root, "reports"), out: (s) => lines.push(s), err: (s) => lines.push(s), cfg: { url: "http://x", token: "" }, cacheDir: path.join(root, "cache") }); + assert.equal(await run(["synth-reel", "--dry-run"]), 0); + assert.match(lines.join("\n"), /1 stand-in\(s\), 1 refused with none, 0 already switched \(alternates from a fresh scan/); + assert.match(lines.join("\n"), /s02 {2}srumble\/vrefuse refused \(network\) -> syt\/yalt @210.00 \(YouTube\)/); + lines.length = 0; + assert.equal(await run(["synth-reel", "--clip", "s02"]), 0); + assert.match(lines.join("\n"), /s02 -> syt\/yalt @210.00 \(YouTube\) · ruling moved · voice score moved/); + assert.match(lines.join("\n"), /umtool fetch synth-reel --dry-run/); + lines.length = 0; + assert.equal(await run(["synth-reel", "--clip", "s03"]), 1, "no stand-in for s03"); + lines.length = 0; + assert.equal(await run(["synth-reel", "--restore", "s02"]), 0); + assert.match(lines.join("\n"), /s02 restored \(srumble\/vrefuse@200.00\), its ruling moved back, its voice score moved back/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/standInsCli.mjs b/umtool/lib/report/standInsCli.mjs @@ -0,0 +1,88 @@ +// `umtool fallback` (release 35 O1): stand-ins for the montage clips whose +// windows the editor refused (lib/report/standIns.mjs) — the clip deck's +// "Use stand-in" and "Restore" from a terminal. +// +// umtool fallback <project> --dry-run [--json] which clips would switch, to what, and which cannot +// umtool fallback <project> [--clip <id> …] [--json] switch them (every candidate, or the ones named) +// umtool fallback <project> --restore <clipId> put one back as it was +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { editorConfig } from "./fetchWindows.mjs"; +import { applyStandIns, platformName, restoreStandIn, standInPlan } from "./standIns.mjs"; + +export const FALLBACK_USAGE = [ + "usage: umtool fallback <project> --dry-run [--json] the refused clips, the stand-in each would take", + " umtool fallback <project> [--clip <id> …] [--json] switch them (all candidates, or the clips named)", + " umtool fallback <project> --restore <clipId> put a switched clip back as it was", + "", + "A candidate: its window is not on disk, a fetch run (fetch-runs.json) says the editor refused it, and its", + "phrase-scan instance has a public alternate (YouTube first, then Odysee / cornbreadman). The switch is recorded", + "on the clip (`fallbackFrom`); its montage ruling and voice-match row move with it. Then: umtool fetch <project>.", +].join("\n"); + +class CliError extends Error {} + +const altLine = (a) => `${a.slug}/${a.videoId} @${Number(a.start).toFixed(2)} (${platformName(a.platform)})`; + +/** + * @param {string[]} args the words after `fallback` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, cfg?: any, cacheDir?: string }} [opts] + * @returns {Promise<number>} + */ +export async function fallbackCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), cfg = editorConfig(), cacheDir } = {}) { + const json = args.includes("--json"); + const words = []; + const clips = []; + let restore = null; + for (let i = 0; i < args.length; i += 1) { + if (args[i] === "--clip") clips.push(args[++i] ?? ""); + else if (args[i] === "--restore") restore = args[++i] ?? ""; + else if (!args[i].startsWith("--")) words.push(args[i]); + } + try { + const [projectArg] = words; + if (!projectArg || args.includes("--help")) { + err(FALLBACK_USAGE); + return 2; + } + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + const opts = { cfg, ...(cacheDir ? { cacheDir } : {}) }; + + if (restore !== null) { + if (!restore) throw new CliError("--restore needs a clip id"); + const mv = await restoreStandIn(project, restore); + if (json) out(JSON.stringify({ project: project.id, restored: mv }, null, 2)); + else out(`${project.id}: ${restore} restored (${mv.to})${mv.ruling ? ", its ruling moved back" : ""}${mv.voice ? ", its voice score moved back" : ""}`); + return 0; + } + + if (args.includes("--dry-run")) { + const plan = await standInPlan(project, opts); + if (json) out(JSON.stringify(plan, null, 2)); + else { + out(`${project.id}: ${plan.candidates.length} stand-in(s), ${plan.none.length} refused with none, ${plan.switched.length} already switched${plan.source === "rescan" ? " (alternates from a fresh scan: phrase-scan.json has none)" : ""}`); + for (const c of plan.candidates) out(` ${c.clipId} ${c.channel}/${c.video} refused (${c.refusal.class}) -> ${altLine(c.alternate)}`); + for (const n of plan.none) out(` ${n.clipId} refused (${n.refusal.class}) — ${n.why}`); + for (const s of plan.switched) out(` ${s.clipId} switched from ${s.from.channel}/${s.from.video} (restore: umtool fallback ${project.id} --restore ${s.clipId})`); + } + return 0; + } + + const res = await applyStandIns(project, { ...opts, clips: clips.length ? clips : null }); + if (json) out(JSON.stringify({ project: project.id, switched: res.switched, none: res.plan.none }, null, 2)); + else { + if (!res.switched.length) out(`${project.id}: nothing to switch (${res.plan.none.length} refused with no stand-in)`); + for (const s of res.switched) out(` ${s.clipId} -> ${altLine(s.alternate)}${s.ruling ? " · ruling moved" : ""}${s.voice ? " · voice score moved" : ""}`); + if (res.switched.length) out(`then fetch them: umtool fetch ${project.id} --dry-run`); + } + return 0; + } catch (e) { + if (e instanceof CliError || e instanceof Error) { + err(e.message); + return 1; + } + throw e; + } +}