Archilyzer · Source

archilyzer

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

commit 60e70671ccdfa4eae7f9a10d873002e23e592915
parent 2275d5b385bde0794d30719baad129cfc02d9845
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 15:01:31 -0400

Merge r26/store (release 26 A3 homepage articles, A4 the private build + the public audit) into r26/integration

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

Diffstat:
M.gitignore | 8++++++++
MCOMMANDS.md | 4++--
MENVIRONMENT.md | 3+++
Mcommon/bin/_cli.test.ts | 6+++---
Mcommon/bin/archilyzer.ts | 16+++++++++++-----
Acommon/bin/compose-homepage.test.ts | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/compose-homepage.ts | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/lib/builtExport.ts | 9+++++++--
Acommon/lib/builtHomepage.test.ts | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/builtHomepage.ts | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 2++
Mcommon/lib/ports.mjs | 1+
Mcommon/publish/build.test.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/build.ts | 104++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/publish/deployStage.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/publish/deployStage.ts | 4+++-
Mcommon/publish/stageBodies.ts | 2+-
Meditor/CHANGELOG.md | 1+
Mhomepage/CHANGELOG.md | 2++
Ahomepage/app/articles/[reportId]/history/page.tsx | 36++++++++++++++++++++++++++++++++++++
Ahomepage/app/articles/[reportId]/page.tsx | 37+++++++++++++++++++++++++++++++++++++
Ahomepage/app/articles/page.tsx | 20++++++++++++++++++++
Mhomepage/app/components/Header.tsx | 9++++++---
Ahomepage/app/lib/articles.test.ts | 32++++++++++++++++++++++++++++++++
Ahomepage/app/lib/articles.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mhomepage/app/lib/nav.ts | 6++++--
Ahomepage/app/m/[...moment]/page.tsx | 43+++++++++++++++++++++++++++++++++++++++++++
Mhomepage/app/page.tsx | 36+++++++++++++++++++++++++++++++++++-
Ahomepage/e2e/articles.spec.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ahomepage/e2e/fixture-articles.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mhomepage/e2e/marketing.spec.ts | 11++++++-----
Mhomepage/next.config.ts | 5+++++
Mhomepage/package.json | 1+
Mhomepage/playwright.config.ts | 12++++++++++++
Mplans/reports-on-homepage.md | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/sites-fixture.mjs | 6+++---
36 files changed, 1143 insertions(+), 43 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -103,6 +103,12 @@ yarn-error.log* # Note this does NOT cover /homepage/public/_headers — the `_headers` rule above # is scoped to /export/public, so the homepage's stays tracked. /homepage/public/downloads +# The articles `compose homepage` writes (release 26: articles/, m/, media/ +# — the clips are binary, a Tailwind hazard as below) and the build's stamp. +/homepage/public/articles/ +/homepage/public/m/ +/homepage/public/media/ +/homepage/public/homepage-build.json # The published source: the git mirror (archilyzer.git: packs, info/refs), the # raw tree and manifest.json, all written by `archilyzer source publish` # (common/publish/source.ts). Ignored for Tailwind as much as for git: Tailwind @@ -153,6 +159,7 @@ yarn-error.log* /homepage/test-results/ /homepage/playwright-report/ /homepage/out/ +/homepage/out-private/ # the e2e's synthetic summary, and a killed run's temp copy (homepage/e2e/fixture-summary.ts) /homepage/e2e/.e2e-summary.json* # the e2e's settings.json (social links only), and its temp copy (homepage/e2e/fixture-social.ts) @@ -161,6 +168,7 @@ yarn-error.log* /homepage/e2e/.e2e-sites/ # the e2e's fixture publish for /source/ (homepage/e2e/fixture-source.ts) /homepage/e2e/.e2e-source/ +/homepage/e2e/.e2e-articles/ # site config /settings.json diff --git a/COMMANDS.md b/COMMANDS.md @@ -16,7 +16,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer build archives` | | warm the shared archive-zip cache for every enabled site's channels, once | | `archilyzer compose site` | `<id> [--allow-missing-media]` | compose one site's export/public (default: SITE\_ID); --allow-missing-media lets a report citation with no prepared media through | | `archilyzer compose hub` | | compose the hub's export/public (hub-sites.json, corpus.json, …) | -| `archilyzer compose homepage` | | compose homepage/public (whole-pool stats + landing summary) | +| `archilyzer compose homepage` | `[--private] [--allow-missing-media]` | compose homepage/public (whole-pool stats + landing summary, and the articles under /articles/: the public ones, or with --private every published one) | | `archilyzer publish index` | | update the index: the LMDB index, the stats datasets and the chart templates in one child (8 GB heap), then the index stamp every build reads | | `archilyzer publish build` | `<id\|all> [--runner local\|docker\|auto] [--force] [--skip-archives] [--allow-missing-media] [--out <dir>]` | build a site (or every stale one) into its bundle &lt;exportBuildsDir&gt;/&lt;id&gt;/out from the current index; --runner docker builds every site in containers (host only); a fresh site is a no-op without --force; --allow-missing-media lets a report citation with no prepared media through compose; --out &lt;dir&gt; then lays the site's bundle out in &lt;dir&gt; for a server that is not Pages (hard links where it can, else copies; emptied first and guarded as a local deploy's destination; not a deploy, nothing recorded) | | `archilyzer publish deploy` | `<id\|all> [--preview <branch>] [--to local] [--force]` | ship a site's bundle to its Pages project (a preview with --preview), or with --to local into ARCHILYZER\_SITE\_OUT; a bundle already deployed there is a no-op without --force | @@ -28,7 +28,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer build site` | `<id> [--nodata] [--skip-archives] [--allow-missing-media]` | alias: publish index (not with --nodata) + publish build &lt;id&gt; --force (default id: SITE\_ID) | | `archilyzer build all` | `[--skip-archives]` | alias: publish index + publish build all --runner auto (containers when an engine answers, else serially on the host) | | `archilyzer build hub` | | compose:hub + INSTANCE\_MODE=hub next build into export/out — a raw build, unstamped; to deploy the hub build it with `publish hub` | -| `archilyzer build homepage` | `[--no-source]` | compose + source publish + next build in homepage/ (reads the index as it stands); --no-source removes the published source instead | +| `archilyzer build homepage` | `[--no-source] [--private]` | compose + source publish + next build in homepage/ (reads the index as it stands), then the public build's audit (no private article, moment or X post); --no-source removes the published source instead; --private builds every published article into homepage/out-private instead (serve it with `pnpm --filter homepage start:private`; never deployed) | | `archilyzer reports prepare` | `<id> \| --article <articleId>` | cut every clip and copy every post capture the site's published reports cite into its report-media cache, before its build, then export the reports as files (reports export) when nothing is missing (exit 1 when a citation lacks media or an export fails; default id: SITE\_ID); --article: the articles' cache (transcripts/reports/), every published article plus that one | | `archilyzer reports export` | `<id> [--report <reportId>] \| --article <articleId>` | \[--formats html,pdf,md,slides,slides-pdf,zip\] \[--allow-missing-media\] write the site's published reports as files (report.html, report.pdf, report.md, slides.html, slides.pdf, evidence-pack.zip) into its report-exports staging, where compose publishes them from (exit 1 on a problem; a PDF skipped for want of a browser is a note; default id: SITE\_ID); --article: one article (transcripts/reports/), published or a draft | | `archilyzer reports check` | `<id> [--reports <a,b>] \| --article <articleId>` | \[--allow-missing-media\] what compose would say about the site's reports, with no build: each report validated, every cited quote checked against its record, every cited moment's prepared media present and current, the report video under the publish limit (exit 1 with the list; --reports checks those, drafts included; default id: SITE\_ID); --article: one article (transcripts/reports/), published or a draft, as the homepage's compose would | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -132,6 +132,7 @@ Every local server's default port, from `common/lib/ports.mjs`. The primary chec | `OLLAMA_STUB_PORT` | `11435` | Digest-lane stub server in the editor e2e suite. A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | | `HOMEPAGE_DEV_PORT` | `3030` | Homepage real dev (`pnpm dev:homepage`). A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | | `HOMEPAGE_PORT` | `3031` | Homepage static `serve out` (start:homepage). A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | +| `HOMEPAGE_PRIVATE_PORT` | `3032` | The private homepage build, `serve out-private` (start:private). A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | | `HOMEPAGE_E2E_PORT` | `3040` | Homepage's own Playwright suite. A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | | `HUB_PORT` | `3041` | Export's hub Playwright suite (e2e:hub). A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | | `REPORT_SITE_E2E_PORT` | `3042` | Export's cited report-site Playwright suite (e2e:report). A worktree adds its offset (`pnpm wt list`). | common/lib/ports.mjs | @@ -153,6 +154,7 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know | `REPORTS_ALLOW_MISSING_MEDIA` | off | `1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list. | common/bin/compose-site.ts | | `ARCHIVES_READONLY` | off | `1` inside a docker-mode build container: materialize archives, never write the shared cache. | common/bin/compose-site.ts | | `GGML_BACKEND_PATH` | settings.tts.orpheus.ggmlBackendPath | The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment. | common/lib/ttsApps.ts | +| `HOMEPAGE_DIST_DIR` | unset (`homepage/out`) | Where the homepage's `next build` writes its export; `archilyzer build homepage --private` sets it to `out-private`, so the private build never replaces the deployable `homepage/out`. | homepage/next.config.ts, common/publish/build.ts | | `HOMEPAGE_PUBLIC_DIR` | `<repo>/homepage/public` | Where `compose homepage` and `source publish` write. | common/bin/compose-homepage.ts, common/publish/source.ts | ## Docker @@ -231,6 +233,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_RETRIES` | `0` | Retries per shard (`--retries N` wins); 0 keeps a sharded run comparable to a serial one. | scripts/run-sharded-e2e.mjs | | `E2E_IMAGE` | `yt-dlp-transcript-browser-e2e` | The sharded e2e run's image tag. | scripts/run-sharded-e2e.mjs | | `E2E_SKIP_BUILD` | off | `1` reuses the sharded e2e image instead of rebuilding it (`--no-build`). | scripts/run-sharded-e2e.mjs | +| `E2E_ARTICLES_PUBLIC_DIR` | unset (the pages read `homepage/public`) | The fixture public dir the homepage's e2e dev server reads the articles and moments from while it holds `articles/index.json`; set by `homepage/playwright.config.ts`, ignored by a production build. | homepage/app/lib/articles.ts | | `E2E_SOURCE_PUBLIC_DIR` | unset (the page reads `homepage/public`) | The fixture publish the homepage's e2e dev server reads the `/source/` page from while it holds a manifest; set by `homepage/playwright.config.ts`, written and removed by `homepage/e2e/source-history.spec.ts`, ignored by a production build. | homepage/app/lib/source.ts | | `E2E_EXPECT_SOURCE` | off (both states pass) | `1` makes the homepage suite's `/source/` specs fail on the empty state; a gate that ran `archilyzer source publish` first sets it. | homepage/e2e/source.spec.ts | | `E2E_HOMEPAGE_SUMMARY_FILE` | `homepage/public/homepage-summary.json` | The synthetic summary the homepage's e2e dev server reads; set by `homepage/playwright.config.ts`, ignored by a production build. | homepage/app/lib/summary.ts | diff --git a/common/bin/_cli.test.ts b/common/bin/_cli.test.ts @@ -320,7 +320,7 @@ test("usage lists source publish, source audit and build homepage's --no-source" const u = usage(COMMANDS); assert.match(u, /archilyzer source publish\s+\[--force\] \[--check\] \[--keep-scratch\] the scrubbed git mirror/); assert.match(u, /archilyzer source audit\s+\[<git dir>\] the denied-literal gate/); - assert.match(u, /archilyzer build homepage\s+\[--no-source\] compose \+ source publish \+ next build/); + assert.match(u, /archilyzer build homepage\s+\[--no-source\] \[--private\] compose \+ source publish \+ next build/); }); test("source publish takes its three booleans and nothing else; none swallows a word", () => { @@ -336,7 +336,7 @@ test("source publish takes its three booleans and nothing else; none swallows a assert.match(argumentProblem(hit!.command, {}, ["extra"])!, /unexpected argument "extra"/); }); -test("source audit takes one git dir; build homepage takes --no-source only", () => { +test("source audit takes one git dir; build homepage takes --no-source and --private only", () => { const audit = resolveCommand(COMMANDS, ["source", "audit", "/tmp/clone/.git"]); assert.deepEqual(audit?.rest, ["/tmp/clone/.git"]); assert.equal(argumentProblem(audit!.command, {}, audit!.rest), null); @@ -345,7 +345,7 @@ test("source audit takes one git dir; build homepage takes --no-source only", () const parsed = parseArgv(["build", "homepage", "--no-source"], booleanFlags(COMMANDS)); assert.deepEqual(parsed, { positionals: ["build", "homepage"], flags: { "no-source": true } }); assert.equal(argumentProblem(home!.command, parsed.flags, []), null); - assert.match(argumentProblem(home!.command, { force: true }, [])!, /unknown flag --force \(accepts --no-source\)/); + assert.match(argumentProblem(home!.command, { force: true }, [])!, /unknown flag --force \(accepts --no-source, --private\)/); }); // ── passthrough commands (one-core Phase 4 slice 3) ───────────────────────── diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -70,9 +70,14 @@ export const COMMANDS: Command[] = [ }, { path: ["compose", "homepage"], - usage: "compose homepage/public (whole-pool stats + landing summary)", - run: async () => { - await (await import("./compose-homepage")).main(); + usage: + "[--private] [--allow-missing-media] compose homepage/public (whole-pool stats + landing summary, and the articles under /articles/: the public ones, or with --private every published one)", + flags: { private: "boolean", "allow-missing-media": "boolean" }, + run: async ({ flags }) => { + await (await import("./compose-homepage")).main({ + audience: flags.private === true ? "private" : "public", + allowMissingMedia: flags["allow-missing-media"] === true, + }); return 0; }, }, @@ -248,13 +253,14 @@ export const COMMANDS: Command[] = [ { path: ["build", "homepage"], usage: - "[--no-source] compose + source publish + next build in homepage/ (reads the index as it stands); --no-source removes the published source instead", - flags: { "no-source": "boolean" }, + "[--no-source] [--private] compose + source publish + next build in homepage/ (reads the index as it stands), then the public build's audit (no private article, moment or X post); --no-source removes the published source instead; --private builds every published article into homepage/out-private instead (serve it with `pnpm --filter homepage start:private`; never deployed)", + flags: { "no-source": "boolean", private: "boolean" }, run: async ({ flags }) => { const { buildHomepage } = await import("../publish/build"); const code = await buildHomepage({ signal: interrupted(), skipSource: flags["no-source"] === true, + private: flags.private === true, }); if (code !== 0) console.error(`build homepage: failed (exit ${code})`); return code; diff --git a/common/bin/compose-homepage.test.ts b/common/bin/compose-homepage.test.ts @@ -0,0 +1,139 @@ +// `compose homepage`'s articles stage (release 26 A3/A4), over a temp corpus: +// the public compose carries only public articles, the private one every +// published article; both stamp homepage-build.json; a moment's record opens +// in the listed public site that publishes its channel. +// +// Run with: node_modules/.bin/tsx --test bin/compose-homepage.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 path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "compose-homepage-")); +const PUBLIC = path.join(ROOT, "homepage-public"); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + HOMEPAGE_PUBLIC_DIR: PUBLIC, +}); +delete process.env.ARTICLES_DIR; +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex } = await import("../controller/buildIndex"); +const { articleDir, configureArticle } = await import("../lib/report/registry"); +const { main, channelSiteUrlOf } = await import("./compose-homepage"); +const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION } = await import("../publish/reportMedia"); + +const paths = getPaths(); +const put = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2)); +}; +const readJson = <T = Record<string, unknown>>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T; +const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23); +const QUOTE = "The bridge opened in the spring, I was there for it."; + +put(paths.settingsFile, {}); +put(path.join(paths.channelsDir, "vids", "config.json"), { handling: "youtube", name: "Vids", url: "https://www.youtube.com/@vids/videos" }); +put(path.join(paths.channelsDir, "vids", "data", "abc1", "metadata.info.json"), { + id: "abc1", + title: "A stream", + channel: "vids", + upload_date: "20260110", + duration: 600, + webpage_url: "https://www.youtube.com/watch?v=abc1", + extractor_key: "Youtube", +}); +put( + path.join(paths.channelsDir, "vids", "data", "abc1", "transcript.en.vtt"), + `WEBVTT\nKind: captions\nLanguage: en\n\n${ts(10)} --> ${ts(20)} align:start position:0%\n${QUOTE}<${ts(10)}><c></c>\n`, +); +put(path.join(paths.sitesDir, "listed", "site.json"), { + siteId: "listed", + siteTitle: "Listed", + groups: [{ id: "default", name: "All", selectedByDefault: true }], + defaultGroupId: "default", + channels: [{ slug: "vids", groupId: "default" }], + siteUrl: "https://listed.example.test", +}); +const article = (id: string, over: Record<string, unknown> = {}) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + citations: { c1: { kind: "video", channel: "vids", id: "abc1", start: 10, end: 20, quote: QUOTE } }, + sections: [{ id: "s", title: "S", body: "Said [this](cite:c1)." }], + ...over, +}); +put(path.join(articleDir(paths, "open"), "report.json"), article("open")); +put(path.join(articleDir(paths, "closed"), "report.json"), article("closed")); +await configureArticle("open", { published: true, audience: "public" }, paths); +await configureArticle("closed", { published: true }, paths); +// The articles' prepared media, as `reports prepare --article` leaves it. +const media = path.join(paths.exportIndexDir, "articles", "report-media"); +const hash = "0".repeat(31) + "1"; +put(path.join(media, `${hash}.mp4`), "video"); +put(path.join(media, `${hash}.json`), { span: { from: 10, to: 20 } }); +put(path.join(media, "index.json"), { + format: REPORT_MEDIA_FORMAT, + version: REPORT_MEDIA_VERSION, + siteId: "articles", + preparedAt: "2026-10-11T00:00:00.000Z", + moments: { "vids/abc1/10.00-20.00": { kind: "video", file: `${hash}.mp4`, bytes: 5, sha256: "f".repeat(64), width: null, height: null, durationSec: 10 } }, + problems: [], +}); +await buildIndex({ paths, onLog: () => {} }); + +const quietly = async (fn: () => Promise<void>) => { + const log = console.log; + console.log = () => {}; + try { + await fn(); + } finally { + console.log = log; + } +}; + +test("a public compose carries the public article only, stamped public; its moment opens in the listed site", async () => { + await quietly(() => main({ paths, audience: "public" })); + const index = readJson<{ reports: { id: string; href: string }[] }>(path.join(PUBLIC, "articles", "index.json")); + assert.deepEqual(index.reports.map((r) => [r.id, r.href]), [["open", "/articles/open/"]]); + assert.deepEqual(readJson(path.join(PUBLIC, "homepage-build.json")), { + format: "archilyzer-homepage-build", + version: 1, + audience: "public", + articles: ["open"], + }); + const moment = readJson<{ record: { corpusUrl?: string } }>(path.join(PUBLIC, "m", "vids", "abc1", "10.00-20.00", "moment.json")); + assert.equal(moment.record.corpusUrl, "https://listed.example.test/?v=vids%2Fabc1&t=10"); + assert.ok(existsSync(path.join(PUBLIC, "media", "clips", "vids", "abc1", "10.00-20.00.mp4"))); + assert.ok(existsSync(path.join(PUBLIC, "homepage-summary.json")), "the landing data is composed as before"); +}); + +test("a private compose carries every published article, stamped private", async () => { + await quietly(() => main({ paths, audience: "private" })); + const index = readJson<{ reports: { id: string }[] }>(path.join(PUBLIC, "articles", "index.json")); + assert.deepEqual(index.reports.map((r) => r.id), ["open", "closed"]); + assert.equal(readJson(path.join(PUBLIC, "homepage-build.json")).audience, "private"); +}); + +test("channelSiteUrlOf: the first listed site with a public URL; none for a channel no listed site has", () => { + const sites = [ + { siteId: "a", siteUrl: undefined }, + { siteId: "b", siteUrl: "https://b.example.test/" }, + { siteId: "p", siteUrl: "https://p.example.test", audience: "private" }, + ] as never; + const of = channelSiteUrlOf({ x: ["a", "b"], y: ["p"] }, sites); + assert.equal(of("x"), "https://b.example.test"); + assert.equal(of("y"), undefined); + assert.equal(of("z"), undefined); +}); diff --git a/common/bin/compose-homepage.ts b/common/bin/compose-homepage.ts @@ -7,6 +7,23 @@ // public/stats/{manifest,page-NNNN}.json <- whole-pool stats (every channel) // public/channel-sites.json <- channel slug -> [siteId, ...] // public/homepage-summary.json <- small cross-site landing summary +// public/articles/, m/, media/ <- the ARTICLES (release 26 A3): the +// reports stage +// (publish/composeReports.ts) over +// the article store, under the +// /articles/ base +// public/homepage-build.json <- the build's audience and the +// articles it carries (the stamp +// lib/builtExport.ts audits) +// +// THE AUDIENCE. A public compose (the default) carries only the published +// articles whose report.json says `audience: "public"`; `--private` +// (`audience: "private"`) every published article, for the local-only private +// build (`archilyzer build homepage --private`), which is never deployed. The +// post visibility rule applies by that audience. A moment's record opens in +// the listed public site that publishes its channel (channel-sites.json and +// the site's `siteUrl`, absolute), or nowhere. Links and feeds are absolute +// on PROJECT_URL. // // None of the three names an unlisted site (site.json `listed: false`) or holds // a channel only unlisted sites expose (lib/siteSchema.ts isListedSite). @@ -18,7 +35,12 @@ import path from "node:path"; import { getPaths, type Paths } from "../lib/paths"; import { writeJsonAtomic as writeJsonAtomicShared } from "../lib/jsonFile-server"; import { buildPoolSummary } from "../controller/poolSummary"; -import { isListedSite } from "../lib/site"; +import { isListedSite, parseSiteUrl, type Site } from "../lib/site"; +import { PROJECT_URL } from "../lib/project"; +import type { ReportAudience } from "../lib/report/schema"; +import type { ChannelSitesMap } from "../lib/homepageSummary"; +import { articlesReportHost } from "../publish/reportHost"; +import { composeHostReports } from "../publish/composeReports"; import { runIfEntryPoint } from "./_cli"; // Where the homepage Next.js app serves static assets from. Overridable for e2e @@ -35,8 +57,36 @@ function writeJsonAtomic(filePath: string, value: unknown): Promise<void> { return writeJsonAtomicShared(filePath, value, { indent: 0, newline: false }); } -export async function main(opts: { paths?: Paths } = {}): Promise<void> { +// The stamp a homepage build carries (public/ → out/): which audience it was +// composed for and the articles in it. lib/builtExport.ts reads it. +export const HOMEPAGE_BUILD_FILE = "homepage-build.json"; +export const HOMEPAGE_BUILD_FORMAT = "archilyzer-homepage-build"; + +// channel slug → the public URL of the first listed site that publishes it +// (a listed site is never private: lib/siteSchema.ts isListedSite), or none. +export function channelSiteUrlOf(channelSites: ChannelSitesMap, sites: readonly Site[]): (slug: string) => string | undefined { + const urlOf = new Map(sites.filter(isListedSite).map((s) => [s.siteId, parseSiteUrl(s.siteUrl)])); + return (slug) => { + for (const id of channelSites[slug] ?? []) { + const url = urlOf.get(id); + if (url) return url; + } + return undefined; + }; +} + +export async function main( + opts: { + paths?: Paths; + // Default "public". + audience?: ReportAudience; + // Let an article citation without prepared media through (its moment then + // renders without a clip). + allowMissingMedia?: boolean; + } = {}, +): Promise<void> { const paths = opts.paths ?? getPaths(); + const audience = opts.audience ?? "public"; const publicDir = homepagePublicDir(paths.monorepoRoot); const statsDir = path.join(publicDir, "stats"); @@ -64,6 +114,27 @@ export async function main(opts: { paths?: Paths } = {}): Promise<void> { summary, ); + // The articles: the reports stage over the article store, under /articles/. + // It fails (and the build with it) on a problem, as a site's compose does. + const host = await articlesReportHost(paths, { + audience, + siteUrl: PROJECT_URL, + channelSiteUrl: channelSiteUrlOf(channelSites, sites), + }); + const composed = await composeHostReports({ + paths, + host, + publicDir, + allowMissingMedia: opts.allowMissingMedia === true, + log: (line) => console.log(line), + }); + await writeJsonAtomicShared( + path.join(publicDir, HOMEPAGE_BUILD_FILE), + { format: HOMEPAGE_BUILD_FORMAT, version: 1, audience, articles: composed.reports.map((r) => r.id) }, + { mkdir: true }, + ); + console.log(`compose-homepage: ${composed.reports.length} ${audience} article(s), ${composed.moments.length} moment(s).`); + const unlisted = sites.filter((s) => !isListedSite(s)).length; console.log( `compose-homepage: ${Object.keys(channelSites).length} channel(s) mapped across ${sites.length - unlisted} listed site(s)` + @@ -74,4 +145,9 @@ export async function main(opts: { paths?: Paths } = {}): Promise<void> { ); } -runIfEntryPoint(import.meta.url, () => main()); +runIfEntryPoint(import.meta.url, () => + main({ + audience: process.argv.includes("--private") ? "private" : "public", + allowMissingMedia: process.argv.includes("--allow-missing-media"), + }), +); diff --git a/common/lib/builtExport.ts b/common/lib/builtExport.ts @@ -17,6 +17,7 @@ import { existsSync, readdirSync, readFileSync, statSync, type Dirent } from "no import path from "node:path"; import { isCitedOnlyChannel, isCitedSite } from "./siteSchema"; import { REPORT_HISTORY_REPO_FILE_RE } from "./report/revisions"; +import { homepageAudienceProblem, type HomepageAuditOptions } from "./builtHomepage"; import { SITE_REPORTS_BASE, reportBaseDir } from "./report/routes"; import { MOMENTS_INDEX_PATH, @@ -686,11 +687,15 @@ export function hubReportDataIn(outDir: string, limit = 5): string[] { * the deploy stage checks inside its job, so the refusal an operator gets before * the job and the one the job would give agree on what "built" means. */ -export function builtHomepageProblem(outDir: string): string | null { +// +// A build that is there is then held to the audience audit (./builtHomepage.ts, +// release 26 A4): no private build, and — with `paths` — no private article, +// no moment a private article cites, no X post while X posts are private. +export function builtHomepageProblem(outDir: string, opts: HomepageAuditOptions = {}): string | null { if (!existsSync(path.join(outDir, "index.html"))) { return "homepage/out holds no build — build the homepage first"; } - return null; + return homepageAudienceProblem(outDir, opts); } /** diff --git a/common/lib/builtHomepage.test.ts b/common/lib/builtHomepage.test.ts @@ -0,0 +1,92 @@ +// The public homepage build's audit (release 26 A4): builtHomepageProblem +// (lib/builtExport.ts) over lib/builtHomepage.ts. Each refusal on a temp out/ +// and article store; a clean public build passes, with articles or none. +// +// Run with: node_modules/.bin/tsx --test lib/builtHomepage.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { builtHomepageProblem } from "./builtExport"; +import { homepageBuildAudience } from "./builtHomepage"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "built-homepage-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const put = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value)); +}; + +const paths = { articlesDir: path.join(ROOT, "reports"), channelsDir: path.join(ROOT, "channels") }; +put(path.join(paths.articlesDir, "open", "report.json"), { audience: "public" }); +put(path.join(paths.articlesDir, "closed", "report.json"), { audience: "private" }); +put(path.join(paths.articlesDir, "unsaid", "report.json"), {}); +put(path.join(paths.channelsDir, "xchan", "config.json"), { sourceKind: "social", platform: "twitter" }); +put(path.join(paths.channelsDir, "vids", "config.json"), { handling: "youtube" }); +const X_PRIVATE = { social: { x: { visibility: "private" } } }; + +let n = 0; +// A built out/ with the given extra files. +function out(files: Record<string, unknown> = {}): string { + const dir = path.join(ROOT, `out-${n++}`); + put(path.join(dir, "index.html"), "<p>home</p>"); + put(path.join(dir, "homepage-build.json"), { format: "archilyzer-homepage-build", version: 1, audience: "public", articles: [] }); + for (const [rel, v] of Object.entries(files)) put(path.join(dir, rel), v); + return dir; +} +const moment = (...hrefs: string[]) => ({ format: "archilyzer-moment-page", citedIn: hrefs.map((href) => ({ href })) }); + +test("no build, then a clean public build with no articles, then one with a public article and its moment", () => { + assert.match(builtHomepageProblem(path.join(ROOT, "nothing"), { paths }) ?? "", /holds no build/); + assert.equal(builtHomepageProblem(out(), { paths, settings: X_PRIVATE }), null); + const withOne = out({ + "articles/open/page.json": {}, + "m/vids/v1/1.00-2.00/moment.json": moment("/articles/open/#c1"), + "media/posts/vids/p1/shot.png": "png", + }); + assert.equal(builtHomepageProblem(withOne, { paths, settings: X_PRIVATE }), null); +}); + +test("a private build is refused by its stamp, with or without the store", () => { + const dir = out({ "homepage-build.json": { audience: "private" } }); + assert.equal(homepageBuildAudience(dir), "private"); + for (const opts of [{}, { paths }]) { + assert.match(builtHomepageProblem(dir, opts) ?? "", /holds a private homepage build .* which is never deployed/); + } +}); + +test("an article the store does not mark public is refused: private, unsaid (private by default), gone", () => { + for (const id of ["closed", "unsaid", "gone"]) { + const dir = out({ [`articles/${id}/page.json`]: {} }); + assert.match( + builtHomepageProblem(dir, { paths }) ?? "", + new RegExp(`carries the article "${id}", which is not public`), + id, + ); + assert.equal(builtHomepageProblem(dir), null, "without the store, the stamp alone is asked"); + } +}); + +test("a moment a private article cites, or one cited by no article, is refused", () => { + assert.match( + builtHomepageProblem(out({ "m/vids/v1/1.00-2.00/moment.json": moment("/articles/open/", "/articles/closed/#c2") }), { paths }) ?? + "", + /moment vids\/v1\/1\.00-2\.00 is cited by the article "closed", which is not public/, + ); + assert.match( + builtHomepageProblem(out({ "m/vids/v1/1.00-2.00/moment.json": moment("/reports/some-site-report/") }), { paths }) ?? "", + /cited by "\/reports\/some-site-report\/", which is no public article/, + ); +}); + +test("while X posts are private: no X post's moment and no X captures; public X posts pass", () => { + const xMoment = out({ "m/xchan/123/moment.json": moment("/articles/open/") }); + assert.match(builtHomepageProblem(xMoment, { paths, settings: X_PRIVATE }) ?? "", /moment xchan\/123 is an X post/); + const xMedia = out({ "media/posts/xchan/123/shot.png": "png" }); + assert.match(builtHomepageProblem(xMedia, { paths, settings: X_PRIVATE }) ?? "", /media\/posts\/xchan\/, an X channel's captures/); + assert.equal(builtHomepageProblem(xMoment, { paths, settings: {} }), null); + assert.equal(builtHomepageProblem(xMedia, { paths, settings: {} }), null); +}); diff --git a/common/lib/builtHomepage.ts b/common/lib/builtHomepage.ts @@ -0,0 +1,131 @@ +// WHAT A PUBLIC HOMEPAGE BUILD MAY NOT HOLD (release 26 A4, +// plans/reports-on-homepage.md, "Two homepage builds"). +// +// The homepage builds twice from one source: the PUBLIC build carries the +// published articles whose report.json says `audience: "public"`, the PRIVATE +// one (`archilyzer build homepage --private`, homepage/out-private) every +// published article, and is never deployed. compose stamps each build in +// `homepage-build.json` (bin/compose-homepage.ts). This audit is the second +// line, asked of homepage/out by the build, the deploy stage and the status +// (lib/builtExport.ts builtHomepageProblem): +// +// - a build stamped `audience: "private"` is never deployed; +// - an article under out/articles/<id>/ must be one the article store marks +// public now (report.json `audience`, absent = private) — one made private, +// or gone, since the build is refused until the homepage is rebuilt; +// - a moment under out/m/ may be cited only by such articles (its page names +// every citing article: a private one's title would leak through it); +// - while `social.x.visibility` is "private", no X channel's post — its +// moment page or its captured media — is in the build, as a public site's +// never is (lib/postsVisibility.ts). +// +// The store and the channel configs are read only when the caller passes the +// paths; without them the stamp alone is checked. Synchronous: a status page +// asks it. + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import type { Paths } from "./paths"; +import { isXPostsChannel, xPostsVisibility } from "./postsVisibility"; +import { ARTICLES_REPORTS_BASE, reportBaseDir } from "./report/routes"; + +export const HOMEPAGE_BUILD_STAMP = "homepage-build.json"; + +export type HomepageAuditOptions = { + paths?: Pick<Paths, "articlesDir" | "channelsDir">; + // `social.x.visibility`; asked only with `paths`. + settings?: { social?: { x?: { visibility?: unknown } } }; +}; + +const readJson = (file: string): unknown => { + try { + return JSON.parse(readFileSync(file, "utf8")); + } catch { + return null; + } +}; + +const dirs = (dir: string): string[] => { + try { + return readdirSync(dir, { withFileTypes: true }) + .filter((e) => e.isDirectory()) + .map((e) => e.name) + .sort(); + } catch { + return []; + } +}; + +// Every moment.json under out/m/, by key. +function momentFiles(outDir: string): { key: string; file: string }[] { + const out: { key: string; file: string }[] = []; + const walk = (dir: string, rel: string[]) => { + if (existsSync(path.join(dir, "moment.json"))) out.push({ key: rel.join("/"), file: path.join(dir, "moment.json") }); + for (const d of dirs(dir)) walk(path.join(dir, d), [...rel, d]); + }; + walk(path.join(outDir, "m"), []); + return out; +} + +// The stamp's audience, when the build carries one. +export function homepageBuildAudience(outDir: string): string | null { + const stamp = readJson(path.join(outDir, HOMEPAGE_BUILD_STAMP)) as { audience?: unknown } | null; + return typeof stamp?.audience === "string" ? stamp.audience : null; +} + +// The first reason `outDir` may not be deployed as the public homepage, or null. +export function homepageAudienceProblem(outDir: string, opts: HomepageAuditOptions = {}): string | null { + if (homepageBuildAudience(outDir) === "private") { + return `${outDir} holds a private homepage build (its ${HOMEPAGE_BUILD_STAMP} says "audience": "private"), which is never deployed`; + } + const paths = opts.paths; + if (!paths) return null; + + const articlesDir = path.join(outDir, reportBaseDir(ARTICLES_REPORTS_BASE)); + const built = dirs(articlesDir).filter((id) => existsSync(path.join(articlesDir, id, "page.json"))); + const isPublic = new Map<string, boolean>(); + const publicNow = (id: string) => { + if (!isPublic.has(id)) { + const doc = readJson(path.join(paths.articlesDir, id, "report.json")) as { audience?: unknown } | null; + // lib/report/registry.ts articleAudience: absent = private. + isPublic.set(id, doc?.audience === "public"); + } + return isPublic.get(id)!; + }; + for (const id of built) { + if (!publicNow(id)) { + return `the homepage build carries the article "${id}", which is not public (its report.json's audience) — rebuild the homepage`; + } + } + + const xPrivate = xPostsVisibility(opts.settings ?? {}) === "private"; + const configs = new Map<string, boolean>(); + const isX = (slug: string) => { + if (!configs.has(slug)) { + configs.set(slug, isXPostsChannel(readJson(path.join(paths.channelsDir, slug, "config.json")) as never)); + } + return configs.get(slug)!; + }; + const articlePrefix = ARTICLES_REPORTS_BASE; + for (const m of momentFiles(outDir)) { + const view = readJson(m.file) as { citedIn?: { href?: unknown }[] } | null; + for (const c of view?.citedIn ?? []) { + const href = typeof c.href === "string" ? c.href : ""; + const id = href.startsWith(articlePrefix) ? href.slice(articlePrefix.length).split(/[/#]/)[0] : ""; + if (!id || !publicNow(id)) { + return `the homepage build's moment ${m.key} is cited by ${id ? `the article "${id}", which is not public` : `"${href}", which is no public article`} — rebuild the homepage`; + } + } + if (xPrivate && isX(m.key.split("/")[0])) { + return `the homepage build's moment ${m.key} is an X post, and X posts are private (social.x.visibility) — rebuild the homepage`; + } + } + if (xPrivate) { + for (const slug of dirs(path.join(outDir, "media", "posts"))) { + if (isX(slug)) { + return `the homepage build carries media/posts/${slug}/, an X channel's captures, and X posts are private (social.x.visibility) — rebuild the homepage`; + } + } + } + return null; +} diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -161,6 +161,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "REPORTS_ALLOW_MISSING_MEDIA", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list." }, { name: "ARCHIVES_READONLY", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` inside a docker-mode build container: materialize archives, never write the shared cache." }, { name: "GGML_BACKEND_PATH", audience: "internal", default: "settings.tts.orpheus.ggmlBackendPath", readBy: "common/lib/ttsApps.ts", doc: "The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment." }, + { name: "HOMEPAGE_DIST_DIR", audience: "internal", default: "unset (`homepage/out`)", readBy: "homepage/next.config.ts, common/publish/build.ts", doc: "Where the homepage's `next build` writes its export; `archilyzer build homepage --private` sets it to `out-private`, so the private build never replaces the deployable `homepage/out`." }, { name: "HOMEPAGE_PUBLIC_DIR", audience: "internal", default: "`<repo>/homepage/public`", readBy: "common/bin/compose-homepage.ts, common/publish/source.ts", doc: "Where `compose homepage` and `source publish` write." }, // ── docker: the container's set ──────────────────────────────────────── @@ -229,6 +230,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_RETRIES", audience: "test", default: "`0`", readBy: "scripts/run-sharded-e2e.mjs", doc: "Retries per shard (`--retries N` wins); 0 keeps a sharded run comparable to a serial one." }, { name: "E2E_IMAGE", audience: "test", default: "`yt-dlp-transcript-browser-e2e`", readBy: "scripts/run-sharded-e2e.mjs", doc: "The sharded e2e run's image tag." }, { name: "E2E_SKIP_BUILD", audience: "test", default: "off", readBy: "scripts/run-sharded-e2e.mjs", doc: "`1` reuses the sharded e2e image instead of rebuilding it (`--no-build`)." }, + { name: "E2E_ARTICLES_PUBLIC_DIR", audience: "test", default: "unset (the pages read `homepage/public`)", readBy: "homepage/app/lib/articles.ts", doc: "The fixture public dir the homepage's e2e dev server reads the articles and moments from while it holds `articles/index.json`; set by `homepage/playwright.config.ts`, ignored by a production build." }, { name: "E2E_SOURCE_PUBLIC_DIR", audience: "test", default: "unset (the page reads `homepage/public`)", readBy: "homepage/app/lib/source.ts", doc: "The fixture publish the homepage's e2e dev server reads the `/source/` page from while it holds a manifest; set by `homepage/playwright.config.ts`, written and removed by `homepage/e2e/source-history.spec.ts`, ignored by a production build." }, { name: "E2E_EXPECT_SOURCE", audience: "test", default: "off (both states pass)", readBy: "homepage/e2e/source.spec.ts", doc: "`1` makes the homepage suite's `/source/` specs fail on the empty state; a gate that ran `archilyzer source publish` first sets it." }, { name: "E2E_HOMEPAGE_SUMMARY_FILE", audience: "test", default: "`homepage/public/homepage-summary.json`", readBy: "homepage/app/lib/summary.ts", doc: "The synthetic summary the homepage's e2e dev server reads; set by `homepage/playwright.config.ts`, ignored by a production build." }, diff --git a/common/lib/ports.mjs b/common/lib/ports.mjs @@ -40,6 +40,7 @@ export const PORTS = Object.freeze({ OLLAMA_STUB_PORT: { base: 11435, what: "digest-lane stub server in the editor e2e suite" }, HOMEPAGE_DEV_PORT: { base: 3030, what: "homepage real dev (`pnpm dev:homepage`)" }, HOMEPAGE_PORT: { base: 3031, what: "homepage static `serve out` (start:homepage)" }, + HOMEPAGE_PRIVATE_PORT: { base: 3032, what: "the private homepage build, `serve out-private` (start:private)" }, HOMEPAGE_E2E_PORT: { base: 3040, what: "homepage's own Playwright suite" }, HUB_PORT: { base: 3041, what: "export's hub Playwright suite (e2e:hub)" }, REPORT_SITE_E2E_PORT: { base: 3042, what: "export's cited report-site Playwright suite (e2e:report)" }, diff --git a/common/publish/build.test.ts b/common/publish/build.test.ts @@ -5,6 +5,7 @@ import { existsSync, mkdirSync, mkdtempSync, + readFileSync, rmSync, writeFileSync, } from "node:fs"; @@ -272,3 +273,69 @@ test("buildHomepage: the source step sits between compose and next build; a refu rmSync(root, { recursive: true, force: true }); } }); + +// The two homepage builds (release 26 A4), over a temp checkout whose compose +// and next build are seams: the private one writes homepage/out-private (never +// homepage/out), checks its stamp and takes its articles back out of public/; +// the public one is audited and refused when it carries a private article. +test("buildHomepage: --private builds into out-private and leaves public/ without articles; a public build carrying a private article is refused", async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "build-homepage-private-")); + const savedPublic = process.env.HOMEPAGE_PUBLIC_DIR; + delete process.env.HOMEPAGE_PUBLIC_DIR; + try { + const home = path.join(root, "homepage"); + const pub = path.join(home, "public"); + const articlesDir = path.join(root, "transcripts", "reports"); + const fakePaths = { monorepoRoot: root, articlesDir, channelsDir: path.join(root, "transcripts", "channels") } as Paths; + const put = (file: string, text: string) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, text); + }; + put(path.join(articlesDir, "pub-one", "report.json"), JSON.stringify({ audience: "public" })); + put(path.join(articlesDir, "priv-one", "report.json"), JSON.stringify({ audience: "private" })); + // homepage/out holds the deployable public build; it must not move. + put(path.join(home, "out", "index.html"), "<p>public</p>"); + + const envs: NodeJS.ProcessEnv[] = []; + // compose: the articles and the stamp it would write. + const compose = async (o: { private: boolean }) => { + for (const id of o.private ? ["pub-one", "priv-one"] : ["pub-one"]) put(path.join(pub, "articles", id, "page.json"), "{}"); + put(path.join(pub, "homepage-build.json"), JSON.stringify({ audience: o.private ? "private" : "public" })); + return 0; + }; + // next build: public/ copied into the out dir HOMEPAGE_DIST_DIR names. + const nextBuild = async (o: { env: NodeJS.ProcessEnv }) => { + envs.push(o.env); + const out = path.join(home, o.env.HOMEPAGE_DIST_DIR ?? "out"); + rmSync(out, { recursive: true, force: true }); + put(path.join(out, "index.html"), "<p>built</p>"); + const { cpSync } = await import("node:fs"); + cpSync(pub, out, { recursive: true }); + return 0; + }; + const logs: string[] = []; + const run = (o: Parameters<typeof buildHomepage>[0]) => + buildHomepage({ paths: fakePaths, onLog: (l) => logs.push(l), compose, nextBuild, skipSource: true, clearSource: async () => {}, ...o }); + + assert.equal(await run({ private: true }), 0, logs.join("\n")); + assert.equal(envs[0].HOMEPAGE_DIST_DIR, "out-private"); + assert.ok(existsSync(path.join(home, "out-private", "articles", "priv-one", "page.json"))); + assert.equal(readFileSync(path.join(home, "out", "index.html"), "utf8"), "<p>public</p>", "homepage/out untouched"); + for (const e of ["articles", "homepage-build.json"]) assert.ok(!existsSync(path.join(pub, e)), `public/${e} cleared`); + + // The public build: clean, then one that carries a private article. + assert.equal(await run({}), 0, logs.join("\n")); + assert.equal(envs[1].HOMEPAGE_DIST_DIR, undefined); + put(path.join(pub, "articles", "priv-one", "page.json"), "{}"); + const leaky = async () => { + put(path.join(pub, "homepage-build.json"), JSON.stringify({ audience: "public" })); + return 0; + }; + logs.length = 0; + assert.equal(await run({ compose: leaky }), 1); + assert.match(logs.join("\n"), /refused: the homepage build carries the article "priv-one", which is not public/); + } finally { + if (savedPublic !== undefined) process.env.HOMEPAGE_PUBLIC_DIR = savedPublic; + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/common/publish/build.ts b/common/publish/build.ts @@ -667,11 +667,21 @@ export function homepageOutDir(paths: Paths): string { return path.join(homepageDir(paths), "out"); } -function homepageEnv(paths: Paths): NodeJS.ProcessEnv { +// The PRIVATE homepage build's out dir (release 26 A4): every published +// article, served locally (`pnpm --filter homepage start:private`), never +// deployed — nothing ships it, and its stamp refuses it if anything tried. +export const HOMEPAGE_PRIVATE_OUT = "out-private"; + +export function homepagePrivateOutDir(paths: Paths): string { + return path.join(homepageDir(paths), HOMEPAGE_PRIVATE_OUT); +} + +function homepageEnv(paths: Paths, extra: Record<string, string> = {}): NodeJS.ProcessEnv { return { ...process.env, NODE_ENV: "production", TRANSCRIPTS_DIR: paths.transcriptsDir, + ...extra, }; } @@ -680,10 +690,15 @@ function homepageEnv(paths: Paths): NodeJS.ProcessEnv { * summary), as a child. Reads the LMDB index as it stands: run `archilyzer * index` first when it is stale. Returns the exit code. */ -export async function composeHomepage(opts: PublishOpts = {}): Promise<number> { +export async function composeHomepage(opts: PublishOpts & { private?: boolean } = {}): Promise<number> { const { paths, onLog, signal } = resolved(opts); return runSteps(onLog, signal, [ - { command: "pnpm", args: ["run", "compose"], cwd: homepageDir(paths), env: homepageEnv(paths) }, + { + command: "pnpm", + args: ["run", "compose", ...(opts.private ? ["--", "--private"] : [])], + cwd: homepageDir(paths), + env: homepageEnv(paths), + }, ]); } @@ -706,15 +721,42 @@ export async function composeHomepage(opts: PublishOpts = {}): Promise<number> { * install) builds with the empty state too. `publishSource` / `clearSource` * are the test's seams. */ +// +// THE PUBLIC BUILD IS AUDITED (release 26 A4): after `next build`, +// homepage/out is held to builtHomepageProblem with the article store and the +// channel configs — no private build, no private article, no moment a private +// article cites, no X post while X posts are private — and the build fails on +// a problem, as a site's does. +// +// `private` is the PRIVATE build: compose carries every published article +// (`compose homepage --private`, stamped `audience: "private"`), the source is +// left as it is, and `next build` writes homepage/out-private +// (HOMEPAGE_DIST_DIR, homepage/next.config.ts) — homepage/out, the bundle a +// deploy ships, is never touched. Afterwards the private articles are taken +// out of homepage/public again, so no later build of the tree (a +// `build:nodata`) can pick them up. export async function buildHomepage( opts: PublishOpts & { skipSource?: boolean; + private?: boolean; publishSource?: (o: PublishOpts & { noRepository?: "refuse" | "empty" }) => Promise<number>; clearSource?: (o: PublishOpts) => Promise<void>; + // The next build step; default `pnpm exec next build` in homepage/, through + // the heavy slot. The test's seam, as `compose` is (default composeHomepage). + nextBuild?: (o: { env: NodeJS.ProcessEnv; onLog: (line: string) => void; signal: AbortSignal }) => Promise<number>; + compose?: (o: { private: boolean }) => Promise<number>; } = {}, ): Promise<number> { const { paths, onLog, signal } = resolved(opts); - const code = await composeHomepage({ paths, onLog, signal }); + const nextBuild = + opts.nextBuild ?? + ((o: { env: NodeJS.ProcessEnv; onLog: (line: string) => void; signal: AbortSignal }) => + runSteps(o.onLog, o.signal, [ + heavyGated(paths, { command: "pnpm", args: ["exec", "next", "build"], cwd: homepageDir(paths), env: o.env }), + ])); + const compose = opts.compose ?? ((o: { private: boolean }) => composeHomepage({ paths, onLog, signal, private: o.private })); + if (opts.private) return buildPrivateHomepage(paths, onLog, signal, nextBuild, compose); + const code = await compose({ private: false }); if (code !== 0) return code; // Loaded lazily: the source step pulls nothing the other publish entry // points need, and it imports this module's types. @@ -729,14 +771,52 @@ export async function buildHomepage( return sourceCode || 1; } } - return runSteps(onLog, signal, [ - heavyGated(paths, { - command: "pnpm", - args: ["exec", "next", "build"], - cwd: homepageDir(paths), - env: homepageEnv(paths), - }), - ]); + const built = await nextBuild({ env: homepageEnv(paths), onLog, signal }); + if (built !== 0) return built; + const { homepageAudienceProblem } = await import("../lib/builtHomepage"); + const problem = homepageAudienceProblem(homepageOutDir(paths), { paths, settings: getSettings() }); + if (problem) { + onLog(`[homepage] refused: ${problem}\n`); + return 1; + } + return 0; +} + +// The private homepage build (buildHomepage's `private`). +async function buildPrivateHomepage( + paths: Paths, + onLog: (line: string) => void, + signal: AbortSignal, + nextBuild: (o: { env: NodeJS.ProcessEnv; onLog: (line: string) => void; signal: AbortSignal }) => Promise<number>, + compose: (o: { private: boolean }) => Promise<number>, +): Promise<number> { + try { + const code = await compose({ private: true }); + if (code !== 0) return code; + const built = await nextBuild({ env: homepageEnv(paths, { HOMEPAGE_DIST_DIR: HOMEPAGE_PRIVATE_OUT }), onLog, signal }); + if (built !== 0) return built; + const { homepageBuildAudience } = await import("../lib/builtHomepage"); + if (homepageBuildAudience(homepagePrivateOutDir(paths)) !== "private") { + onLog(`[homepage] the private build in ${homepagePrivateOutDir(paths)} carries no private stamp\n`); + return 1; + } + onLog(`[homepage] private build in ${homepagePrivateOutDir(paths)} — serve it with \`pnpm --filter homepage start:private\`; it is never deployed.\n`); + return 0; + } finally { + await clearHomepageArticles(paths); + } +} + +// The articles compose wrote into homepage/public (and its stamp): removed +// after a private build. A public build composes them again. +export async function clearHomepageArticles(paths: Paths): Promise<void> { + const { reportPublicEntries } = await import("./composeReports"); + const { ARTICLES_REPORTS_BASE } = await import("../lib/report/routes"); + const { HOMEPAGE_BUILD_STAMP } = await import("../lib/builtHomepage"); + const pub = process.env.HOMEPAGE_PUBLIC_DIR ?? path.join(homepageDir(paths), "public"); + for (const entry of [...reportPublicEntries(ARTICLES_REPORTS_BASE), HOMEPAGE_BUILD_STAMP]) { + await rm(path.join(pub, entry), { recursive: true, force: true }); + } } // The last build's copy of the source, out of homepage/out: a refused source diff --git a/common/publish/deployStage.test.ts b/common/publish/deployStage.test.ts @@ -56,6 +56,8 @@ function fixture(): Fixture { monorepoRoot: root, // Never the checkout's corpus: the local-destination guard resolves it. transcriptsDir: path.join(root, "transcripts"), + articlesDir: path.join(root, "transcripts", "reports"), + channelsDir: path.join(root, "transcripts", "channels"), exportDir: path.join(root, "export"), exportBuildsDir: path.join(root, "builds"), sitesDir, @@ -622,6 +624,34 @@ test("the homepage's local deploy copies homepage/out into ARCHILYZER_HOMEPAGE_O } }); +// Release 26 A4: a homepage build stamped private (`build homepage --private`) +// is never shipped, and nor is a public one carrying a private article. +test("the homepage's deploy refuses a private build, and a public one carrying a private article", async () => { + const fx = fixture(); + try { + const out = path.join(fx.root, "homepage", "out"); + mkdirSync(path.join(out, "source"), { recursive: true }); + writeFileSync(path.join(out, "index.html"), "<!doctype html>"); + writeFileSync(path.join(out, "source", "index.html"), "<!doctype html>"); + writeJson(path.join(fx.paths.exportBuildsDir, "_homepage", "built.json"), { + ...stampFields("_homepage", "homepage"), + stampId: "home-2", + corpusGeneratedAt: null, + }); + const req: DeployStageRequest = { kind: "deploy-homepage", target: "_homepage", to: "local" }; + const env = { ARCHILYZER_HOMEPAGE_OUT: path.join(fx.root, "homepage-out") }; + writeJson(path.join(out, "homepage-build.json"), { audience: "private" }); + await refused(runDeployStage(ctx(fx, env), req), 3, /holds a private homepage build .* never deployed/); + writeJson(path.join(out, "homepage-build.json"), { audience: "public" }); + writeJson(path.join(out, "articles", "secret", "page.json"), {}); + writeJson(path.join(fx.paths.articlesDir, "secret", "report.json"), { audience: "private" }); + await refused(runDeployStage(ctx(fx, env), req), 3, /carries the article "secret", which is not public/); + assert.equal(existsSync(env.ARCHILYZER_HOMEPAGE_OUT), false); + } finally { + fx.cleanup(); + } +}); + test("the hub: its project, its bundle, and every tombstone probed plain and busted", async () => { const fx = fixture(); try { diff --git a/common/publish/deployStage.ts b/common/publish/deployStage.ts @@ -45,6 +45,7 @@ // the sentence the log already ends on, word for word, and stageRun.ts does // not print it again. +import { getSettings } from "../lib/settings"; import os from "node:os"; import path from "node:path"; import { existsSync, readdirSync, readFileSync } from "node:fs"; @@ -460,7 +461,8 @@ export async function runDeployStage( if (problem) refuse(`${problem.replace(/^export\/out/, outDir)}.`, 3); } else { const problem = - builtHomepageProblem(outDir) ?? (await (await import("./source")).publishedSourceProblem(paths, outDir)); + builtHomepageProblem(outDir, { paths, settings: getSettings() }) ?? + (await (await import("./source")).publishedSourceProblem(paths, outDir)); if (problem) refuse(problem, 3); } diff --git a/common/publish/stageBodies.ts b/common/publish/stageBodies.ts @@ -166,7 +166,7 @@ export async function readNeedsInput( deployed: await readDeployedFile(paths, HOMEPAGE_TARGET), changedChannels: [], configChangedAt: null, - bundleProblem: homeBuilt ? builtHomepageProblem(homepageOutDir(paths)) : null, + bundleProblem: homeBuilt ? builtHomepageProblem(homepageOutDir(paths), { paths, settings: getSettings() }) : null, mainHead: opts.mainHead ? await mainHeadOf(paths) : null, }, }; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -157,6 +157,7 @@ - **`archilyzer reports … --article <id>`.** `reports prepare`, `export`, `check`, `verify-quotes` and `attach-video` take `--article <id>` in place of a site (or a report.json): prepare readies every published article plus that one into `.export-index/articles/`, export writes that article's files (a draft too), check says what the homepage's compose would, and attach-video writes `video` through the registry. - **umtool's /articles.** The nav's **articles** now opens `/articles`: the homepage's articles with their audience, notes, video project and source; each article's page, evidence walk and notes (`notes.json` beside its report.json; `umtool notes articles/<id>`). A site's own pages are a link away on /sites, as before. Needs a restart of umtool. - **`archilyzer reports move-to-articles`** (one-off): moves every report a site lists, but the pages named by `--keep <site>/<id>`, to the article store — private, published in the sites' order, its history and notes with it — printing the plan and changing nothing unless `--apply`. +- **`archilyzer build homepage` publishes the public articles; `--private` builds them all, locally.** `compose homepage` now composes the articles (under `/articles/`, the public ones; `--private` every published one) and stamps the build's audience; the public build is audited after `next build` and fails on a private article, a moment one cites, or an X post while X posts are private — as **Deploy homepage** refuses such a build and a private one. `build homepage --private` writes `homepage/out-private` (`pnpm --filter homepage start:private`), never deployed. ## [0.11.0] - 2026-09-30 - **Transcripts that arrived after a video was first seen are counted.** The stats behind the homepage, the hub and every site's charts were cached per video and refreshed only when the video's metadata changed, so a transcript that came later — a Whisper run days after the download, or a video downloaded after the last index build — never reached them, and a video with YouTube captions alone had no transcription date. Counts and charts were low; the homepage could show a site with 0 transcripts, 0 channels and 0 hours while it served its videos. A stat is now also redone whenever the index re-reads the video, every transcript has a date, and a captioned video is dated by when its captions arrived rather than by a later Normalize run, so its place on "Transcribed over time" can move. **After updating, rebuild and restart the editor before anything else:** until then, **Build stats dataset** runs the old code and would undo the new stats, while a site, hub or homepage build already runs the new code — and the first stats build of any kind re-reads every video once (about 10–30 minutes on a large archive; it can be stopped and picks up where it stopped). Then build the index, the stats, the homepage, the hub, and the sites. diff --git a/homepage/CHANGELOG.md b/homepage/CHANGELOG.md @@ -55,6 +55,8 @@ chart palette. No two sites share a colour. The `/stats` By-site leaderboard keeps each site's colour instead of colouring by rank. The e2e reads a copy of the summary with fixture accents (`HOMEPAGE_SUMMARY_FILE`, `e2e/fixture-accents.ts`). +- **Articles.** The homepage publishes the project's articles — the reports in `transcripts/reports/` (see REPORT.md) — at `/articles/` (each at `/articles/<id>/`, its revision history at `/articles/<id>/history/`, each cited moment at `/m/<key>/`), with **Articles** in the header and footer and the newest three under **Latest Articles** on the front page. `archilyzer build homepage` carries only the published articles marked `audience: "public"`; with none, `/articles/` says so. A moment's record opens in the listed public archive that publishes its channel, or nowhere. Rebuild the homepage. +- **A private homepage build, never deployed.** `archilyzer build homepage --private` builds every published article into `homepage/out-private`, served with `pnpm --filter homepage start:private` (port 3032); `homepage/out` is untouched. A homepage build stamped private, or a public one carrying an article that is not public, a moment such an article cites, or an X post while X posts are private, is refused by the build, the deploy and the status line. ## 2026-08-12 diff --git a/homepage/app/articles/[reportId]/history/page.tsx b/homepage/app/articles/[reportId]/history/page.tsx @@ -0,0 +1,36 @@ +import type { Metadata } from "next"; +import { REPORT_PLACEHOLDER_ID, reportFullTitle } from "yt-dlp-transcript-common/lib/report/views"; +import ReportHistory from "yt-dlp-transcript-common/components/report/ReportHistory"; +import { EmptyState } from "yt-dlp-transcript-common/components/report/parts"; +import { PageShell } from "../../../components/PageShell"; +import { ARTICLES_ROUTE_BASE, articleIds, readArticleHistory } from "../../../lib/articles"; + +// /articles/<id>/history/: the article's revisions, from +// /articles/<id>/history/history.json; one with none published says so. +export const dynamicParams = false; + +export function generateStaticParams(): { reportId: string }[] { + const ids = articleIds(); + return (ids.length > 0 ? ids : [REPORT_PLACEHOLDER_ID]).map((reportId) => ({ reportId })); +} + +type Params = { params: Promise<{ reportId: string }> }; + +export async function generateMetadata({ params }: Params): Promise<Metadata> { + const view = readArticleHistory((await params).reportId); + if (!view) return { title: "No history" }; + return { title: `Revision history — ${reportFullTitle(view)}` }; +} + +export default async function ArticleHistoryPage({ params }: Params) { + const view = readArticleHistory((await params).reportId); + return ( + <PageShell> + {view ? ( + <ReportHistory view={view} base={ARTICLES_ROUTE_BASE} /> + ) : ( + <EmptyState title="No history">This article has no published revision history.</EmptyState> + )} + </PageShell> + ); +} diff --git a/homepage/app/articles/[reportId]/page.tsx b/homepage/app/articles/[reportId]/page.tsx @@ -0,0 +1,37 @@ +import type { Metadata } from "next"; +import { REPORT_PLACEHOLDER_ID } from "yt-dlp-transcript-common/lib/report/views"; +import ReportArticle from "yt-dlp-transcript-common/components/report/ReportArticle"; +import { EmptyState } from "yt-dlp-transcript-common/components/report/parts"; +import { PageShell } from "../../components/PageShell"; +import { ARTICLES_ROUTE_BASE, articleIds, readArticleView, reportMetadata } from "../../lib/articles"; + +// /articles/<id>/: one article, from /articles/<id>/page.json. Static: every +// article the build carries, nothing else; with none, the one placeholder page +// (a static export refuses an empty generateStaticParams), which says so. +export const dynamicParams = false; + +export function generateStaticParams(): { reportId: string }[] { + const ids = articleIds(); + return (ids.length > 0 ? ids : [REPORT_PLACEHOLDER_ID]).map((reportId) => ({ reportId })); +} + +type Params = { params: Promise<{ reportId: string }> }; + +export async function generateMetadata({ params }: Params): Promise<Metadata> { + const view = readArticleView((await params).reportId); + if (!view) return { title: "No articles" }; + return reportMetadata(view); +} + +export default async function ArticlePage({ params }: Params) { + const view = readArticleView((await params).reportId); + return ( + <PageShell> + {view ? ( + <ReportArticle view={view} base={ARTICLES_ROUTE_BASE} /> + ) : ( + <EmptyState title="No articles">No article has been published yet.</EmptyState> + )} + </PageShell> + ); +} diff --git a/homepage/app/articles/page.tsx b/homepage/app/articles/page.tsx @@ -0,0 +1,20 @@ +import type { Metadata } from "next"; +import ReportIndex from "yt-dlp-transcript-common/components/report/ReportIndex"; +import { PageShell } from "../components/PageShell"; +import { readArticleIndex } from "../lib/articles"; + +export const metadata: Metadata = { title: "Articles" }; + +// /articles/: every article this build carries, in the article store's order +// (reports/index.json). An honest empty index on a tree with none. +export default function ArticlesPage() { + return ( + <PageShell> + <ReportIndex + index={readArticleIndex()} + heading="Articles" + empty={{ title: "No articles", message: "No article has been published yet." }} + /> + </PageShell> + ); +} diff --git a/homepage/app/components/Header.tsx b/homepage/app/components/Header.tsx @@ -32,7 +32,7 @@ function NavList({ className }: { className?: string }) { ); } -// The project site's header: a hairline bar with the wordmark and the four +// The project site's header: a hairline bar with the wordmark and the five // destinations (Changelog is in the footer only; lib/nav.ts). It carried NO // links at all before this — the page it sat above was the whole site. // @@ -123,7 +123,10 @@ export default function Header() { </Link> <div className="ml-auto flex min-w-0 items-center gap-8"> <nav aria-label="Main" className="hidden md:block"> - <NavList className="gap-6" /> + {/* 16 px between links up to lg, 24 px from it: with five links + (Articles, release 26) the 768 px bar holds the wordmark, the + nav and a three-link row only so. */} + <NavList className="gap-4 lg:gap-6" /> </nav> <div className="flex min-w-0 items-center"> {narrow > 0 && ( @@ -151,7 +154,7 @@ export default function Header() { </div> </div> {/* Below `md` the nav drops to its own rule rather than collapsing behind - a menu button — four links do not earn a disclosure widget, and they + a menu button — five links do not earn a disclosure widget, and they fit a 320 px rule. Only one of the two navs is ever in the accessibility tree (the other is display:none), but they carry distinct labels so a test or a screen reader can never conflate them. diff --git a/homepage/app/lib/articles.test.ts b/homepage/app/lib/articles.test.ts @@ -0,0 +1,32 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { articlesPublicDir } from "./articles"; +import { FOOTER_NAV, HEADER_NAV } from "./nav"; + +// Run with: pnpm --filter homepage test +// +// Where /articles/ reads (release 26 A3): public/, or the e2e fixture outside a +// production build while it holds an index; and the nav names it always. + +test("the fixture dir is read only outside a production build, and only while it holds an article index", () => { + const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "homepage-articles-")); + try { + const env = { E2E_ARTICLES_PUBLIC_DIR: fixture }; + assert.equal(articlesPublicDir(env, "/pub"), "/pub", "no index yet"); + fs.mkdirSync(path.join(fixture, "articles")); + fs.writeFileSync(path.join(fixture, "articles", "index.json"), "{}"); + assert.equal(articlesPublicDir(env, "/pub"), fixture); + assert.equal(articlesPublicDir({ ...env, NODE_ENV: "production" }, "/pub"), "/pub"); + assert.equal(articlesPublicDir({}, "/pub"), "/pub"); + } finally { + fs.rmSync(fixture, { recursive: true, force: true }); + } +}); + +test("Articles is in the header and the footer, unconditionally", () => { + assert.ok(HEADER_NAV.some((n) => n.href === "/articles/" && n.label === "Articles")); + assert.ok(FOOTER_NAV.some((n) => n.href === "/articles/")); +}); diff --git a/homepage/app/lib/articles.ts b/homepage/app/lib/articles.ts @@ -0,0 +1,45 @@ +import fs from "node:fs"; +import path from "node:path"; +import { createReportReader, reportMetadata } from "yt-dlp-transcript-common/lib/report/reader-server"; +import { ARTICLES_REPORTS_BASE } from "yt-dlp-transcript-common/lib/report/routes"; + +// THE ARTICLES (release 26 A3): the reports the project homepage publishes, +// read by the shared reader (common/lib/report/reader-server.ts) under +// /articles/ from what `compose homepage` wrote into public/ — articles/, +// m/ and media/, through the same reports stage a site's compose runs +// (publish/composeReports.ts over publish/reportHost.ts articlesReportHost). +// +// A build:nodata tree has none: every reader answers "none", /articles/ +// renders its empty index and the nav stays unconditional (./nav.ts). +// +// E2E_ARTICLES_PUBLIC_DIR names a fixture public dir to read instead — but +// ONLY outside a production build, and only while it holds an article index +// (the source.ts rule): `next build` runs with NODE_ENV=production. +export function articlesPublicDir( + env: Readonly<Record<string, string | undefined>> = process.env, + publicDir: string = path.join(/* turbopackIgnore: true */ process.cwd(), "public"), +): string { + const fixture = env.NODE_ENV !== "production" ? env.E2E_ARTICLES_PUBLIC_DIR : undefined; + if (fixture && fs.existsSync(path.join(/* turbopackIgnore: true */ fixture, "articles", "index.json"))) return fixture; + return publicDir; +} + +const reader = createReportReader({ publicDir: () => articlesPublicDir(), base: ARTICLES_REPORTS_BASE }); + +export const ARTICLES_ROUTE_BASE = reader.base; +export const readArticleIndex = () => reader.readReportIndex(); +export const articleIds = () => reader.reportIds(); +export const readArticleView = (id: string) => reader.readReportView(id); +export const readArticleHistory = (id: string) => reader.readReportHistory(id); +export const momentKeys = () => reader.momentKeys(); +export const readMomentView = (key: string) => reader.readMomentView(key); + +// The newest few, for the home page: the index's order is the operator's +// (reports/index.json), so "latest" is by date, newest first. +export function latestArticles(n: number) { + const reports = readArticleIndex()?.reports ?? []; + const at = (r: { updated?: string; published?: string }) => Date.parse(r.updated ?? r.published ?? "") || 0; + return [...reports].sort((a, b) => at(b) - at(a)).slice(0, n); +} + +export { reportMetadata }; diff --git a/homepage/app/lib/nav.ts b/homepage/app/lib/nav.ts @@ -1,13 +1,14 @@ // The site's navigation, declared once. Order is editorial: what the software // is, where its code lives, how to get it, what this deployment has done, what -// changed. +// it has published (the articles, release 26), what changed. // // HEADER_NAV the header's links; // FOOTER_NAV the footer's "Sections" and the 404 page: the header's links, // then Changelog, which is in the footer only. // // Every entry must resolve on a `build:nodata` tree — /stats/ renders an honest -// no-data panel and /source/ an honest "nothing published" rather than 404ing — +// no-data panel, /source/ an honest "nothing published" and /articles/ an +// honest empty index rather than 404ing — // so the nav never has to be conditional. export type NavItem = { href: string; label: string }; @@ -16,6 +17,7 @@ export const HEADER_NAV: readonly NavItem[] = [ { href: "/source/", label: "Source" }, { href: "/downloads/", label: "Downloads" }, { href: "/stats/", label: "Stats" }, + { href: "/articles/", label: "Articles" }, ]; export const FOOTER_NAV: readonly NavItem[] = [ diff --git a/homepage/app/m/[...moment]/page.tsx b/homepage/app/m/[...moment]/page.tsx @@ -0,0 +1,43 @@ +import type { Metadata } from "next"; +import { MOMENT_PLACEHOLDER_KEY } from "yt-dlp-transcript-common/lib/report/views"; +import MomentArticle from "yt-dlp-transcript-common/components/report/MomentArticle"; +import { EmptyState } from "yt-dlp-transcript-common/components/report/parts"; +import { PageShell } from "../../components/PageShell"; +import { momentKeys, readMomentView } from "../../lib/articles"; + +// /m/<channel>/<id>/<start>-<end>/ (a span) and /m/<channel>/<id>/ (a post): +// one moment the articles cite, from /m/<key>/moment.json. Its record opens in +// the listed public archive that publishes the channel — compose wrote that +// absolute link into the view — or nowhere. Static: with none, one placeholder. +export const dynamicParams = false; + +export function generateStaticParams(): { moment: string[] }[] { + const keys = momentKeys(); + return (keys.length > 0 ? keys : [MOMENT_PLACEHOLDER_KEY]).map((k) => ({ moment: k.split("/") })); +} + +type Params = { params: Promise<{ moment: string[] }> }; + +async function keyOf(params: Params["params"]): Promise<string> { + return (await params).moment.map((s) => decodeURIComponent(s)).join("/"); +} + +export async function generateMetadata({ params }: Params): Promise<Metadata> { + const view = readMomentView(await keyOf(params)); + if (!view) return { title: "No moments" }; + const who = view.record.title ?? view.record.channelTitle ?? view.record.channel; + return { title: `“${view.quote.length > 60 ? `${view.quote.slice(0, 57)}…` : view.quote}” — ${who}` }; +} + +export default async function MomentPage({ params }: Params) { + const view = readMomentView(await keyOf(params)); + return ( + <PageShell> + {view ? ( + <MomentArticle view={view} /> + ) : ( + <EmptyState title="No moments">No article cites a moment yet.</EmptyState> + )} + </PageShell> + ); +} diff --git a/homepage/app/page.tsx b/homepage/app/page.tsx @@ -4,6 +4,7 @@ import { FamilyStats } from "./components/FamilyStats"; import { ArchiveCards } from "./components/ArchiveCards"; import { loadSummary } from "./lib/summary"; import { currentHomepage } from "./lib/homepage"; +import { latestArticles } from "./lib/articles"; // The project's front page. It says what Archilyzer is, shows what it has // built, and offers the download. @@ -15,7 +16,8 @@ import { currentHomepage } from "./lib/homepage"; // Copy rules, kept deliberately: short declarative sentences, no eyebrow over // every band, no subtitles under the headings or the cards, headings in Title // Case (the hub shelf matches). The page has two headings after -// the H1 and both name what is under them. +// the H1 and both name what is under them, and a third, Latest Articles, when +// the build carries any (release 26: the newest three, linking /articles/). const CONTAINER = "w-full max-w-6xl mx-auto px-5 sm:px-6"; @@ -32,6 +34,7 @@ export default function Home() { // The URL comes from homepage.json (the hub's own build reads it too). const HUB_LINK_ENABLED = false; const hubUrl = HUB_LINK_ENABLED ? (currentHomepage().siteUrl ?? null) : null; + const articles = latestArticles(3); return ( <> @@ -126,6 +129,37 @@ export default function Home() { </section> )} + {/* ── Latest Articles ──────────────────────────────────────────────── */} + {articles.length > 0 && ( + <section data-latest-articles="" className="border-t border-[var(--border)]"> + <div className={`${CONTAINER} py-14 sm:py-20`}> + <h2 className="mb-8 font-display text-2xl font-semibold text-[var(--foreground)]"> + Latest Articles + </h2> + <ul className="flex max-w-3xl flex-col gap-5"> + {articles.map((a) => ( + <li key={a.id} className="flex flex-col gap-1"> + {a.series && <span className="label-machine">{a.series}</span>} + <Link + href={a.href} + className="font-display text-lg font-semibold text-[var(--foreground)] underline decoration-[var(--border-strong)] underline-offset-4 hover:decoration-[var(--foreground)]" + > + {a.title} + </Link> + {a.subtitle && <span className="text-[var(--muted-foreground)]">{a.subtitle}</span>} + </li> + ))} + </ul> + <Link + href="/articles/" + className="mt-8 inline-block text-[var(--foreground)] underline decoration-[var(--border-strong)] underline-offset-4 hover:decoration-[var(--foreground)]" + > + All articles + </Link> + </div> + </section> + )} + {/* ── What It Does ─────────────────────────────────────────────────── */} {/* Three short paragraphs, not three titled panels: without titles, three one-sentence items read as prose, not as a feature grid. */} diff --git a/homepage/e2e/articles.spec.ts b/homepage/e2e/articles.spec.ts @@ -0,0 +1,67 @@ +import path from "node:path"; +import { test, expect } from "@playwright/test"; +import { + FIXTURE_ARCHIVE_URL, + FIXTURE_ARTICLES_NAME, + FIXTURE_ARTICLE_ID, + FIXTURE_LINKED_MOMENT, + clearFixtureArticles, + writeFixtureArticles, +} from "./fixture-articles"; + +// The homepage's articles (release 26 A3): the nav's Articles, /articles/ and +// an article, its moments — one opening in the listed archive that publishes +// its channel, one in none — and the home page's Latest Articles. The fixture +// (e2e/fixture-articles.ts) is written for this file and removed after it; the +// empty index is checked with it gone. + +const DIR = () => path.resolve(test.info().project.testDir, FIXTURE_ARTICLES_NAME); + +test.describe.configure({ mode: "serial" }); + +test("with none, /articles/ is an honest empty index and the home page names no article", async ({ page }) => { + clearFixtureArticles(DIR()); + const res = await page.goto("/articles/"); + expect(res?.status()).toBe(200); + await expect(page.getByText("No articles", { exact: true })).toBeVisible(); + await page.goto("/"); + await expect(page.locator("[data-latest-articles]")).toHaveCount(0); +}); + +test.describe("with articles", () => { + test.beforeAll(() => writeFixtureArticles(DIR())); + test.afterAll(() => clearFixtureArticles(DIR())); + + test("the nav's Articles opens the index; an article reads under /articles/", async ({ page }) => { + await page.goto("/"); + await page.getByRole("navigation", { name: "Main", exact: true }).getByRole("link", { name: "Articles" }).click(); + await expect(page).toHaveURL(/\/articles\/$/); + const card = page.locator("[data-report-index] a").first(); + await expect(card).toHaveAttribute("href", `/articles/${FIXTURE_ARTICLE_ID}/`); + await card.click(); + await expect(page).toHaveURL(new RegExp(`/articles/${FIXTURE_ARTICLE_ID}/$`)); + await expect(page.getByRole("heading", { level: 1 })).toContainText("Checking an example article"); + // Its downloads and history hang off the same base. + await expect(page.locator(`a[href="/articles/${FIXTURE_ARTICLE_ID}/citations.json"]`).first()).toBeAttached(); + }); + + test("a moment opens in the listed archive that publishes its channel, or in none", async ({ page }) => { + await page.goto(`/m/${FIXTURE_LINKED_MOMENT}/`); + await expect(page.getByRole("link", { name: "Open in the archive" })).toHaveAttribute( + "href", + new RegExp(`^${FIXTURE_ARCHIVE_URL.replace(/\./g, "\\.")}/\\?v=`), + ); + const res = await page.goto("/m/demo-podcast/ep-042/610.50-628.00/"); + expect(res?.status()).toBe(200); + await expect(page.getByText("Like I said before, spring twenty nineteen.", { exact: false }).first()).toBeVisible(); + await expect(page.getByRole("link", { name: "Open in the archive" })).toHaveCount(0); + }); + + test("the home page shows the latest articles and links them all", async ({ page }) => { + await page.goto("/"); + const latest = page.locator("[data-latest-articles]"); + await expect(latest.getByRole("heading", { name: "Latest Articles" })).toBeVisible(); + await expect(latest.locator(`a[href="/articles/${FIXTURE_ARTICLE_ID}/"]`)).toBeVisible(); + await expect(latest.getByRole("link", { name: "All articles" })).toHaveAttribute("href", "/articles/"); + }); +}); diff --git a/homepage/e2e/fixture-articles.ts b/homepage/e2e/fixture-articles.ts @@ -0,0 +1,61 @@ +import fs from "node:fs"; +import path from "node:path"; + +// A FIXTURE ARTICLE PUBLISH for /articles/ and /m/ (release 26 A3). The pages +// read the directory E2E_ARTICLES_PUBLIC_DIR names instead of public/ while it +// holds articles/index.json (app/lib/articles.ts, honoured only outside a +// production build), so a spec shows them with articles whatever this checkout +// has composed. e2e/articles.spec.ts writes it and removes it after: with it +// gone, /articles/ is the honest empty index again (no-data and marketing read +// that). playwright.config.ts clears it before the server starts. +// +// Its data is export's report-site fixture (export/fixtures/report-site/ +// public: the view JSON compose writes), as compose writes it for the homepage: +// under /articles/ rather than a site's /pages/, and one moment opening in the listed +// public archive that publishes its channel (an absolute corpusUrl) — the +// others in none. The binary media is not copied: nothing here is served. + +export const FIXTURE_ARTICLES_NAME = ".e2e-articles"; +export const FIXTURE_ARTICLE_ID = "demo-factcheck"; +export const FIXTURE_ARCHIVE_URL = "https://archive.example.test"; +export const FIXTURE_LINKED_MOMENT = "demo-channel/abc123/3126.00-3151.00"; + +// Resolved from the cwd, as playwright.config.ts resolves the fixtures: the suite runs in homepage/. +const SOURCE = path.resolve(process.cwd(), "..", "export", "fixtures", "report-site", "public"); + +function copyJson(from: string, to: string, edit?: (v: Record<string, unknown>) => void): void { + const text = fs.readFileSync(from, "utf8").replaceAll('"/pages/', '"/articles/'); + const value = JSON.parse(text) as Record<string, unknown>; + edit?.(value); + fs.mkdirSync(path.dirname(to), { recursive: true }); + fs.writeFileSync(to, JSON.stringify(value, null, 2)); +} + +function walk(dir: string, rel = ""): string[] { + const out: string[] = []; + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const r = rel ? `${rel}/${e.name}` : e.name; + if (e.isDirectory()) out.push(...walk(path.join(dir, e.name), r)); + else if (e.name.endsWith(".json")) out.push(r); + } + return out; +} + +export function writeFixtureArticles(dest: string): void { + clearFixtureArticles(dest); + for (const rel of walk(path.join(SOURCE, "pages"))) { + copyJson(path.join(SOURCE, "pages", rel), path.join(dest, "articles", rel)); + } + for (const rel of walk(path.join(SOURCE, "m"))) { + copyJson(path.join(SOURCE, "m", rel), path.join(dest, "m", rel), (v) => { + if (rel === `${FIXTURE_LINKED_MOMENT}/moment.json`) { + const record = v.record as Record<string, unknown>; + record.corpusUrl = `${FIXTURE_ARCHIVE_URL}/?v=demo-channel%2Fabc123&t=3126`; + } + }); + } +} + +export function clearFixtureArticles(dest: string): void { + fs.rmSync(dest, { recursive: true, force: true }); +} diff --git a/homepage/e2e/marketing.spec.ts b/homepage/e2e/marketing.spec.ts @@ -38,15 +38,15 @@ test("the hub link, when there is one, leaves for the hub", async ({ page }) => await expect(hub).toHaveAttribute("href", /^https?:\/\/[^/]/); }); -// The header carries four destinations; the footer's "Sections" carries the -// same four and Changelog, which is in the footer only (app/lib/nav.ts). -const HEADER_LINKS = ["Docs", "Source", "Downloads", "Stats"]; +// The header carries five destinations; the footer's "Sections" carries the +// same five and Changelog, which is in the footer only (app/lib/nav.ts). +const HEADER_LINKS = ["Docs", "Source", "Downloads", "Stats", "Articles"]; const FOOTER_LINKS = [...HEADER_LINKS, "Changelog"]; const linkNames = (nav: import("@playwright/test").Locator) => nav.getByRole("link").evaluateAll((els) => els.map((e) => e.textContent?.trim())); -test("the header nav has four links and no Changelog; the footer's has five", async ({ +test("the header nav has five links and no Changelog; the footer's has six", async ({ page, }) => { for (const width of [360, 1280]) { @@ -60,7 +60,7 @@ test("the header nav has four links and no Changelog; the footer's has five", as }); test("Changelog is reachable from the footer on every page", async ({ page }) => { - for (const path of ["/", "/docs/", "/source/", "/downloads/", "/stats/", "/changelog/", "/no-such-page/"]) { + for (const path of ["/", "/docs/", "/source/", "/downloads/", "/stats/", "/articles/", "/changelog/", "/no-such-page/"]) { await page.goto(path); await expect( page.getByRole("navigation", { name: "Footer" }).getByRole("link", { name: "Changelog" }), @@ -78,6 +78,7 @@ test("every nav destination resolves", async ({ page }) => { ["Source", "/source/"], ["Downloads", "/downloads/"], ["Stats", "/stats/"], + ["Articles", "/articles/"], ["Changelog", "/changelog/"], ]) { const res = await page.request.get(path); diff --git a/homepage/next.config.ts b/homepage/next.config.ts @@ -23,6 +23,11 @@ const nextConfig: NextConfig = { // this app also uses. turbopack: { root: path.join(__dirname, "..") }, output: "export", + // The PRIVATE build (release 26 A4: `archilyzer build homepage --private`) + // writes its export to homepage/out-private, never homepage/out — the bundle + // a deploy ships. With output "export", Next takes a custom distDir as the + // export directory and keeps its build files in .next. + ...(process.env.HOMEPAGE_DIST_DIR ? { distDir: process.env.HOMEPAGE_DIST_DIR } : {}), trailingSlash: true, images: { unoptimized: true }, staticPageGenerationTimeout: 600, // Increase timeout to 600 seconds diff --git a/homepage/package.json b/homepage/package.json @@ -12,6 +12,7 @@ "build": "next build", "build:nodata": "next build", "start": "serve out -l ${HOMEPAGE_PORT:-3031}", + "start:private": "serve out-private -l ${HOMEPAGE_PRIVATE_PORT:-3032}", "lint": "eslint", "test": "tsx --test \"app/**/*.test.ts\"", "e2e": "node ../scripts/queue-lock.mjs --name e2e-homepage --estimate 1500 --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", diff --git a/homepage/playwright.config.ts b/homepage/playwright.config.ts @@ -12,6 +12,7 @@ import { writeFixtureSettings, } from "./e2e/fixture-social"; import { FIXTURE_SOURCE_NAME, clearFixtureSource } from "./e2e/fixture-source"; +import { FIXTURE_ARTICLES_NAME, clearFixtureArticles } from "./e2e/fixture-articles"; // Homepage e2e. Runs against `next dev` (default mode) so it reflects uncommitted // source. Kill any stale dev server on the port between runs. @@ -45,6 +46,12 @@ import { FIXTURE_SOURCE_NAME, clearFixtureSource } from "./e2e/fixture-source"; // a production build). e2e/source-history.spec.ts // writes a fixture publish there and removes it; // empty, the page reads public/ +// E2E_ARTICLES_PUBLIC_DIR set below on the dev server: the directory +// /articles/ and /m/ read WHILE it holds +// articles/index.json (app/lib/articles.ts, +// ignored by a production build). +// e2e/articles.spec.ts writes a fixture there +// (e2e/fixture-articles.ts) and removes it const PORT = portFor("HOMEPAGE_E2E_PORT"); const baseURL = `http://localhost:${PORT}`; @@ -68,6 +75,10 @@ fs.mkdirSync(FIXTURE_SITES_DIR, { recursive: true }); const FIXTURE_SOURCE_DIR = path.resolve(process.cwd(), "e2e", FIXTURE_SOURCE_NAME); clearFixtureSource(FIXTURE_SOURCE_DIR); +// The fixture articles: none until e2e/articles.spec.ts writes them. +const FIXTURE_ARTICLES_DIR = path.resolve(process.cwd(), "e2e", FIXTURE_ARTICLES_NAME); +clearFixtureArticles(FIXTURE_ARTICLES_DIR); + // E2E_MODE (start | dev), the editor's and umtool's switch: those suites // default to `start`, a production build the stamp vouches for // (scripts/e2e-stamp.mjs). This suite always runs under `next dev`: the homepage is a @@ -116,6 +127,7 @@ export default defineConfig({ SETTINGS_FILE: FIXTURE_SETTINGS, SITES_DIR: FIXTURE_SITES_DIR, E2E_SOURCE_PUBLIC_DIR: FIXTURE_SOURCE_DIR, + E2E_ARTICLES_PUBLIC_DIR: FIXTURE_ARTICLES_DIR, }, }, use: { diff --git a/plans/reports-on-homepage.md b/plans/reports-on-homepage.md @@ -254,3 +254,59 @@ sites-crud gained "a site with search off and no pages is refused on save" and c `pages` this release; it should write `pages` before the legacy read is removed. The editor's Reports tab still says "Reports" (the tab keeps site pages, A6). corpus.json's spec is not bumped for the `/pages/` paths: no report was ever published, and readers follow `reports.index`. + +### A3, as shipped + +The homepage publishes the articles (branch `r26/store`, Lane B; merged with A5 at 7f8a0809). + +| Commit | What | +|---|---| +| ed9716f6 | homepage: compose's reports stage under `/articles/`, the routes, the nav, the latest few | +| 7f8a0809 | merge r26/integration (A5): A5's host base taken over A3's shim; umtool's sites fixture → `pages` | + +- **Compose.** `compose homepage` runs `composeHostReports` over `articlesReportHost(paths, {audience, siteUrl: + PROJECT_URL, channelSiteUrl})` into homepage/public: `articles/`, `m/`, `media/` (clips, captures), history, + exports, feeds. `channelSiteUrlOf(channelSites, sites)` gives a moment's record the first listed site that + publishes its channel (its `siteUrl`), else no link. The build is stamped `homepage-build.json` `{format, version, + audience, articles}`. `--private` / `--allow-missing-media` on `compose homepage`. +- **Base.** A3 first threaded the host's base through compose, feeds (an optional `base`), history and exports with + a shim for the views' own paths; A5's `ReportHost.base` (views.ts builders taking the base) replaced the shim at + the merge, and `ARTICLES_REPORTS_BASE` (A5's name) is the one constant. +- **App.** `homepage/app/lib/articles.ts` binds the shared reader to `public/` under `/articles/` + (`E2E_ARTICLES_PUBLIC_DIR` outside a production build). Routes `/articles/`, `/articles/[reportId]/`, + `/articles/[reportId]/history/`, `/m/[...moment]/` render the shared components in PageShell, a placeholder param + and an honest empty state with none. Nav: "Articles" in HEADER_NAV (and so the footer); the md nav's link gap is + 16 px below lg so five links and a three-link social row fit 768 px. The front page's "Latest Articles" (newest + three by date, "All articles") shows only when there are articles. + +### A4, as shipped + +| Commit | What | +|---|---| +| 1c064557 | homepage: the private build and the public build's audit | +| eee153fc | cli: the usage test names `build homepage --private` | + +- **Private build.** `archilyzer build homepage --private` → compose `--private`, `next build` with + `HOMEPAGE_DIST_DIR=out-private` (next.config `distDir`; Next exports there and keeps its build in `.next`), its + stamp checked, then the articles removed from homepage/public (`clearHomepageArticles`). `pnpm --filter homepage + start:private` serves it (`HOMEPAGE_PRIVATE_PORT`, 3032). homepage/out is never touched; nothing deploys + out-private. +- **Audit.** `common/lib/builtHomepage.ts` `homepageAudienceProblem(outDir, {paths?, settings?})`, asked by + `builtHomepageProblem` (deploy stage with paths + settings, the publish status, and the public build after `next + build`, which fails on it): a private stamp; an article under `out/articles/` whose report.json is not + `audience: "public"` now (or gone); a moment whose `citedIn` names a non-public article or no article; an X + channel's moment or `media/posts/` capture while `social.x.visibility` is private. + +**Gates (A3 + A4, after the A5 merge).** tsc every package: clean. common 3816 (the two `_cli.test.ts` usage +assertions updated for `--private`, then 26/26); editor unit 264/264; test:scripts 836 (833 pass, 3 skipped); mcp +306/306; export unit 117/117; homepage unit 25/25. New tests: `lib/builtHomepage.test.ts` 5, `bin/compose-homepage.test.ts` +3, `publish/build.test.ts` +1 (both builds through seams), `publish/deployStage.test.ts` +1 (the deploy refuses a +private build and a private article), `homepage/app/lib/articles.test.ts` 2. Homepage e2e, the whole suite, one +foreground run: 110/110 in 2.3 min (a first run, before the nav gap fix, failed `social.spec.ts` "768 and 1280 px … +in one bar": the fifth link made the social row scroll at 768). umtool `sites.spec.ts` + `articles.spec.ts` 6/6 on +the `pages` fixture. `build:nodata` homepage build: rc 0, `/articles/` the empty index, `/articles/_none` and +`/m/_none` placeholders. Over a temp corpus (one public, one private article, a listed site, a real ffmpeg clip +prepared with `reports prepare --article`): the public build rc 0 carrying `open` alone, audit null, its links under +`/articles/open/`; flipping `open` private refuses that out ("carries the article \"open\", which is not public"); +the private build rc 0 into out-private with both, its stamp refused for deploy, homepage/public left without +articles; a public build with zero public articles rc 0, stamp `articles: []`. diff --git a/umtool/e2e/fixtures/sites-fixture.mjs b/umtool/e2e/fixtures/sites-fixture.mjs @@ -10,7 +10,7 @@ // polemic-alpha PUBLISHED: summary, two sections, cites sitechan/sv1 // (a clip window on disk: plays) and sitechan/sv2 (cues, // no media: the fetch_clip line); video.mp4 + poster.jpg -// polemic-beta a DRAFT (not in site.json's reports) +// polemic-beta a DRAFT (not in site.json's pages) // sites/pub public. Reports: // gamma PUBLISHED, one section, no citations // <dest>/sitews/ the WORKSPACE (a direct child of REPORTS_ROOT, which the @@ -103,8 +103,8 @@ export function makeSitesFixture({ dest, channels }) { clip(path.join(channels, "sitechan", "data", "sv1", "clips", "0.00-12.00.mp4"), 12, 523); // ---- the sites ------------------------------------------------------------ - put(path.join(sites, "priv", "site.json"), siteJson("priv", "Private Fixture", { audience: "private", search: false, reports: ["polemic-alpha"] })); - put(path.join(sites, "pub", "site.json"), siteJson("pub", "Public Fixture", { reports: ["gamma"] })); + put(path.join(sites, "priv", "site.json"), siteJson("priv", "Private Fixture", { audience: "private", search: false, pages: ["polemic-alpha"] })); + put(path.join(sites, "pub", "site.json"), siteJson("pub", "Public Fixture", { pages: ["gamma"] })); const alphaDir = path.join(sites, "priv", "reports", "polemic-alpha"); put(path.join(alphaDir, "report.json"), {