commit ed5f3c58fc76c31f516b72d68b1d67f0a79f5e09
parent dc676bf3e2415d4cdc4e1c6718669271dac4cbc9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 11 Oct 2026 13:47:02 -0400
common: the article store — transcripts/reports/, index.json, audience, and its one writer
Release 26 A2. An article is a report directory under transcripts/reports/
(paths.articlesDir), published by reports/index.json {"published": [ids]}
(ordered; an unlisted directory is a draft), with report.json `audience`
"public" | "private" (absent = private, D2).
lib/report/registry.ts is the writer — the patchSite of articles: locked
(in-process withJsonFileLock around an O_EXCL lock file, so a generator
outside the repo and the editor never interleave), validated (an index names
ids once; only a sound article is published; a patch may not add a problem;
a whole document must be sound) and atomic. configureArticle, setPublished,
setArticlesOrder, patchArticle, writeArticle (keeps the stored audience when
a regenerated document names none); readers listArticles, readArticleState,
readArticlesIndex, publishedArticleIds(audience).
lib/report/store.ts names where a store's report directories and staging
live (a site's pages, or the articles). REPORT.md documents both stores.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 871 insertions(+), 8 deletions(-)
diff --git a/REPORT.md b/REPORT.md
@@ -2,7 +2,14 @@
<!-- GENERATED by common/bin/file-schemas-docs.ts from the schemas and their *_FIELD_DOCS records — do not edit by hand. -->
-One cited report, format `"archilyzer-report"`, version 1, persisted to `transcripts/sites/<siteId>/reports/<reportId>/report.json` beside its `stills/` and `sources/<sourceId>/`; a relative path in it is relative to that directory. A site's `reports` list in `site.json` is the published, ordered list — see [SITE.md](SITE.md); a report directory it does not name is a draft. The schema is `common/lib/report/schema.ts`; its citations and sources are the citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` beside it holds the operator's notes on the article (umtool, `umtool notes`; [umtool/docs/notes.md](umtool/docs/notes.md)) and is never published.
+One cited report, format `"archilyzer-report"`, version 1, persisted as `report.json` in its own directory, beside its `stills/` and `sources/<sourceId>/`; a relative path in it is relative to that directory. The schema is `common/lib/report/schema.ts`; its citations and sources are the citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` beside it holds the operator's notes on the article (umtool, `umtool notes`; [umtool/docs/notes.md](umtool/docs/notes.md)) and is never published.
+
+A report lives in one of two stores:
+
+- **An article** — `transcripts/reports/<reportId>/report.json`, published by the project homepage. `transcripts/reports/index.json` — `{"published": [ids]}` — is the published, ordered list; an article directory it does not name is a draft. An article's `audience` (below) says which homepage build carries it: the public one only `"public"` articles, the private one every published article. An article may cite any channel of the corpus.
+- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, published by its site: the site's `reports` list in `site.json` is the published, ordered list — see [SITE.md](SITE.md). A page cites the site's `channels` and `citedChannels`.
+
+`index.json` and an article's `audience` are written ONLY through `common/lib/report/registry.ts` (`configureArticle`, `setPublished`, `setArticlesOrder`, `patchArticle`, `writeArticle`: locked, validated, atomic) and `pnpm ops articles-config` (`{"id", "audience"?, "published"?, "position"?}`), never by hand. Only a sound article (no problem below) is published; a patch may not add a problem to an article.
A **fact-check** (`"kind": "factcheck"`) is sections (chapters) of claims, each with a verdict and its findings. A **sweep** (`"kind": "sweep"`) is sections with no verdicts, or bodies that cite inline. Either may keep a **timeline** (`entries`): dated entries appended over time. Markdown fields (`summary`, an entry's `body`, a section's `body`, a claim's `findings`) cite with `[label](cite:<id>)`.
@@ -18,6 +25,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `version` | yes | `1`. |
| `id` | yes | The report's id: a lowercase slug (`[a-z0-9][a-z0-9-]*`, at most 64), its directory name under `reports/` and the last segment of its page, `/reports/<id>/`. Must match the directory. |
| `kind` | yes | `"factcheck"` — sections of claims, each with a verdict — or `"sweep"` — sections with no verdicts, or bodies with inline citations. |
+| `audience` | no | Who may read the report when it is an ARTICLE (in `transcripts/reports/`, published by the homepage): `"public"` — the public homepage build carries it — or `"private"` — only the private build (`archilyzer build homepage --private`, never deployed) does. Absent = `"private"`: going public is an explicit `pnpm ops articles-config`. Ignored on a site's page, which has its site's audience. |
| `series` | no | The series the report belongs to: a recurring name for its kind of report. It is shown on its own line above the title, in the accent colour, at the head of the report's page, its exports and the report list (where a report with no series shows its kind instead), and is joined to the title as `<series>: <title>` where one line names the report (a page title, a link, a cited-in entry). |
| `title` | yes | The report's title. |
| `subtitle` | no | A line under the title. |
diff --git a/common/lib/paths.ts b/common/lib/paths.ts
@@ -26,6 +26,12 @@ export type Paths = {
// intentionally not a valid siteId (SITE_ID_RE), so listSiteIds() ignores it.
// See common/lib/homepage.ts.
homepageDir: string;
+ // The ARTICLE STORE (release 26): transcripts/reports/<id>/ — one directory
+ // per article (report.json and its siblings, as a site report's directory),
+ // and index.json, the published, ordered list. Written only through
+ // common/lib/report/registry.ts. The homepage publishes it; a site's own
+ // pages stay under sitesDir/<siteId>/reports/.
+ articlesDir: string;
homepageConfigFile: string;
homepageChartTemplatesFile: string;
jobsDir: string;
@@ -236,6 +242,7 @@ export function getPaths(): Paths {
process.env.SAVED_VIDEOS_DIR ?? under(transcriptsDir, "saved-videos"),
sitesDir,
homepageDir,
+ articlesDir: under(transcriptsDir, "reports"),
homepageConfigFile: under(homepageDir, "homepage.json"),
homepageChartTemplatesFile: under(homepageDir, "chart-templates.json"),
jobsDir: under(transcriptsDir, ".jobs"),
diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts
@@ -33,16 +33,40 @@ export function renderReportMarkdown(): string {
out.push("");
out.push(
`One cited report, format \`"${REPORT_FORMAT}"\`, version ${REPORT_VERSION}, ` +
- "persisted to `transcripts/sites/<siteId>/reports/<reportId>/report.json` beside " +
- "its `stills/` and `sources/<sourceId>/`; a relative path in it is relative to " +
- "that directory. A site's `reports` list in `site.json` is the published, " +
- "ordered list — see [SITE.md](SITE.md); a report directory it does not name is a " +
- "draft. The schema is `common/lib/report/schema.ts`; its citations and sources " +
- "are the citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` " +
- "beside it holds the operator's notes on the article (umtool, `umtool notes`; " +
+ "persisted as `report.json` in its own directory, beside its `stills/` and " +
+ "`sources/<sourceId>/`; a relative path in it is relative to that directory. " +
+ "The schema is `common/lib/report/schema.ts`; its citations and sources are the " +
+ "citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` beside it " +
+ "holds the operator's notes on the article (umtool, `umtool notes`; " +
"[umtool/docs/notes.md](umtool/docs/notes.md)) and is never published.",
);
out.push("");
+ out.push("A report lives in one of two stores:");
+ out.push("");
+ out.push(
+ "- **An article** — `transcripts/reports/<reportId>/report.json`, published by the " +
+ "project homepage. `transcripts/reports/index.json` — `{\"published\": [ids]}` — is " +
+ "the published, ordered list; an article directory it does not name is a draft. " +
+ "An article's `audience` (below) says which homepage build carries it: the public " +
+ "one only `\"public\"` articles, the private one every published article. An " +
+ "article may cite any channel of the corpus.",
+ );
+ out.push(
+ "- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, " +
+ "published by its site: the site's `reports` list in `site.json` is the published, " +
+ "ordered list — see [SITE.md](SITE.md). A page cites the site's `channels` and " +
+ "`citedChannels`.",
+ );
+ out.push("");
+ out.push(
+ "`index.json` and an article's `audience` are written ONLY through " +
+ "`common/lib/report/registry.ts` (`configureArticle`, `setPublished`, " +
+ "`setArticlesOrder`, `patchArticle`, `writeArticle`: locked, validated, atomic) and " +
+ "`pnpm ops articles-config` (`{\"id\", \"audience\"?, \"published\"?, " +
+ "\"position\"?}`), never by hand. Only a sound article (no problem below) is " +
+ "published; a patch may not add a problem to an article.",
+ );
+ out.push("");
out.push(
'A **fact-check** (`"kind": "factcheck"`) is sections (chapters) of claims, each ' +
'with a verdict and its findings. A **sweep** (`"kind": "sweep"`) is sections ' +
diff --git a/common/lib/report/registry.test.ts b/common/lib/report/registry.test.ts
@@ -0,0 +1,236 @@
+// The article registry (release 26 A2): the one writer of
+// transcripts/reports/index.json and an article's `audience`. Temp stores only.
+//
+// Run with: node_modules/.bin/tsx --test lib/report/registry.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import os from "node:os";
+import path from "node:path";
+import {
+ ARTICLES_LOCK_FILENAME,
+ ArticleRegistryError,
+ articleFile,
+ articlesIndexFile,
+ configureArticle,
+ listArticles,
+ patchArticle,
+ publishedArticleIds,
+ readArticleState,
+ readArticlesIndex,
+ setArticlesOrder,
+ setPublished,
+ writeArticle,
+} from "./registry";
+
+const ROOTS: string[] = [];
+after(() => {
+ for (const r of ROOTS) rmSync(r, { recursive: true, force: true });
+});
+
+function store() {
+ const root = mkdtempSync(path.join(tmpdir(), "article-registry-"));
+ ROOTS.push(root);
+ return { articlesDir: path.join(root, "transcripts", "reports"), exportIndexDir: path.join(root, ".export-index") };
+}
+
+const doc = (id: string, over: Record<string, unknown> = {}) => ({
+ format: "archilyzer-report",
+ version: 1,
+ id,
+ kind: "sweep",
+ title: `Article ${id}`,
+ sections: [{ id: "s1", title: "One", body: "Plain words." }],
+ ...over,
+});
+
+function put(paths: ReturnType<typeof store>, id: string, value: unknown) {
+ const file = articleFile(paths, id);
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2));
+}
+
+const read = (file: string) => (existsSync(file) ? readFileSync(file, "utf8") : null);
+const json = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
+
+test("an empty store: nothing published, nothing listed", async () => {
+ const paths = store();
+ assert.deepEqual(await readArticlesIndex(paths), { published: [] });
+ assert.deepEqual(await listArticles(paths), []);
+ assert.deepEqual(await publishedArticleIds("private", paths), []);
+ assert.equal(await readArticleState("nothing", paths), null);
+});
+
+test("publish, place, move and unpublish — index.json in order; drafts listed after", async () => {
+ const paths = store();
+ for (const id of ["a", "b", "c", "d"]) put(paths, id, doc(id));
+ await setPublished("a", true, {}, paths);
+ await setPublished("b", true, {}, paths);
+ assert.deepEqual(json(articlesIndexFile(paths)), { published: ["a", "b"] });
+ await configureArticle("c", { published: true, position: 0 }, paths);
+ assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "a", "b"]);
+ // Moved: a published article's position alone.
+ const moved = await configureArticle("b", { position: 1 }, paths);
+ assert.equal(moved.position, 1);
+ assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "b", "a"]);
+ // Publishing an already-published one with no position keeps its place.
+ await setPublished("b", true, {}, paths);
+ assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "b", "a"]);
+ await setPublished("c", false, {}, paths);
+ assert.deepEqual((await readArticlesIndex(paths)).published, ["b", "a"]);
+ assert.ok(existsSync(articleFile(paths, "c")), "unpublishing keeps the article on disk");
+
+ const listed = await listArticles(paths);
+ assert.deepEqual(
+ listed.map((a) => [a.id, a.published, a.position]),
+ [
+ ["b", true, 0],
+ ["a", true, 1],
+ ["c", false, null],
+ ["d", false, null],
+ ],
+ );
+ assert.equal(listed[0].title, "Article b");
+ assert.equal(listed[0].audience, "private", "absent = private");
+ await setArticlesOrder(["a", "b"], paths);
+ assert.deepEqual((await readArticlesIndex(paths)).published, ["a", "b"]);
+});
+
+test("audience: written into report.json, absent = private; a public build carries only public articles", async () => {
+ const paths = store();
+ for (const id of ["pub", "priv", "draft"]) put(paths, id, doc(id));
+ await configureArticle("pub", { audience: "public", published: true }, paths);
+ await configureArticle("priv", { published: true }, paths);
+ await configureArticle("draft", { audience: "public" }, paths);
+ assert.equal(json(articleFile(paths, "pub")).audience, "public");
+ assert.equal("audience" in json(articleFile(paths, "priv")), false, "no audience written unasked");
+ assert.deepEqual(await publishedArticleIds("public", paths), ["pub"]);
+ assert.deepEqual(await publishedArticleIds("private", paths), ["pub", "priv"]);
+ // Back to private.
+ const st = await configureArticle("pub", { audience: "private" }, paths);
+ assert.equal(st.audience, "private");
+ assert.deepEqual(await publishedArticleIds("public", paths), []);
+ // Unchanged audience: report.json's bytes are not rewritten.
+ const before = read(articleFile(paths, "priv"));
+ await configureArticle("priv", { audience: "private" }, paths);
+ assert.equal(read(articleFile(paths, "priv")), before);
+});
+
+test("refusals come before anything is written", async () => {
+ const paths = store();
+ put(paths, "ok", doc("ok"));
+ put(paths, "bad", doc("bad", { sections: [{ id: "s1", title: "x", body: "[a](cite:nope)" }] }));
+ put(paths, "torn", "{ not json");
+ await setPublished("ok", true, {}, paths);
+ const indexBefore = read(articlesIndexFile(paths));
+ const okBefore = read(articleFile(paths, "ok"));
+ const cases: [() => Promise<unknown>, RegExp][] = [
+ [() => configureArticle("Bad Id", { published: true }, paths), /not an article id/],
+ [() => configureArticle("missing", { published: true }, paths), /no article "missing"/],
+ [() => configureArticle("ok", { audience: "everyone" as never }, paths), /audience must be one of public, private/],
+ [() => configureArticle("bad", { published: true }, paths), /cannot be published while report.json has problems[\s\S]*cite:nope|cannot be published/],
+ [() => configureArticle("torn", { published: true }, paths), /unparseable/],
+ [() => configureArticle("bad", { position: 0 }, paths), /is a draft/],
+ [() => configureArticle("ok", { published: false, position: 0 }, paths), /not one being unpublished/],
+ [() => configureArticle("ok", { position: 5 }, paths), /position 5 is out of range: 0 \(first\) to 0/],
+ [() => configureArticle("ok", { audience: "public", position: -1 }, paths), /out of range/],
+ [() => setArticlesOrder(["ok", "ok"], paths), /every published article once/],
+ [() => setArticlesOrder(["bad"], paths), /every published article once/],
+ ];
+ for (const [call, re] of cases) {
+ await assert.rejects(call, (e: unknown) => e instanceof ArticleRegistryError && re.test((e as Error).message), String(re));
+ }
+ assert.equal(read(articlesIndexFile(paths)), indexBefore, "index.json untouched");
+ assert.equal(read(articleFile(paths, "ok")), okBefore, "report.json untouched (audience + bad position refused whole)");
+});
+
+test("an unreadable index.json is an error, never an empty list", async () => {
+ const paths = store();
+ put(paths, "a", doc("a"));
+ mkdirSync(path.dirname(articlesIndexFile(paths)), { recursive: true });
+ for (const bad of ['{"published": "a"}', '{"published": ["a", "a"]}', '{"published": [], "extra": 1}', "[]", "{"]) {
+ writeFileSync(articlesIndexFile(paths), bad);
+ await assert.rejects(readArticlesIndex(paths), ArticleRegistryError, bad);
+ await assert.rejects(setPublished("a", true, {}, paths), ArticleRegistryError, bad);
+ assert.equal(read(articlesIndexFile(paths)), bad, "not overwritten");
+ }
+});
+
+test("unpublishing an article whose directory is gone tidies the index", async () => {
+ const paths = store();
+ put(paths, "a", doc("a"));
+ await setPublished("a", true, {}, paths);
+ rmSync(path.dirname(articleFile(paths, "a")), { recursive: true });
+ const listed = await listArticles(paths);
+ assert.deepEqual(listed.map((a) => [a.id, a.exists]), [["a", false]]);
+ await setPublished("a", false, {}, paths);
+ assert.deepEqual(await readArticlesIndex(paths), { published: [] });
+});
+
+test("patchArticle: patched as on disk, a key given as undefined removed, never made worse", async () => {
+ const paths = store();
+ put(paths, "a", doc("a", { subtitle: "old" }));
+ const r = await patchArticle("a", { title: "New title", subtitle: undefined }, paths);
+ assert.equal(r?.title, "New title");
+ const onDisk = json(articleFile(paths, "a"));
+ assert.equal(onDisk.title, "New title");
+ assert.equal("subtitle" in onDisk, false);
+ const fn = await patchArticle("a", (cur) => ({ title: `${cur.title}!` }), paths);
+ assert.equal(fn?.title, "New title!");
+ assert.equal(await patchArticle("missing", { title: "x" }, paths), null);
+ const before = read(articleFile(paths, "a"));
+ await assert.rejects(patchArticle("a", { kind: "essay" as never }, paths), /would make report.json invalid/);
+ await assert.rejects(
+ patchArticle("a", { summary: "see [x](cite:nobody)" }, paths),
+ /would make report.json invalid[\s\S]*summary/,
+ );
+ await assert.rejects(patchArticle("a", { id: "b" } as never, paths), /may not change "id"/);
+ assert.equal(read(articleFile(paths, "a")), before);
+ // A report that already has a problem may still be patched elsewhere.
+ put(paths, "b", doc("b", { summary: "see [x](cite:nobody)" }));
+ assert.equal((await patchArticle("b", { title: "Still a draft" }, paths))?.title, "Still a draft");
+});
+
+test("writeArticle: only a sound document; a regenerated one keeps its audience", async () => {
+ const paths = store();
+ await assert.rejects(writeArticle(doc("a", { kind: "essay" }), { paths }), /not a sound report/);
+ await assert.rejects(writeArticle(doc("Bad"), { paths }), /not an article id/);
+ assert.equal(existsSync(articleFile(paths, "a")), false);
+ await writeArticle(doc("a"), { paths });
+ await configureArticle("a", { audience: "public", published: true }, paths);
+ await writeArticle(doc("a", { title: "Regenerated" }), { paths });
+ assert.equal(json(articleFile(paths, "a")).audience, "public", "kept");
+ assert.equal(json(articleFile(paths, "a")).title, "Regenerated");
+ await writeArticle(doc("a"), { paths, keepAudience: false });
+ assert.equal("audience" in json(articleFile(paths, "a")), false, "written as given");
+ assert.deepEqual((await readArticlesIndex(paths)).published, ["a"], "the index is untouched by a write");
+});
+
+test("the lock: parallel writes all land; a live holder is waited for; a dead one is taken over", async () => {
+ const paths = store();
+ const ids = Array.from({ length: 12 }, (_, i) => `a${i}`);
+ for (const id of ids) put(paths, id, doc(id));
+ await Promise.all(ids.map((id) => setPublished(id, true, {}, paths)));
+ assert.deepEqual([...(await readArticlesIndex(paths)).published].sort(), [...ids].sort());
+ assert.equal(existsSync(path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME)), false, "released");
+
+ // A live holder (this process, fresh): the write waits until it is gone.
+ const lock = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME);
+ writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() }));
+ let released = false;
+ setTimeout(() => {
+ released = true;
+ rmSync(lock, { force: true });
+ }, 300);
+ await setPublished("a0", false, {}, paths);
+ assert.equal(released, true, "it waited for the holder");
+
+ // A dead holder on this host: taken over at once.
+ writeFileSync(lock, JSON.stringify({ pid: 2 ** 22 + 12345, host: os.hostname(), since: Date.now() }));
+ const t0 = Date.now();
+ await setPublished("a0", true, {}, paths);
+ assert.ok(Date.now() - t0 < 2000, "no wait for a dead holder");
+ assert.equal(existsSync(lock), false);
+});
diff --git a/common/lib/report/registry.ts b/common/lib/report/registry.ts
@@ -0,0 +1,507 @@
+// THE ARTICLE REGISTRY — the one writer of the article store
+// (`transcripts/reports/`, release 26; plans/reports-on-homepage.md, "The
+// model"). The `patchSite` of articles: every write is LOCKED, VALIDATED and
+// ATOMIC, and nothing else — not a generator, not a script, not a hand — writes
+// `index.json` or an article's `audience`.
+//
+// transcripts/reports/index.json {"published": [ids]} — the
+// published, ordered list; an
+// article directory it does not
+// name is a draft
+// transcripts/reports/<id>/report.json the article (REPORT.md), with
+// `audience` "public" | "private"
+// (absent = private, D2)
+// transcripts/reports/.registry.lock held while a write runs
+//
+// THE LOCK is two locks: withJsonFileLock (in-process: the editor's routes and
+// server actions) around an O_EXCL lock file (across processes: a generator
+// in ~/reports/* calling this beside a running editor). A lock file whose
+// holder is gone — its pid does not answer on this host, or it is older than
+// LOCK_STALE_MS — is taken over. A write waits for a live holder up to
+// LOCK_WAIT_MS, then refuses.
+//
+// VALIDATED: an index names report ids, once each. Publishing needs a sound
+// report.json (no problem lib/report/validate.ts names). A patch may not make
+// a report worse: a patched report.json is written only when it parses and
+// has no problem the report did not already have. A whole document
+// (writeArticle) is written only when it has none.
+//
+// ATOMIC: each file is replaced whole (writeJsonAtomic). A call that writes
+// both files (configureArticle) checks everything first and writes nothing
+// when anything is refused.
+//
+// SERVER-ONLY (node:fs).
+
+import type { Dirent } from "node:fs";
+import { mkdir, open, readdir, readFile, rm, stat } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { getPaths, type Paths } from "../paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server";
+import type { Problem } from "../citations/validate";
+import { isReportId, REPORT_AUDIENCES, type Report, type ReportAudience } from "./schema";
+import { parseReport } from "./validate";
+import { articleReportStore, storeReportDir, storeReportFile } from "./store";
+
+export const ARTICLES_INDEX_FILENAME = "index.json";
+export const ARTICLES_LOCK_FILENAME = ".registry.lock";
+// How long a write waits for another process's write, and when a lock file is
+// stale whoever holds it (a write takes milliseconds).
+export const LOCK_WAIT_MS = 10_000;
+export const LOCK_STALE_MS = 60_000;
+const LOCK_POLL_MS = 25;
+
+export type ArticlesIndex = { published: string[] };
+
+// A refusal: nothing was written. `problems` lists a report's problems as
+// `<path>: <message>` lines when that is why.
+export class ArticleRegistryError extends Error {
+ constructor(
+ message: string,
+ readonly problems: string[] = [],
+ ) {
+ super(problems.length > 0 ? `${message}:\n${problems.map((p) => ` ${p}`).join("\n")}` : message);
+ this.name = "ArticleRegistryError";
+ }
+}
+
+// ─── Where ───
+
+export function articlesIndexFile(paths: Pick<Paths, "articlesDir"> = getPaths()): string {
+ return path.join(paths.articlesDir, ARTICLES_INDEX_FILENAME);
+}
+
+export function articleDir(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): string {
+ return storeReportDir(articleReportStore(paths), id);
+}
+
+export function articleFile(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): string {
+ return storeReportFile(articleReportStore(paths), id);
+}
+
+// ─── Reading ───
+
+// Who may read an article: its `audience`, absent = private.
+export function articleAudience(report: { audience?: unknown } | null | undefined): ReportAudience {
+ return report?.audience === "public" ? "public" : "private";
+}
+
+export function isReportAudience(v: unknown): v is ReportAudience {
+ return typeof v === "string" && (REPORT_AUDIENCES as readonly string[]).includes(v);
+}
+
+// index.json's shape: `{"published": [ids]}`, ids once each, nothing else.
+export function parseArticlesIndex(raw: unknown): { ok: true; index: ArticlesIndex } | { ok: false; problem: string } {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
+ return { ok: false, problem: 'is not an object {"published": [ids]}' };
+ }
+ const extra = Object.keys(raw).filter((k) => k !== "published");
+ if (extra.length > 0) return { ok: false, problem: `has unknown key(s): ${extra.join(", ")}` };
+ const published = (raw as { published?: unknown }).published ?? [];
+ if (!Array.isArray(published)) return { ok: false, problem: '"published" is not a list of article ids' };
+ const seen = new Set<string>();
+ for (const id of published) {
+ if (!isReportId(id)) return { ok: false, problem: `"published" names ${JSON.stringify(id)}, which is not an article id` };
+ if (seen.has(id)) return { ok: false, problem: `"published" names "${id}" twice` };
+ seen.add(id);
+ }
+ return { ok: true, index: { published: [...published] as string[] } };
+}
+
+// The published list. No index.json = none published. An index that cannot be
+// read is an error, never an empty list: a build must not publish nothing
+// because a file is torn.
+export async function readArticlesIndex(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<ArticlesIndex> {
+ const file = articlesIndexFile(paths);
+ const read = await readJsonFile(file);
+ if (!read.ok) {
+ if (read.reason === "absent") return { published: [] };
+ throw new ArticleRegistryError(`reports/${ARTICLES_INDEX_FILENAME} is ${read.reason} (${file})`);
+ }
+ const parsed = parseArticlesIndex(read.value);
+ if (!parsed.ok) throw new ArticleRegistryError(`reports/${ARTICLES_INDEX_FILENAME} ${parsed.problem}`);
+ return parsed.index;
+}
+
+// Every article directory, published or draft: a directory under
+// `transcripts/reports/` whose name is an article id. Sorted.
+export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(paths.articlesDir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ return entries
+ .filter((e) => e.isDirectory() && isReportId(e.name))
+ .map((e) => e.name)
+ .sort((a, b) => a.localeCompare(b));
+}
+
+// One article as the registry knows it.
+export type ArticleState = {
+ id: string;
+ // report.json is there (an index may name an article whose directory is gone).
+ exists: boolean;
+ title: string | null;
+ audience: ReportAudience;
+ published: boolean;
+ // Its place in the published list (0 = first), or null for a draft.
+ position: number | null;
+ // What lib/report/validate.ts says about report.json (one entry when it is
+ // not readable JSON).
+ problems: Problem[];
+};
+
+type ReadArticle =
+ | { ok: true; raw: Record<string, unknown>; problems: Problem[]; report: Report | null }
+ | { ok: false; reason: "absent" | "unreadable" | "unparseable" | "not-an-object" };
+
+async function readArticle(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): Promise<ReadArticle> {
+ const read = await readJsonFile(articleFile(paths, id));
+ if (!read.ok) return { ok: false, reason: read.reason };
+ if (!read.value || typeof read.value !== "object" || Array.isArray(read.value)) return { ok: false, reason: "not-an-object" };
+ const raw = read.value as Record<string, unknown>;
+ const parsed = parseReport(raw, { id });
+ return { ok: true, raw, problems: parsed.problems, report: parsed.ok ? parsed.value : null };
+}
+
+function stateOf(id: string, read: ReadArticle, index: ArticlesIndex): ArticleState {
+ const position = index.published.indexOf(id);
+ return {
+ id,
+ exists: read.ok,
+ title: read.ok && typeof read.raw.title === "string" ? read.raw.title : null,
+ audience: articleAudience(read.ok ? read.raw : null),
+ published: position >= 0,
+ position: position >= 0 ? position : null,
+ problems: read.ok
+ ? read.problems
+ : read.reason === "absent"
+ ? []
+ : [{ path: "", message: `report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}` }],
+ };
+}
+
+// One article's state, or null when it has no directory and the index does
+// not name it.
+export async function readArticleState(
+ id: string,
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(),
+): Promise<ArticleState | null> {
+ if (!isReportId(id)) return null;
+ const index = await readArticlesIndex(paths);
+ const read = await readArticle(paths, id);
+ if (!read.ok && read.reason === "absent" && !index.published.includes(id)) {
+ const dir = await stat(articleDir(paths, id)).catch(() => null);
+ if (!dir?.isDirectory()) return null;
+ }
+ return stateOf(id, read, index);
+}
+
+// Every article: the published ones in their order, then the drafts by id.
+// An id the index names whose report.json is gone is listed (`exists` false).
+export async function listArticles(paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths()): Promise<ArticleState[]> {
+ const index = await readArticlesIndex(paths);
+ const dirs = await listArticleDirs(paths);
+ const ids = [...index.published, ...dirs.filter((d) => !index.published.includes(d))];
+ const out: ArticleState[] = [];
+ for (const id of ids) out.push(stateOf(id, await readArticle(paths, id), index));
+ return out;
+}
+
+// The published articles a build of `audience` carries, in order: a public
+// build only those whose report.json says `audience: "public"`; a private build
+// every published one. An article whose report.json cannot be read is kept
+// (compose names its problem) by a private build and left out by a public one,
+// which can never know it is public.
+export async function publishedArticleIds(
+ audience: ReportAudience,
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(),
+): Promise<string[]> {
+ const index = await readArticlesIndex(paths);
+ if (audience === "private") return index.published;
+ const out: string[] = [];
+ for (const id of index.published) {
+ const read = await readArticle(paths, id);
+ if (read.ok && articleAudience(read.raw) === "public") out.push(id);
+ }
+ return out;
+}
+
+// ─── The lock ───
+
+type LockHolder = { pid: number; host: string; since: number };
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+function pidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return (e as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+async function lockIsStale(file: string): Promise<boolean> {
+ let holder: LockHolder | null = null;
+ try {
+ holder = JSON.parse(await readFile(file, "utf8")) as LockHolder;
+ } catch {
+ holder = null;
+ }
+ if (!holder || typeof holder.since !== "number") {
+ // Torn (a taker died between creating and writing it): stale once old.
+ const st = await stat(file).catch(() => null);
+ return !st || Date.now() - st.mtimeMs > LOCK_STALE_MS;
+ }
+ if (Date.now() - holder.since > LOCK_STALE_MS) return true;
+ return holder.host === os.hostname() && typeof holder.pid === "number" && !pidAlive(holder.pid);
+}
+
+// Run `fn` holding the article store's lock, in this process and across
+// processes. Exported for a caller that writes several things as one.
+export function withArticleStoreLock<T>(
+ fn: () => Promise<T>,
+ paths: Pick<Paths, "articlesDir"> = getPaths(),
+): Promise<T> {
+ const file = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME);
+ return withJsonFileLock(file, async () => {
+ await mkdir(paths.articlesDir, { recursive: true });
+ const deadline = Date.now() + LOCK_WAIT_MS;
+ for (;;) {
+ try {
+ const h = await open(file, "wx");
+ try {
+ await h.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() } satisfies LockHolder));
+ } finally {
+ await h.close();
+ }
+ break;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
+ if (await lockIsStale(file)) {
+ await rm(file, { force: true });
+ continue;
+ }
+ if (Date.now() > deadline) {
+ throw new ArticleRegistryError(`the article store is busy (${file} is held by another write) — try again`);
+ }
+ await sleep(LOCK_POLL_MS);
+ }
+ }
+ try {
+ return await fn();
+ } finally {
+ await rm(file, { force: true });
+ }
+ });
+}
+
+// ─── Writing ───
+
+const problemLines = (problems: readonly Problem[]) => problems.map((p) => `${p.path || "(root)"}: ${p.message}`);
+const problemKey = (p: Problem) => `${p.path}\u0000${p.message}`;
+
+function assertId(id: unknown): asserts id is string {
+ if (!isReportId(id)) {
+ throw new ArticleRegistryError(`"${String(id)}" is not an article id (a lowercase slug: [a-z0-9][a-z0-9-]*, at most 64)`);
+ }
+}
+
+async function writeIndex(paths: Pick<Paths, "articlesDir">, index: ArticlesIndex): Promise<void> {
+ await writeJsonAtomic(articlesIndexFile(paths), { published: index.published }, { mkdir: true });
+}
+
+// Where an article goes in a published list: `position` (0 = first), else
+// where it is, else last.
+function placed(list: readonly string[], id: string, position: number | undefined): string[] {
+ const without = list.filter((x) => x !== id);
+ const at = position ?? (list.includes(id) ? list.indexOf(id) : without.length);
+ if (!Number.isInteger(at) || at < 0 || at > without.length) {
+ throw new ArticleRegistryError(
+ `position ${String(position)} is out of range: 0 (first) to ${without.length} (last) for "${id}"`,
+ );
+ }
+ return [...without.slice(0, at), id, ...without.slice(at)];
+}
+
+// The change configureArticle and the ops action make.
+export type ArticleConfigChange = {
+ audience?: ReportAudience;
+ // true publishes (at `position`, else where it is, else last); false
+ // unpublishes (it stays on disk, a draft).
+ published?: boolean;
+ // Its place in the published list, 0 = first. Moves a published article;
+ // with `published: true` places it. Refused on a draft or with `published: false`.
+ position?: number;
+};
+
+// Set an article's audience and its place in the published list, in one
+// locked call: every refusal before anything is written. Answers the article
+// as it now is.
+export async function configureArticle(
+ id: string,
+ change: ArticleConfigChange,
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(),
+): Promise<ArticleState> {
+ assertId(id);
+ if (change.audience !== undefined && !isReportAudience(change.audience)) {
+ throw new ArticleRegistryError(`audience must be one of ${REPORT_AUDIENCES.join(", ")}`);
+ }
+ if (change.published === false && change.position !== undefined) {
+ throw new ArticleRegistryError(`"${id}": a position places a published article — not one being unpublished`);
+ }
+ return withArticleStoreLock(async () => {
+ const index = await readArticlesIndex(paths);
+ const read = await readArticle(paths, id);
+ if (!read.ok) {
+ // Unpublishing an article whose directory is gone tidies the index.
+ if (change.published === false && change.audience === undefined && index.published.includes(id)) {
+ const next = { published: index.published.filter((x) => x !== id) };
+ await writeIndex(paths, next);
+ return stateOf(id, read, next);
+ }
+ throw new ArticleRegistryError(
+ read.reason === "absent"
+ ? `no article "${id}" (no reports/${id}/report.json)`
+ : `reports/${id}/report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}`,
+ );
+ }
+ const wasPublished = index.published.includes(id);
+ const publish = change.published ?? wasPublished;
+ if (change.position !== undefined && !publish) {
+ throw new ArticleRegistryError(`"${id}" is a draft: give "published": true to place it`);
+ }
+ // Only a sound article is published (compose would refuse it anyway).
+ if (publish && !wasPublished && read.problems.length > 0) {
+ throw new ArticleRegistryError(`"${id}" cannot be published while report.json has problems`, problemLines(read.problems));
+ }
+ const nextIndex: ArticlesIndex = publish
+ ? { published: placed(index.published, id, change.position) }
+ : { published: index.published.filter((x) => x !== id) };
+ let raw = read.raw;
+ if (change.audience !== undefined && articleAudience(raw) !== change.audience) {
+ raw = { ...raw, audience: change.audience };
+ const after = parseReport(raw, { id });
+ const before = new Set(read.problems.map(problemKey));
+ const worse = after.problems.filter((p) => !before.has(problemKey(p)));
+ if (!after.ok || worse.length > 0) {
+ throw new ArticleRegistryError(`"${id}": setting its audience would make report.json invalid`, problemLines(worse));
+ }
+ await writeJsonAtomic(articleFile(paths, id), raw);
+ }
+ if (nextIndex.published.join("\n") !== index.published.join("\n")) await writeIndex(paths, nextIndex);
+ return stateOf(id, { ...read, raw }, nextIndex);
+ }, paths);
+}
+
+// Publish (`true`) or unpublish (`false`) an article; `position` places it
+// (0 = first; absent = where it is, else last). Answers the published list.
+export async function setPublished(
+ id: string,
+ published: boolean,
+ opts: { position?: number } = {},
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(),
+): Promise<ArticlesIndex> {
+ await configureArticle(id, { published, ...(opts.position !== undefined ? { position: opts.position } : {}) }, paths);
+ return readArticlesIndex(paths);
+}
+
+// Replace the published order whole: `ids` must be the published articles,
+// each once, in their new order. Answers the published list.
+export async function setArticlesOrder(
+ ids: readonly string[],
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(),
+): Promise<ArticlesIndex> {
+ return withArticleStoreLock(async () => {
+ const index = await readArticlesIndex(paths);
+ const want = [...ids].sort().join("\n");
+ if (new Set(ids).size !== ids.length || want !== [...index.published].sort().join("\n")) {
+ throw new ArticleRegistryError(
+ `an order must name every published article once (published: ${index.published.join(", ") || "none"})`,
+ );
+ }
+ const next = { published: [...ids] };
+ await writeIndex(paths, next);
+ return next;
+ }, paths);
+}
+
+// The keys a patch may change: anything but what names the document.
+export type ArticlePatch = Partial<Omit<Report, "format" | "version" | "id">>;
+
+// PATCH SOME KEYS OF AN ARTICLE'S report.json — read inside the lock and
+// patched as it is now, so a patch never writes back keys read earlier. A key
+// given as `undefined` is removed. A function patch is given the report as it
+// is now. Written only when the result parses and has no problem the report
+// did not already have. Null when the article has no report.json: a patch
+// never creates one (writeArticle does).
+export async function patchArticle(
+ id: string,
+ patch: ArticlePatch | ((current: Report) => ArticlePatch),
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(),
+): Promise<Report | null> {
+ assertId(id);
+ return withArticleStoreLock(async () => {
+ const read = await readArticle(paths, id);
+ if (!read.ok) {
+ if (read.reason === "absent") return null;
+ throw new ArticleRegistryError(`reports/${id}/report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}`);
+ }
+ let changes: ArticlePatch;
+ if (typeof patch === "function") {
+ if (!read.report) {
+ throw new ArticleRegistryError(`reports/${id}/report.json does not parse: fix it before a function patch`, problemLines(read.problems));
+ }
+ changes = patch(read.report);
+ } else {
+ changes = patch;
+ }
+ for (const k of ["format", "version", "id"]) {
+ if (k in (changes as object)) throw new ArticleRegistryError(`"${id}": a patch may not change "${k}"`);
+ }
+ const next: Record<string, unknown> = { ...read.raw };
+ for (const [k, v] of Object.entries(changes)) {
+ if (v === undefined) delete next[k];
+ else next[k] = v;
+ }
+ const after = parseReport(next, { id });
+ const before = new Set(read.problems.map(problemKey));
+ const worse = after.problems.filter((p) => !before.has(problemKey(p)));
+ if (!after.ok || worse.length > 0) {
+ throw new ArticleRegistryError(`"${id}": the patch would make report.json invalid`, problemLines(worse));
+ }
+ await writeJsonAtomic(articleFile(paths, id), next);
+ return after.value;
+ }, paths);
+}
+
+// WRITE A WHOLE ARTICLE — a generator's report.json, created or replaced at
+// `transcripts/reports/<doc.id>/report.json`. Written only when it has no
+// problem. A document with no `audience` keeps the one on disk (regenerating a
+// public article does not make it private); `keepAudience: false` writes it as
+// given. Its place in the index is untouched: publish with setPublished.
+export async function writeArticle(
+ doc: unknown,
+ opts: { paths?: Pick<Paths, "articlesDir" | "exportIndexDir">; keepAudience?: boolean } = {},
+): Promise<Report> {
+ const paths = opts.paths ?? getPaths();
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new ArticleRegistryError("an article is a JSON object");
+ const id = (doc as { id?: unknown }).id;
+ assertId(id);
+ return withArticleStoreLock(async () => {
+ let next = doc as Record<string, unknown>;
+ if (opts.keepAudience !== false && next.audience === undefined) {
+ const read = await readArticle(paths, id);
+ if (read.ok && read.raw.audience !== undefined) next = { ...next, audience: read.raw.audience };
+ }
+ const parsed = parseReport(next, { id });
+ if (!parsed.ok || parsed.problems.length > 0) {
+ throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems));
+ }
+ await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true });
+ return parsed.value;
+ }, paths);
+}
diff --git a/common/lib/report/schema.ts b/common/lib/report/schema.ts
@@ -36,6 +36,14 @@ export const REPORT_VERSION = 1;
export const REPORT_KINDS = ["factcheck", "sweep"] as const;
export type ReportKind = (typeof REPORT_KINDS)[number];
+// Who may read an ARTICLE (a report in the article store, ./store.ts): the
+// public homepage build carries only `public` ones; the private build every
+// published one. Absent = private (release 26, D2) — going public is an
+// explicit `articles-config` (./registry.ts). A site's page ignores it: it
+// has its site's audience.
+export const REPORT_AUDIENCES = ["public", "private"] as const;
+export type ReportAudience = (typeof REPORT_AUDIENCES)[number];
+
const text = z.string();
const verdict = z.enum(VERDICTS as unknown as [Verdict, ...Verdict[]]);
@@ -104,6 +112,7 @@ export const reportSchema = z.strictObject({
version: z.literal(REPORT_VERSION),
id: text,
kind: z.enum(REPORT_KINDS),
+ audience: z.enum(REPORT_AUDIENCES).optional(),
series: text.optional(),
title: text,
subtitle: text.optional(),
@@ -143,6 +152,8 @@ export const REPORT_FIELD_DOCS: FieldDocs<Report> = {
version: `\`${REPORT_VERSION}\`.`,
id: "The report's id: a lowercase slug (`[a-z0-9][a-z0-9-]*`, at most 64), its directory name under `reports/` and the last segment of its page, `/reports/<id>/`. Must match the directory.",
kind: '`"factcheck"` — sections of claims, each with a verdict — or `"sweep"` — sections with no verdicts, or bodies with inline citations.',
+ audience:
+ "Who may read the report when it is an ARTICLE (in `transcripts/reports/`, published by the homepage): `\"public\"` — the public homepage build carries it — or `\"private\"` — only the private build (`archilyzer build homepage --private`, never deployed) does. Absent = `\"private\"`: going public is an explicit `pnpm ops articles-config`. Ignored on a site's page, which has its site's audience.",
series: "The series the report belongs to: a recurring name for its kind of report. It is shown on its own line above the title, in the accent colour, at the head of the report's page, its exports and the report list (where a report with no series shows its kind instead), and is joined to the title as `<series>: <title>` where one line names the report (a page title, a link, a cited-in entry).",
title: "The report's title.",
subtitle: "A line under the title.",
diff --git a/common/lib/report/store.ts b/common/lib/report/store.ts
@@ -0,0 +1,70 @@
+// WHERE A REPORT LIVES — the two stores of report directories (release 26,
+// plans/reports-on-homepage.md, "The model"):
+//
+// a SITE's pages transcripts/sites/<siteId>/reports/<id>/ published by
+// the site's `pages` list (site.json)
+// the ARTICLES transcripts/reports/<id>/ published by
+// transcripts/reports/index.json (./registry.ts)
+//
+// A report directory is the same in both: report.json, its stills/, sources/,
+// video, history-git/ and notes.json. What differs is where the directories
+// are, where their staging (prepared media, exports) goes, and how a message
+// names one — which is all a ReportStore says. Nothing here reads a file:
+// whether a report is published, who may read it and what it may cite is the
+// host's (publish/reportHost.ts).
+
+import path from "node:path";
+import type { Paths } from "../paths";
+
+export type ReportStoreKind = "site" | "articles";
+
+// The id of the article store's staging (`.export-index/articles/`) and of its
+// prepared-media manifest. A site id may be spelled the same; their staging
+// dirs differ (`.export-index/sites/<siteId>/`), so they never meet.
+export const ARTICLES_STORE_ID = "articles";
+
+export type ReportStore = {
+ kind: ReportStoreKind;
+ // The site's id, or ARTICLES_STORE_ID.
+ id: string;
+ // The directory holding the report directories.
+ reportsDir: string;
+ // Staging, never served: `report-media/` and `report-exports/` go under it.
+ stagingDir: string;
+ // How a message names the reports directory, relative to the corpus:
+ // `sites/<siteId>/reports` or `reports`.
+ label: string;
+};
+
+export function siteReportStore(paths: Pick<Paths, "sitesDir" | "exportSitesIndexDir">, siteId: string): ReportStore {
+ return {
+ kind: "site",
+ id: siteId,
+ reportsDir: path.join(paths.sitesDir, siteId, "reports"),
+ stagingDir: path.join(paths.exportSitesIndexDir, siteId),
+ label: `sites/${siteId}/reports`,
+ };
+}
+
+export function articleReportStore(paths: Pick<Paths, "articlesDir" | "exportIndexDir">): ReportStore {
+ return {
+ kind: "articles",
+ id: ARTICLES_STORE_ID,
+ reportsDir: paths.articlesDir,
+ stagingDir: path.join(paths.exportIndexDir, ARTICLES_STORE_ID),
+ label: "reports",
+ };
+}
+
+// A report's directory, its report.json, and how a message names the file.
+export function storeReportDir(store: Pick<ReportStore, "reportsDir">, reportId: string): string {
+ return path.join(store.reportsDir, reportId);
+}
+
+export function storeReportFile(store: Pick<ReportStore, "reportsDir">, reportId: string): string {
+ return path.join(storeReportDir(store, reportId), "report.json");
+}
+
+export function storeReportLabel(store: Pick<ReportStore, "label">, reportId: string): string {
+ return `${store.label}/${reportId}/report.json`;
+}