Archilyzer · Source

archilyzer

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

commit e48270e7ea860bc583f809f722649aee9f7cf3e7
parent decf277138ebfadc6b49d7489579089857c5228a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 20 Nov 2026 16:17:34 -0500

Merge main into lane/gap-cue

main at 65c57cb80 (chat-clock, source-status). editor/CHANGELOG.md: both
unreleased sections kept. Generated docs checked current.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MAGENTS.md | 18++++++++++++++++++
MCOMMANDS.md | 2+-
Mcommon/controller/buildIndex.ts | 10+++++++---
Mcommon/controller/fetchLiveChat.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchLiveChat.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Acommon/controller/normalizeLiveChat.test.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/normalizeLiveChat.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/normalizeTranscript.ts | 5++++-
Acommon/lib/liveChat.test.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/liveChat.ts | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Acommon/lib/sourceStatus-server.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/sourceStatus.mjs | 306+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/sourceStatus.test.ts | 281+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 2++
Meditor/CHANGELOG.md | 14++++++++++++++
Meditor/app/api/ops/fetch-chat/route.ts | 16++++++++++++----
Meditor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts | 8+++++++-
Mscripts/archilyzer-ops.mjs | 8+++++++-
Mumtool/bin/umtool.mjs | 2++
Mumtool/docs/cli.md | 3+++
Mumtool/docs/knobs.md | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/cli/groups.mjs | 12++++++++++++
Mumtool/lib/cli/verbs.mjs | 2++
Mumtool/lib/inbox/groups.mjs | 1+
Mumtool/lib/inbox/what.mjs | 1+
Mumtool/lib/projects/report.mjs | 12++++++++++++
Mumtool/lib/report/onscreen.mjs | 4+++-
Aumtool/lib/report/sourceStatusCli.mjs | 371+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/sourceStatusCli.test.mjs | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/attribution.mjs | 18+++++++++++++++---
Mumtool/report-to-video/build-video.mjs | 8++++++++
Mumtool/report-to-video/chrome-deck.mjs | 58+++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/chrome-finale.mjs | 11+++++++----
Mumtool/report-to-video/cues.mjs | 30+++++++++++++++++++++++-------
Aumtool/report-to-video/deck-source-status.test.mjs | 288+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 14+++++++++++---
Mumtool/report-to-video/modules/settings.mjs | 10++++++++--
Mumtool/report-to-video/modules/subtitle.mjs | 9++++++---
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/source-status.mjs | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/status-fit.mjs | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/status-fit.test.mjs | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
42 files changed, 3246 insertions(+), 62 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -103,6 +103,24 @@ stopped — do not start e2e or builds yourself meanwhile. The umtool take panel renders the machine** toggle is the same `--priority`; `/jobs` and the take panel show a banner. `RENDER_PRIORITY=0` runs a job anyway. Details: WORKTREES.md, "Render mode". +**A cut still being shaped is rendered at the PREVIEW TIER, never at full resolution.** When the +operator asks for a "preview render" he means this, the whole cut, small and fast: + +```sh +umtool take <project> --id <take> --label "…" --draft [--patch-json '…'] # record the take, render nothing +umtool queue add --label "<take> preview" -- take <project> --id <take> --preview --full +``` + +`--preview` is 1280x720, x264 veryfast, crf 26, with the same layout, chrome and sound, into +`takes/<id>/out/<slug>.preview.mp4`; clip segments are reused by key, so a re-preview after a +note re-cuts only what changed. A `--full` render at full resolution is for a cut that is close +to deliverable and that the operator has already watched as a preview: a 75-minute cut took +about three hours at full resolution on this machine while notes were still coming in +(20 Nov 2026). Short full-resolution windows (`--at S --dur D --quick`) are not what "preview" +means either: use them only to look at one effect, and say that is what they are. While the +operator waits on any of these, render mode is on (above) and lane gates that compete for the +CPU are parked. + See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, render mode, and the shared-data caveat. diff --git a/COMMANDS.md b/COMMANDS.md @@ -236,7 +236,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/&lt;slug&gt;.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | | `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -&gt; {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` | -| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` | +| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` | | `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/&lt;id&gt;/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` | | `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` | | `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /cookies, then {"resume": "&lt;run id&gt;"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` | diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -44,7 +44,6 @@ import { open } from "lmdb"; import { writeJsonAtomic as writeJsonAtomicShared } from "../lib/jsonFile-server"; import { parseVtt, type Cue } from "../lib/vtt"; import { parseTranscriptJson } from "../lib/whisper"; -import { parseLiveChat } from "../lib/liveChat"; import { platformLabelStale, summarize, @@ -57,6 +56,7 @@ import { } from "./normalizeTranscript"; import { isLiveChatCuesFresh, + parseLiveChatOnRecordingClock, readNormalizedLiveChat, } from "./normalizeLiveChat"; import type { @@ -1310,11 +1310,15 @@ export async function buildIndex({ else retrySubs = true; continue; } - trackCues = parseLiveChat(raw); + trackCues = (await parseLiveChatOnRecordingClock(videoFullDir, raw)).cues; } else { const raw = await readFile(rawPath, "utf8"); + // A stale chat's raw is parsed onto the recording's clock, + // as the normalizer does (lane chat-clock). trackCues = - t.track === "live_chat" ? parseLiveChat(raw) : parseVtt(raw); + t.track === "live_chat" + ? (await parseLiveChatOnRecordingClock(videoFullDir, raw)).cues + : parseVtt(raw); } } if (trackCues.length > 0) { diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts @@ -348,3 +348,83 @@ test("the job: refusals before any job (info for a skip), a fetch job, a normali assert.equal(spawn.calls.length, 0, "no network for a replay already here"); assert.equal(JSON.parse(await readFile(path.join(dir6, "live_chat.cues.json"), "utf8")).cues.length, 3); }); + +// RE-NORMALIZE ONLY (lane chat-clock): the raw on disk parsed again, fresh or +// not, never a fetch. +test("renormalize: refused with no raw chat on disk (it never fetches), and no job", async () => { + await video("rn1", { webpage_url: "https://www.youtube.com/watch?v=rn1", was_live: true }); + const spawn = stubRunner(); + const out = await runFetchChatJob({ + paths, slug: SLUG, videoId: "rn1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, renormalize: true, + }); + assert.ok(!out.ok && !out.info && /no raw chat on disk/.test(out.error) && /never fetches/.test(out.error), JSON.stringify(out)); + assert.equal(spawn.calls.length, 0); + const none = await runFetchChatJob({ + paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, renormalize: true, + }); + assert.ok(!none.ok); +}); + +test("renormalize: a FRESH chat captured live is parsed again onto the broadcast's clock, with no spawn", async () => { + const t0 = Date.UTC(2026, 0, 2, 3, 0, 0); + const dir = await video("rn2", { + webpage_url: "https://www.youtube.com/watch?v=rn2", + was_live: true, + release_timestamp: t0 / 1000, + }); + const live = JSON.stringify({ + replayChatItemAction: { + actions: [{ + addChatItemAction: { + item: { + liveChatTextMessageRenderer: { + message: { runs: [{ text: "hello" }] }, + authorName: { simpleText: "viewer1" }, + id: "m1", + timestampUsec: String((t0 + 2_335_000) * 1000), + }, + }, + }, + }], + }, + videoOffsetTimeMsec: "100000", + isLive: true, + }); + await writeFile(path.join(dir, "transcript.live_chat.json"), live + "\n"); + // A v1 file written before the fix: fresh by its mtime. + await writeFile( + path.join(dir, "live_chat.cues.json"), + '{"version":1,"source":"live_chat","cues":[{"start":100,"end":105,"text":"viewer1: hello"}]}', + ); + const plain = await runFetchChatJob({ paths, slug: SLUG, videoId: "rn2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); + assert.ok(!plain.ok && plain.info && /already here/.test(plain.error), "without the flag: fresh, no job"); + + const spawn = stubRunner(); + const job = await runFetchChatJob({ + paths, slug: SLUG, videoId: "rn2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, renormalize: true, + }); + assert.ok(job.ok, JSON.stringify(job)); + void job.stream.cancel(); + assert.equal((await job.done).status, "done"); + assert.equal(spawn.calls.length, 0, "no network"); + const doc = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")); + assert.equal(doc.version, 2); + assert.equal(doc.cues[0].start, 2335); + assert.equal(doc.clock.basis, "broadcast-start"); + assert.equal(doc.clock.shiftSeconds, 2235); +}); + +test("renormalize: held by the media guard while the channel's media is moving", async () => { + const dir = await video("rn3", { webpage_url: "https://www.youtube.com/watch?v=rn3", was_live: true }); + await writeFile(path.join(dir, "transcript.live_chat.json"), REPLAY); + const marker = path.join(CORPUS, "channels", SLUG, ".relocating.json"); + await writeFile(marker, JSON.stringify({ target: "/nowhere", direction: "out", startedAt: new Date().toISOString(), phase: "copying", scope: "media" })); + try { + const out = await runFetchChatJob({ + paths, slug: SLUG, videoId: "rn3", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, renormalize: true, + }); + assert.ok(!out.ok && /moving|transition|held/i.test(out.error), JSON.stringify(out)); + } finally { + await rm(marker, { force: true }); + } +}); diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts @@ -29,10 +29,14 @@ // // `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a // tierable big file, and the normalizer moves it into the channel's media/. +// +// `renormalize: true` (lane chat-clock) parses the raw already on disk again, +// fresh or not, and never fetches: the one-video repair for a chat normalized +// before a live capture was put on the recording's clock (normalizeLiveChat). import { localMediaFetchRefusal } from "../lib/localMedia"; import path from "node:path"; -import { readFile, readdir, stat } from "node:fs/promises"; +import { lstat, readFile, readdir, stat } from "node:fs/promises"; import { AUTH_RETRY_CLASSES, classifyDownloadFailure, @@ -79,7 +83,10 @@ export type LiveChatPlan = | { kind: "no-fetcher"; platform: string } // The metadata says the video was never live: there is no replay to ask for. | { kind: "not-live"; liveStatus: string } - | { kind: "fetch"; url: string; platform: string } + // `live`: the metadata says the stream is live now, so the pass captures + // the chat as it is typed (on the capture's clock until normalizeLiveChat + // puts it on the recording's). + | { kind: "fetch"; url: string; platform: string; live?: boolean } | { kind: "refused"; error: string }; async function isDirectory(p: string): Promise<boolean> { @@ -133,7 +140,7 @@ export async function liveChatPlan( if (!CHAT_PLATFORMS.has(platform)) return { kind: "no-fetcher", platform }; const live = await liveStatusOf(videoDir); if (live === "not_live") return { kind: "not-live", liveStatus: live }; - return { kind: "fetch", url, platform }; + return { kind: "fetch", url, platform, ...(live === "is_live" ? { live: true } : {}) }; } function succeeded(exitCode: number | null): boolean { @@ -158,6 +165,8 @@ export type FetchLiveChatOpts = { signal: AbortSignal; onPlatformBackoff?: () => Promise<void> | void; onPlatformClean?: () => Promise<string | null> | string | null; + // The stream is live now (LiveChatPlan `live`): the log says it is a capture. + capturingLive?: boolean; // Test seams: the spawn, and the platform pace in the argv. run?: ChatRunner; paceSeconds?: number; @@ -189,7 +198,12 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC const pass = (cookies: string | undefined) => run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds)); - opts.onLog(`Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`); + opts.onLog( + opts.capturingLive + ? `Capturing the live chat of ${opts.videoId} from ${opts.videoUrl} while it is live (no media); ` + + `it is put on the broadcast's clock when it is normalized\n` + : `Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`, + ); const firstCookies = alwaysCookies(policy); let outcome = await pass(firstCookies); // A pass the platform refused for THIS video ("Join this channel …") is an @@ -278,8 +292,35 @@ export type FetchChatJobOpts = { queueKey?: string; afterRun?: () => void | Promise<void>; run?: ChatRunner; + // RE-NORMALIZE ONLY (lane chat-clock): parse the raw replay already on disk + // again — e.g. a chat captured live and normalized before the chat was put + // on the recording's clock — even when its cues are fresh. Never a fetch: + // refused when no raw is here. No network; the job's kind still declares + // `needsMedia`, so a raw that is a tier link onto an unreachable drive is + // refused by runManagedFunction's guard like any other media reader. + renormalize?: boolean; }; +/** Why a re-normalize cannot run for this video, or null. Reads the disk only. */ +export async function renormalizeChatRefusal( + paths: Paths, + slug: string, + videoId: string, +): Promise<string | null> { + if (!isVideoIdSegment(videoId)) return `"${videoId}" is not a video id (one path segment)`; + const videoDir = path.join(paths.channelsDir, slug, "data", videoId); + if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug); + const here = (name: string) => lstat(path.join(videoDir, name)).then(() => true, () => false); + if (!(await here(LIVE_CHAT_FILENAME))) { + return ( + `${videoId} has no raw chat on disk (${LIVE_CHAT_FILENAME}): "renormalize" reads only the file ` + + `already here and never fetches — fetch-chat without it fetches the chat` + ); + } + if (!(await here(META_FILENAME))) return `${videoId} has no ${META_FILENAME}: its chat cannot be normalized`; + return null; +} + // Every refusal before any job, in the sentences the rest of the app uses. export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamActionResult> { const { paths, slug, videoId, channelConfig } = opts; @@ -288,7 +329,13 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct } catch (err) { return { ok: false, error: (err as Error).message }; } - const plan = await liveChatPlan(paths, slug, videoId, channelConfig); + if (opts.renormalize) { + const refusal = await renormalizeChatRefusal(paths, slug, videoId); + if (refusal) return { ok: false, error: refusal }; + } + const plan: LiveChatPlan = opts.renormalize + ? { kind: "normalize" } + : await liveChatPlan(paths, slug, videoId, channelConfig); switch (plan.kind) { case "refused": return { ok: false, error: plan.error }; @@ -326,7 +373,11 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct ...(plan.kind === "normalize" ? { network: false as const } : {}), fn: async (onLog, signal) => { if (plan.kind === "normalize") { - onLog(`The chat replay of ${videoId} is on disk; normalizing it (no network).`); + onLog( + opts.renormalize + ? `Re-normalizing the chat of ${videoId} from the raw on disk (no network).` + : `The chat replay of ${videoId} is on disk; normalizing it (no network).`, + ); await normalizeChat({ slug, videoId, channelConfig, onLog }, videoDir); } else { await fetchLiveChat({ @@ -340,6 +391,7 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct signal, onPlatformBackoff: () => recordDownloadBackoff(plan.platform, paths), onPlatformClean: () => recordPlatformClean(plan.platform, paths), + ...(plan.live ? { capturingLive: true } : {}), ...(opts.run ? { run: opts.run } : {}), }); } diff --git a/common/controller/normalizeLiveChat.test.ts b/common/controller/normalizeLiveChat.test.ts @@ -0,0 +1,227 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/normalizeLiveChat.test.ts +// +// ONE CLOCK PER RECORDING, THE CUES' — for the live chat (lane chat-clock). +// A chat yt-dlp captures WHILE THE STREAM IS LIVE is timed from the moment the +// capture began (`videoOffsetTimeMsec = timestampUsec/1000 − start_time`, +// every line `"isLive": true`); a recording made from the broadcast's start is +// timed from the broadcast's start. These cases pin the normalizer putting the +// chat on the recording's clock. Temp dirs, synthetic names, no network. + +const ROOT = await mkdtemp(path.join(tmpdir(), "chat-clock-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const { normalizeLiveChat, isLiveChatCuesFresh } = await import("./normalizeLiveChat"); + +// The broadcast went live at T0; the chat capture began 2,235 s later. +const T0_MS = Date.UTC(2026, 0, 2, 3, 0, 0); +const SHIFT_MS = 2_235_000; +const CAPTURE_MS = T0_MS + SHIFT_MS; +const URL = "https://www.youtube.com/watch?v=abc123"; + +type Msg = { id?: string; author: string; text: string }; + +function renderer(m: Msg, postedMs: number) { + return { + liveChatTextMessageRenderer: { + message: { runs: [{ text: m.text }] }, + authorName: { simpleText: m.author }, + ...(m.id ? { id: m.id } : {}), + timestampUsec: String(postedMs * 1000), + }, + }; +} + +// yt-dlp's live pseudo-replay line: the offset is from the capture's start. +function liveLine(offsetMs: number, m: Msg, captureMs = CAPTURE_MS): string { + return JSON.stringify({ + replayChatItemAction: { actions: [{ addChatItemAction: { item: renderer(m, captureMs + offsetMs) } }] }, + videoOffsetTimeMsec: String(offsetMs), + isLive: true, + }); +} + +// A replay line (after the stream): YouTube's offset, on the VOD's clock. +function replayLine(offsetMs: number, m: Msg): string { + return JSON.stringify({ + replayChatItemAction: { + actions: [{ addChatItemAction: { item: renderer(m, T0_MS + offsetMs) } }], + videoOffsetTimeMsec: String(offsetMs), + }, + }); +} + +const META = { + id: "abc123", + title: "Demo stream", + upload_date: "20260102", + release_timestamp: T0_MS / 1000, + live_status: "post_live", + was_live: true, + duration: 10_000, + webpage_url: URL, +}; + +function recording(o: { fromStart?: boolean; status?: string; startedAtMs?: number } = {}) { + const startedAt = new Date(o.startedAtMs ?? CAPTURE_MS - 5_000).toISOString(); + const fromStart = o.fromStart ?? true; + return { + status: o.status ?? "landed", + url: URL, + platform: "youtube", + fromStart, + startedAt, + parts: [{ method: "ytdlp", url: URL, fromStart, startedAt, seconds: 10_000 }], + ...((o.status ?? "landed") === "landed" ? { landedPart: 0 } : {}), + }; +} + +let n = 0; +async function videoDir(files: { meta?: object; raw: string[]; rec?: object }): Promise<string> { + const dir = path.join(ROOT, `case-${++n}`, "demo-channel", "data", "abc123"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(files.meta ?? META)); + await writeFile(path.join(dir, "transcript.live_chat.json"), files.raw.join("\n") + "\n"); + if (files.rec) await writeFile(path.join(dir, "live-recording.json"), JSON.stringify(files.rec)); + return dir; +} + +type Doc = { version: number; cues: { start: number; text: string }[]; clock?: Record<string, unknown> }; +async function normalize(dir: string): Promise<Doc> { + const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", force: true, tier: false }); + assert.equal(out.status, "wrote"); + return JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")) as Doc; +} + +test("a chat captured while live lands on a from-start recording's clock (the broadcast's start)", async () => { + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" }), liveLine(-300_000, { id: "m0", author: "viewer0", text: "backlog" })], + rec: recording(), + }); + const doc = await normalize(dir); + assert.deepEqual( + doc.cues.map((c) => [c.start, c.text]), + [ + [1935, "viewer0: backlog"], + [2335, "viewer1: hello"], + ], + ); + assert.equal(doc.version, 2); + assert.equal(doc.clock?.basis, "broadcast-start"); + assert.equal(doc.clock?.certain, true); + assert.equal(doc.clock?.shiftSeconds, 2235); + assert.equal(doc.clock?.zeroAt, new Date(T0_MS).toISOString()); + assert.equal(doc.clock?.liveLines, 2); +}); + +test("a recording still in progress has the same zero (the chat may be normalized before it lands)", async () => { + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })], + rec: recording({ status: "recording" }), + }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 2335); + assert.equal(doc.clock?.basis, "broadcast-start"); +}); + +test("no recording: the media is the post-live VOD, timed from the broadcast's start too", async () => { + const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })] }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 2335); + assert.equal(doc.clock?.basis, "broadcast-start"); +}); + +test("a live head then a replay (a resumed .part): the replay copy wins, a head-only message is shifted, an id-less line is kept", async () => { + const dir = await videoDir({ + raw: [ + liveLine(10_000, { id: "dup", author: "viewer1", text: "said twice" }), + liveLine(20_000, { id: "head-only", author: "viewer2", text: "only live" }), + liveLine(30_000, { author: "viewer3", text: "no id" }), + replayLine(500_000, { id: "early", author: "viewer4", text: "replay" }), + replayLine(2_245_000, { id: "dup", author: "viewer1", text: "said twice" }), + ], + }); + const doc = await normalize(dir); + assert.deepEqual( + doc.cues.map((c) => [c.start, c.text]), + [ + [500, "viewer4: replay"], + [2245, "viewer1: said twice"], + [2255, "viewer2: only live"], + [2265, "viewer3: no id"], + ], + ); + assert.equal(doc.clock?.duplicatesDropped, 1); + assert.equal(doc.clock?.liveLines, 3); + assert.equal(doc.clock?.replayLines, 2); +}); + +test("a recording NOT from the start: its part's start is the zero, and it is not certain", async () => { + const startedAtMs = T0_MS + 3_000_000; + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" }, startedAtMs + 2_000)], + rec: recording({ fromStart: false, startedAtMs }), + }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 102); + assert.equal(doc.clock?.basis, "recording-start"); + assert.equal(doc.clock?.certain, false); +}); + +test("no zero to be had (no release_timestamp, no recording): the capture's clock, said so", async () => { + const { release_timestamp, ...meta } = META; + void release_timestamp; + const dir = await videoDir({ meta, raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })] }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 100); + assert.equal(doc.clock?.basis, "capture-start"); + assert.equal(doc.clock?.certain, false); +}); + +test("a recording NOT from the start with no readable start: no zero, the capture's clock, and the log says so", async () => { + const rec = recording({ fromStart: false }); + const parts = rec.parts.map(({ startedAt, ...p }) => (void startedAt, p)); + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })], + rec: { ...rec, parts }, + }); + const logs: string[] = []; + const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", force: true, tier: false, log: (m) => logs.push(m) }); + assert.equal(out.status, "wrote"); + const doc = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")) as Doc; + assert.equal(doc.cues[0].start, 100); + assert.equal(doc.clock?.basis, "capture-start"); + assert.equal(doc.clock?.certain, false); + assert.ok(logs.some((l) => /left on the capture's clock/.test(l)), logs.join("\n")); +}); + +test("a pure replay: the same starts as ever, basis replay", async () => { + const dir = await videoDir({ + raw: [replayLine(12_000, { id: "a", author: "viewer1", text: "lol" }), replayLine(14_000, { id: "b", author: "viewer2", text: "W" })], + rec: recording(), + }); + const doc = await normalize(dir); + assert.deepEqual(doc.cues.map((c) => c.start), [12, 14]); + assert.equal(doc.clock?.basis, "replay"); + assert.equal(doc.clock?.liveLines, 0); +}); + +test("the version bump makes no v1 file stale: a v1 cues file over a pure replay stays fresh and byte-unchanged", async () => { + const dir = await videoDir({ raw: [replayLine(12_000, { id: "a", author: "viewer1", text: "lol" })] }); + const cuesPath = path.join(dir, "live_chat.cues.json"); + const v1 = '{"version":1,"source":"live_chat","id":"abc123","cues":[{"start":12,"end":17,"text":"viewer1: lol"}]}'; + await writeFile(cuesPath, v1); + const older = new Date(Date.now() - 60_000); + await utimes(path.join(dir, "metadata.info.json"), older, older); + await utimes(path.join(dir, "transcript.live_chat.json"), older, older); + assert.equal((await isLiveChatCuesFresh(dir)).fresh, true); + const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", tier: false }); + assert.equal(out.status, "fresh"); + assert.equal(await readFile(cuesPath, "utf8"), v1); +}); diff --git a/common/controller/normalizeLiveChat.ts b/common/controller/normalizeLiveChat.ts @@ -2,12 +2,28 @@ // alongside the raw file so that downstream consumers (buildIndex, archives) // can skip re-parsing potentially huge live-chat JSON-lines payloads. Shape // matches NormalizedTranscript with source: "live_chat". +// +// ONE CLOCK PER RECORDING, THE CUES' (lane chat-clock): a chat yt-dlp captured +// WHILE THE STREAM WAS LIVE is timed from the moment the capture began, not +// from the broadcast's start. The cues written here are on the recording's +// clock — the zero is the metadata's `release_timestamp` or the recording's +// own part (lib/liveChat.ts liveChatClockZero) — and the file says so in +// `clock`. A chat fetched as a replay is already on that clock and is not moved. import path from "node:path"; import { lstat, readFile, stat } from "node:fs/promises"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { tierMediaFile } from "../lib/mediaTier-server"; -import { parseLiveChat } from "../lib/liveChat"; +import { + hasLiveCapturedLines, + liveChatClockOf, + liveChatClockZero, + parseLiveChatDetailed, + type LiveChatClock, + type LiveChatZero, + type LiveRecordingLike, +} from "../lib/liveChat"; +import { LIVE_RECORDING_FILENAME, coerceLiveRecording } from "../lib/liveCapture"; import type { Cue } from "../lib/vtt"; import { summarize, type RawMetadata } from "../lib/transcripts-server"; import { @@ -19,7 +35,13 @@ import { META_FILENAME, } from "../lib/videoStatus"; -export const LIVE_CHAT_FILE_VERSION = 1; +// 2 (lane chat-clock): a chat captured while live is on the recording's +// clock, and the file says which clock in `clock`. A version-1 file is NOT +// stale for being version 1 — freshness stays the mtimes below, so no build +// re-reads every raw replay off the media drive; a v1 file over a live capture +// is re-normalized one video at a time (`pnpm ops fetch-chat {…, +// "renormalize": true}`). +export const LIVE_CHAT_FILE_VERSION = 2; export type NormalizeLiveChatOptions = { videoDir: string; @@ -59,6 +81,53 @@ async function rawMtimeMs(p: string): Promise<number | null> { } } +/** + * The recording's zero for this video's live-captured chat: its metadata's + * `release_timestamp` and its `live-recording.json`, when there is one + * (lib/liveChat.ts liveChatClockZero). `meta` is the parsed metadata when the + * caller holds it already (it can be tens of MB). + */ +export async function readLiveChatZero( + videoDir: string, + meta?: { release_timestamp?: unknown } | null, +): Promise<LiveChatZero> { + const parsedMeta = + meta !== undefined + ? meta + : await readFile(path.join(videoDir, META_FILENAME), "utf8").then( + (raw) => JSON.parse(raw) as { release_timestamp?: unknown }, + () => null, + ); + // The record as written, not coerceLiveRecording's: that drops a part with + // no `startedAt`, and a "from now" part with no start must still say "no + // zero" rather than fall back to the broadcast's start. + const record = await readFile(path.join(videoDir, LIVE_RECORDING_FILENAME), "utf8").then( + (raw) => { + const parsed: unknown = JSON.parse(raw); + return coerceLiveRecording(parsed) ? (parsed as LiveRecordingLike) : null; + }, + () => null, + ); + return liveChatClockZero(parsedMeta, record); +} + +/** + * Parse a raw replay onto the recording's clock. The zero is read only when + * the raw holds a line captured live: a pure replay is never moved, and costs + * no extra read. + */ +export async function parseLiveChatOnRecordingClock( + videoDir: string, + raw: string, + meta?: { release_timestamp?: unknown } | null, +): Promise<{ cues: Cue[]; clock: LiveChatClock }> { + const zero: LiveChatZero = hasLiveCapturedLines(raw) + ? await readLiveChatZero(videoDir, meta) + : { zeroMs: null, basis: "capture-start", certain: false }; + const { cues, stats } = parseLiveChatDetailed(raw, { liveZeroMs: zero.zeroMs }); + return { cues, clock: liveChatClockOf(zero, stats) }; +} + // TODO: live_chat files can be hundreds of MB. parseLiveChat already splits // on "\n", so a streaming readline variant is straightforward if we hit a // memory wall. For now this matches the readFile pattern used by the @@ -99,8 +168,13 @@ export async function normalizeLiveChat( const rawLiveChat = await readFile(rawPath, "utf8"); let cues: Cue[]; + let clock: LiveChatClock; try { - cues = parseLiveChat(rawLiveChat); + ({ cues, clock } = await parseLiveChatOnRecordingClock( + opts.videoDir, + rawLiveChat, + parsedMeta as { release_timestamp?: unknown }, + )); } catch (err) { throw new Error( `Failed to parse ${LIVE_CHAT_FILENAME} for ${opts.channelSlug}/${path.basename(opts.videoDir)}: ${(err as Error).message}`, @@ -111,13 +185,15 @@ export async function normalizeLiveChat( version: LIVE_CHAT_FILE_VERSION, source: "live_chat", ...summary, + clock, cues, }; // Compact, no trailing newline: live_chat.cues.json's historical bytes. await writeJsonAtomic(cuesPath, out, { indent: 0, newline: false }); opts.log?.( - `Normalized live chat ${opts.channelSlug}/${path.basename(opts.videoDir)} (${cues.length} cues)`, + `Normalized live chat ${opts.channelSlug}/${path.basename(opts.videoDir)} (${cues.length} cues)` + + clockNote(clock), ); // THE MEDIA TIER'S HOOK (release 17): the raw replay is read once, here, and // every other reader uses the cues just written — so it moves into @@ -128,6 +204,20 @@ export async function normalizeLiveChat( return { status: "wrote", cuesPath }; } +// The log's word on the clock, for a chat that had lines captured live. +function clockNote(clock: LiveChatClock): string { + if (clock.basis === "replay") return ""; + const dup = clock.duplicatesDropped > 0 ? `, ${clock.duplicatesDropped} duplicate(s) of the replay dropped` : ""; + if (clock.basis === "capture-start") { + return ` — ${clock.liveLines} line(s) captured live, left on the capture's clock (no zero known for the recording)${dup}`; + } + const shift = clock.shiftSeconds !== undefined ? ` ${clock.shiftSeconds} s` : ""; + return ( + ` — ${clock.liveLines} line(s) captured live, moved${shift} onto the recording's clock ` + + `(${clock.basis}${clock.certain ? "" : ", not certain"})${dup}` + ); +} + export async function readNormalizedLiveChat( cuesPath: string, ): Promise<NormalizedLiveChat | null> { @@ -144,7 +234,8 @@ export async function readNormalizedLiveChat( // Sidecar is fresh iff it exists and its mtime is >= both metadata.info.json // and transcript.live_chat.json. Used by buildIndex to decide whether to -// trust the cached cues without re-parsing the raw payload. +// trust the cached cues without re-parsing the raw payload. Its version is +// not asked (LIVE_CHAT_FILE_VERSION above). export async function isLiveChatCuesFresh( videoDir: string, ): Promise<{ fresh: boolean; cuesPath: string }> { diff --git a/common/controller/normalizeTranscript.ts b/common/controller/normalizeTranscript.ts @@ -12,6 +12,7 @@ import { parseTranscriptJson, } from "../lib/whisper"; import type { TranscriptOutputFormat } from "../lib/transcriptionApps"; +import type { LiveChatClock } from "../lib/liveChat"; import { summarize, type RawMetadata } from "../lib/transcripts-server"; import type { TranscriptDetail } from "../lib/transcripts"; import { @@ -51,7 +52,9 @@ export type NormalizedTranscript = TranscriptDetail & { transcriptFormat?: TranscriptOutputFormat; }; -export type NormalizedLiveChat = NormalizedTranscript & { source: "live_chat" }; +// `clock` (version 2, lane chat-clock): the clock a chat's cues were put on +// (lib/liveChat.ts LiveChatClock). Absent from a version-1 file. +export type NormalizedLiveChat = NormalizedTranscript & { source: "live_chat"; clock?: LiveChatClock }; export type NormalizeOptions = { videoDir: string; diff --git a/common/lib/liveChat.test.ts b/common/lib/liveChat.test.ts @@ -0,0 +1,113 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + hasLiveCapturedLines, + liveChatClockOf, + liveChatClockZero, + parseLiveChat, + parseLiveChatDetailed, +} from "./liveChat"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/liveChat.test.ts +// +// The pure half of lane chat-clock: the parser's two clocks and the +// recording's zero. normalizeLiveChat.test.ts drives it through the files. + +const T0 = Date.UTC(2026, 0, 2, 3, 0, 0); + +function line(o: { offsetMs: number; live?: boolean; postedMs?: number; id?: string; text?: string }): string { + const renderer: Record<string, unknown> = { + message: { simpleText: o.text ?? "hi" }, + authorName: { simpleText: "viewer1" }, + }; + if (o.id) renderer.id = o.id; + if (o.postedMs !== undefined) renderer.timestampUsec = String(o.postedMs * 1000); + const actions = [{ addChatItemAction: { item: { liveChatTextMessageRenderer: renderer } } }]; + return o.live + ? JSON.stringify({ replayChatItemAction: { actions }, videoOffsetTimeMsec: String(o.offsetMs), isLive: true }) + : JSON.stringify({ replayChatItemAction: { actions, videoOffsetTimeMsec: String(o.offsetMs) } }); +} + +test("without a zero, the parser answers exactly as before (live and replay lines alike)", () => { + const src = [line({ offsetMs: 5000, live: true, postedMs: T0 + 9000 }), line({ offsetMs: 2000 })].join("\n"); + assert.deepEqual(parseLiveChat(src).map((c) => c.start), [2, 5]); +}); + +test("a live line with no timestamp of its own takes the capture zero before it", () => { + const capture = T0 + 600_000; + const src = [ + line({ offsetMs: 1000, live: true, postedMs: capture + 1000, id: "a" }), + line({ offsetMs: 4000, live: true, id: "b" }), + ].join("\n"); + const { cues, stats } = parseLiveChatDetailed(src, { liveZeroMs: T0 }); + assert.deepEqual(cues.map((c) => c.start), [601, 604]); + assert.equal(stats.captureZeroMs, capture); +}); + +test("two capture sessions in one file: each message by its own posting time", () => { + const src = [ + line({ offsetMs: 1000, live: true, postedMs: T0 + 101_000, id: "a" }), + line({ offsetMs: 1000, live: true, postedMs: T0 + 901_000, id: "b" }), + ].join("\n"); + assert.deepEqual(parseLiveChat(src, { liveZeroMs: T0 }).map((c) => c.start), [101, 901]); +}); + +test("the cheap scan for a live capture", () => { + assert.equal(hasLiveCapturedLines(line({ offsetMs: 0, live: true })), true); + assert.equal(hasLiveCapturedLines(line({ offsetMs: 0 })), false); +}); + +test("the recording's zero", () => { + const meta = { release_timestamp: T0 / 1000 }; + const part = (fromStart: boolean, startedAt = new Date(T0 + 50_000).toISOString()) => ({ fromStart, startedAt }); + // From the start, landed or still recording; no recording at all. + assert.deepEqual(liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [part(true)] }), { + zeroMs: T0, basis: "broadcast-start", certain: true, + }); + assert.equal(liveChatClockZero(meta, { status: "recording", parts: [part(true)] }).zeroMs, T0); + assert.equal(liveChatClockZero(meta, null).zeroMs, T0); + // A playlist reach that missed the first 60 s of the broadcast. + assert.equal( + liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [part(true)], reach: { fromStart: false, missingSeconds: 60 } }).zeroMs, + T0 + 60_000, + ); + // From now: the part's start, not certain. + assert.deepEqual(liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [part(false)] }), { + zeroMs: T0 + 50_000, basis: "recording-start", certain: false, + }); + // From now with no readable start: no zero (never the broadcast's start). + for (const startedAt of [undefined, "not a date"]) { + assert.deepEqual( + liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [{ fromStart: false, ...(startedAt ? { startedAt } : {}) }] }), + { zeroMs: null, basis: "capture-start", certain: false }, + ); + } + // The landed part missing from the record: the record's own mode decides. + assert.deepEqual(liveChatClockZero(meta, { status: "landed", landedPart: 0, fromStart: false, parts: [] }), { + zeroMs: null, basis: "capture-start", certain: false, + }); + assert.equal(liveChatClockZero(meta, { status: "landed", landedPart: 0, fromStart: true, parts: [] }).zeroMs, T0); + // A recording that landed nothing did not make the media. + assert.equal(liveChatClockZero(meta, { status: "failed", parts: [part(false)] }).basis, "broadcast-start"); + // Nothing known. + assert.deepEqual(liveChatClockZero({}, null), { zeroMs: null, basis: "capture-start", certain: false }); +}); + +test("the clock record", () => { + const stats = { liveLines: 2, replayLines: 1, duplicatesDropped: 1, captureZeroMs: T0 + 2_234_980 }; + assert.deepEqual(liveChatClockOf({ zeroMs: T0, basis: "broadcast-start", certain: true }, stats), { + basis: "broadcast-start", + certain: true, + zeroAt: new Date(T0).toISOString(), + captureStartedAt: new Date(T0 + 2_234_980).toISOString(), + shiftSeconds: 2234.98, + liveLines: 2, + replayLines: 1, + duplicatesDropped: 1, + }); + assert.equal( + liveChatClockOf({ zeroMs: null, basis: "capture-start", certain: false }, { ...stats, liveLines: 0 }).basis, + "replay", + ); +}); diff --git a/common/lib/liveChat.ts b/common/lib/liveChat.ts @@ -7,7 +7,8 @@ import type { Cue } from "./vtt"; // `liveChatPaidMessageRenderer`, `liveChatMembershipItemRenderer`, etc.). // // We emit one Cue per addChatItemAction that has a renderable text body, with -// `start` derived from `videoOffsetTimeMsec` and `text` formatted as +// `start` derived from `videoOffsetTimeMsec` — on the recording's clock for a +// line captured while live (parseLiveChatDetailed) — and `text` formatted as // `<author>: <message>`. Non-text events (ticker pings without an associated // message, viewer-engagement nags) are skipped. @@ -19,6 +20,9 @@ type ChatRenderer = { headerSubtext?: MessageBody; text?: MessageBody; authorName?: AuthorBody; + // The message's id and its posting time (epoch µs, a string). + id?: string; + timestampUsec?: string; }; type ChatItem = Record<string, ChatRenderer | undefined>; type AddAction = { item?: ChatItem }; @@ -30,6 +34,8 @@ type ReplayAction = { type ReplayEnvelope = { replayChatItemAction?: ReplayAction; videoOffsetTimeMsec?: string; + // yt-dlp's mark on a line captured while the stream was live. + isLive?: boolean; }; const TEXT_RENDERERS = [ @@ -71,11 +77,75 @@ function textOf(renderer: ChatRenderer): string { ); } -export function parseLiveChat(src: string): Cue[] { +// ONE CLOCK PER RECORDING, THE CUES' (lane chat-clock, 20 Nov 2026). yt-dlp +// writes two kinds of line, and they are not on one clock: +// +// a REPLAY line (the chat fetched after the stream) carries YouTube's own +// `videoOffsetTimeMsec` — the VOD's clock, zero at the broadcast's start; +// a LIVE line (`"isLive": true`, the chat captured while the stream is live) +// carries `timestampUsec/1000 − start_time`, where start_time is the +// moment yt-dlp's chat downloader began — the CAPTURE's clock. A capture +// begun 37 minutes into a broadcast put every message 37 minutes early on a +// from-start recording. +// +// So a live line is placed by its item's ABSOLUTE posting time against the +// recording's zero (`liveZeroMs`, liveChatClockZero below) — not by the offset +// plus one constant, so a file stitched from several capture sessions (several +// start_times) still comes out right. A replay line is never moved. A live +// line with no timestamp of its own is placed by the nearest capture zero +// before it (else the file's first). With no zero, live lines keep yt-dlp's +// offsets, exactly as before, and the stats say so. +// +// A file can hold both: yt-dlp resuming a live `.part` after the stream ended +// appends the replay, from 0, below the live head — whose messages the replay +// mostly carries again. A message (item `id`) the replay holds is taken from +// the replay alone; a line with no id is never dropped. + +export type LiveChatParseStats = { + liveLines: number; + replayLines: number; + duplicatesDropped: number; + // The median capture zero (epoch ms) of the live messages that carry a + // timestamp: `timestampUsec/1000 − videoOffsetTimeMsec`. Null with none. + captureZeroMs: number | null; +}; + +export type ParseLiveChatOptions = { + // The recording's zero, epoch ms (liveChatClockZero). Absent or null: live + // lines keep yt-dlp's capture-relative offsets. + liveZeroMs?: number | null; +}; + +type Entry = { + offsetMs: number; + live: boolean; + postedMs: number | null; + id: string | null; + text: string; + line: number; +}; + +/** Does this raw replay hold any line captured while live? (A cheap scan.) */ +export function hasLiveCapturedLines(src: string): boolean { + return /"isLive"\s*:\s*true/.test(src); +} + +function median(xs: number[]): number | null { + if (xs.length === 0) return null; + const s = [...xs].sort((a, b) => a - b); + return s[Math.floor(s.length / 2)]; +} + +export function parseLiveChatDetailed( + src: string, + opts: ParseLiveChatOptions = {}, +): { cues: Cue[]; stats: LiveChatParseStats } { const lines = src.split("\n"); - const cues: Cue[] = []; - for (const line of lines) { - const trimmed = line.trim(); + const entries: Entry[] = []; + let liveLines = 0; + let replayLines = 0; + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i].trim(); if (!trimmed) continue; let envelope: ReplayEnvelope; try { @@ -88,7 +158,9 @@ export function parseLiveChat(src: string): Cue[] { replay?.videoOffsetTimeMsec ?? envelope.videoOffsetTimeMsec; const offsetMs = offsetRaw ? Number(offsetRaw) : NaN; if (!Number.isFinite(offsetMs)) continue; - const start = offsetMs / 1000; + const live = envelope.isLive === true; + if (live) liveLines++; + else replayLines++; for (const action of replay?.actions ?? []) { const item = action.addChatItemAction?.item; if (!item) continue; @@ -98,15 +170,166 @@ export function parseLiveChat(src: string): Cue[] { const text = textOf(renderer).trim(); if (!text) continue; const author = authorOf(renderer); - cues.push({ - start, - end: start + 5, + const usec = renderer.timestampUsec ? Number(renderer.timestampUsec) : NaN; + entries.push({ + offsetMs, + live, + postedMs: Number.isFinite(usec) ? usec / 1000 : null, + id: typeof renderer.id === "string" && renderer.id ? renderer.id : null, text: author ? `${author}: ${text}` : text, + line: i, }); break; } } } + + // The capture zero of every timestamped live message, in file order. + const zeros: { line: number; zeroMs: number }[] = []; + for (const e of entries) { + if (e.live && e.postedMs !== null) zeros.push({ line: e.line, zeroMs: e.postedMs - e.offsetMs }); + } + const captureZeroMs = median(zeros.map((z) => z.zeroMs)); + + const replayIds = new Set<string>(); + for (const e of entries) if (!e.live && e.id) replayIds.add(e.id); + + const liveZeroMs = opts.liveZeroMs ?? null; + const cues: Cue[] = []; + let duplicatesDropped = 0; + let zi = 0; + let lastZero: number | null = null; + for (const e of entries) { + let start = e.offsetMs / 1000; + if (e.live) { + if (e.id && replayIds.has(e.id)) { + duplicatesDropped++; + continue; + } + while (zi < zeros.length && zeros[zi].line <= e.line) lastZero = zeros[zi++].zeroMs; + if (liveZeroMs !== null) { + if (e.postedMs !== null) start = (e.postedMs - liveZeroMs) / 1000; + else { + const zero = lastZero ?? zeros[0]?.zeroMs ?? null; + if (zero !== null) start = (e.offsetMs + zero - liveZeroMs) / 1000; + } + } + } + cues.push({ start, end: start + 5, text: e.text }); + } cues.sort((a, b) => a.start - b.start); - return cues; + return { cues, stats: { liveLines, replayLines, duplicatesDropped, captureZeroMs } }; +} + +export function parseLiveChat(src: string, opts: ParseLiveChatOptions = {}): Cue[] { + return parseLiveChatDetailed(src, opts).cues; +} + +// --- the recording's zero ------------------------------------------------------ + +export type LiveChatClockBasis = + // the broadcast's start (metadata `release_timestamp`): a from-start + // recording's zero, and the post-live VOD's + | "broadcast-start" + // a recording begun "from now": its landed part's own start + | "recording-start" + // no zero known: the live lines kept the capture's clock + | "capture-start" + // no line was captured live: nothing was moved + | "replay"; + +export type LiveChatZero = { + zeroMs: number | null; + basis: Exclude<LiveChatClockBasis, "replay">; + certain: boolean; +}; + +// The part of live-recording.json this reads (lib/liveCapture.ts +// LiveRecordingRecord), structurally, so this file stays import-free. +export type LiveRecordingLike = { + status?: string; + // The record's own mode, for a part the record cannot show. + fromStart?: boolean; + landedPart?: number; + parts?: { fromStart?: boolean; startedAt?: string }[]; + reach?: { fromStart?: boolean; missingSeconds?: number | null } | null; +}; + +/** + * The epoch ms the RECORDING's clock (the cues', the saved container's) is + * zero at, for a YouTube chat captured live. + * + * - The part that made the media — the landed one, or the latest while it is + * still recording (a chat can be normalized before the recording lands) — + * recorded from the start, or no recording at all (the media is the + * post-live VOD): the broadcast's start, `release_timestamp`, plus the + * stretch a recorded playlist reach said was no longer listed. Certain to + * the second (measured 20 Nov: four lines a streamer read aloud sat 6–14 s + * after it — the stream's latency and the reading, which stay). + * - A part recorded "from now": that part's start — yt-dlp's start-up and the + * live edge's lag are not known, so it is NOT certain. With no readable + * start, no zero: the broadcast's start is known to be wrong for it. + * - A failed or cancelled recording that landed nothing did not make the + * media: as if there were none. + * - Neither known: null (the capture's clock stays). + */ +export function liveChatClockZero( + meta: { release_timestamp?: unknown } | null | undefined, + record: LiveRecordingLike | null | undefined, +): LiveChatZero { + const parts = Array.isArray(record?.parts) ? record.parts : []; + // The recording made the media when it landed a part or is still recording. + const madeMedia = typeof record?.landedPart === "number" || record?.status === "recording"; + const picked = typeof record?.landedPart === "number" ? parts[record.landedPart] : madeMedia ? parts.at(-1) : undefined; + const part = picked && typeof picked === "object" ? picked : undefined; + // The part's own mode, else the record's (a part missing from the record). + const fromStart = part && typeof part.fromStart === "boolean" ? part.fromStart : madeMedia ? record?.fromStart : undefined; + if (fromStart === false) { + const startedMs = typeof part?.startedAt === "string" ? Date.parse(part.startedAt) : NaN; + if (Number.isFinite(startedMs)) return { zeroMs: startedMs, basis: "recording-start", certain: false }; + // A "from now" recording with no readable start: the broadcast's start is + // known to be the WRONG zero here, so there is none. + return { zeroMs: null, basis: "capture-start", certain: false }; + } + const release = meta?.release_timestamp; + if (typeof release === "number" && Number.isFinite(release) && release > 0) { + const reach = madeMedia ? record?.reach : null; + const missing = + reach && reach.fromStart === false && typeof reach.missingSeconds === "number" ? reach.missingSeconds : 0; + return { zeroMs: (release + missing) * 1000, basis: "broadcast-start", certain: true }; + } + return { zeroMs: null, basis: "capture-start", certain: false }; +} + +// What live_chat.cues.json records of the clock it was put on (version 2). +export type LiveChatClock = { + basis: LiveChatClockBasis; + certain: boolean; + // The recording's zero the live lines were placed against. + zeroAt?: string; + // The median capture start, and how far after the zero it was. + captureStartedAt?: string; + shiftSeconds?: number; + liveLines: number; + replayLines: number; + duplicatesDropped: number; +}; + +export function liveChatClockOf(zero: LiveChatZero, stats: LiveChatParseStats): LiveChatClock { + const counts = { + liveLines: stats.liveLines, + replayLines: stats.replayLines, + duplicatesDropped: stats.duplicatesDropped, + }; + if (stats.liveLines === 0) return { basis: "replay", certain: true, ...counts }; + const capture = stats.captureZeroMs; + const placed = zero.zeroMs !== null; + return { + basis: placed ? zero.basis : "capture-start", + certain: placed ? zero.certain : false, + ...(placed ? { zeroAt: new Date(zero.zeroMs as number).toISOString() } : {}), + ...(capture !== null ? { captureStartedAt: new Date(capture).toISOString() } : {}), + ...(capture !== null && placed ? { shiftSeconds: Math.round(capture - (zero.zeroMs as number)) / 1000 } : {}), + ...counts, + }; } diff --git a/common/lib/sourceStatus-server.mjs b/common/lib/sourceStatus-server.mjs @@ -0,0 +1,70 @@ +// The disk half of the source status (./sourceStatus.mjs): one video directory's +// records read and handed to deriveSourceStatus. READ ONLY, and only these five +// files: availability.json, download-outcome.json, metadata.info.json, +// metadata.history.json, live-recording.json. A file that is missing or is not +// JSON is null, never an error: no record is no state. +// +// SERVER-ONLY (node:fs). Plain JS: umtool's bins run under bare node. + +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; + +import { deriveSourceStatus } from "./sourceStatus.mjs"; + +/** The record files a source status is read from, by deriveSourceStatus's names. */ +export const SOURCE_RECORD_FILES = Object.freeze({ + availability: "availability.json", + outcome: "download-outcome.json", + metadata: "metadata.info.json", + metadataHistory: "metadata.history.json", + liveRecording: "live-recording.json", +}); + +async function readJson(file) { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch { + return null; + } +} + +/** The records deriveSourceStatus reads, from one video directory. */ +export async function readSourceRecords(videoDir) { + const entries = await Promise.all( + Object.entries(SOURCE_RECORD_FILES).map(async ([k, name]) => [k, await readJson(path.join(videoDir, name))]), + ); + const records = Object.fromEntries(entries); + // metadata.info.json can be tens of MB (formats, captions): keep the few fields read. + const m = records.metadata; + if (m && typeof m === "object") { + records.metadata = { + ...(Object.hasOwn(m, "availability") ? { availability: m.availability } : {}), + ...(Object.hasOwn(m, "live_status") ? { live_status: m.live_status } : {}), + ...(Number.isFinite(m.epoch) ? { epoch: m.epoch } : {}), + ...(Number.isFinite(m.release_timestamp) ? { release_timestamp: m.release_timestamp } : {}), + ...(Number.isFinite(m.duration) ? { duration: m.duration } : {}), + }; + } + return records; +} + +/** One video directory's source status (deriveSourceStatus), or null. */ +export async function readSourceStatus(videoDir) { + return deriveSourceStatus(await readSourceRecords(videoDir)); +} + +/** + * The newest modification time (ms, whole) of the record files in one video + * directory, or null when it holds none: what a stamp keeps per source + * (`recordsAt`), so `umtool check` says it is out of date only when a record + * was written after the reading it holds -- not after the stamp's own write, + * which a refresh that found nothing new does not make. + */ +export async function newestSourceRecordMs(videoDir) { + let newest = null; + for (const name of Object.values(SOURCE_RECORD_FILES)) { + const st = await stat(path.join(videoDir, name)).catch(() => null); + if (st?.isFile()) newest = Math.max(newest ?? 0, Math.floor(st.mtimeMs)); + } + return newest; +} diff --git a/common/lib/sourceStatus.mjs b/common/lib/sourceStatus.mjs @@ -0,0 +1,306 @@ +// WHAT BECAME OF A RECORDING'S SOURCE, AND WHAT IT WAS AT FIRST (lane source-status). +// +// A report video clips streams a streamer later privates, deletes or moves behind a +// membership. Its source line says so ("… · now private (public when streamed)"), and +// the line may only say what the archive's own records prove. This is the one +// reading of those records: pure, plain JS (umtool's bins run under bare node), fed +// the parsed files of one video directory by sourceStatus-server.mjs. +// +// NOW is the effective availability every other reader uses +// (availability-server.ts resolveEffectiveAvailabilityObserved, re-stated here +// because umtool cannot import TypeScript, and kept to its rules: the +// download-outcome's last class wins only when its finishedAt is LATER than the +// record's checkedAt, both parseable, and only an outcome of +// coerceDownloadOutcome's shape counts). `since` is the first time the archive +// saw that state (the trailing run of history entries that agree with it), +// `asOf` the newest observation behind it. Two rules on top, both of which draw +// NOTHING (`now: null`, the reason kept as an evidence item) rather than a claim +// the records do not make: +// +// DELETED only from the channel's Check availability: availability.json's own +// top level written by a check (`checkedBy: "check"`, or a legacy record with +// no checkedBy whose trailing run holds a check). A download's class is +// parseUnavailableFromStderr over its stderr, and any bare "Video unavailable" +// (a region block, a transient answer) reads "deleted" there. +// THE RECORDS DISAGREE: a first-hand public or unlisted reading NEWER than the +// state's asOf -- the metadata's own field at its epoch (a successful persist +// rewrites it and writes no availability entry), a check/fetch history entry, +// or a download that succeeded without cookies -- means the source may be +// back. `asOf` is then that newer reading's time. +// +// The published archive's "deleted" is the same effective reading +// (buildIndex), so umtool source-status does not draw it either. +// +// WAS PUBLIC is said only with EVIDENCE, each item kept with its time: +// +// metadata metadata.info.json's OWN `availability: "public"` field, at the time +// the file was saved (`epoch`), and every earlier state of it that +// metadata.history.json lets us rebuild. The field must be there. +// fetch an availability.json history entry of "public" written by a +// one-video fetch: a metadata refresh records only a field that is +// there (refreshVideoMetadata), so it is the platform's own word. +// check the same written by a real probe -- but checkAvailability reads a +// MISSING field (an extractor that sets none) or unparseable output +// as "public", and the record does not say which it was. So a check's +// public counts only when this video's metadata shows its extractor +// reports the field (some snapshot carries a string `availability`). +// The limit left: a check whose own output had no parseable JSON, +// on a video whose metadata has the field, still reads public. +// +// "When streamed": a metadata snapshot that was itself taken while the stream was +// live (`live_status: "is_live"`), or a check/fetch observation inside the stream's +// span (release_timestamp .. + duration, else the live recording's end). +// +// NOT EVIDENCE, and recorded as such (`counts: false`): +// +// backfill a copy of metadata's field that turns a MISSING field into +// "public" (availabilityFromJsonField): the metadata is the +// evidence, not the copy. +// download a download attempt's class in the history: stderr read +// loosely, not the platform's field. +// live recording the recorder passes the channel's cookies when its policy says +// so and does not record whether it did: a member's login records a +// members-only stream as well as a public one. +// a download without cookies watchable without a login: public OR unlisted. +// +// Client-safe: no node: imports. + +/** The states a viewer cannot watch at the platform (availability.ts NOT_PUBLIC_STATES, by availability). */ +export const NOT_PUBLIC = Object.freeze(["private", "members_only", "deleted"]); + +/** availability.ts AVAILABILITY_VALUES: every value a stamp's `now` may hold, beside null. */ +export const AVAILABILITIES = Object.freeze(["public", "unlisted", "private", "members_only", "needs_auth", "deleted", "error"]); +const AVAILABLE = new Set(AVAILABILITIES); + +/** downloadOutcome.ts DOWNLOAD_OUTCOME_STATUS_VALUES (coerceDownloadOutcome's shape check). */ +const OUTCOME_STATUSES = new Set([ + "ok", "ok-with-cookies", "ok-auto-transcribed", "ok-audio-checked", "failed", "failed-corrupt-source", + "corrupt-full-source", "failed-short-audio", "skipped-filtered", "chat-only", +]); + +/** The metadata field's words that mean anyone could watch it (yt-dlp's, availabilityFromJsonField). */ +const OPEN_FIELD = new Map([["public", "public"], ["unlisted", "unlisted"], ["public_unlisted", "unlisted"]]); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const msOf = (iso) => { + const t = typeof iso === "string" ? Date.parse(iso) : NaN; + return Number.isFinite(t) ? t : null; +}; +const isoOf = (ms) => (ms === null ? null : new Date(ms).toISOString()); +/** `a` strictly after `b`, both parseable (a Date comparison with NaN is false: availability-server.ts). */ +const later = (a, b) => { + const x = msOf(a); + const y = msOf(b); + return x !== null && y !== null && x > y; +}; + +/** availability.json as availability-server.ts coerceAvailability accepts it, else null. */ +function explicitOf(rec) { + return isObj(rec) && AVAILABLE.has(rec.availability) && typeof rec.checkedAt === "string" ? rec : null; +} + +/** download-outcome.json as downloadOutcome-server.ts coerceDownloadOutcome accepts it, else null. */ +function outcomeRecordOf(rec) { + return isObj(rec) && OUTCOME_STATUSES.has(rec.status) && typeof rec.videoId === "string" && + typeof rec.startedAt === "string" && typeof rec.finishedAt === "string" && Array.isArray(rec.attempts) + ? rec + : null; +} + +/** The outcome's last attempt's class, as loadDownloadOutcomeAvailability reads it. */ +function outcomeOf(rec) { + const cls = rec?.attempts.at(-1)?.availabilityClass; + return AVAILABLE.has(cls) ? { availability: cls, finishedAt: rec.finishedAt } : null; +} + +/** A download that succeeded on its last attempt without cookies: anyone could watch it then. */ +function cookielessSuccess(rec) { + return Boolean(rec && rec.status.startsWith("ok") && rec.status !== "ok-with-cookies" && rec.attempts.at(-1)?.usedCookies === false); +} + +function firstOfTrailingRun(record, availability) { + const history = Array.isArray(record.history) ? record.history : []; + let since = null; + for (let i = history.length - 1; i >= 0; i--) { + if (history[i]?.availability !== availability) break; + since = history[i].observedAt ?? null; + } + return since; +} + +/** + * The metadata's states over time, oldest first: `{ at, availability, liveStatus }`, + * `availability` the file's own field (undefined when it was absent). The current + * file is the last; metadata.history.json's entries, walked back, give the ones + * before (an entry's `changed[k].from`, `removed[k]`, or absent for `added[k]`). + */ +export function metadataSnapshots(metadata, history) { + if (!isObj(metadata)) return []; + const KEYS = ["availability", "live_status"]; + const cur = Object.fromEntries(KEYS.map((k) => [k, metadata[k]])); + const epochMs = Number.isFinite(metadata.epoch) ? metadata.epoch * 1000 : null; + const entries = isObj(history) && Array.isArray(history.entries) ? history.entries.filter(isObj) : []; + const shots = []; + let values = { ...cur }; + let at = epochMs ?? msOf(entries.at(-1)?.at); + shots.push({ at, ...values }); + for (let i = entries.length - 1; i >= 0; i--) { + const e = entries[i]; + const before = { ...values }; + for (const k of KEYS) { + if (isObj(e.changed) && isObj(e.changed[k]) && "from" in e.changed[k]) before[k] = e.changed[k].from; + else if (isObj(e.added) && k in e.added) before[k] = undefined; + else if (isObj(e.removed) && k in e.removed) before[k] = e.removed[k]; + } + values = before; + at = msOf(e.from?.at); + shots.push({ at, ...values }); + } + return shots + .reverse() + .map((s) => ({ at: isoOf(s.at), availability: s.availability, liveStatus: s.live_status })); +} + +/** The stream's span, ms, when the records say it was a live: start, end (either may be null). */ +function liveSpan(metadata, liveRecording) { + const start = isObj(metadata) && Number.isFinite(metadata.release_timestamp) ? metadata.release_timestamp * 1000 : null; + let end = start !== null && Number.isFinite(metadata?.duration) ? start + metadata.duration * 1000 : null; + if (end === null && isObj(liveRecording)) end = msOf(liveRecording.endedAt); + return { start, end }; +} + +/** Was this deletion read by the channel's Check availability (see the header)? */ +function removalByCheck(explicit) { + if (explicit.availability !== "deleted") return false; + if (explicit.checkedBy === "check") return true; + if (explicit.checkedBy !== undefined) return false; + const history = Array.isArray(explicit.history) ? explicit.history : []; + for (let i = history.length - 1; i >= 0 && history[i]?.availability === "deleted"; i--) { + if (history[i].source === "check") return true; + } + return false; +} + +/** + * One video's source status from its parsed records, or null when the archive holds + * no availability reading for it at all (no record is no state: never "gone"). + * `now` is null when the records hold a state the line may not say (a removal not + * read by a check, or a newer reading that disagrees): the reason is an evidence + * item with `counts: false`. + * + * @param {{ availability?: any, outcome?: any, metadata?: any, metadataHistory?: any, liveRecording?: any }} records + * @returns {null | { now: string|null, since: string|null, asOf: string|null, first: "public"|null, firstAt: string|null, + * firstWhen: "live"|"other"|null, evidence: Array<Record<string, any>> }} + */ +export function deriveSourceStatus({ availability = null, outcome = null, metadata = null, metadataHistory = null, liveRecording = null } = {}) { + const explicit = explicitOf(availability); + const outRec = outcomeRecordOf(outcome); + const out = outcomeOf(outRec); + const fromOutcome = Boolean(out && (!explicit || later(out.finishedAt, explicit.checkedAt))); + /** @type {string|null} */ + let now; + let since; + let asOf; + if (fromOutcome) { + now = out.availability; + since = explicit ? firstOfTrailingRun(explicit, now) : null; + asOf = out.finishedAt; + } else if (explicit) { + now = explicit.availability; + since = firstOfTrailingRun(explicit, now); + asOf = explicit.checkedAt; + } else { + return null; + } + + const evidence = []; + const span = liveSpan(metadata, liveRecording); + const inLive = (ms) => ms !== null && span.start !== null && span.end !== null && ms >= span.start && ms <= span.end; + const shots = metadataSnapshots(metadata, metadataHistory); + // Does this video's extractor report the field at all (a check's "public" is then its word, not a default)? + const fieldReported = shots.some((x) => typeof x.availability === "string"); + + // A REMOVAL only from a check. + if (now === "deleted" && (fromOutcome || !removalByCheck(explicit))) { + evidence.push({ + kind: fromOutcome ? "download" : (explicit.checkedBy ?? "record"), at: asOf, availability: "deleted", counts: false, + why: fromOutcome + ? "a download's class: any \"Video unavailable\" (a region block, a transient answer) reads deleted -- a removal is read only by the channel's Check availability" + : "not written by the channel's Check availability, the one reader of a removal", + }); + now = null; + since = null; + } + + // THE RECORDS DISAGREE: a first-hand open reading newer than the state. + if (NOT_PUBLIC.includes(now)) { + const open = []; + for (const x of shots) { + const word = typeof x.availability === "string" ? OPEN_FIELD.get(x.availability) : undefined; + if (word && msOf(x.at) !== null) open.push({ from: "metadata", at: x.at, availability: word }); + } + for (const h of Array.isArray(explicit?.history) ? explicit.history : []) { + if (isObj(h) && (h.source === "check" || h.source === "fetch") && (h.availability === "public" || h.availability === "unlisted") && msOf(h.observedAt) !== null) { + open.push({ from: h.source, at: h.observedAt, availability: h.availability }); + } + } + if (cookielessSuccess(outRec) && msOf(outRec.finishedAt) !== null) open.push({ from: "download", at: outRec.finishedAt, availability: "public or unlisted" }); + const asOfMs = msOf(asOf); + const newer = open.filter((o) => asOfMs === null || msOf(o.at) > asOfMs).sort((p, q) => msOf(q.at) - msOf(p.at))[0]; + if (newer) { + evidence.push({ + kind: "disagree", at: newer.at, availability: newer.availability, from: newer.from, counts: false, + why: `a ${newer.from} reading of ${newer.availability} ${asOfMs === null ? "beside an undated" : "newer than the"} ${now} one: the records disagree, so nothing is drawn`, + }); + now = null; + since = null; + asOf = isoOf(msOf(newer.at)); + } + } + + for (const x of shots) { + if (x.availability !== "public") continue; + evidence.push({ kind: "metadata", at: x.at, availability: "public", ...(x.liveStatus ? { liveStatus: x.liveStatus } : {}), live: x.liveStatus === "is_live", counts: true }); + } + for (const h of Array.isArray(explicit?.history) ? explicit.history : []) { + if (!isObj(h) || h.availability !== "public") continue; + const ms = msOf(h.observedAt); + const at = h.observedAt ?? null; + if (h.source === "fetch" || (h.source === "check" && fieldReported)) { + evidence.push({ kind: h.source, at, availability: "public", live: inLive(ms), counts: true }); + } else if (h.source === "check") { + evidence.push({ kind: "check", at, availability: "public", counts: false, + why: "a check reads a missing field as public, and this video's metadata carries no availability field" }); + } else if (h.source === "download") { + evidence.push({ kind: "download", at, availability: "public", counts: false, + why: "a download attempt's class (its stderr read loosely), not the platform's field" }); + } else { + evidence.push({ kind: h.source ?? "backfill", at, availability: "public", counts: false, + why: "a copy of the metadata's field (a missing field reads public)" }); + } + } + if (isObj(liveRecording)) { + evidence.push({ kind: "live-recording", at: typeof liveRecording.startedAt === "string" ? liveRecording.startedAt : null, counts: false, + why: "recorded live, possibly with the channel's cookies (not recorded): a members-only stream records too" }); + } + if (cookielessSuccess(outRec)) { + evidence.push({ kind: "download", at: outRec.finishedAt, counts: false, + why: "downloaded without cookies: public or unlisted" }); + } + + // Evidence of the FIRST state precedes the state it is first to: an observation + // after `since` (when both are dated) says nothing about how it started. + const sinceMs = msOf(since); + const counting = evidence.filter((e) => e.counts && (sinceMs === null || msOf(e.at) === null || msOf(e.at) <= sinceMs)); + const first = NOT_PUBLIC.includes(now) && counting.length ? "public" : null; + const dated = counting.map((e) => msOf(e.at)).filter((t) => t !== null); + return { + now, + since: since ?? null, + asOf: asOf ?? null, + first, + firstAt: first && dated.length ? isoOf(Math.min(...dated)) : null, + firstWhen: first ? (counting.some((e) => e.live) ? "live" : "other") : null, + evidence, + }; +} diff --git a/common/lib/sourceStatus.test.ts b/common/lib/sourceStatus.test.ts @@ -0,0 +1,281 @@ +// The source status (lane source-status): what became of a recording's source and +// what it was at first -- "was public" only from the evidence the records hold, never +// from a backfill default, a live recording or a cookieless download alone. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/sourceStatus.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { deriveSourceStatus, metadataSnapshots } from "./sourceStatus.mjs"; +import { readSourceStatus } from "./sourceStatus-server.mjs"; + +const sec = (iso: string) => Date.parse(iso) / 1000; + +// A synthetic stream: live 10:00 -> 14:00 on 1 Mar 2031. +const LIVE_META = { + availability: "public", + live_status: "is_live", + epoch: sec("2031-03-01T10:05:00Z"), + release_timestamp: sec("2031-03-01T10:00:00Z"), +}; +/** A download-outcome.json of coerceDownloadOutcome's shape. */ +const outcomeOf = (o: Record<string, unknown>) => ({ videoId: "synth-vid-001", startedAt: "2031-03-01T00:00:00Z", ...o }); + +const RECORDING = { status: "landed", startedAt: "2031-03-01T10:01:00Z", endedAt: "2031-03-01T14:00:00Z" }; + +test("public when streamed, then members-only: the metadata saved during the live is the evidence", () => { + const s = deriveSourceStatus({ + availability: { + checkedAt: "2031-03-01T20:00:00Z", + checkedBy: "fetch", + availability: "members_only", + history: [ + { availability: "public", observedAt: "2031-03-01T10:30:00Z", source: "backfill" }, + { availability: "members_only", observedAt: "2031-03-01T20:00:00Z", source: "fetch" }, + ], + }, + metadata: LIVE_META, + liveRecording: RECORDING, + }); + assert.equal(s?.now, "members_only"); + assert.equal(s?.since, "2031-03-01T20:00:00Z"); + assert.equal(s?.asOf, "2031-03-01T20:00:00Z"); + assert.equal(s?.first, "public"); + assert.equal(s?.firstWhen, "live"); + assert.equal(s?.firstAt, "2031-03-01T10:05:00.000Z"); + assert.ok(s?.evidence.some((e) => e.kind === "metadata" && e.counts && e.live)); + assert.ok(s?.evidence.some((e) => e.kind === "backfill" && !e.counts)); +}); + +test("one observation only (private): the metadata saved while it was live says public", () => { + const s = deriveSourceStatus({ + availability: { + checkedAt: "2031-03-01T14:00:00Z", + checkedBy: "fetch", + availability: "private", + history: [{ availability: "private", observedAt: "2031-03-01T14:00:00Z", source: "fetch" }], + }, + metadata: LIVE_META, + liveRecording: RECORDING, + }); + assert.deepEqual([s?.now, s?.first, s?.firstWhen], ["private", "public", "live"]); +}); + +test("no availability record is no state", () => { + assert.equal(deriveSourceStatus({ metadata: LIVE_META, liveRecording: RECORDING }), null); + assert.equal(deriveSourceStatus({}), null); +}); + +test("NOT EVIDENCE: a backfill's public alone (the metadata has no availability field)", () => { + const s = deriveSourceStatus({ + availability: { + checkedAt: "2031-03-02T00:00:00Z", + availability: "private", + history: [ + { availability: "public", observedAt: "2031-03-01T10:30:00Z", source: "backfill" }, + { availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "fetch" }, + ], + }, + metadata: { live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z") }, + }); + assert.equal(s?.now, "private"); + assert.equal(s?.first, null); + assert.equal(s?.firstWhen, null); +}); + +test("NOT EVIDENCE: a live recording alone (it may have been made with a member's cookies)", () => { + const s = deriveSourceStatus({ + availability: { checkedAt: "2031-03-02T00:00:00Z", availability: "members_only", history: [{ availability: "members_only", observedAt: "2031-03-02T00:00:00Z", source: "fetch" }] }, + liveRecording: RECORDING, + }); + assert.equal(s?.first, null); + assert.ok(s?.evidence.some((e) => e.kind === "live-recording" && e.counts === false)); +}); + +test("NOT EVIDENCE: a download without cookies alone (public or unlisted)", () => { + const s = deriveSourceStatus({ + availability: { checkedAt: "2031-03-05T00:00:00Z", availability: "private", history: [{ availability: "private", observedAt: "2031-03-05T00:00:00Z", source: "fetch" }] }, + outcome: outcomeOf({ status: "ok", finishedAt: "2031-03-02T00:00:00Z", attempts: [{ n: 0, usedCookies: false, ytdlpExitCode: 0 }] }), + }); + assert.equal(s?.now, "private"); + assert.equal(s?.first, null); + assert.ok(s?.evidence.some((e) => e.kind === "download" && e.counts === false)); +}); + +test("the metadata's earlier state is rebuilt from metadata.history.json", () => { + const metadata = { availability: "private", live_status: "was_live", epoch: sec("2031-03-03T00:00:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z"), duration: 14400 }; + const history = { + entries: [ + { at: "2031-03-03T00:00:00Z", by: "refresh", from: { at: "2031-03-01T10:05:00Z" }, + changed: { availability: { from: "public", to: "private" }, live_status: { from: "is_live", to: "was_live" } }, added: {}, removed: {} }, + ], + }; + const shots = metadataSnapshots(metadata, history); + assert.deepEqual(shots.map((x) => [x.at, x.availability, x.liveStatus]), [ + ["2031-03-01T10:05:00.000Z", "public", "is_live"], + ["2031-03-03T00:00:00.000Z", "private", "was_live"], + ]); + const s = deriveSourceStatus({ + availability: { checkedAt: "2031-03-03T00:00:00Z", availability: "private", history: [{ availability: "private", observedAt: "2031-03-03T00:00:00Z", source: "fetch" }] }, + metadata, metadataHistory: history, + }); + assert.deepEqual([s?.first, s?.firstWhen, s?.firstAt], ["public", "live", "2031-03-01T10:05:00.000Z"]); +}); + +test("a check of public outside the live is 'other'; a removal a check read is 'deleted'", () => { + const s = deriveSourceStatus({ + availability: { + checkedAt: "2031-03-20T00:00:00Z", checkedBy: "check", availability: "deleted", + history: [ + { availability: "public", observedAt: "2031-03-10T00:00:00Z", source: "check" }, + { availability: "deleted", observedAt: "2031-03-20T00:00:00Z", source: "check" }, + ], + }, + metadata: { availability: "public", live_status: "was_live", epoch: sec("2031-03-09T00:00:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z"), duration: 14400 }, + }); + assert.deepEqual([s?.now, s?.asOf, s?.since, s?.first, s?.firstWhen], ["deleted", "2031-03-20T00:00:00Z", "2031-03-20T00:00:00Z", "public", "other"]); +}); + +test("a check of public inside the stream's span is 'live' (its extractor reports the field)", () => { + const s = deriveSourceStatus({ + availability: { + checkedAt: "2031-03-02T00:00:00Z", availability: "private", + history: [ + { availability: "public", observedAt: "2031-03-01T12:00:00Z", source: "check" }, + { availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "check" }, + ], + }, + // The field is there (it reads private now): the check's public was the platform's word. + metadata: { availability: "private", epoch: sec("2031-03-02T00:00:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z"), duration: 14400 }, + }); + assert.deepEqual([s?.now, s?.first, s?.firstWhen], ["private", "public", "live"]); +}); + +// REVIEW 1, finding 1: "now deleted" only from a check. +test("FALSE CLAIM GUARD: a download's 'deleted' newer than a check of public draws nothing", () => { + const s = deriveSourceStatus({ + availability: { checkedAt: "2031-03-10T00:00:00Z", checkedBy: "check", availability: "public", history: [{ availability: "public", observedAt: "2031-03-10T00:00:00Z", source: "check" }] }, + // "Video unavailable. The uploader has not made this video available in your country." classifies deleted. + outcome: outcomeOf({ status: "failed", finishedAt: "2031-03-20T00:00:00Z", attempts: [{ n: 0, usedCookies: false, availabilityClass: "deleted" }] }), + metadata: { availability: "public", live_status: "was_live", epoch: sec("2031-03-05T00:00:00Z") }, + }); + assert.equal(s?.now, null); + assert.equal(s?.first, null); + assert.equal(s?.asOf, "2031-03-20T00:00:00Z"); + assert.ok(s?.evidence.some((e) => e.kind === "download" && e.availability === "deleted" && e.counts === false)); +}); + +test("FALSE CLAIM GUARD: a top-level 'deleted' not written by a check draws nothing; a legacy one a check's history backs is deleted", () => { + const fetched = deriveSourceStatus({ availability: { checkedAt: "2031-03-10T00:00:00Z", checkedBy: "fetch", availability: "deleted", history: [{ availability: "deleted", observedAt: "2031-03-10T00:00:00Z", source: "fetch" }] } }); + assert.equal(fetched?.now, null); + const legacy = deriveSourceStatus({ availability: { checkedAt: "2031-03-10T00:00:00Z", availability: "deleted", history: [{ availability: "deleted", observedAt: "2031-03-10T00:00:00Z", source: "check" }] } }); + assert.equal(legacy?.now, "deleted"); + const bare = deriveSourceStatus({ availability: { checkedAt: "2031-03-10T00:00:00Z", availability: "deleted" } }); + assert.equal(bare?.now, null); +}); + +// REVIEW 1, finding 2: a newer first-hand public reading. +test("FALSE CLAIM GUARD: privated, then public again and persisted (metadata rewritten, no availability entry): nothing", () => { + const s = deriveSourceStatus({ + availability: { + checkedAt: "2031-03-02T00:00:00Z", checkedBy: "fetch", availability: "private", + history: [{ availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "fetch" }], + }, + metadata: { availability: "public", live_status: "was_live", epoch: sec("2031-03-04T00:00:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, + metadataHistory: { entries: [{ at: "2031-03-04T00:00:00Z", from: { at: "2031-03-01T10:05:00Z" }, changed: { live_status: { from: "is_live", to: "was_live" } } }] }, + }); + assert.equal(s?.now, null); + assert.equal(s?.asOf, "2031-03-04T00:00:00.000Z", "as of the newer reading"); + assert.ok(s?.evidence.some((e) => e.kind === "disagree" && e.from === "metadata" && e.counts === false)); + // A legacy record (no history) says the same. + const legacy = deriveSourceStatus({ + availability: { checkedAt: "2031-03-02T00:00:00Z", availability: "members_only" }, + metadata: { availability: "public", epoch: sec("2031-03-04T00:00:00Z") }, + }); + assert.equal(legacy?.now, null); + // A download that succeeded without cookies after the private reading: anyone could watch it. + const played = deriveSourceStatus({ + availability: { checkedAt: "2031-03-02T00:00:00Z", availability: "private", history: [{ availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "check" }] }, + outcome: outcomeOf({ status: "ok", finishedAt: "2031-03-03T00:00:00Z", attempts: [{ n: 0, usedCookies: false, ytdlpExitCode: 0 }] }), + }); + assert.equal(played?.now, null); + // An open reading OLDER than the state is the first state, not a disagreement. + const older = deriveSourceStatus({ + availability: { checkedAt: "2031-03-02T00:00:00Z", availability: "private", history: [{ availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "fetch" }] }, + metadata: { availability: "public", epoch: sec("2031-03-01T00:00:00Z") }, + }); + assert.deepEqual([older?.now, older?.first, older?.firstWhen], ["private", "public", "other"]); +}); + +test("an outcome's error or login wall newer than an explicit private: that is now, and the line draws nothing", () => { + for (const cls of ["error", "needs_auth"]) { + const s = deriveSourceStatus({ + availability: { checkedAt: "2031-03-02T00:00:00Z", checkedBy: "check", availability: "private", history: [{ availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "check" }] }, + outcome: outcomeOf({ status: "failed", finishedAt: "2031-03-03T00:00:00Z", attempts: [{ n: 0, usedCookies: false, availabilityClass: cls }] }), + metadata: LIVE_META, + }); + assert.deepEqual([s?.now, s?.first], [cls, null], cls); + } +}); + +// REVIEW 1, nit 9: the TypeScript reader's rules. +test("as availability-server.ts: an unparseable checkedAt lets the record win; an outcome of the wrong shape is no outcome", () => { + const record = { checkedAt: "not a time", checkedBy: "check", availability: "private" }; + const late = outcomeOf({ status: "failed", finishedAt: "2031-03-03T00:00:00Z", attempts: [{ n: 0, usedCookies: false, availabilityClass: "members_only" }] }); + assert.equal(deriveSourceStatus({ availability: record, outcome: late })?.now, "private"); + const { videoId: _drop, ...shapeless } = late; + const good = { checkedAt: "2031-03-01T00:00:00Z", checkedBy: "check", availability: "private" }; + assert.equal(deriveSourceStatus({ availability: good, outcome: shapeless })?.now, "private", "a shapeless outcome is ignored"); + assert.equal(deriveSourceStatus({ availability: good, outcome: late })?.now, "members_only"); + assert.equal(deriveSourceStatus({ outcome: shapeless }), null); +}); + +// REVIEW 1, nit 10: a check reads a missing field as public. +test("a check's public counts only where the video's metadata shows its extractor reports the field", () => { + const record = { + checkedAt: "2031-03-05T00:00:00Z", checkedBy: "check", availability: "members_only", + history: [ + { availability: "public", observedAt: "2031-03-01T12:00:00Z", source: "check" }, + { availability: "members_only", observedAt: "2031-03-05T00:00:00Z", source: "check" }, + ], + }; + const none = deriveSourceStatus({ availability: record, metadata: { live_status: "was_live", epoch: sec("2031-03-01T00:00:00Z") } }); + assert.deepEqual([none?.now, none?.first], ["members_only", null]); + assert.ok(none?.evidence.some((e) => e.kind === "check" && e.counts === false && /missing field/.test(e.why))); + const reported = deriveSourceStatus({ availability: record, metadata: { availability: "subscriber_only", epoch: sec("2031-03-05T00:00:00Z") } }); + assert.deepEqual([reported?.now, reported?.first, reported?.firstWhen], ["members_only", "public", "other"]); + // A download's public in the history is its own kind, with its own reason. + const dl = deriveSourceStatus({ availability: { ...record, history: [{ availability: "public", observedAt: "2031-03-01T12:00:00Z", source: "download" }, record.history[1]] } }); + assert.ok(dl?.evidence.some((e) => e.kind === "download" && e.counts === false && /stderr/.test(e.why))); + assert.equal(dl?.first, null); +}); + +test("a public source has no first state to name; evidence after the state began does not count", () => { + const pub = deriveSourceStatus({ availability: { checkedAt: "2031-03-01T00:00:00Z", availability: "public" }, metadata: LIVE_META }); + assert.deepEqual([pub?.now, pub?.first], ["public", null]); + const late = deriveSourceStatus({ + availability: { checkedAt: "2031-03-05T00:00:00Z", availability: "private", history: [{ availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "fetch" }] }, + metadata: { availability: "public", epoch: sec("2031-03-04T00:00:00Z") }, + }); + assert.equal(late?.first, null); +}); + +test("readSourceStatus reads one video directory, and keeps no big metadata", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "source-status-")); + try { + const v = path.join(dir, "synth-vid-001"); + await mkdir(v); + await writeFile(path.join(v, "availability.json"), JSON.stringify({ checkedAt: "2031-03-01T14:00:00Z", availability: "private", history: [{ availability: "private", observedAt: "2031-03-01T14:00:00Z", source: "fetch" }] })); + await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ ...LIVE_META, formats: [{ id: "x" }] })); + await writeFile(path.join(v, "live-recording.json"), "{ not json"); + const s = await readSourceStatus(v); + assert.deepEqual([s?.now, s?.first, s?.firstWhen], ["private", "public", "live"]); + assert.equal(await readSourceStatus(path.join(dir, "absent")), null); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/package.json b/common/package.json @@ -74,6 +74,8 @@ "./lib/report/social.mjs": "./lib/report/social.mjs", "./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs", "./lib/toolProbe.mjs": "./lib/toolProbe.mjs", + "./lib/sourceStatus.mjs": "./lib/sourceStatus.mjs", + "./lib/sourceStatus-server.mjs": "./lib/sourceStatus-server.mjs", "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", "./lib/videoDirId.mjs": "./lib/videoDirId.mjs", "./ytdlp/platformArgs.mjs": "./ytdlp/platformArgs.mjs", diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -48,6 +48,20 @@ manifest's estimates, a clip counted at its whole cut span, gaps included. A window aimed at the clip after it then landed earlier by the gaps' total and rendered the gapped clip instead. The estimate now counts the seconds that play, as the build and Play the cut do. Under `render.montage`, which applies no gaps, it counts the whole cut. +- **A chat captured while the stream was live is on the recording's clock.** + - yt-dlp times a chat captured live from the moment its capture began, not from the broadcast's start. A chat + fetched while a from-start recording ran therefore showed every message as early as the capture was late: 37 + minutes early on the stream that showed it. + - The live chat's cues now place each message captured live by its own posting time against the recording's + zero. For a from-start recording, or the post-live video, that is the broadcast's start (`release_timestamp`). + For a recording begun "from now" it is the recording's own start, marked not certain. + - A chat that holds both a live capture and the replay after it keeps the replay's copy of a message. A line + with no id is never dropped. A chat fetched as a replay is not moved. + - `live_chat.cues.json` is now version 2 and says which clock it is on in `clock` (basis, zero, shift, counts). + A version-1 file stays fresh: no build re-reads the raw chats. + - To repair one video: `pnpm ops fetch-chat {"slug","id","renormalize":true}`. It parses the raw chat already + on disk again, with no network, and is refused when there is none. The index build's fallback for a stale + chat uses the same clock. - **A fetch the platform refused for one video now records why.** - The chat replay pass (`fetch-chat`, the chat backlog, find-clips) and `refresh-metadata` used to drop a refusal such as "Join this channel to get access to members-only content". A stream backfilled "public" while it was diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts @@ -1,9 +1,9 @@ import { fetchChatAction } from "../../../channels/[slug]/videos/[id]/mediaToolsActions"; -import { jobResponse, ops, optString, reqSlug, reqVideoId } from "../_lib"; +import { jobResponse, ops, optBool, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, queueKey? } -> { ok: true, jobId } +// POST { slug, id, queueKey?, renormalize? } -> { ok: true, jobId } // // ONE video's live chat replay, and nothing else (release 36, lane A; // controller/fetchLiveChat.ts): the chat-only yt-dlp pass the managed download @@ -16,8 +16,16 @@ export const dynamic = "force-dynamic"; // here and fresh, a video that was never live, a held platform or one in a // rate-limit cooldown. Refused: an id with no data/<id>/, a channel whose text // cannot be read. A pass that finds no replay ends `done` and says so. +// +// `renormalize: true` parses the raw chat already on disk again (fresh or +// not) onto the recording's clock, with no network: refused when no raw is +// here — it never fetches. export async function POST(request: Request) { - return ops(request, ["slug", "id", "queueKey"], async (body) => - jobResponse(await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"))), + return ops(request, ["slug", "id", "queueKey", "renormalize"], async (body) => + jobResponse( + await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"), { + renormalize: optBool(body, "renormalize") === true, + }), + ), ); } diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts @@ -53,7 +53,12 @@ export async function attachVideoMediaAction( }); } -export async function fetchChatAction(slug: string, videoId: string, queueKey?: string): Promise<StreamActionResult> { +export async function fetchChatAction( + slug: string, + videoId: string, + queueKey?: string, + opts: { renormalize?: boolean } = {}, +): Promise<StreamActionResult> { if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; const paths = getPaths(); const config = await readChannelConfig(paths, slug); @@ -65,6 +70,7 @@ export async function fetchChatAction(slug: string, videoId: string, queueKey?: channelConfig: config, cookiePolicy: resolveCookiePolicy(getSettings(), config), ...(queueKey !== undefined ? { queueKey } : {}), + ...(opts.renormalize ? { renormalize: true } : {}), afterRun: () => safeRevalidate([`/channels/${slug}/videos/${videoId}`]), }); } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -49,6 +49,7 @@ // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait +// pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait // pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}' // pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}' // pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait @@ -1878,7 +1879,12 @@ export function usage() { " that finds no replay ends done and says so. A pass the source refuses for", " the video as members-only or private records that in its", " availability.json (source fetch); a removal is recorded only by the", - " channel's Check availability.", + " channel's Check availability. A chat captured while the stream was live", + " is put on the recording's clock (the broadcast's start, or a recording", + ' begun "from now" its own start) and its cues say which in "clock".', + ' "renormalize": true parses the raw chat already on disk again, fresh or', + " not, with no network — for a chat normalized before that; refused when no", + " raw is here (it never fetches).", "", 'fetch-chat-backlog fetches a channel\'s stream chats after its downloads:', ' {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose', diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -941,6 +941,8 @@ const COMMANDS = { diff: cmdDiff, export: cmdExport, "check-sources": cmdCheckSources, + // What became of each cited source, stamped into the manifest for the deck's source line: lib/report/sourceStatusCli.mjs. + "source-status": async () => process.exit(await (await import("../lib/report/sourceStatusCli.mjs")).sourceStatusCommand(argv.slice(argv.indexOf("source-status") + 1))), notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))), // The take maker (release 33): lib/report/takeCli.mjs. take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))), diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -121,6 +121,7 @@ Inbox cannot disagree about what is wrong with one. | `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) | | `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) | | `provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `""` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | +| `source-status <project> [ls] [--json]` · `source-status <project> refresh [--dry-run] [--json]` | **what became of each cited source**: `refresh` reads each recording's records — the project's channels tree, then the corpus (availability.json, download-outcome.json, metadata.info.json and its history, live-recording.json; read only), else the published archive's `state` (its index re-read) — and merges it into the manifest's `sourceStatus` (a source it cannot read keeps its entry, an older reading never replaces a newer one; one write, one undo point, only when the stamp changed); `ls` prints it, a status older than 14 days marked stale. Records that disagree, or a removal no check read, draw nothing. The deck's source line reads ONLY the stamp, when `deck.subtitle.status` is `end`: `now private` / `now members-only` / `now deleted`, with `(public when streamed)` or `(was public)` only on evidence ([knobs.md](knobs.md#source-status-on-the-source-line)) | | `title <project> ["<title>"] [--subtitle "…" \| --no-subtitle] [--json]` | the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` | @@ -187,6 +188,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `links <project> [--fix] [--embed-ids] [--clips CLIPS] [--dry-run]` | do the clip QRs open on their sites (out/links.json) | form · *project* | | `provenance <project> ls` | the project's provenance: site origin, channel slug, channel, link policy | form · *project* | | `provenance <project> set [--site-origin SITE-ORIGIN] [--channel-slug CHANNEL-SLUG] [--channel CHANNEL]` | the project's site origin, channel slug and channel name ("" removes one) | form · *draft* | +| `source-status <project> ls` | what became of each cited source, as the manifest's stamp has it | form · *project* | +| `source-status <project> refresh [--dry-run]` | stamp each cited source's status from the archive's records (never a platform) | form · *draft* | | `title <project> [<title>] [--subtitle SUBTITLE] [--no-subtitle]` | the project's title and subtitle (no words: print them) | form · *draft* | | `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* | | `still <project> ls` | the pictures in the project's shots/ | form · *project* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -188,6 +188,65 @@ site.test** / **Link its YouTube page**, the citeUrl through the window writer clip whose record names no `webpage_url` is a row without a fix. A clip with its own media (`src`) is not judged. +## Source status on the source line + +A stream a streamer later privates, deletes or puts behind a membership cannot be opened by a viewer, and the clip's +source line says so: `Synth Channel · Mar 1, 2031 · 35:00 · now members-only (public when streamed)`. + +| the source now | what the records prove about its first state | the part reads | +|---|---|---| +| private · members-only · deleted | public, seen while the stream was live | `now private (public when streamed)` · `now members-only (…)` · `now deleted (…)` | +| the same | public, seen at another time | `now private (was public)` … | +| the same | nothing | `now private` · `now members-only` · `now deleted` | +| public · unlisted · age-gated or behind a login · an error · no record | — | nothing: the line is what it always was | +| records that disagree, or a removal no check read | — | nothing | + +The words are one table (`umtool/report-to-video/source-status.mjs` `SOURCE_STATUS_WORDS`). "Was public" is said only +on EVIDENCE (`common/lib/sourceStatus.mjs`): metadata.info.json's own `availability: "public"` (an earlier value of it +rebuilt from metadata.history.json), or an availability.json history entry of `public` written by a check or a +one-video fetch (a check's `public` only when this video's metadata shows its extractor reports the field: a check +reads a missing field as public). "When streamed": that metadata was saved while `live_status` was `is_live`, or the +check fell inside the stream's span. NOT evidence: a backfill's `public` alone (it reads a missing field as public), a +download's class, a live recording (it may have used a member's cookies), a download without cookies (public or +unlisted). + +The line never says more than the records do. **Deleted** is drawn only when the channel's Check availability read it +(availability.json written by a check): a download's "deleted" is any bare "Video unavailable", a region block +included, so it draws nothing, and nor does the published archive's (the same reading). **When records disagree** -- +a public or unlisted reading newer than the private/members-only one (the metadata rewritten by a later persist, a +check, a download without cookies) -- it draws nothing. **Never cut**: where the line cannot hold the status whole +(a tally narrowing the column, a long channel) the page drops the parenthesis, then lets the channel give way, then +leaves the status out; the title gives way first, but not below 6 em for the whole words. + +| | In umtool | From a terminal | +|---|---|---| +| draw it (default off: a cut without it draws the page it always did) | Build, **Look**: **Subtitle**, Source status | `umtool look <p> deck.subtitle.status=end` (or name `status` in `deck.subtitle.parts`) | +| stamp what became of each source | — | `umtool source-status <p> refresh [--dry-run]`; `umtool source-status <p>` prints it | +| hide it on one clip (a clip whose `citeUrl` cites a public mirror) | — | the clip's `"sourceStatus": false` | + +A render reads ONLY the manifest's `sourceStatus` stamp: never the corpus, never the network. `refresh` reads each +recording's records in the project's channels tree, then the corpus (read only), else the published archive's +record (`state`, its index re-read, 20 s a document; the archive does not publish the first state, so no +parenthesis). It MERGES into the last stamp: a source it cannot read keeps its entry, an older reading never replaces +a newer one, and a corpus reading and an archive one that disagree draw nothing unless the corpus's is later than the +archive's build. It writes the stamp, one undo point, only when it changed. With the switch on and no stamp, the line +is unchanged and the build says once that `refresh` has not been run; a status older than 14 days is a build note and +is listed by `umtool check`, never a refusal, and so is a source whose records were written after the reading its +entry holds (each entry keeps `recordsAt`, so a refresh that finds nothing new still clears it). A source with no +availability record at all is not listed. +The status is the recording the clip is CUT from, not the one its `citeUrl` opens. + +Retrofit an old project: the switch (or a look preset that sets it), `refresh`, a retake. With the deck on only the +deck's page and the final pass are redrawn; no clip segment is re-encoded. Surfaces: the 16:9 deck, its finale copy +(the title still last, the status before it: the caption's last part is the one its two-line clamp cuts), the live +preview and Present. Not yet: the stacked vertical deck, the +end card's source list, the shorts/desktop tag, `umtool export`'s Sources list, the share line. + +**The ledger cards can disagree.** A stacked ledger card's "source private" / "members only" comes from the build's +own `yt-dlp --simulate` probe (`out/availability.json`, render-cards.mjs `SOURCE_TAG`), a looser reading taken at +build; the source line comes from the archive's records via the stamp. Until the two share the stamp, a card and a +line about one recording can say different things. + ## Gaps inside a clip A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than @@ -2940,7 +2999,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr | Module | What it is | Its home | |---|---|---| | [Deck (the shell)](#deck-the-shell) `shell` | The panel at the foot of the frame: each clip's title, and the band the subtitle, QR, rail and counter draw in. (a page over the whole cut) | `render.chrome.deck` | -| [Subtitle](#subtitle) `subtitle` | Each clip's source line under its title: the channel, the source's title, the date, the clock. (drawn in the deck's page) | `render.chrome.deck.subtitle` | +| [Subtitle](#subtitle) `subtitle` | Each clip's source line under its title: the channel, the source's title, the date, the clock, and (when on) what became of the source. (drawn in the deck's page) | `render.chrome.deck.subtitle` | | [QR](#qr) `qr` | Each clip's code in the deck, to the archive at the clip or to the record itself. (drawn in the deck's page) | `render.chrome.deck.qr` | | [Rail](#rail) `rail` | The deck's pip track: a pip per clip, the marker, the fuse, and the markers' flags. (drawn in the deck's page) | `render.chrome.deck.pip` | | [Counter](#counter) `counter` | A running tally of named series in the deck, each cell stepping as a mark's stamp lands. (drawn in the deck's page) | `render.chrome.deck.counter` | @@ -3014,9 +3073,10 @@ The source line under each clip's title, in the deck. The automatic line is set | Knob | Range · default | From a terminal | |---|---|---| -| `deck.subtitle.parts` | `auto` · a list of distinct `channel` `title` `date` `clock` · default `auto` | `umtool look <p> deck.subtitle='{"parts":["channel","date","clock"]}'` | +| `deck.subtitle.parts` | `auto` · a list of distinct `channel` `title` `date` `clock` `status` · default `auto` | `umtool look <p> deck.subtitle='{"parts":["channel","date","clock"]}'` | | `deck.subtitle.dateFormat` | `long` (24 Oct 2020) · `iso` · default `long` | `umtool look <p> deck.subtitle='{"dateFormat":"iso"}'` | | `deck.subtitle.lines` | `1` · `2`: the source's title on a line of its own (a size up; it shrinks to 70 % before it ellipsizes), the other parts under it. The deck grows by that line (39 px at the default title size) and the footage must still fit above it: with full-width footage that needs `footageScale` at most about 0.78 · default `1` | `umtool look <p> deck.subtitle.lines=2 deck.footageScale=0.78` | +| `deck.subtitle.status` | `off` · `end`: the SOURCE STATUS after the last part (or name `status` in `parts` to place it; an explicit `off` wins over that) -- `now private` / `now members-only` / `now deleted`, with `(public when streamed)` or `(was public)` only when the archive's records prove it; nothing for a public, unlisted or age-gated source, or when the records disagree. Never drawn cut: where the line cannot hold it whole it drops the parenthesis, then lets the channel give way, then is not drawn. Read from the manifest's `sourceStatus` stamp alone (`umtool source-status <p> refresh`; never the network at render) · default `off` | `umtool look <p> deck.subtitle.status=end` then `umtool source-status <p> refresh` | | `deck.subtitle.head` | `auto` (the source's title) · a list of distinct parts for the first of two lines; the rest of `parts` take the second · default `auto` | `umtool look <p> deck.subtitle.head='["channel","title"]'` | ### QR diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -1009,6 +1009,18 @@ export const GROUPS = [ ], }, { + cmd: "source-status", + usage: [ + " umtool source-status <project> [ls] | refresh [--dry-run] [--json] what became of each cited source: refresh stamps", + " the manifest's sourceStatus from the archive's records (never a platform); the deck's source line", + " says it with deck.subtitle.status=end: \"now private (public when streamed)\"", + ], + docs: [ + ["`source-status <project> [ls] [--json]` · `source-status <project> refresh [--dry-run] [--json]`", + "**what became of each cited source**: `refresh` reads each recording's records — the project's channels tree, then the corpus (availability.json, download-outcome.json, metadata.info.json and its history, live-recording.json; read only), else the published archive's `state` (its index re-read) — and merges it into the manifest's `sourceStatus` (a source it cannot read keeps its entry, an older reading never replaces a newer one; one write, one undo point, only when the stamp changed); `ls` prints it, a status older than 14 days marked stale. Records that disagree, or a removal no check read, draw nothing. The deck's source line reads ONLY the stamp, when `deck.subtitle.status` is `end`: `now private` / `now members-only` / `now deleted`, with `(public when streamed)` or `(was public)` only on evidence ([knobs.md](knobs.md#source-status-on-the-source-line))"], + ], + }, + { cmd: "title", usage: [ " umtool title <project> [\"<title>\"] [--subtitle \"…\" | --no-subtitle] [--json] the project's title and subtitle", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -133,6 +133,8 @@ export const VERBS = Object.freeze([ form("provenance set", "draft", "the project's site origin, channel slug and channel name (\"\" removes one)", [ project(), opt("--site-origin", { help: "https://… (the archive its QRs open)" }), opt("--channel-slug", { help: "the channel a clip with no channel is from" }), opt("--channel", { help: "the display name" }), ], { shape: "provenance <project> set" }), + form("source-status ls", "project", "what became of each cited source, as the manifest's stamp has it", [project()], { shape: "source-status <project> ls" }), + form("source-status refresh", "draft", "stamp each cited source's status from the archive's records (never a platform)", [project(), dry()], { shape: "source-status <project> refresh" }), form("title", "draft", "the project's title and subtitle (no words: print them)", [ project(), arg("title", { required: false, help: "the new title (none: print them)" }), opt("--subtitle"), bool("--no-subtitle", "remove the subtitle"), ]), diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -152,6 +152,7 @@ const ACTION_LABEL = { unbuilt: "Build the video", "storage-unreachable": "Reconnect the media drive", "storage-mismatch": "Settle the storage", + "source-status-stale": "Refresh the source status", "unjudged-variant": "Judge variant", "missing-cut": "Ship the cut", "stale-recipe": "Record the recipe", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -47,6 +47,7 @@ export const WHAT = { unbuilt: "never built", "storage-unreachable": "media drive unreachable", "storage-mismatch": "storage disagrees", + "source-status-stale": "source status not current", "unjudged-variant": "variants not judged", "missing-cut": "cuts missing", "stale-recipe": "recipes out of date", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -1097,6 +1097,11 @@ export const REPORT_DECISION_KINDS = [ // Where the deliverables are disagrees with `storage.deliverables`, or a // move was cut. `open`: nothing is lost, and one command settles it. "storage-mismatch", + // The SOURCE STATUS the deck's source line draws (`deck.subtitle.status`, + // lane source-status): the stamp was never written, a cited source is not in + // it, its status is older than 14 days, or its records changed since. `open`: + // the line draws what the stamp says; `umtool source-status <p> refresh`. + "source-status-stale", // The clock (`cite`) or the QR's `t=` names a second more than a lead-in // before what the clip plays, or after it (citeFollow.mjs). `open`: the // build does not refuse it, but the video cites a moment it does not show. @@ -1458,6 +1463,13 @@ export async function reportDecisions(ctx, summary) { }); } } + // THE SOURCE STATUS STAMP, when the deck draws it: never refreshed, a source + // missing or older than 14 days, or records written since (their mtimes). + { + const { sourceStatusStaleness } = await import("../report/sourceStatusCli.mjs"); + const stale = await sourceStatusStaleness(dir, m); + if (stale) add("source-status-stale", "sourceStatus", stale, "open", { fix: `umtool source-status ${id} refresh` }); + } // A clip rejected (irrelevant, weak, …) but kept in place: open, never blocking. for (const e of rejectedClips(clips)) { add("clip-rejected", e.id, rejectedWhy(e, id), "open", { href: clipHref(e.id) }); diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -45,6 +45,7 @@ import { transitionOf, } from "umtool-report-to-video/deck"; import { marksOf, rawMarksOf, roundStamps, stampSchedule } from "umtool-report-to-video/factcheck"; +import { clipSourceStatus, subtitleStatusOn } from "umtool-report-to-video/source-status"; import { setMarks } from "./knobs.mjs"; import { channelsDirFor, @@ -277,7 +278,8 @@ export function previewSchedule({ variantManifest, built, draft, metas, postsDra segments: claimed.map((s, i) => { const e = patchedEntries[i]; const meta = metas[i] ?? null; - const { title, subtitle, subtitleParts, subtitleLines, subtitleLinesParts } = deckText(e, meta, provenance, deck, built.multiChannel); + const status = subtitleStatusOn(deck.subtitle) ? clipSourceStatus(e, variantManifest.sourceStatus, provenance) : ""; + const { title, subtitle, subtitleParts, subtitleLines, subtitleLinesParts } = deckText(e, meta, provenance, deck, built.multiChannel, status); const keepBuilt = e.type === "clip" && e.onscreen?.subtitle === undefined && !meta; // A two-line subtitle's lines, and the line's parts by token, go with the subtitle they were cut from. const { subtitleLines: builtLines, subtitleParts: builtParts, subtitleLinesParts: builtLinesParts, ...seg } = s; diff --git a/umtool/lib/report/sourceStatusCli.mjs b/umtool/lib/report/sourceStatusCli.mjs @@ -0,0 +1,371 @@ +// `umtool source-status <project> [ls] [--json]` +// `umtool source-status <project> refresh [--dry-run] [--json]` +// +// THE SOURCE STATUS STAMP (lane source-status): what became of each recording a +// project cites -- now private, members-only or deleted, and whether the archive's +// records prove it was public at first -- written into the manifest's +// `sourceStatus` so the deck's source line can say it (`deck.subtitle.status`, +// umtool-report-to-video/source-status.mjs). A render reads only this stamp. +// +// ls each cited source, its stamped words, its state and when that was true +// refresh reads each source's records -- the project's channels tree, then the +// corpus behind it (common lib/sourceStatus-server.mjs: availability.json, +// download-outcome.json, metadata.info.json, metadata.history.json, +// live-recording.json; READ ONLY) -- else the published archive's record +// (`state`, `stateSince`: the first state is not published, so no +// parenthesis; its index re-read, not the cue cache's copy). Never a +// platform. MERGED into the last stamp (mergeSourceEntry): a source it +// cannot read keeps what the last refresh knew, an older reading never +// replaces a newer one, and a corpus reading and an archive one that +// disagree with no provable order draw nothing. One write to the draft, +// one undo point, only when the stamp changed. +// +// Exit 0 done, 1 refused, 2 a usage error. Plain ESM: the CLI runs it under bare node. +import { stat } from "node:fs/promises"; + +import { newestSourceRecordMs, readSourceStatus } from "yt-dlp-transcript-common/lib/sourceStatus-server.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { manifestSources } from "umtool-report-to-video/manifest-sources"; +import { + SOURCE_STATUS_STALE_DAYS, sourceStatusNotes, sourceStatusText, statusSourceKeys, subtitleStatusOn, +} from "umtool-report-to-video/source-status"; +import { presetManifest } from "umtool-report-to-video/presets"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { StaleToken, StructureRefused, manifestToken, structuralEdit } from "./manifest.mjs"; + +class CliError extends Error {} + +export const SOURCE_STATUS_USAGE = [ + "usage: umtool source-status <project> [ls] [--json]", + " umtool source-status <project> refresh [--dry-run] [--json]", + " WHAT BECAME OF EACH CITED SOURCE: refresh stamps the manifest's sourceStatus from the archive's records (the", + " corpus, else the published record; never a platform), which the deck's source line reads when", + " deck.subtitle.status is \"end\" (umtool look <p> deck.subtitle.status=end): \"now private (public when streamed)\".", + " Merged into the last stamp: a source it cannot read keeps its entry. One write, one undo point, only when", + " the stamp changed. ls prints the stamp.", +].join("\n"); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** + * A published record's `state` as the stamp's `now` (availability.ts summaryState + * for a record with none: the legacy `isDeleted` / `isUnlisted`, else still public + * there). The archive's "deleted" is buildIndex's effective reading, a download's + * loose class included (common lib/sourceStatus.mjs), so it draws nothing; a state + * this does not know draws nothing. + * + * @returns {{ now: string|null, why?: string, state: string }} + */ +export function archiveReading(r) { + const state = typeof r?.state === "string" && r.state ? r.state : r?.isDeleted ? "deleted" : r?.isUnlisted ? "unlisted" : "available"; + const now = { available: "public", unlisted: "unlisted", private: "private", members_only: "members_only" }; + if (Object.hasOwn(now, state)) return { now: now[state], state }; + if (state === "deleted") { + return { now: null, state, why: "the archive's deleted is its effective reading, a download's loose class included: a removal is drawn only from a check the corpus holds" }; + } + return { now: null, state, why: `the archive's state "${state}" is not one the line names` }; +} + +/** A YYYYMMDD day as an ISO instant (its UTC midnight), else null. */ +const dayIso = (d) => (typeof d === "string" && /^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}T00:00:00.000Z` : null); + +/** The first video directory that exists for `<channel>/<video>` among the trees, else null. */ +async function videoDirIn(layers, channel, video) { + for (const root of layers) { + const dir = await resolveVideoDir(root, channel, video).catch(() => null); + if (dir && (await stat(dir).then((s) => s.isDirectory(), () => false))) return dir; + } + return null; +} + +/** + * Every cited source's status, as the stamp keeps it. + * + * @param {{ manifest: any, layers: string[], archive?: ((src: { channel: string, video: string, entry: any }) => Promise<any>) | null }} o + * `archive` answers a source no local tree holds: the published record (cues.mjs's http record), or throws. + * @returns {Promise<{ sources: Record<string, any>, unresolved: Array<{ key: string, why: string }> }>} + */ +export async function collectSourceStatus({ manifest, layers, archive = null }) { + const sources = {}; + const unresolved = []; + for (const w of manifestSources(manifest)) { + const dir = await videoDirIn(layers, w.channel, w.video); + if (dir) { + const s = await readSourceStatus(dir); + const newest = await newestSourceRecordMs(dir); + sources[w.key] = { + ...(s ?? { now: null, since: null, asOf: null, first: null, firstAt: null, firstWhen: null, evidence: [] }), + from: "corpus", + // The records' newest write this reading saw: `umtool check` compares the disk against it. + ...(newest !== null ? { recordsAt: new Date(newest).toISOString() } : {}), + }; + continue; + } + if (!archive) { + unresolved.push({ key: w.key, why: "no local record, and no archive to ask (provenance.siteOrigin)" }); + continue; + } + try { + const r = await archive({ channel: w.channel, video: w.video, entry: w.entries[0] ?? null }); + const read = archiveReading(r); + const asOf = typeof r?.archiveGeneratedAt === "string" && Number.isFinite(Date.parse(r.archiveGeneratedAt)) ? r.archiveGeneratedAt : null; + sources[w.key] = { + now: read.now, + since: read.now === "private" || read.now === "members_only" ? dayIso(r?.stateSince) : null, + asOf, + first: null, firstAt: null, firstWhen: null, + from: "archive", + evidence: read.why ? [{ kind: "archive", at: asOf, availability: read.state, counts: false, why: read.why }] : [], + }; + } catch (e) { + unresolved.push({ key: w.key, why: e instanceof Error ? e.message.split("\n")[0] : String(e) }); + } + } + return { sources, unresolved }; +} + +const msOf = (iso) => { + const t = typeof iso === "string" ? Date.parse(iso) : NaN; + return Number.isFinite(t) ? t : null; +}; + +/** + * One source's entry in the stamp, from the last stamp's (`prior`) and this + * refresh's reading (`fresh`), either absent: + * + * - no reading this time (unresolved: the network down, a 404, an id miss): the + * last refresh's entry stands; + * - the same reader twice: the newer reading, never an older one (an older one + * only carries its `recordsAt` over, so check does not ask again); + * - the corpus and the archive AGREE on `now`: the corpus's entry (its first state + * and evidence) as of the later of the two; + * - they DISAGREE: the corpus wins when its reading is later than the archive's + * build (`asOf` is that build's time, an upper bound on what the archive read); + * otherwise the order is unknown and the entry draws nothing (`now: null`, a + * "disagree" evidence item). + */ +export function mergeSourceEntry(prior, fresh) { + const p = isObj(prior) ? prior : null; + if (!isObj(fresh)) return p; + if (!p) return fresh; + const pa = msOf(p.asOf); + const fa = msOf(fresh.asOf); + if (p.from === fresh.from) { + if (pa !== null && (fa === null || fa < pa)) { + const { recordsAt: _old, ...kept } = p; + return { ...kept, ...(fresh.recordsAt ? { recordsAt: fresh.recordsAt } : {}) }; + } + return fresh; + } + const corpus = p.from === "corpus" ? p : fresh; + const archived = p.from === "corpus" ? fresh : p; + const ca = msOf(corpus.asOf); + const aa = msOf(archived.asOf); + if (corpus.now === archived.now) { + return { ...corpus, asOf: aa !== null && (ca === null || aa > ca) ? archived.asOf : corpus.asOf }; + } + if (ca !== null && (aa === null || ca > aa)) return corpus; + return { + now: null, since: null, asOf: archived.asOf ?? null, first: null, firstAt: null, firstWhen: null, + from: fresh.from, + ...(corpus.recordsAt ? { recordsAt: corpus.recordsAt } : {}), + evidence: [{ + kind: "disagree", at: archived.asOf ?? null, from: "archive", availability: archived.now, counts: false, + why: `the corpus read ${corpus.now ?? "no state"} as of ${corpus.asOf ?? "never"}, the archive built ${archived.asOf ?? "at an unknown time"} says ${archived.now ?? "no state"}: which is newer is not known, so nothing is drawn`, + }], + }; +} + +/** The stamp's sources after a refresh: every cited source, in manifest order, merged (mergeSourceEntry); uncited ones dropped. */ +export function mergeSourceStatus(prior, fresh, keys) { + const before = isObj(prior) ? prior : {}; + const out = {}; + for (const k of keys) { + const merged = mergeSourceEntry(before[k], fresh[k]); + if (merged) out[k] = merged; + } + return out; +} + +/** Two stamps' sources the same (refreshedAt aside)? */ +const sameSources = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); + +/** How long one archive document may take, redirects and body included. */ +export const ARCHIVE_TIMEOUT_MS = 20_000; + +/** + * The archive reader for a project: the cue source's published record (cues.mjs), + * its corpus.json and channel manifest RE-READ (the cue cache keeps them forever: + * the state would be the first fetch's), each document within ARCHIVE_TIMEOUT_MS. + * Lazy: only when asked. `cacheDir` / `fetchImpl` / `timeoutMs` for tests. + */ +export async function archiveReaderFor(manifest, { cacheDir, fetchImpl, timeoutMs = ARCHIVE_TIMEOUT_MS } = {}) { + const { createCueSource, siteOriginFromManifest } = await import("umtool-report-to-video/cues"); + const siteOrigin = siteOriginFromManifest(manifest); + if (!siteOrigin) return null; + const cues = createCueSource({ + siteOrigin, prefer: "http", refreshIndex: true, timeoutMs, + ...(cacheDir !== undefined ? { cacheDir } : {}), ...(fetchImpl ? { fetchImpl } : {}), + }); + return ({ channel, video, entry }) => cues.load(channel, video, { siteChannel: entry?.siteChannel, siteVideo: entry?.siteVideo }); +} + +/** Does the project's look (its preset under it) draw the source status? */ +export function statusOnFor(manifest) { + let laid = manifest; + try { + laid = presetManifest(manifest) ?? manifest; + } catch { + // An unknown preset: the build says so; here the manifest's own look is read. + } + return subtitleStatusOn(laid?.render?.chrome?.deck?.subtitle); +} + +/** + * Why the project's stamp is not current, or null (also null when the deck does + * not draw the status): never refreshed, a cited source missing, a status older + * than SOURCE_STATUS_STALE_DAYS (the build's notes, sourceStatusNotes), or a + * corpus record written after the reading its entry holds (its `recordsAt`, by + * mtime; read only) -- over the same sources the notes name (statusSourceKeys). + * A refresh that finds nothing new still writes the newer `recordsAt`, so this + * clears. `umtool check`'s `source-status-stale`, open, never blocking. + * + * @param {string} dir the project + * @param {any} manifest + * @param {{ now?: number, layers?: string[] }} [opts] + */ +export async function sourceStatusStaleness(dir, manifest, { now = Date.now(), layers = null } = {}) { + if (!statusOnFor(manifest)) return null; + const notes = sourceStatusNotes(manifest, { now }); + const stamp = manifest.sourceStatus; + if (isObj(stamp?.sources)) { + const keys = new Set(statusSourceKeys(manifest)); + const trees = layers ?? channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); + const moved = []; + for (const w of manifestSources(manifest)) { + const entry = stamp.sources[w.key]; + if (!keys.has(w.key) || entry?.from !== "corpus") continue; + const vdir = await videoDirIn(trees, w.channel, w.video); + if (!vdir) continue; + const newest = await newestSourceRecordMs(vdir); + const seen = msOf(entry.recordsAt); + if (newest !== null && (seen === null || newest > seen)) moved.push(w.key); + } + if (moved.length) notes.push(`records written since their reading: ${moved.join(", ")}`); + } + return notes.length ? notes.join("; ") : null; +} + +/** The stamp's rows for printing, in manifest order. */ +export function sourceStatusRows(manifest, { now = Date.now() } = {}) { + const stamp = isObj(manifest?.sourceStatus) ? manifest.sourceStatus : null; + const limit = SOURCE_STATUS_STALE_DAYS * 86_400_000; + return manifestSources(manifest).map((w) => { + const s = isObj(stamp?.sources?.[w.key]) ? stamp.sources[w.key] : null; + const at = Date.parse(s?.asOf ?? ""); + return { + key: w.key, + clips: w.clips, + stamped: Boolean(s), + words: sourceStatusText(s), + now: s?.now ?? null, + asOf: s?.asOf ?? null, + first: s?.first ?? null, + firstWhen: s?.firstWhen ?? null, + from: s?.from ?? null, + // As sourceStatusNotes: no record at all (no state, no reading) is not stale. + stale: !s || (!(s.now == null && s.asOf == null) && (!Number.isFinite(at) || now - at > limit)), + }; + }); +} + +function parse(args) { + const words = []; + const flags = new Set(); + for (const a of args) { + if (a.startsWith("--")) flags.add(a.slice(2)); + else words.push(a); + } + return { words, flags }; +} + +/** + * @param {string[]} args the words after `source-status` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, + * archive?: ((src: any) => Promise<any>) | null, now?: () => number }} [opts] + * `archive` replaces the published-record reader (tests); null asks none. + * @returns {Promise<number>} + */ +export async function sourceStatusCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), archive, now = Date.now } = {}) { + try { + const { words, flags } = parse(args); + const [projectArg, verb = "ls"] = words; + if (!projectArg || flags.has("help")) { + err(SOURCE_STATUS_USAGE); + return 2; + } + for (const f of flags) if (!["json", "dry-run"].includes(f)) throw new CliError(`unknown flag --${f} (--json, --dry-run)`); + const json = flags.has("json"); + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + // The token WITH the read: a write after it is refused at ours (StaleToken), never overwritten. + const token = await manifestToken(project.dir); + const m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const on = statusOnFor(m); + + if (verb === "ls") { + const rows = sourceStatusRows(m, { now: now() }); + if (json) { + out(JSON.stringify({ project: project.id, on, refreshedAt: m.sourceStatus?.refreshedAt ?? null, sources: rows }, null, 2)); + return 0; + } + out(`${project.id}: deck.subtitle.status ${on ? "on" : "off"}; stamp ${m.sourceStatus?.refreshedAt ? `refreshed ${m.sourceStatus.refreshedAt}` : "never refreshed (umtool source-status <p> refresh)"}`); + for (const row of rows) { + const state = row.stamped ? `${row.now ?? "no record"}${row.asOf ? ` as of ${row.asOf.slice(0, 10)}` : ""}` : "not stamped"; + out(` ${row.key.padEnd(40)} ${state.padEnd(30)} ${row.words || "—"}${row.stale ? " (stale)" : ""}`); + } + return 0; + } + if (verb !== "refresh") throw new CliError(`unknown: source-status ${verb} — ls or refresh`); + + const shadowExists = await hasShadowChannels(project.dir); + const layers = channelsLayersFor(project.dir, m, { shadowExists }); + const reader = archive === undefined ? await archiveReaderFor(m) : archive; + const { sources: fresh, unresolved } = await collectSourceStatus({ manifest: m, layers, archive: reader }); + const prior = isObj(m.sourceStatus?.sources) ? m.sourceStatus.sources : null; + const sources = mergeSourceStatus(prior, fresh, manifestSources(m).map((w) => w.key)); + // Nothing read and nothing stamped before: no stamp to write (an empty one would say "refreshed"). + const changed = !(prior === null && Object.keys(sources).length === 0) && !sameSources(prior, sources); + let result = null; + if (changed && !flags.has("dry-run")) { + const refreshedAt = new Date(now()).toISOString(); + const res = await withEditNotes(project, async () => + structuralEdit(project.dir, "source-status", token, (mm) => { + mm.sourceStatus = { refreshedAt, sources }; + return { refreshedAt }; + })); + result = res.result; + } + const rows = sourceStatusRows({ ...m, sourceStatus: { refreshedAt: "", sources } }, { now: now() }); + if (json) { + out(JSON.stringify({ ok: true, project: project.id, on, changed, written: Boolean(result), dryRun: flags.has("dry-run"), sources: rows, unresolved }, null, 2)); + } else { + for (const row of rows) out(` ${row.key.padEnd(40)} ${String(row.now ?? "no record").padEnd(14)} ${row.words || "—"}`); + for (const u of unresolved) out(` ${u.key.padEnd(40)} unresolved: ${u.why}`); + out(!changed ? "unchanged" : flags.has("dry-run") ? "would write the stamp (dry run)" : "stamp written"); + if (result?.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`); + if (!on) out(" the deck does not draw it yet: umtool look <p> deck.subtitle.status=end"); + } + return 0; + } catch (e) { + if (e instanceof StructureRefused) err(`umtool source-status: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`); + else if (e instanceof StaleToken) err(`umtool source-status: ${e.message} — somebody else wrote it; run it again`); + else err(`umtool source-status: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} diff --git a/umtool/lib/report/sourceStatusCli.test.mjs b/umtool/lib/report/sourceStatusCli.test.mjs @@ -0,0 +1,305 @@ +// `umtool source-status` (lane source-status): refresh stamps the manifest from the +// channels tree's records (read only), else the archive's record; a second refresh +// with nothing changed writes nothing; ls prints the stamp. Synthetic channels only. +// +// Run with: node --test umtool/lib/report/sourceStatusCli.test.mjs + +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-source-status-")); +process.env.REPORTS_DIR = path.join(ROOT, "reports"); +process.env.CHANNELS_DIR = path.join(ROOT, "channels"); +process.env.CHANNELS_FALLBACK = "1"; +const { sourceStatusCommand } = await import("./sourceStatusCli.mjs"); +const { setUndoEveryMs } = await import("./manifest.mjs"); +setUndoEveryMs(0); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const sec = (iso) => Date.parse(iso) / 1000; +const REPORTS = path.join(ROOT, "reports"); +const CHANNELS = path.join(ROOT, "channels"); + +async function video(slug, id, files) { + const dir = path.join(CHANNELS, slug, "data", id); + await mkdir(dir, { recursive: true }); + for (const [name, body] of Object.entries(files)) await writeFile(path.join(dir, name), JSON.stringify(body)); +} + +async function project(id, timeline) { + const dir = path.join(REPORTS, id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: id, title: "Synthetic cut", + provenance: { siteOrigin: "https://archive.example.test", channelSlug: "synth-channel" }, + render: { fps: 30, transition: 0 }, + timeline, + }, null, 2) + "\n"); + return dir; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); +const run = async (args, opts = {}) => { + const out = []; + const err = []; + const code = await sourceStatusCommand(args, { root: REPORTS, out: (s) => out.push(s), err: (s) => err.push(s), ...opts }); + return { code, out: out.join("\n"), err: err.join("\n") }; +}; + +await video("synth-channel", "synthvid001", { + "availability.json": { + checkedAt: "2031-03-01T20:00:00Z", checkedBy: "fetch", availability: "members_only", + history: [ + { availability: "public", observedAt: "2031-03-01T10:30:00Z", source: "backfill" }, + { availability: "members_only", observedAt: "2031-03-01T20:00:00Z", source: "fetch" }, + ], + }, + "metadata.info.json": { availability: "public", live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, +}); +await video("synth-channel", "synthvid002", { "metadata.info.json": { availability: "public", live_status: "was_live" } }); + +test("refresh stamps the corpus's reading and the archive's; a second refresh writes nothing; ls prints it", async () => { + const dir = await project("ss1", [ + { type: "clip", id: "c01", video: "synthvid001", start: 1, end: 3, cite: 1 }, + { type: "clip", id: "c02", video: "synthvid002", start: 4, end: 6, cite: 4 }, + { type: "clip", id: "c03", video: "synthvid003", start: 1, end: 2, cite: 1 }, + ]); + const asked = []; + const archive = async ({ channel, video }) => { + asked.push(`${channel}/${video}`); + return { id: video, state: "private", stateSince: "20310305", archiveGeneratedAt: "2031-03-06T00:00:00Z" }; + }; + const r = await run(["ss1", "refresh", "--json"], { archive, now: () => Date.parse("2031-03-07T00:00:00Z") }); + assert.equal(r.code, 0, r.err); + const res = JSON.parse(r.out); + assert.equal(res.written, true); + // Only the source no local tree holds is asked of the archive. + assert.deepEqual(asked, ["synth-channel/synthvid003"]); + const m = await read(dir); + assert.equal(m.sourceStatus.refreshedAt, "2031-03-07T00:00:00.000Z"); + const s1 = m.sourceStatus.sources["synth-channel/synthvid001"]; + assert.deepEqual([s1.now, s1.first, s1.firstWhen, s1.from], ["members_only", "public", "live", "corpus"]); + const s2 = m.sourceStatus.sources["synth-channel/synthvid002"]; + assert.deepEqual([s2.now, s2.asOf, s2.from], [null, null, "corpus"], "no availability record: no state, never 'gone'"); + const s3 = m.sourceStatus.sources["synth-channel/synthvid003"]; + assert.deepEqual([s3.now, s3.since, s3.asOf, s3.first, s3.from], ["private", "2031-03-05T00:00:00.000Z", "2031-03-06T00:00:00Z", null, "archive"]); + const undo = (await readdir(path.join(dir, "revisions")).catch(() => [])).filter((f) => f.includes("auto-before-source-status")); + assert.equal(undo.length, 1, "one undo point"); + + const before = (await stat(path.join(dir, "video.manifest.json"))).mtimeMs; + const again = await run(["ss1", "refresh", "--json"], { archive, now: () => Date.parse("2031-03-08T00:00:00Z") }); + assert.equal(JSON.parse(again.out).written, false); + assert.equal((await stat(path.join(dir, "video.manifest.json"))).mtimeMs, before, "nothing changed: nothing written"); + + const ls = await run(["ss1", "ls"], { now: () => Date.parse("2031-03-08T00:00:00Z") }); + assert.equal(ls.code, 0); + assert.match(ls.out, /synth-channel\/synthvid001\s+members_only as of 2031-03-01\s+now members-only \(public when streamed\)/); + assert.match(ls.out, /synth-channel\/synthvid003\s+private as of 2031-03-06\s+now private/); + assert.match(ls.out, /deck\.subtitle\.status off/); +}); + +test("a dry run writes nothing; with no archive a source no tree holds is unresolved, not gone", async () => { + const dir = await project("ss2", [{ type: "clip", id: "c01", video: "synthvid009", start: 1, end: 3, cite: 1 }]); + const r = await run(["ss2", "refresh", "--json", "--dry-run"], { archive: null }); + assert.equal(r.code, 0, r.err); + const res = JSON.parse(r.out); + assert.equal(res.written, false); + assert.equal(res.unresolved[0].key, "synth-channel/synthvid009"); + assert.equal((await read(dir)).sourceStatus, undefined); +}); + +test("usage: no project, an unknown verb or flag", async () => { + assert.equal((await run([])).code, 2); + assert.equal((await run(["ss1", "wat"])).code, 2); + assert.equal((await run(["ss1", "refresh", "--force"])).code, 2); +}); + +test("check's staleness: off says nothing; on says never refreshed, then current, then records written since", async () => { + const { sourceStatusStaleness } = await import("./sourceStatusCli.mjs"); + const dir = await project("ss3", [{ type: "clip", id: "c01", video: "synthvid001", start: 1, end: 3, cite: 1 }]); + const now = Date.parse("2031-03-05T00:00:00Z"); + assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null, "the deck does not draw it"); + const m = await read(dir); + m.render.chrome = { deck: { subtitle: { status: "end" } } }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + assert.match(await sourceStatusStaleness(dir, await read(dir), { now }), /has not been run/); + const r = await run(["ss3", "refresh"], { archive: null, now: () => Date.now() + 60_000 }); + assert.equal(r.code, 0, r.err); + assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null); + assert.match(await sourceStatusStaleness(dir, await read(dir), { now: Date.parse("2031-03-30T00:00:00Z") }), /older than 14 days/); + // A record written after the reading the entry holds (its recordsAt moved into the past). + const back = await read(dir); + back.sourceStatus.sources["synth-channel/synthvid001"].recordsAt = "2000-01-01T00:00:00.000Z"; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(back, null, 2) + "\n"); + assert.match(await sourceStatusStaleness(dir, await read(dir), { now }), /records written since their reading: synth-channel\/synthvid001/); +}); + +// REVIEW 1, finding 7a: a metadata refresh that changes no evidence still rewrites a record. The +// stamp keeps each source's newest record write (`recordsAt`): refresh writes the newer one, and +// check is quiet again -- not stale forever. +test("check's staleness clears after a refresh that found nothing new", async () => { + const { sourceStatusStaleness } = await import("./sourceStatusCli.mjs"); + await video("synth-channel", "synthvid020", { + "availability.json": { checkedAt: "2031-03-04T00:00:00Z", checkedBy: "fetch", availability: "private", history: [{ availability: "private", observedAt: "2031-03-04T00:00:00Z", source: "fetch" }] }, + "metadata.info.json": { availability: "public", live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, + }); + const dir = await project("ss7", [{ type: "clip", id: "c01", video: "synthvid020", start: 1, end: 3, cite: 1 }]); + const m = await read(dir); + m.render.chrome = { deck: { subtitle: { status: "end" } } }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + const now = Date.parse("2031-03-05T00:00:00Z"); + assert.equal((await run(["ss7", "refresh"], { archive: null })).code, 0); + assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null); + // The same metadata written again, a little later (a refresh that changed nothing it reads). + const meta = path.join(CHANNELS, "synth-channel", "data", "synthvid020", "metadata.info.json"); + const { utimes } = await import("node:fs/promises"); + const later = new Date(Date.now() + 5_000); + await utimes(meta, later, later); + assert.match(await sourceStatusStaleness(dir, await read(dir), { now }), /records written since their reading/); + const r = await run(["ss7", "refresh", "--json"], { archive: null }); + assert.equal(JSON.parse(r.out).written, true, "the newer records time is written"); + assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null, "and check is quiet again"); + const s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid020"]; + assert.deepEqual([s.now, s.first, s.firstWhen], ["private", "public", "live"], "the reading itself unchanged"); +}); + +// REVIEW 1, finding 4a: a source this refresh cannot read keeps what the last one knew. +test("an unresolved source keeps its last entry; nothing read and nothing stamped writes nothing", async () => { + const dir = await project("ss4", [{ type: "clip", id: "c01", video: "synthvid030", start: 1, end: 3, cite: 1 }]); + const ok = async () => ({ state: "private", stateSince: "20310305", archiveGeneratedAt: "2031-03-06T00:00:00Z" }); + const down = async () => { throw new Error("GET https://archive.example.test/corpus.json -> 503"); }; + const first = await run(["ss4", "refresh", "--json"], { archive: down }); + assert.equal(JSON.parse(first.out).written, false, "no {} stamp for a refresh that read nothing"); + assert.equal((await read(dir)).sourceStatus, undefined); + assert.equal(JSON.parse((await run(["ss4", "refresh", "--json"], { archive: ok })).out).written, true); + const before = (await read(dir)).sourceStatus; + const again = JSON.parse((await run(["ss4", "refresh", "--json"], { archive: down })).out); + assert.equal(again.written, false); + assert.equal(again.unresolved[0].key, "synth-channel/synthvid030"); + assert.deepEqual((await read(dir)).sourceStatus, before, "the last reading stands"); +}); + +// REVIEW 1, finding 4b: a project stamped on the corpus machine, refreshed where there is none. +test("mergeSourceEntry: never an older reading; corpus and archive agreeing keep the corpus's first state; disagreeing with no order, nothing", async () => { + const { mergeSourceEntry, mergeSourceStatus } = await import("./sourceStatusCli.mjs"); + const corpus = { now: "members_only", since: "2031-03-01T20:00:00Z", asOf: "2031-03-01T20:00:00Z", first: "public", firstAt: "2031-03-01T10:05:00Z", firstWhen: "live", from: "corpus", evidence: [{ kind: "metadata", counts: true }], recordsAt: "2031-03-01T20:00:00.000Z" }; + const archive = (now, asOf) => ({ now, since: null, asOf, first: null, firstAt: null, firstWhen: null, from: "archive", evidence: [] }); + // Agree, the archive newer: the corpus's first state and evidence, as of the archive's build. + const agree = mergeSourceEntry(corpus, archive("members_only", "2031-03-06T00:00:00Z")); + assert.deepEqual([agree.now, agree.first, agree.firstWhen, agree.from, agree.asOf], ["members_only", "public", "live", "corpus", "2031-03-06T00:00:00Z"]); + // Disagree, the archive's build newer than the corpus's reading: which is newer is not known -- nothing. + const unknown = mergeSourceEntry(corpus, archive("public", "2031-03-06T00:00:00Z")); + assert.deepEqual([unknown.now, unknown.first], [null, null]); + assert.ok(unknown.evidence.some((e) => e.kind === "disagree")); + // Disagree, the corpus's reading later than the archive's build: the corpus. + assert.equal(mergeSourceEntry(corpus, archive("private", "2031-02-01T00:00:00Z")), corpus); + // The same reader, an older reading: the newer stands. + const older = { ...corpus, now: "private", asOf: "2031-02-01T00:00:00Z", recordsAt: "2031-03-09T00:00:00.000Z" }; + const kept = mergeSourceEntry(corpus, older); + assert.deepEqual([kept.now, kept.asOf, kept.recordsAt], ["members_only", "2031-03-01T20:00:00Z", "2031-03-09T00:00:00.000Z"]); + // An unresolved source (no fresh reading) keeps its entry; an uncited one is dropped. + assert.deepEqual(mergeSourceStatus({ "a/b": corpus, "a/c": corpus }, {}, ["a/b"]), { "a/b": corpus }); +}); + +test("refresh without the corpus keeps what the corpus machine stamped (end to end)", async () => { + await video("synth-channel", "synthvid040", { + "availability.json": { checkedAt: "2031-03-01T20:00:00Z", checkedBy: "fetch", availability: "members_only", history: [{ availability: "members_only", observedAt: "2031-03-01T20:00:00Z", source: "fetch" }] }, + "metadata.info.json": { availability: "public", live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, + }); + const dir = await project("ss5", [{ type: "clip", id: "c01", video: "synthvid040", start: 1, end: 3, cite: 1 }]); + assert.equal((await run(["ss5", "refresh"], { archive: null })).code, 0); + assert.equal((await read(dir)).sourceStatus.sources["synth-channel/synthvid040"].firstWhen, "live"); + // The corpus goes away (another machine): the archive's older build says members-only, then public. + const { rename } = await import("node:fs/promises"); + const vdir = path.join(CHANNELS, "synth-channel", "data", "synthvid040"); + await rename(vdir, `${vdir}.away`); + try { + await run(["ss5", "refresh"], { archive: async () => ({ state: "members_only", archiveGeneratedAt: "2031-02-20T00:00:00Z" }) }); + let s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid040"]; + assert.deepEqual([s.now, s.first, s.firstWhen, s.from, s.asOf], ["members_only", "public", "live", "corpus", "2031-03-01T20:00:00Z"], "an older archive build adds nothing"); + await run(["ss5", "refresh"], { archive: async () => ({ archiveGeneratedAt: "2031-03-10T00:00:00Z" }) }); + s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid040"]; + assert.deepEqual([s.now, s.first], [null, null], "a newer build says public: the order is not known, nothing is drawn"); + } finally { + await rename(`${vdir}.away`, vdir); + } +}); + +// REVIEW 1, finding 5: a published record's state. +test("archiveReading: no state is public only without the legacy flags; a deleted or unknown state draws nothing", async () => { + const { archiveReading } = await import("./sourceStatusCli.mjs"); + assert.equal(archiveReading({}).now, "public"); + assert.equal(archiveReading({ state: "private" }).now, "private"); + assert.equal(archiveReading({ state: "members_only" }).now, "members_only"); + assert.equal(archiveReading({ isUnlisted: true }).now, "unlisted"); + assert.equal(archiveReading({ isDeleted: true }).now, null, "legacy deleted: the loose reading, not drawn"); + assert.equal(archiveReading({ state: "deleted" }).now, null); + assert.equal(archiveReading({ state: "constructor" }).now, null); + assert.equal(archiveReading({ state: "gone-ish" }).now, null); + assert.equal(archiveReading({ state: "private", isDeleted: true }).now, "private", "state wins, as summaryState"); + // Through refresh: the reason is kept as evidence. + const dir = await project("ss6", [{ type: "clip", id: "c01", video: "synthvid050", start: 1, end: 3, cite: 1 }]); + await run(["ss6", "refresh"], { archive: async () => ({ isDeleted: true, archiveGeneratedAt: "2031-03-06T00:00:00Z" }) }); + const s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid050"]; + assert.equal(s.now, null); + assert.ok(s.evidence.some((e) => e.kind === "archive" && e.availability === "deleted")); +}); + +// REVIEW 1, finding 3: the archive's index is re-read on refresh, and a fetch that hangs gives up. +test("the archive reader re-reads corpus.json and the channel manifest, and times out", async () => { + const { archiveReaderFor } = await import("./sourceStatusCli.mjs"); + const origin = "https://archive.example.test"; + const cacheDir = path.join(ROOT, "cue-cache"); + let state = "private"; + const asked = []; + const json = (body) => ({ ok: true, status: 200, headers: { get: () => null }, text: async () => JSON.stringify(body) }); + const fetchImpl = async (url) => { + asked.push(url); + if (url === `${origin}/corpus.json`) return json({ channels: [{ slug: "synth-channel" }] }); + if (url.endsWith("/manifest.json")) return json({ generatedAt: `gen-${state}`, slugToPage: { synthvid060: 0 } }); + if (url.endsWith("/page-0000.json")) return json([{ id: "synthvid060", state }]); + return { ok: false, status: 404, headers: { get: () => null }, text: async () => "" }; + }; + const manifest = { provenance: { siteOrigin: origin, channelSlug: "synth-channel" } }; + const first = await (await archiveReaderFor(manifest, { cacheDir, fetchImpl }))({ channel: "synth-channel", video: "synthvid060", entry: null }); + assert.equal(first.state, "private"); + // The archive is rebuilt; a NEW refresh (a new reader, as a new process) reads the new state. + state = "members_only"; + asked.length = 0; + const second = await (await archiveReaderFor(manifest, { cacheDir, fetchImpl }))({ channel: "synth-channel", video: "synthvid060", entry: null }); + assert.equal(second.state, "members_only"); + assert.ok(asked.includes(`${origin}/corpus.json`) && asked.some((u) => u.endsWith("/manifest.json")), "the index was fetched again"); + // A server that never answers: the read fails within the timeout, it is not waited on forever. + const hang = (url, init) => new Promise((_, reject) => init.signal?.addEventListener("abort", () => reject(init.signal.reason))); + // (AbortSignal.timeout's timer does not hold the process open; a real fetch's socket does, this stub's nothing.) + const alive = setInterval(() => {}, 1000); + try { + const t0 = Date.now(); + await assert.rejects((await archiveReaderFor(manifest, { cacheDir: null, fetchImpl: hang, timeoutMs: 100 }))({ channel: "synth-channel", video: "synthvid060", entry: null })); + assert.ok(Date.now() - t0 < 5_000); + } finally { + clearInterval(alive); + } +}); + +// REVIEW 1, nit 11: the token is taken WITH the read, so a write between the read and ours is refused. +test("a manifest written while refresh reads is refused, not overwritten", async () => { + const dir = await project("ss8", [{ type: "clip", id: "c01", video: "synthvid070", start: 1, end: 3, cite: 1 }]); + const archive = async () => { + // Somebody else's write lands while the sources are read. + const m = await read(dir); + m.title = "Edited meanwhile"; + await new Promise((r) => setTimeout(r, 20)); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { state: "private", archiveGeneratedAt: "2031-03-06T00:00:00Z" }; + }; + const r = await run(["ss8", "refresh"], { archive }); + assert.equal(r.code, 1); + assert.match(r.err, /somebody else wrote it/); + const m = await read(dir); + assert.equal(m.title, "Edited meanwhile"); + assert.equal(m.sourceStatus, undefined); +}); diff --git a/umtool/report-to-video/attribution.mjs b/umtool/report-to-video/attribution.mjs @@ -179,7 +179,9 @@ export function deckSubtitle(parts, opts = {}, multiChannel = false) { * empty ones dropped): what `deckSubtitle` joins, kept apart so the page can * set each part by WHAT it is -- the date and the clock never give way, the * title gives way first -- rather than by where it stands in the line - * (chrome-deck.mjs subtitleMarkup). Tokens: channel, title, date, clock. + * (chrome-deck.mjs subtitleMarkup). Tokens: channel, title, date, clock, + * status (source-status.mjs: "now private (public when streamed)", from the + * manifest's stamp; drawn only when `parts.status` carries words). * * @returns {Array<[string, string]>} */ @@ -187,16 +189,26 @@ export function deckSubtitleParts(parts, opts = {}, multiChannel = false) { return subtitleValues(parts, opts, multiChannel); } -/** The subtitle's parts as `[token, text]`, in order, the empty ones dropped. */ +/** + * The subtitle's parts as `[token, text]`, in order, the empty ones dropped. + * `opts.status: "end"` puts the source status after the last part, whatever + * `parts` is; named in `parts`, it stands where it is named; "off" drops it + * even where it is named. Empty (a public + * source, no stamp, the switch off): dropped, so the line is what it was. + */ function subtitleValues(parts, opts, multiChannel) { - const want = !opts.parts || opts.parts === "auto" + const base = !opts.parts || opts.parts === "auto" ? (multiChannel ? ["channel", "title", "date"] : ["title", "date"]) : opts.parts; + // An explicit "off" wins over `status` named in the parts (source-status.mjs subtitleStatusOn). + const want = opts.status === "off" ? base.filter((k) => k !== "status") + : opts.status === "end" && !base.includes("status") ? [...base, "status"] : base; const value = { channel: () => parts.channel, title: () => parts.title, date: () => formatDeckDate(parts.date, opts.dateFormat ?? "long"), clock: () => (parts.at === null || parts.at === undefined ? "" : hms(parts.at)), + status: () => parts.status ?? "", }; return want .map((k) => [k, String(value[k]?.() ?? "").trim()]) diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -128,6 +128,7 @@ // // Requires: yt-dlp, ffmpeg/ffprobe, ImageMagick with Pango. +import { sourceStatusNotes, subtitleStatusOn, validateSourceStatus } from "./source-status.mjs"; import { localRecordingFetchRefusal } from "./local-recording.mjs"; import { presetManifest } from "./presets.mjs"; // The basic output mode (render.mode "basic"): the footage alone, cut and spliced in basic.mjs. @@ -6495,6 +6496,11 @@ export async function writeChromeSchedule({ manifest, entries, segments, D, outD // What the record says to a deck claim's `claim` (it does not contradict // him, a stamp with no date): notes, the operator's to weigh. for (const message of claimRecordNotes(doc)) EMIT("note", { message }); + // The source status (source-status.mjs): drawn from the stamp alone; what the + // stamp lacks or how old it is, said here, never a refusal. + if (subtitleStatusOn(resolveDeck(manifest.render ?? {}).subtitle)) { + for (const message of sourceStatusNotes({ ...manifest, timeline: entries })) EMIT("note", { message }); + } return doc; } @@ -6556,6 +6562,7 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du // upload dates. A manifest without posts writes the schedule it always did. return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null, + sourceStatus: manifest.sourceStatus ?? null, ...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}), ...(chat ? { chat } : {}), ...(clipClock ? { clipClock } : {}), @@ -7070,6 +7077,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole), ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole), ...validateGapEntries(whole), ...measureSettingsProblems(whole), ...validateAnalysisEntries(whole), ...validateClipKit(whole), ...validatePromo(whole), ...validateZooms(whole), ...validateCensor(whole), + ...validateSourceStatus(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -47,6 +47,7 @@ import { fitTallyLabel, resolveFactcheck, TALLY_WRITTEN, tallyCues, tallyFinals, import { resolveCounter } from "./counter.mjs"; import { SUBSECTION_SEPARATOR } from "./marker-limits.mjs"; import { settleFirstFrame } from "./cue-start.mjs"; +import { TITLE_KEEP_EM, fitStatusLine, statusShortForm } from "./status-fit.mjs"; /** * GSAP, vendored, for every chrome region. @@ -670,7 +671,13 @@ export function subtitleTokens(text, tokens) { */ export function subtitleMarkup(text, tokens = null) { const tok = subtitleTokens(text, tokens); - if (tok) return tok.map(([k, v]) => `<span class="part" data-p="${esc(k)}">${esc(v)}</span>`).join('<span class="sep">·</span>'); + if (tok) { + return tok.map(([k, v]) => { + // The source status carries its short form, for the page's fit (status-fit.mjs). + const short = k === "status" ? statusShortForm(v) : null; + return `<span class="part" data-p="${esc(k)}"${short ? ` data-short="${esc(short)}"` : ""}>${esc(v)}</span>`; + }).join('<span class="sep">·</span>'); + } return String(text ?? "") .split(" · ") .map((p) => `<span class="part">${esc(p)}</span>`) @@ -694,6 +701,42 @@ export function subtitlePartsCss(sel) { } /** + * Does any segment's automatic line carry the source status (deck.mjs deckText's + * `subtitleParts` / `subtitleLinesParts`, token `status`)? Only then do the pages + * add its rule, so a cut without one draws the page it always did. + */ +export function scheduleHasStatus(schedule) { + const has = (parts) => Array.isArray(parts) && parts.some((p) => Array.isArray(p) && p[0] === "status"); + return (schedule?.segments ?? []).some((s) => has(s.subtitleParts) || (Array.isArray(s.subtitleLinesParts) && s.subtitleLinesParts.some(has))); +} + +/** + * The source status part's rule (`sels` the lines it stands in): the line's own + * size and weight, a quiet accent; never shrinks (a `.part` is `flex: none` + * unless it is the title or the channel), never ellipsized -- the page's fit + * (status-fit.mjs) takes the short form or drops it instead, and on the way lets + * the channel give way (`.st-give`). + */ +export function statusPartCss(sels, pal) { + return sels.map((sel) => `${sel} .part[data-p="status"]`).join(", ") + ` { color: ${mix(pal.muted, pal.accent, 0.55)}; } + ${sels.map((sel) => `${sel}.st-give .part[data-p="channel"]`).join(", ")} { flex: 0 1 auto; min-width: 0; }`; +} + +/** + * The page's status fit (status-fit.mjs), as script: the function's own source and, + * per `[selector, mode, name]`, a caller `name(root?)` over those lines. Only a + * page with a status carries it. + */ +export function statusFitScript(calls) { + return ` // The source status, never cut (status-fit.mjs): the whole words, else the + // short form, else with the channel giving way, else nothing. + ${fitStatusLine.toString().replace(/\n/g, "\n ")} +${calls.map(([sel, mode, name]) => ` const ${name} = (root) => (root || document).querySelectorAll(${JSON.stringify(sel)}).forEach((n) => + fitStatusLine(n, parseFloat(getComputedStyle(n).fontSize) || 0, ${JSON.stringify(mode)}, ${TITLE_KEEP_EM})); +`).join("")}`; +} + +/** * The deck composition's HTML. * * `fonts` = `{ regular, bold }` asset-relative paths (DeckSans / DeckSansBold), @@ -746,6 +789,8 @@ export function deckHtml(schedule, render, opts = {}) { // Untitled, the two are promoted into the title's band as the one line is, // and centred on the same block. const two = t.lines === 2; + // A line carries the source status: only then does the page add its rule and its fit. + const hs = scheduleHasStatus(schedule); const u2HeadBox = Math.round(uSubSize * 1.25); const u2Block = u2HeadBox + t.subtitleBox; const u2Y = two ? Math.round(t.titleY + (t.subtitleY + (t.headBox ?? 0) + t.subtitleBox - t.titleY - u2Block - 14) / 2) : 0; @@ -1009,7 +1054,8 @@ export function deckHtml(schedule, render, opts = {}) { font-size: ${t.subtitleSize}px; line-height: ${t.subtitleBox}px; letter-spacing: 0.005em; color: ${pal.muted}; } ${subtitlePartsCss(".deck-sub")} - .deck-sub .sep { color: ${pal.accent}; padding: 0 0.42em; font-family: 'DeckSansBold', sans-serif; } + .deck-sub .sep { color: ${pal.accent}; padding: 0 0.42em; font-family: 'DeckSansBold', sans-serif; }${hs ? ` + ${statusPartCss([".deck-sub"], pal)}` : ""} .blade { position: absolute; right: 0; top: ${Math.round(t.titleBox * 0.14)}px; width: 4px; height: ${Math.round(t.titleBox * 0.72)}px; border-radius: 2px; background: ${pal.accent}; box-shadow: 0 0 14px 2px ${rgba(pal.accent, 0.55)}; } @@ -1175,7 +1221,7 @@ ${two ? ` // A two-line subtitle's head likewise, from its own size to 70 % document.querySelectorAll(".deck-sub.head").forEach(fitHead); }; ` : ` const fitAll = () => document.querySelectorAll(".deck-title").forEach(fitTitle); -`} +`}${hs ? statusFitScript([[".deck-sub", "row", "fitStatus"]]) : ""} // The QR's host runs up beside the code, and its INK is exactly as long // as the code is tall, whatever the host. Every length in it scales with // the font size (the tracking is in em), so one measurement in the @@ -1201,7 +1247,8 @@ ${two ? ` // A two-line subtitle's head likewise, from its own size to 70 % document.fonts.load(D.titleSize + "px DeckSansBold"), document.fonts.load("26px DeckSans"), ]).catch(() => {}).then(() => { - fitAll(); + fitAll();${hs ? ` + fitStatus();` : ""} document.querySelectorAll(".deck-qr-host").forEach(fitHost); document.documentElement.dataset.fit = "1"; }); @@ -1242,7 +1289,8 @@ ${two ? ` // A two-line subtitle's head likewise, from its own size to 70 % const auto = m.subtitle === seg.dataset.sub; si.innerHTML = auto ? seg._auto : '<div class="deck-sub">' + subMarkup(m.subtitle) + "</div>";${two ? ` seg.classList.toggle("two", auto && seg._wasTwo); - seg.querySelectorAll(".deck-sub.head").forEach(fitHead);` : ""} + seg.querySelectorAll(".deck-sub.head").forEach(fitHead);` : ""}${hs ? ` + if (auto) fitStatus(seg);` : ""} } else if (typeof m.subtitle === "string") seg.querySelector(".deck-sub").innerHTML = subMarkup(m.subtitle); } }); diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs @@ -24,7 +24,7 @@ // The timeline is cues, each stating its from (chrome-deck.mjs says why). import { cueTime, cueTimeAfter, finaleRail, pageDuration, railDrawn, railOffStyle, resolveDeck } from "./deck.mjs"; import { finaleClaimsMarkup } from "./chrome-claims.mjs"; -import { mix, rgba, shapeCss, subtitleMarkup, subtitlePartsCss, subtitleTokens } from "./chrome-deck.mjs"; +import { mix, rgba, scheduleHasStatus, shapeCss, statusFitScript, statusPartCss, subtitleMarkup, subtitlePartsCss, subtitleTokens } from "./chrome-deck.mjs"; import { resolveFactcheck, tallyCells, tallyFinals, tallyOf } from "./factcheck.mjs"; import { settleFirstFrame } from "./cue-start.mjs"; import { resolveCounter } from "./counter.mjs"; @@ -339,6 +339,8 @@ export function titleLastParts(subtitle, tokens) { export function finaleHtml(schedule, render, window, opts = {}) { const L = finaleLayout(schedule, render); const { init, cues } = finaleCues(schedule, render, L); + // A line carries the source status: only then does the page add its rule and its fit (status-fit.mjs). + const hs = scheduleHasStatus(schedule); const pal = render.palette; const g = L.geo; const W = g.W, H = g.H; @@ -530,7 +532,8 @@ export function finaleHtml(schedule, render, window, opts = {}) { .dtt { font-family: 'DeckSansBold', sans-serif; font-size: ${L.foot.text.titleSize}px; line-height: ${L.foot.text.titleBox}px; letter-spacing: -0.012em; } .dts { display: flex; font-size: ${L.foot.text.subtitleSize}px; line-height: ${L.foot.text.subtitleBox}px; color: ${pal.muted}; } .dts .sep { color: ${pal.accent}; padding: 0 0.42em; font-family: 'DeckSansBold', sans-serif; } - ${subtitlePartsCss(".dts")} + ${subtitlePartsCss(".dts")}${hs ? ` + ${statusPartCss([".dts", ".cs"], pal)}` : ""} .drule { width: ${Math.round(L.foot.text.titleSize * 1.5)}px; height: 4px; border-radius: 2px; background: ${pal.accent}; } .hole { position: absolute; transform-origin: 0 0; box-shadow: 0 0 0 ${HOLE_REACH}px ${pal.bg}; } .ground { position: absolute; inset: 0; background: ${pal.bg}; } @@ -636,10 +639,10 @@ export function finaleHtml(schedule, render, window, opts = {}) { tl.add(inner.tweenFromTo(F.from, F.from + F.dur, { duration: F.dur, ease: "none" }), 0); window.__timelines = window.__timelines || {}; window.__timelines["finale"] = tl; - const ready = Promise.all([ +${hs ? statusFitScript([[".dts", "row", "fitStatusRows"], [".cs", "block", "fitStatusBlocks"]]) : ""} const ready = Promise.all([ document.fonts.load("28px DeckSansBold"), document.fonts.load("24px DeckSans"), - ]).catch(() => {}).then(() => { document.documentElement.dataset.fit = "1"; }); + ]).catch(() => {}).then(() => {${hs ? " fitStatusRows(); fitStatusBlocks();" : ""} document.documentElement.dataset.fit = "1"; }); const params = new URLSearchParams(location.search); // The review still, in CUT seconds. const still = params.get("still"); diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -111,6 +111,10 @@ function unwrapCached(doc) { export const pagesVersionOf = (manifest) => typeof manifest?.generatedAt === "string" && manifest.generatedAt ? manifest.generatedAt : null; +// The archive build an http record is from (its transcripts manifest's +// `generatedAt`): what the record's `state` is true as of (umtool source-status). +const archiveAt = (manifest) => (pagesVersionOf(manifest) ? { archiveGeneratedAt: pagesVersionOf(manifest) } : {}); + export function pageFileName(pageNumber) { return `page-${String(pageNumber).padStart(4, "0")}.json`; } @@ -208,12 +212,16 @@ export class CueLookupError extends Error { * (linkCheck refreshes manifests), so the walk could read a record from a page * the new manifest no longer puts it on, or cues an archive rebuild rewrote. * A read with no `version` takes either form. + * + * `timeoutMs`: a network fetch (its redirects and its body) is abandoned after + * that long (AbortSignal.timeout). Absent: no limit, as it always was. */ export function createJsonCache({ cacheDir = DEFAULT_CACHE_DIR, fetchImpl = globalThis.fetch, log = () => {}, refreshAfterMs = Infinity, + timeoutMs = null, } = {}) { /** URL -> { version, body }: version null for a document cached without one. */ const mem = new Map(); @@ -250,7 +258,7 @@ export function createJsonCache({ log(`fetch ${url}`); // An archive is untrusted input (archive-fetch.mjs): the document is // read on the origin it was asked on, and never past 32 MB. - const res = await fetchOnOrigin(fetchImpl, url); + const res = await fetchOnOrigin(fetchImpl, url, timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}); if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`); const json = await readJsonBounded(res, url); mem.set(url, { version, body: json }); @@ -289,14 +297,22 @@ export function createCueSource({ prefer = "auto", // Opt-in, because it is expensive: see resolveSiteId below. resolveSiteIds = false, + // Re-read the archive's INDEX -- corpus.json and a channel's transcripts + // manifest -- once in this process, not the disk cache's copy (which is kept + // forever): for a reader that wants the archive's current word on a record + // (umtool source-status). A shard page follows its manifest's generation anyway. + refreshIndex = false, + // createJsonCache's: each network fetch abandoned after this long (null: no limit). + timeoutMs = null, } = {}) { - const { getJson } = createJsonCache({ cacheDir, fetchImpl, log }); + const { getJson } = createJsonCache({ cacheDir, fetchImpl, log, timeoutMs }); + const index = refreshIndex ? { refresh: true } : {}; const layers = Array.isArray(channelsDirs) && channelsDirs.length ? channelsDirs : [ownChannelsDir]; const channelsDir = layers[0]; let saidFallback = false; async function channelEntry(origin, channelSlug) { - const corpus = await getJson(`${origin}/corpus.json`); + const corpus = await getJson(`${origin}/corpus.json`, index); // A cited report site (corpus spec 5, `site.scope: "cited"`) publishes its // reports and the moments they cite — no channels, no transcript shards — // so there are no cues to walk to. Say that, not "channel not found". @@ -331,7 +347,7 @@ export function createCueSource({ // instead and this runs only when asked. async function resolveSiteId(origin, entry, wanted) { const manifestAt = transcriptsManifestUrl(origin, entry); - const manifest = await getJson(manifestAt); + const manifest = await getJson(manifestAt, index); log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`); for (let n = 0; n < manifest.pageCount; n += 1) { const page = await getJson(pageUrlFrom(manifestAt, n), { version: pagesVersionOf(manifest) }); @@ -358,13 +374,13 @@ export function createCueSource({ // The manifest corpus.json names, when it is on the archive's own origin; // one named elsewhere is not followed — the contract's URL is read instead. const manifestAt = transcriptsManifestUrl(origin, entry); - const manifest = await getJson(manifestAt); + const manifest = await getJson(manifestAt, index); const pageNumber = manifest.slugToPage?.[siteVideo]; if (pageNumber === undefined) { if (resolveSiteIds) { const hit = await resolveSiteId(origin, entry, siteVideo); - if (hit) return { ...hit, from: "http" }; + if (hit) return { ...hit, from: "http", ...archiveAt(manifest) }; } throw new CueLookupError( `"${siteVideo}" is not in ${siteChannel}'s published slugToPage on ${origin}.\n` + @@ -388,7 +404,7 @@ export function createCueSource({ { channelSlug, videoId, tried: [pageUrlFrom(manifestAt, pageNumber)] }, ); } - return { ...record, from: "http" }; + return { ...record, from: "http", ...archiveAt(manifest) }; } // A TWIN OF THE EDITOR'S TEXT GUARD. `assertChannelTextReadable` diff --git a/umtool/report-to-video/deck-source-status.test.mjs b/umtool/report-to-video/deck-source-status.test.mjs @@ -0,0 +1,288 @@ +// The source status on the deck's source line (lane source-status): the words from +// one table, the part placed by the switch or by `parts`, read from the manifest's +// stamp alone -- and a cut with the switch off, or on with no stamp, draws the +// schedule and the deck page it always did, byte for byte. +// +// Run with: node --test umtool/report-to-video/deck-source-status.test.mjs + +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import test from "node:test"; + +import { deckSubtitleLinesParts, deckSubtitleParts } from "./attribution.mjs"; +import { deckHtml, scheduleHasStatus, subtitleMarkup } from "./chrome-deck.mjs"; +import { finaleHtml, titleLastParts } from "./chrome-finale.mjs"; +import { estimateSchedule } from "./deck.mjs"; +import { finaleRegions, measureChromeSchedule } from "./build-video.mjs"; +import { validateSubtitleSettings } from "./modules/settings.mjs"; +import { + SOURCE_STATUS_NOW, SOURCE_STATUS_WORDS, clipSourceStatus, sourceStatusNotes, sourceStatusText, statusSourceKeys, + subtitleStatusOn, validateSourceStatus, +} from "./source-status.mjs"; +import { AVAILABILITIES } from "yt-dlp-transcript-common/lib/sourceStatus.mjs"; + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const FONTS = { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf" }; + +const clip = (id, video, start, extra = {}) => ({ id, type: "clip", video, start, end: start + 10, cite: start + 2, quote: "a synthetic line", ...extra }); + +/** A synthetic cut: four clips of one made-up channel. */ +function manifest({ subtitle = null, stamp = undefined, timeline = null } = {}) { + return { + title: "Synthetic cut", + provenance: { channelSlug: "synth-channel", channel: "Synth Channel", siteOrigin: "https://archive.example.test" }, + render: { + width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, + chrome: { engine: "hyperframes", layout: "deck", deck: subtitle ? { subtitle } : {} }, + }, + timeline: timeline ?? [ + clip("c01", "synthvid001", 600, { onscreen: { title: "The first moment" } }), + clip("c02", "synthvid002", 1200, { onscreen: { title: "The second moment" } }), + clip("c03", "synthvid003", 1800, { onscreen: { title: "The third moment" } }), + clip("c04", "synthvid004", 2400, { onscreen: { title: "The fourth moment" } }), + ], + ...(stamp !== undefined ? { sourceStatus: stamp } : {}), + }; +} +const META = (n) => ({ title: `Synthetic stream ${n}`, uploadDate: "20310301", channel: "Synth Channel", webpageUrl: `https://video.example.test/${n}` }); +const METAS = [META(1), META(2), META(3), META(4)]; + +const STAMP = { + refreshedAt: "2031-03-02T00:00:00.000Z", + sources: { + "synth-channel/synthvid001": { now: "members_only", since: "2031-03-01T20:00:00Z", asOf: "2031-03-01T20:00:00Z", first: "public", firstAt: "2031-03-01T10:05:00Z", firstWhen: "live", from: "corpus", evidence: [] }, + "synth-channel/synthvid002": { now: "private", since: null, asOf: "2031-03-01T20:00:00Z", first: "public", firstAt: "2031-02-01T00:00:00Z", firstWhen: "other", from: "corpus", evidence: [] }, + "synth-channel/synthvid003": { now: "deleted", since: null, asOf: "2031-03-01T20:00:00Z", first: null, firstAt: null, firstWhen: null, from: "archive", evidence: [] }, + "synth-channel/synthvid004": { now: "public", since: null, asOf: "2031-03-01T20:00:00Z", first: null, firstAt: null, firstWhen: null, from: "corpus", evidence: [] }, + }, +}; + +const scheduleOf = (m) => estimateSchedule(m, { metas: METAS }); +const pageOf = (m) => deckHtml(scheduleOf(m), m.render, { fonts: FONTS }); +const sha = (s) => createHash("sha256").update(s).digest("hex"); +const seg = (s, id) => s.segments.find((x) => x.id === id); + +// THE BYTES MAIN DRAWS for this cut (no switch, no stamp), computed from main's +// own modules at the lane's base (bbe528138) with this lane's changes stashed. +const MAIN_SCHEDULE_SHA = "c70ee12800800ea78e724d4633b43893abcfb2beea4a86a7681a5b6d7f295f51"; +const MAIN_PAGE_SHA = "19cc5f822e220de5db9131fbe0cac60c8368aa8c801f7b28449577337e8ba093"; + +test("the words: one table, each state with and without its parenthesis", () => { + const w = (now, first = null, firstWhen = null) => sourceStatusText({ now, first, firstWhen }); + assert.equal(w("private", "public", "live"), "now private (public when streamed)"); + assert.equal(w("private", "public", "other"), "now private (was public)"); + assert.equal(w("private"), "now private"); + assert.equal(w("members_only", "public", "live"), "now members-only (public when streamed)"); + assert.equal(w("members_only", "public", "other"), "now members-only (was public)"); + assert.equal(w("members_only"), "now members-only"); + assert.equal(w("deleted", "public", "live"), "now deleted (public when streamed)"); + assert.equal(w("deleted", "public", "other"), "now deleted (was public)"); + assert.equal(w("deleted"), "now deleted"); + for (const quiet of ["public", "unlisted", "needs_auth", "error", "maybe_missing", null]) assert.equal(w(quiet, "public", "live"), "", `${quiet} draws nothing`); + assert.equal(sourceStatusText(null), ""); + // Every string the part can draw is in the table. + assert.deepEqual(Object.keys(SOURCE_STATUS_WORDS.now).sort(), ["deleted", "members_only", "private"]); +}); + +test("a clip's words from the stamp: hidden per clip, none for a src clip or an unstamped source", () => { + const prov = { channelSlug: "synth-channel" }; + assert.equal(clipSourceStatus(clip("a", "synthvid002", 0), STAMP, prov), "now private (was public)"); + assert.equal(clipSourceStatus(clip("a", "synthvid002", 0, { sourceStatus: false }), STAMP, prov), ""); + assert.equal(clipSourceStatus(clip("a", "synthvid002", 0, { src: "clips/own.mp4" }), STAMP, prov), ""); + assert.equal(clipSourceStatus(clip("a", "synthvid009", 0), STAMP, prov), ""); + assert.equal(clipSourceStatus(clip("a", "synthvid002", 0, { channel: "other-synth" }), STAMP, prov), ""); + assert.equal(clipSourceStatus(clip("a", "synthvid002", 0), null, prov), ""); +}); + +test("the subtitle parts: status after the last with the switch, where named in parts, on the second of two lines", () => { + const parts = { channel: "Synth Channel", title: "Synthetic stream", date: "2031-03-01", at: 2100, status: "now private (public when streamed)" }; + assert.deepEqual(deckSubtitleParts(parts, { parts: ["channel", "date", "clock"], status: "end" }).map(([k]) => k), ["channel", "date", "clock", "status"]); + assert.deepEqual(deckSubtitleParts(parts, { parts: ["channel", "status", "date"] }).map(([k]) => k), ["channel", "status", "date"]); + // Off: the part is not drawn even with words; on with no words: dropped. + assert.deepEqual(deckSubtitleParts(parts, {}).map(([k]) => k), ["title", "date"]); + assert.deepEqual(deckSubtitleParts({ ...parts, status: "" }, { status: "end" }).map(([k]) => k), ["title", "date"]); + const [one, two] = deckSubtitleLinesParts(parts, { parts: ["channel", "title", "date", "clock"], status: "end", lines: 2 }); + assert.deepEqual(one.map(([k]) => k), ["title"]); + assert.deepEqual(two.map(([k]) => k), ["channel", "date", "clock", "status"]); +}); + +test("the schedule: each clip's line ends in its status; a public source's line is the line it was", () => { + const s = scheduleOf(manifest({ subtitle: { parts: ["channel", "date", "clock"], status: "end" }, stamp: STAMP })); + assert.equal(seg(s, "c01").subtitle, "Synth Channel · Mar 1, 2031 · 10:02 · now members-only (public when streamed)"); + assert.deepEqual(seg(s, "c01").subtitleParts.at(-1), ["status", "now members-only (public when streamed)"]); + assert.equal(seg(s, "c02").subtitle, "Synth Channel · Mar 1, 2031 · 20:02 · now private (was public)"); + assert.equal(seg(s, "c03").subtitle, "Synth Channel · Mar 1, 2031 · 30:02 · now deleted"); + assert.equal(seg(s, "c04").subtitle, "Synth Channel · Mar 1, 2031 · 40:02"); + assert.ok(seg(s, "c04").subtitleParts.every(([k]) => k !== "status")); + // The page: the part by token, its quiet accent only because one is drawn. + assert.ok(scheduleHasStatus(s)); + const html = deckHtml(s, manifest().render, { fonts: FONTS }); + assert.match(html, /<span class="part" data-p="status" data-short="now members-only">now members-only \(public when streamed\)<\/span>/); + assert.match(html, /<span class="part" data-p="status">now deleted<\/span>/, "no parenthesis: no short form to carry"); + assert.match(html, /\.deck-sub \.part\[data-p="status"\] \{ color: /); + assert.equal(subtitleMarkup("a · b", [["title", "a"], ["status", "b"]]), '<span class="part" data-p="title">a</span><span class="sep">·</span><span class="part" data-p="status">b</span>'); +}); + +test("BYTE FOR BYTE: the switch off, or on with no stamp, draws main's schedule and page", () => { + const base = manifest({ subtitle: { parts: ["channel", "date", "clock"] } }); + const baseSchedule = JSON.stringify(scheduleOf(base), null, 2); + const basePage = pageOf(base); + assert.equal(sha(baseSchedule), MAIN_SCHEDULE_SHA, "the schedule main writes"); + assert.equal(sha(basePage), MAIN_PAGE_SHA, "the deck page main draws"); + for (const [why, m] of [ + ["the switch on, no stamp", manifest({ subtitle: { parts: ["channel", "date", "clock"], status: "end" } })], + ["a stamp, the switch off", manifest({ subtitle: { parts: ["channel", "date", "clock"] }, stamp: STAMP })], + ["a stamp, the switch off explicitly", manifest({ subtitle: { parts: ["channel", "date", "clock"], status: "off" }, stamp: STAMP })], + ]) { + const s = scheduleOf(m); + assert.equal(JSON.stringify(s, null, 2), baseSchedule, `${why}: the schedule`); + assert.equal(scheduleHasStatus(s), false); + // The page reads render.chrome.deck; the switch alone may not change a byte of it. + assert.equal(deckHtml(s, m.render, { fonts: FONTS }), basePage, `${why}: the page`); + } +}); + +// THE BYTES MAIN DRAWS for more of the surfaces (review 1, item 12): a cut whose subtitle is +// `auto`, one of two lines, a finale page, and measureChromeSchedule's schedule -- each with no +// switch and no stamp, computed from main's own modules at the lane's base (bbe528138, the lane's +// changes stashed) with the same fixtures. +const MAIN = { + auto: { schedule: "2562917695a31e711f682f7d83c99ba6277163d768e3cc346856a849ce72bb5a", page: "e8866263a8f9772994fc1e32521e09f96d85c979b1c46a6d86b3e85d5ecef45d" }, + lines2: { schedule: "ba5087e52fed6c6c69df62a27b8857439ef55e7e7edd260c6f747f13a97a5fee", page: "f304f54383a9d3304b6ebf881546b3ad5d36e5cd2c3e88cc167bf664909667de" }, + finale: { schedule: "46d35ab16a28eaed128e735e1da81b2a06ec6b92c1b9ce8c1e5a36e57bdb20b1", page: "e3520445bc3ee328081505aa3e285ff30c94d345f12ee9ddf7a2cfd810353c31" }, + measure: { schedule: "9f8bbe2885447273a660d5d7d0eaf20b86aa67be2c208872febd9f9efe98cb5c" }, +}; + +/** The cut with `deck` as its deck settings, a stamp or not, its last clip the finale's or not. */ +function cut(deck, { stamp = undefined, finale = false } = {}) { + const m = manifest({ stamp }); + m.render.chrome.deck = deck; + if (finale) m.timeline[3] = { ...m.timeline[3], layout: "finale" }; + return m; +} +/** The three ways the part must draw nothing: the switch on with no stamp, a stamp with it off, and "off" said. */ +const QUIET = (deck) => [ + ["the switch on, no stamp", { ...deck, subtitle: { ...deck.subtitle, status: "end" } }, undefined], + ["a stamp, the switch off", deck, STAMP], + ["a stamp, the switch off explicitly", { ...deck, subtitle: { ...deck.subtitle, status: "off" } }, STAMP], + ["a stamp, status named in parts, the switch off", { ...deck, subtitle: { ...deck.subtitle, ...(Array.isArray(deck.subtitle.parts) ? { parts: [...deck.subtitle.parts, "status"] } : {}), status: "off" } }, STAMP], +]; + +for (const [name, deck] of [["auto", { subtitle: {} }], ["lines2", { subtitle: { parts: ["channel", "title", "date", "clock"], lines: 2 } }]]) { + test(`BYTE FOR BYTE (${name === "auto" ? "parts: auto" : "lines: 2"}): main's schedule and page, and the same with the part quiet`, () => { + const base = cut(deck); + const s = scheduleOf(base); + assert.equal(sha(JSON.stringify(s, null, 2)), MAIN[name].schedule, "the schedule main writes"); + assert.equal(sha(deckHtml(s, base.render, { fonts: FONTS })), MAIN[name].page, "the deck page main draws"); + for (const [why, d, stamp] of QUIET(deck)) { + const m = cut(d, { stamp }); + const q = scheduleOf(m); + assert.equal(sha(JSON.stringify(q, null, 2)), MAIN[name].schedule, `${why}: the schedule`); + assert.equal(sha(deckHtml(q, m.render, { fonts: FONTS })), MAIN[name].page, `${why}: the page`); + } + }); +} + +test("BYTE FOR BYTE (the finale page): main's, and the same with the part quiet", () => { + const deck = { subtitle: { parts: ["channel", "title", "date", "clock"] }, finale: {} }; + const page = (m) => { + const s = scheduleOf(m); + return [sha(JSON.stringify(s, null, 2)), sha(finaleHtml(s, m.render, finaleRegions(m.render, "/nowhere", s)[0].window, {}))]; + }; + assert.deepEqual(page(cut(deck, { finale: true })), [MAIN.finale.schedule, MAIN.finale.page]); + for (const [why, d, stamp] of QUIET(deck)) assert.deepEqual(page(cut(d, { stamp, finale: true })), [MAIN.finale.schedule, MAIN.finale.page], why); + // On, with a stamp: the finale's copies of the line carry the status and the page its fit. + const gone = { ...STAMP, sources: { ...STAMP.sources, "synth-channel/synthvid004": STAMP.sources["synth-channel/synthvid001"] } }; + const on = cut({ ...deck, subtitle: { ...deck.subtitle, status: "end" } }, { stamp: gone, finale: true }); + const s = scheduleOf(on); + const html = finaleHtml(s, on.render, finaleRegions(on.render, "/nowhere", s)[0].window, {}); + assert.match(html, /data-p="status" data-short="now members-only">now members-only \(public when streamed\)</); + assert.match(html, /fitStatusRows\(\); fitStatusBlocks\(\);/); +}); + +test("BYTE FOR BYTE (measureChromeSchedule, the build's schedule): main's, and the same with the part quiet", async () => { + const deck = { subtitle: { parts: ["channel", "date", "clock"] } }; + const measured = async (m) => sha(JSON.stringify(await measureChromeSchedule({ manifest: m, entries: m.timeline, segments: [], D: 0.5, durs: [12, 12, 12, 12] }), null, 2)); + assert.equal(await measured(cut(deck)), MAIN.measure.schedule); + for (const [why, d, stamp] of QUIET(deck)) assert.equal(await measured(cut(d, { stamp })), MAIN.measure.schedule, why); + // On, with a stamp: the build's schedule carries it (the stamp alone, no corpus, no network). + const on = cut({ subtitle: { ...deck.subtitle, status: "end" } }, { stamp: STAMP }); + const s = await measureChromeSchedule({ manifest: on, entries: on.timeline, segments: [], D: 0.5, durs: [12, 12, 12, 12] }); + assert.deepEqual(seg(s, "c01").subtitleParts.at(-1), ["status", "now members-only (public when streamed)"]); +}); + +test("an explicit off wins over status named in the parts (review 1, nit 11)", () => { + assert.equal(subtitleStatusOn({ parts: ["channel", "status"], status: "off" }), false); + assert.equal(subtitleStatusOn({ parts: ["channel", "status"] }), true); + assert.equal(subtitleStatusOn({ status: "end" }), true); + const parts = { channel: "Synth Channel", date: "2031-03-01", status: "now private" }; + assert.deepEqual(deckSubtitleParts(parts, { parts: ["channel", "status", "date"], status: "off" }).map(([k]) => k), ["channel", "date"]); +}); + +test("a stamp cannot draw what is not a state: 'constructor' and its kin draw nothing and fail validation (review 1, finding 8)", () => { + for (const now of ["constructor", "toString", "__proto__", "hasOwnProperty", "maybe_missing", "gone"]) { + assert.equal(sourceStatusText({ now }), "", now); + assert.equal(sourceStatusText({ now: "private", first: "public", firstWhen: now }), "now private", `firstWhen ${now}`); + const errors = validateSourceStatus(manifest({ stamp: { refreshedAt: STAMP.refreshedAt, sources: { "a/b": { now } } } })); + assert.match(errors[0] ?? "", /now must be one of/, now); + } + assert.deepEqual(validateSourceStatus(manifest({ stamp: { refreshedAt: STAMP.refreshedAt, sources: { "a/b": { now: null, asOf: null } } } })), []); + // The two lists of states, umtool's and common's, are one list. + assert.deepEqual(SOURCE_STATUS_NOW, AVAILABILITIES); +}); + +test("the notes and check name the same sources: platform clips that are not hidden (review 1, finding 7c)", () => { + const m = manifest({ + timeline: [ + clip("c01", "synthvid001", 0), + clip("c02", "synthvid002", 0, { sourceStatus: false }), + clip("c03", "synthvid003", 0, { src: "clips/own.mp4" }), + clip("c04", "synthvid001", 50), + ], + }); + m.ledger = [{ id: "k1", video: "synthvid009" }]; + assert.deepEqual(statusSourceKeys(m), ["synth-channel/synthvid001"]); +}); + +test("the build's notes leave out a source with no record at all (no state, no reading): nothing to recheck (review 1, finding 7b)", () => { + const stamp = { refreshedAt: STAMP.refreshedAt, sources: { ...STAMP.sources, "synth-channel/synthvid004": { now: null, asOf: null, first: null, from: "corpus", evidence: [] } } }; + const notes = sourceStatusNotes(manifest({ subtitle: { status: "end" }, stamp }), { now: Date.parse("2031-04-30T00:00:00Z") }); + assert.equal(notes.length, 1); + assert.doesNotMatch(notes[0], /synthvid004|never read/); + assert.match(notes[0], /synthvid001/); +}); + +// Review 1, nit 11: the design said status last. In the finale's caption the LAST part is the +// one that wraps and is clamped at two lines (the title, titleLastParts), so a status after a long +// title would be the part cut or pushed out of sight; before it, it stays whole (the page's fit +// drops it whole if even that cannot hold). So the status stays before the title there. +test("the finale's copy of the line keeps the title last, the status before it", () => { + const tok = [["channel", "Synth Channel"], ["title", "Synthetic stream"], ["date", "Mar 1, 2031"], ["status", "now private"]]; + const line = tok.map(([, v]) => v).join(" · "); + assert.deepEqual(titleLastParts(line, tok).map(([k]) => k), ["channel", "date", "status", "title"]); +}); + +test("the build's notes: once that refresh has not been run, and a status older than 14 days", () => { + const on = manifest({ subtitle: { status: "end" } }); + assert.deepEqual(sourceStatusNotes(on, { now: Date.parse("2031-03-03T00:00:00Z") }).length, 1); + assert.match(sourceStatusNotes(on)[0], /source-status <p> refresh` has not been run/); + const stamped = manifest({ subtitle: { status: "end" }, stamp: STAMP }); + assert.deepEqual(sourceStatusNotes(stamped, { now: Date.parse("2031-03-10T00:00:00Z") }), []); + const late = sourceStatusNotes(stamped, { now: Date.parse("2031-03-20T00:00:00Z") }); + assert.equal(late.length, 1); + assert.match(late[0], /older than 14 days: synth-channel\/synthvid001 \(2031-03-01\)/); + const partial = manifest({ subtitle: { status: "end" }, stamp: { ...STAMP, sources: { "synth-channel/synthvid001": STAMP.sources["synth-channel/synthvid001"] } } }); + assert.match(sourceStatusNotes(partial, { now: Date.parse("2031-03-03T00:00:00Z") })[0], /3 source\(s\) not in the stamp/); +}); + +test("validation: the switch's values, the status token, the stamp's shape, a clip's hide", () => { + const v = (subtitle) => validateSubtitleSettings({ subtitle }, { where: "deck" }); + assert.deepEqual(v({ status: "end" }), []); + assert.deepEqual(v({ parts: ["channel", "status"] }), []); + assert.match(v({ status: "on" })[0], /subtitle\.status must be "off" or "end"/); + assert.deepEqual(validateSourceStatus(manifest({ stamp: STAMP })), []); + assert.deepEqual(validateSourceStatus(manifest()), []); + assert.match(validateSourceStatus(manifest({ stamp: { sources: {} } }))[0], /refreshedAt/); + assert.match(validateSourceStatus(manifest({ stamp: { refreshedAt: STAMP.refreshedAt, sources: { "a/b": { now: "private", first: "public" } } } }))[0], /firstWhen/); + assert.match(validateSourceStatus(manifest({ timeline: [clip("c01", "synthvid001", 0, { sourceStatus: true })] }))[0], /may only be false/); +}); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -22,6 +22,7 @@ import { measureOn, measureSlice } from "./measure-slice.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; +import { clipSourceStatus, subtitleStatusOn } from "./source-status.mjs"; import { attributionParts, deckSubtitle, deckSubtitleLines, deckSubtitleLinesParts, deckSubtitleParts, formatDeckDate, hms } from "./attribution.mjs"; import { panelEntry, postDeckText, postItemSeconds, postLayout } from "./post-item.mjs"; import { analysisSeconds } from "./analysis-plan.mjs"; @@ -1301,7 +1302,7 @@ const sameTitle = (a, b) => titleKey(a) === titleKey(b); * `onscreen.title` that only repeats its source's title (sameTitle) is * dropped when the two lines show that title. */ -export function deckText(entry, meta, provenance, deck, multiChannel) { +export function deckText(entry, meta, provenance, deck, multiChannel, status = "") { const o = entry.onscreen ?? {}; let title = o.title ?? ""; let subtitle = o.subtitle; @@ -1314,7 +1315,9 @@ export function deckText(entry, meta, provenance, deck, multiChannel) { const two = deck.subtitle?.lines === 2; if (subtitle === undefined) { if (entry.type === "clip") { - const parts = attributionParts(entry, meta ?? {}, provenance); + // The source status (source-status.mjs), when the deck draws it and the + // stamp names a state: else no key, and the parts are what they were. + const parts = { ...attributionParts(entry, meta ?? {}, provenance), ...(status ? { status } : {}) }; subtitle = deckSubtitle(parts, deck.subtitle, multiChannel); subtitleParts = deckSubtitleParts(parts, deck.subtitle, multiChannel); if (two) subtitleLines = deckSubtitleLines(parts, deck.subtitle, multiChannel); @@ -1409,8 +1412,12 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin export function deckSchedule({ entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null, fxWords = null, fxClock = null, clipClock = null, clipGaps = null, chat = null, measure = null, + sourceStatus = null, }) { const deck = resolveDeck(render); + // The source status on a clip's line (source-status.mjs): the manifest's stamp + // alone, and only when the subtitle draws it. + const statusOf = subtitleStatusOn(deck.subtitle) ? (e) => clipSourceStatus(e, sourceStatus, provenance) : () => ""; // A clip's gaps (gaps.mjs) on its segment: its cut record's as built // (`clipGaps`), else its own. A source second after one plays that much // earlier in the cut; only a segment with any carries `gaps`, so a cut @@ -1532,7 +1539,7 @@ export function deckSchedule({ multiChannel, ...(feed ? { layout: "feed" } : {}), segments: entries.map((e, i) => { - const { title, subtitle, subtitleParts, subtitleLines, subtitleLinesParts } = deckText(e, metas[i] ?? null, provenance, deck, multiChannel); + const { title, subtitle, subtitleParts, subtitleLines, subtitleLinesParts } = deckText(e, metas[i] ?? null, provenance, deck, multiChannel, statusOf(e)); return { id: e.id, type: e.type, @@ -2257,6 +2264,7 @@ export function estimateSchedule(manifest, { metas = [], noXfade = false } = {}) metas, estimated: true, frameScan: manifest.frameScan ?? null, + sourceStatus: manifest.sourceStatus ?? null, // A measure ledger's slice, timed by the quotes (no words in an estimate). ...(manifest.ledgerSchema ? { measure: { ledgerSchema: manifest.ledgerSchema, ledger: manifest.measureLedger ?? manifest.ledger ?? [] } } : {}), }); diff --git a/umtool/report-to-video/modules/settings.mjs b/umtool/report-to-video/modules/settings.mjs @@ -121,7 +121,10 @@ export const MARKER_DEFAULT_COLOR = "amber"; export const QR_LINKS = Object.freeze(["site", "original"]); /** Subtitle tokens a `subtitle.parts` array may name. "auto" picks from these. */ -export const SUBTITLE_TOKENS = Object.freeze(["channel", "title", "date", "clock"]); +export const SUBTITLE_TOKENS = Object.freeze(["channel", "title", "date", "clock", "status"]); + +/** `subtitle.status`: "off" (default) or "end" -- the source status after the last part (source-status.mjs). */ +export { SUBTITLE_STATUS_MODES } from "../source-status.mjs"; /** How many lines the subtitle takes (`subtitle.lines`). */ export const SUBTITLE_LINES = Object.freeze([1, 2]); @@ -342,7 +345,10 @@ export function validateSectionTitleSettings(v, { where: w }) { export function validateSubtitleSettings(d, { where: w }) { const errors = []; const tokens = (v) => Array.isArray(v) && v.length > 0 && v.every((p) => SUBTITLE_TOKENS.includes(p)) && new Set(v).size === v.length; - sub(d, "subtitle", ["parts", "dateFormat", "lines", "head"], w, errors, (s) => { + sub(d, "subtitle", ["parts", "dateFormat", "lines", "head", "status"], w, errors, (s) => { + if (s.status !== undefined && !["off", "end"].includes(s.status)) { + errors.push(`${w}.subtitle.status must be "off" or "end" (the source status after the last part)`); + } if (s.parts !== undefined && s.parts !== "auto") { if (!tokens(s.parts)) { errors.push(`${w}.subtitle.parts must be "auto" or a list of distinct ${SUBTITLE_TOKENS.join("/")}`); diff --git a/umtool/report-to-video/modules/subtitle.mjs b/umtool/report-to-video/modules/subtitle.mjs @@ -18,27 +18,30 @@ export default defineModule({ // Its form in the stacked vertical deck (vertical-deck.mjs). vertical: { slot: "inline" }, title: "Subtitle", - summary: "Each clip's source line under its title: the channel, the source's title, the date, the clock.", + summary: "Each clip's source line under its title: the channel, the source's title, the date, the clock, and (when on) what became of the source.", configKey: "render.chrome.deck.subtitle", defaults: DECK_DEFAULTS.subtitle, validate: settingsOf("subtitle").validate, resolve: (render) => ({ ...DECK_DEFAULTS.subtitle, ...(render?.chrome?.deck?.subtitle ?? {}) }), ui: [ { key: "parts", type: "list", options: ["auto", ...SUBTITLE_TOKENS], label: "Parts", default: "auto", - help: "\"auto\", or the parts in order: channel, title, date, clock" }, + help: "\"auto\", or the parts in order: channel, title, date, clock, status" }, { key: "dateFormat", type: "enum", options: ["long", "iso"], label: "Date format", default: "long" }, { key: "lines", type: "number", min: SUBTITLE_LINES[0], max: SUBTITLE_LINES[SUBTITLE_LINES.length - 1], step: 1, label: "Lines", default: 1, help: "2: the source's title on a line of its own (it shrinks to fit before it ellipsizes), the channel, date and clock under it; the deck grows by that line" }, { key: "head", type: "list", options: ["auto", ...SUBTITLE_TOKENS], label: "First line", default: "auto", when: { lines: 2 }, help: "\"auto\" (the source's title), or the parts on the first line; the rest of the parts go on the second" }, + { key: "status", type: "enum", options: ["off", "end"], label: "Source status", default: "off", + help: "end: \"now private (public when streamed)\" after the last part, for a source a viewer can no longer watch -- from the stamp `umtool source-status <p> refresh` writes" }, ], docs: { heading: "Subtitle", intro: "The source line under each clip's title, in the deck. The automatic line is set by what each part IS, wherever it stands: when it runs long the title gives way first (an ellipsis at its end), a channel ellipsizes only past 40 % of the line, and the date and the clock always show whole -- so `[channel, title, date, clock]` never reads \"… · Oct … · 1:08:48\" (the schedule's `subtitleParts`, chrome-deck.mjs subtitleMarkup; the finale's copy of the line too). An entry's typed `onscreen.subtitle` has no parts to name: its middle parts give way, its first and last show whole.", rows: [ - ["`deck.subtitle.parts`", "`auto` · a list of distinct `channel` `title` `date` `clock` · default `auto`", "`umtool look <p> deck.subtitle='{\"parts\":[\"channel\",\"date\",\"clock\"]}'`"], + ["`deck.subtitle.parts`", "`auto` · a list of distinct `channel` `title` `date` `clock` `status` · default `auto`", "`umtool look <p> deck.subtitle='{\"parts\":[\"channel\",\"date\",\"clock\"]}'`"], ["`deck.subtitle.dateFormat`", "`long` (24 Oct 2020) · `iso` · default `long`", "`umtool look <p> deck.subtitle='{\"dateFormat\":\"iso\"}'`"], ["`deck.subtitle.lines`", "`1` · `2`: the source's title on a line of its own (a size up; it shrinks to 70 % before it ellipsizes), the other parts under it. The deck grows by that line (39 px at the default title size) and the footage must still fit above it: with full-width footage that needs `footageScale` at most about 0.78 · default `1`", "`umtool look <p> deck.subtitle.lines=2 deck.footageScale=0.78`"], + ["`deck.subtitle.status`", "`off` · `end`: the SOURCE STATUS after the last part (or name `status` in `parts` to place it; an explicit `off` wins over that) -- `now private` / `now members-only` / `now deleted`, with `(public when streamed)` or `(was public)` only when the archive's records prove it; nothing for a public, unlisted or age-gated source, or when the records disagree. Never drawn cut: where the line cannot hold it whole it drops the parenthesis, then lets the channel give way, then is not drawn. Read from the manifest's `sourceStatus` stamp alone (`umtool source-status <p> refresh`; never the network at render) · default `off`", "`umtool look <p> deck.subtitle.status=end` then `umtool source-status <p> refresh`"], ["`deck.subtitle.head`", "`auto` (the source's title) · a list of distinct parts for the first of two lines; the rest of `parts` take the second · default `auto`", "`umtool look <p> deck.subtitle.head='[\"channel\",\"title\"]'`"], ], }, diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -18,6 +18,7 @@ }, "exports": { "./attribution": "./attribution.mjs", + "./source-status": "./source-status.mjs", "./video-entry": "./video-entry.mjs", "./full-frame": "./full-frame.mjs", "./analysis-plan": "./analysis-plan.mjs", diff --git a/umtool/report-to-video/source-status.mjs b/umtool/report-to-video/source-status.mjs @@ -0,0 +1,179 @@ +// THE SOURCE STATUS ON THE SOURCE LINE (lane source-status): "… · now private (public +// when streamed)". The words in ONE table, and the reading of the manifest's stamp. +// +// A render reads ONLY the stamp: the manifest's `sourceStatus`, written by +// `umtool source-status <p> refresh` (lib/report/sourceStatusCli.mjs) from the +// corpus's records (common lib/sourceStatus.mjs) or the published record. It never +// reads the corpus for this and never asks the network, so a machine with no +// corpus draws the same line and a take is reproducible. +// +// "sourceStatus": { "refreshedAt": ISO, "sources": { "<channel>/<video>": { +// now, since, asOf, first: "public"|null, firstAt, firstWhen: "live"|"other"|null, +// from: "corpus"|"archive", evidence: [...], recordsAt?: ISO } } } +// +// `now` is null when the records hold no state the line may say (no record, records +// that disagree, a removal no check read): the reason is in `evidence`. `recordsAt` +// (corpus entries) is the newest write of the records that reading saw. +// +// The part draws only for the states a viewer cannot watch at the platform +// (private, members-only, deleted). Public, unlisted, an age gate or a login +// wall, an error, no record: nothing, and the line is what it always was. +// +// No node builtins: attribution.mjs, which the clip bench's client preview +// imports, imports this. + +/** THE WORDS. Every string the part can draw, here and nowhere else (the operator rules on them). */ +export const SOURCE_STATUS_WORDS = Object.freeze({ + now: Object.freeze({ + private: "now private", + members_only: "now members-only", + deleted: "now deleted", + }), + first: Object.freeze({ + live: "public when streamed", + other: "was public", + }), +}); + +/** A status older than this many days at build is stale: the build notes it, `umtool check` lists it (never blocks). */ +export const SOURCE_STATUS_STALE_DAYS = 14; + +/** `deck.subtitle.status`: "off" (the default: the line as it always was) or "end" (the part after the last). */ +export const SUBTITLE_STATUS_MODES = Object.freeze(["off", "end"]); + +/** + * Every value a stamped source's `now` may hold, beside null: availability.ts + * AVAILABILITY_VALUES (common lib/sourceStatus.mjs AVAILABILITIES; a test holds the + * two equal). Restated, not imported: the clip bench's client preview imports this. + */ +export const SOURCE_STATUS_NOW = Object.freeze(["public", "unlisted", "private", "members_only", "needs_auth", "deleted", "error"]); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +/** A table's own entry, never an inherited one ("constructor", "toString"). */ +const own = (table, k) => (typeof k === "string" && Object.hasOwn(table, k) ? table[k] : undefined); + +/** The stamp's key for a clip: `<channel>/<video>`, as manifestSources keys a source. */ +export function sourceKeyOf(entry, provenance = {}) { + const channel = entry?.channel ?? provenance?.channelSlug ?? null; + return channel && entry?.video ? `${channel}/${entry.video}` : null; +} + +/** One stamped source's words, or "" (a state the part does not name, or no stamp). */ +export function sourceStatusText(s) { + if (!isObj(s)) return ""; + const now = own(SOURCE_STATUS_WORDS.now, s.now); + if (!now) return ""; + const first = s.first === "public" ? own(SOURCE_STATUS_WORDS.first, s.firstWhen) : null; + return first ? `${now} (${first})` : now; +} + +/** + * A clip's status words from the manifest's stamp, or "": not a clip, a `src` + * clip (a file on no platform), a clip that hides it (`sourceStatus: false`), or + * a source the stamp does not name. + */ +export function clipSourceStatus(entry, stamp, provenance = {}) { + if (entry?.type !== "clip" || entry.src != null || entry.sourceStatus === false) return ""; + if (!isObj(stamp) || !isObj(stamp.sources)) return ""; + const key = sourceKeyOf(entry, provenance); + return key ? sourceStatusText(stamp.sources[key]) : ""; +} + +/** + * Does the deck's subtitle draw the part: the switch at "end", or `status` named in + * its parts -- unless the switch says "off", which wins over the parts. + */ +export function subtitleStatusOn(subtitle) { + if (subtitle?.status === "off") return false; + return subtitle?.status === "end" || (Array.isArray(subtitle?.parts) && subtitle.parts.includes("status")); +} + +/** + * The stamp's keys the deck's lines read: one per clip that can draw the part (a + * platform clip, not a `src` file, not hidden with `sourceStatus: false`), in + * timeline order. The build's notes and `umtool check`'s record walk both read + * these, so they name the same sources. + */ +export function statusSourceKeys(manifest) { + const provenance = manifest?.provenance ?? {}; + return [...new Set((manifest?.timeline ?? []) + .filter((e) => e?.type === "clip" && e.src == null && e.sourceStatus !== false) + .map((e) => sourceKeyOf(e, provenance)) + .filter(Boolean))]; +} + +/** The manifest's `sourceStatus` checked: a list of what is wrong with it (empty: fine, or absent). */ +export function validateSourceStatusStamp(v, where = "sourceStatus") { + if (v === undefined) return []; + const errors = []; + if (!isObj(v)) return [`${where} must be an object ({ refreshedAt, sources }) -- written by \`umtool source-status <p> refresh\``]; + if (typeof v.refreshedAt !== "string" || !Number.isFinite(Date.parse(v.refreshedAt))) errors.push(`${where}.refreshedAt must be an ISO time`); + if (!isObj(v.sources)) errors.push(`${where}.sources must be an object keyed "<channel>/<video>"`); + else { + for (const [k, s] of Object.entries(v.sources)) { + if (!/^[^/\s]+\/[^/\s]+$/.test(k)) errors.push(`${where}.sources key "${k}" is not "<channel>/<video>"`); + if (!isObj(s)) { + errors.push(`${where}.sources["${k}"] must be an object`); + continue; + } + if (s.now !== null && !SOURCE_STATUS_NOW.includes(s.now)) errors.push(`${where}.sources["${k}"].now must be one of ${SOURCE_STATUS_NOW.join("/")} or null`); + if (s.first !== null && s.first !== undefined && s.first !== "public") errors.push(`${where}.sources["${k}"].first must be "public" or null`); + if (s.first === "public" && !["live", "other"].includes(s.firstWhen)) errors.push(`${where}.sources["${k}"].firstWhen must be "live" or "other" beside first "public"`); + if (s.asOf != null && (typeof s.asOf !== "string" || !Number.isFinite(Date.parse(s.asOf)))) errors.push(`${where}.sources["${k}"].asOf must be an ISO time or null`); + if (s.recordsAt != null && (typeof s.recordsAt !== "string" || !Number.isFinite(Date.parse(s.recordsAt)))) errors.push(`${where}.sources["${k}"].recordsAt must be an ISO time or absent`); + } + } + return errors; +} + +/** The manifest's stamp and every clip's `sourceStatus` (only `false`, to hide it there), checked. */ +export function validateSourceStatus(manifest) { + const errors = validateSourceStatusStamp(manifest?.sourceStatus); + for (const e of manifest?.timeline ?? []) { + if (e?.sourceStatus !== undefined && e.sourceStatus !== false) { + errors.push(`clip ${e?.id ?? "?"}: sourceStatus may only be false (hide the source status on its line)`); + } + } + return errors; +} + +/** + * What the build says about the stamp, once each (notes, never refusals), for a + * deck whose subtitle draws the part: the stamp is missing (`source-status + * refresh` has not been run), or a cited source's status is older than + * SOURCE_STATUS_STALE_DAYS (or not in the stamp at all). + * + * @param {{ timeline?: any[], provenance?: any, sourceStatus?: any }} manifest + * @param {{ now?: number }} [opts] + * @returns {string[]} + */ +export function sourceStatusNotes(manifest, { now = Date.now() } = {}) { + const stamp = manifest?.sourceStatus; + const keys = statusSourceKeys(manifest); + if (!keys.length) return []; + if (!isObj(stamp) || !isObj(stamp.sources)) { + return ["deck.subtitle draws the source status, but `umtool source-status <p> refresh` has not been run: no clip's line says it"]; + } + const limit = SOURCE_STATUS_STALE_DAYS * 86_400_000; + const old = []; + const missing = []; + for (const k of keys) { + const s = stamp.sources[k]; + if (!isObj(s)) { + missing.push(k); + continue; + } + // No availability record at all (no state, no reading): nothing a recheck of it would + // change on the line, and a public never-checked source is the common case. Not listed. + if (s.now == null && s.asOf == null) continue; + const at = Date.parse(s.asOf ?? ""); + if (!Number.isFinite(at) || now - at > limit) old.push(`${k} (${Number.isFinite(at) ? new Date(at).toISOString().slice(0, 10) : "never read"})`); + } + const notes = []; + if (missing.length) notes.push(`source status: ${missing.length} source(s) not in the stamp (${missing.join(", ")}) -- \`umtool source-status <p> refresh\``); + if (old.length) { + const shown = old.length > 6 ? `${old.slice(0, 6).join(", ")} and ${old.length - 6} more` : old.join(", "); + notes.push(`source status older than ${SOURCE_STATUS_STALE_DAYS} days: ${shown} -- recheck (pnpm ops refresh-metadata; a removal: the channel's Check availability), then \`umtool source-status <p> refresh\``); + } + return notes; +} diff --git a/umtool/report-to-video/status-fit.mjs b/umtool/report-to-video/status-fit.mjs @@ -0,0 +1,86 @@ +// THE SOURCE STATUS NEVER DRAWS CUT (lane source-status, review 1 finding 6). +// +// A deck's source line is one nowrap row that clips what it cannot hold +// (chrome-deck.mjs .deck-sub: flex, overflow hidden). The title gives way first; +// the channel holds up to 40 % of the line; the date, the clock and the status +// never shrink. So in a narrow column (a tally beside the QR, a long channel) the +// row's TAIL is cut -- "now members-only (public wh" -- which is worse than no +// status at all. This is the page's fit, run once the faces are in (the same +// moment the title's fit runs), on every line that carries a status: +// +// 1. the whole words, when the row holds them and the source's title keeps at +// least TITLE_KEEP_EM of itself (or all of itself); +// 2. the short form -- the state alone, "now members-only", no parenthesis -- +// when the row holds that; +// 3. the same with the channel giving way too (it ellipsizes); +// 4. nothing: the status and its separator are not drawn. +// +// The finale's caption (`.cs`, two wrapped lines, the title last) is a block, not +// a row: a status that is not wholly inside its two lines takes the short form, +// then nothing. Never a cut status, in either. +// +// `fitStatusLine` is a plain function so the page carries its own source +// (`fitStatusLine.toString()`, chrome-deck.mjs / chrome-finale.mjs) and a test can +// drive it over a stand-in for the DOM. It touches only what it is given: the +// line's `querySelector`, `classList`, `scrollWidth` / `clientWidth`, and the +// parts' text, attributes, offsets and style. No closure: the page has none. + +/** The least of the source's title, in em of the line, that the whole status may squeeze it to. */ +export const TITLE_KEEP_EM = 6; + +/** + * The status's short form: its state words, the parenthesis dropped (source-status.mjs + * SOURCE_STATUS_WORDS: "now private (public when streamed)" -> "now private"), or + * null when it has none to drop. + */ +export function statusShortForm(words) { + const i = String(words ?? "").indexOf(" ("); + return i > 0 ? String(words).slice(0, i) : null; +} + +/** + * Fit one line's status (see the header). Returns what it drew: "long", "short", + * "short-channel" (the channel gave way too), "none" (dropped), or "absent" (no + * status on the line). + * + * @param {any} line a `.deck-sub` / `.dts` row, or a `.cs` block (`mode: "block"`) + * @param {number} em the line's font size, px + * @param {"row"|"block"} [mode] + * @param {number} [keepEm] TITLE_KEEP_EM (passed: the page's copy has no imports) + */ +export function fitStatusLine(line, em, mode = "row", keepEm = 6) { + const st = line.querySelector('.part[data-p="status"]'); + if (!st) return "absent"; + if (!st.hasAttribute("data-full")) st.setAttribute("data-full", st.textContent); + const full = st.getAttribute("data-full"); + const short = st.getAttribute("data-short"); + // The separator that joins the status to the line: the one before it, else (first in the line) the one after. + const prev = st.previousElementSibling; + const next = st.nextElementSibling; + const sep = prev && prev.classList.contains("sep") ? prev : next && next.classList.contains("sep") ? next : null; + // From the start, so a second fit (the live preview's) reads the line as drawn. + st.textContent = full; + st.style.display = ""; + if (sep) sep.style.display = ""; + line.classList.remove("st-give"); + + const holds = mode === "block" + ? () => st.offsetWidth <= line.clientWidth + 0.5 && st.offsetTop - line.offsetTop + st.offsetHeight <= line.clientHeight + 0.5 + : () => line.scrollWidth <= line.clientWidth + 0.5; + const title = mode === "row" ? line.querySelector('.part[data-p="title"]') : null; + const titleKept = () => !title || title.clientWidth + 0.5 >= Math.min(title.scrollWidth, keepEm * em); + + if (holds() && titleKept()) return "long"; + if (short && short !== full) { + st.textContent = short; + if (holds()) return "short"; + } + if (mode === "row" && line.querySelector('.part[data-p="channel"]')) { + line.classList.add("st-give"); + if (holds()) return "short-channel"; + line.classList.remove("st-give"); + } + st.style.display = "none"; + if (sep) sep.style.display = "none"; + return "none"; +} diff --git a/umtool/report-to-video/status-fit.test.mjs b/umtool/report-to-video/status-fit.test.mjs @@ -0,0 +1,251 @@ +// The source status never draws cut (lane source-status, review 1 finding 6): the +// page's fit takes the whole words, else the short form, else lets the channel +// give way, else draws nothing -- driven here over a stand-in for the DOM that lays +// a row out as the deck's CSS does (the title and, given way, the channel shrink in +// proportion to their widths, to nothing; the channel holds at most 40 %; every +// other part stays whole), and once in chromium when it is there. +// +// Run with: node --test umtool/report-to-video/status-fit.test.mjs + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { TITLE_KEEP_EM, fitStatusLine, statusShortForm } from "./status-fit.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PX = 12; // a character's advance in the stand-in +const SEP = 22; +const EM = 26; + +class ClassList { + constructor(names = []) { this.set = new Set(names); } + contains(n) { return this.set.has(n); } + add(n) { this.set.add(n); } + remove(n) { this.set.delete(n); } +} + +/** A row of parts `[token, text]` joined by separators, `width` px wide. */ +function row(width, parts) { + const nodes = []; + const line = { classList: new ClassList(["deck-sub"]), clientWidth: width }; + for (const [k, text, short] of parts) { + if (nodes.length) nodes.push({ classList: new ClassList(["sep"]), style: { display: "" }, textContent: "·" }); + const attrs = new Map([["data-p", k], ...(short ? [["data-short", short]] : [])]); + nodes.push({ + classList: new ClassList(["part"]), style: { display: "" }, textContent: text, + hasAttribute: (a) => attrs.has(a), getAttribute: (a) => attrs.get(a) ?? null, setAttribute: (a, v) => attrs.set(a, v), + }); + } + nodes.forEach((n, i) => { + n.previousElementSibling = nodes[i - 1] ?? null; + n.nextElementSibling = nodes[i + 1] ?? null; + }); + const shown = () => nodes.filter((n) => n.style.display !== "none"); + const natural = (n) => (n.classList.contains("sep") ? SEP : n.textContent.length * PX); + const keyOf = (n) => (n.getAttribute ? n.getAttribute("data-p") : null); + // The CSS's layout: flex-basis is the natural width (a channel's capped at 40 %); + // the shrinkable parts give up the overflow in proportion to their basis, to 0. + function layout() { + const give = line.classList.contains("st-give"); + const width = line.clientWidth; + const basis = new Map(shown().map((n) => [n, keyOf(n) === "channel" ? Math.min(natural(n), 0.4 * width) : natural(n)])); + const shrinks = (n) => keyOf(n) === "title" || (give && keyOf(n) === "channel"); + let over = [...basis.values()].reduce((a, b) => a + b, 0) - width; + const size = new Map(basis); + for (let pass = 0; over > 1e-9 && pass < 10; pass++) { + const live = [...size].filter(([n, w]) => shrinks(n) && w > 0); + const total = live.reduce((a, [, w]) => a + w, 0); + if (!total) break; + for (const [n, w] of live) size.set(n, Math.max(0, w - over * (w / total))); + over = [...size.values()].reduce((a, b) => a + b, 0) - width; + } + return size; + } + Object.defineProperty(line, "scrollWidth", { get: () => Math.max(line.clientWidth, [...layout().values()].reduce((a, b) => a + b, 0)) }); + for (const n of nodes) { + Object.defineProperty(n, "clientWidth", { get: () => layout().get(n) ?? 0 }); + Object.defineProperty(n, "scrollWidth", { get: () => natural(n) }); + } + line.querySelector = (sel) => { + const m = /\[data-p="([^"]+)"\]/.exec(sel); + return nodes.find((n) => keyOf(n) === m?.[1]) ?? null; + }; + const status = nodes.find((n) => keyOf(n) === "status"); + return { line, status, sepBefore: status?.previousElementSibling, layout }; +} + +const LONG = "now members-only (public when streamed)"; // 39 characters: 468 px +const SHORT = "now members-only"; // 16: 192 px +const PARTS = (title = "A synthetic stream title") => [ + ["channel", "Synth Channel"], // 156 px + ["title", title], + ["date", "Mar 1, 2031"], // 132 px + ["clock", "35:00"], // 60 px + ["status", LONG, SHORT], +]; + +test("the short form drops the parenthesis, and only that", () => { + assert.equal(statusShortForm(LONG), SHORT); + assert.equal(statusShortForm("now deleted (was public)"), "now deleted"); + assert.equal(statusShortForm("now private"), null); + assert.equal(statusShortForm(""), null); +}); + +test("a wide column draws the whole words; the title keeps its room", () => { + const r = row(1500, PARTS()); + assert.equal(fitStatusLine(r.line, EM, "row", TITLE_KEEP_EM), "long"); + assert.equal(r.status.textContent, LONG); +}); + +test("THE NARROWEST COLUMN: the tail is never cut -- the short form, then the channel gives way, then nothing", () => { + // Fixed parts: channel 156 + date 132 + clock 60 + 4 separators 88 = 436 px, then the status. + // 700 px: the whole status (468) would leave the title nothing; the short (192) fits. + const narrow = row(700, PARTS()); + assert.equal(fitStatusLine(narrow.line, EM, "row", TITLE_KEEP_EM), "short"); + assert.equal(narrow.status.textContent, SHORT); + assert.ok(narrow.line.scrollWidth <= 700 + 0.5, "nothing past the column"); + // 600 px: even the short one overflows with the channel whole (436 + 192 = 628); the channel gives way. + const tighter = row(600, PARTS()); + assert.equal(fitStatusLine(tighter.line, EM, "row", TITLE_KEEP_EM), "short-channel"); + assert.ok(tighter.line.classList.contains("st-give")); + assert.ok(tighter.line.scrollWidth <= 600 + 0.5); + // 400 px: the date, the clock and the separators alone take 280 with the short form's 192 past it: nothing. + const tightest = row(400, PARTS()); + assert.equal(fitStatusLine(tightest.line, EM, "row", TITLE_KEEP_EM), "none"); + assert.equal(tightest.status.style.display, "none"); + assert.equal(tightest.sepBefore.style.display, "none", "its separator goes with it"); + assert.equal(tightest.line.classList.contains("st-give"), false, "the channel is not squeezed for nothing"); +}); + +test("the whole words may squeeze the title, but not below TITLE_KEEP_EM (or all of itself)", () => { + // 1000 px: 436 + 468 = 904 leaves the title 96 px of its 288, under 6 em (156): the short form. + const squeezed = row(1000, PARTS()); + assert.equal(fitStatusLine(squeezed.line, EM, "row", TITLE_KEEP_EM), "short"); + // A short title (60 px) kept whole: the whole words. + const shortTitle = row(1000, PARTS("Live")); + assert.equal(fitStatusLine(shortTitle.line, EM, "row", TITLE_KEEP_EM), "long"); +}); + +test("a second fit starts from the line as drawn (the live preview's)", () => { + const r = row(400, PARTS()); + assert.equal(fitStatusLine(r.line, EM), "none"); + r.line.clientWidth = 1500; // the same line, its column widened + assert.equal(fitStatusLine(r.line, EM), "long"); + assert.equal(fitStatusLine(r.line, EM), "long", "idempotent"); + assert.equal(r.status.style.display, ""); + assert.equal(r.status.textContent, LONG); + r.line.clientWidth = 700; + assert.equal(fitStatusLine(r.line, EM), "short"); +}); + +test("a line with no status is left alone", () => { + const r = row(300, PARTS().slice(0, 4)); + assert.equal(fitStatusLine(r.line, EM), "absent"); +}); + +test("the finale's caption (a block of two lines): wholly inside, else the short form, else nothing", () => { + const make = (fitsLong, fitsShort) => { + const attrs = new Map([["data-p", "status"], ["data-short", SHORT]]); + const st = { + classList: new ClassList(["part"]), style: { display: "" }, textContent: LONG, + hasAttribute: (a) => attrs.has(a), getAttribute: (a) => attrs.get(a) ?? null, setAttribute: (a, v) => attrs.set(a, v), + previousElementSibling: { classList: new ClassList(["sep"]), style: { display: "" } }, nextElementSibling: null, + get offsetWidth() { return this.textContent.length * PX; }, + get offsetTop() { return (this.textContent === LONG ? fitsLong : fitsShort) ? 31 : 62; }, + offsetHeight: 31, + }; + const cs = { classList: new ClassList(["cs"]), clientWidth: 640, clientHeight: 62, offsetTop: 0, querySelector: (sel) => (/status/.test(sel) ? st : null) }; + return { cs, st }; + }; + const a = make(true, true); + assert.equal(fitStatusLine(a.cs, EM, "block"), "long"); + const b = make(false, true); + assert.equal(fitStatusLine(b.cs, EM, "block"), "short"); + const c = make(false, false); + assert.equal(fitStatusLine(c.cs, EM, "block"), "none"); + assert.equal(c.st.style.display, "none"); +}); + +// THE REAL PAGE, when chromium is on the machine: a deck whose column a tally and a +// long channel narrow, its DOM after the fit. +const CHROME = process.env.CHROME ?? "/usr/bin/chromium"; +const haveChromium = spawnSync(CHROME, ["--version"], { stdio: "ignore" }).status === 0; + +test("in chromium: the narrowest column draws a whole status or none, never a cut one", { skip: !haveChromium }, async () => { + const { composeChrome } = await import("./compose-chrome.mjs"); + const { estimateSchedule } = await import("./deck.mjs"); + const dir = mkdtempSync(path.join(tmpdir(), "status-fit-")); + try { + const face = path.join(HERE, "fonts", "IBMPlexSans[wdth,wght].ttf"); + const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; + const stamp = (now, firstWhen) => ({ now, since: null, asOf: "2031-03-01T00:00:00Z", first: firstWhen ? "public" : null, firstAt: null, firstWhen, from: "corpus", evidence: [] }); + const manifest = { + slug: "t", title: "Synthetic cut", + provenance: { channelSlug: "synth-channel", channel: "A Synthetic Channel With A Long Display Name" }, + render: { + width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, fontRegular: face, fontBold: face, + chrome: { + engine: "hyperframes", layout: "deck", + deck: { subtitle: { parts: ["channel", "title", "date", "clock"], status: "end" } }, + factcheck: { verdicts: { CONTRADICTED: { label: "Synthetic" }, CORROBORATED: { label: "Synthetic too" } } }, + }, + }, + timeline: [ + { id: "c01", type: "clip", video: "synthvid001", start: 2090, end: 2110, cite: 2100, onscreen: { title: "The first synthetic moment" }, claim: { id: "k1", verdict: "CONTRADICTED" } }, + { id: "c02", type: "clip", video: "synthvid002", start: 2090, end: 2110, cite: 2100, onscreen: { title: "The second" }, claim: { id: "k2", verdict: "CORROBORATED" } }, + ], + sourceStatus: { refreshedAt: "2031-03-02T00:00:00.000Z", sources: { "synth-channel/synthvid001": stamp("members_only", "live"), "synth-channel/synthvid002": stamp("private", "other") } }, + }; + const meta = { title: "A synthetic stream title that runs long enough to have to give way on the line", uploadDate: "20310301", channel: manifest.provenance.channel }; + const schedule = estimateSchedule(manifest, { metas: [meta, meta] }); + const manifestPath = path.join(dir, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify(manifest)); + const { projDir } = await composeChrome({ manifestPath, region: "deck", schedule }); + // The test's own probe, after the page's fit: does each line hold what it draws, and + // would it have held the whole words (the column is as narrow as the test says)? + const page = path.join(projDir, "index.html"); + const { readFileSync } = await import("node:fs"); + writeFileSync(page, readFileSync(page, "utf8").replace("</body>", `<script> + const probe = () => { + if (document.documentElement.dataset.fit !== "1") return setTimeout(probe, 20); + for (const line of document.querySelectorAll(".deck-sub")) { + const st = line.querySelector('.part[data-p="status"]'); + if (!st) continue; + line.dataset.holds = String(line.scrollWidth <= line.clientWidth + 0.5); + const drawn = [st.textContent, st.style.display, line.className]; + st.textContent = st.dataset.full; st.style.display = ""; line.classList.remove("st-give"); + line.dataset.wholeHeld = String(line.scrollWidth <= line.clientWidth + 0.5); + [st.textContent, st.style.display, line.className] = drawn; + } + document.documentElement.dataset.probed = "1"; + }; + probe(); + </script></body>`)); + const out = spawnSync(CHROME, [ + "--headless", "--disable-gpu", "--no-sandbox", "--hide-scrollbars", "--window-size=1920,1080", + "--virtual-time-budget=6000", "--dump-dom", `file://${path.join(projDir, "index.html")}?still=3`, + ], { encoding: "utf8", maxBuffer: 1 << 26 }); + assert.equal(out.status, 0, out.stderr); + assert.match(out.stdout, /data-probed="1"/, "the probe ran after the fit"); + const lines = [...out.stdout.matchAll(/<div class="deck-sub[^"]*"([^>]*)>/g)].map((x) => x[1]).filter((a) => /data-holds/.test(a)); + assert.equal(lines.length, 2); + for (const a of lines) assert.match(a, /data-holds="true"/, "the line holds what it draws"); + assert.ok(lines.some((a) => /data-whole-held="false"/.test(a)), "the column is too narrow for the whole words somewhere"); + const spans = [...out.stdout.matchAll(/<span class="part" data-p="status"([^>]*)>([^<]*)<\/span>/g)]; + assert.equal(spans.length, 2, "both lines carry a status part"); + for (const [, attrs, text] of spans) { + const full = /data-full="([^"]*)"/.exec(attrs)?.[1]; + assert.ok(full, "the fit ran"); + const hidden = /display: none/.test(attrs); + // Whole words, its short form, or not drawn: never a prefix of either. + assert.ok(hidden || text === full || text === statusShortForm(full), `drawn "${text}" of "${full}"`); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});