commit 81be8df333d4f7d58b9250ad47a071165e8f62b0 parent 94d5e21dfd7e4d5afbd335d005c277bf4ec1bdcb Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Wed, 11 Nov 2026 07:24:43 -0500 windows: clip windows without a local channel -- a REMOTE-ONLY channel registered on first need, inert everywhere; a whole recording refused with its size; a media 403 asked once more; the cut's windows, stop before render (demo epic D1 item 5) fetch-windows takes `archive` (a CONNECTED archive's origin) and `allowWholeRecording`. A channel the editor does not hold is registered as a REMOTE-ONLY channel of that archive (controller/remoteOnlyChannel.ts): config only -- name and platform from its corpus.json, `remoteOnly`, `remoteArchive`, `remoteUrl`, `downloadMode: "manual"`, and NO `url`, so nothing that syncs a channel by its url can -- no listing sweep; answered in `registered` (a dry run registers nothing). Its windows are fetched on the paced queue as any other; its page URL comes from the archive's own record when the item has none. Another origin registers nothing and changes nothing. Inert everywhere a real channel is active, by one predicate (isRemoteOnlyChannel) at: the lanes (autoRunner listChannelMeta), the sync scheduler (due + the console's eligibility), Sync all, every pipeline action and the metadata scan (remoteOnlyRefusal), cleanup's cleanable channels, the storage watch, the index and stats builds, the site writer (never on a site), a research run's channel list, Create's channel picker; the channel list shows "remote only" (not "manual dl"), `pnpm ops channels` says kind "remote-only". Whole-recording platforms (Rumble): a remote-only channel's window is refused with the recording's length and estimated size until `allowWholeRecording`; umtool's chain shows the refusal and one press, "Fetch the whole recordings", runs the step again with it (umtool chain --allow-whole-recording). A transient media 403 (ffmpeg's "Server returned 403 Forbidden", googlevideo in D0) is asked once more after a pause before it counts toward the two-403 stop; never a Rumble 403; raises no cookie alert. The chain: Draft everything fetches the windows of the clips the drafted cut kept (`cut-windows`, from the manifest) instead of every citation's before it (its prepare goes on past evidence clips not fetched yet); "Make the video" keeps `windows` (its cut is every cited clip). The windows steps name the archive and each clip's page URL from its record when the sweep read one. "Stop before render" (ChainPanel, Create; --stop-before-render) ends a run before the voices. umtool's fetch and fetch-via-editor send the manifest's siteOrigin as `archive`. CHANNEL.md, COMMANDS.md, umtool/docs/cli.md regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Diffstat:
45 files changed, 1153 insertions(+), 83 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md @@ -39,6 +39,9 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `lastFullDownloadAt` | sync state | SYNC STATE. When a full download pass last completed (ISO time). | | `lastFullSweepAt` | sync state | SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk. | | `excludeFromBuild` | config | Leave this channel out of every site build. | +| `remoteOnly` | config | A REMOTE-ONLY channel: held only to fetch clip windows that a connected archive's citations name (settings.remoteArchives). Registered by the editor the first time a window of it is asked for, with no listing sweep. Inert: no sync, no lane, no cleanup, no auto-download, on no site, in no index build; the channel list shows it as remote-only. A whole-recording platform's window (Rumble) is refused with the recording's size until the ask says `allowWholeRecording`. | +| `remoteArchive` | config | A remote-only channel's archive: the origin whose corpus.json names it. | +| `remoteUrl` | config | A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: a remote-only channel has no `url`, so nothing syncs it. | | `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. | | `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. | | `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -174,7 +174,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` | | `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | -| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | +| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. "archive" (items only) names the CONNECTED archive the items cite (settings.remoteArchives): a channel this editor does not hold is registered as a remote-only channel of it (config only, no listing; answered in "registered"; a dry run registers nothing), and a remote-only channel's page URL comes from the archive's record. Its window on a whole-recording platform is refused with the recording's estimated size unless "allowWholeRecording": true. Another origin registers nothing. A media URL's transient 403 (googlevideo's) is asked once more after a pause before it counts toward the two-403 stop. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "<its version, as you saw it>", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` | | `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` | diff --git a/common/controller/autoRunner.test.ts b/common/controller/autoRunner.test.ts @@ -926,3 +926,37 @@ test("a manual-downloads channel projects no download work but keeps its transcr "side by side, only the automatic channel's backlog counts", ); }); + +// --- Remote-only: on no lane (demo epic D1) -------------------------------- +// +// A remote-only channel holds a connected archive's clip windows. Even with a +// video dir on disk and a report that lists work, no lane draws it. + +test("a remote-only channel is no lane's work, whatever its report lists", async () => { + const paths = pendingFixture(); + const transcribeOp = bucketLaneOperationId("transcription"); + const downloadOp = bucketLaneOperationId("download"); + const slug = "remote"; + const channelDir = path.join(paths.channelsDir, slug); + mkdirSync(path.join(channelDir, "data", `${slug}-on-disk`), { recursive: true }); + const config = { handling: "youtube", platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" }; + writeFileSync(path.join(channelDir, "config.json"), JSON.stringify(config)); + writeFileSync( + path.join(channelDir, "snapshot.json"), + JSON.stringify({ + generatedAt: new Date().toISOString(), + totals: { videos: 1, downloaded: 1, transcribed: 0 }, + buckets: { downloadedNoTranscript: [`${slug}-on-disk`] }, + undownloadedIds: [`${slug}-listed`], + backfill: { + ...(downloadOp ? { [downloadOp]: { ids: [`${slug}-listed`] } } : {}), + ...(transcribeOp ? { [transcribeOp]: { ids: [`${slug}-on-disk`] } } : {}), + }, + }), + ); + forgetChannelMedia(slug); + const ch = { slug, config: config as never }; + for (const lane of ["download", "transcription", "digest", "backfill"] as const) { + assert.equal(await laneTotal(lane, paths, [ch]), 0, `the ${lane} lane skips a remote-only channel`); + } +}); diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -1,6 +1,6 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; -import type { ChannelConfig } from "../lib/channelConfig"; +import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig"; import { mapConcurrent } from "../lib/concurrency"; import { getPaths } from "../lib/paths"; import { getSettings, type SiteSettings } from "../lib/settings"; @@ -397,6 +397,9 @@ async function listChannelMeta( return { meta: configs .filter(({ slug }) => !isChannelPaused(priority, slug, kind)) + // A REMOTE-ONLY channel (demo epic D1) is on no lane at all: it holds a + // connected archive's clip windows and nothing a lane could work on. + .filter(({ config }) => !isRemoteOnlyChannel(config)) // A MANUAL-DOWNLOADS CHANNEL is not on the download lane's list at all // (lib/manualDownloads.ts): its listing's backlog, its retries, its // metadata scan and its chat backlog are all things nobody asked for. diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -149,7 +149,7 @@ import { readPostAvailability, postsAvailabilityPath, } from "../lib/posts-server"; -import { isSocialChannel } from "../lib/channelConfig"; +import { isRemoteOnlyChannel, isSocialChannel } from "../lib/channelConfig"; import { publishedMemberSlugs } from "../lib/postsVisibility"; import { DIGESTS_MANIFEST_VERSION, @@ -445,6 +445,12 @@ async function scanSource( log(`Skipping channel ${ch.name}: excluded from build`); continue; } + // A remote-only channel (demo epic D1) holds an archive's clip windows, + // not a corpus of its own: it is in no index build. + if (isRemoteOnlyChannel(cfg)) { + log(`Skipping channel ${ch.name}: remote-only`); + continue; + } channels.set(ch.name, cfg); // A social channel carries posts, not videos: it has no data/ dir to walk, // and routing it through the video scan would only ever produce noise. Its diff --git a/common/controller/buildStats.test.ts b/common/controller/buildStats.test.ts @@ -814,3 +814,27 @@ test("(z) no write this file caused landed outside its temp root", () => { assert.deepEqual(outside, []); assert.ok(fsCalls.some((c) => c.write), "the spy saw the writes"); }); + +// demo epic D1: a remote-only channel's clip-window dirs are no corpus — in no +// index build and no stats build. +test("a remote-only channel is in no index and no stats build", async () => { + resetCorpus(); + seedVideo("own1"); + addCaptions("own1", "2026-07-11T12:00:00Z"); + writeJson(path.join(paths.channelsDir, "remote-ch", "config.json"), { + handling: "youtube", + name: "Remote", + platform: "youtube", + remoteOnly: true, + remoteArchive: "https://stub.test", + downloadMode: "manual", + }); + seedVideo("r1", "2026-07-11T11:00:00Z", {}, "remote-ch"); + addCaptions("r1", "2026-07-11T12:00:00Z", "remote-ch"); + const indexLog: string[] = []; + await buildIndex({ paths, onLog: (s) => indexLog.push(s) }); + assert.ok(indexLog.some((l) => /Skipping channel remote-ch: remote-only/.test(l)), indexLog.join("\n")); + const { byId } = await runStats(); + assert.ok(byId.has("own1")); + assert.equal(byId.has("r1"), false); +}); diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts @@ -61,7 +61,7 @@ import { readVideoFiles, } from "../lib/videoStatus"; import type { VideoStatus } from "../lib/stats"; -import type { ChannelConfig } from "../lib/channelConfig"; +import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig"; import { readChannelConfigFile } from "./channels"; import { inspectChannelMedia } from "../lib/channelMedia"; import { @@ -307,6 +307,8 @@ async function scanSource( continue; } if (cfg.excludeFromBuild) continue; + // A remote-only channel (demo epic D1) is in no build. + if (isRemoteOnlyChannel(cfg)) continue; channels.set(ch.name, cfg); // An unreadable text tier is not an empty channel (lib/channelMedia.ts): // the readdir below would fail and every one of its stats would be removed. diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -33,11 +33,20 @@ process.env.FAKE_ARGS_LOG = ARGS_LOG; await writeFile( BIN, `#!/usr/bin/env node -import { appendFileSync, writeFileSync } from "node:fs"; +import { appendFileSync, existsSync, writeFileSync } from "node:fs"; const args = process.argv.slice(2); appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n"); const url = args[args.length - 1]; const fail = (msg) => { process.stderr.write(msg + "\\n"); process.exit(1); }; +if (url.includes("/m403once")) { + // The media URL refuses the first ask of this URL only (demo epic D1). + const mark = process.env.FAKE_ARGS_LOG + "." + Buffer.from(url).toString("hex"); + if (!existsSync(mark)) { + writeFileSync(mark, "1"); + fail("[https @ 0x1] HTTP error 403 Forbidden\\nhttps://rr1.googlevideo.example/videoplayback Server returned 403 Forbidden (access denied)\\nERROR: ffmpeg exited with code 1"); + } +} +if (url.includes("/m403always")) fail("[https @ 0x1] HTTP error 403 Forbidden\\nhttps://rr1.googlevideo.example/videoplayback Server returned 403 Forbidden (access denied)\\nERROR: ffmpeg exited with code 1"); if (url.includes("/403")) fail("ERROR: [download] Got error: HTTP Error 403: Forbidden"); if (url.includes("/429")) fail("ERROR: [youtube] x: HTTP Error 429: Too Many Requests"); if (url.includes("/gone")) fail("ERROR: [youtube] x: Video unavailable. This video has been removed by the uploader"); @@ -836,3 +845,28 @@ test("one clock: a window held ON the map's clock is answered from the cache", a assert.equal(r.cached.length, 1); assert.equal(c.cuts.length, 0); }); + +// demo epic D1: a transient media 403 (googlevideo's) is asked once more after a pause. +test("a media URL's 403 is asked once more after a pause, and then fetched", async () => { + const h = harness(); + const before = await spawns(); + const r = await go(await corpus(), [item("v1", "/m403once")], h); + assert.equal(r.failed.length, 0); + assert.equal(r.fetched.length, 1); + assert.equal((await spawns()) - before, 2, "one retry"); + assert.deepEqual(h.rec.sleeps, [1000], "the pause before the retry (the run's gap here)"); + assert.deepEqual(h.rec.backoffs, []); +}); + +test("a media 403 that persists fails once, counts once toward the streak; a Rumble 403 is never retried", async () => { + const h = harness(); + const before = await spawns(); + const r = await go(await corpus(), [item("v1", "/m403always"), item("v2", "/ok")], h); + assert.equal(r.stopped, undefined, "one failed window is not a streak"); + assert.deepEqual(r.failed.map((f) => [f.item.id, f.class]), [["v1", "network"]]); + assert.equal((await spawns()) - before, 3, "v1 twice, v2 once"); + const { isTransientMedia403 } = await import("./fetchWindows"); + assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "youtube"), true); + assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "rumble"), false); + assert.equal(isTransientMedia403("ERROR: [download] Got error: HTTP Error 403: Forbidden", "youtube"), false); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -195,6 +195,21 @@ function testGapMs(): number | undefined { return Number.isFinite(raw) && raw > 0 ? raw : undefined; } +// A TRANSIENT MEDIA 403 (demo epic D1): the page answered and gave a media URL, +// and that URL refused the stream — ffmpeg's "Server returned 403 Forbidden" +// (googlevideo above all, measured in D0: one in ten windows, fine on a manual +// re-ask). That is the media host, not the platform turning us away and not a +// cookie that went stale (lib/serviceCookies.ts raises no alert for it): the +// window is asked ONCE more after a pause, before it counts toward the +// network streak. A Rumble 403 is its Cloudflare (and a removed video answers +// 403 too): never retried here. +const MEDIA_403 = /Server returned 403 Forbidden|HTTP error 403 Forbidden/; +export const MEDIA_403_RETRY_MS = 20_000; + +export function isTransientMedia403(message: string, platform: string): boolean { + return platform !== "rumble" && MEDIA_403.test(message) && !/\[Rumble/.test(message); +} + export type FetchWindowsItem = { slug: string; id: string; @@ -1148,6 +1163,23 @@ export async function fetchWindows({ out = await attempt({ ...stored, why: "rate-limited" }); } + // A TRANSIENT MEDIA 403 (the header above FetchWindowsItem): once more, + // after a pause, before it counts. + if (!out.ok && !usedStored && classOf(out.e) === "network" && isTransientMedia403((out.e as Error).message, platform)) { + const pause = gapMs ?? testGapMs() ?? Math.max(gap, MEDIA_403_RETRY_MS); + log(` ${label}: the media URL answered 403 — asking once more in ${Math.round(pause / 1000)}s.`); + await deps.sleep(pause, signal); + const after = interrupted(); + if (after) { + fail(item, "network", (out.e as Error).message); + done += 1; + progress(); + stop(after, i + 1); + break; + } + out = await attempt(null); + } + if (out.ok) { networkStreak = 0; // THE SYNC CHECK on what the fetch produced (the header): a desynced diff --git a/common/controller/remoteOnlyChannel.test.ts b/common/controller/remoteOnlyChannel.test.ts @@ -0,0 +1,118 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, mkdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + WHOLE_RECORDING_REFUSED, + archiveRecordOf, + ensureRemoteOnlyChannel, + estimateRecordingBytes, + wholeRecordingRefusal, +} from "./remoteOnlyChannel"; +import type { GetJson } from "../lib/remoteArchives-server"; +import type { Paths } from "../lib/paths"; +import { isRemoteOnlyChannel, remoteOnlyRefusal } from "../lib/channelConfig"; + +// demo epic D1 item 5: a channel cited from a connected archive is registered +// remote-only on first need — config only — and its records come from the archive. + +const ORIGIN = "https://stub.test"; +const DOCS: Record<string, unknown> = { + [`${ORIGIN}/corpus.json`]: { + spec: 6, + site: { id: "stub", title: "Stub" }, + channels: [ + { slug: "alpha", name: "Alpha", videoCount: 2, platform: "youtube", url: "https://www.youtube.com/@alpha", manifests: { transcripts: `${ORIGIN}/transcripts/alpha/manifest.json` } }, + { slug: "rum", name: "Rum", videoCount: 1, platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rum/manifest.json` } }, + ], + }, + [`${ORIGIN}/transcripts/alpha/manifest.json`]: { pageCount: 1, slugToPage: { a1: 0, a2: 0 } }, + [`${ORIGIN}/transcripts/alpha/page-0000.json`]: [ + { id: "a1", title: "One", duration: 600, webpageUrl: "https://www.youtube.com/watch?v=a1" }, + { id: "a2", title: "Two", duration: 7980, webpageUrl: "https://www.youtube.com/watch?v=a2" }, + ], +}; + +function fake(): GetJson & { asked: string[] } { + const asked: string[] = []; + const f = (async (url: string) => { + asked.push(url); + if (!(url in DOCS)) throw new Error(`${url} answered HTTP 404`); + return DOCS[url]; + }) as GetJson & { asked: string[] }; + f.asked = asked; + return f; +} + +function pool(): { paths: Paths; root: string } { + const root = mkdtempSync(path.join(tmpdir(), "remote-only-")); + return { root, paths: { channelsDir: path.join(root, "channels") } as unknown as Paths }; +} + +test("first need registers config only: remote-only, manual, the platform, no url", async () => { + const { paths, root } = pool(); + try { + const r = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: fake() }); + assert.equal(r.registered, true); + const onDisk = JSON.parse(readFileSync(path.join(paths.channelsDir, "alpha", "config.json"), "utf8")); + assert.deepEqual(onDisk, { + name: "Alpha", + handling: "youtube", + platform: "youtube", + remoteOnly: true, + remoteArchive: ORIGIN, + remoteUrl: "https://www.youtube.com/@alpha", + downloadMode: "manual", + }); + assert.equal("url" in onDisk, false, "nothing that syncs by url can sync it"); + assert.equal(isRemoteOnlyChannel(r.config), true); + assert.match(remoteOnlyRefusal("alpha", r.config)!, /alpha is a remote-only channel of https:\/\/stub\.test/); + // Second need: the one on disk, nothing read. + const f = fake(); + const again = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: f }); + assert.equal(again.registered, false); + assert.deepEqual(f.asked, []); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a channel held here is never touched; one the archive does not list is refused, nothing written", async () => { + const { paths, root } = pool(); + try { + mkdirSync(path.join(paths.channelsDir, "alpha"), { recursive: true }); + writeFileSync(path.join(paths.channelsDir, "alpha", "config.json"), JSON.stringify({ name: "Mine", handling: "youtube", url: "https://www.youtube.com/@alpha" })); + const r = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: fake() }); + assert.equal(r.registered, false); + assert.equal(r.config.name, "Mine"); + assert.equal(isRemoteOnlyChannel(r.config), false); + await assert.rejects(ensureRemoteOnlyChannel(paths, "nope", { origin: ORIGIN }, { getJson: fake() }), /lists no channel "nope"/); + assert.throws(() => readFileSync(path.join(paths.channelsDir, "nope", "config.json"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a cited record's page URL and length come from the archive", async () => { + const f = fake(); + assert.deepEqual(await archiveRecordOf(ORIGIN, "alpha", "a2", { getJson: f }), { + webpageUrl: "https://www.youtube.com/watch?v=a2", + duration: 7980, + title: "Two", + }); + assert.deepEqual(f.asked, [`${ORIGIN}/corpus.json`, `${ORIGIN}/transcripts/alpha/manifest.json`, `${ORIGIN}/transcripts/alpha/page-0000.json`]); + assert.equal(await archiveRecordOf(ORIGIN, "alpha", "zz", { getJson: fake() }), null); + assert.equal(await archiveRecordOf(ORIGIN, "rum", "r1", { getJson: fake() }), null); +}); + +test("a whole recording is refused with its length and estimated size, and the key that allows it", () => { + assert.equal(estimateRecordingBytes(3600, 720), 1_125_000_000); + assert.equal(estimateRecordingBytes(3600, 360), 360_000_000); + const msg = wholeRecordingRefusal({ platform: "rumble", slug: "rum", id: "r1", duration: 7980 }); + assert.ok(msg.startsWith(WHOLE_RECORDING_REFUSED)); + assert.match(msg, /Rumble windows are cut from the WHOLE recording/); + assert.match(msg, /rum\/r1 is 2:13:00 long, about 2\.5 GB \(estimated\)/); + assert.match(msg, /"allowWholeRecording": true/); + assert.match(wholeRecordingRefusal({ platform: "rumble", slug: "rum", id: "r1" }), /length is not known to its archive/); +}); diff --git a/common/controller/remoteOnlyChannel.ts b/common/controller/remoteOnlyChannel.ts @@ -0,0 +1,156 @@ +// A REMOTE-ONLY CHANNEL, registered on first need (demo epic D1 item 5). +// +// A sweep over a connected archive (settings.remoteArchives) cites moments of +// channels this editor does not hold. Its clip windows are still fetched HERE — +// the editor's paced queues, cookie policy and provenance — so the editor needs +// a channel to put them under. The first time a window of such a channel is +// asked for, with the archive named, the editor registers it: +// +// config only (`remoteOnly: true`, `remoteArchive`, `remoteUrl`, the +// platform, `downloadMode: "manual"`), and NO `url` — nothing that syncs a +// channel by its url can sync this one; no listing sweep is run. +// +// Every place a real channel is active skips it (lib/channelConfig.ts +// isRemoteOnlyChannel): the lanes, the sync scheduler, Sync all and every +// pipeline action, the metadata scan, cleanup, the storage watch, index and +// stats builds, the site writer, a research run's channel list. The channel +// list shows it as "remote only". +// +// A cited recording's page URL — what a window is fetched from — comes from +// the archive's own record (archiveRecordOf), since the editor holds no +// metadata for it; the ask may carry it too (umtool's chain sends it). +// +// A WHOLE-RECORDING PLATFORM (settings.clips.wholeRecordingPlatforms, Rumble): +// a window there is cut from the saved whole recording — for a channel this +// editor does not archive that is a whole download nobody planned. It is +// refused with the recording's size (wholeRecordingRefusal) until the ask says +// `allowWholeRecording: true` (one press: umtool's chain offers it). + +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { PLATFORM_VALUES, type Platform } from "../lib/platform"; +import { corpusUrl, manifestUrl, pageUrl } from "../lib/archive/contract"; +import { WHOLE_RECORDING_REFUSED, archiveOriginOf, type ConnectedArchive } from "../lib/remoteArchives"; +import { archiveChannelFacts, plainGetJson, type ArchiveChannelFacts, type GetJson } from "../lib/remoteArchives-server"; +import { createChannel, readChannelConfig } from "./channels"; + +export type RemoteOnlyDeps = { + // One JSON document over HTTP (the cached reader, item 6); a test's fake. + getJson?: GetJson; + facts?: (origin: string, slug: string, opts: { getJson?: GetJson }) => Promise<ArchiveChannelFacts>; +}; + +export class RemoteOnlyChannelError extends Error {} + +/** The config a remote-only channel is registered with, from its archive's facts. */ +export function remoteOnlyConfigOf(archive: Pick<ConnectedArchive, "origin">, facts: ArchiveChannelFacts): ChannelConfig { + const platform = facts.platform && (PLATFORM_VALUES as readonly string[]).includes(facts.platform) ? (facts.platform as Platform) : undefined; + return { + name: facts.name, + handling: platform === "youtube" ? "youtube" : "transcribe", + ...(platform ? { platform } : {}), + remoteOnly: true, + remoteArchive: archive.origin, + ...(facts.url ? { remoteUrl: facts.url } : {}), + downloadMode: "manual", + } as ChannelConfig; +} + +/** + * The channel's config: the one on disk, or — when there is none — a + * remote-only channel registered now from `archive`'s corpus.json. A channel + * the archive does not list is refused. + */ +export async function ensureRemoteOnlyChannel( + paths: Paths, + slug: string, + archive: Pick<ConnectedArchive, "origin">, + deps: RemoteOnlyDeps = {}, +): Promise<{ config: ChannelConfig; registered: boolean }> { + const have = await readChannelConfig(paths, slug); + if (have) return { config: have, registered: false }; + const facts = await (deps.facts ?? archiveChannelFacts)(archive.origin, slug, { getJson: deps.getJson }); + const config = remoteOnlyConfigOf(archive, facts); + try { + await createChannel(paths, slug, config); + } catch (e) { + // Two asks at once: the other registered it first. + const again = await readChannelConfig(paths, slug); + if (again) return { config: again, registered: false }; + throw e; + } + return { config: (await readChannelConfig(paths, slug)) ?? config, registered: true }; +} + +export type ArchiveRecord = { webpageUrl?: string; duration?: number; platform?: string; title?: string }; + +/** + * A recording's own record in its archive: the transcripts manifest's page for + * the id, then the record whose id matches — its page URL and duration. Null + * when the archive does not hold it. At most three documents, in order. + */ +export async function archiveRecordOf(origin: string, slug: string, id: string, deps: { getJson?: GetJson } = {}): Promise<ArchiveRecord | null> { + const base = archiveOriginOf(origin); + if (!base) return null; + const getJson = deps.getJson ?? plainGetJson(); + const corpus = (await getJson(corpusUrl(base)).catch(() => null)) as { channels?: { slug?: string; manifests?: { transcripts?: string } }[] } | null; + const entry = corpus?.channels?.find((c) => c?.slug === slug); + const at = entry?.manifests?.transcripts ?? manifestUrl("transcripts", slug, base); + const manifest = (await getJson(at).catch(() => null)) as { slugToPage?: Record<string, number> } | null; + const page = manifest?.slugToPage?.[id] ?? manifest?.slugToPage?.[`${slug}/${id}`]; + if (typeof page !== "number") return null; + const records = (await getJson(pageUrl("transcripts", slug, page, base)).catch(() => null)) as Record<string, unknown>[] | null; + const r = (Array.isArray(records) ? records : []).find((x) => x?.id === id); + if (!r) return null; + const s = (k: string) => (typeof r[k] === "string" && (r[k] as string).trim() ? (r[k] as string).trim() : undefined); + const duration = typeof r.duration === "number" && Number.isFinite(r.duration) ? r.duration : undefined; + const webpageUrl = s("webpageUrl"); + return { + ...(webpageUrl && /^https?:\/\//i.test(webpageUrl) ? { webpageUrl } : {}), + ...(duration !== undefined ? { duration } : {}), + ...(s("platform") ? { platform: s("platform") } : {}), + ...(s("title") ? { title: s("title") } : {}), + }; +} + +// A whole recording's size, ESTIMATED from its length: what the saved-video +// store's copy weighs at about this height. Approximate on purpose (no request +// is made to learn it): video of this kind runs ~0.8 Mb/s at 360p up to ~5 Mb/s +// at 1080p, audio included. +const MBPS_BY_HEIGHT: [number, number][] = [ + [360, 0.8], + [480, 1.2], + [720, 2.5], + [1080, 5], +]; + +export function estimateRecordingBytes(durationSec: number, maxHeight = 720): number { + const mbps = (MBPS_BY_HEIGHT.find(([h]) => maxHeight <= h) ?? MBPS_BY_HEIGHT[MBPS_BY_HEIGHT.length - 1])[1]; + return Math.round((durationSec * mbps * 1e6) / 8); +} + +const clock = (s: number) => { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = Math.floor(s % 60); + return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`; +}; +const gb = (bytes: number) => (bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1e6))} MB`); + +export { WHOLE_RECORDING_REFUSED }; + +/** + * The refusal of a remote-only channel's window on a whole-recording platform: + * the recording's length and estimated size, and the one key that fetches it. + */ +export function wholeRecordingRefusal(o: { platform: string; slug: string; id: string; duration?: number; maxHeight?: number }): string { + const name = o.platform.charAt(0).toUpperCase() + o.platform.slice(1); + const size = + o.duration !== undefined + ? `${o.slug}/${o.id} is ${clock(o.duration)} long, about ${gb(estimateRecordingBytes(o.duration, o.maxHeight))} (estimated)` + : `${o.slug}/${o.id}'s length is not known to its archive`; + return ( + `${WHOLE_RECORDING_REFUSED} ${name} windows are cut from the WHOLE recording, and ${o.slug} is a remote-only channel: ` + + `${size}. Send "allowWholeRecording": true to download it whole (once; its windows are cut from it).` + ); +} diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -63,6 +63,7 @@ import os from "node:os"; import { projectsRootFrom } from "../lib/projectsRoot.mjs"; import { originOfHandle } from "../lib/remoteArchives"; +import { isRemoteOnlyChannel } from "../lib/channelConfig"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; @@ -557,7 +558,10 @@ export type ReportDraftDeps = { // The editor's channels, as a research run lists them. async function editorChannelsOf(paths: Paths): Promise<EditorChannel[]> { - return (await listChannelConfigs(paths)).map(({ slug, config }) => { + // A remote-only channel (demo epic D1) is no channel of the editor's own — + // it holds an archive's clip windows — so a research run never lists it, or + // imports into it. + return (await listChannelConfigs(paths)).filter(({ config }) => !isRemoteOnlyChannel(config)).map(({ slug, config }) => { const c = config as Record<string, unknown>; const s = (k: string) => (typeof c[k] === "string" && c[k] ? (c[k] as string) : undefined); const kind = s("sourceKind") ?? (s("postFetcher") ? "posts" : s("handling")); diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts @@ -1,3 +1,4 @@ +import { isRemoteOnlyChannel } from "../lib/channelConfig"; import { getPaths, type Paths } from "../lib/paths"; import { withJsonFileLock } from "../lib/jsonFile-server"; import { @@ -212,6 +213,9 @@ export async function runStorageWatchPass( const pauseCauses = new Map<string, AutoPauseCause>(); for (const { slug, config } of configs) { + // A remote-only channel (demo epic D1) has no media drive to watch and no + // lane a pause would hold. + if (isRemoteOnlyChannel(config)) continue; const wasAutoPaused = Boolean(model.channels[slug]?.autoPaused); // ONE TIER PER CHANNEL (release 17): the drive its MEDIA is on — // `mediaDir`, or on a channel not yet migrated off the retired diff --git a/common/jobs/syncScheduler.test.ts b/common/jobs/syncScheduler.test.ts @@ -287,3 +287,10 @@ test("nextEligibleAfterFailure: the backoff only grows with the jitter", () => { assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 0), 30 * 60_000); assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 1), Math.ceil(30 * 60_000 * 1.25)); }); + +test("a remote-only channel never syncs, even with a url, and the console says so (demo epic D1)", () => { + const channels = [channel("own", 1 * DAY), channel("remote", 1 * DAY, { remoteOnly: true, remoteArchive: "https://stub.test" })]; + assert.deepEqual(due(channels).due, ["own"]); + const view = buildScheduleView({ channels, scheduler: scheduler(), state: emptySchedulerState(), now: NOW, priority: NO_MODEL }); + assert.deepEqual(view.map((v) => [v.slug, v.autoSyncEligible]), [["own", true], ["remote", false]]); +}); diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts @@ -1,4 +1,4 @@ -import type { ChannelConfig } from "../lib/channelConfig"; +import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig"; import type { SyncSchedulerSettings } from "../lib/settings"; import { type ChannelPriority, @@ -141,6 +141,8 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult { for (const { slug, config } of channels) { if (!config.url) continue; // not auto-sync material; no noise in the log + // A remote-only channel (demo epic D1) never syncs: it has no listing. + if (isRemoteOnlyChannel(config)) continue; // ONE SKIP. `excludeFromSync` is gone (S5); the document's `sync` tier is // what it became, and the migration turned each of the 15 channels that // carried the flag into `overrides: {sync: "paused"}`. Silent `continue` — @@ -280,6 +282,7 @@ export function buildScheduleView(input: { autoSyncEligible: scheduler.enabled && !!config.url && + !isRemoteOnlyChannel(config) && !isChannelPaused(priority, slug, "sync") && interval > 0, intervalMinutes: interval, diff --git a/common/lib/archiveCache-server.ts b/common/lib/archiveCache-server.ts @@ -0,0 +1,18 @@ +// THE ARCHIVE READS the editor makes for a connected archive (demo epic D1): +// corpus.json, a channel's transcripts manifest, a shard page — for a +// remote-only channel's facts and a cited record's page URL. One document at a +// time, never in parallel. Item 6 keeps them on disk. + +import { plainGetJson, type GetJson } from "./remoteArchives-server"; + +/** The editor's reader of archive documents. */ +export function cachedArchiveGetJson(): GetJson { + const get = plainGetJson(); + let chain: Promise<unknown> = Promise.resolve(); + // Sequential: each read waits for the one before it. + return (url) => { + const next = chain.then(() => get(url)); + chain = next.catch(() => {}); + return next; + }; +} diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -35,6 +35,30 @@ export function isSocialChannel( return config?.sourceKind === "social"; } +// A REMOTE-ONLY channel (demo epic D1): one the editor holds ONLY to fetch +// clip windows a connected archive's citations name — config only, no +// listing, no transcripts of its own. Inert everywhere a real channel is +// active: no sync, no lane, no cleanup, no auto-download, on no site, in no +// index build (every guard asks this predicate). +export function isRemoteOnlyChannel( + config: Pick<ChannelConfig, "remoteOnly"> | null | undefined, +): boolean { + return config?.remoteOnly === true; +} + +// The sentence every door that would list, sync or download a channel +// answers a remote-only one with; null for any other channel. +export function remoteOnlyRefusal( + slug: string, + config: Pick<ChannelConfig, "remoteOnly" | "remoteArchive"> | null | undefined, +): string | null { + if (!isRemoteOnlyChannel(config)) return null; + return ( + `${slug} is a remote-only channel${config?.remoteArchive ? ` of ${config.remoteArchive}` : ""}: ` + + "it holds that archive's clip windows only, and is never listed, synced or downloaded here" + ); +} + export type AudioFormat = "m4a" | "mp3" | "opus"; // Who owns audio extraction for a transcribe-handling download: @@ -244,6 +268,13 @@ export type ChannelConfig = { lastFullDownloadAt?: string; lastFullSweepAt?: string; excludeFromBuild?: boolean; + // A remote-only channel (isRemoteOnlyChannel): registered on first need for + // a connected archive's clip windows; `remoteArchive` is that archive's + // origin and `remoteUrl` the channel's page on its platform, as the archive + // named it (never `url`, so nothing that syncs a channel by its url can). + remoteOnly?: boolean; + remoteArchive?: string; + remoteUrl?: string; excludeFromCleanup?: boolean; syncIntervalMinutes?: number; fullSweepIntervalMinutes?: number; @@ -315,6 +346,16 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { lastFullSweepAt: "SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk.", excludeFromBuild: "Leave this channel out of every site build.", + remoteOnly: + "A REMOTE-ONLY channel: held only to fetch clip windows that a connected archive's citations name " + + "(settings.remoteArchives). Registered by the editor the first time a window of it is asked for, with no " + + "listing sweep. Inert: no sync, no lane, no cleanup, no auto-download, on no site, in no index build; the " + + "channel list shows it as remote-only. A whole-recording platform's window (Rumble) is refused with the " + + "recording's size until the ask says `allowWholeRecording`.", + remoteArchive: "A remote-only channel's archive: the origin whose corpus.json names it.", + remoteUrl: + "A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: " + + "a remote-only channel has no `url`, so nothing syncs it.", excludeFromCleanup: "Leave this channel's reclaimable bytes out of the aggregate \"cleanable data\" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes.", syncIntervalMinutes: @@ -538,6 +579,9 @@ export const CHANNEL_CONFIG_COERCIONS: { lastFullDownloadAt: str, lastFullSweepAt: str, excludeFromBuild: bool, + remoteOnly: (v) => (v === true ? true : undefined), + remoteArchive: trimmedNonBlank, + remoteUrl: trimmedNonBlank, excludeFromCleanup: bool, syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES), fullSweepIntervalMinutes: zeroOrClamped( diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -68,6 +68,9 @@ export const channelConfigObjectSchema = z.object({ lastFullDownloadAt: field("lastFullDownloadAt"), lastFullSweepAt: field("lastFullSweepAt"), excludeFromBuild: field("excludeFromBuild"), + remoteOnly: field("remoteOnly"), + remoteArchive: field("remoteArchive"), + remoteUrl: field("remoteUrl"), excludeFromCleanup: field("excludeFromCleanup"), syncIntervalMinutes: field("syncIntervalMinutes"), fullSweepIntervalMinutes: field("fullSweepIntervalMinutes"), diff --git a/common/lib/remoteArchives.ts b/common/lib/remoteArchives.ts @@ -174,3 +174,10 @@ export function findConnectedArchive(list: readonly ConnectedArchive[], origin: const want = archiveOriginOf(origin); return want ? (list.find((a) => a.origin === want) ?? null) : null; } + +/** + * The marker a remote-only channel's whole-recording refusal starts with + * (controller/remoteOnlyChannel.ts wholeRecordingRefusal): umtool's chain + * looks for it to offer the one-press override (`allowWholeRecording`). + */ +export const WHOLE_RECORDING_REFUSED = "whole recording refused:"; diff --git a/common/lib/site.ts b/common/lib/site.ts @@ -11,7 +11,7 @@ import { type SocialLink, } from "./settings"; import { socialLinksForSave } from "./socialLinks"; -import { parseChannelConfig } from "./channelConfig"; +import { isRemoteOnlyChannel, parseChannelConfig } from "./channelConfig"; import { isXSearchChannel } from "./xSearch/config"; import { readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; import { @@ -231,6 +231,25 @@ function storedSocialLinks(file: string): SocialLink[] { export const X_SEARCH_NOT_ON_A_SITE = (slug: string) => `${slug} is an X search channel: it is never put on a site.`; +export const REMOTE_ONLY_NOT_ON_A_SITE = (slug: string) => + `${slug} is a remote-only channel (a connected archive's clip windows): it is never put on a site.`; + +// The first member of `site` (or of its cited scope) that is a remote-only +// channel (demo epic D1), by its config.json — or null. +export function remoteOnlyChannelOnSite( + site: Pick<Site, "channels" | "citedChannels">, + paths: Paths, +): string | null { + if (!paths.channelsDir) return null; + const slugs = [...site.channels.map((c) => c.slug), ...(site.citedChannels ?? []).map((c) => c.slug)]; + for (const slug of slugs) { + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) continue; + const raw = readJsonFileSync(path.join(paths.channelsDir, slug, "config.json")); + if (raw.ok && isRemoteOnlyChannel(parseChannelConfig(raw.value))) return slug; + } + return null; +} + // The first member of `site` (or of its cited scope) that is an X search // channel, by its config.json — or null. One small read per member. export function xSearchChannelOnSite( @@ -278,6 +297,9 @@ export async function writeSite( // the one writer every site edit goes through. const searchChannel = xSearchChannelOnSite(site, paths); if (searchChannel) throw new Error(X_SEARCH_NOT_ON_A_SITE(searchChannel)); + // Nor a remote-only channel (demo epic D1): it has no corpus to publish. + const remoteOnly = remoteOnlyChannelOnSite(site, paths); + if (remoteOnly) throw new Error(REMOTE_ONLY_NOT_ON_A_SITE(remoteOnly)); // undefined socialLinks = inherit the global default; only validate/persist a // key when the site explicitly overrides (an array, even empty). // A link whose SVG is unchanged from the file on disk is kept as it is; a new diff --git a/common/lib/siteRemoteOnly.test.ts b/common/lib/siteRemoteOnly.test.ts @@ -0,0 +1,41 @@ +// demo epic D1: a remote-only channel is never put on a site (writeSite, the +// one writer every site edit goes through). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "site-remote-only-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const { getPaths } = await import("./paths"); +const { writeSite, REMOTE_ONLY_NOT_ON_A_SITE } = await import("./site"); +const paths = getPaths(); + +async function channel(slug: string, config: Record<string, unknown>) { + await mkdir(path.join(paths.channelsDir, slug), { recursive: true }); + await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ name: slug, handling: "youtube", ...config })); +} + +test("no site may carry a remote-only channel, as a member or a cited channel", async () => { + await channel("own", { url: "https://www.youtube.com/@own" }); + await channel("remote", { platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" }); + const site = { + siteId: "demo-site", + siteTitle: "Demo", + siteDescription: "", + headerTitle: "Demo", + homeTagline: "", + groups: [{ id: "default", name: "All", selectedByDefault: true }], + defaultGroupId: "default", + channels: [{ slug: "own", groupId: "default" }], + }; + await writeSite(site as never, paths); + await assert.rejects(writeSite({ ...site, channels: [...site.channels, { slug: "remote", groupId: "default" }] } as never, paths), { + message: REMOTE_ONLY_NOT_ON_A_SITE("remote"), + }); + await assert.rejects(writeSite({ ...site, citedChannels: [{ slug: "remote" }] } as never, paths), { message: REMOTE_ONLY_NOT_ON_A_SITE("remote") }); +}); diff --git a/common/views/channelRow.test.ts b/common/views/channelRow.test.ts @@ -181,3 +181,13 @@ test("channelVolumeOf: no mediaDir is internal, a named root wins, else unnamed" label: "Big disk", }); }); + +test("a remote-only channel's row says so, with its archive, and is not 'manual dl' (demo epic D1)", () => { + const remote = buildChannelRowView( + input({ config: { handling: "youtube", name: "Remote", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" } as ChannelConfig }), + ); + assert.equal(remote.remoteOnly, "https://stub.test"); + assert.equal(remote.manualDownloads, false); + assert.equal(remote.hasUrl, false); + assert.equal(buildChannelRowView(input()).remoteOnly, null); +}); diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts @@ -1,5 +1,5 @@ import { channelDownloadsAreManual } from "../lib/manualDownloads"; -import { isSocialChannel, type ChannelConfig } from "../lib/channelConfig"; +import { isRemoteOnlyChannel, isSocialChannel, type ChannelConfig } from "../lib/channelConfig"; import type { ChannelSnapshot } from "../controller/channelSnapshot"; import type { ChannelMediaLocation } from "../lib/channelMedia"; import { mediaHoldText } from "../lib/channelMediaHold"; @@ -120,6 +120,10 @@ export type ChannelRowView = { // the channel by design and its `work.undownloaded` is 0 — the rack says so, // so a long, mostly undownloaded listing is not read as a stalled channel. manualDownloads: boolean; + // A REMOTE-ONLY channel (lib/channelConfig.ts isRemoteOnlyChannel, demo epic + // D1): the archive it holds clip windows for — its origin — or null for any + // other channel. The list says so; nothing syncs or downloads it. + remoteOnly: string | null; // WHICH VOLUME THE MEDIA IS ON, as an id a filter can name: a location id, // "internal" for the corpus volume, or "" for a mediaDir under a root nobody // named. (The text is on the corpus volume whatever this says.) @@ -231,7 +235,8 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView { } : null, mediaHold: i.media ? mediaHoldText(i.media.status) : null, - manualDownloads: channelDownloadsAreManual(i.config), + manualDownloads: channelDownloadsAreManual(i.config) && !isRemoteOnlyChannel(i.config), + remoteOnly: isRemoteOnlyChannel(i.config) ? (i.config.remoteArchive ?? "") : null, volumeId: i.volume.id, volumeLabel: i.volume.label, mediaBytes: snap?.totalMediaBytes ?? null, diff --git a/editor/app/api/ops/channels/route.ts b/editor/app/api/ops/channels/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels"; -import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; +import { isRemoteOnlyChannel, isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { siteChannelIndex } from "yt-dlp-transcript-common/lib/site"; import { opsAuth } from "../_lib"; @@ -32,13 +32,15 @@ export async function GET(request: Request) { channels: rows.map(({ slug, config }) => ({ slug, name: config.name ?? slug, - kind: isSocialChannel(config) ? "social" : "video", + // "remote-only" (demo epic D1): a connected archive's clip windows only. + kind: isRemoteOnlyChannel(config) ? "remote-only" : isSocialChannel(config) ? "social" : "video", platform: config.platform ?? null, handling: config.handling, url: config.url ?? null, sites: sitesOf.get(slug) ?? [], ...(config.excludeFromBuild ? { excludeFromBuild: true } : {}), ...(config.excludeFromCleanup ? { excludeFromCleanup: true } : {}), + ...(isRemoteOnlyChannel(config) && config.remoteArchive ? { remoteArchive: config.remoteArchive } : {}), })), }); } diff --git a/editor/app/api/ops/fetch-windows/route.remote.test.ts b/editor/app/api/ops/fetch-windows/route.remote.test.ts @@ -0,0 +1,96 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/fetch-windows/route.remote.test.ts" +// +// demo epic D1 item 5: a window cited from a CONNECTED archive, of a channel +// this editor does not hold. The archive is a fake fetch (no request leaves +// the process); no job is queued — every run here ends refused or unresolved. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-windows-remote-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +delete process.env.TRANSCRIPT_SITE_URL; +const ORIGIN = "https://stub.test"; +await writeFile( + process.env.SETTINGS_FILE, + JSON.stringify({ remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }), +); + +const DOCS: Record<string, unknown> = { + [`${ORIGIN}/corpus.json`]: { + spec: 6, + site: { id: "stub", title: "Stub" }, + channels: [ + { slug: "yt-remote", name: "YT Remote", videoCount: 1, platform: "youtube", url: "https://www.youtube.com/@ytr", manifests: { transcripts: `${ORIGIN}/transcripts/yt-remote/manifest.json` } }, + { slug: "rb-remote", name: "RB Remote", videoCount: 1, platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rb-remote/manifest.json` } }, + ], + }, + [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { pageCount: 1, slugToPage: { rb9: 0 } }, + [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 5400, webpageUrl: "https://rumble.com/vrb9-x.html" }], +}; +const asked: string[] = []; +globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = String(input); + asked.push(url); + if (!(url in DOCS)) return new Response("not found", { status: 404 }); + return new Response(JSON.stringify(DOCS[url]), { status: 200 }); +}) as typeof fetch; + +const { POST } = await import("./route"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function post(body: Record<string, unknown>) { + const res = await POST( + new Request("http://localhost/api/ops/fetch-windows", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> & { error?: string } }; +} + +type Unresolved = { item: { slug: string }; error: string }[]; + +test("a dry run names the channel it would register, and registers nothing", async () => { + const r = await post({ requestedBy: "test", archive: ORIGIN, dryRun: true, items: [{ slug: "yt-remote", id: "v1", from: 1, to: 5, webpageUrl: "https://www.youtube.com/watch?v=v1" }] }); + assert.equal(r.status, 200, r.json.error); + assert.deepEqual(r.json.registered, ["yt-remote"]); + assert.match((r.json.unresolved as Unresolved)[0].error, /would register it as a remote-only channel of https:\/\/stub\.test/); + await assert.rejects(readFile(path.join(ROOT, "channels", "yt-remote", "config.json"))); + assert.deepEqual(asked, [], "a dry run reads no archive either"); +}); + +test("an origin not connected registers nothing, and the refusal names the connect", async () => { + const r = await post({ requestedBy: "test", archive: "https://elsewhere.test", dryRun: true, items: [{ slug: "yt-remote", id: "v1", from: 1, to: 5 }] }); + assert.equal(r.status, 200, r.json.error); + assert.deepEqual(r.json.registered, []); + assert.match((r.json.unresolved as Unresolved)[0].error, /not found — https:\/\/elsewhere\.test is not a connected archive: connect it/); +}); + +test("a run registers the remote-only channel from the archive, and refuses its Rumble whole recording with the size", async () => { + const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] }); + assert.equal(r.status, 200, r.json.error); + assert.deepEqual(r.json.registered, ["rb-remote"]); + assert.deepEqual(r.json.jobIds, [], "nothing queued"); + const error = (r.json.unresolved as Unresolved)[0].error; + assert.match(error, /^whole recording refused: Rumble windows are cut from the WHOLE recording/); + assert.match(error, /rb-remote\/rb9 is 1:30:00 long, about 1\.7 GB \(estimated\)/); + const config = JSON.parse(await readFile(path.join(ROOT, "channels", "rb-remote", "config.json"), "utf8")); + assert.deepEqual(config, { name: "RB Remote", handling: "transcribe", platform: "rumble", remoteOnly: true, remoteArchive: ORIGIN, downloadMode: "manual" }); + // Its page URL came from the archive's record (the item had none). + assert.ok(asked.includes(`${ORIGIN}/transcripts/rb-remote/page-0000.json`)); + // The allowance, as a dry run: planned on Rumble's download queue, the archive's URL. + const allowed = await post({ requestedBy: "test", archive: ORIGIN, allowWholeRecording: true, dryRun: true, items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] }); + assert.equal(allowed.status, 200, allowed.json.error); + const groups = allowed.json.groups as { platform: string; queueKey: string; items: { webpageUrl: string }[] }[]; + assert.equal(groups.length, 1); + assert.equal(groups[0].platform, "rumble"); + assert.equal(groups[0].items[0].webpageUrl, "https://rumble.com/vrb9-x.html"); +}); diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts @@ -35,7 +35,8 @@ export const dynamic = "force-dynamic"; // POST { siteId, maxHeight?, storedUrl?, wholeRecording?, dryRun? } // | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl?, force? }, …], -// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?, dryRun? } +// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?, +// archive?, allowWholeRecording?, dryRun? } // dryRun -> { ok, dryRun: true, groups: [{ platform, queueKey, items }], // cached, inFlight, unresolved[, onDisk, unfetchable] } // else -> { ok, dryRun: false, jobs: [{ platform, queueKey, jobId, items }], @@ -75,6 +76,16 @@ export const dynamic = "force-dynamic"; // `"wholeRecording": false` fetches every window of this run by a remote seek // instead, as before. // +// `archive` (items only; demo epic D1): the connected archive the items cite +// (settings.remoteArchives — any other origin is refused). A channel this +// editor does not hold is then REGISTERED as a remote-only channel of it +// (config only, no listing; answered in `registered`) and its windows fetched +// on the paced queue as any other; a remote-only channel's page URL comes +// from the archive's record when the item has none. A remote-only channel's +// window on a whole-recording platform (Rumble) is unresolved with the +// recording's estimated size unless `"allowWholeRecording": true`. A dry run +// registers nothing (it names who would be). +// // A big list goes in a file: `pnpm ops fetch-windows --file list.json`. const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"]; @@ -182,7 +193,7 @@ function optMaxHeight(body: OpsBody): number | undefined { export async function POST(request: Request) { return ops( request, - ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "dryRun"], + ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "archive", "allowWholeRecording", "dryRun"], async (body) => { const maxHeight = optMaxHeight(body); const storedUrl = optStoredUrl(body); @@ -196,7 +207,7 @@ export async function POST(request: Request) { let result: Awaited<ReturnType<typeof fetchWindowsAction>>; if (body.siteId !== undefined) { // A site's windows say who asked themselves (the reports, by site). - for (const k of ["requestedBy", "manifest", "minGapSeconds"]) { + for (const k of ["requestedBy", "manifest", "minGapSeconds", "archive", "allowWholeRecording"]) { if (body[k] !== undefined) { throw new OpsInputError(`"${k}" goes with "items"; a site's windows name the site`); } @@ -221,6 +232,8 @@ export async function POST(request: Request) { storedUrl, dryRun, ...(minGapSeconds !== undefined ? { minGapSeconds } : {}), + ...(optString(body, "archive")?.trim() ? { archive: optString(body, "archive")!.trim() } : {}), + ...(optBool(body, "allowWholeRecording") === true ? { allowWholeRecording: true } : {}), ...seek, }); } else { diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -1,7 +1,7 @@ "use server"; import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads"; -import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; +import { isSocialChannel, remoteOnlyRefusal } from "yt-dlp-transcript-common/lib/channelConfig"; import { fetchPostsAction } from "./socialActions"; import path from "node:path"; import { safeRevalidate } from "../../lib/safeRevalidate"; @@ -154,6 +154,9 @@ async function runPipelineAction( if (!channelConfig) { return { ok: false, error: `Channel "${slug}" not found` }; } + // A REMOTE-ONLY channel (demo epic D1) is never listed, synced or downloaded. + const remoteOnly = remoteOnlyRefusal(slug, channelConfig); + if (remoteOnly) return { ok: false, info: true, error: remoteOnly }; if (!channelConfig.url) { return { ok: false, error: "Channel has no `url` configured" }; } @@ -445,6 +448,8 @@ export async function runMetadataScanAction( if (!channelConfig) { return { ok: false, error: `Channel "${slug}" not found` }; } + const remoteOnly = remoteOnlyRefusal(slug, channelConfig); + if (remoteOnly) return { ok: false, info: true, error: remoteOnly }; if (!channelConfig.url) { return { ok: false, error: "Channel has no `url` configured" }; } diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -61,6 +61,14 @@ import { type StreamActionResult, } from "yt-dlp-transcript-common/jobs/streamCommand"; import { safeRevalidate } from "../../../lib/safeRevalidate"; +import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; +import { connectedArchives, findConnectedArchive, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { + archiveRecordOf, + ensureRemoteOnlyChannel, + wholeRecordingRefusal, +} from "yt-dlp-transcript-common/controller/remoteOnlyChannel"; +import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server"; // FETCH A LIST OF CLIP WINDOWS through the managed path, as ONE JOB PER // PLATFORM QUEUE (controller/fetchWindows.ts walks each one, paced). @@ -122,6 +130,15 @@ export type FetchWindowsRequest = { minGapSeconds?: number; // false: every window by a remote seek, the whole-recording platforms' too. wholeRecording?: boolean; + // THE ARCHIVE THE ITEMS CITE (demo epic D1): a connected archive's origin + // (settings.remoteArchives). A channel this editor does not hold is then + // registered as a REMOTE-ONLY channel of it (controller/remoteOnlyChannel.ts) + // instead of refused, and a remote-only channel's page URL comes from the + // archive's record. A dry run registers nothing. + archive?: string; + // A remote-only channel's window on a whole-recording platform (Rumble) is + // refused with the recording's size unless this is true. + allowWholeRecording?: boolean; }; export type FetchWindowsUnresolved = { item: FetchWindowsItem; error: string }; @@ -152,6 +169,9 @@ export type FetchWindowsActionResult = // Windows a queued or running job will already write, and that job. inFlight: FetchWindowsInFlight[]; unresolved: FetchWindowsUnresolved[]; + // Channels registered as remote-only for these windows (a dry run: the + // ones that would be), each once. + registered: string[]; }; export type FetchWindowsInFlight = { item: FetchWindowsItem; jobId: string }; @@ -185,11 +205,13 @@ async function planFetchWindows( maxHeight: number | undefined, storedMode: StoredUrlMode, wholeRecording?: boolean, + remote: { archive?: ConnectedArchive | null; unconnected?: string; allowWholeRecording?: boolean; dryRun?: boolean } = {}, ): Promise<{ groups: FetchWindowsGroup[]; cached: FetchWindowsItem[]; inFlight: FetchWindowsInFlight[]; unresolved: FetchWindowsUnresolved[]; + registered: string[]; // The planned items (as grouped) whose record stores a trusted media URL. stored: Set<FetchWindowsItem>; }> { @@ -201,6 +223,10 @@ async function planFetchWindows( const inFlight: FetchWindowsInFlight[] = []; const unresolved: FetchWindowsUnresolved[] = []; const stored = new Set<FetchWindowsItem>(); + const registered: string[] = []; + // A slug the archive could not register, with why (asked once per run). + const unregistrable = new Map<string, string>(); + const getJson = cachedArchiveGetJson(); const live = getRegistry().list(); for (const item of dedupeFetchWindowsItems(items)) { const problem = itemProblem(item); @@ -211,9 +237,36 @@ async function planFetchWindows( if (!configs.has(item.slug)) { configs.set(item.slug, await readChannelConfig(paths, item.slug)); } - const config = configs.get(item.slug); + let config = configs.get(item.slug); + // NOT HELD HERE, CITED FROM A CONNECTED ARCHIVE (demo epic D1): registered + // as a remote-only channel of it, config only — or, in a dry run, said. + if (!config && remote.archive && !unregistrable.has(item.slug)) { + if (remote.dryRun) { + if (!registered.includes(item.slug)) registered.push(item.slug); + unresolved.push({ item, error: `Channel "${item.slug}" is not held here: the run would register it as a remote-only channel of ${remote.archive.origin}` }); + continue; + } + try { + const r = await ensureRemoteOnlyChannel(paths, item.slug, remote.archive, { getJson }); + config = r.config; + configs.set(item.slug, config); + if (r.registered && !registered.includes(item.slug)) registered.push(item.slug); + } catch (e) { + unregistrable.set(item.slug, (e as Error).message); + } + } if (!config) { - unresolved.push({ item, error: `Channel "${item.slug}" not found` }); + const why = unregistrable.get(item.slug); + unresolved.push({ + item, + error: + `Channel "${item.slug}" not found` + + (why + ? `, and it could not be registered from its archive: ${why}` + : remote.unconnected + ? ` — ${remote.unconnected} is not a connected archive: connect it (/sites → Connected archives, or pnpm ops archives {"connect": …}) to fetch its windows here` + : ""), + }); continue; } // The item names a RECORD; its directory may be another id — a Twitch @@ -292,9 +345,16 @@ async function planFetchWindows( continue; } } + // A REMOTE-ONLY channel has no metadata or playlist of its own: the page + // URL is the ask's, else its archive's record. + const record = + isRemoteOnlyChannel(config) && config.remoteArchive + ? await archiveRecordOf(config.remoteArchive, item.slug, item.id, { getJson }).catch(() => null) + : null; const url = item.webpageUrl?.trim() || - (await findVideoSourceUrl(paths, item.slug, dirId, config)); + record?.webpageUrl || + (isRemoteOnlyChannel(config) ? null : await findVideoSourceUrl(paths, item.slug, dirId, config)); if (!url) { unresolved.push({ item, @@ -310,6 +370,15 @@ async function planFetchWindows( // only itself. const platform = detectPlatform(url) ?? "unknown"; const whole = wholeRecordingFor(settings, platform, item, wholeRecording); + // A remote-only channel's whole recording is a download nobody planned: + // refused with its size until the ask allows it (one press in umtool). + if (whole && isRemoteOnlyChannel(config) && !remote.allowWholeRecording) { + unresolved.push({ + item, + error: wholeRecordingRefusal({ platform, slug: item.slug, id: item.id, ...(record?.duration !== undefined ? { duration: record.duration } : {}), ...(maxHeight ? { maxHeight } : {}) }), + }); + continue; + } const queueKey = resolveQueueKey( whole ? queueKeyForUrl(url) : clipWindowQueueKey(queueKeyForUrl(url)), queueOverride, @@ -328,7 +397,7 @@ async function planFetchWindows( } groups.set(queueKey, group); } - return { groups: [...groups.values()], cached, inFlight, unresolved, stored }; + return { groups: [...groups.values()], cached, inFlight, unresolved, stored, registered }; } // The door each group passes before its job is queued: the platform's hold, @@ -455,14 +524,28 @@ export async function fetchWindowsAction( }; } const storedMode = req.storedUrl ?? "never"; - const { groups, cached, inFlight, unresolved, stored } = await planFetchWindows( + // The archive the items cite: only a CONNECTED one registers anything. Any + // other origin (a site's own, an archive not connected) registers nothing — + // a channel held here is fetched as always, one not held is refused, naming + // the connect that would register it. + const archive: ConnectedArchive | null = req.archive?.trim() + ? findConnectedArchive(connectedArchives(getSettings().remoteArchives), req.archive) + : null; + const { groups, cached, inFlight, unresolved, stored, registered } = await planFetchWindows( req.items, req.queueKey, req.maxHeight, storedMode, req.wholeRecording, + { + archive, + ...(req.archive?.trim() && !archive ? { unconnected: req.archive.trim() } : {}), + allowWholeRecording: req.allowWholeRecording === true, + dryRun: req.dryRun === true, + }, ); - const base = { groups, cached, inFlight, unresolved, jobs: [], refused: [] }; + if (registered.length && !req.dryRun) safeRevalidate(["/channels"]); + const base = { groups, cached, inFlight, unresolved, registered, jobs: [], refused: [] }; if (req.dryRun) return { ok: true, dryRun: true, ...base }; if (groups.length === 0) return { ok: true, dryRun: false, ...base }; @@ -536,7 +619,7 @@ export async function fetchWindowsAction( error: refused.map((r) => `${r.platform}: ${r.error}`).join("; "), }; } - return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, jobs, refused }; + return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, registered, jobs, refused }; } export type FetchMissingEvidenceResult = @@ -600,6 +683,7 @@ async function fetchMissingFor( cached: [], inFlight: [], unresolved: [], + registered: [], ...extra, }; } diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -1,5 +1,6 @@ "use server"; +import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; @@ -638,6 +639,7 @@ export async function syncAllChannelsAction( skip: async (slug) => { const config = bySlug.get(slug); if (!config?.url) return "no url"; + if (isRemoteOnlyChannel(config)) return "remote-only"; if (isChannelPaused(priority, slug, "sync")) return "paused for sync"; if (active.has(slug)) return "already running"; const media = await inspectChannelMedia(paths, slug, config); diff --git a/editor/app/channels/components/ChannelTierSelect.tsx b/editor/app/channels/components/ChannelTierSelect.tsx @@ -67,6 +67,8 @@ export type ChannelTierSelectProps = { // A manual-downloads channel (lib/manualDownloads.ts): the download lane // skips it by design, so its rack row says so rather than looking stalled. manualDownloads?: boolean; + // A remote-only channel's archive origin (demo epic D1), else null/undefined. + remoteOnly?: string | null; disabled?: boolean; }; @@ -98,6 +100,7 @@ export default function ChannelTierSelect({ autoPausedReason = null, mediaHold = null, manualDownloads = false, + remoteOnly = null, disabled = false, }: ChannelTierSelectProps): React.ReactNode { const [pending, startTransition] = useTransition(); @@ -213,6 +216,17 @@ export default function ChannelTierSelect({ <span className="sr-only"> — {mediaHold}</span> </span> )} + {remoteOnly !== null && remoteOnly !== undefined && ( + <span + role="note" + aria-label={`remote-only channel ${slug}`} + title={`Remote-only: holds clip windows of ${remoteOnly || "a connected archive"}; never listed, synced or downloaded here.`} + className="rounded-full border border-border px-1.5 text-[10px] uppercase tracking-wide text-muted-foreground" + > + remote only + <span className="sr-only"> — holds clip windows of {remoteOnly || "a connected archive"}</span> + </span> + )} {manualDownloads && ( <span role="note" diff --git a/editor/app/channels/components/channelColumns.tsx b/editor/app/channels/components/channelColumns.tsx @@ -180,6 +180,7 @@ export const CHANNEL_COLUMNS: Record< autoPausedReason={c.priority.autoPausedReason} mediaHold={c.mediaHold} manualDownloads={c.manualDownloads} + remoteOnly={c.remoteOnly} /> ), }), diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts @@ -1,3 +1,4 @@ +import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; import type { ChannelBrief } from "yt-dlp-transcript-common/controller/channels"; import { getChannelBriefs } from "../../lib/requestCache"; @@ -234,6 +235,8 @@ export async function cleanableChannels( const channels = await getChannelBriefs(paths); const rows = channels.map((channel) => { if (channel.config.excludeFromCleanup) return null; + // A remote-only channel (demo epic D1) has nothing a cleanup sweeps. + if (isRemoteOnlyChannel(channel.config)) return null; const snap = channel.snapshot; const bytes = transcribedBytesOf(snap); const count = snap?.buckets.transcribedWithAudio?.length ?? 0; diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1840,6 +1840,15 @@ export function usage() { " fetches in place of the platform's floor (Rumble's 120 s); still jittered", " up to half again. Shorter than the default risks Rumble's IP-wide", " Cloudflare challenge; a Retry keeps it.", + ' "archive" (items only) names the CONNECTED archive the items cite', + " (settings.remoteArchives): a channel this editor does not hold is", + ' registered as a remote-only channel of it (config only, no listing;', + ' answered in "registered"; a dry run registers nothing), and a remote-only', + " channel's page URL comes from the archive's record. Its window on a", + " whole-recording platform is refused with the recording's estimated size", + ' unless "allowWholeRecording": true. Another origin registers nothing.', + " A media URL's transient 403 (googlevideo's) is asked once more after a", + " pause before it counts toward the two-403 stop.", ' A window on a whole-recording platform (settings.clips', ' .wholeRecordingPlatforms, default Rumble) is not seeked: the video is', ' saved whole once, as "Persist source video" saves it, on the platform\'s', diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts @@ -13,7 +13,7 @@ export const dynamic = "force-dynamic"; // `from`. The projects root is the editor's policy's (generation.projectsRoot). // // GET ?article=<id>&n=<n>[&mode=draft-all][&deck=1] -> { chain } the steps, where it resumes, its job -// POST { article, n, from?, draftAll?, model?, deck? } -> { ok, job } started +// POST { article, n, from?, draftAll?, model?, deck?, stopBeforeRender?, allowWholeRecording? } -> { ok, job } started // POST { cancel: <jobId> } -> { cancelled } // // `draftAll` is Draft everything (release 28 M9): the chain with its @@ -21,6 +21,10 @@ export const dynamic = "force-dynamic"; // route) — and the fast build; a job of its own kind, resumed as the chain is. // `deck` (release 29 G1, Draft everything's option, off by default) adds the // deck step before the flips: the minimal on-screen deck on a cut with none. +// `stopBeforeRender` (demo epic D1) ends the run before the voices: nothing +// voiced or built; the next run resumes there. `allowWholeRecording` (the +// windows step's one press) lets a remote-only channel's Rumble windows +// download their whole recording, refused with its size otherwise. function parse(article: unknown, n: unknown): { article: string; n: number } | string { const a = String(article ?? ""); const k = Number(n); @@ -52,7 +56,17 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown; draftAll?: unknown; model?: unknown; deck?: unknown }; + const body = (await request.json().catch(() => ({}))) as { + article?: unknown; + n?: unknown; + from?: unknown; + cancel?: unknown; + draftAll?: unknown; + model?: unknown; + deck?: unknown; + stopBeforeRender?: unknown; + allowWholeRecording?: unknown; + }; if (body.cancel !== undefined) { const id = String(body.cancel); if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 }); @@ -73,7 +87,18 @@ export async function POST(request: Request) { if (model && mode !== "draft-all") return Response.json({ error: "a model is Draft everything's (draftAll): the model its drafts run on" }, { status: 400 }); const deck = body.deck === true; if (deck && mode !== "draft-all") return Response.json({ error: "the deck is Draft everything's option (draftAll)" }, { status: 400 }); - const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, mode, ...(deck ? { deck } : {}), ...(model ? { model } : {}), ...(projectsRoot ? { projectsRoot } : {}) }); + const plan = planChain({ + articlesDir: ARTICLES_DIR, + article: p.article, + n: p.n, + from, + mode, + ...(deck ? { deck } : {}), + ...(model ? { model } : {}), + ...(projectsRoot ? { projectsRoot } : {}), + ...(body.stopBeforeRender === true ? { stopBeforeRender: true } : {}), + ...(body.allowWholeRecording === true ? { allowWholeRecording: true } : {}), + }); if (plan.steps.length === 0) return Response.json({ error: `every step of ${mode === "draft-all" ? "Draft everything" : "the chain"} is done — pick a step to run from` }, { status: 400 }); const job = startJob(chainKind(p.article, p.n, mode), plan.steps); return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n, mode, deck) }); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -46,11 +46,15 @@ // umtool build <project> [--preset preview|fast|final] [--only ID] [--dry] // [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels // umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] -// [--draft-all [--model M] [--deck]] +// [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording] // an iteration's pipeline: current, windows, prepare, posts, manifest, // voices, video, podcast, attach, dedupe (resumes at the first step not done); -// --draft-all is Draft everything: the drafts between manifest and the fast build; -// --deck adds the on-screen deck to a cut with none before the flips +// --draft-all is Draft everything: the drafts between manifest and the fast build, +// the cut's windows after the cut is drafted (cut-windows); +// --deck adds the on-screen deck to a cut with none before the flips; +// --stop-before-render ends it before the voices (nothing voiced or built); +// --allow-whole-recording lets a remote-only channel's windows download +// their whole recording (Rumble), which is refused with its size otherwise // umtool index [--rebuild] [--prune] [--since MS] [--json] // umtool new <slug> | <folder>/<slug> [--folder <folder>] [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>] // [--site-origin URL] [--seed chapters|frames [--target S]] [--brand archilyzer-media] @@ -1426,7 +1430,7 @@ async function cmdChain() { const article = positional[0]; const n = Number(positional[1]); if (!article || !Number.isInteger(n) || n < 1) { - die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]"); + die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]"); } const draftAll = has("--draft-all"); if (val("--model") && !draftAll) die("--model is Draft everything's (--draft-all): the model its drafts run on"); @@ -1444,12 +1448,14 @@ async function cmdChain() { ...(val("--site-origin") ? { siteOrigin: val("--site-origin") } : {}), final: has("--final"), ...(draftAll ? { mode: "draft-all", ...(val("--model") ? { model: val("--model") } : {}), ...(deck ? { deck: true } : {}) } : {}), + ...(has("--stop-before-render") ? { stopBeforeRender: true } : {}), + ...(has("--allow-whole-recording") ? { allowWholeRecording: true } : {}), }); } catch (err) { die(err.message); } const { start, steps } = plan; - const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}`; + const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}${has("--stop-before-render") ? " --stop-before-render" : ""}`; if (json && has("--dry")) return out({ article, n, start, steps }); if (steps.length === 0) { console.log(`${article} i${n}: every step of the ${draftAll ? "Draft everything chain" : "chain"} is done (--from <step> runs one again)`); diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx @@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button"; import { JobProgress, type JobStep, type JobStepState } from "@/components/ui/job-progress"; import type { ChainMode, ChainView } from "@/lib/articles/generation"; import { spendFromLog } from "@/lib/running.mjs"; +import { WHOLE_RECORDING_REFUSED } from "yt-dlp-transcript-common/lib/remoteArchives"; // MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten // steps (lib/report/chain.mjs) as a umtool job — what each step last did, where @@ -36,6 +37,8 @@ export default function ChainPanel({ const [from, setFrom] = useState<string>(""); const [error, setError] = useState(""); const [sending, setSending] = useState(false); + // Stop before render (demo epic D1): this run ends before the voices. + const [stopBefore, setStopBefore] = useState(false); const load = useCallback(async () => { const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? `&mode=draft-all${deck ? "&deck=1" : ""}` : ""}`, { cache: "no-store" }); @@ -58,13 +61,21 @@ export default function ChainPanel({ return () => clearInterval(t); }, [running, load]); - const start = useCallback(async () => { + const start = useCallback(async (extra: { from?: string; allowWholeRecording?: boolean } = {}) => { setError(""); setSending(true); try { + const at = extra.from ?? from; const r = await fetch("/api/articles/chain", { method: "POST", - body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}) }), + body: JSON.stringify({ + article, + n, + ...(at ? { from: at } : {}), + ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}), + ...(stopBefore ? { stopBeforeRender: true } : {}), + ...(extra.allowWholeRecording ? { allowWholeRecording: true } : {}), + }), }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); @@ -75,7 +86,7 @@ export default function ChainPanel({ } finally { setSending(false); } - }, [article, n, from, draftAll, model, deck, load]); + }, [article, n, from, draftAll, model, deck, stopBefore, load]); useEffect(() => { if (!autoStart || started.current) return; @@ -102,6 +113,9 @@ export default function ChainPanel({ attrs: { "data-chain-step": s.name, "data-step-status": s.status }, })); const job = chain?.job ?? null; + // A windows step a remote-only channel's whole recording refused, with its + // size (demo epic D1): one press fetches them and goes on from there. + const wholeRefused = chain?.steps.find((s) => s.status === "failed" && (s.detail ?? "").startsWith(WHOLE_RECORDING_REFUSED)) ?? null; const done = job ? chain!.steps.filter((s) => s.status === "done" || s.status === "skipped" || s.status === "failed").length : 0; return ( <section @@ -143,6 +157,14 @@ export default function ChainPanel({ )} </JobProgress> )} + {!running && wholeRefused && ( + <div className="flex flex-wrap items-center gap-2 rounded-[3px] border border-seam-2 p-2" data-whole-recording-refused={wholeRefused.name}> + <p className="min-w-0 flex-1 text-text-2">{wholeRefused.detail}</p> + <Button size="sm" variant="outline" disabled={sending} onClick={() => void start({ from: wholeRefused.name, allowWholeRecording: true })}> + Fetch the whole recordings + </Button> + </div> + )} {!running && ( <div className="flex flex-wrap items-center gap-2"> <label className="flex items-center gap-1"> @@ -161,6 +183,10 @@ export default function ChainPanel({ ))} </select> </label> + <label className="flex items-center gap-1 text-muted" title="end this run before the voices: nothing voiced or built; the next run resumes there"> + <input type="checkbox" aria-label={`${label} stop before render`} checked={stopBefore} onChange={(e) => setStopBefore(e.target.checked)} /> + stop before render + </label> <Button size="sm" variant="outline" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}> {draftAll ? "Run Draft everything" : "Run the chain"} </Button> diff --git a/umtool/components/create/forms.tsx b/umtool/components/create/forms.tsx @@ -214,6 +214,7 @@ export function ArticleVideoForm({ const [chain, setChain] = useState<ChainView | null>(null); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); + const [stopBefore, setStopBefore] = useState(false); // The article's iterations: those with a report (done) are what a chain runs over. useEffect(() => { @@ -255,10 +256,17 @@ export function ArticleVideoForm({ const start = async () => { if (!article || n === null) return; + // stopBefore (demo epic D1): the run ends before the voices. setBusy(true); setError(null); try { - await json(await fetch("/api/articles/chain", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ article, n }) })); + await json( + await fetch("/api/articles/chain", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ article, n, ...(stopBefore ? { stopBeforeRender: true } : {}) }), + }), + ); router.push(articleHref({ site: "articles", id: article }, { tab: "iterations" })); } catch (e) { setError((e as Error).message); @@ -303,6 +311,10 @@ export function ArticleVideoForm({ ))} </Select> </Field> + <label className="flex items-center gap-1 self-center text-[12px] text-text-2" title="end the run before the voices: nothing voiced or built; the next run resumes there"> + <input type="checkbox" aria-label="stop before render" checked={stopBefore} onChange={(e) => setStopBefore(e.target.checked)} /> + stop before render + </label> <Actions error={error}> <Button type="submit" variant="go" disabled={busy || n === null || !chain || chain.resumeAt === null || chain.job?.state === "running"}> {busy ? "Starting…" : "Make the video"} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -52,7 +52,7 @@ Inbox cannot disagree about what is wrong with one. | `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | | `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) | -| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) | +| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]] [--stop-before-render] [--allow-whole-recording]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything, which fetches the windows of the clips the drafted cut kept, `cut-windows`); `--stop-before-render` is **Stop before render** (it ends before the voices); `--allow-whole-recording` is **Fetch the whole recordings** (a remote-only channel's Rumble windows, refused with their size otherwise) | | `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 <folder>/<slug> …` · `new <slug> --folder <folder> …` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold; `<folder>/<slug>` (or `--folder`) makes it in a folder of the reports tree — its id `<folder>/<slug>`, routed `/projects/<folder>/<slug>` (a spin-off beside its parent); a folder that is itself a project, the reserved `at`, or one past the walk's four levels is refused | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | @@ -203,7 +203,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `variants <project> [--take TAKE] [--list]` | make the encode ladder of a build | form · queued · *project* | | `corrections <project>` | what the report got wrong, as markdown | form · *project* | | `build <project> [--preset preview\|fast\|final] [--only ONLY] [--dry]` | the build's chain, printed (the Cut tab's Build runs it) | form · *project* | -| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck]` | an article iteration's pipeline to a video | form · queued · *corpus* | +| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck] [--stop-before-render] [--allow-whole-recording]` | an article iteration's pipeline to a video | form · queued · *corpus* | | `index [--rebuild] [--prune] [--since N]` | the project index (the cache) | form · *corpus* | | `new <slug> [--folder FOLDER] [--from FROM] [--site-origin SITE-ORIGIN] [--seed chapters\|frames\|phrase\|reactions] [--target N] [--phrase PHRASE] [--channels CHANNELS] [--prefer PREFER] [--exclude EXCLUDE] [--max N] [--from-posts FROM-POSTS] [--brand BRAND]` | a new project (scaffold) | form · *corpus* | | `doctor` | the tools and the roots on this machine | form · *corpus* | diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -372,16 +372,19 @@ export const GROUPS = [ { cmd: "chain", usage: [ - " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]", + " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]", " an article iteration's pipeline, one step a process: {chainSteps}", " (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)", " --draft-all (Draft everything): {draftAllSteps} —", " each draft a report-draft job on --model (else its route); a draft that fails does not stop it;", " --deck adds a step before the flips: the minimal on-screen deck on a cut with none", + " --stop-before-render ends it before the voices: nothing voiced or built", + " --allow-whole-recording: a remote-only channel's Rumble windows may download", + " their whole recording (refused with its size otherwise)", ], docs: [ - ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]`", - "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything)"], + ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]] [--stop-before-render] [--allow-whole-recording]`", + "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything, which fetches the windows of the clips the drafted cut kept, `cut-windows`); `--stop-before-render` is **Stop before render** (it ends before the voices); `--allow-whole-recording` is **Fetch the whole recordings** (a remote-only channel's Rumble windows, refused with their size otherwise)"], ], }, { diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -197,6 +197,8 @@ export const VERBS = Object.freeze([ form("chain", "corpus", "an article iteration's pipeline to a video", [ arg("article"), num("n", { required: true, help: "the iteration" }), opt("--from", { help: "the step to start at" }), bool("--dry", "print it"), bool("--final"), opt("--site-origin"), bool("--draft-all", "Draft everything"), opt("--model"), bool("--deck"), + bool("--stop-before-render", "end before the voices: nothing voiced or built"), + bool("--allow-whole-recording", "a remote-only channel's windows may download their whole recording (Rumble)"), ], Q), form("index", "corpus", "the project index (the cache)", [bool("--rebuild"), bool("--prune"), num("--since", { help: "ms" })], { confirm: { what: "prune the index's rows of projects no longer on disk", when: ["--prune"] } }), form("new", "corpus", "a new project (scaffold)", [ diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -3,6 +3,7 @@ // // node --import tsx umtool/lib/report/chain-run.mjs step <article> <n> <step> // [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>] +// [--mode draft-all] [--allow-whole-recording] // // — under tsx, because the article registry, the iterations store and the // reports CLIs it calls are common's TypeScript. The Next app never imports @@ -50,17 +51,20 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert"; import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video"; import { checkMain } from "yt-dlp-transcript-common/bin/reports-check"; -import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; +import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, cutWindows, originFromSweep } from "./chain.mjs"; import { deckChrome, deckRefusedDetail, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; import { ChromeRefused, addDeckChrome } from "./manifest.mjs"; import { socialTexts } from "umtool-report-to-video/social"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; -import { originOfHandle } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { WHOLE_RECORDING_REFUSED, originOfHandle } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { archiveRecordOf } from "yt-dlp-transcript-common/controller/remoteOnlyChannel"; +import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server"; const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"); const SCREENSHOT_MISSING = /no captured screenshot/; +const CLIP_MISSING = /fetch the window or persist the video in the editor/; /** A step that ends early with a reason: failed, with that line. */ class StepFailed extends Error {} @@ -100,7 +104,48 @@ async function ownProblems(paths, article) { const index = await readStoreMediaIndex(articleReportStore(paths)); const own = (index?.problems ?? []).filter((p) => isArticleProblem(p, article)); const shots = own.filter((p) => p.kind === "missing-media" && SCREENSHOT_MISSING.test(p.message) && p.moment); - return { own, shots, rest: own.filter((p) => !shots.includes(p)) }; + // An evidence clip whose window is not on disk (publish/reportMedia.ts). + const clips = own.filter((p) => p.kind === "missing-media" && CLIP_MISSING.test(p.message) && !shots.includes(p)); + return { own, shots, clips, rest: own.filter((p) => !shots.includes(p) && !clips.includes(p)) }; +} + +/** + * Ask the editor for a step's windows (demo epic D1 adds the archive): when + * the lineage read a connected archive (`scope.source`), the body names it and + * each item carries its page URL from the archive's record, so the editor + * registers a channel it does not hold as remote-only. Then a DRY RUN first: + * a remote-only channel's whole recording (Rumble) refused with its size fails + * the step with every such refusal — nothing fetched — until the chain runs + * again with `allowWholeRecording` (umtool's one press). Then the run, waited on. + */ +async function fetchWindowsStep(ctx, body, what) { + const origin = originOfHandle(await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null)); + if (origin) { + const getJson = cachedArchiveGetJson(); + body.archive = origin; + for (const item of body.items) { + if (item.webpageUrl) continue; + const r = await archiveRecordOf(origin, item.slug, item.id, { getJson }).catch(() => null); + if (r?.webpageUrl) item.webpageUrl = r.webpageUrl; + } + if (ctx.allowWholeRecording) body.allowWholeRecording = true; + const dry = await editorCall(await editorEnv(), "POST", "/api/ops/fetch-windows", { ...body, dryRun: true }); + if (!dry.ok) throw new StepFailed(`the editor refused the windows: ${dry.error}`); + const whole = (dry.body?.unresolved ?? []).filter((u) => String(u?.error ?? "").startsWith(WHOLE_RECORDING_REFUSED)); + if (whole.length > 0) { + const sizes = whole.map((u) => /: (\S+ is [^.]+|\S+'s length is not known to its archive)\./.exec(String(u.error))?.[1] ?? `${u.item?.slug}/${u.item?.id}`); + throw new StepFailed( + `${WHOLE_RECORDING_REFUSED} ${whole.length} window(s) need their whole recording downloaded — ${[...new Set(sizes)].join("; ")}. ` + + "Allow the whole recordings to fetch them (the chain again, allowWholeRecording).", + ); + } + } + await mkdir(ctx.project, { recursive: true }); + const file = path.join(ctx.project, "windows.json"); + await writeJson(file, body); + const code = await ops("fetch-windows", ["--file", file]); + if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`); + return `${body.items.length} window(s) ${what} on disk${origin ? ` (archive ${origin})` : ""}`; } const describe = (problems) => @@ -123,24 +168,39 @@ const STEPS = { const report = JSON.parse(await readFile(articleFile(ctx.paths, ctx.article), "utf8")); const body = chainWindows(report, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n}` }); if (body.items.length === 0) return "no clip windows cited"; - await mkdir(ctx.project, { recursive: true }); - const file = path.join(ctx.project, "windows.json"); - await writeJson(file, body); - const code = await ops("fetch-windows", ["--file", file]); - if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`); - return `${body.items.length} window(s) on disk`; + return fetchWindowsStep(ctx, body, "cited"); + }, + + // Draft everything's (demo epic D1): the windows of the clips the cut kept. + async ["cut-windows"](ctx) { + const file = path.join(ctx.project, "video.manifest.json"); + const manifest = await readJsonOr(file); + if (!manifest) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); + const body = cutWindows(manifest, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n} cut` }); + if (body.items.length === 0) return "the cut has no clip"; + return fetchWindowsStep(ctx, body, "of the cut's"); }, async prepare(ctx) { const code = await prepareMain({ article: ctx.article, only: true }); if (code === 0) return "the evidence media is complete; the article is exported"; - const { own, shots, rest } = await ownProblems(ctx.paths, ctx.article); - if (own.length > 0 && rest.length === 0) return `${shots.length} post screenshot(s) to capture (the next step)`; - throw new StepFailed(rest.length ? describe(rest) : `reports prepare ended ${code}`); + const { own, shots, clips, rest } = await ownProblems(ctx.paths, ctx.article); + // Draft everything fetches the CUT's windows later (cut-windows): an + // evidence clip not fetched yet does not stop it. + const later = ctx.mode === "draft-all" ? clips : []; + const blocking = ctx.mode === "draft-all" ? rest : [...clips, ...rest]; + if (own.length > 0 && blocking.length === 0) { + return [ + shots.length ? `${shots.length} post screenshot(s) to capture (the next step)` : "", + later.length ? `${later.length} evidence clip(s) not fetched: the cut's are fetched after the cut is drafted; the rest by Fetch missing evidence` : "", + ].filter(Boolean).join("; "); + } + throw new StepFailed(blocking.length ? describe(blocking) : `reports prepare ended ${code}`); }, async posts(ctx) { - const { shots, rest } = await ownProblems(ctx.paths, ctx.article); + const { shots, clips, rest: others } = await ownProblems(ctx.paths, ctx.article); + const rest = ctx.mode === "draft-all" ? others : [...clips, ...others]; if (rest.length > 0) throw new StepFailed(`prepare has this article's other problems first: ${describe(rest)}`); if (shots.length === 0) return "no post screenshot to capture"; const bySlug = new Map(); @@ -157,7 +217,9 @@ const STEPS = { const code = await prepareMain({ article: ctx.article, only: true }); if (code !== 0) { const again = await ownProblems(ctx.paths, ctx.article); - throw new StepFailed(again.own.length ? describe(again.own) : `reports prepare ended ${code}`); + const left = ctx.mode === "draft-all" ? [...again.shots, ...again.rest] : again.own; + if (left.length === 0) return `${shots.length} post screenshot(s) captured; ${again.clips.length} evidence clip(s) not fetched yet`; + throw new StepFailed(left.length ? describe(left) : `reports prepare ended ${code}`); } return `${shots.length} post screenshot(s) captured; the evidence media is complete`; }, @@ -487,6 +549,8 @@ export async function runChainStep(article, n, name, opts = {}) { siteOrigin: opts.siteOrigin, final: opts.final === true, model: opts.model, + mode: opts.mode === "draft-all" ? "draft-all" : "video", + allowWholeRecording: opts.allowWholeRecording === true, cancels: [], onCancel(fn) { this.cancels.push(fn); @@ -558,6 +622,8 @@ function parseArgs(argv) { siteOrigin: flag("--site-origin"), final: rest.includes("--final"), model: flag("--model"), + mode: flag("--mode"), + allowWholeRecording: rest.includes("--allow-whole-recording"), }; } @@ -565,7 +631,7 @@ const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToP if (isMain) { const a = parseArgs(process.argv.slice(2)); if (a.cmd !== "step" || !a.article || !Number.isInteger(a.n) || !a.name) { - console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]"); + console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>] [--mode draft-all] [--allow-whole-recording]"); process.exit(2); } runChainStep(a.article, a.n, a.name, a).then( diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs @@ -5,7 +5,8 @@ // current make the iteration current (the article's report.json) // windows the editor fetches every cited clip window, padded to the // video build's fetchPad, so one fetch serves both the article's -// evidence clips and the cut +// evidence clips and the cut (in "make the video" the cut IS every +// cited clip: to-manifest makes one of each) // prepare `reports prepare --article <id> --only` // posts the editor captures THIS article's missing post screenshots, // then prepare again @@ -24,11 +25,28 @@ // steps in it, each OPTIONAL — `draft-<task>` runs one `report-draft` job on // the iteration through the editor and waits for it: // -// current → windows → prepare → posts → manifest → draft-cut → +// current → prepare → posts → manifest → draft-cut → cut-windows → // draft-onscreen → draft-teaser → draft-flips → draft-threads → // draft-narrate → voices → video (fast, never --final) → podcast → // draft-youtube → draft-social // +// WINDOWS FOR THE CUT, NOT FOR EVERY CITATION (demo epic D1): Draft +// everything has no early `windows`; `cut-windows` fetches the windows of the +// clips the drafted cut kept (cutWindows, from the manifest), so a 37-citation +// report whose cut keeps 9 asks the editor for 9. Its prepare and posts steps +// go on past evidence clips not fetched yet (the article's remaining evidence +// is the site's Fetch missing evidence, never the chain's). +// +// STOP BEFORE RENDER (demo epic D1, `stopBeforeRender`, off by default): the +// chain ends before `voices` — nothing voiced, built or attached — so the cut +// can be walked first; the next run resumes at `voices`. +// +// A connected archive's sweep (its iteration's `scope.source`, demo epic D1): +// the windows steps name the archive and each clip's page URL from its record, +// so the editor registers the channel remote-only; a remote-only channel's +// whole recording (Rumble) is refused with its size until the chain is run +// again with `allowWholeRecording` (umtool's one press). +// // The drafts go after `manifest` (a media task drafts the project's manifest) // and before `voices` (narration is voiced) and the build (the drafts are in // it); YouTube's after the build, which then re-muxes its chapters so @@ -75,11 +93,12 @@ const DRAFT_TIMEOUT = 3 * 60 * 60_000; export const CHAIN_STEPS = [ { name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000, modes: BOTH }, - { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: BOTH }, + { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: VIDEO_ONLY }, { name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000, modes: BOTH }, { name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000, modes: BOTH }, { name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000, modes: BOTH }, { name: "draft-cut", label: "draft the cut: which clips, in what order", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "cut" }, + { name: "cut-windows", label: "fetch the cut's clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: DRAFT_ONLY }, { name: "draft-onscreen", label: "draft the on-screen titles", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "onscreen" }, { name: "draft-teaser", label: "draft the teaser", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "teaser" }, { name: "deck", label: "add the on-screen deck when the cut has none", timeoutMs: 5 * 60_000, modes: DRAFT_ONLY, optional: true, option: "deck" }, @@ -98,19 +117,26 @@ export const CHAIN_STEPS = [ /** The chains: "video" (make the video, the default) and "draft-all" (Draft everything). */ export const CHAIN_MODES = ["video", "draft-all"]; -/** The chains' options: `deck` (Draft everything's deck step, release 29 G1). Each is off by default. */ -export const CHAIN_OPTIONS = ["deck"]; +/** The chains' options: `deck` (Draft everything's deck step, release 29 G1), `stopBeforeRender` (demo epic D1). Each is off by default. */ +export const CHAIN_OPTIONS = ["deck", "stopBeforeRender"]; + +/** The step a `stopBeforeRender` chain ends before: nothing is voiced or built. */ +export const RENDER_STEP = "voices"; /** * A chain's steps, in order. A step with an `option` is in it only when that - * option is on (`{ deck: true }`); with none on, the chain is as it always was. + * option is on (`{ deck: true }`); `stopBeforeRender` ends it before + * RENDER_STEP; with none on, the chain is as it always was. * * @param {string} [mode] - * @param {{ deck?: boolean }} [options] + * @param {{ deck?: boolean, stopBeforeRender?: boolean }} [options] */ export function chainStepsOf(mode = "video", options = {}) { if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`); - return CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true)); + const steps = CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true)); + if (options?.stopBeforeRender !== true) return steps; + const at = steps.findIndex((s) => s.name === RENDER_STEP); + return at < 0 ? steps : steps.slice(0, at); } /** Every step's name, either chain's (what the executor runs). */ @@ -174,8 +200,8 @@ export function chainProject(projectsRoot, article, n) { * has not recorded finished (`done`: the step names recorded finished, * doneSteps), else nothing (the whole chain is done: null). */ -export function chainStart({ from = null, done = [], mode = "video", deck = false } = {}) { - const names = chainStepsOf(mode, { deck }).map((s) => s.name); +export function chainStart({ from = null, done = [], mode = "video", deck = false, stopBeforeRender = false } = {}) { + const names = chainStepsOf(mode, { deck, stopBeforeRender }).map((s) => s.name); if (from !== null && from !== undefined) { if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`); return from; @@ -220,7 +246,7 @@ export function readIterationRecord(articlesDir, article, n) { * `final` says, and `model` rides on the draft steps (else each task's route); * `deck` adds its deck step (G1). * - * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean }} o + * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o * @returns {import("../trim").Step[]} */ export function chainSteps(o) { @@ -228,7 +254,7 @@ export function chainSteps(o) { chainProject(projectsRoot, o.article, o.n); const mode = o.mode ?? "video"; if (o.deck === true && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)"); - const defs = chainStepsOf(mode, { deck: o.deck === true }); + const defs = chainStepsOf(mode, { deck: o.deck === true, stopBeforeRender: o.stopBeforeRender === true }); const start = o.start === undefined ? defs[0].name : o.start; if (start === null) return []; const at = defs.findIndex((s) => s.name === start); @@ -241,6 +267,8 @@ export function chainSteps(o) { projectsRoot, ...(o.siteOrigin ? ["--site-origin", o.siteOrigin] : []), ...(o.final && mode === "video" ? ["--final"] : []), + ...(mode !== "video" ? ["--mode", mode] : []), + ...(o.allowWholeRecording === true ? ["--allow-whole-recording"] : []), ]; return defs.slice(at).map((s, i) => ({ label: `${at + i + 1}/${defs.length} ${s.label}`, @@ -259,7 +287,7 @@ export function chainSteps(o) { * iteration not done, or an unknown `from`. `steps` is empty when every step * is done. * - * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean }} o + * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o */ export function planChain(o) { const record = readIterationRecord(o.articlesDir, o.article, o.n); @@ -268,19 +296,22 @@ export function planChain(o) { const mode = o.mode ?? "video"; const deck = o.deck === true; if (deck && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)"); - const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck }); + const stopBeforeRender = o.stopBeforeRender === true; + const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck, stopBeforeRender }); const steps = chainSteps({ article: o.article, n: o.n, start, mode, ...(deck ? { deck } : {}), + ...(stopBeforeRender ? { stopBeforeRender } : {}), + ...(o.allowWholeRecording === true ? { allowWholeRecording: true } : {}), ...(o.model ? { model: o.model } : {}), ...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}), ...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}), final: o.final === true, }); - return { record, start, steps, mode, deck }; + return { record, start, steps, mode, deck, stopBeforeRender }; } const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100; @@ -321,6 +352,39 @@ export function chainWindows(report, { pad = CHAIN_WINDOW_PAD, requestedBy = "um return { items, requestedBy }; } +/** + * The windows of the clips a CUT keeps (demo epic D1): its manifest's clip + * entries, each its span widened by `pad` and rounded outward to the + * hundredth, one per distinct moment — the same body chainWindows makes from + * a report, for the cut a draft (or a person) narrowed. + */ +export function cutWindows(manifest, { pad = CHAIN_WINDOW_PAD, requestedBy = "umtool chain" } = {}) { + const items = []; + const byMoment = new Map(); + const fallbackChannel = manifest?.provenance?.channelSlug; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip") continue; + const slug = e.channel ?? fallbackChannel; + if (!slug || !e.video || typeof e.start !== "number" || typeof e.end !== "number") continue; + const from = floor2(Math.max(0, e.start - pad)); + const to = ceil2(e.end + pad); + const key = `${slug}/${e.video}`; + if ((byMoment.get(key) ?? []).some((w) => w.from <= from && w.to >= to)) continue; + const item = { + slug, + id: e.video, + from, + to, + clipId: `${manifest.slug ?? "cut"}#${e.id}`, + reason: `cut ${manifest.slug ?? ""} ${e.id}`.trim(), + pad, + }; + items.push(item); + byMoment.set(key, [...(byMoment.get(key) ?? []), item]); + } + return { items, requestedBy }; +} + /** The archive origin a sweep's moment links name (`https://host/?v=…`), or null. */ export function originFromSweep(text) { const m = /(https?:\/\/[^/\s)"']+)\/?\?v=/.exec(String(text ?? "")); diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs @@ -23,6 +23,7 @@ import { chainWindows, chainStepsOf, CHAIN_OPTIONS, + cutWindows, DRAFT_STEP_TASKS, doneSteps, originFromSweep, @@ -55,7 +56,7 @@ test("the steps, in order, each one process of the executor under tsx, from the }); test("the deck option (release 29 G1): a step before the flips, off by default — without it the chain is as it was", () => { - assert.deepEqual(CHAIN_OPTIONS, ["deck"]); + assert.deepEqual(CHAIN_OPTIONS, ["deck", "stopBeforeRender"]); const plain = chainStepsOf("draft-all").map((s) => s.name); assert.ok(!plain.includes("deck")); const withDeck = chainStepsOf("draft-all", { deck: true }).map((s) => s.name); @@ -77,7 +78,7 @@ test("the deck option (release 29 G1): a step before the flips, off by default ); assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", deck: true }), /the deck is Draft everything's option/); // Resume: a chain that ran to the threads without the deck starts again at the deck with it. - const ran = ["current", "windows", "prepare", "posts", "manifest", "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"]; + const ran = ["current", "prepare", "posts", "manifest", "draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"]; assert.equal(chainStart({ done: ran, mode: "draft-all", deck: true }), "deck"); assert.equal(chainStart({ done: ran, mode: "draft-all" }), "draft-narrate"); assert.ok(doneSteps({ steps: [{ task: "chain:deck", status: "failed" }] }).includes("deck"), "optional: a failed deck step is passed"); @@ -103,8 +104,8 @@ test("resume: the first step not recorded done; --from names one; all done is no test("Draft everything: the drafts between the manifest and the fast build, YouTube after it; the default chain unchanged", () => { const names = chainStepsOf("draft-all").map((s) => s.name); assert.deepEqual(names, [ - "current", "windows", "prepare", "posts", "manifest", - "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate", + "current", "prepare", "posts", "manifest", + "draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate", "voices", "video", "podcast", "draft-youtube", "draft-social", ]); assert.deepEqual(chainStepsOf("video").map((s) => s.name), CHAIN_STEP_NAMES); @@ -114,14 +115,16 @@ test("Draft everything: the drafts between the manifest and the fast build, YouT const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all", model: "qwen3:8b", final: true }); assert.equal(steps.length, 16); - assert.equal(steps[5].label, "6/16 draft the cut: which clips, in what order"); + assert.equal(steps[4].label, "5/16 draft the cut: which clips, in what order"); + // demo epic D1: the cut's windows right after the cut is drafted, not every citation's before it. + assert.equal(steps[5].label, "6/16 fetch the cut's clip windows (editor)"); // The model rides on the draft steps only; the build is the fast one (--final is ignored). for (const s of steps) { const draft = s.argv[7].startsWith("draft-"); assert.equal(s.argv.includes("--model"), draft, s.argv[7]); assert.ok(!s.argv.includes("--final"), s.argv[7]); } - assert.deepEqual(steps[5].argv.slice(8), ["--projects-root", "/p", "--model", "qwen3:8b"]); + assert.deepEqual(steps[4].argv.slice(8), ["--projects-root", "/p", "--mode", "draft-all", "--model", "qwen3:8b"]); // No model: each task's route chooses. assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all" }).every((s) => !s.argv.includes("--model"))); assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", model: "a b" }), /not a model name/); @@ -133,18 +136,19 @@ test("Draft everything resumes past a draft that ran — done, skipped or failed const it = { steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done" })).concat([ { task: "chain:draft-cut", status: "done" }, + { task: "chain:cut-windows", status: "done" }, { task: "chain:draft-onscreen", status: "failed" }, { task: "chain:draft-teaser", status: "skipped" }, { task: "chain:draft-flips", status: "cancelled" }, ]), }; const done = doneSteps(it); - assert.deepEqual(done.slice(5), ["draft-cut", "draft-onscreen", "draft-teaser"]); + assert.deepEqual(done.slice(5), ["draft-cut", "cut-windows", "draft-onscreen", "draft-teaser"]); assert.equal(chainStart({ done, mode: "draft-all" }), "draft-flips"); // The default chain never sees the drafts: it resumes at voices. assert.equal(chainStart({ done }), "voices"); - const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:windows", status: "failed" }] }; - assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "windows"); + const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:prepare", status: "failed" }] }; + assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "prepare"); assert.equal(chainStart({ from: "draft-threads", mode: "draft-all" }), "draft-threads"); assert.throws(() => chainStart({ from: "draft-threads" }), /--from must be one of/); const all = chainStepsOf("draft-all").map((s) => s.name); @@ -203,14 +207,14 @@ test("umtool chain --dry: the plan, resuming where the iteration left off; refus // --draft-all: the same resume point, the drafts in the plan, the model on them. const all = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--model", "claude-sonnet-5-5", "--projects-root", path.join(ROOT, "projects"))); assert.equal(all.start, "prepare"); - assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate"]); + assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"]); assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(-2), ["draft-youtube", "draft-social"]); assert.ok(all.steps.at(-1).argv.includes("claude-sonnet-5-5")); assert.throws(() => run("art", "2", "--dry", "--model", "qwen3:8b"), (e) => /--model is Draft everything's/.test(String(e.stderr))); assert.throws(() => run("art", "2", "--dry", "--draft-all", "--final"), (e) => /builds the fast cut/.test(String(e.stderr))); // --deck (release 29 G1): the deck step before the flips; Draft everything's only. const deck = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--deck", "--projects-root", path.join(ROOT, "projects"))); - assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(6, 8), ["deck", "draft-flips"]); + assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(7, 9), ["deck", "draft-flips"]); assert.throws(() => run("art", "2", "--dry", "--deck"), (e) => /--deck is Draft everything's option/.test(String(e.stderr))); }); @@ -249,3 +253,43 @@ test("the projects root comes from settings.generation.projectsRoot (release 27 rmSync(dir, { recursive: true, force: true }); } }); + +// demo epic D1: windows for the cut; stop before render; the whole-recording allowance. +test("cutWindows: the manifest's clips, padded and rounded outward, once per moment", () => { + const body = cutWindows( + { + slug: "art-i2", + provenance: { channelSlug: "fallback" }, + timeline: [ + { type: "card", id: "t0" }, + { type: "clip", id: "c1", channel: "alpha", video: "v1", start: 10.004, end: 20 }, + { type: "clip", id: "c2", channel: "alpha", video: "v1", start: 12, end: 18 }, // inside c1's window + { type: "clip", id: "c3", video: "v2", start: 1, end: 4 }, // the manifest's channel + { type: "clip", id: "bad", channel: "alpha", video: "v3" }, + ], + }, + { pad: 3, requestedBy: "t" }, + ); + assert.deepEqual(body, { + requestedBy: "t", + items: [ + { slug: "alpha", id: "v1", from: 7, to: 23, clipId: "art-i2#c1", reason: "cut art-i2 c1", pad: 3 }, + { slug: "fallback", id: "v2", from: 0, to: 7, clipId: "art-i2#c3", reason: "cut art-i2 c3", pad: 3 }, + ], + }); +}); + +test("stopBeforeRender ends either chain before the voices; the allowance rides on every step", () => { + const video = chainStepsOf("video", { stopBeforeRender: true }).map((s) => s.name); + assert.deepEqual(video, ["current", "windows", "prepare", "posts", "manifest"]); + const all = chainStepsOf("draft-all", { stopBeforeRender: true }).map((s) => s.name); + assert.equal(all.at(-1), "draft-narrate"); + assert.ok(!all.includes("voices") && !all.includes("video")); + // All done before the render: nothing to run; without the option, it resumes at the voices. + assert.equal(chainStart({ done: video, stopBeforeRender: true }), null); + assert.equal(chainStart({ done: video }), "voices"); + const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", stopBeforeRender: true, allowWholeRecording: true }); + assert.equal(steps.length, 5); + assert.ok(steps.every((s) => s.argv.includes("--allow-whole-recording"))); + assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node" }).every((s) => !s.argv.includes("--allow-whole-recording") && !s.argv.includes("--mode"))); +}); diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -63,7 +63,7 @@ export const isMontage = (manifest) => * * @param {Record<string, any>} manifest * @param {{ manifestPath: string, project: string, rulings?: { rulings: Record<string, { verdict: string }> } | null, reason?: string | null }} opts - * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }} + * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", archive?: string, items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }} */ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = null, reason = null }) { const montage = isMontage(manifest); @@ -106,8 +106,18 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu }); } } + // The archive the cut cites (demo epic D1): its provenance.siteOrigin. The + // editor registers a channel it does not hold as remote-only only when that + // origin is a CONNECTED archive; any other origin changes nothing. + const site = typeof manifest?.provenance?.siteOrigin === "string" ? manifest.provenance.siteOrigin.trim().replace(/\/+$/, "") : ""; return { - body: { requestedBy: `umtool:${project}`, manifest: path.resolve(manifestPath), storedUrl: "fallback", items }, + body: { + requestedBy: `umtool:${project}`, + manifest: path.resolve(manifestPath), + storedUrl: "fallback", + ...(/^https?:\/\//.test(site) ? { archive: site } : {}), + items, + }, skipped, }; } diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs @@ -292,6 +292,9 @@ if (wantAll) { items: local.items, requestedBy: "umtool", manifest: manifestId, + // The archive the cut cites (demo epic D1): a CONNECTED one registers a + // channel the editor does not hold as remote-only; any other is ignored. + ...(/^https?:\/\//.test(String(provenance.siteOrigin ?? "")) ? { archive: String(provenance.siteOrigin).trim().replace(/\/+$/, "") } : {}), ...(maxHeight !== undefined ? { maxHeight } : {}), ...storedUrl, }),