commit 5b981d45d20a00f18ded8f1a7d488d263cbac056
parent 89e108f7f0094ecefca837d14d23d0119fe40943
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 20 Nov 2026 15:16:39 -0500
source-status: the line never says more than the records do (review 1)
A source line that says "now deleted" or "now private (public when streamed)"
must be true. Where the records disagree or are missing it now draws nothing.
common lib/sourceStatus.mjs:
- "deleted" only when the channel's Check availability wrote it; a download's
class (any bare "Video unavailable") gives no state.
- A public or unlisted first-hand reading newer than the private one (the
metadata a later persist rewrote, a check or fetch, a cookieless download)
gives no state, "records disagree".
- Kept to availability-server.ts's reading: an unparseable time lets the
record win, an outcome must have coerceDownloadOutcome's shape.
- A check's "public" is evidence only when the video's metadata shows its
extractor reports the field.
umtool source-status refresh:
- Merges into the last stamp. An unresolved source keeps its entry and an
older reading never replaces a newer one. A corpus and an archive reading
that disagree with no provable order draw nothing. A refresh that read
nothing writes no empty stamp.
- The archive's index is re-read (createCueSource refreshIndex) with a 20 s
timeout. A record with no state is public only without the legacy flags,
and the archive's "deleted" or an unknown state gives no state.
- The manifest token is taken with the read.
Each corpus entry keeps recordsAt, so check's "records written since" clears
after a refresh that found nothing new. A source with no record at all is not
listed, and the notes and check name the same sources.
The page never draws a cut status (status-fit.mjs). It tries the whole words,
then the short form, then lets the channel give way, then leaves it out, on
the deck and on the finale's rows and caption. Only a page that has a status
carries this, so every other page is still main's byte for byte. New pinned
tests cover parts auto, lines 2, the finale page and measureChromeSchedule.
An explicit `status: "off"` wins over `status` in parts. A stamp's `now` must
be a known state ("constructor" draws nothing).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
17 files changed, 1184 insertions(+), 121 deletions(-)
diff --git a/common/lib/sourceStatus-server.mjs b/common/lib/sourceStatus-server.mjs
@@ -6,18 +6,19 @@
//
// SERVER-ONLY (node:fs). Plain JS: umtool's bins run under bare node.
-import { readFile } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { deriveSourceStatus } from "./sourceStatus.mjs";
-const FILES = {
+/** 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 {
@@ -30,7 +31,7 @@ async function readJson(file) {
/** 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))]),
+ 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.
@@ -51,3 +52,19 @@ export async function readSourceRecords(videoDir) {
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
@@ -8,19 +8,44 @@
//
// 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.
+// 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.
-// check / fetch an availability.json history entry of "public" written by a
-// real probe or a one-video fetch.
+// 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
@@ -31,6 +56,8 @@
// 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.
@@ -41,7 +68,18 @@
/** 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"]);
+/** 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) => {
@@ -49,18 +87,35 @@ const msOf = (iso) => {
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) && AVAILABILITIES.has(rec.availability) && typeof rec.checkedAt === "string" ? rec : null;
+ return isObj(rec) && AVAILABLE.has(rec.availability) && typeof rec.checkedAt === "string" ? rec : null;
}
-/** download-outcome.json's last attempt's class, as loadDownloadOutcomeAvailability reads it. */
+/** 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) {
- 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 };
+ 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) {
@@ -114,18 +169,35 @@ function liveSpan(metadata, liveRecording) {
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, since: string|null, asOf: string|null, first: "public"|null, firstAt: string|null,
+ * @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 out = outcomeOf(outcome);
- const fromOutcome = out && (!explicit || (out.finishedAt !== null && msOf(out.finishedAt) > msOf(explicit.checkedAt)));
+ 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;
@@ -144,18 +216,66 @@ export function deriveSourceStatus({ availability = null, outcome = null, metada
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 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 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);
- if (h.source === "check" || h.source === "fetch") {
- evidence.push({ kind: h.source, at: h.observedAt ?? null, availability: "public", live: inLive(ms), counts: true });
+ 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: h.observedAt ?? null, availability: "public", counts: false,
+ evidence.push({ kind: h.source ?? "backfill", at, availability: "public", counts: false,
why: "a copy of the metadata's field (a missing field reads public)" });
}
}
@@ -163,8 +283,8 @@ export function deriveSourceStatus({ availability = null, outcome = null, metada
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,
+ if (cookielessSuccess(outRec)) {
+ evidence.push({ kind: "download", at: outRec.finishedAt, counts: false,
why: "downloaded without cookies: public or unlisted" });
}
diff --git a/common/lib/sourceStatus.test.ts b/common/lib/sourceStatus.test.ts
@@ -22,6 +22,9 @@ const LIVE_META = {
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", () => {
@@ -96,7 +99,7 @@ test("NOT EVIDENCE: a live recording alone (it may have been made with a member'
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 }] },
+ 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);
@@ -123,16 +126,21 @@ test("the metadata's earlier state is rebuilt from metadata.history.json", () =>
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'", () => {
+test("a check of public outside the live is 'other'; a removal a check read is 'deleted'", () => {
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 },
+ 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?.first, s?.firstWhen], ["deleted", "2031-03-20T00:00:00Z", "public", "other"]);
+ 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'", () => {
+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",
@@ -141,9 +149,109 @@ test("a check of public inside the stream's span is 'live'", () => {
{ availability: "private", observedAt: "2031-03-02T00:00:00Z", source: "check" },
],
},
- metadata: { release_timestamp: sec("2031-03-01T10:00:00Z"), duration: 14400 },
+ // 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.deepEqual([s?.first, s?.firstWhen], ["public", "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", () => {
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -121,7 +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)) |
+| `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}` |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -198,13 +198,24 @@ source line says so: `Synth Channel · Mar 1, 2031 · 35:00 · now members-only
| 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. "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 live recording
-(it may have used a member's cookies), a download without cookies (public or unlisted).
+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 |
|---|---|---|
@@ -214,14 +225,20 @@ the stream's span. NOT evidence: a backfill's `public` alone (it reads a missing
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`; the archive does not publish the first state, so no parenthesis). It writes the stamp, one undo
-point, only when a status 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, never a refusal.
+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 live preview and Present. Not yet: the stacked vertical deck, the
+(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
@@ -3005,7 +3022,7 @@ The source line under each clip's title, in the deck. The automatic line is set
| `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) -- `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. 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.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
@@ -1017,7 +1017,7 @@ export const GROUPS = [
],
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))"],
+ "**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))"],
],
},
{
diff --git a/umtool/lib/report/sourceStatusCli.mjs b/umtool/lib/report/sourceStatusCli.mjs
@@ -13,17 +13,21 @@
// 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.
+// 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 { readSourceStatus } from "yt-dlp-transcript-common/lib/sourceStatus-server.mjs";
+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, subtitleStatusOn,
+ 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";
@@ -39,13 +43,30 @@ export const SOURCE_STATUS_USAGE = [
" 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.",
+ " 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);
-/** 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 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);
@@ -73,9 +94,13 @@ export async function collectSourceStatus({ manifest, layers, archive = null })
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: [] };
+ 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) {
@@ -84,14 +109,15 @@ export async function collectSourceStatus({ manifest, layers, archive = null })
}
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";
+ const read = archiveReading(r);
+ const asOf = typeof r?.archiveGeneratedAt === "string" && Number.isFinite(Date.parse(r.archiveGeneratedAt)) ? r.archiveGeneratedAt : null;
sources[w.key] = {
- now,
- since: now === "public" ? null : dayIso(r?.stateSince),
- asOf: typeof r?.archiveGeneratedAt === "string" ? r.archiveGeneratedAt : null,
+ 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: [],
+ 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) });
@@ -100,15 +126,89 @@ export async function collectSourceStatus({ manifest, layers, archive = null })
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);
-/** The archive reader for a project: the cue source's published record, cached (cues.mjs). Lazy: only when asked. */
-async function archiveReaderFor(manifest) {
+/** 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" });
+ 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 });
}
@@ -123,15 +223,14 @@ export function statusOnFor(manifest) {
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.
+ * 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
@@ -141,23 +240,20 @@ export async function sourceStatusStaleness(dir, manifest, { now = Date.now(), l
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)) {
+ 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)) {
- if (stamp.sources[w.key]?.from !== "corpus") continue;
+ 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;
- for (const name of WATCHED) {
- const st = await stat(`${vdir}/${name}`).catch(() => null);
- if (st && st.mtimeMs > since) {
- moved.push(w.key);
- break;
- }
- }
+ 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 the stamp (${stamp.refreshedAt.slice(0, 10)}): ${moved.join(", ")}`);
+ if (moved.length) notes.push(`records written since their reading: ${moved.join(", ")}`);
}
return notes.length ? notes.join("; ") : null;
}
@@ -179,7 +275,8 @@ export function sourceStatusRows(manifest, { now = Date.now() } = {}) {
first: s?.first ?? null,
firstWhen: s?.firstWhen ?? null,
from: s?.from ?? null,
- stale: !s || !Number.isFinite(at) || now - at > limit,
+ // 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)),
};
});
}
@@ -215,6 +312,8 @@ export async function sourceStatusCommand(args, { root = REPORTS_ROOT, out = (s)
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);
@@ -237,13 +336,16 @@ export async function sourceStatusCommand(args, { root = REPORTS_ROOT, out = (s)
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);
+ 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", await manifestToken(project.dir), (mm) => {
+ structuralEdit(project.dir, "source-status", token, (mm) => {
mm.sourceStatus = { refreshedAt, sources };
return { refreshedAt };
}));
diff --git a/umtool/lib/report/sourceStatusCli.test.mjs b/umtool/lib/report/sourceStatusCli.test.mjs
@@ -130,9 +130,176 @@ test("check's staleness: off says nothing; on says never refreshed, then current
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).
+ // A record written after the reading the entry holds (its recordsAt moved into the past).
const back = await read(dir);
- back.sourceStatus.refreshedAt = "2000-01-01T00:00:00.000Z";
+ 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 the stamp \(2000-01-01\): synth-channel\/synthvid001/);
+ 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
@@ -192,14 +192,17 @@ export function deckSubtitleParts(parts, opts = {}, multiChannel = false) {
/**
* 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. Empty (a public
+ * `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 base = !opts.parts || opts.parts === "auto"
? (multiChannel ? ["channel", "title", "date"] : ["title", "date"])
: opts.parts;
- const want = opts.status === "end" && !base.includes("status") ? [...base, "status"] : base;
+ // 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,
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>`)
@@ -706,10 +713,27 @@ export function scheduleHasStatus(schedule) {
/**
* 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.
+ * 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)}; }`;
+ 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("")}`;
}
/**
@@ -765,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;
@@ -1028,7 +1054,7 @@ 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; }${scheduleHasStatus(schedule) ? `
+ .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};
@@ -1195,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
@@ -1221,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";
});
@@ -1262,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, resolveDeck } from "./deck.mjs";
import { finaleClaimsMarkup } from "./chrome-claims.mjs";
-import { mix, rgba, scheduleHasStatus, shapeCss, statusPartCss, 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;
@@ -527,7 +529,7 @@ 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")}${scheduleHasStatus(schedule) ? `
+ ${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}; }
@@ -634,10 +636,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
@@ -212,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();
@@ -254,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 });
@@ -293,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".
@@ -335,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) });
@@ -362,7 +374,7 @@ 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) {
diff --git a/umtool/report-to-video/deck-source-status.test.mjs b/umtool/report-to-video/deck-source-status.test.mjs
@@ -11,12 +11,15 @@ import test from "node:test";
import { deckSubtitleLinesParts, deckSubtitleParts } from "./attribution.mjs";
import { deckHtml, scheduleHasStatus, subtitleMarkup } from "./chrome-deck.mjs";
-import { titleLastParts } from "./chrome-finale.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_WORDS, clipSourceStatus, sourceStatusNotes, sourceStatusText, validateSourceStatus,
+ 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" };
@@ -114,7 +117,8 @@ test("the schedule: each clip's line ends in its status; a public source's line
// 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">now members-only \(public when streamed\)<\/span>/);
+ 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>');
});
@@ -138,6 +142,120 @@ test("BYTE FOR BYTE: the switch off, or on with no stamp, draws main's schedule
}
});
+// 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(" · ");
diff --git a/umtool/report-to-video/modules/subtitle.mjs b/umtool/report-to-video/modules/subtitle.mjs
@@ -41,7 +41,7 @@ export default defineModule({
["`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) -- `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. 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.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/source-status.mjs b/umtool/report-to-video/source-status.mjs
@@ -9,7 +9,11 @@
//
// "sourceStatus": { "refreshedAt": ISO, "sources": { "<channel>/<video>": {
// now, since, asOf, first: "public"|null, firstAt, firstWhen: "live"|"other"|null,
-// from: "corpus"|"archive", evidence: [...] } } }
+// 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
@@ -37,7 +41,16 @@ 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 = {}) {
@@ -48,9 +61,9 @@ export function sourceKeyOf(entry, provenance = {}) {
/** 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];
+ const now = own(SOURCE_STATUS_WORDS.now, s.now);
if (!now) return "";
- const first = s.first === "public" ? SOURCE_STATUS_WORDS.first[s.firstWhen] : null;
+ const first = s.first === "public" ? own(SOURCE_STATUS_WORDS.first, s.firstWhen) : null;
return first ? `${now} (${first})` : now;
}
@@ -66,11 +79,29 @@ export function clipSourceStatus(entry, stamp, provenance = {}) {
return key ? sourceStatusText(stamp.sources[key]) : "";
}
-/** Does the deck's subtitle draw the part (the switch, or `status` named in its parts)? */
+/**
+ * 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 [];
@@ -85,9 +116,11 @@ export function validateSourceStatusStamp(v, where = "sourceStatus") {
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.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;
@@ -116,11 +149,7 @@ export function validateSourceStatus(manifest) {
*/
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))];
+ 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"];
@@ -134,6 +163,9 @@ export function sourceStatusNotes(manifest, { now = Date.now() } = {}) {
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"})`);
}
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 });
+ }
+});