Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit cb3200668510f589f26e92042f7d20fee2cd335e
parent 5743b040e29dffa57ce1bdc1a84b9c9792e79811
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 12:31:18 -0400

Merge r23/cited-only (release 23: cited-only channels, the citedChannels key) into r23/integration

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCITATIONS.md | 6+++---
MCOMMANDS.md | 3++-
MREPORT.md | 2+-
MSITE.md | 23+++++++++++++++++++++--
Mcommon/controller/renameChannel.test.ts | 11+++++++++++
Mcommon/controller/renameChannel.ts | 13++++++++++---
Mcommon/lib/builtExport.test.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/builtExport.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/lib/citations/schema.ts | 6++++--
Mcommon/lib/fileSchemaDocs.ts | 2++
Mcommon/lib/report/docs.ts | 7+++++--
Mcommon/lib/site.ts | 7+------
Mcommon/lib/siteSchema.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/siteSchema.ts | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/publish/build.ts | 10++++++++--
Mcommon/publish/composeReports.test.ts | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/publish/composeReports.ts | 35+++++++++++++++++++++++------------
Mcommon/publish/deployStage.test.ts | 11++++++++++-
Mcommon/publish/deployStage.ts | 8++++++--
Mcommon/publish/inputSig.test.ts | 37+++++++++++++++++++++++++++++++++++++
Mcommon/publish/inputSig.ts | 20+++++++++++++++++++-
Mcommon/publish/missingEvidenceWindows.test.ts | 22++++++++++++++++++++++
Mcommon/publish/reportMedia.test.ts | 28++++++++++++++++++++++++++++
Mcommon/publish/reportMedia.ts | 26+++++++++++++++++---------
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/_read.test.ts | 2++
Meditor/app/api/ops/sites/route.ts | 4+++-
Meditor/app/sites/actions.ts | 8++++++++
Meditor/app/sites/components/SiteForm.tsx | 35++++++++++++++++++++++++++++++++++-
Aeditor/app/sites/lib/citedChannelsFromForm.test.ts | 35+++++++++++++++++++++++++++++++++++
Aeditor/app/sites/lib/citedChannelsFromForm.ts | 36++++++++++++++++++++++++++++++++++++
Meditor/app/sites/page.tsx | 5++++-
Meditor/e2e/sites-crud.spec.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mplans/FACTS.md | 9+++++++++
Mplans/release-23.md | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 3++-
36 files changed, 927 insertions(+), 73 deletions(-)

diff --git a/CITATIONS.md b/CITATIONS.md @@ -46,7 +46,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Required | Description | |---|---|---| | `kind` | yes | `"video"`. | -| `channel` | yes | The record's channel slug (its directory under `transcripts/channels/`). A path segment of the moment page. | +| `channel` | yes | The record's channel slug (its directory under `transcripts/channels/`). A path segment of the moment page. The citing site must name it in `channels` (its pool) or `citedChannels` (cited only: the moment page and its clip publish, with no link into a corpus) — see [SITE.md](SITE.md); any other channel is refused at compose (`not-in-site`). | | `id` | yes | The record's video id (its directory under `data/`; may start with `-`). A path segment of the moment page. | | `start` | yes | Where the cited span starts, in seconds from the start of the record. | | `end` | yes | Where the cited span ends, in seconds; after `start`. | @@ -57,7 +57,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Required | Description | |---|---|---| | `kind` | yes | `"audio"`: a span of a record with no picture worth showing (a podcast). Rendered with a poster. | -| `channel` | yes | The record's channel slug (its directory under `transcripts/channels/`). A path segment of the moment page. | +| `channel` | yes | The record's channel slug (its directory under `transcripts/channels/`). A path segment of the moment page. The citing site must name it in `channels` (its pool) or `citedChannels` (cited only: the moment page and its clip publish, with no link into a corpus) — see [SITE.md](SITE.md); any other channel is refused at compose (`not-in-site`). | | `id` | yes | The record's video id (its directory under `data/`; may start with `-`). A path segment of the moment page. | | `start` | yes | Where the cited span starts, in seconds from the start of the record. | | `end` | yes | Where the cited span ends, in seconds; after `start`. | @@ -75,7 +75,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Required | Description | |---|---|---| | `kind` | yes | `"post"`. | -| `channel` | yes | The post's channel slug. A path segment of the moment page. | +| `channel` | yes | The post's channel slug. A path segment of the moment page. The citing site must name it in `channels` or `citedChannels` (see [SITE.md](SITE.md)), and may carry the post (the post visibility rule). | | `id` | yes | The post's id. A path segment of the moment page. | | `thread` | no | True to show the post with the thread it belongs to. Absent = the post alone. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -175,7 +175,8 @@ get settings [<key>] is settings.json as the editor reads it (migrated and defaulted; a secret is "<redacted>"), or one top-level key of it. get storage is /storage: each location, mounted or not, free space, tiers. get sites lists every site: id, title, siteUrl, Pages project, audience, - listed, search, publish policy, channels. (`get publish` is the status.) + listed, search, publish policy, channels, citedChannels. (`get publish` + is the status.) get workers, get auto-queue and get scheduler are /workers, the four lanes of /operations, and /operations/sync — the payloads those pages poll. get cleanup <slug> is one channel's /cleanup row: what each sweep would diff --git a/REPORT.md b/REPORT.md @@ -6,7 +6,7 @@ One cited report, format `"archilyzer-report"`, version 1, persisted to `transcr 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>)`. -`common/lib/report/validate.ts` reports every problem with its JSON path: an unknown key, a reference that names nothing (a listed citation, a claim's source sentence, a `cite:` link, the subject), a section, claim or entry id used twice (they share one namespace: the report page's anchors) or named for one of the page's own anchors, a sweep's claim with a verdict, `updated` before `published` (or an entry's before its `date`), a date that is not one, a slide field out of bounds (below), and every citation problem CITATIONS.md lists. Whether a still or the report's video exists, whether the video fits the publish limit, and whether a quote matches its cues are checked when the site is composed. +`common/lib/report/validate.ts` reports every problem with its JSON path: an unknown key, a reference that names nothing (a listed citation, a claim's source sentence, a `cite:` link, the subject), a section, claim or entry id used twice (they share one namespace: the report page's anchors) or named for one of the page's own anchors, a sweep's claim with a verdict, `updated` before `published` (or an entry's before its `date`), a date that is not one, a slide field out of bounds (below), and every citation problem CITATIONS.md lists. Whether a still or the report's video exists, whether the video fits the publish limit, whether a quote matches its cues, and whether each cited channel is one the site may cite — in its `channels` (its pool) or its `citedChannels` (cited only: the moment pages and clips publish, the channel's transcripts, search and corpus.json entry do not; see [SITE.md](SITE.md)) — are checked when the site is composed. Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/file-schemas-docs.ts`. diff --git a/SITE.md b/SITE.md @@ -20,6 +20,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | [`groups`](#groups) | list — see below | | [`defaultGroupId`](#defaultgroupid) | `"default"` | | [`channels`](#channels) | `[]` | +| [`citedChannels`](#citedchannels) | `[]` | | [`cloudflareProject`](#cloudflareproject) | absent | | [`accent`](#accent) | absent | | [`siteUrl`](#siteurl) | absent | @@ -126,7 +127,7 @@ Default: `"default"` ## `channels` -The channels this site exposes. A channel absent from this list is not built or deployed for this site even though its data exists in the pool. +The channels this site exposes — its pool: what it builds, browses, searches and lists in its `/corpus.json`, and the pool its citations resolve against. A channel absent from this list is not built or deployed for this site even though its data exists in the pool (a channel in `citedChannels` publishes only what this site's reports cite). #### `channels[]` @@ -144,6 +145,24 @@ Default: [] ``` +## `citedChannels` + +Channels in the cited scope: channels this site's reports may cite without the site publishing them. A cited-only channel publishes only what the reports cite — the moment pages and their clips — with no browse page, search entry, transcripts, subs, digests or `/corpus.json` entry, and its moments link no corpus page. A slug already in `channels` is dropped (the pool wins). Written only when non-empty; absent = none. It fails closed: a reader that does not know the key drops it, and compose then refuses a citation of the channel as `not-in-site` — it never publishes the channel's transcripts. + +#### `citedChannels[]` + +Per entry — each entry spells its own values. + +| Key | Description | +|---|---| +| `slug` | Channel slug (its directory name under `transcripts/channels/`). Trimmed; blank and duplicate slugs are dropped, and so is a slug already in `channels`. | + +Default: + +```json +[] +``` + ## `cloudflareProject` Cloudflare Pages project name this site deploys to (`wrangler pages deploy out --project-name <cloudflareProject>`). Trimmed; blank = none. @@ -205,7 +224,7 @@ Default: ## `search` -Whether this site publishes its searchable corpus. Opt-OUT: absent/true = on, only an explicit `false` is written. Off = report-only: the site publishes only its `reports` and the moments they cite — no search, browse, transcripts or archives; `channels` is the pool its citations resolve against, and its `/corpus.json` says `"scope": "cited"`. A report-only site is never listed (as `listed: false`, whatever `listed` says). Legacy `publish: "cited"` reads as `false`. +Whether this site publishes its searchable corpus. Opt-OUT: absent/true = on, only an explicit `false` is written. Off = report-only: the site publishes only its `reports` and the moments they cite — no search, browse, transcripts or archives; `channels` is the pool its citations resolve against (with `citedChannels`), and its `/corpus.json` says `"scope": "cited"`. A report-only site is never listed (as `listed: false`, whatever `listed` says). Legacy `publish: "cited"` reads as `false`. Default: `true` diff --git a/common/controller/renameChannel.test.ts b/common/controller/renameChannel.test.ts @@ -80,6 +80,12 @@ async function seedOld(paths: Paths): Promise<void> { path.join(paths.sitesDir, "mysite", "site.json"), JSON.stringify({ channels: [{ slug: "old" }] }), ); + // A site that cites the channel without publishing it (citedChannels). + await mkdir(path.join(paths.sitesDir, "citing"), { recursive: true }); + await writeFile( + path.join(paths.sitesDir, "citing", "site.json"), + JSON.stringify({ channels: [{ slug: "other" }], citedChannels: [{ slug: "keep" }, { slug: "old" }] }), + ); const state = await readSchedulerState(paths); state.channels["old"] = { ...emptyChannelSyncState(), consecutiveFailures: 5 }; @@ -114,6 +120,11 @@ test("renameChannel migrates every slug-keyed store", async () => { ["new"], ); + // The cited scope retargeted in place, the pool untouched. + const citing = getSite("citing", paths); + assert.deepEqual(citing.citedChannels, [{ slug: "keep" }, { slug: "new" }]); + assert.deepEqual(citing.channels.map((c) => c.slug), ["other"]); + // Scheduler backoff carried over under the new key. const state = await readSchedulerState(paths); assert.equal(state.channels["old"], undefined); diff --git a/common/controller/renameChannel.ts b/common/controller/renameChannel.ts @@ -246,15 +246,22 @@ export async function renameChannel( } } - // 5. Rewrite site memberships that reference the old slug. + // 5. Rewrite site memberships that reference the old slug: the pool + // (`channels`) and the cited scope (`citedChannels`). try { for (const siteId of listSiteIds(paths)) { const site = getSite(siteId, paths); - if (!site.channels.some((c) => c.slug === oldSlug)) continue; + const cited = site.citedChannels ?? []; + const inPool = site.channels.some((c) => c.slug === oldSlug); + const inCited = cited.some((c) => c.slug === oldSlug); + if (!inPool && !inCited) continue; const channels = site.channels.map((c) => c.slug === oldSlug ? { ...c, slug: newSlug } : c, ); - await writeSite({ ...site, channels }, paths); + const citedChannels = cited.map((c) => + c.slug === oldSlug ? { ...c, slug: newSlug } : c, + ); + await writeSite({ ...site, channels, citedChannels }, paths); } } catch (err) { warnings.push(`Site membership update failed: ${(err as Error).message}`); diff --git a/common/lib/builtExport.test.ts b/common/lib/builtExport.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { builtBundleProblem, + builtCitedOnlyProblem, builtHomepageAt, builtHomepageProblem, builtHubProblem, @@ -19,6 +20,7 @@ import { publishFileSizeProblem, reportHistoryProblem, isTombstonePostsTree, + isTombstoneChannelPostsDir, hubReportDataIn, } from "./builtExport"; @@ -538,6 +540,70 @@ test("a site configured cited with a full build is refused at deploy; a cited bu } }); +// RELEASE 23: a cited-only channel (`citedChannels`) publishes its cited +// moments and clips, never its corpus. +test("a build that publishes a cited-only channel's corpus is refused; its moments and clips are not", () => { + const site = { + siteId: "citing", + channels: [{ slug: "pool" }], + citedChannels: [{ slug: "critic" }], + }; + const corpus = { spec: 5, kind: "site", site: { id: "citing" }, channels: [{ slug: "pool" }] }; + const t = bundle({ site: { siteId: "citing", channels: [{ slug: "pool" }] }, corpus }); + const put = (rel: string, body = "{}") => { + mkdirSync(path.dirname(path.join(t.dir, rel)), { recursive: true }); + writeFileSync(path.join(t.dir, rel), body); + }; + try { + // The pool's trees, and the cited channel's moments and clips: clean. + put("transcripts/pool/page-0000.json", "[]"); + put("posts/pool/page-0000.json", "[]"); + put("m/critic/abc123/10.00-20.00/moment.json"); + put("media/clips/critic/abc123/10.00-20.00.mp4", "mp4"); + assert.equal(builtCitedOnlyProblem(site, t.dir), null); + assert.equal(deployAudienceProblem(site, t.dir), null); + // A site with no cited scope, or the id alone, is never asked. + assert.equal(builtCitedOnlyProblem({ siteId: "citing" }, t.dir), null); + // 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(builtCitedOnlyProblem(site, t.dir), null); + + // Its trees, each named. + put("transcripts/critic/page-0000.json", "[]"); + put("digests/critic/manifest.json"); + put("posts/critic/page-0001.json", '[{"id":"1"}]'); + const problem = builtCitedOnlyProblem(site, t.dir)!; + assert.match(problem, /^Site "citing" cites "critic" only \(citedChannels\), but .* publishes its corpus: /); + assert.match(problem, /transcripts\/critic\//); + assert.match(problem, /digests\/critic\//); + assert.match(problem, /posts\/critic\//); + assert.match(problem, /compose the site again$/); + assert.equal(deployAudienceProblem(site, t.dir), problem); + // A slug the pool also holds is the pool's: nothing is cited-only. + assert.equal(builtCitedOnlyProblem({ ...site, channels: [{ slug: "pool" }, { slug: "critic" }] }, t.dir), null); + } finally { + t.cleanup(); + } + // Listed in corpus.json's or site.json's channels. + const listed = bundle({ + site: { siteId: "citing", channels: [{ slug: "pool" }, { slug: "critic" }] }, + corpus: { ...corpus, channels: [{ slug: "pool" }, { slug: "critic" }] }, + }); + try { + const problem = builtCitedOnlyProblem(site, listed.dir)!; + assert.match(problem, /"critic" in corpus\.json's channels/); + assert.match(problem, /"critic" in site\.json's channels/); + } finally { + listed.cleanup(); + } + // Nothing built: the identity checks answer that, not this one. + const empty = tempOut(); + assert.equal(builtCitedOnlyProblem(site, empty.dir), null); + empty.cleanup(); +}); + test("the publish limit: 24 MiB, inside Pages' 25, one sentence naming the file over it", () => { assert.equal(PUBLISH_MAX_FILE_BYTES, 24 * 1024 * 1024); assert.ok(PUBLISH_MAX_FILE_BYTES < PAGES_MAX_FILE_BYTES); diff --git a/common/lib/builtExport.ts b/common/lib/builtExport.ts @@ -15,7 +15,7 @@ import { existsSync, readdirSync, readFileSync, statSync, type Dirent } from "node:fs"; import path from "node:path"; -import { isCitedSite } from "./siteSchema"; +import { isCitedOnlyChannel, isCitedSite } from "./siteSchema"; import { REPORT_HISTORY_REPO_FILE_RE } from "./report/revisions"; import { MOMENTS_INDEX_PATH, @@ -160,10 +160,15 @@ export function builtAudienceProblem(outDir: string): string | null { * logs or throws, or null. */ export function deployAudienceProblem( - site: { siteId: string; audience?: string; search?: boolean }, + site: CitedOnlySite & { audience?: string; search?: boolean }, outDir: string, ): string | null { - return siteDeployProblem(site) ?? builtAudienceProblem(outDir) ?? builtScopeProblem(site, outDir); + return ( + siteDeployProblem(site) ?? + builtAudienceProblem(outDir) ?? + builtScopeProblem(site, outDir) ?? + builtCitedOnlyProblem(site, outDir) + ); } // ─── A CITED build (a report-only site: site.json `search: false`) ─── @@ -398,6 +403,76 @@ export function builtScopeProblem( ); } +// ─── A cited-only channel (site.json `citedChannels`, release 23) ─── + +// The site keys builtCitedOnlyProblem reads; a caller without the channel +// lists (an audience check) passes the id alone, and nothing is cited-only. +export type CitedOnlySite = { + siteId: string; + channels?: readonly { slug: string }[]; + citedChannels?: readonly { slug: string }[]; +}; + +// The per-channel trees a bundle publishes a channel's corpus in. +const CHANNEL_TREES = ["transcripts", "subs", "posts", "digests", "stats", "archives"] as const; + +// The slugs a bundle's `<file>` lists under `channels[]` (corpus.json and +// site.json both carry `{slug}` entries), or none when it cannot be read. +function listedChannelSlugsIn(outDir: string, file: string): Set<string> { + try { + const parsed: unknown = JSON.parse(readFileSync(path.join(outDir, file), "utf8")); + const channels = (parsed as { channels?: unknown } | null)?.channels; + if (!Array.isArray(channels)) return new Set(); + return new Set( + channels + .map((c) => (c as { slug?: unknown } | null)?.slug) + .filter((slug): slug is string => typeof slug === "string"), + ); + } catch { + return new Set(); + } +} + +/** + * Why `outDir` may not be built or deployed as `site` because it publishes a + * 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 + * 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. + */ +export function builtCitedOnlyProblem(site: CitedOnlySite, outDir: string): string | null { + const pool = { channels: site.channels ?? [], citedChannels: site.citedChannels }; + const citedOnly = [...new Set((site.citedChannels ?? []).map((c) => c.slug))].filter((slug) => + isCitedOnlyChannel(pool, slug), + ); + if (citedOnly.length === 0 || !existsSync(outDir)) return null; + const listedIn = { + "corpus.json": listedChannelSlugsIn(outDir, "corpus.json"), + "site.json": listedChannelSlugsIn(outDir, "site.json"), + }; + const found: string[] = []; + for (const slug of citedOnly.sort()) { + for (const tree of CHANNEL_TREES) { + const dir = path.join(outDir, tree, slug); + if (!existsSync(dir)) continue; + if (tree === "posts" && isTombstoneChannelPostsDir(dir)) continue; + found.push(`${tree}/${slug}/`); + } + for (const [file, slugs] of Object.entries(listedIn)) { + if (slugs.has(slug)) found.push(`"${slug}" in ${file}'s channels`); + } + } + if (found.length === 0) return null; + const shown = found.slice(0, 8).join(", ") + (found.length > 8 ? `, … (${found.length} in all)` : ""); + return ( + `Site "${site.siteId}" cites ${citedOnly.map((s) => `"${s}"`).join(", ")} only (citedChannels), ` + + `but ${outDir} publishes its corpus: ${shown} — compose the site again` + ); +} + // corpus.json's `site.id`, or null when there is no readable one. function corpusSiteIdIn(outDir: string): string | null { try { @@ -480,24 +555,39 @@ export function isTombstonePostsTree(postsDir: string): boolean { for (const e of entries) { if (e.name === "manifest.json" && e.isFile()) continue; if (!e.isDirectory()) return false; - const dir = path.join(postsDir, e.name); - const channel = readJson(path.join(dir, "manifest.json")) as - | { pageCount?: unknown; slugToPage?: unknown } - | undefined; - if (!channel || channel.pageCount !== 0) return false; - if (channel.slugToPage && Object.keys(channel.slugToPage as object).length > 0) return false; - let files: Dirent[]; + if (!isTombstoneChannelPostsDir(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. + */ +export function isTombstoneChannelPostsDir(dir: string): boolean { + const readJson = (file: string): unknown => { try { - files = readdirSync(dir, { withFileTypes: true }); + return JSON.parse(readFileSync(file, "utf8")); } catch { - return false; - } - for (const f of files) { - if (f.name === "manifest.json") continue; - if (!f.isFile() || !/^page-\d+\.json$/.test(f.name)) return false; - const page = readJson(path.join(dir, f.name)); - if (!Array.isArray(page) || page.length > 0) return false; + return undefined; } + }; + const channel = readJson(path.join(dir, "manifest.json")) as + | { pageCount?: unknown; slugToPage?: unknown } + | undefined; + if (!channel || channel.pageCount !== 0) return false; + if (channel.slugToPage && Object.keys(channel.slugToPage as object).length > 0) return false; + let files: Dirent[]; + try { + files = readdirSync(dir, { withFileTypes: true }); + } catch { + return false; + } + for (const f of files) { + if (f.name === "manifest.json") continue; + if (!f.isFile() || !/^page-\d+\.json$/.test(f.name)) return false; + const page = readJson(path.join(dir, f.name)); + if (!Array.isArray(page) || page.length > 0) return false; } return true; } diff --git a/common/lib/citations/schema.ts b/common/lib/citations/schema.ts @@ -166,7 +166,8 @@ type Own<T> = Omit<T, keyof CitationCommon>; export const VIDEO_CITATION_FIELD_DOCS: FieldDocs<Own<VideoCitation>> = { kind: '`"video"`.', - channel: "The record's channel slug (its directory under `transcripts/channels/`). A path segment of the moment page.", + channel: + "The record's channel slug (its directory under `transcripts/channels/`). A path segment of the moment page. The citing site must name it in `channels` (its pool) or `citedChannels` (cited only: the moment page and its clip publish, with no link into a corpus) — see [SITE.md](SITE.md); any other channel is refused at compose (`not-in-site`).", id: "The record's video id (its directory under `data/`; may start with `-`). A path segment of the moment page.", start: "Where the cited span starts, in seconds from the start of the record.", end: "Where the cited span ends, in seconds; after `start`.", @@ -185,7 +186,8 @@ export const CITATION_PAD_FIELD_DOCS: FieldDocs<CitationPad> = { export const POST_CITATION_FIELD_DOCS: FieldDocs<Own<PostCitation>> = { kind: '`"post"`.', - channel: "The post's channel slug. A path segment of the moment page.", + channel: + "The post's channel slug. A path segment of the moment page. The citing site must name it in `channels` or `citedChannels` (see [SITE.md](SITE.md)), and may carry the post (the post visibility rule).", id: "The post's id. A path segment of the moment page.", thread: "True to show the post with the thread it belongs to. Absent = the post alone.", }; diff --git a/common/lib/fileSchemaDocs.ts b/common/lib/fileSchemaDocs.ts @@ -27,6 +27,7 @@ import { SOCIAL_LINK_FIELD_DOCS } from "./settingsSchema"; import { RELATED_SITE_GROUP_FIELD_DOCS, SITE_CHANNEL_MEMBERSHIP_FIELD_DOCS, + SITE_CITED_CHANNEL_FIELD_DOCS, SITE_FIELD_DOCS, SITE_PUBLISH_FIELD_DOCS, parseSite, @@ -51,6 +52,7 @@ const SITE_NESTED: Partial<Record<keyof Site, KeyTable[]>> = { socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }], groups: [{ path: "groups[]", docs: CHANNEL_GROUP_FIELD_DOCS }], channels: [{ path: "channels[]", docs: SITE_CHANNEL_MEMBERSHIP_FIELD_DOCS }], + citedChannels: [{ path: "citedChannels[]", docs: SITE_CITED_CHANNEL_FIELD_DOCS }], relatedSites: [{ path: "relatedSites[]", docs: RELATED_SITE_GROUP_FIELD_DOCS }], publish: [{ path: "publish", docs: SITE_PUBLISH_FIELD_DOCS }], }; diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts @@ -61,8 +61,11 @@ export function renderReportMarkdown(): string { "`published` (or an entry's before its `date`), a date that is not one, a slide " + "field out of bounds (below), and every citation problem " + "CITATIONS.md lists. Whether a still or the report's video exists, whether the " + - "video fits the publish limit, and whether a quote matches its cues are checked " + - "when the site is composed.", + "video fits the publish limit, whether a quote matches its cues, and whether each " + + "cited channel is one the site may cite — in its `channels` (its pool) or its " + + "`citedChannels` (cited only: the moment pages and clips publish, the channel's " + + "transcripts, search and corpus.json entry do not; see [SITE.md](SITE.md)) — are " + + "checked when the site is composed.", ); out.push(""); out.push(REGENERATE_SCHEMA_DOC); diff --git a/common/lib/site.ts b/common/lib/site.ts @@ -18,6 +18,7 @@ import { isValidSiteId, parseSite, parseSiteUrl, + siteChannelSlugs, sitePublishProblem, siteToDisk, type Site, @@ -100,12 +101,6 @@ export function resolveHubUrl( return site.hubUrl ?? parseSiteUrl(settings.homepageUrl); } -// The set of channel slugs a site exposes. Used to scope the editor's -// site-specific views (dashboard, channels) down to one site's membership. -export function siteChannelSlugs(site: Site): Set<string> { - return new Set(site.channels.map((c) => c.slug)); -} - // siteId -> that site's channel slugs: the one shape `resolveFocusSlugs` // (lib/channelPriority.ts) resolves a `{kind:"site"}` focus against. // diff --git a/common/lib/siteSchema.test.ts b/common/lib/siteSchema.test.ts @@ -11,10 +11,14 @@ import { SITE_KEYS, channelsOnlyOnUnlistedSites, clampSitePublishPolicy, + isCitedOnlyChannel, isCitedSite, isListedSite, parseSite, + parseSiteCitedChannels, parseSiteReports, + siteChannelSlugs, + siteCitableChannelSlugs, siteFieldsSchema, sitePublishPolicy, sitePublishProblem, @@ -71,6 +75,7 @@ test("empty, null, [] and a number all read as the defaults, every key emitted", assert.deepEqual(want.relatedSites, []); assert.equal(want.search, true); assert.deepEqual(want.reports, []); + assert.deepEqual(want.citedChannels, []); assert.equal(want.socialLinks, undefined); assert.ok("socialLinks" in want); for (const raw of [null, [], 3, "x", undefined]) { @@ -239,6 +244,7 @@ function fixtures(): Array<[string, unknown]> { ], defaultGroupId: "b", channels: [{ slug: "c1", groupId: "a", order: 3 }, { slug: "c2", groupId: "q" }], + citedChannels: [{ slug: " k1 " }, { slug: "k1" }, { slug: "" }, { slug: "c1" }, "k2", { slug: "k3" }], cloudflareProject: "p", siteUrl: "https://s.example//", listed: false, @@ -532,3 +538,77 @@ test("writeSite refuses a public deploy policy with no cloudflareProject, naming await writeSite({ ...base, cloudflareProject: "proj", publish: { auto: "production" } }, paths); assert.deepEqual(getSite("s", paths).publish, { auto: "production" }); }); + +// RELEASE 23: the cited scope — channels a site's reports may cite without the +// site publishing them. +test("citedChannels: trimmed, blanks and repeats dropped, a pool slug dropped, absent reads []", () => { + assert.deepEqual( + parseSiteCitedChannels([{ slug: " a " }, { slug: "a" }, { slug: "" }, { slug: " " }, "b", null, { slug: 3 }, { slug: "c" }]), + [{ slug: "a" }, { slug: "c" }], + ); + for (const v of [undefined, null, "a", { slug: "a" }, 5]) { + assert.deepEqual(parseSite("s", v === undefined ? {} : { citedChannels: v }).citedChannels, [], String(v)); + } + // The pool wins: a slug already in `channels` is not cited-only. + const site = parseSite("s", { + channels: [{ slug: "pool" }], + citedChannels: [{ slug: "pool" }, { slug: "critic" }, { slug: "critic" }], + }); + assert.deepEqual(site.citedChannels, [{ slug: "critic" }]); + assert.deepEqual([...siteChannelSlugs(site)], ["pool"]); + assert.deepEqual([...siteCitableChannelSlugs(site)].sort(), ["critic", "pool"]); + assert.equal(isCitedOnlyChannel(site, "critic"), true); + assert.equal(isCitedOnlyChannel(site, "pool"), false); + assert.equal(isCitedOnlyChannel(site, "nobody"), false); + // A hand-built Site holding a slug in both reads as the pool's. + assert.equal(isCitedOnlyChannel({ channels: [{ slug: "x" }], citedChannels: [{ slug: "x" }] }, "x"), false); + assert.deepEqual([...siteCitableChannelSlugs({ channels: [] })], []); +}); + +test("citedChannels: written only when non-empty, re-parsed and pool-filtered on the way out", () => { + assert.equal("citedChannels" in siteToDisk(parseSite("s", {})), false); + assert.equal("citedChannels" in siteToDisk(parseSite("s", { citedChannels: [] })), false); + const site = parseSite("s", { channels: [{ slug: "pool" }], citedChannels: [{ slug: "critic" }] }); + const disk = siteToDisk(site) as Record<string, unknown>; + assert.deepEqual(disk.citedChannels, [{ slug: "critic" }]); + // Written beside the pool, after `channels`. + const keys = Object.keys(disk); + assert.equal(keys.indexOf("citedChannels"), keys.indexOf("channels") + 1); + // A caller's list is re-parsed: blanks, repeats and pool slugs are not persisted. + assert.deepEqual( + siteToDisk({ ...site, citedChannels: [{ slug: " critic " }, { slug: "critic" }, { slug: "pool" }, { slug: "" }] }) + .citedChannels, + [{ slug: "critic" }], + ); + assert.equal("citedChannels" in siteToDisk({ ...site, citedChannels: [{ slug: "pool" }] }), false); +}); + +test("writeSite → getSite round-trips citedChannels, and patchSite keeps the key", async () => { + const paths = scratchPaths(await mkdtemp(path.join(os.tmpdir(), "site-"))); + const site = parseSite("s", { + channels: [{ slug: "pool" }], + citedChannels: [{ slug: "critic" }, { slug: "other-critic" }], + search: false, + reports: ["one"], + }); + await writeSite(site, paths); + assert.deepEqual(getSite("s", paths), site); + const disk = JSON.parse(await readFile(siteConfigFile(paths, "s"), "utf8")); + assert.deepEqual(disk.citedChannels, [{ slug: "critic" }, { slug: "other-critic" }]); + // A surface that patches another key leaves the cited scope as it is. + const patched = await patchSite("s", { reports: ["one", "two"] }, paths); + assert.deepEqual(patched?.citedChannels, [{ slug: "critic" }, { slug: "other-critic" }]); + // Emptied, the key leaves the file. + await patchSite("s", { citedChannels: [] }, paths); + const after = JSON.parse(await readFile(siteConfigFile(paths, "s"), "utf8")); + assert.equal("citedChannels" in after, false); + assert.deepEqual(getSite("s", paths).citedChannels, []); +}); + +test("channelsOnlyOnUnlistedSites ignores cited-only slugs: the cited scope publishes no channel", () => { + const sites = [ + parseSite("shown", { channels: [{ slug: "shared" }], citedChannels: [{ slug: "critic" }] }), + parseSite("hidden", { listed: false, channels: [{ slug: "secret" }], citedChannels: [{ slug: "critic2" }] }), + ]; + assert.deepEqual([...channelsOnlyOnUnlistedSites(sites)], ["secret"]); +}); diff --git a/common/lib/siteSchema.ts b/common/lib/siteSchema.ts @@ -62,6 +62,15 @@ export const SITE_CHANNEL_MEMBERSHIP_FIELD_DOCS: FieldDocs<SiteChannelMembership order: "Optional explicit ordering hint within the site (lower first); floored to an integer.", }; +// Each field is documented in SITE_CITED_CHANNEL_FIELD_DOCS below. +export type SiteCitedChannel = { + slug: string; +}; + +export const SITE_CITED_CHANNEL_FIELD_DOCS: FieldDocs<SiteCitedChannel> = { + slug: "Channel slug (its directory name under `transcripts/channels/`). Trimmed; blank and duplicate slugs are dropped, and so is a slug already in `channels`.", +}; + // Each field is documented in RELATED_SITE_GROUP_FIELD_DOCS below. export type RelatedSiteGroup = { label?: string; @@ -148,6 +157,7 @@ export type Site = { groups: ChannelGroup[]; defaultGroupId: string; channels: SiteChannelMembership[]; + citedChannels?: SiteCitedChannel[]; cloudflareProject?: string; accent?: string; siteUrl?: string; @@ -181,7 +191,9 @@ export const SITE_FIELD_DOCS: FieldDocs<Site> = { defaultGroupId: "The group a channel falls into when its membership names none (or an unknown one). Must name a configured group on save; on read an unknown value resolves to the first group.", channels: - "The channels this site exposes. A channel absent from this list is not built or deployed for this site even though its data exists in the pool.", + "The channels this site exposes — its pool: what it builds, browses, searches and lists in its `/corpus.json`, and the pool its citations resolve against. A channel absent from this list is not built or deployed for this site even though its data exists in the pool (a channel in `citedChannels` publishes only what this site's reports cite).", + citedChannels: + "Channels in the cited scope: channels this site's reports may cite without the site publishing them. A cited-only channel publishes only what the reports cite — the moment pages and their clips — with no browse page, search entry, transcripts, subs, digests or `/corpus.json` entry, and its moments link no corpus page. A slug already in `channels` is dropped (the pool wins). Written only when non-empty; absent = none. It fails closed: a reader that does not know the key drops it, and compose then refuses a citation of the channel as `not-in-site` — it never publishes the channel's transcripts.", cloudflareProject: "Cloudflare Pages project name this site deploys to (`wrangler pages deploy out --project-name <cloudflareProject>`). Trimmed; blank = none.", accent: @@ -197,7 +209,7 @@ export const SITE_FIELD_DOCS: FieldDocs<Site> = { relatedSites: "Pulls specific siblings to the front of the footer's cross-site list, in named groups. Siblings not named here fall into a trailing \"Other sites\" group. Absent/empty = one flat list of every sibling.", search: - "Whether this site publishes its searchable corpus. Opt-OUT: absent/true = on, only an explicit `false` is written. Off = report-only: the site publishes only its `reports` and the moments they cite — no search, browse, transcripts or archives; `channels` is the pool its citations resolve against, and its `/corpus.json` says `\"scope\": \"cited\"`. A report-only site is never listed (as `listed: false`, whatever `listed` says). Legacy `publish: \"cited\"` reads as `false`.", + "Whether this site publishes its searchable corpus. Opt-OUT: absent/true = on, only an explicit `false` is written. Off = report-only: the site publishes only its `reports` and the moments they cite — no search, browse, transcripts or archives; `channels` is the pool its citations resolve against (with `citedChannels`), and its `/corpus.json` says `\"scope\": \"cited\"`. A report-only site is never listed (as `listed: false`, whatever `listed` says). Legacy `publish: \"cited\"` reads as `false`.", pwa: "Whether this site ships an installable PWA (service worker + web manifest). Default false: a \"dumb instance\" that serves the CORS-enabled JSON federation contract but is not independently installable, so a visitor trusts only the hub PWA. Stored only when true.", archives: @@ -286,6 +298,44 @@ export function isListedSite(site: Pick<Site, "listed" | "audience" | "search">) return site.listed !== false && !isPrivateSite(site) && !isCitedSite(site); } +// THE POOL: the channel slugs a site exposes — builds, browses, searches and +// lists in its corpus.json. Pool-only: a cited-only channel (`citedChannels`) +// is not here. Used to scope the editor's site-specific views (dashboard, +// channels) and everything a build publishes per channel. +// The channel lists the helpers below read, readonly so a guard's narrower +// shape (lib/builtExport.ts) fits as well as a Site. +type ChannelLists = { + channels: readonly { slug: string }[]; + citedChannels?: readonly { slug: string }[]; +}; + +export function siteChannelSlugs(site: Pick<ChannelLists, "channels">): Set<string> { + return new Set(site.channels.map((c) => c.slug)); +} + +// THE CITABLE SET: the pool plus the cited-only channels — what a report on +// this site may cite (compose's and reportMedia's membership checks). Never a +// publish set: a cited-only channel publishes only the moments cited. +export function siteCitableChannelSlugs(site: ChannelLists): Set<string> { + const out = siteChannelSlugs(site); + for (const c of site.citedChannels ?? []) out.add(c.slug); + return out; +} + +// THE ONE PREDICATE for a cited-only channel on a site: in `citedChannels` and +// not in the pool (the pool wins, as the parser drops such a slug anyway). +export function isCitedOnlyChannel(site: ChannelLists, slug: string): boolean { + if (site.channels.some((c) => c.slug === slug)) return false; + return (site.citedChannels ?? []).some((c) => c.slug === slug); +} + +// The sentence a citation of a channel outside the citable set is refused +// with (`not-in-site`, compose and prepare): it names both keys, since either +// would let the site cite the channel. +export function notInSiteMessage(slug: string): string { + return `channel "${slug}" is in neither this site's \`channels\` nor its \`citedChannels\``; +} + // The channels whose content belongs to unlisted sites alone: exposed by at // least one site, and by no listed one. No public total counts them. A channel // a listed site also exposes is not here (it is credited to the listed site), @@ -329,6 +379,33 @@ export function parseSiteChannels(input: unknown): SiteChannelMembership[] { return out; } +// Parse the cited-only channels: trimmed slugs, blanks and repeats dropped, +// order preserved. Dropping a slug already in `channels` is the object step's +// (it needs the sibling key). +export function parseSiteCitedChannels(input: unknown): SiteCitedChannel[] { + if (!Array.isArray(input)) return []; + const out: SiteCitedChannel[] = []; + const seen = new Set<string>(); + for (const raw of input) { + if (!raw || typeof raw !== "object") continue; + const r = raw as Record<string, unknown>; + const slug = typeof r.slug === "string" ? r.slug.trim() : ""; + if (!slug || seen.has(slug)) continue; + seen.add(slug); + out.push({ slug }); + } + return out; +} + +// The cited-only channels with any slug the pool already holds removed. +function citedOutsidePool( + cited: readonly SiteCitedChannel[], + channels: readonly SiteChannelMembership[], +): SiteCitedChannel[] { + const pool = new Set(channels.map((c) => c.slug)); + return cited.filter((c) => !pool.has(c.slug)); +} + // Normalize a raw siteUrl into a trimmed absolute http(s) URL with no trailing // slash, or undefined when missing/not a usable absolute URL. Relative or // scheme-less values are rejected — a cross-site link must be absolute. @@ -406,6 +483,8 @@ export const siteFieldsSchema = z.object({ // Resolved against `groups` in the object step below. defaultGroupId: settingsField((v): unknown => v).describe(d.defaultGroupId), channels: settingsField(parseSiteChannels).describe(d.channels), + // A slug already in `channels` is dropped in the object step below. + citedChannels: settingsField(parseSiteCitedChannels).describe(d.citedChannels), cloudflareProject: settingsField((v): string | undefined => typeof v === "string" && v.trim() ? v.trim() : undefined, ).describe(d.cloudflareProject), @@ -435,7 +514,7 @@ export const siteFieldsSchema = z.object({ publish: settingsField(parseSitePublish).describe(d.publish), }); -// The whole schema: the per-key object, then the three sibling-dependent +// The whole schema: the per-key object, then the four sibling-dependent // fields. // // THE OBJECT STEP ALSO RE-EMITS EVERY KEY, in order. zod 4 omits a key that was @@ -461,6 +540,8 @@ export const siteSchema = z.preprocess(migrateLegacyPublish, siteFieldsSchema).t } return c; }), + // The pool wins: a cited-only slug the pool already holds is dropped. + citedChannels: citedOutsidePool(s.citedChannels, s.channels), // A private site at most builds; no Pages project, no deploy policy. publish: s.publish ? { auto: clampSitePublishPolicy(s, s.publish.auto) } : undefined, }; @@ -490,6 +571,10 @@ export function siteToDisk(site: Site): Site { const channels = parseSiteChannels(site.channels).filter( (c) => !c.groupId || groups.some((g) => g.id === c.groupId), ); + const citedChannels = citedOutsidePool( + parseSiteCitedChannels(site.citedChannels), + channels, + ); const relatedSites = parseRelatedSites(site.relatedSites); const reports = parseSiteReports(site.reports); const accent = parseAccentSetting(site.accent); @@ -512,6 +597,8 @@ export function siteToDisk(site: Site): Site { groups, defaultGroupId: site.defaultGroupId, channels, + // None is the default: only a non-empty cited scope is persisted. + ...(citedChannels.length > 0 ? { citedChannels } : {}), ...(site.cloudflareProject && site.cloudflareProject.trim() ? { cloudflareProject: site.cloudflareProject.trim() } : {}), diff --git a/common/publish/build.ts b/common/publish/build.ts @@ -15,6 +15,7 @@ import { Upload } from "@aws-sdk/lib-storage"; import { runChildIntoLog } from "../jobs/runChild"; import { builtBundleProblem, + builtCitedOnlyProblem, builtHubProblem, builtScopeProblem, citedBuildProblem, @@ -199,10 +200,15 @@ export async function runBuildPhase( if (code !== 0) return code; // A CITED site's build must hold nothing but its reports, their moments and // the shell (lib/builtExport.ts citedBuildProblem) — and must BE a cited - // build. Failing here is loud and early; every deploy path asks again. + // build; and no site's build may publish a cited-only channel's corpus + // (builtCitedOnlyProblem). Failing here is loud and early; every deploy + // path asks again. const outDir = resolveOutDir(siteId, paths); + const builtSite = getSite(siteId, paths); const scopeProblem = - citedBuildProblem(outDir) ?? builtScopeProblem(getSite(siteId, paths), outDir); + citedBuildProblem(outDir) ?? + builtScopeProblem(builtSite, outDir) ?? + builtCitedOnlyProblem(builtSite, outDir); if (scopeProblem) { onLog(`[build] REFUSED — ${scopeProblem}.\n`); return 1; diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts @@ -47,7 +47,9 @@ const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION, reportMediaDir, reportMediaIn const { QUOTE_CHECK_METHOD } = await import("../lib/citations/verify"); const { parseCitationSet } = await import("../lib/citations/validate"); const { CONTRACT } = await import("../lib/archive/contract"); -const { citedBuildProblem, builtBundleProblem, reportHistoryProblem } = await import("../lib/builtExport"); +const { citedBuildProblem, builtBundleProblem, builtCitedOnlyProblem, reportHistoryProblem } = await import( + "../lib/builtExport" +); const paths = getPaths(); const VIDEOS = "demo-channel"; @@ -886,3 +888,95 @@ test("a report's notes.json (umtool's operator notes) is never published, export } } }); + +// RELEASE 23 — cited-only channels (`citedChannels`). Three sites cite the same +// report: `padded` has the video channel in its pool (today's padding, which +// publishes the channel's corpus); `padded-private` and `padded-cited` keep it +// in the cited scope instead (pool [SOCIAL], cited [VIDEOS]) — its moments and +// clips publish, its corpus does not, and no moment links into a corpus. +test("a cited-only channel: its moment pages and clips publish on the citing site, its corpus never does", async () => { + const pool = [{ slug: SOCIAL, groupId: "default" }]; + const citedScope = { reports: [REPORT], channels: pool, citedChannels: [{ slug: VIDEOS }] }; + seedSite("padded", { reports: [REPORT] }); + seedSite("padded-private", { ...citedScope, audience: "private" }); + seedSite("padded-cited", citedScope); + seedSite("unpadded", { reports: [REPORT], channels: pool }); + await buildIndex({ paths, onLog: () => {} }); + + const abc = `${VIDEOS}/abc123/10.00-20.00`; + type Moment = { record: { corpusUrl?: string }; clip?: { src: string } }; + + // Padding: the channel's corpus is published, and its moments link into it. + await compose("padded"); + assert.ok(existsSync(pub("transcripts", VIDEOS))); + assert.equal(readJson<Moment>(pub("m", abc, "moment.json")).record.corpusUrl, `/?v=${VIDEOS}%2Fabc123&t=10`); + // A padded build is refused as the cited site's: it publishes the corpus. + const asCited = { siteId: "padded-cited", channels: pool, citedChannels: [{ slug: VIDEOS }] }; + assert.match(builtCitedOnlyProblem(asCited, paths.exportPublicDir) ?? "", /transcripts\/demo-channel\//); + // What a padded build leaves in the shared public dir, and a stray digest. + writeText(pub("digests", VIDEOS, "manifest.json"), "{}"); + + for (const siteId of ["padded-cited", "padded-private"]) { + await compose(siteId); + const files = filesUnder(paths.exportPublicDir); + // The cited channel's moment pages and clips publish ... + const span = readJson<Moment>(pub("m", abc, "moment.json")); + assert.equal(span.clip?.src, `/media/clips/${abc}.mp4`, siteId); + assert.ok(files.includes(`media/clips/${abc}.mp4`), siteId); + assert.ok(files.includes(`m/${VIDEOS}/def456/5.00-9.00/moment.json`), siteId); + // ... with no link into a corpus that does not publish it; the pool's post + // still links into this site's corpus. + assert.equal(span.record.corpusUrl, undefined, siteId); + assert.equal(readJson<Moment>(pub("m", SOCIAL, "3kabc", "moment.json")).record.corpusUrl, `/?v=${SOCIAL}%2F3kabc&vm=post`); + const view = readJson<View>(pub("reports", REPORT, "page.json")); + assert.equal(view.citations.c01.record?.corpusUrl, undefined, siteId); + assert.equal(view.citations.c02.record?.corpusUrl, undefined, siteId); + assert.ok(view.citations.p01.record?.corpusUrl, siteId); + // Its transcripts, subs and digests trees are pruned: nothing of the + // channel's but its moments and clips. + for (const tree of ["transcripts", "subs", "digests", "posts", "stats", "archives"]) { + assert.ok(!existsSync(pub(tree, VIDEOS)), `${siteId}: ${tree}/${VIDEOS}`); + } + assert.deepEqual( + files.filter((f) => f.includes(VIDEOS) && !f.startsWith(`m/${VIDEOS}/`) && !f.startsWith(`media/clips/${VIDEOS}/`)), + [], + siteId, + ); + // No browse, search or contract file names it: only the report, its + // citations, the moment index and the sitemap do. + const naming = files.filter( + (f) => + !f.startsWith("reports/") && + !f.startsWith("m/") && + !f.startsWith("media/") && + f !== "sitemap.xml" && + readFileSync(pub(f)).includes(VIDEOS), + ); + assert.deepEqual(naming, [], siteId); + assert.ok(files.includes("summaries/manifest.json"), `${siteId}: a full site still browses its pool`); + // corpus.json and site.json list the pool alone. + const corpus = readJson<{ channels: { slug: string }[]; site: { audience?: string } }>(pub("corpus.json")); + assert.deepEqual(corpus.channels.map((c) => c.slug), [SOCIAL], siteId); + const site = readJson<{ channels: { slug: string }[] }>(pub("site.json")); + assert.deepEqual(site.channels.map((c) => c.slug), [SOCIAL], siteId); + // The sitemap lists the moment. + assert.match(readFileSync(pub("sitemap.xml"), "utf8"), new RegExp(`/m/${abc}/`), siteId); + // And the build guard passes what compose wrote. + assert.equal(builtCitedOnlyProblem({ ...asCited, siteId }, paths.exportPublicDir), null, siteId); + } + assert.equal(readJson<{ site: { audience?: string } }>(pub("corpus.json")).site.audience, "private"); + + // In neither key, the channel is refused: compose names both. + await assert.rejects(compose("unpadded"), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.citation]), + [ + ["not-in-site", `${REPORT}#c01`], + ["not-in-site", `${REPORT}#c02`], + ], + ); + assert.match(e.message, /"demo-channel" is in neither this site's `channels` nor its `citedChannels`/); + return true; + }); +}); diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -64,8 +64,14 @@ import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs import path from "node:path"; import { publishFileSizeProblem } from "../lib/builtExport"; import type { Paths } from "../lib/paths"; -import { siteChannelSlugs, type Site } from "../lib/site"; -import { isCitedSite, parseSiteUrl } from "../lib/siteSchema"; +import { type Site } from "../lib/site"; +import { + isCitedOnlyChannel, + isCitedSite, + notInSiteMessage, + parseSiteUrl, + siteCitableChannelSlugs, +} from "../lib/siteSchema"; import { getSettings } from "../lib/settings"; import { postsVisibleTo } from "../lib/postsVisibility"; import { assertChannelTextReadable } from "../lib/channelMedia"; @@ -474,7 +480,10 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi const { paths, site } = opts; const log = opts.log ?? (() => {}); const now = (opts.now?.() ?? new Date()).toISOString(); - const cited = isCitedSite(site); + const citedSite = isCitedSite(site); + // No corpus page to link a moment to: a cited site publishes none, and a + // cited-only channel (`citedChannels`) is not in the site's corpus. + const noCorpus = (slug: string) => citedSite || isCitedOnlyChannel(site, slug); const problems: ComposeReportsProblem[] = []; const loaded = await loadSiteReports(paths, site); @@ -492,7 +501,9 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi const momentCues = new Map<string, Cue[]>(); const settings = opts.settings ?? getSettings(); - const pool = siteChannelSlugs(site); + // What a report on this site may cite: the pool plus its cited-only + // channels. Never a publish set — only the cited moments publish. + const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug).catch(() => null)); @@ -528,8 +539,8 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi }; // Resolve and verify every citation the reports cite. A channel outside the - // site's pool, or a post the site may not carry, is refused before its - // record is read. + // site's citable set (`channels` plus `citedChannels`), or a post the site + // may not carry, is refused before its record is read. const refusedChannel = new Set<string>(); for (const report of reports) { // The report's video and its poster: on disk, and small enough to publish. @@ -559,8 +570,8 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi } continue; } - if (!pool.has(c.channel)) { - problems.push({ kind: "not-in-site", citation: ref, report: report.id, message: `channel "${c.channel}" is not one of this site's channels` }); + if (!citable.has(c.channel)) { + problems.push({ kind: "not-in-site", citation: ref, report: report.id, message: notInSiteMessage(c.channel) }); refusedChannel.add(c.channel); continue; } @@ -662,7 +673,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi date: post.createdAt.slice(0, 10), platform: post.platform, originalUrl: post.url, - corpusUrl: cited ? undefined : corpusLink(`${c.channel}/${c.id}`, { vm: "post" }), + corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(`${c.channel}/${c.id}`, { vm: "post" }), }); } const { summary, archiveOrg, wayback } = (await recordOf(c.channel, c.id))!; @@ -684,7 +695,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi originalUrl: links.original.url, originalLabel: links.original.label, downloads: [links.copy], - corpusUrl: cited ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); } if (summary.platform === "archiveorg") { @@ -701,7 +712,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi originalUrl: links.original?.url ?? (summary.webpageUrl || undefined), originalLabel: links.original?.label, downloads: links.downloads.length > 0 ? links.downloads : undefined, - corpusUrl: cited ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); } return defined({ @@ -716,7 +727,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi : (platformMomentUrl(summary.webpageUrl, summary.platform as Platform, c.start) ?? undefined), // The viewer keys a record by its PUBLISHED slug, which on a platform // with two ids is not the data dir's name. - corpusUrl: cited ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); }; // buildReportPageView's resolver is synchronous: resolve every cited diff --git a/common/publish/deployStage.test.ts b/common/publish/deployStage.test.ts @@ -384,7 +384,7 @@ test("production ships only a build of main; the same build may go to a preview" } }); -test("the bundle guards: another site's bundle and a private build are refused before wrangler", async () => { +test("the bundle guards: another site's bundle, a private build and a cited-only channel's corpus are refused before wrangler", async () => { const fx = fixture(); try { site(fx, "anilyzer"); @@ -401,8 +401,17 @@ test("the bundle guards: another site's bundle and a private build are refused b 3, /private build of "bonnellyzer"/, ); + // A cited-only channel's corpus in the bundle (release 23). + site(fx, "citing", { channels: [{ slug: "pool" }], citedChannels: [{ slug: "critic" }] }); + built(fx, "citing", { corpus: { site: { id: "citing" }, channels: [{ slug: "pool" }, { slug: "critic" }] } }); + await refused( + runDeployStage(ctx(fx, TOKEN), { kind: "deploy-site", target: "citing" }), + 3, + /cites "critic" only \(citedChannels\), but .* publishes its corpus: "critic" in corpus\.json's channels/, + ); assert.deepEqual(sidecar(fx, "anilyzer"), []); assert.deepEqual(sidecar(fx, "bonnellyzer"), []); + assert.deepEqual(sidecar(fx, "citing"), []); } finally { fx.cleanup(); } diff --git a/common/publish/deployStage.ts b/common/publish/deployStage.ts @@ -25,7 +25,7 @@ // 5. the bundle guards over the bundle itself (exit 3): builtBundleProblem // (the site's own, by site.json AND corpus.json — the stricter twin of // builtSiteProblem, naming the directory), builtAudienceProblem, -// builtScopeProblem; the hub's builtHubProblem; the homepage's +// builtScopeProblem, builtCitedOnlyProblem; the hub's builtHubProblem; the homepage's // builtHomepageProblem + publishedSourceProblem // 6. `--to local`: the bundle is copied into ARCHILYZER_SITE_OUT (the // directory the compose `site` service serves; the homepage's is @@ -53,6 +53,7 @@ import { runChildIntoLog } from "../jobs/runChild"; import { builtAudienceProblem, builtBundleProblem, + builtCitedOnlyProblem, builtHomepageProblem, builtHubProblem, builtScopeProblem, @@ -427,7 +428,10 @@ export async function runDeployStage( // --- 5. the bundle guards --- if (req.kind === "deploy-site") { const problem = - builtBundleProblem(outDir, target) ?? builtAudienceProblem(outDir) ?? builtScopeProblem(site!, outDir); + builtBundleProblem(outDir, target) ?? + builtAudienceProblem(outDir) ?? + builtScopeProblem(site!, outDir) ?? + builtCitedOnlyProblem(site!, outDir); if (problem) { refuse(`${problem}. Nothing was sent to Cloudflare Pages; build ${target} again, then deploy.`, 3); } diff --git a/common/publish/inputSig.test.ts b/common/publish/inputSig.test.ts @@ -180,6 +180,43 @@ test("inputSig moves with what the export BUILD renders: social links, the hub u } }); +// RELEASE 23: a cited-only channel's records and posts are read by compose +// (its cited moments), so its shared transcripts and posts trees are signed — +// and its subs and digests, which nothing on the site publishes, are not. +test("inputSig signs a cited-only channel's transcripts and posts trees, and nothing changes for a site with none", async () => { + const s = setup(); + try { + const none = await s.sig(); + // An empty cited scope is no change at all. + (s.site as { citedChannels?: unknown }).citedChannels = []; + assert.equal(await s.sig(), none, "an empty citedChannels signs as before"); + // A pool slug in citedChannels is the pool's: nothing new is signed. + (s.site as { citedChannels?: unknown }).citedChannels = [{ slug: "a" }]; + assert.equal(await s.sig(), none, "the pool wins"); + s.write(path.join(s.paths.exportSharedTranscriptsDir, "other", "page-0002.json"), "[8]"); + assert.equal(await s.sig(), none, "another channel's tree is not this site's input"); + + (s.site as { citedChannels?: unknown }).citedChannels = [{ slug: "other" }]; + let last = await s.sig(); + assert.notEqual(last, none, "the cited scope is part of the signature"); + const moved = async (what: string) => { + const now = await s.sig(); + assert.notEqual(now, last, what); + last = now; + }; + s.write(path.join(s.paths.exportSharedTranscriptsDir, "other", "page-0003.json"), "[9]"); + await moved("a cited-only channel's transcripts"); + s.write(path.join(s.paths.exportSharedPostsDir, "other", "page-0000.json"), "[10]"); + await moved("a cited-only channel's posts"); + s.write(path.join(s.paths.exportSharedSubsDir, "other", "page-0000.json"), "[11]"); + assert.equal(await s.sig(), last, "its subs are never published here"); + s.write(path.join(s.paths.exportSharedDigestsDir, "other", "page-0000.json"), "[12]"); + assert.equal(await s.sig(), last, "nor its digests"); + } finally { + rmSync(s.root, { recursive: true, force: true }); + } +}); + test("a manifest-only member tree is signed as one, not as absent", async () => { const s = setup(); try { diff --git a/common/publish/inputSig.ts b/common/publish/inputSig.ts @@ -11,6 +11,10 @@ // report media and exports); // - each PUBLISHED member channel's shared transcripts / subs / posts / // digests tree, `manifest.json` ignored (its `generatedAt` churns); +// - each cited-only channel's (`citedChannels`) shared transcripts / posts +// tree: compose reads its cited records and posts from the channel's data, +// which those trees are built from (release 23). Signed only when the site +// has one, so a site with none keeps its signature; // - the bytes of `site.json`, and the signature of the site's config dir // (`sites/<id>/`: tags, aliases, reports); // - the corpus-wide files compose reads at compose time (search aliases, @@ -42,7 +46,7 @@ import { siteIndexDir, type Site, } from "../lib/site"; -import { isListedSite } from "../lib/siteSchema"; +import { isCitedOnlyChannel, isListedSite } from "../lib/siteSchema"; import { INDEX_SCANNED_AT_KEY } from "../lib/stats"; import { readChannelConfig } from "../controller/channels"; import type { ChannelConfig } from "../lib/channelConfig"; @@ -118,6 +122,20 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> { lines.push(`${tree}/${slug}\t${await channelTreeSig(root, slug, cache)}`); } } + // A cited-only channel publishes only its cited moments, but they are read + // from its records and posts: a change there must make the site stale. + const citedOnly = [...new Set((site.citedChannels ?? []).map((c) => c.slug))] + .filter((slug) => isCitedOnlyChannel(site, slug)) + .sort(); + if (citedOnly.length > 0) lines.push(`cited-only\t${citedOnly.join(",")}`); + for (const slug of citedOnly) { + for (const [tree, root] of [ + ["transcripts", paths.exportSharedTranscriptsDir], + ["posts", paths.exportSharedPostsDir], + ] as const) { + lines.push(`cited/${tree}/${slug}\t${await channelTreeSig(root, slug, cache)}`); + } + } lines.push(`site.json\t${await fileBytesSig(siteConfigFile(paths, site.siteId))}`); lines.push(`site-dir\t${await dirSignature(siteDir(paths, site.siteId))}`); for (const file of [ diff --git a/common/publish/missingEvidenceWindows.test.ts b/common/publish/missingEvidenceWindows.test.ts @@ -124,6 +124,28 @@ test("on disk, to fetch, and what no window can fill", async () => { elsewhere: "not-in-site", }); assert.match(r.unfetchable.find((u) => u.id === "gone1")!.message, /deleted/); + // The refusal names both keys that would let the site cite the channel. + assert.match(r.unfetchable.find((u) => u.id === "elsewhere")!.message, /`channels` nor its `citedChannels`/); +}); + +test("a cited-only channel (citedChannels) is citable: its window is one to fetch, not not-in-site", async () => { + const CITING = "demo-citing"; + writeJson(path.join(paths.sitesDir, CITING, "site.json"), { + title: "Citing", + channels: [{ slug: CH }], + citedChannels: [{ slug: OFF }], + reports: ["r3"], + }); + writeJson( + path.join(paths.sitesDir, CITING, "reports", "r3", "report.json"), + report("r3", { e01: { kind: "video", channel: OFF, id: "elsewhere", start: 5, end: 6, quote: "a critic's" } }), + ); + const r = await missingEvidenceWindows(paths, CITING); + assert.deepEqual(r.unfetchable, []); + assert.deepEqual( + r.missing.map((m) => [m.slug, m.id, m.citations]), + [[OFF, "elsewhere", ["r3#e01"]]], + ); }); test("a site that does not exist is an error", async () => { diff --git a/common/publish/reportMedia.test.ts b/common/publish/reportMedia.test.ts @@ -253,3 +253,31 @@ test("a clean prepare ends by exporting the reports; a host with no browser skip assert.deepEqual(manifest.notes, ["report.pdf skipped: no browser here", "slides.pdf skipped: no browser here"]); assert.ok(out.some((l) => l.includes("report.pdf skipped: no browser here"))); }); + +// RELEASE 23: a cited-only channel (`citedChannels`) is citable — its moment is +// cut like a pool channel's — while a channel in neither key is refused with a +// sentence naming both. +test("a cited-only channel's moment is prepared; a channel in neither key is not-in-site, naming both keys", async () => { + const CITING = "demo-citing"; + writeJson(path.join(paths.sitesDir, CITING, "site.json"), { + title: "Citing", + channels: [{ slug: X }], + citedChannels: [{ slug: CH }], + reports: ["r9"], + }); + writeJson( + path.join(paths.sitesDir, CITING, "reports", "r9", "report.json"), + report("r9", { + c01: { kind: "video", channel: CH, id: "abc123", start: 1, end: 2, quote: "one" }, + c02: { kind: "video", channel: "elsewhere", id: "xyz", start: 1, end: 2, quote: "five" }, + }), + ); + const index = await prepareReportMedia({ siteId: CITING, settings: PUBLIC }); + assert.deepEqual(Object.keys(index.moments), [VIDEO_KEY]); + assert.equal(index.moments[VIDEO_KEY].kind, "video"); + assert.deepEqual( + index.problems.map((p) => [p.kind, p.moment]), + [["not-in-site", "elsewhere/xyz/1.00-2.00"]], + ); + assert.match(index.problems[0].message, /"elsewhere" is in neither this site's `channels` nor its `citedChannels`/); +}); diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -15,8 +15,8 @@ // post ./citedPostCaptures.ts copies the post's screenshot // and media — only cited posts — into the cache. // -// A citation must resolve against the site's own `channels` (the pool a cited -// site's citations may draw on), and a post must be one the site may carry +// A citation must resolve against the site's citable set — its `channels` (the +// pool) plus its `citedChannels` (cited only) — and a post must be one the site may carry // (lib/postsVisibility.ts — a public site never shows a private platform's // posts, cited or not). // @@ -48,7 +48,15 @@ import path from "node:path"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; -import { getSite, listSiteIds, siteChannelSlugs, siteDir, siteIndexDir, type Site } from "../lib/site"; +import { + getSite, + listSiteIds, + notInSiteMessage, + siteCitableChannelSlugs, + siteDir, + siteIndexDir, + type Site, +} from "../lib/site"; import { postsVisibleTo } from "../lib/postsVisibility"; import { inspectChannelMedia } from "../lib/channelMedia"; import type { ChannelConfig } from "../lib/channelConfig"; @@ -251,7 +259,7 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi const moments = citedMoments(reports); log(`${moments.length} cited moment(s) with media.`); - const pool = siteChannelSlugs(site); + const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug)); @@ -267,8 +275,8 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi for (const m of moments) { if (opts.signal?.aborted) throw new Error("prepare cancelled"); const slug = m.moment.channel; - if (!pool.has(slug)) { - fail(m, "not-in-site", `channel "${slug}" is not one of this site's channels`); + if (!citable.has(slug)) { + fail(m, "not-in-site", notInSiteMessage(slug)); continue; } const config = await configOf(slug); @@ -463,7 +471,7 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom if (typeof c.quote === "string" && c.quote.trim()) quotes.set(`${report.id}#${cid}`, c.quote.trim()); } } - const pool = siteChannelSlugs(site); + const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug)); @@ -490,8 +498,8 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom const unfetchable = (why: UnfetchableReason, message: string) => out.unfetchable.push({ ...window, why, message }); - if (!pool.has(slug)) { - unfetchable("not-in-site", `channel "${slug}" is not one of this site's channels`); + if (!citable.has(slug)) { + unfetchable("not-in-site", notInSiteMessage(slug)); continue; } const config = await configOf(slug); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **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. - **What an Odysee or BitChute channel lists that it does not hold.** `pnpm ops get remote-listing <slug>` reads the channel's listing once, on the platform's own queue at its pace, and prints the videos listed but not held and the ones held but no longer listed. Nothing is written. diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts @@ -30,6 +30,7 @@ await corpus.writeSettings({ await corpus.writeSite("demo-site", { siteUrl: "https://demo.example", channels: [{ slug: "test-youtube", groupId: "default" }], + citedChannels: [{ slug: "demo-critic" }], }); await writeFile( path.join(corpus.transcripts, "channels", "test-youtube", "snapshot.json"), @@ -96,6 +97,7 @@ test("get sites lists each site from its site.json", async () => { search: true, publish: null, channels: ["test-youtube"], + citedChannels: ["demo-critic"], }, ]); }); diff --git a/editor/app/api/ops/sites/route.ts b/editor/app/api/ops/sites/route.ts @@ -9,7 +9,8 @@ export const dynamic = "force-dynamic"; // // Every site, one row each, from its site.json: id, title, public URL // (`siteUrl`), Pages project, audience, whether the family lists it, whether it -// publishes search, its publish policy and the channels it carries. The deep +// publishes search, its publish policy, the channels it carries (its pool) and +// the channels it cites without publishing (`citedChannels`). The deep // status of a site's builds and deploys is `get publish`. export async function GET(request: Request) { return readRoute(request, [], async () => ({ @@ -23,6 +24,7 @@ export async function GET(request: Request) { search: s.search !== false, publish: s.publish ?? null, channels: s.channels.map((c) => c.slug), + citedChannels: (s.citedChannels ?? []).map((c) => c.slug), })), })); } diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts @@ -33,6 +33,7 @@ import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSit import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks"; import { formValues, type FormState } from "../lib/formState"; import { reportSiteKeysFromForm } from "./lib/reportSiteKeys"; +import { citedChannelsFromForm } from "./lib/citedChannelsFromForm"; // A failure carries what was submitted, so SiteForm keeps what was typed // (lib/formState.ts). @@ -256,6 +257,12 @@ export async function saveSiteAction( }; } const channels = parseSiteChannels(channelsInput); + // The cited scope: channels outside the pool this site's reports may cite + // without publishing them (lib/citedChannelsFromForm.ts). + const citedChannels = citedChannelsFromForm(formData, channels); + if (citedChannels === null) { + return { ok: false, error: "Cited channels payload is malformed", values }; + } const site: Site = { siteId, @@ -268,6 +275,7 @@ export async function saveSiteAction( groups, defaultGroupId, channels, + ...(citedChannels.length > 0 ? { citedChannels } : {}), ...(accent ? { accent } : {}), ...(cloudflareProject ? { cloudflareProject } : {}), ...(siteUrl ? { siteUrl } : {}), diff --git a/editor/app/sites/components/SiteForm.tsx b/editor/app/sites/components/SiteForm.tsx @@ -122,13 +122,32 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { }), ); - const toggleMember = (slug: string, on: boolean) => + // The cited scope (site.json `citedChannels`): channels outside the pool + // this site's reports may cite without publishing them. A row in the pool + // is never cited-only, so ticking Include clears its box. + const [cited, setCited] = useState<Set<string>>( + () => new Set((initial.citedChannels ?? []).map((c) => c.slug)), + ); + const citedChannelsJson = JSON.stringify( + channels.filter((c) => cited.has(c.slug) && !members.has(c.slug)).map((c) => c.slug), + ); + const toggleCited = (slug: string, on: boolean) => + setCited((prev) => { + const next = new Set(prev); + if (on) next.add(slug); + else next.delete(slug); + return next; + }); + + const toggleMember = (slug: string, on: boolean) => { setMembers((prev) => { const next = new Map(prev); if (on) next.set(slug, prev.get(slug) ?? ""); else next.delete(slug); return next; }); + if (on) toggleCited(slug, false); + }; const setMemberGroup = (slug: string, groupId: string) => setMembers((prev) => { const next = new Map(prev); @@ -210,6 +229,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <input type="hidden" name="groupsJson" value={groupsJson} /> <input type="hidden" name="defaultGroupId" value={defaultGroupId} /> <input type="hidden" name="channelsJson" value={channelsJson} /> + <input type="hidden" name="citedChannelsJson" value={citedChannelsJson} /> <input type="hidden" name="relatedSitesJson" value={relatedSitesJson} /> {isNew ? ( @@ -539,6 +559,8 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <p className="text-xs text-muted-foreground"> Pick the channels this site exposes and the group each belongs to. Channels not checked here are excluded from this site&apos;s build. + &ldquo;Cited only&rdquo; lets this site&apos;s reports cite a channel + it does not expose: only the cited moments and their clips publish. </p> <div className="flex flex-col gap-1 max-h-96 overflow-y-auto"> {channels.length === 0 && ( @@ -563,6 +585,17 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <code className="text-xs text-muted-foreground">{c.slug}</code> </span> </label> + {!on && ( + <label className="flex items-center gap-1 text-xs text-muted-foreground shrink-0"> + <ControlledCheck + type="checkbox" + checked={cited.has(c.slug)} + onChange={(e) => toggleCited(c.slug, e.target.checked)} + aria-label={`Cited only: ${c.name || c.slug}`} + /> + cited only + </label> + )} {on && groupOptions.length > 0 && ( <ControlledSelect value={members.get(c.slug) ?? ""} diff --git a/editor/app/sites/lib/citedChannelsFromForm.test.ts b/editor/app/sites/lib/citedChannelsFromForm.test.ts @@ -0,0 +1,35 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { CITED_CHANNELS_FIELD, citedChannelsFromForm } from "./citedChannelsFromForm"; + +// Run with: pnpm -C editor exec tsx --test "app/**/*.test.ts" + +function form(value?: string): FormData { + const fd = new FormData(); + if (value !== undefined) fd.set(CITED_CHANNELS_FIELD, value); + return fd; +} + +test("the ticked slugs, trimmed, blanks and repeats dropped, in the order sent", () => { + assert.deepEqual(citedChannelsFromForm(form('["critic", " other ", "critic", "", 3]'), []), [ + { slug: "critic" }, + { slug: "other" }, + ]); + // A `{slug}` entry reads the same as a bare slug. + assert.deepEqual(citedChannelsFromForm(form('[{"slug":"critic"}]'), []), [{ slug: "critic" }]); +}); + +test("a channel the pool holds is never cited-only: the pool wins", () => { + assert.deepEqual( + citedChannelsFromForm(form('["pool", "critic"]'), [{ slug: "pool" }]), + [{ slug: "critic" }], + ); +}); + +test("no field is no cited scope; a malformed payload is refused, never read as none", () => { + assert.deepEqual(citedChannelsFromForm(form(), []), []); + assert.deepEqual(citedChannelsFromForm(form("[]"), []), []); + assert.equal(citedChannelsFromForm(form("{"), []), null); + assert.equal(citedChannelsFromForm(form('{"slug":"x"}'), []), null); + assert.equal(citedChannelsFromForm(form('"critic"'), []), null); +}); diff --git a/editor/app/sites/lib/citedChannelsFromForm.ts b/editor/app/sites/lib/citedChannelsFromForm.ts @@ -0,0 +1,36 @@ +// The site form's cited scope (site.json `citedChannels`, release 23), pure so +// the parse is tested without a server (saveSiteAction calls it). +// +// The form posts `citedChannelsJson`: the slugs whose "Cited only" box is +// ticked, a box shown only on a channel row outside the pool. A channel the +// pool holds is never cited-only (the pool wins — ticking "Include" clears the +// box, and the schema drops such a slug anyway). The Site is rebuilt from the +// form on save, so a missing field means no cited scope; a payload that is not +// a JSON array is refused (null), never read as "none". + +import { + parseSiteCitedChannels, + type SiteChannelMembership, + type SiteCitedChannel, +} from "yt-dlp-transcript-common/lib/site"; + +export const CITED_CHANNELS_FIELD = "citedChannelsJson"; + +export function citedChannelsFromForm( + formData: FormData, + pool: readonly Pick<SiteChannelMembership, "slug">[], +): SiteCitedChannel[] | null { + const raw = formData.get(CITED_CHANNELS_FIELD); + if (raw === null) return []; + let input: unknown; + try { + input = JSON.parse(String(raw)); + } catch { + return null; + } + if (!Array.isArray(input)) return null; + // The form sends bare slugs; a `{slug}` entry reads the same. + const entries = input.map((v) => (typeof v === "string" ? { slug: v } : v)); + const inPool = new Set(pool.map((c) => c.slug)); + return parseSiteCitedChannels(entries).filter((c) => !inPool.has(c.slug)); +} diff --git a/editor/app/sites/page.tsx b/editor/app/sites/page.tsx @@ -104,7 +104,10 @@ export default async function SitesPage() { <div className="font-medium">{s.siteTitle}</div> <div className="text-xs text-muted-foreground"> <code>{s.siteId}</code> · {s.channels.length} channel - {s.channels.length === 1 ? "" : "s"} · {s.groups.length} group + {s.channels.length === 1 ? "" : "s"} + {s.citedChannels?.length ? ` · ${s.citedChannels.length} cited` : ""} + {" · "} + {s.groups.length} group {s.groups.length === 1 ? "" : "s"} {s.cloudflareProject ? ` · ${s.cloudflareProject}` : ""} </div> diff --git a/editor/e2e/sites-crud.spec.ts b/editor/e2e/sites-crud.spec.ts @@ -47,6 +47,49 @@ test("create a site with channel membership via the UI", async ({ page }) => { expect(site.channels.map((c) => c.slug)).toContain("test-youtube"); }); +// The cited scope (site.json `citedChannels`, release 23): a channel outside +// the pool this site's reports may cite without publishing it. Its box is on +// rows outside the pool only, and ticking Include clears it (the pool wins). +test("a cited-only channel saves to citedChannels, shows on the list, and Include clears it", async ({ + page, +}) => { + await resetData("one-youtube-channel-with-data"); + type CitedSiteFile = SiteFile & { citedChannels?: { slug: string }[] }; + const file = "test-transcripts/sites/citing/site.json"; + const include = page.getByRole("checkbox", { name: /include test youtube channel/i }); + const citedOnly = page.getByRole("checkbox", { name: "Cited only: Test YouTube Channel" }); + const save = async (name: RegExp) => { + await page.getByRole("button", { name }).click(); + await expect(page.getByRole("status").filter({ hasText: "Saved" })).toBeVisible(); + }; + + await page.goto("/sites/new"); + await page.getByLabel(/site id/i).fill("citing"); + await page.getByLabel(/site title/i).fill("Citing"); + await page.getByLabel(/header title/i).fill("Citing"); + await citedOnly.check(); + await save(/create site/i); + await expect(async () => { + const site = await readJson<CitedSiteFile>(file); + expect(site.channels).toEqual([]); + expect(site.citedChannels).toEqual([{ slug: "test-youtube" }]); + }).toPass({ timeout: 10_000 }); + + await page.goto("/sites"); + await expect(page.getByRole("link", { name: /Citing/ })).toContainText("0 channels · 1 cited"); + + await page.goto("/sites/citing"); + await expect(citedOnly).toBeChecked(); + await include.check(); + await expect(citedOnly).toHaveCount(0); + await save(/save site/i); + await expect(async () => { + const site = await readJson<CitedSiteFile>(file); + expect(site.channels.map((c) => c.slug)).toEqual(["test-youtube"]); + expect("citedChannels" in site).toBe(false); + }).toPass({ timeout: 10_000 }); +}); + test("list shows configured sites and edit updates branding", async ({ page, }) => { diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -169,6 +169,15 @@ Never name the curated field `tags`. Never assume a `tags.json` is the keyword l A grep for either word finds all three; read the file before assuming which. +**`cited` means four things** (release 23): + +| Which | Where | What it is | +| --- | --- | --- | +| A cited (report-only) site | `common/lib/siteSchema.ts` — `isCitedSite` (`search: false`); corpus.json `site.scope: "cited"`; `isCitedBuild` / `citedBuildProblem` (`lib/builtExport.ts`) | A site that publishes only its reports and the moments they cite. | +| A cited-only channel | `site.json` `citedChannels`; `siteCitableChannelSlugs`, `isCitedOnlyChannel` (`lib/siteSchema.ts`); `builtCitedOnlyProblem` (`lib/builtExport.ts`) | A channel a site's reports may cite without the site publishing it: its moments and clips publish, its corpus does not. `siteChannelSlugs` (and `publishedMemberSlugs`) stay pool-only. | +| `citedMoments` | `common/publish/reportMedia.ts` | The moments a site's reports cite, one per span, with the citations that cite each. | +| Compose's `citedSite` | `common/publish/composeReports.ts` `resolveSiteReports` | The local `isCitedSite(site)` (renamed from `cited` in release 23). | + **Never publish a path segment named `.git`.** wrangler's Pages upload drops `**/.git` (and `**/node_modules`) SILENTLY, and Cloudflare's managed rules block `/.git/` requests. The source mirror is `/source/archilyzer.git/` for that reason (release 12, below). A mirror named `.git` would diff --git a/plans/release-23.md b/plans/release-23.md @@ -67,3 +67,84 @@ straight from `channels/<slug>/data` (`readCitedRecord`). ## Record (Lane 2 adds "### Step S<n>, as shipped" sections here; the orchestrator adds "As it went" and "Rollout".) + +Lane 2 (`r23/cited-only` off `r23/integration` `d3296bab`), S1 → S5, one commit each, tsc clean per commit. Every +fixture is synthetic; nothing read the corpus. + +### Step S1, as shipped — the schema + +`citedChannels: [{slug}]` in `common/lib/siteSchema.ts`: `SiteCitedChannel` and its field docs, `parseSiteCitedChannels` +(trim, blanks and repeats dropped), the object step dropping a slug the pool holds, `siteToDisk` writing the key only +when non-empty (re-parsed and pool-filtered), and the nested table in `fileSchemaDocs.ts`. Absent parses to `[]`; the +type is optional, so no existing `Site` literal changed. `siteChannelSlugs` (pool-only, unchanged) moved from +`site.ts` to beside the new `siteCitableChannelSlugs` and `isCitedOnlyChannel` (all re-exported by `site.ts`). The +`channels` and `search` docs say what the pool is; SITE.md regenerated. Tests in `siteSchema.test.ts`: the shape pins +(the key in every parse), the parse rules, the round trip (the `everything` fixture carries dirty cited slugs), +`writeSite`/`getSite`, `patchSite` keeping the key, `channelsOnlyOnUnlistedSites` ignoring cited slugs. + +### Step S2, as shipped — resolution and media + +Compose's membership check (`resolveSiteReports`) and prepare's and `missingEvidenceWindows`' (`reportMedia.ts`, the +pool-membership lines only) take `siteCitableChannelSlugs`. `corpusUrl` is dropped when `citedSite || +isCitedOnlyChannel(site, channel)` (the four record views); compose's local `cited` is `citedSite`. `not-in-site`'s +sentence is one helper, `notInSiteMessage` (siteSchema.ts): `channel "<slug>" is in neither this site's `channels` nor +its `citedChannels``. `postsVisibleTo` still runs after the citable check, unchanged. **The proving test** +(`composeReports.test.ts`): `padded` (pool both channels) publishes the video channel's corpus and links its moments; +`padded-cited` and `padded-private` (pool `[SOCIAL]`, cited `[VIDEOS]`) publish its two moment pages and clips with no +`corpusUrl` (the pool's post keeps its link), prune its `transcripts/`, `subs/`, `digests/`, `posts/`, `stats/`, +`archives/` trees (a padded build and a stray digest left them in public/), no non-report file names it, corpus.json +and site.json list the pool alone, and the sitemap lists the moment; `unpadded` (pool `[SOCIAL]`, nothing cited) is +refused naming both keys. A mutation check (the `corpusUrl` drop disabled) fails it. `reportMedia.test.ts` +1 (a cited +channel's clip is cut; a channel in neither key is `not-in-site`), `missingEvidenceWindows.test.ts` +1 and a message +assertion. + +### Step S3, as shipped — staleness and the leak guard + +`siteInputSig` signs each cited-only channel's shared `transcripts` and `posts` trees (`cited/<tree>/<slug>`), and a +`cited-only` line, only when the site has one: every existing site keeps its signature. `builtCitedOnlyProblem(site, +outDir)` (`lib/builtExport.ts`) refuses an out dir holding a cited-only channel's `transcripts`, `subs`, `posts` (a +tombstone tree aside — `isTombstoneChannelPostsDir`, split out of `isTombstonePostsTree`), `digests`, `stats` or +`archives` tree, or listing it in corpus.json's or site.json's `channels`. Chained after `builtScopeProblem` in the +build phase (`publish/build.ts`), the deploy stage's bundle guards and `deployAudienceProblem`. Tests: `inputSig.test.ts` ++1, `builtExport.test.ts` +1, the deploy-stage bundle-guard test extended (refused before wrangler, nothing recorded), +and the compose proving test asks the guard over a padded build (refused) and each cited build (clean). + +### Step S4, as shipped — writers and the editor + +`renameChannel` rewrites `citedChannels` beside `channels`; `get sites` (`/api/ops/sites`) carries `citedChannels` +(slugs) and its help line says so (COMMANDS.md regenerated). The site form: a "Cited only: <name>" box on each channel +row outside the pool (never "Include …"), ticking Include clears it; the save action reads the hidden +`citedChannelsJson` through the pure `editor/app/sites/lib/citedChannelsFromForm.ts` (bare slugs or `{slug}`, a pool +slug dropped, a non-array payload refused). `/sites` shows "· N cited". Tests: `renameChannel.test.ts` (a citing site +retargeted in place), `citedChannelsFromForm.test.ts` (3), `_read.test.ts` (the ops row), and one `sites-crud.spec` +test (save to `citedChannels`, the list's count, Include clears it). + +**Stays pool-only, verified, unchanged:** `publishedMemberSlugs` (and through it the per-site index, compose's trees, +archives, tombstones, publish state and plan), poolSummary / channel-sites.json, buildStats, curatedTagsIndex, the +channel views, the seeder, the editor channel pages and `siteChannelIndex` all read `site.channels` or +`siteChannelSlugs`; none reads the cited scope. The channel page's membership writer (`siteMemberships.ts`) carries +`citedChannels` through `writeSite`, and adding a cited channel to the pool there drops it from the cited scope. + +### Step S5, as shipped — docs and this record + +REPORT.md (what compose checks) and CITATIONS.md (the `channel` rows of video, audio and post) from their sources +(`lib/report/docs.ts`, `lib/citations/schema.ts`), regenerated; FACTS "Naming hazards" gains "`cited` means four +things"; `editor/CHANGELOG.md` `[Unreleased]` leads with the bullet ("rebuild each site that uses it"). + +**Export e2e: not added.** The report suite's fixture is a cited (report-only) site staged from precomposed views, on +which a cited-only channel is no different from any citation; the default export suite's fixture composes no reports. +Carrying a full site with a report would mean new fixture machinery, so the compose proving test (S2) is the proof. + +**Found and left.** A channel moved from a site's pool to its cited scope is not tombstoned: its posts paths a public +site served before stay at the edge until their TTL, as for any channel taken off a site today. + +| Gate | Result | +| --- | --- | +| tsc (`pnpm -r … tsc --noEmit`), each commit | clean ×5 | +| common suite, whole, at the end | 3681 tests, 3671 pass, 10 fail — `controller/attachMedia.test.ts` (8) and `controller/preparePlayable.test.ts` (2), which fail the same on `r23/integration` (environmental) | +| touched common files | siteSchema 31, composeReports 19, reportMedia + missingEvidenceWindows 10, inputSig 6, builtExport 22, deployStage 15, renameChannel 7 — all pass | +| editor unit (`pnpm --filter editor test`) | 240/240 | +| export unit / homepage unit | 118/118 / 23/23 | +| `test:scripts` | 761: 758 pass, 3 skipped | +| `docs files --check`, `docs cli --check` | clean | +| `sites-crud.spec` (start mode; the editor rebuilt through the heavy slot, 40 s) | 18/18, 29.1 s | diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -688,7 +688,8 @@ export function usage() { " defaulted; a secret is \"<redacted>\"), or one top-level key of it.", "get storage is /storage: each location, mounted or not, free space, tiers.", "get sites lists every site: id, title, siteUrl, Pages project, audience,", - " listed, search, publish policy, channels. (`get publish` is the status.)", + " listed, search, publish policy, channels, citedChannels. (`get publish`", + " is the status.)", "get workers, get auto-queue and get scheduler are /workers, the four lanes", " of /operations, and /operations/sync — the payloads those pages poll.", "get cleanup <slug> is one channel's /cleanup row: what each sweep would",