commit 47057dd76a29dc6ed0a2ca9df8b51bf3995787f6
parent 78e92f2ad8da7b9f2506ae3faf93fb6dec3fd589
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 20 Nov 2026 14:00:49 -0500
umtool: source-status stamps what became of each cited source
A clip's source can be privated, deleted or moved behind a membership after it
is clipped. `umtool source-status <p> refresh` reads each cited recording's
records (the project's channels tree, then the corpus, read only; else the
published archive's record) and stamps the manifest's `sourceStatus`, one
write and one undo point, only when a status changed. `ls` prints it.
common lib/sourceStatus.mjs is the one reading: now is the effective
availability; "was public" only on evidence (the metadata's own public field,
rebuilt through metadata.history.json, or a check/fetch observation), "when
streamed" when that evidence was taken during the live. A backfill default, a
live recording and a cookieless download are recorded as not evidence.
`umtool check` lists source-status-stale (open, never blocking) when the deck
draws it and the stamp is missing, older than 14 days, or older than the
records. A cue source's http record carries its archive build time.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
16 files changed, 1008 insertions(+), 2 deletions(-)
diff --git a/common/lib/sourceStatus-server.mjs b/common/lib/sourceStatus-server.mjs
@@ -0,0 +1,53 @@
+// 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 } from "node:fs/promises";
+import path from "node:path";
+
+import { deriveSourceStatus } from "./sourceStatus.mjs";
+
+const FILES = {
+ 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(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));
+}
diff --git a/common/lib/sourceStatus.mjs b/common/lib/sourceStatus.mjs
@@ -0,0 +1,186 @@
+// 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): availability.json's top level, or the
+// download-outcome's last class when that is newer. `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. A removal is only ever recorded by the
+// channel's Check availability; this reads it, never infers it.
+//
+// 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.
+// check / fetch an availability.json history entry of "public" written by a
+// real probe or a one-video fetch.
+//
+// "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.
+// 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"]);
+
+const AVAILABILITIES = new Set(["public", "unlisted", "private", "members_only", "needs_auth", "deleted", "error"]);
+
+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());
+
+/** availability.json as availability-server.ts coerceAvailability accepts it, else null. */
+function explicitOf(rec) {
+ return isObj(rec) && AVAILABILITIES.has(rec.availability) && typeof rec.checkedAt === "string" ? rec : null;
+}
+
+/** download-outcome.json's last attempt's class, as loadDownloadOutcomeAvailability reads it. */
+function outcomeOf(rec) {
+ if (!isObj(rec) || !Array.isArray(rec.attempts)) return null;
+ const cls = rec.attempts.at(-1)?.availabilityClass;
+ if (!AVAILABILITIES.has(cls)) return null;
+ return { availability: cls, finishedAt: typeof rec.finishedAt === "string" ? rec.finishedAt : null };
+}
+
+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 };
+}
+
+/**
+ * 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").
+ *
+ * @param {{ availability?: any, outcome?: any, metadata?: any, metadataHistory?: any, liveRecording?: any }} records
+ * @returns {null | { now: string, 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 out = outcomeOf(outcome);
+ const fromOutcome = out && (!explicit || (out.finishedAt !== null && msOf(out.finishedAt) > msOf(explicit.checkedAt)));
+ 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;
+
+ for (const s of metadataSnapshots(metadata, metadataHistory)) {
+ if (s.availability !== "public") continue;
+ evidence.push({ kind: "metadata", at: s.at, availability: "public", ...(s.liveStatus ? { liveStatus: s.liveStatus } : {}), live: s.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);
+ if (h.source === "check" || h.source === "fetch") {
+ evidence.push({ kind: h.source, at: h.observedAt ?? null, availability: "public", live: inLive(ms), counts: true });
+ } else {
+ evidence.push({ kind: h.source ?? "backfill", at: h.observedAt ?? null, 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 (isObj(outcome) && outcome.status === "ok" && Array.isArray(outcome.attempts) && outcome.attempts.some((a) => a?.usedCookies === false)) {
+ evidence.push({ kind: "download", at: typeof outcome.finishedAt === "string" ? outcome.finishedAt : null, 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,173 @@
+// 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"),
+};
+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: { 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 removal from a newer download outcome; a check of public outside the live is 'other'", () => {
+ 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" }] },
+ outcome: { status: "failed", finishedAt: "2031-03-20T00:00:00Z", attempts: [{ n: 0, availabilityClass: "deleted" }] },
+ metadata: { live_status: "was_live", release_timestamp: sec("2031-03-01T10:00:00Z"), duration: 14400 },
+ });
+ assert.deepEqual([s?.now, s?.asOf, s?.first, s?.firstWhen], ["deleted", "2031-03-20T00:00:00Z", "public", "other"]);
+});
+
+test("a check of public inside the stream's span is 'live'", () => {
+ 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" },
+ ],
+ },
+ metadata: { release_timestamp: sec("2031-03-01T10:00:00Z"), duration: 14400 },
+ });
+ assert.deepEqual([s?.first, s?.firstWhen], ["public", "live"]);
+});
+
+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
@@ -73,6 +73,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/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` — and stamps the manifest's `sourceStatus` (one write, one undo point, only when a status changed); `ls` prints it, a status older than 14 days marked stale. 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/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` — and stamps the manifest's `sourceStatus` (one write, one undo point, only when a status changed); `ls` prints it, a status older than 14 days marked stale. 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/sourceStatusCli.mjs b/umtool/lib/report/sourceStatusCli.mjs
@@ -0,0 +1,269 @@
+// `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). Never a platform. One write to the draft, one undo point,
+// only when a source's status 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 { 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, 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)\".",
+ " One write, one undo point, only when a status changed. ls prints the stamp.",
+].join("\n");
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** The archive's word for a published record's `state` (absent: still public there). */
+const ARCHIVE_STATES = new Set(["members_only", "private", "deleted", "unlisted"]);
+
+/** 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);
+ sources[w.key] = s
+ ? { ...s, from: "corpus" }
+ : { now: null, since: null, asOf: null, first: null, firstAt: null, firstWhen: null, from: "corpus", evidence: [] };
+ 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 now = ARCHIVE_STATES.has(r?.state) ? r.state : "public";
+ sources[w.key] = {
+ now,
+ since: now === "public" ? null : dayIso(r?.stateSince),
+ asOf: typeof r?.archiveGeneratedAt === "string" ? r.archiveGeneratedAt : null,
+ first: null, firstAt: null, firstWhen: null,
+ from: "archive",
+ evidence: [],
+ };
+ } catch (e) {
+ unresolved.push({ key: w.key, why: e instanceof Error ? e.message.split("\n")[0] : String(e) });
+ }
+ }
+ return { sources, unresolved };
+}
+
+/** Two stamps' sources the same (refreshedAt aside)? */
+const sameSources = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+
+/** The archive reader for a project: the cue source's published record, cached (cues.mjs). Lazy: only when asked. */
+async function archiveReaderFor(manifest) {
+ const { createCueSource, siteOriginFromManifest } = await import("umtool-report-to-video/cues");
+ const siteOrigin = siteOriginFromManifest(manifest);
+ if (!siteOrigin) return null;
+ const cues = createCueSource({ siteOrigin, prefer: "http" });
+ 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);
+}
+
+/** The records whose writes make a stamp from the corpus out of date. */
+const WATCHED = ["availability.json", "download-outcome.json", "metadata.info.json", "metadata.history.json"];
+
+/**
+ * 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 since the stamp (by mtime; read only). `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;
+ const since = Date.parse(stamp?.refreshedAt ?? "");
+ if (Number.isFinite(since) && isObj(stamp?.sources)) {
+ const trees = layers ?? channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) });
+ const moved = [];
+ for (const w of manifestSources(manifest)) {
+ if (stamp.sources[w.key]?.from !== "corpus") continue;
+ const vdir = await videoDirIn(trees, w.channel, w.video);
+ if (!vdir) continue;
+ for (const name of WATCHED) {
+ const st = await stat(`${vdir}/${name}`).catch(() => null);
+ if (st && st.mtimeMs > since) {
+ moved.push(w.key);
+ break;
+ }
+ }
+ }
+ if (moved.length) notes.push(`records written since the stamp (${stamp.refreshedAt.slice(0, 10)}): ${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,
+ stale: !s || !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;
+ 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, unresolved } = await collectSourceStatus({ manifest: m, layers, archive: reader });
+ const changed = !sameSources(m.sourceStatus?.sources, 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", await manifestToken(project.dir), (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,138 @@
+// `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 stamp (its refreshedAt moved into the past).
+ const back = await read(dir);
+ back.sourceStatus.refreshedAt = "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 the stamp \(2000-01-01\): synth-channel\/synthvid001/);
+});
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`;
}
@@ -364,7 +368,7 @@ export function createCueSource({
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 +392,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/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,147 @@
+// 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: [...] } } }
+//
+// 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"]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** 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 = SOURCE_STATUS_WORDS.now[s.now];
+ if (!now) return "";
+ const first = s.first === "public" ? 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, or `status` named in its parts)? */
+export function subtitleStatusOn(subtitle) {
+ return subtitle?.status === "end" || (Array.isArray(subtitle?.parts) && subtitle.parts.includes("status"));
+}
+
+/** 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 && typeof s.now !== "string") errors.push(`${where}.sources["${k}"].now must be a state 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"`);
+ }
+ }
+ 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 provenance = manifest?.provenance ?? {};
+ const keys = [...new Set((manifest?.timeline ?? [])
+ .filter((e) => e?.type === "clip" && e.src == null && e.sourceStatus !== false)
+ .map((e) => sourceKeyOf(e, provenance))
+ .filter(Boolean))];
+ 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;
+ }
+ 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;
+}