// `umtool source-status` (lane source-status): refresh stamps the manifest from the // channels tree's records (read only), else the archive's record; a second refresh // with nothing changed writes nothing; ls prints the stamp. Synthetic channels only. // // Run with: node --test umtool/lib/report/sourceStatusCli.test.mjs import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-source-status-")); process.env.REPORTS_DIR = path.join(ROOT, "reports"); process.env.CHANNELS_DIR = path.join(ROOT, "channels"); process.env.CHANNELS_FALLBACK = "1"; const { sourceStatusCommand } = await import("./sourceStatusCli.mjs"); const { setUndoEveryMs } = await import("./manifest.mjs"); setUndoEveryMs(0); test.after(() => rm(ROOT, { recursive: true, force: true })); const sec = (iso) => Date.parse(iso) / 1000; const REPORTS = path.join(ROOT, "reports"); const CHANNELS = path.join(ROOT, "channels"); async function video(slug, id, files) { const dir = path.join(CHANNELS, slug, "data", id); await mkdir(dir, { recursive: true }); for (const [name, body] of Object.entries(files)) await writeFile(path.join(dir, name), JSON.stringify(body)); } async function project(id, timeline) { const dir = path.join(REPORTS, id); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: id, title: "Synthetic cut", provenance: { siteOrigin: "https://archive.example.test", channelSlug: "synth-channel" }, render: { fps: 30, transition: 0 }, timeline, }, null, 2) + "\n"); return dir; } const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); const run = async (args, opts = {}) => { const out = []; const err = []; const code = await sourceStatusCommand(args, { root: REPORTS, out: (s) => out.push(s), err: (s) => err.push(s), ...opts }); return { code, out: out.join("\n"), err: err.join("\n") }; }; await video("synth-channel", "synthvid001", { "availability.json": { checkedAt: "2031-03-01T20:00:00Z", checkedBy: "fetch", availability: "members_only", history: [ { availability: "public", observedAt: "2031-03-01T10:30:00Z", source: "backfill" }, { availability: "members_only", observedAt: "2031-03-01T20:00:00Z", source: "fetch" }, ], }, "metadata.info.json": { availability: "public", live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, }); await video("synth-channel", "synthvid002", { "metadata.info.json": { availability: "public", live_status: "was_live" } }); test("refresh stamps the corpus's reading and the archive's; a second refresh writes nothing; ls prints it", async () => { const dir = await project("ss1", [ { type: "clip", id: "c01", video: "synthvid001", start: 1, end: 3, cite: 1 }, { type: "clip", id: "c02", video: "synthvid002", start: 4, end: 6, cite: 4 }, { type: "clip", id: "c03", video: "synthvid003", start: 1, end: 2, cite: 1 }, ]); const asked = []; const archive = async ({ channel, video }) => { asked.push(`${channel}/${video}`); return { id: video, state: "private", stateSince: "20310305", archiveGeneratedAt: "2031-03-06T00:00:00Z" }; }; const r = await run(["ss1", "refresh", "--json"], { archive, now: () => Date.parse("2031-03-07T00:00:00Z") }); assert.equal(r.code, 0, r.err); const res = JSON.parse(r.out); assert.equal(res.written, true); // Only the source no local tree holds is asked of the archive. assert.deepEqual(asked, ["synth-channel/synthvid003"]); const m = await read(dir); assert.equal(m.sourceStatus.refreshedAt, "2031-03-07T00:00:00.000Z"); const s1 = m.sourceStatus.sources["synth-channel/synthvid001"]; assert.deepEqual([s1.now, s1.first, s1.firstWhen, s1.from], ["members_only", "public", "live", "corpus"]); const s2 = m.sourceStatus.sources["synth-channel/synthvid002"]; assert.deepEqual(s2, { evidence: [], from: "corpus", recordsAt: s2.recordsAt }, "no availability record: no state, never 'gone' -- and no null keys (a take's manifest has none)"); const s3 = m.sourceStatus.sources["synth-channel/synthvid003"]; assert.deepEqual([s3.now, s3.since, s3.asOf, s3.from], ["private", "2031-03-05T00:00:00.000Z", "2031-03-06T00:00:00Z", "archive"]); assert.ok(!("first" in s3) && !("firstAt" in s3) && !("firstWhen" in s3), "a null first state is left out, not written null"); const undo = (await readdir(path.join(dir, "revisions")).catch(() => [])).filter((f) => f.includes("auto-before-source-status")); assert.equal(undo.length, 1, "one undo point"); const before = (await stat(path.join(dir, "video.manifest.json"))).mtimeMs; const again = await run(["ss1", "refresh", "--json"], { archive, now: () => Date.parse("2031-03-08T00:00:00Z") }); assert.equal(JSON.parse(again.out).written, false); assert.equal((await stat(path.join(dir, "video.manifest.json"))).mtimeMs, before, "nothing changed: nothing written"); const ls = await run(["ss1", "ls"], { now: () => Date.parse("2031-03-08T00:00:00Z") }); assert.equal(ls.code, 0); assert.match(ls.out, /synth-channel\/synthvid001\s+members_only as of 2031-03-01\s+now members-only \(public when streamed\)/); assert.match(ls.out, /synth-channel\/synthvid003\s+private as of 2031-03-06\s+now private/); assert.match(ls.out, /deck\.subtitle\.status off/); }); test("a dry run writes nothing; with no archive a source no tree holds is unresolved, not gone", async () => { const dir = await project("ss2", [{ type: "clip", id: "c01", video: "synthvid009", start: 1, end: 3, cite: 1 }]); const r = await run(["ss2", "refresh", "--json", "--dry-run"], { archive: null }); assert.equal(r.code, 0, r.err); const res = JSON.parse(r.out); assert.equal(res.written, false); assert.equal(res.unresolved[0].key, "synth-channel/synthvid009"); assert.equal((await read(dir)).sourceStatus, undefined); }); test("usage: no project, an unknown verb or flag", async () => { assert.equal((await run([])).code, 2); assert.equal((await run(["ss1", "wat"])).code, 2); assert.equal((await run(["ss1", "refresh", "--force"])).code, 2); }); test("check's staleness: off says nothing; on says never refreshed, then current, then records written since", async () => { const { sourceStatusStaleness } = await import("./sourceStatusCli.mjs"); const dir = await project("ss3", [{ type: "clip", id: "c01", video: "synthvid001", start: 1, end: 3, cite: 1 }]); const now = Date.parse("2031-03-05T00:00:00Z"); assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null, "the deck does not draw it"); const m = await read(dir); m.render.chrome = { deck: { subtitle: { status: "end" } } }; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); assert.match(await sourceStatusStaleness(dir, await read(dir), { now }), /has not been run/); const r = await run(["ss3", "refresh"], { archive: null, now: () => Date.now() + 60_000 }); assert.equal(r.code, 0, r.err); assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null); assert.match(await sourceStatusStaleness(dir, await read(dir), { now: Date.parse("2031-03-30T00:00:00Z") }), /older than 14 days/); // A record written after the reading the entry holds (its recordsAt moved into the past). const back = await read(dir); back.sourceStatus.sources["synth-channel/synthvid001"].recordsAt = "2000-01-01T00:00:00.000Z"; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(back, null, 2) + "\n"); assert.match(await sourceStatusStaleness(dir, await read(dir), { now }), /records written since their reading: synth-channel\/synthvid001/); }); // REVIEW 1, finding 7a: a metadata refresh that changes no evidence still rewrites a record. The // stamp keeps each source's newest record write (`recordsAt`): refresh writes the newer one, and // check is quiet again -- not stale forever. test("check's staleness clears after a refresh that found nothing new", async () => { const { sourceStatusStaleness } = await import("./sourceStatusCli.mjs"); await video("synth-channel", "synthvid020", { "availability.json": { checkedAt: "2031-03-04T00:00:00Z", checkedBy: "fetch", availability: "private", history: [{ availability: "private", observedAt: "2031-03-04T00:00:00Z", source: "fetch" }] }, "metadata.info.json": { availability: "public", live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, }); const dir = await project("ss7", [{ type: "clip", id: "c01", video: "synthvid020", start: 1, end: 3, cite: 1 }]); const m = await read(dir); m.render.chrome = { deck: { subtitle: { status: "end" } } }; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); const now = Date.parse("2031-03-05T00:00:00Z"); assert.equal((await run(["ss7", "refresh"], { archive: null })).code, 0); assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null); // The same metadata written again, a little later (a refresh that changed nothing it reads). const meta = path.join(CHANNELS, "synth-channel", "data", "synthvid020", "metadata.info.json"); const { utimes } = await import("node:fs/promises"); const later = new Date(Date.now() + 5_000); await utimes(meta, later, later); assert.match(await sourceStatusStaleness(dir, await read(dir), { now }), /records written since their reading/); const r = await run(["ss7", "refresh", "--json"], { archive: null }); assert.equal(JSON.parse(r.out).written, true, "the newer records time is written"); assert.equal(await sourceStatusStaleness(dir, await read(dir), { now }), null, "and check is quiet again"); const s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid020"]; assert.deepEqual([s.now, s.first, s.firstWhen], ["private", "public", "live"], "the reading itself unchanged"); }); // REVIEW 1, finding 4a: a source this refresh cannot read keeps what the last one knew. test("an unresolved source keeps its last entry; nothing read and nothing stamped writes nothing", async () => { const dir = await project("ss4", [{ type: "clip", id: "c01", video: "synthvid030", start: 1, end: 3, cite: 1 }]); const ok = async () => ({ state: "private", stateSince: "20310305", archiveGeneratedAt: "2031-03-06T00:00:00Z" }); const down = async () => { throw new Error("GET https://archive.example.test/corpus.json -> 503"); }; const first = await run(["ss4", "refresh", "--json"], { archive: down }); assert.equal(JSON.parse(first.out).written, false, "no {} stamp for a refresh that read nothing"); assert.equal((await read(dir)).sourceStatus, undefined); assert.equal(JSON.parse((await run(["ss4", "refresh", "--json"], { archive: ok })).out).written, true); const before = (await read(dir)).sourceStatus; const again = JSON.parse((await run(["ss4", "refresh", "--json"], { archive: down })).out); assert.equal(again.written, false); assert.equal(again.unresolved[0].key, "synth-channel/synthvid030"); assert.deepEqual((await read(dir)).sourceStatus, before, "the last reading stands"); }); // REVIEW 1, finding 4b: a project stamped on the corpus machine, refreshed where there is none. test("mergeSourceEntry: never an older reading; corpus and archive agreeing keep the corpus's first state; disagreeing with no order, nothing", async () => { const { mergeSourceEntry, mergeSourceStatus } = await import("./sourceStatusCli.mjs"); const corpus = { now: "members_only", since: "2031-03-01T20:00:00Z", asOf: "2031-03-01T20:00:00Z", first: "public", firstAt: "2031-03-01T10:05:00Z", firstWhen: "live", from: "corpus", evidence: [{ kind: "metadata", counts: true }], recordsAt: "2031-03-01T20:00:00.000Z" }; const archive = (now, asOf) => ({ now, since: null, asOf, first: null, firstAt: null, firstWhen: null, from: "archive", evidence: [] }); // Agree, the archive newer: the corpus's first state and evidence, as of the archive's build. const agree = mergeSourceEntry(corpus, archive("members_only", "2031-03-06T00:00:00Z")); assert.deepEqual([agree.now, agree.first, agree.firstWhen, agree.from, agree.asOf], ["members_only", "public", "live", "corpus", "2031-03-06T00:00:00Z"]); // Disagree, the archive's build newer than the corpus's reading: which is newer is not known -- nothing. const unknown = mergeSourceEntry(corpus, archive("public", "2031-03-06T00:00:00Z")); assert.deepEqual([unknown.now, unknown.first], [null, null]); assert.ok(unknown.evidence.some((e) => e.kind === "disagree")); // Disagree, the corpus's reading later than the archive's build: the corpus. assert.equal(mergeSourceEntry(corpus, archive("private", "2031-02-01T00:00:00Z")), corpus); // The same reader, an older reading: the newer stands. const older = { ...corpus, now: "private", asOf: "2031-02-01T00:00:00Z", recordsAt: "2031-03-09T00:00:00.000Z" }; const kept = mergeSourceEntry(corpus, older); assert.deepEqual([kept.now, kept.asOf, kept.recordsAt], ["members_only", "2031-03-01T20:00:00Z", "2031-03-09T00:00:00.000Z"]); // An unresolved source (no fresh reading) keeps its entry; an uncited one is dropped. assert.deepEqual(mergeSourceStatus({ "a/b": corpus, "a/c": corpus }, {}, ["a/b"]), { "a/b": corpus }); }); test("refresh without the corpus keeps what the corpus machine stamped (end to end)", async () => { await video("synth-channel", "synthvid040", { "availability.json": { checkedAt: "2031-03-01T20:00:00Z", checkedBy: "fetch", availability: "members_only", history: [{ availability: "members_only", observedAt: "2031-03-01T20:00:00Z", source: "fetch" }] }, "metadata.info.json": { availability: "public", live_status: "is_live", epoch: sec("2031-03-01T10:05:00Z"), release_timestamp: sec("2031-03-01T10:00:00Z") }, }); const dir = await project("ss5", [{ type: "clip", id: "c01", video: "synthvid040", start: 1, end: 3, cite: 1 }]); assert.equal((await run(["ss5", "refresh"], { archive: null })).code, 0); assert.equal((await read(dir)).sourceStatus.sources["synth-channel/synthvid040"].firstWhen, "live"); // The corpus goes away (another machine): the archive's older build says members-only, then public. const { rename } = await import("node:fs/promises"); const vdir = path.join(CHANNELS, "synth-channel", "data", "synthvid040"); await rename(vdir, `${vdir}.away`); try { await run(["ss5", "refresh"], { archive: async () => ({ state: "members_only", archiveGeneratedAt: "2031-02-20T00:00:00Z" }) }); let s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid040"]; assert.deepEqual([s.now, s.first, s.firstWhen, s.from, s.asOf], ["members_only", "public", "live", "corpus", "2031-03-01T20:00:00Z"], "an older archive build adds nothing"); await run(["ss5", "refresh"], { archive: async () => ({ archiveGeneratedAt: "2031-03-10T00:00:00Z" }) }); s = (await read(dir)).sourceStatus.sources["synth-channel/synthvid040"]; assert.deepEqual([s.now ?? null, s.first ?? null, "now" in s], [null, null, false], "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, undefined, "no state: the key left out (reads as 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); }); // LANE source-status-nulls: a take lays the manifest over its look preset AS A MERGE PATCH // (presets.mjs resolvePresetLayers), which drops every null, so refresh writes none -- and a // stamp written before that, with explicit nulls, keeps working and is not rewritten for them. test("a no-record entry is written without null keys; one written with them reads the same and is not rewritten", async () => { const { sourceStatusRows, sourceStatusStaleness } = await import("./sourceStatusCli.mjs"); const dir = await project("ssn1", [{ type: "clip", id: "c01", video: "synthvid002", start: 1, end: 3, cite: 1 }]); const m0 = await read(dir); m0.render.chrome = { deck: { subtitle: { status: "end" } } }; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m0, null, 2) + "\n"); assert.equal(JSON.parse((await run(["ssn1", "refresh", "--json"], { archive: null })).out).written, true); const key = "synth-channel/synthvid002"; const compact = (await read(dir)).sourceStatus.sources[key]; assert.deepEqual(Object.keys(compact), ["evidence", "from", "recordsAt"], "an entry (it was read), its nulls left out"); // The same entry as the stamp held it before this lane: every nullable field an explicit null. const m = await read(dir); m.sourceStatus.sources[key] = { now: null, since: null, asOf: null, first: null, firstAt: null, firstWhen: null, evidence: [], from: "corpus", recordsAt: compact.recordsAt }; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); const before = (await stat(path.join(dir, "video.manifest.json"))).mtimeMs; const again = JSON.parse((await run(["ssn1", "refresh", "--json"], { archive: null })).out); assert.deepEqual([again.changed, again.written], [false, false], "explicit nulls are not a change"); assert.equal((await stat(path.join(dir, "video.manifest.json"))).mtimeMs, before); // Both shapes read the same: ls, the rows, check's staleness. const now = Date.now(); for (const entry of [compact, m.sourceStatus.sources[key]]) { const mm = { ...m, sourceStatus: { ...m.sourceStatus, sources: { [key]: entry } } }; const [row] = sourceStatusRows(mm, { now }); assert.deepEqual([row.stamped, row.now, row.asOf, row.first, row.firstWhen, row.words, row.stale], [true, null, null, null, null, "", false]); assert.equal(await sourceStatusStaleness(dir, mm, { now }), null); } assert.match((await run(["ssn1", "ls"])).out, /synth-channel\/synthvid002\s+no record\s+—/); }); test("mergeSourceEntry: an absent now is null -- a no-record corpus entry and an archive's null agree; the stamp is compacted", async () => { const { compactSourceEntry, mergeSourceEntry, mergeSourceStatus, sameSources } = await import("./sourceStatusCli.mjs"); const noRecord = { evidence: [], from: "corpus", recordsAt: "2031-03-01T00:00:00.000Z" }; const archiveNull = { now: null, since: null, asOf: "2031-03-06T00:00:00Z", first: null, firstAt: null, firstWhen: null, from: "archive", evidence: [{ kind: "archive", availability: "deleted", counts: false }] }; for (const [p, f] of [[noRecord, archiveNull], [archiveNull, noRecord]]) { const merged = mergeSourceEntry(p, f); assert.equal(merged.from, "corpus", "agreeing: the corpus's entry"); assert.ok(!merged.evidence.some((e) => e.kind === "disagree"), "not a disagreement"); assert.equal(merged.asOf, "2031-03-06T00:00:00Z"); } const out = mergeSourceStatus({}, { "a/b": { ...archiveNull } }, ["a/b"]); assert.deepEqual(Object.keys(out["a/b"]), ["asOf", "from", "evidence"]); assert.deepEqual(compactSourceEntry({ now: "private", since: null, recordsAt: null, x: null }), { now: "private", recordsAt: null, x: null }, "only the nullable fields"); assert.ok(sameSources({ "a/b": archiveNull }, out)); assert.ok(!sameSources({ "a/b": archiveNull }, { "a/b": { ...out["a/b"], now: "private" } })); });