commit 0c812a0134331c300af8f3d728acfe0ca175b1e8
parent aeed4f9dc17797963a3deb90ea4fda63c74dd85e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 10 Oct 2026 16:28:59 -0400
Merge r24/hygiene H1–H4 (c4108062: departed-channel tombstones, temp-dir test robustness, persist keeps provenance, mix.spec) into r24/integration
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
26 files changed, 1535 insertions(+), 55 deletions(-)
diff --git a/PUBLISH.md b/PUBLISH.md
@@ -449,6 +449,20 @@ manifest — a channel only private sites carry is never named on the hub. `_hea
serves them `Cache-Control: no-store`. **The hub's deploy reads each tombstone back**,
plain and busted, into its live check.
+**Tombstones for a channel that leaves a site.** A channel removed from a site's
+`channels`, or moved to its `citedChannels`, is withdrawn the same way. The record of
+what the site published is its last bundle, `export/.export-builds/<site>/out`, read by
+compose before the build replaces it: every `transcripts/`, `subs/`, `posts/` or
+`digests/<slug>/` tree it served that the new compose does not ship is written as a
+tombstone, path for path — the tree's manifest at `pageCount: 0` and `[]` for each page
+the bundle held — and served no-store. A bundle's tombstones are served paths too, so
+they are carried build to build while the channel stays out; a channel back in the pool
+gets its real trees again. A cited-only channel's moment pages and clips still publish
+and are never tombstoned. A site's deploy probes its tombstones like the hub's (each
+tree its `_headers` declares withdrawn). The hub carries the tombstones its own last
+bundle shipped while a non-private site's pool still holds the channel, and names no
+other. A docker-runner build sees no last bundle in its container, so it writes none.
+
## The source mirror (homepage)
The homepage carries the project's own source, read-only, as static files:
diff --git a/common/bin/compose-hub.test.ts b/common/bin/compose-hub.test.ts
@@ -46,6 +46,9 @@ function fixturePaths(root: string): Paths {
// The hub's tombstones read the shared posts tree (release 18): this
// fixture's own, never the checkout's.
exportSharedPostsDir: path.join(root, ".export-index", "shared", "posts"),
+ // The hub's last bundle (release 24 H1 carries its tombstones): this
+ // fixture's own, never the checkout's.
+ exportBuildsDir: path.join(root, ".export-builds"),
};
}
@@ -376,3 +379,94 @@ test("while X posts are private, the hub ships tombstones for every X channel, s
rmSync(root, { recursive: true, force: true });
}
});
+
+// Release 24 H1: a channel the hub's LAST BUNDLE tombstoned keeps its
+// tombstone once it is no longer withdrawn — while the hub may still name it
+// (a non-private site's pool holds it). One that left every such pool (moved
+// to a public site's cited scope, kept only by a private site, or on no site)
+// is never named, carried or not; nor is a tree that is not posts.
+test("the hub carries its last bundle's tombstones while it may name the channel, and never names one it may not", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "compose-hub-"));
+ const log = console.log;
+ try {
+ const paths = fixturePaths(root);
+ const pub = paths.exportPublicDir;
+ const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value));
+ };
+ const STILL = "still-pooled-x";
+ const CITED = "now-cited-x";
+ const PRIV = "now-private-x";
+ const NONE = "now-nowhere-x";
+ for (const slug of [STILL, CITED, PRIV, NONE]) {
+ writeJson(path.join(paths.channelsDir, slug, "config.json"), {
+ handling: "youtube",
+ url: `https://x.com/${slug}`,
+ sourceKind: "social",
+ platform: "twitter",
+ });
+ }
+ const site = (siteId: string, slugs: string[], extra: Record<string, unknown> = {}) =>
+ writeJson(path.join(paths.sitesDir, siteId, "site.json"), {
+ siteId,
+ siteTitle: siteId,
+ channels: slugs.map((slug) => ({ slug, groupId: "default" })),
+ ...extra,
+ });
+ site("pub", [STILL], { citedChannels: [{ slug: CITED }] });
+ site("mine", [PRIV], { audience: "private" });
+ // The hub's last bundle: the four channels' posts tombstones (all were on
+ // a public site's pool then), and a stray transcripts tree.
+ const bundle = path.join(paths.exportBuildsDir, "_hub", "out");
+ writeJson(path.join(bundle, "hub-sites.json"), []);
+ writeJson(path.join(bundle, "posts", "manifest.json"), { channels: [], totalCount: 0 });
+ for (const slug of [STILL, CITED, PRIV, NONE]) {
+ writeJson(path.join(bundle, "posts", slug, "manifest.json"), { pageCount: 0, slugToPage: {} });
+ writeJson(path.join(bundle, "posts", slug, "page-0000.json"), []);
+ writeJson(path.join(bundle, "posts", slug, "page-0001.json"), []);
+ }
+ writeJson(path.join(bundle, "transcripts", STILL, "manifest.json"), { pageCount: 0, slugToPage: {} });
+
+ // X posts public: nothing is withdrawn, and only STILL is carried.
+ console.log = () => {};
+ await main({ paths, settings: {} });
+ console.log = log;
+ assert.deepEqual(readdirSync(path.join(pub, "posts")).sort(), ["manifest.json", STILL]);
+ assert.deepEqual(readdirSync(path.join(pub, "posts", STILL)).sort(), [
+ "manifest.json",
+ "page-0000.json",
+ "page-0001.json",
+ ]);
+ assert.deepEqual(JSON.parse(readFileSync(path.join(pub, "posts", "manifest.json"), "utf8")).channels, []);
+ assert.ok(!existsSync(path.join(pub, "transcripts")), "the hub carries posts tombstones only");
+ for (const hidden of [CITED, PRIV, NONE]) {
+ const named = readdirSync(pub, { recursive: true, withFileTypes: true })
+ .filter((e) => e.isFile())
+ .filter(
+ (e) =>
+ e.name.includes(hidden) ||
+ e.parentPath.includes(hidden) ||
+ readFileSync(path.join(e.parentPath, e.name), "utf8").includes(hidden),
+ );
+ assert.deepEqual(named.map((e) => e.name), [], `${hidden} is named in the hub's public/`);
+ }
+ assert.ok(
+ readFileSync(path.join(pub, "_headers"), "utf8").endsWith(
+ "# Withdrawn content (tombstones): never stored at the edge.\n" +
+ "/posts/*\n Cache-Control: no-store\n Access-Control-Allow-Origin: *\n",
+ ),
+ );
+ assert.equal(builtHubProblem(pub), null);
+
+ // No last bundle, X public: no posts/ at all, as before.
+ rmSync(bundle, { recursive: true, force: true });
+ console.log = () => {};
+ await main({ paths, settings: {} });
+ console.log = log;
+ assert.ok(!existsSync(path.join(pub, "posts")));
+ } finally {
+ console.log = log;
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/bin/compose-hub.ts b/common/bin/compose-hub.ts
@@ -18,7 +18,10 @@
// channel with a shared posts tree that a
// non-private site carries, its manifest at
// pageCount 0 and `[]` pages
-// (publish/tombstones.ts), served no-store
+// (publish/tombstones.ts), served no-store —
+// and each one the last hub bundle shipped,
+// while a non-private site's pool holds it
+// (release 24 H1)
//
// and REMOVES every per-site entry a site's compose left in public/
// (SITE_ONLY_PUBLIC_ENTRIES below): the hub holds no site's data.
@@ -47,11 +50,17 @@ import { readGlobalAliases } from "../lib/aliasesStore";
import { getSettings } from "../lib/settings";
import {
emptyPostsManifest,
+ hubNameableChannels,
+ lastBundleDir,
+ servedChannelTrees,
tombstoneNoStoreForHub,
withdrawnXChannels,
+ writeDepartedTombstones,
writePostsTombstones,
+ type ChannelTreeTombstone,
type PostsTombstone,
} from "../publish/tombstones";
+import { HUB_TARGET } from "../publish/stamps";
import { runIfEntryPoint } from "./_cli";
import { writePublicFile } from "./_publicFile";
@@ -134,24 +143,38 @@ export const SITE_ONLY_PUBLIC_ENTRIES: readonly string[] = [
// now — all served no-store. A channel only private sites (or no site) carry is
// never named here: private data is never named on the hub. With X
// posts public, or no X channel, the hub ships no posts/ at all, as before.
+//
+// RELEASE 24 H1: a channel the hub's LAST BUNDLE served (its tombstones are
+// the only channel paths a hub bundle holds — builtHubProblem) keeps its
+// tombstone after it stops being withdrawn (X posts public again, or no
+// longer an X channel), for as long as the hub may name it: a member of a
+// non-private site's pool (hubNameableChannels). A channel that left every
+// such pool — moved to a site's cited scope, kept only by private sites, or
+// on no site — is never named here, carried or not.
async function composeHubTombstones(
paths: Paths,
publicDir: string,
settings: { social?: { x?: { visibility?: unknown } } },
-): Promise<PostsTombstone[]> {
- const slugs = await withdrawnXChannels(paths, settings, listSites(paths));
- if (slugs.length === 0) return [];
+): Promise<{ withdrawn: PostsTombstone[]; carried: ChannelTreeTombstone[] }> {
+ const sites = listSites(paths);
+ const slugs = await withdrawnXChannels(paths, settings, sites);
+ const nameable = hubNameableChannels(sites);
+ const served = (await servedChannelTrees(lastBundleDir(paths, HUB_TARGET))).filter(
+ (t) => t.tree === "posts" && nameable.has(t.slug) && !slugs.includes(t.slug),
+ );
+ if (slugs.length === 0 && served.length === 0) return { withdrawn: [], carried: [] };
const postsDir = path.join(publicDir, "posts");
- const tombstones = await writePostsTombstones({
+ const withdrawn = await writePostsTombstones({
postsDir,
sharedPostsDir: paths.exportSharedPostsDir,
slugs,
});
+ const carried = await writeDepartedTombstones({ publicDir, served });
await writePublicFile(
path.join(postsDir, "manifest.json"),
JSON.stringify(emptyPostsManifest(new Date().toISOString())),
);
- return tombstones;
+ return { withdrawn, carried };
}
export async function main(
@@ -163,7 +186,17 @@ export async function main(
for (const entry of SITE_ONLY_PUBLIC_ENTRIES) {
await rm(path.join(publicDir, entry), { recursive: true, force: true });
}
- const tombstones = await composeHubTombstones(paths, publicDir, opts.settings ?? getSettings());
+ const { withdrawn, carried } = await composeHubTombstones(
+ paths,
+ publicDir,
+ opts.settings ?? getSettings(),
+ );
+ // tombstoneNoStoreForHub asks only whether there is any: the hub's whole
+ // posts tree is served no-store.
+ const tombstones: PostsTombstone[] = [
+ ...withdrawn,
+ ...carried.map((t) => ({ slug: t.slug, pages: t.pages })),
+ ];
// The hub's own alias dictionary is the global one (no site's overrides):
// what a hub reader loads for hub-wide search (lib/archive/reader-hub.ts),
// where it used to get whichever site had composed last.
@@ -246,9 +279,12 @@ export async function main(
const summaryNote = await composeHubSummary(paths, publicDir);
const tombstoneNote =
- tombstones.length > 0
- ? `; ${tombstones.length} withdrawn X channel(s) shipped as tombstones, served no-store`
- : "";
+ (withdrawn.length > 0
+ ? `; ${withdrawn.length} withdrawn X channel(s) shipped as tombstones, served no-store`
+ : "") +
+ (carried.length > 0
+ ? `; ${carried.length} channel(s) the last hub bundle tombstoned kept as tombstones, served no-store`
+ : "");
console.log(
`compose-hub: ${builtins.length} built-in pool site(s) into ${publicDir}; ${summaryNote}${tombstoneNote}.`,
);
diff --git a/common/bin/compose-site.departed.test.ts b/common/bin/compose-site.departed.test.ts
@@ -0,0 +1,276 @@
+// Integration (release 24 H1): a channel that leaves a site's published pool —
+// removed from `channels`, or moved to `citedChannels` — ships TOMBSTONES for
+// every per-channel path the site's last bundle served for it, through the
+// REAL index build and the REAL site compose over a temp corpus.
+//
+// The record of what the site published before is its last bundle,
+// `<exportBuildsDir>/<siteId>/out`; each test stands one in by copying the
+// composed public/ there, as the build stage's install does.
+//
+// Run with: node_modules/.bin/tsx --test common/bin/compose-site.departed.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Every path getPaths() can resolve to a place this file's code may write is
+// pinned under ROOT before anything calls it (buildIndex.test.ts's list).
+const ROOT = mkdtempSync(path.join(tmpdir(), "departed-"));
+const PINNED: Record<string, string> = {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+};
+Object.assign(process.env, PINNED);
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("../controller/buildIndex");
+const { main: composeSite } = await import("./compose-site");
+const { builtCitedOnlyProblem, isTombstoneChannelDir } = await import("../lib/builtExport");
+const { lastBundleDir } = await import("../publish/tombstones");
+
+const paths = getPaths();
+const KEEP = "keeper";
+const GONE = "departs";
+const FRESH = "fresh-critic";
+
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+const readJson = <T>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T;
+
+// YouTube's rolling-caption shape (parseVtt keeps lines with inline timing).
+const VTT =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" +
+ "00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c><00:00:02.000><c> line.</c>\n";
+
+function videoChannel(slug: string, videos: number) {
+ writeJson(path.join(paths.channelsDir, slug, "config.json"), {
+ handling: "youtube",
+ name: slug,
+ url: `https://www.youtube.com/@${slug}/videos`,
+ });
+ for (let i = 1; i <= videos; i++) {
+ const id = `${slug}-v${i}`;
+ const dir = path.join(paths.channelsDir, slug, "data", id);
+ writeJson(path.join(dir, "metadata.info.json"), {
+ id,
+ title: `${slug} video ${i}`,
+ channel: slug,
+ upload_date: `2026060${i}`,
+ duration: 120,
+ webpage_url: `https://www.youtube.com/watch?v=${id}`,
+ extractor_key: "Youtube",
+ });
+ writeFileSync(path.join(dir, "transcript.en.vtt"), VTT);
+ }
+}
+
+function site(pool: string[], cited: string[] = []) {
+ writeJson(path.join(paths.sitesDir, "pub", "site.json"), {
+ siteId: "pub",
+ siteTitle: "pub",
+ siteDescription: "fixture",
+ headerTitle: "pub",
+ homeTagline: "",
+ socialLinks: [],
+ groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: pool.map((slug) => ({ slug, groupId: "default" })),
+ ...(cited.length > 0 ? { citedChannels: cited.map((slug) => ({ slug })) } : {}),
+ siteUrl: "https://pub.example.test",
+ archives: false,
+ });
+}
+
+const quiet = () => {};
+async function indexAndCompose(): Promise<void> {
+ const log = console.log;
+ console.log = quiet;
+ try {
+ await buildIndex({ paths, onLog: quiet });
+ await composeSite({ siteId: "pub", paths });
+ } finally {
+ console.log = log;
+ }
+}
+
+// The build stage's install, as far as compose can see it: public/ becomes
+// the site's bundle.
+function install(): string {
+ const bundle = lastBundleDir(paths, "pub");
+ rmSync(bundle, { recursive: true, force: true });
+ mkdirSync(path.dirname(bundle), { recursive: true });
+ cpSync(paths.exportPublicDir, bundle, { recursive: true, dereference: true });
+ return bundle;
+}
+
+const pub = (...rel: string[]) => path.join(paths.exportPublicDir, ...rel);
+const TREES = ["transcripts", "subs", "posts", "digests"] as const;
+// The trees public/ holds for `slug`.
+const treesOf = (slug: string) => TREES.filter((t) => existsSync(pub(t, slug)));
+const pageFiles = (dir: string) => readdirSync(dir).filter((f) => f.startsWith("page-")).sort();
+
+test("a channel removed from the pool ships a tombstone for every tree its last bundle served", async () => {
+ videoChannel(KEEP, 1);
+ videoChannel(GONE, 2);
+ videoChannel(FRESH, 1);
+ writeJson(paths.settingsFile, {});
+ site([KEEP, GONE]);
+ await indexAndCompose();
+ // This fixture's index writes the channel's transcripts; its subs and
+ // digests trees (two pages each) stand in for what a richer build served.
+ assert.deepEqual(treesOf(GONE), ["transcripts"]);
+ const bundle = install();
+ for (const tree of ["subs", "digests"]) {
+ writeJson(path.join(bundle, tree, GONE, "manifest.json"), {
+ version: 1,
+ channelSlug: GONE,
+ pageCount: 2,
+ maxPageBytes: 4096,
+ generatedAt: "2026-10-01T00:00:00.000Z",
+ slugToPage: { [`${GONE}-v1`]: 0, [`${GONE}-v2`]: 1 },
+ ...(tree === "subs" ? { tracks: ["en"] } : { pageHashes: ["a", "b"] }),
+ });
+ for (const page of ["page-0000.json", "page-0001.json"]) {
+ writeJson(path.join(bundle, tree, GONE, page), [{ id: `${GONE}-v1`, text: "served" }]);
+ }
+ }
+ const servedTrees = ["transcripts", "subs", "digests"];
+ const servedPages = Object.fromEntries(
+ servedTrees.map((t) => [t, pageFiles(path.join(bundle, t, GONE))]),
+ );
+ assert.deepEqual(servedPages.subs, ["page-0000.json", "page-0001.json"]);
+
+ site([KEEP]);
+ await indexAndCompose();
+ // Path for path: the same trees, the same page files, each empty.
+ assert.deepEqual(treesOf(GONE), servedTrees);
+ for (const tree of servedTrees) {
+ const dir = pub(tree, GONE);
+ assert.ok(isTombstoneChannelDir(dir), `${tree}/${GONE} is a tombstone`);
+ assert.deepEqual(pageFiles(dir), servedPages[tree], tree);
+ for (const page of pageFiles(dir)) assert.deepEqual(readJson(path.join(dir, page)), []);
+ const m = readJson<Record<string, unknown>>(path.join(dir, "manifest.json"));
+ assert.equal(m.channelSlug, GONE);
+ if (tree === "subs") assert.deepEqual(m.tracks, []);
+ assert.equal(m.pageHashes, undefined);
+ assert.equal(m.pageCount, 0);
+ assert.equal(m.maxPageBytes, 0);
+ assert.deepEqual(m.slugToPage, {});
+ assert.ok(!readFileSync(path.join(dir, "manifest.json"), "utf8").includes(`${GONE}-v1`));
+ }
+ // The member's trees are real; the departed channel is listed nowhere.
+ assert.ok(!isTombstoneChannelDir(pub("transcripts", KEEP)));
+ for (const file of ["corpus.json", "site.json", "summaries/manifest.json", "subs/manifest.json"]) {
+ assert.ok(!readFileSync(pub(file), "utf8").includes(GONE), `${file} names ${GONE}`);
+ }
+ // …served no-store, each tree by its own rule, under the trees' CORS lines.
+ const headers = readFileSync(pub("_headers"), "utf8");
+ assert.ok(
+ headers.endsWith(
+ "# Withdrawn content (tombstones): never stored at the edge.\n" +
+ servedTrees.map((t) => `/${t}/${GONE}/*\n Cache-Control: no-store\n`).join(""),
+ ),
+ headers,
+ );
+ // The bundle compose read is untouched by it.
+ assert.ok(!isTombstoneChannelDir(path.join(bundle, "transcripts", GONE)));
+
+ // Carried: a build over a bundle that holds the tombstones (never deployed,
+ // say) ships them again.
+ install();
+ await indexAndCompose();
+ assert.deepEqual(treesOf(GONE), servedTrees);
+ for (const tree of servedTrees) assert.ok(isTombstoneChannelDir(pub(tree, GONE)));
+
+ // Back in the pool: its real transcripts replace the tombstone and leave the
+ // no-store block. The subs and digests it has no tree for now stay
+ // tombstones — a path served once is never left to the edge's cache.
+ install();
+ site([KEEP, GONE]);
+ await indexAndCompose();
+ assert.ok(!isTombstoneChannelDir(pub("transcripts", GONE)));
+ assert.ok(isTombstoneChannelDir(pub("subs", GONE)));
+ assert.ok(readFileSync(pub("corpus.json"), "utf8").includes(GONE));
+ const back = readFileSync(pub("_headers"), "utf8");
+ assert.ok(!back.includes(`/transcripts/${GONE}/*`), back);
+ assert.ok(back.includes(`/subs/${GONE}/*`), back);
+});
+
+test("a channel moved to the cited scope is tombstoned; one never published is not; the guard passes", async () => {
+ site([KEEP, GONE]);
+ await indexAndCompose();
+ const servedTrees = treesOf(GONE);
+ install();
+
+ // GONE moves to the cited scope; FRESH is cited too, and was never in the
+ // pool, so no bundle served anything for it.
+ site([KEEP], [GONE, FRESH]);
+ await indexAndCompose();
+ assert.deepEqual(treesOf(GONE), servedTrees);
+ for (const tree of servedTrees) assert.ok(isTombstoneChannelDir(pub(tree, GONE)), tree);
+ assert.deepEqual(treesOf(FRESH), [], "a channel the site never published gets nothing");
+ const headers = readFileSync(pub("_headers"), "utf8");
+ assert.ok(!headers.includes(FRESH));
+ for (const file of ["corpus.json", "site.json"]) {
+ assert.ok(!readFileSync(pub(file), "utf8").includes(GONE), `${file} names ${GONE}`);
+ }
+ // A tombstone is not a leak: the cited-only guard passes over the
+ // tombstoned bundle…
+ const cited = {
+ siteId: "pub",
+ channels: [{ slug: KEEP }],
+ citedChannels: [{ slug: GONE }, { slug: FRESH }],
+ };
+ assert.equal(builtCitedOnlyProblem(cited, paths.exportPublicDir), null);
+ // …and still refuses the corpus itself.
+ assert.match(
+ builtCitedOnlyProblem(cited, lastBundleDir(paths, "pub")) ?? "",
+ /cites "departs", "fresh-critic" only \(citedChannels\), but .* publishes its corpus: transcripts\/departs\//,
+ );
+});
+
+test("no bundle, or another site's, is no record: nothing is tombstoned", async () => {
+ site([KEEP, GONE]);
+ await indexAndCompose();
+ const bundle = install();
+ // A bundle that names another site is not this site's record.
+ writeJson(path.join(bundle, "site.json"), { siteId: "elsewhere" });
+ site([KEEP]);
+ await indexAndCompose();
+ assert.deepEqual(treesOf(GONE), []);
+ assert.ok(!readFileSync(pub("_headers"), "utf8").includes("no-store"));
+
+ rmSync(path.dirname(bundle), { recursive: true, force: true });
+ site([KEEP, GONE]);
+ await indexAndCompose();
+ site([KEEP]);
+ await indexAndCompose();
+ assert.deepEqual(treesOf(GONE), []);
+});
diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts
@@ -80,8 +80,12 @@ import {
} from "../publish/composeReports";
import {
emptyPostsManifest,
+ lastBundleDir,
+ servedChannelTrees,
tombstoneNoStoreForSite,
+ writeDepartedTombstones,
writePostsTombstones,
+ type ChannelTreeTombstone,
} from "../publish/tombstones";
import { runIfEntryPoint } from "./_cli";
import { copyPublicFile, ownDir, writePublicFile } from "./_publicFile";
@@ -769,6 +773,21 @@ export async function reconcileChannelTree(
return next;
}
+// The channel trees `siteId`'s last bundle served that public/ no longer holds,
+// written as tombstones into public/ (release 24 H1). Nothing when there is no
+// bundle, or it is not this site's (its site.json names another).
+async function departedChannelTombstones(
+ paths: Paths,
+ siteId: string,
+): Promise<ChannelTreeTombstone[]> {
+ const bundle = lastBundleDir(paths, siteId);
+ if (builtSiteIdIn(bundle) !== siteId) return [];
+ return writeDepartedTombstones({
+ publicDir: paths.exportPublicDir,
+ served: await servedChannelTrees(bundle),
+ });
+}
+
// `archilyzer compose site <id>` passes the id; the bare bin (export's
// compose:site script) reads SITE_ID, as it always has.
export async function main(
@@ -974,7 +993,20 @@ export async function main(
sharedPostsDir: paths.exportSharedPostsDir,
slugs: site.channels.map((c) => c.slug).filter((slug) => !memberSet.has(slug)),
});
- if (tombstones.length > 0) {
+ // --- tombstones for the channels that left this site's pool (release 24 H1) ---
+ // Every per-channel tree the site's last bundle served that this compose does
+ // not ship — a channel removed from `channels` or moved to `citedChannels` —
+ // is replaced, path for path, by a tombstone (publish/tombstones.ts). The
+ // record is the bundle itself, read before this build replaces it; one that
+ // names another site is not this site's record.
+ const departed = await departedChannelTombstones(paths, siteId);
+ if (departed.length > 0) {
+ console.log(
+ `[compose] ${departed.length} channel tree(s) this site served before and no longer publishes ` +
+ `shipped as tombstones (${[...new Set(departed.map((t) => t.slug))].join(", ")}), served no-store.`,
+ );
+ }
+ if (tombstones.length > 0 || departed.some((t) => t.tree === "posts")) {
if (!(await exists(postsManifestSrc))) {
await writePublicFile(
path.join(paths.exportPostsDir, "manifest.json"),
@@ -1155,7 +1187,7 @@ export async function main(
const composed = await composeReports({ paths, site, allowMissingMedia, log: console.log });
// --- federation contract: /site.json descriptor + CORS _headers ---
- await emitFederationFiles(site, paths, { noStore: tombstoneNoStoreForSite(tombstones) });
+ await emitFederationFiles(site, paths, { noStore: tombstoneNoStoreForSite(tombstones, departed) });
// A site's bundle is not a hub's. export/public is shared with the hub build,
// whose compose writes hub-sites.json; left in place it ships in this site's
// out/ and makes the bundle ambiguous to builtHubProblem (and to a site's
diff --git a/common/controller/attachMedia.test.ts b/common/controller/attachMedia.test.ts
@@ -11,7 +11,12 @@ import { makeZip, type ZipFixtureEntry } from "../testing/makeZip";
import { loadSavedVideo } from "../lib/savedVideo-server";
import { savedVideoPath } from "../lib/savedVideo";
import { SAVED_VIDEOS_MARKER_FILENAME } from "../lib/savedVideoStore";
-import { attachMedia, parse7zListing, type AttachMediaOptions } from "./attachMedia";
+import {
+ ATTACH_MEDIA_DISK_MARGIN_BYTES,
+ attachMedia,
+ parse7zListing,
+ type AttachMediaOptions,
+} from "./attachMedia";
// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/attachMedia.test.ts
//
@@ -20,6 +25,7 @@ import { attachMedia, parse7zListing, type AttachMediaOptions } from "./attachMe
// here; nothing reads a real archive or corpus.
const SLUG = "demo";
+const PLENTY = 1024 ** 4;
const sha = (b: Buffer) => createHash("sha256").update(b).digest("hex");
const bytes = (n: number, seed: number) => Buffer.from(Array.from({ length: n }, (_, i) => (i * seed + 3) & 0xff));
@@ -68,8 +74,16 @@ async function withFixture(fn: (ctx: Ctx) => Promise<void>, entries = ENTRIES):
channelConfig: { name: "Demo", handling: "youtube", platform: "youtube" } as unknown as ChannelConfig,
source: zip,
onLog: (l) => lines.push(l),
- deps: { probeDuration: async () => 61.5, now: () => new Date("2026-10-09T12:00:00Z") },
...o,
+ // The store's free space is the fixture's, never the machine's (a /tmp
+ // tmpfs under 2 GiB free used to stop every attach): only the margin test
+ // below judges it.
+ deps: {
+ probeDuration: async () => 61.5,
+ now: () => new Date("2026-10-09T12:00:00Z"),
+ freeBytes: async () => PLENTY,
+ ...o.deps,
+ },
});
try {
await fn({ dir, paths, zip, lines, opts });
@@ -249,6 +263,32 @@ test("guards: a store being moved stops the run; a store root that is not there
});
});
+test("the disk margin: a store disk without the video plus 2 GiB free stops the run before any copy", async () => {
+ await withFixture(async ({ paths, opts, lines }) => {
+ const asked: string[] = [];
+ const r = await attachMedia(
+ opts({
+ deps: {
+ freeBytes: async (dir) => {
+ asked.push(dir);
+ return ATTACH_MEDIA_DISK_MARGIN_BYTES + A.length - 1;
+ },
+ },
+ }),
+ );
+ assert.deepEqual(r.attached, []);
+ assert.match(r.stopped ?? "", /^the store's disk has 2\.00 GB free; aaaaaaaaaaa needs 48\.8 KB plus 2\.00 GB$/);
+ assert.ok(lines.some((l) => /A re-run resumes/.test(l)));
+ assert.deepEqual(asked, [paths.savedVideosDir]);
+ assert.equal(await loadSavedVideo(videoDir(paths, "aaaaaaaaaaa")), null);
+ // One byte more and it attaches.
+ const ok = await attachMedia(
+ opts({ deps: { freeBytes: async () => ATTACH_MEDIA_DISK_MARGIN_BYTES + A.length } }),
+ );
+ assert.deepEqual(ok.attached, ["aaaaaaaaaaa"]);
+ });
+});
+
test("drain stops before the next video", async () => {
await withFixture(async ({ opts }) => {
const drain = new AbortController();
diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts
@@ -245,6 +245,9 @@ export type AttachMediaOptions = {
now?: () => Date;
probeDuration?: (file: string) => Promise<number | null>;
openSource?: (source: string) => Promise<ArchiveSource>;
+ // The store disk's free bytes (default lib/diskSpace.ts getFreeBytes):
+ // a test names the disk it judges, never the machine's.
+ freeBytes?: (dir: string) => Promise<number>;
};
};
@@ -418,7 +421,7 @@ export async function attachMedia(opts: AttachMediaOptions): Promise<AttachMedia
onLog(`Stopped: ${result.stopped}`);
break;
}
- const free = await getFreeBytes(storeRoot);
+ const free = await (opts.deps?.freeBytes ?? getFreeBytes)(storeRoot);
if (free < media.size + ATTACH_MEDIA_DISK_MARGIN_BYTES) {
result.stopped = `the store's disk has ${formatBytes(free)} free; ${id} needs ${formatBytes(media.size)} plus ${formatBytes(ATTACH_MEDIA_DISK_MARGIN_BYTES)}`;
onLog(`Stopped: ${result.stopped}. A re-run resumes.`);
diff --git a/common/controller/preparePlayable.test.ts b/common/controller/preparePlayable.test.ts
@@ -10,6 +10,7 @@ import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import { loadSavedVideo } from "../lib/savedVideo-server";
import {
+ PLAYABLE_DISK_MARGIN_BYTES,
loadPlayableManifest,
makePlayableTorrent,
preparePlayable,
@@ -76,8 +77,11 @@ async function withFixture(fn: (f: Fixture) => Promise<void>): Promise<void> {
slug: SLUG,
channelConfig: { name: "Demo", handling: "youtube", platform: "youtube" } as unknown as ChannelConfig,
onLog: (l) => lines.push(l),
- deps: { now: () => new Date("2026-10-09T12:00:00Z") },
...o,
+ // The root's free space is the fixture's, never the machine's (a /tmp
+ // tmpfs under 2 GiB free used to stop every remux): only the margin test
+ // below judges it.
+ deps: { now: () => new Date("2026-10-09T12:00:00Z"), freeBytes: async () => 1024 ** 4, ...o.deps },
});
try {
await fn({ dir, paths, root, opts, lines });
@@ -232,6 +236,35 @@ test("dryRun decides and writes nothing", { skip: !tools && "ffmpeg/ffprobe not
});
});
+test("the disk margin: a root without the container plus 2 GiB free stops the run before any remux", async () => {
+ await withFixture(async ({ dir, paths, root, opts, lines }) => {
+ await writeFile(path.join(dir, "a.mp4"), Buffer.alloc(1000, 1));
+ await saved(paths, "aaaaaaaaaaa", path.join(dir, "a.mp4"), "mp4");
+ const asked: string[] = [];
+ let remuxes = 0;
+ const r = await preparePlayable(
+ opts({
+ root,
+ deps: {
+ probe: async () => ({ formatName: "mov,mp4,m4a,3gp,3g2,mj2", ext: "mp4", vcodec: "h264", acodec: "aac" }),
+ remux: async () => {
+ remuxes += 1;
+ },
+ freeBytes: async (d) => {
+ asked.push(d);
+ return PLAYABLE_DISK_MARGIN_BYTES + 999;
+ },
+ },
+ }),
+ );
+ assert.deepEqual(r.prepared, []);
+ assert.equal(remuxes, 0);
+ assert.match(r.stopped ?? "", /^the playable root's disk has 2\.00 GB free; aaaaaaaaaaa needs about 1000 B plus 2\.00 GB$/);
+ assert.ok(lines.some((l) => /A re-run resumes/.test(l)));
+ assert.deepEqual(asked, [path.dirname(root)]);
+ });
+});
+
test("the default root is playable/ beside the store's real directory; an absent drive refuses", async () => {
await withFixture(async ({ dir, paths, opts }) => {
await mkdir(paths.savedVideosDir, { recursive: true });
diff --git a/common/controller/preparePlayable.ts b/common/controller/preparePlayable.ts
@@ -139,6 +139,9 @@ export type PreparePlayableOptions = {
now?: () => Date;
probe?: (file: string) => Promise<MediaProbe>;
remux?: (src: string, dest: string, args: string[], signal?: AbortSignal) => Promise<void>;
+ // The playable root's free bytes (default lib/diskSpace.ts getFreeBytes):
+ // a test names the disk it judges, never the machine's.
+ freeBytes?: (dir: string) => Promise<number>;
};
};
@@ -284,7 +287,7 @@ export async function preparePlayable(opts: PreparePlayableOptions): Promise<Pre
result.prepared.push(id);
continue;
}
- const free = await getFreeBytes(path.dirname(root));
+ const free = await (opts.deps?.freeBytes ?? getFreeBytes)(path.dirname(root));
if (free < srcBytes + PLAYABLE_DISK_MARGIN_BYTES) {
result.stopped = `the playable root's disk has ${formatBytes(free)} free; ${id} needs about ${formatBytes(srcBytes)} plus ${formatBytes(PLAYABLE_DISK_MARGIN_BYTES)}`;
onLog(`Stopped: ${result.stopped}. A re-run resumes.`);
diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts
@@ -30,9 +30,10 @@
//
// NOT FOR A RECORD yt-dlp DID NOT WRITE. An archive.org record, a Wayback copy
// and a record completed from a podcast feed hold metadata their own writers
-// put there; a yt-dlp re-read would replace it with what the bare URL says (the
-// hazard the persist prefetch already has with Wayback titles). Those are
-// refused, by URL and by the writers in the history.
+// put there; a yt-dlp re-read would replace it with what the bare URL says.
+// Those are refused, by URL and by the writers in the history. (A managed
+// download's prefetch over such a record keeps the provenance's fields since
+// release 24 H3 — lib/metadataHistory.ts keepProvenanceFields.)
//
// A RATE LIMIT IS RECORDED, NOT RETRIED: the caller's `onPlatformBackoff`
// writes the shared per-platform cooldown the download lane honours, and the
diff --git a/common/lib/builtExport.test.ts b/common/lib/builtExport.test.ts
@@ -20,7 +20,7 @@ import {
publishFileSizeProblem,
reportHistoryProblem,
isTombstonePostsTree,
- isTombstoneChannelPostsDir,
+ isTombstoneChannelDir,
hubReportDataIn,
} from "./builtExport";
@@ -567,7 +567,25 @@ test("a build that publishes a cited-only channel's corpus is refused; its momen
// A tombstone of its posts is not its posts.
put("posts/critic/manifest.json", JSON.stringify({ pageCount: 0, slugToPage: {} }));
put("posts/critic/page-0000.json", "[]");
- assert.equal(isTombstoneChannelPostsDir(path.join(t.dir, "posts", "critic")), true);
+ assert.equal(isTombstoneChannelDir(path.join(t.dir, "posts", "critic")), true);
+ assert.equal(builtCitedOnlyProblem(site, t.dir), null);
+ // Release 24 H1: nor is a tombstone of its transcripts, subs or digests (a
+ // build before it moved to the cited scope served them).
+ const tomb = { pageCount: 0, maxPageBytes: 0, slugToPage: {} };
+ put("transcripts/critic/manifest.json", JSON.stringify(tomb));
+ put("transcripts/critic/page-0000.json", "[]");
+ put("subs/critic/manifest.json", JSON.stringify({ ...tomb, tracks: [] }));
+ put("digests/critic/manifest.json", JSON.stringify(tomb));
+ assert.equal(builtCitedOnlyProblem(site, t.dir), null);
+ // A tombstone names no track and no page hash.
+ put("subs/critic/manifest.json", JSON.stringify({ ...tomb, tracks: ["en"] }));
+ assert.equal(isTombstoneChannelDir(path.join(t.dir, "subs", "critic")), false);
+ assert.match(builtCitedOnlyProblem(site, t.dir) ?? "", /subs\/critic\//);
+ put("subs/critic/manifest.json", JSON.stringify({ ...tomb, pageHashes: ["h"] }));
+ assert.equal(isTombstoneChannelDir(path.join(t.dir, "subs", "critic")), false);
+ rmSync(path.join(t.dir, "subs", "critic"), { recursive: true });
+ rmSync(path.join(t.dir, "transcripts", "critic"), { recursive: true });
+ rmSync(path.join(t.dir, "digests", "critic"), { recursive: true });
assert.equal(builtCitedOnlyProblem(site, t.dir), null);
// Its trees, each named.
diff --git a/common/lib/builtExport.ts b/common/lib/builtExport.ts
@@ -438,7 +438,9 @@ function listedChannelSlugsIn(outDir: string, file: string): Set<string> {
* CITED-ONLY channel's corpus, as one sentence — or null. A cited-only channel
* (`citedChannels`) publishes its cited moments and clips (`m/`, `media/`) and
* nothing else: no transcripts, subs, posts, digests, stats or archives tree
- * named for it (a posts tree of tombstones only aside), and no entry in
+ * named for it (a tree that is a tombstone aside — release 18's posts ones,
+ * and since release 24 H1 any of its four channel trees a build before it
+ * moved to the cited scope served), and no entry in
* corpus.json's or site.json's `channels`. Compose never writes those for it;
* this is the second line, chained beside builtScopeProblem by the build
* (publish/build.ts), the deploy stage and deployAudienceProblem.
@@ -458,7 +460,9 @@ export function builtCitedOnlyProblem(site: CitedOnlySite, outDir: string): stri
for (const tree of CHANNEL_TREES) {
const dir = path.join(outDir, tree, slug);
if (!existsSync(dir)) continue;
- if (tree === "posts" && isTombstoneChannelPostsDir(dir)) continue;
+ // A tombstone publishes nothing (release 24 H1: the channel's trees a
+ // build before it moved to the cited scope served are replaced by them).
+ if (tree !== "stats" && tree !== "archives" && isTombstoneChannelDir(dir)) continue;
found.push(`${tree}/${slug}/`);
}
for (const [file, slugs] of Object.entries(listedIn)) {
@@ -555,16 +559,18 @@ export function isTombstonePostsTree(postsDir: string): boolean {
for (const e of entries) {
if (e.name === "manifest.json" && e.isFile()) continue;
if (!e.isDirectory()) return false;
- if (!isTombstoneChannelPostsDir(path.join(postsDir, e.name))) return false;
+ if (!isTombstoneChannelDir(path.join(postsDir, e.name))) return false;
}
return true;
}
/**
- * Whether one channel's posts dir (`posts/<slug>/`) is a TOMBSTONE: a posts
- * manifest at pageCount 0 with no `slugToPage` entries, and only `[]` pages.
+ * Whether one channel's dir in a channel tree (`posts/<slug>/`, and since
+ * release 24 H1 `transcripts/`, `subs/` or `digests/<slug>/`) is a TOMBSTONE:
+ * a channel manifest at pageCount 0 with no `slugToPage` entries, no `tracks`
+ * and no `pageHashes`, and only `[]` pages — it publishes nothing.
*/
-export function isTombstoneChannelPostsDir(dir: string): boolean {
+export function isTombstoneChannelDir(dir: string): boolean {
const readJson = (file: string): unknown => {
try {
return JSON.parse(readFileSync(file, "utf8"));
@@ -573,10 +579,13 @@ export function isTombstoneChannelPostsDir(dir: string): boolean {
}
};
const channel = readJson(path.join(dir, "manifest.json")) as
- | { pageCount?: unknown; slugToPage?: unknown }
+ | { pageCount?: unknown; slugToPage?: unknown; tracks?: unknown; pageHashes?: unknown }
| undefined;
if (!channel || channel.pageCount !== 0) return false;
if (channel.slugToPage && Object.keys(channel.slugToPage as object).length > 0) return false;
+ for (const list of [channel.tracks, channel.pageHashes]) {
+ if (list !== undefined && !(Array.isArray(list) && list.length === 0)) return false;
+ }
let files: Dirent[];
try {
files = readdirSync(dir, { withFileTypes: true });
diff --git a/common/lib/metadataHistory-server.test.ts b/common/lib/metadataHistory-server.test.ts
@@ -175,3 +175,154 @@ test("patchMetadataInfo refuses a missing file or one that is not a JSON object"
await assert.rejects(patchMetadataInfo(dir, { title: "x" }, { by: "feed-backfill" }), /not JSON/);
});
});
+
+// ── Release 24 H3: a rewrite keeps what a provenance writer applied ──────────
+
+const readInfo = async (dir: string) => JSON.parse(await readFile(path.join(dir, INFO), "utf8"));
+
+// A raw JW Player file captured by the Wayback Machine, as yt-dlp's generic
+// extractor writes it: the title is the file's name, and there is no date.
+const CAPTURE = "https://web.archive.org/web/20190405000000/https://cdn.example.test/videos/AbCd1234-720.mp4";
+const waybackCapture = (extra: Record<string, unknown> = {}) =>
+ JSON.stringify({
+ id: "AbCd1234-720",
+ title: "AbCd1234-720",
+ webpage_url: CAPTURE,
+ extractor_key: "Generic",
+ formats: [{ url: `${CAPTURE}?sig=${Math.random()}` }],
+ ...extra,
+ });
+
+test("a prefetch over a Wayback record keeps the title and date the provenance set; a new field lands", async () => {
+ await withDir(async (dir) => {
+ await writeFile(path.join(dir, INFO), waybackCapture());
+ await patchMetadataInfo(
+ dir,
+ { title: "The Real Title", upload_date: "20190405" },
+ { by: "wayback-provenance", requestedBy: "cli" },
+ );
+ const lines: string[] = [];
+ await withMetadataHistory(dir, { by: "prefetch", onLog: (l) => lines.push(l) }, async () => {
+ // The persist prefetch rewrites the file from the capture again.
+ await writeFile(path.join(dir, INFO), waybackCapture({ duration: 61.5 }));
+ });
+ const info = await readInfo(dir);
+ assert.equal(info.title, "The Real Title");
+ assert.equal(info.upload_date, "20190405");
+ assert.equal(info.duration, 61.5, "a genuinely new field still lands");
+ // The title stays in the head, the date is the tail's last key.
+ assert.deepEqual(Object.keys(info), ["id", "title", "webpage_url", "extractor_key", "formats", "duration", "upload_date"]);
+ assert.ok(lines.some((l) => /^Kept what the provenance set over this rewrite: title, upload_date/.test(l)), lines.join(""));
+ // The prefetch's entry is still written, net of the kept fields.
+ const h = await loadMetadataHistory(dir);
+ assert.deepEqual(h?.entries.map((e) => e.by), ["wayback-provenance", "prefetch"]);
+ const pre = h!.entries[1];
+ assert.deepEqual(pre.changed, {});
+ assert.deepEqual(pre.added, { duration: 61.5 });
+ assert.deepEqual(pre.removed, {});
+ assert.deepEqual(pre.volatile, ["formats"]);
+
+ // A title the source genuinely changed is the source's.
+ await withMetadataHistory(dir, { by: "prefetch" }, async () => {
+ await writeFile(path.join(dir, INFO), waybackCapture({ title: "Retitled At The Source" }));
+ });
+ const again = await readInfo(dir);
+ assert.equal(again.title, "Retitled At The Source");
+ assert.equal(again.upload_date, "20190405");
+ });
+});
+
+test("a record a prefetch already reverted gets the provenance's fields back on the next rewrite", async () => {
+ await withDir(async (dir) => {
+ await writeFile(path.join(dir, INFO), waybackCapture());
+ await patchMetadataInfo(dir, { title: "The Real Title", upload_date: "20190405" }, { by: "wayback-provenance" });
+ // The history a pre-H3 prefetch left: the placeholder back, the date gone.
+ const reverted = await readInfo(dir);
+ const h = await loadMetadataHistory(dir);
+ await writeFile(
+ metadataHistoryPath(dir),
+ JSON.stringify({
+ entries: [
+ ...h!.entries,
+ {
+ at: "2026-10-06T00:00:00.000Z",
+ by: "prefetch",
+ from: { sha256: "a".repeat(64), bytes: 1 },
+ to: { sha256: "b".repeat(64), bytes: 1 },
+ changed: { title: { from: "The Real Title", to: "AbCd1234-720" } },
+ added: {},
+ removed: { upload_date: "20190405" },
+ counters: {},
+ volatile: ["formats"],
+ },
+ ],
+ }),
+ );
+ assert.equal(reverted.title, "The Real Title");
+ await writeFile(path.join(dir, INFO), waybackCapture());
+ await withMetadataHistory(dir, { by: "audio-check" }, async () => {
+ await writeFile(path.join(dir, INFO), waybackCapture());
+ });
+ const info = await readInfo(dir);
+ assert.equal(info.title, "The Real Title");
+ assert.equal(info.upload_date, "20190405");
+ });
+});
+
+test("an archive.org re-import keeps the mirror's title and date and the dropped timestamp; a new field lands", async () => {
+ await withDir(async (dir) => {
+ // As imported: the item's title and date, and the timestamp yt-dlp
+ // derived from the item's publicdate.
+ const item = (extra: Record<string, unknown> = {}) =>
+ JSON.stringify({
+ id: "some-item--show-2019-03-01",
+ title: "Some Item",
+ webpage_url: "https://archive.org/details/some-item/show-2019-03-01.mp4",
+ extractor_key: "ArchiveOrg",
+ timestamp: 1577836800,
+ formats: [{ url: "https://archive.org/download/some-item/show-2019-03-01.mp4" }],
+ ...extra,
+ upload_date: "20200101",
+ });
+ await writeFile(path.join(dir, INFO), item());
+ await patchMetadataInfo(
+ dir,
+ { title: "The Mirror's Title", upload_date: "20190301", timestamp: null },
+ { by: "archiveorg-provenance" },
+ );
+ await withMetadataHistory(dir, { by: "archiveorg-import" }, async () => {
+ await writeFile(path.join(dir, INFO), item({ description: "now described" }));
+ });
+ const info = await readInfo(dir);
+ assert.equal(info.title, "The Mirror's Title");
+ assert.equal(info.upload_date, "20190301");
+ assert.equal(info.timestamp, null);
+ assert.equal(info.description, "now described");
+ const h = await loadMetadataHistory(dir);
+ assert.deepEqual(h?.entries.map((e) => e.by), ["archiveorg-provenance", "archiveorg-import"]);
+ assert.deepEqual(h!.entries[1].added, { description: "now described" });
+ assert.deepEqual(h!.entries[1].changed, {});
+ });
+});
+
+test("a provenance writer is never kept against, and a record with no provenance is the rewrite's", async () => {
+ await withDir(async (dir) => {
+ await writeFile(path.join(dir, INFO), waybackCapture());
+ await patchMetadataInfo(dir, { title: "First Find" }, { by: "wayback-provenance" });
+ // The operator's next find replaces the first.
+ await patchMetadataInfo(dir, { title: "Better Find" }, { by: "wayback-provenance" });
+ assert.equal((await readInfo(dir)).title, "Better Find");
+ // A placeholder rewrite now restores the newest find.
+ await withMetadataHistory(dir, { by: "prefetch" }, async () => {
+ await writeFile(path.join(dir, INFO), waybackCapture());
+ });
+ assert.equal((await readInfo(dir)).title, "Better Find");
+ });
+ await withDir(async (dir) => {
+ await writeFile(path.join(dir, INFO), meta("old"));
+ await withMetadataHistory(dir, { by: "prefetch" }, async () => {
+ await writeFile(path.join(dir, INFO), meta("new"));
+ });
+ assert.equal((await readInfo(dir)).title, "new");
+ });
+});
diff --git a/common/lib/metadataHistory-server.ts b/common/lib/metadataHistory-server.ts
@@ -18,9 +18,12 @@
// so this needs a directory left by an earlier pass that was NOT rejected (a
// failed download, say) and a filter that rejects it now.
//
-// THE FILE yt-dlp WRITES IS STILL THE FILE. Nothing here changes what lands in
-// metadata.info.json; it reads the old bytes before the spawn and the new ones
-// after it, and appends what moved.
+// THE FILE yt-dlp WRITES IS STILL THE FILE — with one exception (release 24
+// H3): a field a provenance writer applied (a Wayback copy's title and date,
+// an archive.org mirror's, a feed entry's) that the rewrite lost, or reverted
+// to the placeholder the provenance replaced, is put back before the entry is
+// recorded (keepProvenanceInFile). Otherwise it reads the old bytes before the
+// spawn and the new ones after it, and appends what moved.
//
// SERVER-ONLY (node:fs).
@@ -30,7 +33,9 @@ import { withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
import { sidecar, sidecarField } from "./sidecar-server";
import {
METADATA_HISTORY_FILENAME,
+ PROVENANCE_WRITERS,
appendMetadataHistoryEntry,
+ keepProvenanceFields,
buildMetadataHistoryEntry,
coerceMetadataHistory,
type MetadataHistoryEntry,
@@ -124,6 +129,16 @@ export async function withMetadataHistory<T>(
return await run();
} finally {
if (before) {
+ // A rewrite by anything but a provenance writer keeps what one applied
+ // (release 24 H3, keepProvenanceFields) — BEFORE the entry is recorded,
+ // so the entry says what the rewrite changed net of the kept fields.
+ if (!PROVENANCE_WRITERS.has(ctx.by)) {
+ try {
+ await keepProvenanceInFile(videoDir, before, ctx.onLog);
+ } catch (err) {
+ ctx.onLog?.(`Could not keep the provenance's fields: ${(err as Error).message}\n`);
+ }
+ }
try {
const entry = await recordMetadataRewrite(videoDir, before, ctx);
if (entry) ctx.onEntry?.(entry);
@@ -136,6 +151,37 @@ export async function withMetadataHistory<T>(
}
}
+// After a rewrite of metadata.info.json (its bytes differ from `before`): put
+// back every field a provenance writer applied that the rewrite lost or
+// reverted to the placeholder it replaced (lib/metadataHistory.ts
+// keepProvenanceFields, over the history as it stood before this rewrite).
+// Returns the keys kept. Not under the file's lock: it runs inside the wrap a
+// yt-dlp spawn runs in, which does not lock either (patchMetadataInfo's
+// caveat), and patchMetadataInfo — which does — is a provenance writer's,
+// never asked to keep.
+export async function keepProvenanceInFile(
+ videoDir: string,
+ before: MetadataSnapshot,
+ onLog?: (line: string) => void,
+): Promise<string[]> {
+ const after = await snapshotMetadata(videoDir);
+ if (!after || after.text.equals(before.text)) return [];
+ let fresh: unknown;
+ try {
+ fresh = JSON.parse(after.text.toString("utf8"));
+ } catch {
+ return [];
+ }
+ if (typeof fresh !== "object" || fresh === null || Array.isArray(fresh)) return [];
+ const history = await loadMetadataHistory(videoDir).catch(() => null);
+ if (!history?.entries.length) return [];
+ const { next, kept } = keepProvenanceFields(history, fresh as Record<string, unknown>);
+ if (kept.length === 0) return [];
+ await writeJsonAtomic(path.join(videoDir, INFO_JSON), next, { indent: 0, newline: false });
+ onLog?.(`Kept what the provenance set over this rewrite: ${kept.join(", ")} (metadata.history.json).\n`);
+ return kept;
+}
+
// THE ONE WRITER OF metadata.info.json THAT IS NOT yt-dlp: merge `patch` into
// the file on disk, inside `withMetadataHistory`, so the rewrite is recorded
// exactly as a yt-dlp one is (by `ctx.by`, with what moved).
diff --git a/common/lib/metadataHistory.test.ts b/common/lib/metadataHistory.test.ts
@@ -10,6 +10,8 @@ import {
isValueDigest,
normalizeForDiff,
type MetadataHistoryEntry,
+ keepProvenanceFields,
+ provenanceClaims,
} from "./metadataHistory";
// Run with:
@@ -213,3 +215,69 @@ test("coerceMetadataHistory keeps good entries and drops torn ones", () => {
entries: [good],
});
});
+
+// ── Release 24 H3: keepProvenanceFields ──────────────────────────────────────
+
+function provEntry(by: string, diff: Partial<Pick<MetadataHistoryEntry, "changed" | "added" | "removed">>): MetadataHistoryEntry {
+ return {
+ at: "2026-10-01T00:00:00.000Z",
+ by: by as MetadataHistoryEntry["by"],
+ from: { sha256: "a".repeat(64), bytes: 1 },
+ to: { sha256: "b".repeat(64), bytes: 1 },
+ changed: {},
+ added: {},
+ removed: {},
+ counters: {},
+ volatile: [],
+ ...diff,
+ };
+}
+
+test("provenanceClaims: the newest provenance value per key, every value it replaced; other writers ignored", () => {
+ const claims = provenanceClaims({
+ entries: [
+ provEntry("wayback-provenance", { changed: { title: { from: "f-720", to: "First" } }, added: { upload_date: "20190405" } }),
+ provEntry("prefetch", { changed: { title: { from: "First", to: "f-720" } }, removed: { upload_date: "20190405" } }),
+ provEntry("wayback-provenance", { changed: { title: { from: "f-720", to: "Better" } } }),
+ provEntry("archiveorg-provenance", { changed: { timestamp: { from: 1, to: null } }, removed: { uploader: "a@b" } }),
+ provEntry("feed-backfill", { added: { description: { sha256: "c".repeat(64), bytes: 20000 }, subtitles_langs: ["en"] } }),
+ ],
+ });
+ assert.deepEqual(Object.fromEntries(claims), {
+ title: { value: "Better", replaced: ["f-720", "First", "f-720"] },
+ upload_date: { value: "20190405", replaced: [] },
+ timestamp: { value: null, replaced: [1] },
+ uploader: { value: undefined, replaced: ["a@b"] },
+ });
+ assert.equal(provenanceClaims(null).size, 0);
+});
+
+test("keepProvenanceFields: a lost or placeholder field comes back, a new value lands, order kept for the byte readers", () => {
+ const history = {
+ entries: [
+ provEntry("wayback-provenance", {
+ changed: { title: { from: "f-720", to: "Real" } },
+ added: { upload_date: "20190405" },
+ }),
+ provEntry("archiveorg-provenance", { removed: { uploader: "a@b" } }),
+ ],
+ };
+ // Title reverted, date gone, the removed key back: all three kept.
+ const r = keepProvenanceFields(history, { id: "f", title: "f-720", uploader: "a@b", duration: 3 });
+ assert.deepEqual(r.kept.sort(), ["title", "upload_date", "uploader"]);
+ assert.deepEqual(r.next, { id: "f", title: "Real", duration: 3, upload_date: "20190405" });
+ // A title lost entirely goes right after the id.
+ assert.deepEqual(Object.keys(keepProvenanceFields(history, { id: "f", duration: 3 }).next), [
+ "id",
+ "title",
+ "duration",
+ "upload_date",
+ ]);
+ // A new title and date from the source land; nothing to keep is `fresh` itself.
+ const fresh = { id: "f", title: "Retitled", upload_date: "20200101" };
+ const none = keepProvenanceFields(history, fresh);
+ assert.deepEqual(none.kept, []);
+ assert.equal(none.next, fresh);
+ // No history: the rewrite's.
+ assert.deepEqual(keepProvenanceFields(null, { id: "f", title: "f-720" }).kept, []);
+});
diff --git a/common/lib/metadataHistory.ts b/common/lib/metadataHistory.ts
@@ -397,3 +397,100 @@ export function coerceMetadataHistory(value: unknown): MetadataHistory | null {
);
return { entries };
}
+
+// ── WHAT A PROVENANCE WRITER APPLIED, KEPT OVER A LATER REWRITE ──────────────
+//
+// Release 24 H3. A record yt-dlp cannot describe is completed by a writer that
+// is not yt-dlp: a raw Wayback file's title and date as the operator found
+// them (`wayback-provenance`), an archive.org record's mirror title and date
+// (`archiveorg-provenance`), a podcast episode's feed entry (`feed-backfill`).
+// A later managed download rewrites the whole file from the source again — the
+// persist prefetch put a Wayback JW record's title back to `<id>-<rendition>`
+// and dropped its upload_date, and the next index skipped the record. Nothing
+// in the info json marks a field as provenance-applied; the HISTORY does: each
+// of those writers' entries names the key, the value it wrote and the value it
+// replaced.
+//
+// The rule (keepProvenanceFields): for each key a provenance writer last set,
+// a rewrite that LACKS the key, or carries exactly a value a provenance entry
+// replaced (the capture's own placeholder, or an earlier find a later one
+// superseded), gets the provenance's newest value back.
+// Any other value is the source saying something new, and it lands. A value
+// the history holds only as a digest (over 16 KB) cannot be restored and is
+// left to the rewrite.
+
+// The writers whose fields a later rewrite keeps: every writer that completes
+// a record with what its source cannot say (refreshVideoMetadata.ts refuses a
+// yt-dlp re-read of a record they touched, for the same reason).
+export const PROVENANCE_WRITERS: ReadonlySet<MetadataHistoryWriter> = new Set<MetadataHistoryWriter>([
+ "wayback-provenance",
+ "archiveorg-provenance",
+ "feed-backfill",
+]);
+
+// One key's claim: the value the provenance wrote last (undefined: it removed
+// the key), and every value it replaced on the way — the capture's own, and an
+// earlier provenance value a later one superseded (an absent key is no value).
+export type ProvenanceClaim = { value: Json | undefined; replaced: Json[] };
+
+const DERIVED_KEYS: ReadonlySet<string> = new Set(Object.values(LANG_LIST_KEYS));
+
+/** Per key, what the NEWEST provenance entry that touched it wrote and replaced. */
+export function provenanceClaims(history: MetadataHistory | null): Map<string, ProvenanceClaim> {
+ const claims = new Map<string, ProvenanceClaim>();
+ const claim = (k: string, value: Json | undefined, replaced: Json | undefined) => {
+ const prev = claims.get(k);
+ const all = [...(prev?.replaced ?? []), ...(prev && prev.value !== undefined ? [prev.value] : [])];
+ if (replaced !== undefined) all.push(replaced);
+ claims.set(k, { value, replaced: all });
+ };
+ for (const e of history?.entries ?? []) {
+ if (!PROVENANCE_WRITERS.has(e.by)) continue;
+ for (const [k, c] of Object.entries(e.changed)) claim(k, c.to, c.from);
+ for (const [k, v] of Object.entries(e.added)) claim(k, v, undefined);
+ for (const [k, v] of Object.entries(e.removed)) claim(k, undefined, v);
+ }
+ for (const [k, c] of claims) {
+ if (DERIVED_KEYS.has(k) || isValueDigest(c.value)) claims.delete(k);
+ else c.replaced = c.replaced.filter((v) => !isValueDigest(v));
+ }
+ return claims;
+}
+
+/**
+ * `fresh` (a rewritten info json) with every provenance-applied key it lost or
+ * reverted to its placeholder restored, and the keys restored (empty: `next`
+ * is `fresh` itself). A restored key `fresh` lacked is placed where the byte
+ * readers look for it: `title` right after `id` (the 16 KB head,
+ * videoTitles.ts), anything else at the end (`upload_date`: the 8 KB tail,
+ * recencyIndex.ts). PURE.
+ */
+export function keepProvenanceFields(
+ history: MetadataHistory | null,
+ fresh: JsonObject,
+): { next: JsonObject; kept: string[] } {
+ const kept: string[] = [];
+ const set: JsonObject = {};
+ const drop = new Set<string>();
+ for (const [k, c] of provenanceClaims(history)) {
+ const has = Object.hasOwn(fresh, k);
+ const current = has ? fresh[k] : undefined;
+ if (canonicalJson(current) === canonicalJson(c.value)) continue;
+ const placeholder = !has || c.replaced.some((r) => jsonEqual(current, r));
+ if (!placeholder) continue;
+ kept.push(k);
+ if (c.value === undefined) drop.add(k);
+ else set[k] = c.value;
+ }
+ if (kept.length === 0) return { next: fresh, kept };
+ const next: JsonObject = {};
+ const putTitle = Object.hasOwn(set, "title") && !Object.hasOwn(fresh, "title");
+ if (putTitle && !Object.hasOwn(fresh, "id")) next.title = set.title;
+ for (const [k, v] of Object.entries(fresh)) {
+ if (drop.has(k)) continue;
+ next[k] = Object.hasOwn(set, k) ? set[k] : v;
+ if (k === "id" && putTitle) next.title = set.title;
+ }
+ for (const [k, v] of Object.entries(set)) if (!Object.hasOwn(next, k)) next[k] = v;
+ return { next, kept };
+}
diff --git a/common/publish/deployStage.test.ts b/common/publish/deployStage.test.ts
@@ -139,12 +139,13 @@ function built(
}
// A live check that finds the build live: every URL answers this build's
-// corpus.json (or a tombstone body for a posts path), and records each URL.
+// corpus.json (or a tombstone body for a channel tree's path), and records
+// each URL.
function liveFetch(asked: string[], generatedAt = GENERATED): typeof fetch {
return (async (input: string | URL | Request) => {
const url = String(input);
asked.push(url);
- const body = url.includes("/posts/")
+ const body = /\/(posts|transcripts|subs|digests)\//.test(url)
? url.includes("page-")
? []
: url.includes("/posts/manifest.json")
@@ -669,6 +670,56 @@ test("the hub: its project, its bundle, and every tombstone probed plain and bus
}
});
+// Release 24 H1: a site's deploy probes the tombstones its bundle's _headers
+// declares withdrawn — a departed channel's trees and a withheld X channel's
+// posts — plain and busted, as the hub's.
+test("a site: every tree its _headers declares withdrawn is probed plain and busted", async () => {
+ const fx = fixture();
+ try {
+ site(fx, "anilyzer");
+ built(fx, "anilyzer");
+ const out = path.join(fx.paths.exportBuildsDir, "anilyzer", "out");
+ writeFileSync(
+ path.join(out, "_headers"),
+ "/transcripts/*\n Access-Control-Allow-Origin: *\n" +
+ "# Withdrawn content (tombstones): never stored at the edge.\n" +
+ "/posts/manifest.json\n Cache-Control: no-store\n" +
+ "/posts/jer-x/*\n Cache-Control: no-store\n" +
+ "/transcripts/gone/*\n Cache-Control: no-store\n" +
+ "/digests/gone/*\n Cache-Control: no-store\n",
+ );
+ writeJson(path.join(out, "posts", "jer-x", "manifest.json"), { pageCount: 0, slugToPage: {} });
+ writeJson(path.join(out, "posts", "jer-x", "page-0000.json"), []);
+ writeJson(path.join(out, "transcripts", "gone", "manifest.json"), { pageCount: 0, slugToPage: {} });
+ writeJson(path.join(out, "transcripts", "gone", "page-0000.json"), []);
+ writeJson(path.join(out, "transcripts", "gone", "page-0001.json"), []);
+ writeJson(path.join(out, "digests", "gone", "manifest.json"), { pageCount: 0, slugToPage: {} });
+ // A real member's tree is not probed.
+ writeJson(path.join(out, "transcripts", "kept", "manifest.json"), { pageCount: 1, slugToPage: { a: 0 } });
+ const c = ctx(fx, TOKEN);
+ const res = await runDeployStage(c, { kind: "deploy-site", target: "anilyzer" });
+ assert.equal(res.status, "ran");
+ const probed = [
+ "posts/jer-x/manifest.json",
+ "posts/jer-x/page-0000.json",
+ "transcripts/gone/manifest.json",
+ "transcripts/gone/page-0000.json",
+ "digests/gone/manifest.json",
+ ];
+ for (const rel of probed) {
+ assert.ok(c.asked.includes(`https://anilyzer.example.test/${rel}`), rel);
+ assert.ok(c.asked.includes(`https://anilyzer.example.test/${rel}?cb=built-anilyzer-1`), `${rel} busted`);
+ }
+ assert.ok(!c.asked.some((u) => u.includes("/kept/") || u.includes("page-0001")), c.asked.join("\n"));
+ const rec = await deployedOf(fx, "anilyzer");
+ assert.equal(rec.production?.liveCheck?.verdict, "ok");
+ assert.deepEqual(rec.production?.liveCheck?.tombstones?.map((t) => t.path), probed);
+ assert.ok(c.lines.some((l) => /5 withdrawn path\(s\) read as tombstones/.test(l)), c.lines.join(""));
+ } finally {
+ fx.cleanup();
+ }
+});
+
test("a stale edge is a WARNING: the deploy is recorded with its verdict and the stage succeeds", async () => {
const fx = fixture();
try {
diff --git a/common/publish/deployStage.ts b/common/publish/deployStage.ts
@@ -61,6 +61,7 @@ import {
siteDeployProblem,
} from "../lib/builtExport";
import { getHomepageConfig } from "../lib/homepage";
+import { tombstonedTreesInHeaders } from "./tombstones";
import {
CLOUDFLARE_AUTH_REFUSED,
PRODUCTION_BRANCH,
@@ -199,6 +200,25 @@ function hubTombstoneProbes(outDir: string): string[] {
return out;
}
+// A site bundle's tombstone paths worth probing (release 24 H1): per tree its
+// `_headers` declares withdrawn — a withheld X channel's posts, a departed
+// channel's transcripts/subs/posts/digests — its manifest and first page.
+function siteTombstoneProbes(outDir: string): string[] {
+ let headers: string;
+ try {
+ headers = readFileSync(path.join(outDir, "_headers"), "utf8");
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (const { tree, slug } of tombstonedTreesInHeaders(headers)) {
+ if (!existsSync(path.join(outDir, tree, slug, "manifest.json"))) continue;
+ out.push(`${tree}/${slug}/manifest.json`);
+ if (existsSync(path.join(outDir, tree, slug, "page-0000.json"))) out.push(`${tree}/${slug}/page-0000.json`);
+ }
+ return out;
+}
+
function readdirSyncDirs(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory())
@@ -538,7 +558,12 @@ export async function runDeployStage(
builtStampId: b.stampId,
expected: req.kind === "deploy-homepage" ? null : (b.corpusGeneratedAt ?? bundleGeneratedAt(outDir)),
path: req.kind === "deploy-homepage" ? "" : "corpus.json",
- tombstones: req.kind === "deploy-hub" ? hubTombstoneProbes(outDir) : undefined,
+ tombstones:
+ req.kind === "deploy-hub"
+ ? hubTombstoneProbes(outDir)
+ : req.kind === "deploy-site"
+ ? siteTombstoneProbes(outDir)
+ : undefined,
},
{ env, signal, ...ctx.liveCheck },
);
diff --git a/common/publish/liveCheck.ts b/common/publish/liveCheck.ts
@@ -29,7 +29,9 @@
//
// The hub's deploy also probes its TOMBSTONES (publish/tombstones.ts): each
// path must answer, plain and busted, with the empty object that replaced the
-// withdrawn content.
+// withdrawn content. A site's deploy probes its own since release 24 H1 (each
+// tree its `_headers` declares withdrawn: a withheld X channel's posts, a
+// departed channel's trees).
//
// Everything that touches the network or the clock is injected: `fetch`,
// `sleep`, `now`, `env`.
diff --git a/common/publish/tombstones.test.ts b/common/publish/tombstones.test.ts
@@ -13,8 +13,16 @@ import {
import { tmpdir } from "node:os";
import path from "node:path";
import type { Paths } from "../lib/paths";
+import { renderHeadersFile, SITE_CORS_PATHS } from "../lib/archive/headers";
+import { isTombstoneChannelDir } from "../lib/builtExport";
import {
emptyPostsManifest,
+ hubNameableChannels,
+ lastBundleDir,
+ servedChannelTrees,
+ tombstonedTreesInHeaders,
+ tombstoneTreeManifest,
+ writeDepartedTombstones,
tombstoneChannelManifest,
tombstoneNoStoreForHub,
tombstoneNoStoreForSite,
@@ -174,3 +182,135 @@ test("withdrawnXChannels: the X channels with a shared posts tree that a non-pri
rmSync(root, { recursive: true, force: true });
}
});
+
+// --- release 24 H1: channels that leave a site's published pool -------------
+
+test("servedChannelTrees: every channel tree a bundle serves, with its page count; none without a bundle", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "tombstones-"));
+ try {
+ const out = path.join(root, "out");
+ sharedTree(path.join(out, "transcripts"), "b-chan", 2);
+ sharedTree(path.join(out, "transcripts"), "a-chan", 1);
+ // A manifest-only tree (a social channel's transcripts) is served too.
+ writeJson(path.join(out, "transcripts", "social", "manifest.json"), { pageCount: 0, slugToPage: {} });
+ // Pages are counted by the highest index, not by how many there are.
+ writeJson(path.join(out, "subs", "b-chan", "page-0003.json"), []);
+ sharedTree(path.join(out, "digests"), "a-chan", 1);
+ writeJson(path.join(out, "posts", "x", "manifest.json"), tombstoneChannelManifest("x", "T"));
+ // Not a served tree: an empty dir, a stray file, a site manifest.
+ mkdirSync(path.join(out, "digests", "empty"), { recursive: true });
+ writeJson(path.join(out, "transcripts", "manifest.json"), {});
+ writeJson(path.join(out, "stats", "a-chan", "page-0000.json"), []);
+ assert.deepEqual(await servedChannelTrees(out), [
+ { tree: "transcripts", slug: "a-chan", pages: 1 },
+ { tree: "transcripts", slug: "b-chan", pages: 2 },
+ { tree: "transcripts", slug: "social", pages: 0 },
+ { tree: "subs", slug: "b-chan", pages: 4 },
+ { tree: "posts", slug: "x", pages: 0 },
+ { tree: "digests", slug: "a-chan", pages: 1 },
+ ]);
+ assert.deepEqual(await servedChannelTrees(path.join(root, "absent")), []);
+ assert.equal(
+ lastBundleDir({ exportBuildsDir: "/b" } as Paths, "pub"),
+ path.join("/b", "pub", "out"),
+ );
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("tombstoneTreeManifest: each tree's manifest shape at pageCount 0, with no size and no tracks", () => {
+ for (const tree of ["transcripts", "subs", "digests"] as const) {
+ const m = tombstoneTreeManifest(tree, "gone", "T");
+ assert.equal(m.channelSlug, "gone");
+ assert.equal(m.pageCount, 0);
+ assert.equal(m.maxPageBytes, 0);
+ assert.deepEqual(m.slugToPage, {});
+ assert.equal(m.generatedAt, "T");
+ assert.equal(typeof m.version, "number");
+ assert.equal("pageHashes" in m, false);
+ }
+ assert.deepEqual(tombstoneTreeManifest("subs", "gone", "T").tracks, []);
+ assert.equal("tracks" in tombstoneTreeManifest("transcripts", "gone", "T"), false);
+ assert.deepEqual(tombstoneTreeManifest("posts", "gone", "T"), tombstoneChannelManifest("gone", "T"));
+});
+
+test("writeDepartedTombstones: a tombstone for each served tree public/ no longer holds, path for path", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "tombstones-"));
+ try {
+ const pub = path.join(root, "public");
+ // Held now: a member's real tree, and a tombstone written earlier in this
+ // compose (a withheld X channel's) — both left alone.
+ sharedTree(path.join(pub, "transcripts"), "member", 1);
+ writeJson(path.join(pub, "posts", "x", "manifest.json"), tombstoneChannelManifest("x", "earlier"));
+ // A worktree's linked tree root: replaced by public/'s own, its target untouched.
+ const primary = path.join(root, "primary", "subs");
+ writeJson(path.join(primary, "other", "page-0000.json"), [{ id: "keep" }]);
+ symlinkSync(primary, path.join(pub, "subs"));
+ const served = [
+ { tree: "transcripts" as const, slug: "member", pages: 1 },
+ { tree: "transcripts" as const, slug: "gone", pages: 3 },
+ { tree: "subs" as const, slug: "gone", pages: 1 },
+ { tree: "posts" as const, slug: "x", pages: 2 },
+ { tree: "digests" as const, slug: "gone", pages: 0 },
+ ];
+ const written = await writeDepartedTombstones({ publicDir: pub, served, generatedAt: "T" });
+ assert.deepEqual(written, served.filter((t) => t.slug === "gone"));
+ assert.deepEqual(readdirSync(path.join(pub, "transcripts", "gone")).sort(), [
+ "manifest.json",
+ "page-0000.json",
+ "page-0001.json",
+ "page-0002.json",
+ ]);
+ for (const t of written) assert.ok(isTombstoneChannelDir(path.join(pub, t.tree, t.slug)), t.tree);
+ assert.deepEqual(readdirSync(path.join(pub, "digests", "gone")), ["manifest.json"]);
+ assert.deepEqual(readJson(path.join(pub, "subs", "gone", "manifest.json")).tracks, []);
+ assert.deepEqual(readJson(path.join(pub, "transcripts", "member", "page-0000.json")), [{ id: "p0" }]);
+ assert.equal(readJson(path.join(pub, "posts", "x", "manifest.json")).generatedAt, "earlier");
+ assert.deepEqual(readJson(path.join(primary, "other", "page-0000.json")), [{ id: "keep" }]);
+ assert.equal(existsSync(path.join(primary, "gone")), false, "never written through the link");
+ // Nothing served, nothing written.
+ assert.deepEqual(await writeDepartedTombstones({ publicDir: path.join(root, "none"), served: [] }), []);
+ assert.equal(existsSync(path.join(root, "none")), false);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("a site's no-store paths name each departed tree; its _headers says which trees a deploy probes", () => {
+ const departed = [
+ { tree: "transcripts" as const, slug: "gone", pages: 1 },
+ { tree: "subs" as const, slug: "gone", pages: 1 },
+ ];
+ // No posts tombstone: the posts manifest is not named.
+ assert.deepEqual(tombstoneNoStoreForSite([], departed), ["/transcripts/gone/*", "/subs/gone/*"]);
+ assert.deepEqual(
+ tombstoneNoStoreForSite([{ slug: "a-x", pages: 1 }], [{ tree: "posts", slug: "gone", pages: 0 }, ...departed]),
+ ["/posts/manifest.json", "/posts/a-x/*", "/posts/gone/*", "/transcripts/gone/*", "/subs/gone/*"],
+ );
+ const headers = renderHeadersFile("compose-site.ts", SITE_CORS_PATHS, {
+ noStore: tombstoneNoStoreForSite([{ slug: "a-x", pages: 1 }], departed),
+ });
+ // The CORS block's `/transcripts/*` is not a tombstone; the manifest rule is no tree.
+ assert.deepEqual(tombstonedTreesInHeaders(headers), [
+ { tree: "posts", slug: "a-x" },
+ { tree: "transcripts", slug: "gone" },
+ { tree: "subs", slug: "gone" },
+ ]);
+ assert.deepEqual(tombstonedTreesInHeaders(renderHeadersFile("compose-site.ts", SITE_CORS_PATHS)), []);
+ assert.deepEqual(tombstonedTreesInHeaders(""), []);
+});
+
+test("hubNameableChannels: the pools of the sites that are not private, never a cited-only slug", () => {
+ const members = (...slugs: string[]) => slugs.map((slug) => ({ slug, groupId: "default" }));
+ assert.deepEqual(
+ [
+ ...hubNameableChannels([
+ { channels: members("a", "b") },
+ { audience: "public", channels: members("c"), citedChannels: [{ slug: "cited" }] } as never,
+ { audience: "private", channels: members("mine", "a") },
+ ]),
+ ].sort(),
+ ["a", "b", "c"],
+ );
+});
diff --git a/common/publish/tombstones.ts b/common/publish/tombstones.ts
@@ -23,10 +23,25 @@
//
// The writers go through bin/_publicFile.ts: in a worktree, public/'s entries
// are links into the primary checkout, and nothing here writes through one.
+//
+// RELEASE 24 H1 — A CHANNEL THAT LEAVES A SITE'S PUBLISHED POOL (removed from
+// `channels`, or moved to `citedChannels`) is withdrawn the same way: every
+// per-channel path the site's LAST BUNDLE served for it — `transcripts/`,
+// `subs/`, `posts/` and `digests/<slug>/`, manifest and pages — ships as a
+// tombstone of the same shape, served no-store. "What the site published
+// before" is that bundle, `<exportBuildsDir>/<siteId>/out` (servedChannelTrees),
+// read before the build replaces it: it is the one record of the exact paths
+// (and page counts) a deploy of that build shipped; no stamp lists them. A
+// bundle's own tombstones are served paths too, so they are carried into the
+// next build for as long as the channel stays out — a build that is never
+// deployed cannot drop them before one that is. A cited-only channel's moment
+// pages and clips (`m/`, `media/`) still publish and are never tombstoned.
import path from "node:path";
-import { readdir, readFile, rm } from "node:fs/promises";
+import { lstat, readdir, readFile, rm } from "node:fs/promises";
import type { Paths } from "../lib/paths";
+import { SUBS_CHANNEL_MANIFEST_VERSION, TRANSCRIPTS_MANIFEST_VERSION } from "../lib/manifest";
+import { DIGESTS_MANIFEST_VERSION } from "../lib/digests";
import {
POSTS_MANIFEST_VERSION,
SITE_POSTS_MANIFEST_VERSION,
@@ -38,6 +53,7 @@ import { isXPostsChannel, xPostsVisibility } from "../lib/postsVisibility";
import { isPrivateSite, type Site } from "../lib/siteSchema";
import { readChannelConfig } from "../controller/channels";
import { ownDir, writePublicFile } from "../bin/_publicFile";
+import { targetDir } from "./stamps";
// One channel's tombstone: its slug and how many empty pages stand in for it.
export type PostsTombstone = { slug: string; pages: number };
@@ -133,10 +149,22 @@ export function tombstonePaths(
return out;
}
-/** A site's no-store paths: its posts manifest and each tombstoned tree. */
-export function tombstoneNoStoreForSite(tombstones: readonly PostsTombstone[]): string[] {
- if (tombstones.length === 0) return [];
- return ["/posts/manifest.json", ...tombstones.map((t) => `/posts/${t.slug}/*`)];
+/**
+ * A site's no-store paths: its posts manifest (when any posts tree is a
+ * tombstone) and each tombstoned tree — the withheld X channels' posts, then
+ * each departed channel's trees (release 24 H1).
+ */
+export function tombstoneNoStoreForSite(
+ tombstones: readonly PostsTombstone[],
+ departed: readonly ChannelTreeTombstone[] = [],
+): string[] {
+ if (tombstones.length === 0 && departed.length === 0) return [];
+ const posts = tombstones.length > 0 || departed.some((t) => t.tree === "posts");
+ return [
+ ...(posts ? ["/posts/manifest.json"] : []),
+ ...tombstones.map((t) => `/posts/${t.slug}/*`),
+ ...departed.map((t) => `/${t.tree}/${t.slug}/*`),
+ ];
}
/** The hub's no-store paths: its whole posts tree, which holds only tombstones. */
@@ -160,11 +188,7 @@ export async function withdrawnXChannels(
sites: readonly Pick<Site, "audience" | "channels">[],
): Promise<string[]> {
if (xPostsVisibility(settings) !== "private") return [];
- const onPublicSite = new Set<string>();
- for (const site of sites) {
- if (isPrivateSite(site)) continue;
- for (const c of site.channels) onPublicSite.add(c.slug);
- }
+ const onPublicSite = hubNameableChannels(sites);
let entries: string[];
try {
entries = (await readdir(paths.exportSharedPostsDir, { withFileTypes: true }))
@@ -181,3 +205,164 @@ export async function withdrawnXChannels(
}
return out;
}
+
+/**
+ * The channels the hub may NAME: every member (`channels`, the pool) of a site
+ * whose audience is not private — the release 18 rule (review H1): private
+ * data is never named on the hub. A channel only private sites carry, one only
+ * cited (`citedChannels`), or one no site carries is not here.
+ */
+export function hubNameableChannels(
+ sites: readonly Pick<Site, "audience" | "channels">[],
+): Set<string> {
+ const out = new Set<string>();
+ for (const site of sites) {
+ if (isPrivateSite(site)) continue;
+ for (const c of site.channels) out.add(c.slug);
+ }
+ return out;
+}
+
+// --- release 24 H1: channels that leave a site's published pool -------------
+
+/** The per-channel trees a bundle publishes a channel's corpus in. */
+export const CHANNEL_TOMBSTONE_TREES = ["transcripts", "subs", "posts", "digests"] as const;
+export type ChannelTree = (typeof CHANNEL_TOMBSTONE_TREES)[number];
+
+/** One served (or tombstoned) channel tree: its tree, slug and page count. */
+export type ChannelTreeTombstone = { tree: ChannelTree; slug: string; pages: number };
+
+/** `<exportBuildsDir>/<target>/out`: the bundle the target's last build left. */
+export function lastBundleDir(paths: Pick<Paths, "exportBuildsDir">, target: string): string {
+ return path.join(targetDir(paths, target), "out");
+}
+
+const PAGE_FILE = /^page-(\d+)\.json$/;
+
+/**
+ * Every per-channel tree `outDir` (a built bundle) serves — `<tree>/<slug>/`
+ * under the four channel trees, real or tombstone — with its page count (the
+ * highest `page-NNNN.json` + 1). A dir with neither a manifest nor a page is
+ * not a served tree. None when the bundle is absent. Sorted by tree, then slug.
+ */
+export async function servedChannelTrees(outDir: string): Promise<ChannelTreeTombstone[]> {
+ const out: ChannelTreeTombstone[] = [];
+ for (const tree of CHANNEL_TOMBSTONE_TREES) {
+ let entries;
+ try {
+ entries = await readdir(path.join(outDir, tree), { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ const slugs = entries
+ .filter((e) => e.isDirectory())
+ .map((e) => e.name)
+ .sort();
+ for (const slug of slugs) {
+ let files: string[];
+ try {
+ files = await readdir(path.join(outDir, tree, slug));
+ } catch {
+ continue;
+ }
+ let pages = 0;
+ for (const f of files) {
+ const m = PAGE_FILE.exec(f);
+ if (m) pages = Math.max(pages, Number(m[1]) + 1);
+ }
+ if (pages === 0 && !files.includes("manifest.json")) continue;
+ out.push({ tree, slug, pages });
+ }
+ }
+ return out;
+}
+
+/**
+ * The channel manifest a tree tombstone ships: the tree's own manifest shape
+ * at pageCount 0, with no pages, no size and (subs) no tracks.
+ */
+export function tombstoneTreeManifest(
+ tree: ChannelTree,
+ slug: string,
+ generatedAt: string,
+): Record<string, unknown> {
+ if (tree === "posts") return tombstoneChannelManifest(slug, generatedAt);
+ const version =
+ tree === "transcripts"
+ ? TRANSCRIPTS_MANIFEST_VERSION
+ : tree === "subs"
+ ? SUBS_CHANNEL_MANIFEST_VERSION
+ : DIGESTS_MANIFEST_VERSION;
+ return {
+ version,
+ channelSlug: slug,
+ pageCount: 0,
+ maxPageBytes: 0,
+ generatedAt,
+ ...(tree === "subs" ? { tracks: [] } : {}),
+ slugToPage: {},
+ };
+}
+
+async function present(p: string): Promise<boolean> {
+ try {
+ await lstat(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Write a tombstone under `publicDir` for every tree in `served` (what the last
+ * bundle served) that `publicDir` does not serve now — a channel that left the
+ * pool, or a tree a member no longer has: its manifest at pageCount 0 and `[]`
+ * for each page the bundle held. A tree `publicDir` holds (a member's, or a
+ * tombstone written earlier in this compose) is left alone. Returns what was
+ * written, in `served` order.
+ */
+export async function writeDepartedTombstones(opts: {
+ publicDir: string;
+ served: readonly ChannelTreeTombstone[];
+ generatedAt?: string;
+}): Promise<ChannelTreeTombstone[]> {
+ const generatedAt = opts.generatedAt ?? new Date().toISOString();
+ const written: ChannelTreeTombstone[] = [];
+ for (const t of opts.served) {
+ const treeDir = path.join(opts.publicDir, t.tree);
+ const dir = path.join(treeDir, t.slug);
+ if (await present(dir)) continue;
+ await ownDir(treeDir);
+ await ownDir(dir);
+ await writePublicFile(
+ path.join(dir, "manifest.json"),
+ JSON.stringify(tombstoneTreeManifest(t.tree, t.slug, generatedAt)),
+ );
+ for (let i = 0; i < t.pages; i++) {
+ await writePublicFile(path.join(dir, postsPageFileName(i)), "[]");
+ }
+ written.push({ ...t });
+ }
+ return written;
+}
+
+/**
+ * The tombstoned channel trees a bundle's `_headers` declares no-store
+ * (`/<tree>/<slug>/*` in its "Withdrawn content" block): what a deploy's live
+ * check probes on a site. The bundle's own word — a real manifest-only tree
+ * (a social channel's transcripts, pageCount 0) reads like a tombstone on
+ * disk, but is never in that block.
+ */
+export function tombstonedTreesInHeaders(headers: string): { tree: ChannelTree; slug: string }[] {
+ const out: { tree: ChannelTree; slug: string }[] = [];
+ const lines = headers.split("\n");
+ const start = lines.findIndex((l) => l.startsWith("# Withdrawn content"));
+ if (start < 0) return out;
+ const rule = new RegExp(`^/(${CHANNEL_TOMBSTONE_TREES.join("|")})/([^/*]+)/\\*$`);
+ for (const line of lines.slice(start + 1)) {
+ if (line.startsWith("#")) break;
+ const m = rule.exec(line.trim());
+ if (m) out.push({ tree: m[1] as ChannelTree, slug: m[2] });
+ }
+ return out;
+}
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -760,7 +760,9 @@ async function runManagedDownload(
// EVERY PREFETCH REWRITES metadata.info.json (no existence check — the
// filters decide on today's metadata), so each spawn runs inside the
// history wrap: what moved since the last version is appended to
- // metadata.history.json. The file yt-dlp writes is still the file.
+ // metadata.history.json. The file yt-dlp writes is still the file, less
+ // any field a provenance writer set that the rewrite reverted (a Wayback
+ // copy's title and date: release 24 H3, keepProvenanceFields).
const prefetchHistory = {
by: "prefetch" as const,
...(opts.persistOrigin?.requestedBy
diff --git a/common/ytdlp/forceMedia.test.ts b/common/ytdlp/forceMedia.test.ts
@@ -19,6 +19,7 @@ import {
type ManagedDownloadOpts,
} from "./downloadOneManaged";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
+import { patchMetadataInfo } from "../lib/metadataHistory-server";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/forceMedia.test.ts
@@ -104,6 +105,8 @@ async function runWith(opts: {
// The media pass (the source-media output) fails with a 403 after writing a
// partial.
mediaFail?: boolean;
+ // Anything else the video dir holds before the run (after priorMeta).
+ seed?: (videoDir: string) => Promise<void>;
}): Promise<Run & { cleanup: () => Promise<void> }> {
const root = await mkdtemp(path.join(tmpdir(), "force-media-"));
const ytdlp = path.join(root, "fake-ytdlp.cjs");
@@ -134,6 +137,7 @@ async function runWith(opts: {
JSON.stringify(opts.priorMeta),
);
}
+ await opts.seed?.(videoDir);
let log = "";
const record = await downloadOneManaged({
channelSlug: "c",
@@ -319,6 +323,41 @@ test("the prefetch's rewrite of metadata.info.json lands in metadata.history.jso
}
});
+// RELEASE 24 H3: "Persist source video" over a record whose title and date a
+// provenance writer set (a Wayback copy's, as the operator found them): the
+// prefetch's rewrite from the bare source keeps them, a field the source
+// genuinely adds still lands, and the prefetch's history entry is written.
+test("a persist prefetch keeps the title and date a provenance writer set, and records its own rewrite", async () => {
+ const placeholder = { ...META, title: ID };
+ const r = await runWith({
+ meta: { ...placeholder, view_count: 7 },
+ priorMeta: placeholder,
+ seed: (videoDir) =>
+ patchMetadataInfo(
+ videoDir,
+ { title: "The Real Title", upload_date: "20190405" },
+ { by: "wayback-provenance", requestedBy: "cli" },
+ ).then(() => undefined),
+ transcript: TRANSCRIPT,
+ managed: FORCED,
+ });
+ try {
+ const info = JSON.parse(await readFile(path.join(r.videoDir, "metadata.info.json"), "utf8"));
+ assert.equal(info.title, "The Real Title");
+ assert.equal(info.upload_date, "20190405");
+ assert.equal(info.view_count, 7);
+ assert.match(r.log, /Kept what the provenance set over this rewrite: title, upload_date/);
+ const h = JSON.parse(
+ await readFile(path.join(r.videoDir, "metadata.history.json"), "utf8"),
+ ) as { entries: Array<Record<string, unknown>> };
+ assert.deepEqual(h.entries.map((e) => e.by), ["wayback-provenance", "prefetch"]);
+ assert.deepEqual(h.entries[1].changed, {});
+ assert.deepEqual(h.entries[1].counters, { view_count: [null, 7] });
+ } finally {
+ await r.cleanup();
+ }
+});
+
// A FAILED MEDIA PASS OVER A TRANSCRIPT IS NOT A FAILED DOWNLOAD (release 11
// slice O3; release 10 slice N's review L2). The subtitle pass succeeded and the
// transcript is on disk; the extra the caller asked for — the source — failed.
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **A channel taken off a site, or moved to its cited scope, is withdrawn at the edge.** The next build of the site replaces every `transcripts/`, `subs/`, `posts/` and `digests/` path its last build served for that channel with an empty file of the same shape, served no-store (the way withheld X posts already are), and keeps doing so while the channel stays out. The channel's cited moments and clips still publish. A site's deploy now reads its withdrawn paths back in its live check, as the hub's does.
+- **Persisting a Wayback or archive.org record no longer undoes its title and date.** A re-download that rewrites `metadata.info.json` keeps the title, upload date and other fields `archilyzer wayback refresh --titles`, `archive-org refresh` or the feed backfill set, when the source only has its placeholder for them; a value the source genuinely changed still lands. A record a persist already reverted gets them back on its next download.
- **A site's reports can cite a channel the site does not publish.** A channel row outside the site's pool on the site form now has a **Cited only** box (`citedChannels` in site.json — see SITE.md); `/sites` shows "· N cited" beside the channel count. A report on that site may cite the channel: its moment pages and their clips publish, but not its browse page, transcripts, search entry or corpus.json entry, and its moments link no corpus page. A channel in the pool is never cited-only: ticking **Include** clears the box. A citation of a channel in neither list is still refused at compose (`not-in-site`), and the refusal now names both keys. A build or deploy whose bundle holds a cited-only channel's transcripts, subs, posts, digests, stats or archives, or lists it in corpus.json or site.json, is refused; a change to its transcripts or posts makes the site stale. Renaming a channel renames it in `citedChannels` too, and `pnpm ops get sites` lists the key. A site padding its pool with a channel only to cite it can move the channel to **Cited only**. Needs a restart of the editor for the form; rebuild each site that uses it.
- **"Clear failure list" keeps its log on screen.** On a channel's Transcribe stage, clearing the failed-transcriptions list hid the controls the moment the list emptied, its output ("Cleared N entries") with them. They now stay until the page is reloaded, the button disabled at (0).
- **archive.org imports take many items, or a search.** `pnpm ops import-archive-org` now takes `"items"` (identifiers, or `{item, files | match}`) or `"query"` (an archive.org search, its first `"limit"` items) as one job, paced between files and between items. Records already held — on disk or in the saved-video store — are skipped; a dry run lists every file as held, RESTRICTED (archive.org will not hand it out) or would-get; three items in a row refused by archive.org stop the job and back the platform off.
diff --git a/plans/release-24.md b/plans/release-24.md
@@ -26,3 +26,112 @@ worker, same results), then S5's per-worker servers if time allows. Record: `e2e
- Prune merged worktrees and branches (ruled 2026-10-10): the merged `r18-*` and `r20-*` worktrees; `r20/twitch-ids`
is kept.
- The source verify no longer probes the retired `source.archilyzer.pages.dev` alias (a script outside the repo).
+
+## Record
+
+Lane A (`r24/hygiene` off `r24/integration` `72c44159`), H1 → H4, tsc clean per commit. Every fixture is synthetic;
+nothing read the corpus.
+
+### H1, as shipped — tombstones for a channel that leaves a site's scope
+
+**What the site published before is its last bundle**, `<exportBuildsDir>/<siteId>/out`
+(`tombstones.ts` `lastBundleDir`), read by compose before the build replaces it, and only when its `site.json` names the
+site. Ruling: the bundle is the one record of the exact paths and page counts a deploy of that build shipped. No stamp
+lists them: `built.json` and `deployed.json` carry ids, counts and live checks, the compose cache only signatures of
+member trees, and `public/` is shared by every site's compose.
+
+- **Site** (`compose-site.ts`, after the X tombstones): `servedChannelTrees` lists every `transcripts/`, `subs/`,
+ `posts/` and `digests/<slug>/` the bundle served. `writeDepartedTombstones` writes a tombstone path for path for
+ each tree this compose does not ship: the tree's manifest at `pageCount: 0` (`tombstoneTreeManifest`: no size, no
+ `slugToPage`, `tracks: []` on subs, no `pageHashes`) and `[]` for each page the bundle held. A tree `public/` holds
+ (a member's, or an X tombstone) is left alone. The trees are served no-store (`tombstoneNoStoreForSite(x,
+ departed)`; `/posts/manifest.json` only when a posts tree is a tombstone). An empty site posts manifest is written as
+ for X tombstones. **Carried:** a bundle's tombstones are served paths, so they are written again while the channel
+ stays out. A channel back in the pool gets its real trees, and a tree it has none of stays a tombstone. A cited-only
+ channel's `m/` and `media/` are not touched.
+- **Hub** (`compose-hub.ts`): the hub's channel paths are its tombstones (`builtHubProblem` allows nothing else). Its
+ last bundle's posts tombstones are carried while the release 18 rule allows naming the channel
+ (`hubNameableChannels`: a non-private site's pool; `withdrawnXChannels` now uses it). A channel moved to a cited
+ scope, kept only by private sites, or on no site is never named, carried or not.
+- **Live check:** a site's deploy probes the trees its bundle's `_headers` declares withdrawn
+ (`tombstonedTreesInHeaders` → `deployStage.ts` `siteTombstoneProbes`, manifest + first page, plain and busted). The
+ bundle's own word: a real manifest-only tree reads like a tombstone on disk. This closes release 18's "a site's
+ live check does not probe its tombstones".
+- **Guard:** `builtCitedOnlyProblem` accepts a tombstone of any of the four trees (`isTombstoneChannelDir`, renamed
+ from `isTombstoneChannelPostsDir`; it now also refuses a non-empty `tracks` or `pageHashes`). The cited-only proving
+ test asks it over the tombstoned `public/` (clean) and over the last bundle (refused).
+- PUBLISH.md: "Tombstones for a channel that leaves a site".
+
+**Found and left.** A docker-runner build sees no last bundle in its container (`EXPORT_BUILDS_DIR` is the
+container's), so it writes no departed tombstones. A site switched to `search: false` (a cited site) composes no
+corpus and writes none either (`citedBuildProblem` refuses every corpus tree). Archive zips (`archives/`) and per-site
+aggregates (summaries, stats) are rewritten at the same paths and are not tombstoned. Departed tombstones never
+expire.
+
+### H2, as shipped — temp-dir test robustness
+
+`attachMedia` and `preparePlayable` take `deps.freeBytes` (default `getFreeBytes`, as `probeDuration`/`probe` are).
+Their fixtures hand in 1 TiB. One test each judges the 2 GiB margin with a fake: the exact stop sentence, nothing
+copied or remuxed, and the disk asked. `umtool/lib/articles/sources.test.mjs` compares through the `tildify` the code
+applies. Product behaviour unchanged.
+
+### H3, as shipped — persist-videos keeps provenance
+
+**The mark is the history.** Nothing in `metadata.info.json` marks a provenance-applied field. Each
+`wayback-provenance`, `archiveorg-provenance` and `feed-backfill` entry in `metadata.history.json` names the key, the
+value written and the value replaced (`PROVENANCE_WRITERS`, the writers `refreshVideoMetadata.ts` already refuses
+over).
+
+- `withMetadataHistory` runs `keepProvenanceInFile` before it records the entry, after any writer that is not a
+ provenance writer: prefetch, audio-check, download-one, archiveorg-import, refresh, local-archive.
+- Rule (`keepProvenanceFields`, pure): a key a provenance entry set comes back at the newest provenance value when the
+ rewrite lacks it, or carries a value a provenance entry replaced. That is the capture's placeholder, or an earlier
+ find a later one superseded. Any other value is the source's and lands.
+- A restored title goes right after `id` (the 16 KB head reader). Anything else absent goes at the end (`upload_date`:
+ the 8 KB tail reader).
+- A record a pre-H3 prefetch already reverted heals on its next rewrite. The rewrite's own entry is still written,
+ net of the kept fields.
+- A value the history holds only as a digest (over 16 KB) is not restored.
+
+**Found and left.** The history keeps 200 entries: a record rewritten 200 times after its provenance entry loses the
+claim. The records already reverted on disk heal only when next re-downloaded; `archilyzer wayback refresh --titles`
+still mends them offline.
+
+### H4, as shipped — umtool `mix.spec` order dependence
+
+**Already fixed by release 19 B5 (`10042c2d`), verified here: no code change.** `mix.spec.ts` moves the fixture
+corpus's clip windows (`channels/*/data/*/clips/`) aside in `beforeAll` and puts them back in `afterAll`. A run killed
+part-way is restored at the next start. The memory this slice was raised from predates B5's merge, and no full umtool
+run since B5 lists a `mix.spec` red (release 19's full run: all 12 passed; the overnight 2026-10-10 rounds: 14 reds,
+none of them mix).
+
+**How the config orders files:** `workers: 1`, `fullyParallel: false`. Files run in path order whatever order the CLI
+names them, so `clip-bench` always runs before `mix` in a run that holds both, as in the full suite. The reverse order
+was forced with an untracked copy of `mix.spec.ts` that sorts first (`a-mix-first.spec.ts`), deleted after the run.
+After the first run `testchan/vid1/clips/0.00-14.00.mp4`, clip-bench's editor-stub window, was back on disk: mix had
+set it aside and restored it.
+
+### Commits
+
+| Commit | What |
+|---|---|
+| `2fbb5fdc` | `common:` H1 — departed-channel tombstones on the site and the hub, the site live check's tombstone probes, `isTombstoneChannelDir`; PUBLISH.md |
+| `60cea572` | `common, umtool:` H2 — `deps.freeBytes` in attachMedia/preparePlayable and their tests; `sources.test.mjs` through `tildify` |
+| `198d4a8f` | `common:` H3 — `keepProvenanceFields` / `keepProvenanceInFile` in the history wrap |
+| — | H4: no commit (release 19 B5 `10042c2d` fixed it; verified above) |
+| this commit | `plans:` this record; `editor/CHANGELOG.md` (two bullets at the start of `[Unreleased]`) |
+
+### Gates
+
+| Gate | Result |
+| --- | --- |
+| tsc (`pnpm -r … tsc --noEmit`), each code commit | clean ×3 (this commit is docs only) |
+| H1 touched files | `compose-site.departed.test.ts` (new) 3/3; `tombstones.test.ts` 9/9 (+5); `compose-hub.test.ts` 8/8 (+1); `deployStage.test.ts` 16/16 (+1); `builtExport.test.ts` 22/22 (extended); compose-site + postsVisibility + composeReports + headers + liveCheck + build + lib/postsVisibility 68/68 |
+| H2 | `attachMedia.test.ts` 12/12 (+1) and `preparePlayable.test.ts` 6/6 (+1) with `/tmp` as is (tmpfs, 1.7 GB free; 8 + 2 failed before) and again 18/18 with `TMPDIR=$T/tmpdir` under `$HOME`; `sources.test.mjs` 2/2 both ways (1 failed before under `$HOME`) |
+| H3 | `metadataHistory-server.test.ts` 12/12 (+4: a Wayback prefetch, a reverted record healing, an archive.org re-import, superseded finds and no provenance); `metadataHistory.test.ts` 15/15 (+2); `forceMedia.test.ts` 9/9 (+1: a persist prefetch through `downloadOneManaged` with a fake yt-dlp); archive.org, feed, refresh, wayback, downloadOneManaged and persist tests 84/84 |
+| common, whole (after H3) | 3721 tests: 3720 pass, 1 fail — `relocateChannelMedia.test.ts` "reconcile: an extra and a changed file…" reported `./` as changed too (a directory-mtime timing flake; the file alone 44/44 twice; not touched by this lane). The two environmental files release 23 recorded (attachMedia 8, preparePlayable 2) pass |
+| `test:scripts` | 774: 771 pass, 3 skipped |
+| export unit | 118/118 |
+| umtool e2e `clip-bench.spec.ts mix.spec.ts` (`E2E_MODE=dev`) | 62 passed, 2.7 min (clip-bench first) |
+| umtool e2e, mix first (`a-mix-first.spec.ts` + `clip-bench.spec.ts`) | 62 passed, 2.4 min |
+| counts-only privacy greps over `72c44159..` (home paths, the operator's names and email, session links and trailers) | 0 each |
diff --git a/umtool/lib/articles/sources.test.mjs b/umtool/lib/articles/sources.test.mjs
@@ -7,7 +7,7 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
-import { clearSourcesCache, names, siteWorkspaces, sourceFor } from "./sources.mjs";
+import { clearSourcesCache, names, siteWorkspaces, sourceFor, tildify } from "./sources.mjs";
async function put(file, text) {
await mkdir(path.dirname(file), { recursive: true });
@@ -38,23 +38,27 @@ async function fixture() {
test("each layout finds its draft and generator", async () => {
const root = await fixture();
const o = { reportsRoot: root };
+ // sourceFor names a file the way a note shows it — `~/…` under the home
+ // directory — so the expectation goes through the same tildify, wherever
+ // TMPDIR puts the fixture.
+ const at = (rel) => tildify(path.join(root, rel));
const isr = await sourceFor("candalyzer", "polemic-israel", o);
- assert.equal(isr.draft, path.join(root, "candace/polemics/drafts/israel.json"));
- assert.equal(isr.generator, path.join(root, "candace/site/polemics.py"));
+ assert.equal(isr.draft, at("candace/polemics/drafts/israel.json"));
+ assert.equal(isr.generator, at("candace/site/polemics.py"));
assert.match(isr.how, /draft matched by id polemic-israel/);
const fc = await sourceFor("candalyzer", "deconstruction-fact-check", o);
assert.equal(fc.draft, undefined);
- assert.equal(fc.generator, path.join(root, "candace/site/make-report.py"));
+ assert.equal(fc.generator, at("candace/site/make-report.py"));
const skg = await sourceFor("jasolyzer-private", "polemic-skg", o);
- assert.equal(skg.draft, path.join(root, "pirate/polemics/drafts/skg.json"));
- assert.equal(skg.generator, path.join(root, "pirate/polemics/make-site.py"));
+ assert.equal(skg.draft, at("pirate/polemics/drafts/skg.json"));
+ assert.equal(skg.generator, at("pirate/polemics/make-site.py"));
// The decoy's draft id is exactly `blame`, but its workspace never names the site.
const blame = await sourceFor("jeralyzer-private", "blame", o);
- assert.equal(blame.draft, path.join(root, "quartering/polemics/drafts/blame.json"));
- assert.equal(blame.generator, path.join(root, "quartering/polemics/make-site.py"));
+ assert.equal(blame.draft, at("quartering/polemics/drafts/blame.json"));
+ assert.equal(blame.generator, at("quartering/polemics/make-site.py"));
assert.match(blame.how, /preferred over 1 other/);
assert.equal(await sourceFor("candalyzer", "no-such-report", o), null);