Archilyzer · Source

archilyzer

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

commit 8395b5124da84dc881631872a7f3c1886da22400
parent 74e70fac29663d486fa204eb0cbbd6425ad6098c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 00:38:52 -0400

Merge r35/montage-ops slice 4 + tail: stand-ins (umtool fallback + deck buttons), best-match alternates, docs

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

Diffstat:
Mcommon/lib/montage/phraseScan.mjs | 13+++++++++++--
Meditor/CHANGELOG.md | 2++
Mplans/FACTS.md | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-35/montage-ops.md | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 4+++-
Mumtool/docs/report-video.md | 37+++++++++++++++++++++++++++++++++++++
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+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
19 files changed, 1190 insertions(+), 6 deletions(-)

diff --git a/common/lib/montage/phraseScan.mjs b/common/lib/montage/phraseScan.mjs @@ -289,10 +289,19 @@ async function foldHits({ hits, prefer, preferred, recordOf, ex, availability }) } const ctx = words(h.context); // Its twin already has the hit: nothing to add. + // Covered when any twin's hit says it (as release 34 decided); the + // alternate goes to the twin hit that says it BEST, since the phrase's + // own words alone clear the bar for every twin of the day. let covered = null; + let coveredScore = -1; for (const id of twins) { - covered = (preferredHits.get(id) ?? []).find((p) => locateInCues([{ text: p.context }], ctx).score >= SAME_HIT_MIN_SCORE) ?? null; - if (covered) break; + for (const p of preferredHits.get(id) ?? []) { + const score = locateInCues([{ text: p.context }], ctx).score; + if (score >= SAME_HIT_MIN_SCORE && score > coveredScore) { + covered = p; + coveredScore = score; + } + } } if (covered) { altsOf.get(placedOf.get(covered))?.push(alternateOf(h)); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first — how many per platform, how many already on disk — then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** — the same moment in the stream's YouTube upload (or Odysee) — and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`. +- **Cap a phrase montage at N clips, spread across the years.** `umtool new … --seed phrase --max N`, the New project form's **Max** and the phrase finder's **Max clips** keep N instances, each year's share in proportion to how often it was said there (at least one per year), preferring clips with no speaker change in the captions and spread through each year. The rest are listed in `phrase-scan.json`. - **The report-video test suite passes in the Docker image.** Run inside `archilyzer:r33-umtool` (Debian's ffmpeg 7.1), six report-to-video tests failed that pass on a newer ffmpeg. Four came from how the tests drove ffmpeg, not from the videos it renders: they now run the graphs the way a build does. One compared against an older ffmpeg's timing drift, which 7.1 does not show; it is now only checked where the drift happens. The sixth needs a git checkout, which an image does not include, and now says so and skips. Nothing a build renders changed. - **umtool scores who is speaking in each montage clip.** A montage's clip deck and its Cut tab have **Score the voices**: each clip's phrase (and a second either side, its speech only) is compared with the host's voice, and every Cut-tab row then reads `voice 0.43 · unsure` — likely, unsure or unlikely him — and the deck puts the doubtful clips first with their scores. The host's voice is the clips you ruled keep in the audition deck once there are three, or before that solo uploads of the channel found on disk (captioned, no speaker change in the captions, not a stream, no guest in the title, spread over the years); the picker beside the button chooses. It runs on this machine with the speaker model the diarization lane already uses — no network, no AI model — and takes about half a minute for 73 clips. It sorts and flags; whether it is him is still decided by ear. The scores are kept in `voice-match.json` beside the manifest, by the source moment, so a re-seeded montage keeps them. The same from a terminal: `umtool voice-match <project>`. Needs a restart of umtool. - **A montage's closing wall is the right length on older ffmpeg.** With ffmpeg 7.1 (the umtool Docker image), a tile did not hold its last frame after saying its phrase and did not wait for its turn, so the wall came out short of the length its plan gives (23 frames on the test cut) and, with groups, tiles vanished instead of freezing. The tiles now hold and wait on ffmpeg 7.1 as they do on newer versions; renders on the newer ffmpeg are unchanged. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10600,3 +10600,51 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri run and by the next. Engine: `VOICE_MATCH_PYTHON` / `_SCRIPT` / `_MODEL` (ENVIRONMENT.md), else `settings.diarization.python` / `.embModel` (read from `SETTINGS_FILE` or `<repo>/settings.json`), else `.diarize/`. The e2e runs `common/testing/audio/fakeSpeakerEmbed.mjs` with node. + +## Release 35 lane O1: montage operations in the app (verified 2026-10-19, branch `r35/montage-ops`) + +- **`alternates`** (common/lib/montage/phraseScan.mjs `foldHits`, both scanners): every instance in `instances` carries + `alternates: [{slug, videoId, start, end, platform, availability}]` (an empty list when none; ABSENT = a scan made + before release 35) — the other-channel hits folded into it: a twin's hit its preferred copy already has (attached + to the twin hit that scores best, ≥ `SAME_HIT_MIN_SCORE`; whether a hit is covered is release 34's rule), the hit a + `via` instance was placed from, and every `alsoIn` fold with that fold's own alternates. Deduped by + `<slug>/<videoId>`, the instance's own recording left out; `availability` null for the preferred channel, else + availability.json's. Everything else is release 34's answer: `fixtures/phraseScan.r34.json` (release 34's output on + the test corpus) == the new answer minus `alternates`. `dropped` carries none. +- **The cap**: `capInstances(instances, max)` → `{kept, skipped}` (both chronological, the given order). Year = the + date's first 4 digits (no date = its own year "~", last). `max ≥ years`: each year `max(1, floor(quota))` capped at + its count, then +1 by largest `quota − alloc` (ties: bigger year, then earlier), or −1 from a year > 1 with the + smallest `quota − alloc` (ties: bigger year, then later); `max < years`: one each for `spreadIndices(years, max)`. + Within a year the instances without `speakerCheck` first, `spreadIndices` = the middle of each of n equal + stretches. The scaffold's `max` (1…10000): `phrase-scan.json` gains `max` and `skippedByCap` (instance shape) after + `instances`; README and notes name it. No `max`: manifest + README byte-identical to release 34, phrase-scan.json + differs only by `alternates`. +- **`<project>/fetch-runs.json`** (umtool/lib/report/fetchWindows.mjs, one writer, in-process queue, tmp + rename, the + newest 50 kept): `{runs: [{at, bodyHash (sha256 of the body with sorted keys), dryRun, items, jobIds, summary: + {dryRun, groups[{platform, queueKey, items, storedUrlItems?}], cached[clipId], inFlight[{clipId, jobId}], + unresolved[{clipId, slug, id, error}], refused[{platform, items, error}], jobs[{platform, queueKey, jobId, items}]}, + jobs?: {<jobId>: {status, platform, failed[{slug, id, from, to, clipId, class, message}], at}}}]}`. A job's + `failed` is parsed from its whole log (`GET /api/jobs/<id>/log`, ungated) — the controller's ` ✗ <slug>/<id> + <from>–<to> (<clipId>): <class> — <message>` lines — once `GET /api/ops/job/<id>` says it ended + (done/failed/cancelled/interrupted); an ended job is never asked again. +- **The body** (`fetchWindowsBody`): `{requestedBy: "umtool:<project id>", manifest: <abs manifest path>, storedUrl: + "fallback", items: [{slug: clip.channel ?? provenance.channelSlug, id, from, to, clipId, pad, reason}]}`; from/to = + build-video `fetchSpan` (start − fetchPad … end + fetchPad, 2 dp; a phrase seed's fetchPad is 0); `pad` = fetchPad + when > 0 else 3 (provenance); `reason` = `--reason`, else "<title> montage" when any clip carries `montage`, else + the title. Skipped: a clip with no channel/video, and a clip ruled cut / not-him / read-aloud. Token: `agentToken()` + (WORKER_TOKEN, else editor/.env*); URL: ARCHILYZER_EDITOR_URL (default http://localhost:3001). +- **`fallbackFrom`** (umtool/lib/report/standIns.mjs): a switched clip carries `fallbackFrom: {channel, ownChannel?: + false, video, start, end, cutStart, cutEnd, cite, note, platform, reason}` (null for a field the clip lacked; + `reason` "403" when the refusal's message says 403, else its class) and `note` "from the <Platform> upload: the + <Platform> copy refused (<reason>)"; its channel/video/cut become the alternate's, start/end keep the clip's + margins, `montage.platform` the alternate's. `restoredClip` puts every field back (same key order). A candidate: + not on disk (`projectCache(...).isFetched`), refused (`refusedWindows`: failed classes except rate_limit / + unreachable / cut-failed / cancel(led), or the editor's `unresolved`; the newest word per clip), not already + switched, and an `eligibleAlternates` entry (availability null / public / unknown; not a refused recording; + ranked youtube 0, odysee or slug cornbreadman 1, else 2). Writes: `replaceManifest` op `stand-in` / + `restore-stand-in` (auto snapshot → Undo); `moveMontageRuling(dir, from, to)` (the rulings writer; nothing when + `from` has none or `to` has one); the voice-match row moved the same way (`writeVoiceMatch`). +- Surfaces: `/api/report/fetch-windows` (GET; POST `{project, action: "dry-run"|"start"|"follow"}`), + `/api/report/stand-ins` (GET plan; POST `{project, clips?}` | `{project, restore}`), `umtool fetch`, `umtool + fallback`; components `FetchWindowsPanel` (Cut tab, clip deck) and `MontageFetchTools` (clip deck: fetch + + stand-ins). The e2e stub's door is `umtool/e2e/fixtures/editor-stub-fetch-windows.mjs` (a `vrefuse*` id = a 403). diff --git a/plans/release-35/montage-ops.md b/plans/release-35/montage-ops.md @@ -0,0 +1,60 @@ +# Release 35 lane O1 — montage operations in the app (`r35/montage-ops`), as shipped + +The steps the orchestrator did by hand for the slow-news montage — a scan, no cap, a fetch-windows body built in +python, a second fetch for refused Rumble windows from the same stream's other upload — as app operations, each with a +CLI and a UI button, deterministic, no model. + +## What + +1. **Alternates** (common/lib/montage/phraseScan.mjs): every instance records `alternates: [{slug, videoId, start, end, + platform, availability}]` — the other-channel hits folded into it (a covered twin hit, attached to the twin hit that + scores best; the `via` source; every `alsoIn` fold). Everything else is release 34's answer + (`fixtures/phraseScan.r34.json`, equivalence-tested for both scanners). +2. **The cap**: `capInstances` + the phrase seed's `max` (`umtool new … --seed phrase --max N`, the New project form's + **Max**, the phrase finder's **Max clips**). `phrase-scan.json` gains `max` and `skippedByCap`; README and notes name + it. No `max`: manifest + README byte-identical to release 34. +3. **Fetch windows**: `umtool fetch <project> [--body | --dry-run | --wait | --status] [--reason R]`, the + `/api/report/fetch-windows` route and `FetchWindowsPanel` (Cut tab, clip deck). Runs in `<project>/fetch-runs.json`. +4. **Stand-ins**: `umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>]`, `/api/report/stand-ins`, + `MontageFetchTools` on the clip deck (Use stand-in / Use all / Restore). `fallbackFrom` on the clip; ruling and + voice-match row moved with it (`moveMontageRuling`, the rulings' writer). + +Shapes: plans/FACTS.md, "Release 35 lane O1". + +## Commits + +| sha | | +|---|---| +| 07caf3eb | common: the phrase scan records each instance's alternates (slice 1) | +| f5914aeb | umtool: the phrase seed's cap `--max N` (slice 2) | +| 7992d406 | umtool: Fetch windows — `umtool fetch` and the button (slice 3) | +| be45001b | common: a covered twin hit's alternate goes to the best-scoring twin hit (slice 1 follow-up) | +| aa9b8ad9 | umtool: stand-ins — `umtool fallback`, Use stand-in / Restore (slice 4) | +| (this) | plans + docs: record, FACTS, CHANGELOG, cli.md, report-video.md | + +Slices 1–3 (07caf3eb..7992d406) were merged to main by the orchestrator as 9d0ab192. + +## Gates (all through r31-locked.sh) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean at 7992d406 and at aa9b8ad9. +- common: 4627 tests, 4625 pass, 0 fail, 2 skip (both points; the new tests are in phraseScan.test.ts +3 and + phraseScanMany.test.ts +2 — net count equal because the count was first taken after they were written). +- test:scripts: 1175 / 1171 pass / 4 skip at 7992d406 (+4 scaffold-phrase/fetchWindows tests); 1180 / 1176 pass / + 4 skip at aa9b8ad9 (+5 standIns tests). 0 fail. +- e2e `umtool/e2e/montage-ops.spec.ts`: **written, NOT run** — three attempts (10 min each, inside r31-locked6.sh) never + got the machine-wide heavy slot (held by other agents' e2e and builds; MemAvailable under the floor). Owed: one run. +- Checked on real data (read-only): `umtool fetch quartering-oopsie --body --reason "oopsie montage"` == the hand-built + `~/reports/quartering-oopsie/windows.json` (68 items; python dict equality); with no `--reason` all but the reason + ("Oopsie doopsie montage"). A release-34 scaffold (the primary checkout's module) vs this branch on a synthetic + corpus: video.manifest.json and README.md byte-identical; phrase-scan.json differs only by `alternates`. +- Stand-ins on a COPY of quartering-oopsie with a synthesized fetch-runs.json from its refusals (s23, s24, s27, s29, + s30, all the-quartering-rumble, 403): the re-scan (the scan predates alternates) finds each instance and **no + alternate for any** — no other channel's transcript says those moments, so `umtool fallback` reports "refused with + none" for all five. Correct, but it means oopsie's refused clips need another source. + +## Rulings followed + +- No model anywhere; every step has a UI button and a CLI. +- The editor fetches; umtool asks (WORKER_TOKEN, else editor/.env, never sent to the browser). +- The manifest is written only through `replaceManifest` (lock, auto snapshot, atomic); rulings through their writer. +- Fixtures synthetic; nothing under `~/reports` written (copies under the job's scratch). 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/docs/cli.md b/umtool/docs/cli.md @@ -25,7 +25,7 @@ Inbox cannot disagree about what is wrong with one. | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | | `index [--rebuild] [--prune] [--since MS] [--json]` | the cache | -| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]` | scaffold | +| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` | scaffold | | `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there | | `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch | | `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building | @@ -43,6 +43,8 @@ Inbox cannot disagree about what is wrong with one. | `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | | `takes styles [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | +| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. Every run is recorded in `<project>/fetch-runs.json`. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | +| `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in | | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -860,6 +860,43 @@ the picked take (or the one whole-cut take) again with them. A seed's `edits.json` (its `exclude` and `match` lists) is offered once as **Import earlier rulings**. The same writer is `umtool rulings` ([cli.md](cli.md)). +### Fetching the windows, and stand-ins + +A phrase seed's every clip needs its window on disk before anything plays or +renders. **Fetch windows** (the Cut tab, the clip deck; `umtool fetch <project>`) +asks the editor for all of them as one `fetch-windows` batch — the body is +`{requestedBy: "umtool:<project>", manifest: <its path>, storedUrl: "fallback", +items: [{slug, id, from, to, clipId, pad, reason}]}`, the window the build would +fetch (`start`–`end` for a phrase seed, whose `fetchPad` is 0), `pad` 3 as +provenance, `reason` "<title> montage". Clips ruled cut, not him or read aloud +are not asked for. The dry run says what the editor would do (the windows per +platform, those already on disk, those a job is already fetching, those it +cannot resolve); **Start** queues one paced job per platform and the panel +follows them to their end, naming each window a job failed. Every run is +recorded in `fetch-runs.json` beside the manifest. + +Some windows are refused for good: a Rumble video whose embed lookup answers 403 +on every try (per video — not the Cloudflare clearance), or a recording gone +from its platform. The phrase scan knows the other uploads of each moment: every +instance in `phrase-scan.json` lists its `alternates` (the other channels' hits +folded into it, each at its own moment). The clip deck then offers a **stand-in** +for each refused clip whose window is still missing — the first public +alternate, YouTube first, then Odysee or cornbreadman — and **Use stand-in** +switches the clip to it: its channel, video and moment become the alternate's +(the cut is the alternate's phrase, the window keeps the clip's margins), the +note says "from the YouTube upload: the Rumble copy refused (403)", and +`fallbackFrom` records everything it was. Its montage ruling and voice score +move to the new moment. **Restore** (or `umtool fallback <project> --restore +<clip>`) puts every field back, and the ruling with it. Then **Fetch windows** +again asks for the stand-ins' windows. A scan made before release 35 has no +`alternates`; the stand-in step scans the same channels again (the cue-text +cache makes it quick) to find them. + +A capped reel (`--max N`, the form's **Max**, the phrase finder's **Max clips**) +keeps N instances spread across the years in proportion to each year's count, +at least one for each year; the rest are in `phrase-scan.json` as +`skippedByCap`. + ### Who is speaking: the voice match A montage of one phrase is also a montage of everyone who said it near the host: 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; + } +}