Archilyzer · Source

archilyzer

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

commit be396e88b0a0315696bc18feae5cdb14955a3efc
parent c8c84def5e0c91c54c4fab858008a30e8486f5f5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 14:41:41 -0400

Merge r26/integration (A2 the article store, A6 the tools, the A7 script) into r26/renderer

Conflicts resolved to the integration's host model (reportHost.ts), with A5
carried into it, and the orchestrator's four asks for A5:

- the rename reaches the host model: siteReportHost publishes `pages`,
  reports check and the umtool sites views read `pages`; the A7 move script
  writes `pages` through patchSite and RETIRES a search-off site it empties —
  the patch dropping its last page turns its search on in the same write, so
  it saves as an empty site (no channels, no pages) instead of being refused
  by siteSearchProblem; the plan line says to delete it on /sites;
- the base is a host parameter: ReportHost.base — `/pages/` for a site,
  `/articles/` (ARTICLES_REPORTS_BASE) for the homepage — threaded through
  compose (every written path, the index entries, cited-in hrefs, stills and
  video, downloads, feeds, the history page, view and clone), the exports
  (the page link, the evidence pack's report files) and the history;
  reportPublicEntries(base) is what compose clears;
- reserved site ids: `articles` and `new` are refused by writeSite and the
  editor's save (reservedSiteIdProblem), with a test;
- ComposeReportsError names its host: "the site's pages" or "the articles".

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

Diffstat:
MCOMMANDS.md | 16+++++++++-------
MENVIRONMENT.md | 1+
MREPORT.md | 10+++++++++-
Mcommon/bin/archilyzer.ts | 88++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Acommon/bin/move-reports-to-articles.test.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/move-reports-to-articles.ts | 225+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/reports-article.test.ts | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/reports-attach-video.ts | 26+++++++++++++++++++++++---
Mcommon/bin/reports-check.ts | 47+++++++++++++++++++++++++++++++++--------------
Mcommon/bin/reports-export.ts | 18+++++++++++++++---
Mcommon/bin/reports-prepare.ts | 31+++++++++++++++++++++++++------
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/paths.ts | 7+++++++
Mcommon/lib/report/docs.ts | 38+++++++++++++++++++++++++++++++-------
Mcommon/lib/report/exportHtml.ts | 6+++++-
Mcommon/lib/report/exportMarkdown.ts | 2+-
Mcommon/lib/report/exportSlidesHtml.ts | 7+++++--
Mcommon/lib/report/feeds.ts | 45+++++++++++++++++++++++++++++----------------
Acommon/lib/report/registry.test.ts | 236+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/registry.ts | 507+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/routes.ts | 3+++
Mcommon/lib/report/schema.ts | 11+++++++++++
Acommon/lib/report/store.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/views.ts | 13++++++++-----
Mcommon/lib/site.ts | 3+++
Mcommon/lib/siteSchema.test.ts | 17+++++++++++++++++
Mcommon/lib/siteSchema.ts | 12++++++++++++
Mcommon/publish/composeReports.ts | 227++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Acommon/publish/composeReportsArticles.test.ts | 264+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/reportExportFiles.ts | 45++++++++++++++++++++++++++++++++++++---------
Mcommon/publish/reportExports.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Mcommon/publish/reportHistory.ts | 30+++++++++++++++++++++++-------
Acommon/publish/reportHost.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/reportMedia.ts | 122++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
Mcommon/publish/reportVideo.ts | 15++++++++++++---
Meditor/CHANGELOG.md | 5+++++
Aeditor/app/api/ops/articles-config/route.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/articles-config/route.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/reports-export/route.test.ts | 11+++++++++++
Meditor/app/api/ops/reports-export/route.ts | 27++++++++++++++++++---------
Meditor/app/api/ops/reports-prepare/route.test.ts | 11+++++++++++
Meditor/app/api/ops/reports-prepare/route.ts | 19++++++++++++++++---
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 27+++++++++++++++++++++++++--
Meditor/app/jobs/jobReplayRegistry.ts | 9+++++++++
Meditor/app/sites/[siteId]/reports/page.tsx | 2+-
Meditor/app/sites/actions.ts | 5+++++
Aeditor/app/sites/articles/page.tsx | 289++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/sites/components/ArticleRowActions.tsx | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/sites/components/ArticlesJobButtons.tsx | 40++++++++++++++++++++++++++++++++++++++++
Meditor/app/sites/components/FetchMissingEvidenceButton.tsx | 10++++++++--
Meditor/app/sites/components/ReportRowActions.tsx | 2+-
Aeditor/app/sites/lib/articlesActions.ts | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/sites/lib/articlesServer.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/sites/lib/reportList.ts | 2+-
Meditor/app/sites/lib/reportsActions.ts | 2+-
Meditor/app/sites/page.tsx | 21+++++++++++++++------
Aeditor/e2e/articles.spec.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/reports-on-homepage.md | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 21++++++++++++++++++++-
Mumtool/app/api/sites/evidence/route.ts | 4++--
Mumtool/app/api/sites/media/route.ts | 17+++++++++--------
Aumtool/app/articles/[report]/evidence/page.tsx | 18++++++++++++++++++
Aumtool/app/articles/[report]/page.tsx | 32++++++++++++++++++++++++++++++++
Aumtool/app/articles/page.tsx | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/sites/[site]/[report]/evidence/page.tsx | 55+++++++++++++------------------------------------------
Mumtool/app/sites/[site]/[report]/page.tsx | 213+++++++------------------------------------------------------------------------
Mumtool/components/AppNav.tsx | 11++++++-----
Aumtool/components/articles/ArticlePage.tsx | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/ArticleReader.tsx | 3++-
Mumtool/components/articles/ArticleTable.tsx | 10+++++++---
Aumtool/components/articles/EvidencePage.tsx | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/EvidenceWalk.tsx | 3++-
Mumtool/docs/notes.md | 19++++++++++++-------
Mumtool/docs/sites.md | 2+-
Aumtool/e2e/articles.spec.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3++-
Mumtool/e2e/fixtures/sites-fixture.mjs | 33++++++++++++++++++++++++++++++++-
Mumtool/lib/annotations/cli.mjs | 17+++++++++--------
Mumtool/lib/annotations/cli.test.mjs | 3++-
Mumtool/lib/annotations/digest.mjs | 10+++++-----
Mumtool/lib/annotations/store.test.mjs | 37+++++++++++++++++++++++++++++++++++--
Mumtool/lib/annotations/targets.mjs | 30+++++++++++++++++++++---------
Mumtool/lib/articles/evidence.ts | 8++++----
Aumtool/lib/articles/href.ts | 16++++++++++++++++
Aumtool/lib/articles/key.mjs | 6++++++
Mumtool/lib/articles/sites.ts | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/decisions.ts | 3++-
Mumtool/lib/paths.mjs | 54+++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/paths.ts | 2++
Mumtool/playwright.config.ts | 3+++
90 files changed, 4408 insertions(+), 618 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -29,11 +29,12 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `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 reports prepare` | `<id>` | 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) | -| `archilyzer reports export` | `<id> [--report <reportId>] [--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) | -| `archilyzer reports check` | `<id> [--reports <a,b>] [--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) | -| `archilyzer reports verify-quotes` | `<report.json> [--json]` | every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted) | -| `archilyzer reports attach-video` | `<report.json> <video> [--poster <image>] [--caption <line>]` | the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json | +| `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 | +| `archilyzer reports verify-quotes` | `<report.json> \| --article <articleId>` | \[--json\] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted) | +| `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster &lt;image&gt;\] \[--caption &lt;line&gt;\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) | +| `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* | | `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) | | `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) | | `archilyzer source publish` | `[--force] [--check] [--keep-scratch]` | the scrubbed git mirror, raw tree, history pages (stagit, when installed) and tarball into homepage/public, behind the denied-literal gate (--check: audit and count, write nothing) | @@ -82,6 +83,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'` | | `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). | `pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | | `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | +| `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | | `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` | | `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` | | `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | @@ -109,8 +111,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `relocate` | relocate moves channels' media to a location: {"slugs", "locationId" \| "root"}. "dryRun": true answers each channel's preview (bytes to copy, free space both sides) and moves nothing — though, as on the Storage panel, a channel never tiered is first tiered in place on the corpus disk. | `pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}'`<br>`pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}'` | | `relocate-back` | relocate-back moves channels' media back onto the corpus disk, one job per channel on the relocation queue: {"slugs"}. A busy channel is answered in "skipped"; --wait follows the jobs started. | | | `evict-clips` | evict-clips deletes cached clip windows (data/&lt;id&gt;/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. | | -| `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait` | -| `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}. | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | +| `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "&lt;id&gt;"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` | +| `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | | `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` | | `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -15,6 +15,7 @@ The one override surface for where things live and which binary runs. Every one | `TRANSCRIPTS_DIR` | `<repo>/transcripts` | The corpus: channels, sites, the LMDB index, job logs, the saved-video store. umtool reads `<it>/channels` too, when its own `CHANNELS_DIR` is unset. | common/lib/paths.ts (getPaths) | | `SAVED_VIDEOS_DIR` | `<TRANSCRIPTS_DIR>/saved-videos` | The persisted source-video store, when it should live on another disk. | common/lib/paths.ts (getPaths) | | `SITES_DIR` | `<TRANSCRIPTS_DIR>/sites` | Per-site config (`<id>/site.json`, every key in [SITE.md](SITE.md)) and the homepage's `_homepage/`. | common/lib/paths.ts (getPaths) | +| `ARTICLES_DIR` | `<TRANSCRIPTS_DIR>/reports` | The article store: one directory per article (`<id>/report.json`, [REPORT.md](REPORT.md)) and `index.json`, the published list. umtool reads it too. | common/lib/paths.ts (getPaths) | | `SETTINGS_FILE` | `<repo>/settings.json` | The settings file (every key in [SETTINGS.md](SETTINGS.md)). | common/lib/paths.ts (getPaths) | | `EXPORT_PUBLIC_DIR` | `<repo>/export/public` | The dir the export site serves at `/`, composed one site at a time. | common/lib/paths.ts (getPaths) | | `EXPORT_INDEX_DIR` | `.export-index` beside `EXPORT_PUBLIC_DIR` | The build's staging area (not served): the shared index and per-site aggregates. | common/lib/paths.ts (getPaths) | diff --git a/REPORT.md b/REPORT.md @@ -2,7 +2,14 @@ <!-- GENERATED by common/bin/file-schemas-docs.ts from the schemas and their *_FIELD_DOCS records — do not edit by hand. --> -One cited report, format `"archilyzer-report"`, version 1, persisted to `transcripts/sites/<siteId>/reports/<reportId>/report.json` beside its `stills/` and `sources/<sourceId>/`; a relative path in it is relative to that directory. A site's `pages` list in `site.json` is the published, ordered list, each served at `/pages/<id>/` — see [SITE.md](SITE.md); a report directory it does not name is a draft. The schema is `common/lib/report/schema.ts`; its citations and sources are the citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` beside it holds the operator's notes on the article (umtool, `umtool notes`; [umtool/docs/notes.md](umtool/docs/notes.md)) and is never published. +One cited report, format `"archilyzer-report"`, version 1, persisted as `report.json` in its own directory, beside its `stills/` and `sources/<sourceId>/`; a relative path in it is relative to that directory. The schema is `common/lib/report/schema.ts`; its citations and sources are the citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` beside it holds the operator's notes on the article (umtool, `umtool notes`; [umtool/docs/notes.md](umtool/docs/notes.md)) and is never published. + +A report lives in one of two stores: + +- **An article** — `transcripts/reports/<reportId>/report.json`, published by the project homepage. `transcripts/reports/index.json` — `{"published": [ids]}` — is the published, ordered list; an article directory it does not name is a draft. An article's `audience` (below) says which homepage build carries it: the public one only `"public"` articles, the private one every published article. An article may cite any channel of the corpus. +- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, published by its site at `/pages/<reportId>/`: the site's `pages` list in `site.json` is the published, ordered list — see [SITE.md](SITE.md). A page cites the site's `channels` and `citedChannels`. + +`index.json` and an article's `audience` are written ONLY through `common/lib/report/registry.ts` (`configureArticle`, `setPublished`, `setArticlesOrder`, `patchArticle`, `writeArticle`: locked, validated, atomic) and `pnpm ops articles-config` (`{"id", "audience"?, "published"?, "position"?}`), never by hand. Only a sound article (no problem below) is published; a patch may not add a problem to an article. A **fact-check** (`"kind": "factcheck"`) is sections (chapters) of claims, each with a verdict and its findings. A **sweep** (`"kind": "sweep"`) is sections with no verdicts, or bodies that cite inline. Either may keep a **timeline** (`entries`): dated entries appended over time. Markdown fields (`summary`, an entry's `body`, a section's `body`, a claim's `findings`) cite with `[label](cite:<id>)`. @@ -18,6 +25,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `version` | yes | `1`. | | `id` | yes | The report's id: a lowercase slug (`[a-z0-9][a-z0-9-]*`, at most 64), its directory name under `reports/` and the last segment of its page (on a site, `/pages/<id>/`). Must match the directory. | | `kind` | yes | `"factcheck"` — sections of claims, each with a verdict — or `"sweep"` — sections with no verdicts, or bodies with inline citations. | +| `audience` | no | Who may read the report when it is an ARTICLE (in `transcripts/reports/`, published by the homepage): `"public"` — the public homepage build carries it — or `"private"` — only the private build (`archilyzer build homepage --private`, never deployed) does. Absent = `"private"`: going public is an explicit `pnpm ops articles-config`. Ignored on a site's page, which has its site's audience. | | `series` | no | The series the report belongs to: a recurring name for its kind of report. It is shown on its own line above the title, in the accent colour, at the head of the report's page, its exports and the report list (where a report with no series shows its kind instead), and is joined to the title as `<series>: <title>` where one line names the report (a page title, a link, a cited-in entry). | | `title` | yes | The report's title. | | `subtitle` | no | A line under the title. | diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -263,9 +263,13 @@ export const COMMANDS: Command[] = [ { path: ["reports", "prepare"], usage: - "<id> 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)", + "<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", + flags: { article: "string" }, maxPositionals: 1, - run: async ({ positionals, env }) => { + run: async ({ positionals, flags, env }) => { + const article = articleFrom(positionals, flags, "reports prepare"); + if (article === null) return 2; + if (article) return (await import("./reports-prepare")).main({ article, signal: interrupted() }); const siteId = siteIdFrom(positionals, env, "reports prepare"); if (!siteId) return 2; return (await import("./reports-prepare")).main({ siteId, signal: interrupted() }); @@ -274,12 +278,18 @@ export const COMMANDS: Command[] = [ { path: ["reports", "export"], usage: - "<id> [--report <reportId>] [--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)", - flags: { report: "string", formats: "string", "allow-missing-media": "boolean" }, + "<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", + flags: { report: "string", formats: "string", "allow-missing-media": "boolean", article: "string" }, maxPositionals: 1, run: async ({ positionals, flags, env }) => { - const siteId = siteIdFrom(positionals, env, "reports export"); - if (!siteId) return 2; + const article = articleFrom(positionals, flags, "reports export"); + if (article === null) return 2; + if (article && typeof flags.report === "string") { + console.error("reports export: --article names the report; --report is for a site's"); + return 2; + } + const siteId = article ? undefined : siteIdFrom(positionals, env, "reports export"); + if (!article && !siteId) return 2; const { parseReportExportFormats } = await import("../publish/reportExports"); const formats = typeof flags.formats === "string" ? parseReportExportFormats(flags.formats) : undefined; if (formats === null) { @@ -287,7 +297,7 @@ export const COMMANDS: Command[] = [ return 2; } return (await import("./reports-export")).main({ - siteId, + ...(article ? { article } : { siteId: siteId! }), signal: interrupted(), ...(typeof flags.report === "string" ? { reportId: flags.report } : {}), ...(formats ? { formats } : {}), @@ -298,10 +308,18 @@ export const COMMANDS: Command[] = [ { path: ["reports", "check"], usage: - "<id> [--reports <a,b>] [--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)", - flags: { reports: "string", "allow-missing-media": "boolean" }, + "<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", + flags: { reports: "string", "allow-missing-media": "boolean", article: "string" }, maxPositionals: 1, run: async ({ positionals, flags, env }) => { + const article = articleFrom(positionals, flags, "reports check"); + if (article === null) return 2; + if (article) { + return (await import("./reports-check")).checkMain({ + article, + allowMissingMedia: flags["allow-missing-media"] === true, + }); + } const siteId = siteIdFrom(positionals, env, "reports check"); if (!siteId) return 2; const reports = @@ -318,13 +336,15 @@ export const COMMANDS: Command[] = [ { path: ["reports", "verify-quotes"], usage: - "<report.json> [--json] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted)", - flags: { json: "boolean" }, + "<report.json> | --article <articleId> [--json] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted)", + flags: { json: "boolean", article: "string" }, maxPositionals: 1, run: async ({ positionals, flags }) => { - const [file] = positionals; + const article = articleFrom(positionals, flags, "reports verify-quotes"); + if (article === null) return 2; + const file = article ? await articleReportFile(article) : positionals[0]; if (!file) { - console.error("reports verify-quotes: give <report.json>"); + console.error("reports verify-quotes: give <report.json> or --article <id>"); return 2; } return (await import("./reports-check")).verifyQuotesMain({ file, json: flags.json === true }); @@ -333,23 +353,26 @@ export const COMMANDS: Command[] = [ { path: ["reports", "attach-video"], usage: - "<report.json> <video> [--poster <image>] [--caption <line>] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json", - flags: { poster: "string", caption: "string" }, + "<report.json> <video> | --article <articleId> <video> [--poster <image>] [--caption <line>] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry)", + flags: { poster: "string", caption: "string", article: "string" }, maxPositionals: 2, run: async ({ positionals, flags }) => { - const [reportFile, video] = positionals; - if (!reportFile || !video) { - console.error("reports attach-video: give <report.json> <video>"); + const article = typeof flags.article === "string" ? flags.article.trim() : undefined; + const [reportFile, video] = article ? [undefined, positionals[0]] : positionals; + if ((article ? positionals.length !== 1 : !reportFile) || !video) { + console.error("reports attach-video: give <report.json> <video>, or --article <id> <video>"); return 2; } return (await import("./reports-attach-video")).attachVideoMain({ - reportFile, + ...(article ? { article } : { reportFile }), video, ...(typeof flags.poster === "string" ? { poster: flags.poster } : {}), ...(typeof flags.caption === "string" ? { caption: flags.caption } : {}), }); }, }, + script(["reports", "move-to-articles"], "move-reports-to-articles.ts", + "[--keep <site>/<id>,…] [--drafts] [--apply] ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply"), { path: ["reports", "convert"], usage: @@ -761,6 +784,33 @@ function script(path: string[], file: string, usage: string, heapMb?: number): C }; } +// `--article <id>`: the id, "" when the flag is absent, or null (after saying +// why) when it is empty or given beside a positional site / report.json. +function articleFrom( + positionals: string[], + flags: Record<string, unknown>, + name: string, +): string | null { + if (flags.article === undefined) return ""; + const id = typeof flags.article === "string" ? flags.article.trim() : ""; + if (!id) { + console.error(`${name}: --article needs an article id`); + return null; + } + if (positionals.length > 0) { + console.error(`${name}: --article names the article; give no site or file beside it`); + return null; + } + return id; +} + +// An article's report.json (transcripts/reports/<id>/report.json). +async function articleReportFile(id: string): Promise<string> { + const { articleFile } = await import("../lib/report/registry"); + const { getPaths } = await import("../lib/paths"); + return articleFile(getPaths(), id); +} + // The site a site command names: its argument, else SITE_ID (which is how // export's `build` / `deploy` scripts are called). Prints and returns null when // there is neither. diff --git a/common/bin/move-reports-to-articles.test.ts b/common/bin/move-reports-to-articles.test.ts @@ -0,0 +1,140 @@ +// `archilyzer reports move-to-articles` (release 26 A7's script), over a temp +// corpus only: a dry run writes nothing; --apply moves each listed report +// (history-git and notes.json with it) to reports/<id>/, private, published in +// the sites' order (one with problems as a draft), off its site; a kept page +// stays; refusals come before anything moves. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/move-reports-to-articles.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "move-to-articles-")); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + 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"), +}); +delete process.env.ARTICLES_DIR; +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { main } = await import("./move-reports-to-articles"); + +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 doc = (id: string, over: Record<string, unknown> = {}) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Fixture ${id}`, + sections: [{ id: "s", title: "S", body: "Words." }], + ...over, +}); +// `key`: site-a is written with the pre-release-26 key, which reads as `pages`. +function site(id: string, pages: string[], extra: Record<string, unknown> = {}, key: "pages" | "reports" = "pages") { + put(path.join(paths.sitesDir, id, "site.json"), { + siteId: id, + siteTitle: id, + groups: [{ id: "default", name: "All", selectedByDefault: true }], + defaultGroupId: "default", + channels: [], + [key]: pages, + ...extra, + }); +} +const reportDir = (s: string, id: string) => path.join(paths.sitesDir, s, "reports", id); +function capture() { + const lines: string[] = []; + return { text: () => lines.join("\n"), out: { log: (s: string) => lines.push(s), error: (s: string) => lines.push(s) } } as const; +} + +// Two sites: a report-only private one with two listed reports (one with a +// problem) and a draft; a full one with a page it keeps and one to move. +site("site-a", ["alpha", "beta"], { search: false, audience: "private" }, "reports"); +put(path.join(reportDir("site-a", "alpha"), "report.json"), doc("alpha")); +put(path.join(reportDir("site-a", "alpha"), "notes.json"), { format: "umtool-notes", version: 1, notes: [] }); +put(path.join(reportDir("site-a", "alpha"), "history-git", "HEAD"), "ref: refs/heads/main\n"); +put(path.join(reportDir("site-a", "alpha"), "stills", "a.png"), "png"); +put(path.join(reportDir("site-a", "beta"), "report.json"), doc("beta", { summary: "see [x](cite:nobody)" })); +put(path.join(reportDir("site-a", "draft-one"), "report.json"), doc("draft-one")); +site("site-b", ["page-kept", "gamma"]); +put(path.join(reportDir("site-b", "page-kept"), "report.json"), doc("page-kept")); +put(path.join(reportDir("site-b", "gamma"), "report.json"), doc("gamma", { audience: "public" })); + +const snapshot = () => { + const out: string[] = []; + const walk = (d: string, rel: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const r = `${rel}/${e.name}`; + if (e.isDirectory()) walk(path.join(d, e.name), r); + else out.push(`${r}:${readFileSync(path.join(d, e.name), "utf8")}`); + } + }; + walk(paths.transcriptsDir, ""); + return out.sort().join("\n"); +}; + +test("refusals before anything moves: a --keep that names nothing, an id reports/ already holds", async () => { + const before = snapshot(); + const c = capture(); + assert.equal(await main(["--keep", "site-b/nope", "--apply"], paths, c.out), 1); + assert.match(c.text(), /REFUSED --keep site-b\/nope: no site lists that report/); + put(path.join(paths.articlesDir, "gamma", "report.json"), doc("gamma")); + const c2 = capture(); + assert.equal(await main(["--keep", "site-b/page-kept", "--apply"], paths, c2.out), 1); + assert.match(c2.text(), /REFUSED site-b\/gamma: reports\/gamma\/ already exists/); + rmSync(path.join(paths.articlesDir, "gamma"), { recursive: true }); + assert.equal(snapshot(), before, "nothing written"); +}); + +test("a dry run prints the plan and writes nothing", async () => { + const before = snapshot(); + const c = capture(); + assert.equal(await main(["--keep", "site-b/page-kept"], paths, c.out), 0); + const text = c.text(); + assert.match(text, /move {3}site-a\/alpha → reports\/alpha\/ {2}published, audience private/); + assert.match(text, /move {3}site-a\/beta → reports\/beta\/ {2}draft \(1 problem\(s\) in report\.json\)/); + assert.match(text, /keep {3}site-b\/page-kept/); + assert.match(text, /retire site-a: search off and no pages left — saved with search on, as an empty site; delete it on \/sites/); + assert.match(text, /3 to move \(2 published\), 1 kept, 0 refusal/); + assert.match(text, /dry run: nothing moved/); + assert.equal(snapshot(), before); +}); + +test("--apply: moved whole, private, published in the sites' order, off the site; the kept page stays", async () => { + const c = capture(); + assert.equal(await main(["--keep", "site-b/page-kept", "--apply"], paths, c.out), 0, c.text()); + const art = (id: string, ...p: string[]) => path.join(paths.articlesDir, id, ...p); + for (const f of ["report.json", "notes.json", "history-git/HEAD", "stills/a.png"]) assert.ok(existsSync(art("alpha", f)), f); + assert.equal(existsSync(reportDir("site-a", "alpha")), false); + assert.deepEqual(readJson(path.join(paths.articlesDir, "index.json")), { published: ["alpha", "gamma"] }); + for (const id of ["alpha", "beta", "gamma"]) assert.equal(readJson(art(id, "report.json")).audience, "private", id); + // The emptied search-off site is retired: no pages, search on (a save + // refuses search off with none); the legacy key is gone from both files. + const a = readJson(path.join(paths.sitesDir, "site-a", "site.json")); + assert.equal("pages" in a || "reports" in a || "search" in a, false, JSON.stringify(a)); + assert.equal(a.audience, "private"); + const b = readJson(path.join(paths.sitesDir, "site-b", "site.json")); + assert.deepEqual(b.pages, ["page-kept"]); + assert.equal("reports" in b, false); + assert.ok(existsSync(path.join(reportDir("site-b", "page-kept"), "report.json"))); + // The unlisted draft stays without --drafts. + assert.ok(existsSync(path.join(reportDir("site-a", "draft-one"), "report.json"))); + + // Again: nothing left to move but with --drafts the draft. + const again = capture(); + assert.equal(await main(["--keep", "site-b/page-kept", "--drafts", "--apply"], paths, again.out), 0, again.text()); + assert.match(again.text(), /moved site-a\/draft-one → reports\/draft-one\/ \(draft\)/); + assert.deepEqual(readJson(path.join(paths.articlesDir, "index.json")), { published: ["alpha", "gamma"] }); +}); diff --git a/common/bin/move-reports-to-articles.ts b/common/bin/move-reports-to-articles.ts @@ -0,0 +1,225 @@ +// `archilyzer reports move-to-articles [--keep <site>/<id>,…] [--drafts] [--apply]` +// — release 26 A7, ONE-OFF: a site's published reports become ARTICLES +// (plans/reports-on-homepage.md, "A7 — move the data"). +// +// DRY RUN BY DEFAULT: it prints the plan and writes nothing. `--apply` does it. +// +// For every site (by id), every report its site.json lists, in the site's +// order — except each `--keep <site>/<id>` (a page the site keeps, D5): +// 1. its directory `sites/<site>/reports/<id>/` moves to `reports/<id>/` +// whole — report.json, stills, sources, video, history-git/ and +// notes.json with it (a rename; a copy then a removal across devices); +// 2. report.json gets `audience: "private"` (D2), through the article +// registry (lib/report/registry.ts patchArticle); +// 3. it is published in reports/index.json, after what is there, sites in +// id order, each site's reports in its order — through the registry +// (configureArticle), which publishes only a sound article: one with +// problems is moved as a DRAFT, and the plan says so; +// 4. the site's list (`pages`) drops it (patchSite). +// `--drafts` moves the sites' unlisted report directories too, as drafts. +// +// REFUSED BEFORE ANYTHING MOVES: an id two sites both use, an id that +// `reports/<id>/` already holds, a `--keep` that names no listed report, a +// site whose reports cannot be read. Nothing is half-done by a refusal. +// +// Not moved: the staging a site's prepare and export wrote +// (`.export-index/sites/<site>/report-{media,exports}/`) — run +// `archilyzer reports prepare --article <id>` for the articles afterwards. +// +// A SEARCH-OFF SITE LEFT WITH NO PAGES is retired: a save refuses a search-off +// site with none (siteSearchProblem, D5), so the patch that drops its last +// page turns its search on in the same write — it is saved as an empty site +// (no channels, no pages), which validates, builds nothing worth deploying and +// is never listed while private. The plan names it; delete it on /sites (or +// keep it) once the move is checked. Nothing about it is deleted here. +// +// Stop the editor's report jobs first (a prepare reads these directories). +// Exit 0 when the plan is clean (and applied, with --apply); 1 when it was +// refused; 2 for usage. + +import { cp, mkdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { getPaths, type Paths } from "../lib/paths"; +import { getSite, listSiteIds, patchSite, type Site } from "../lib/site"; +import { isCitedSite } from "../lib/siteSchema"; +import { readJsonFile } from "../lib/jsonFile-server"; +import { isReportId } from "../lib/report/schema"; +import { parseReport } from "../lib/report/validate"; +import { articleDir, configureArticle, patchArticle, readArticlesIndex } from "../lib/report/registry"; +import { listReportDirs, siteReportDir } from "../publish/reportMedia"; +import { parseArgv } from "./_parseFlags"; +import { runIfEntryPoint } from "./_cli"; + +export type MoveItem = { + site: string; + id: string; + // Listed by its site (published there), or a draft (--drafts). + listed: boolean; + from: string; + to: string; + // Whether it will be published in reports/index.json (a sound, listed report). + publish: boolean; + // Why it moves as a draft although its site listed it. + draftBecause?: string; +}; + +export type MovePlan = { + moves: MoveItem[]; + // Kept on their sites, as pages. + kept: string[]; + // Search-off sites left with no reports. + emptied: string[]; + refusals: string[]; +}; + +// THE PLAN — read only. +export async function planMove( + paths: Paths, + opts: { keep?: readonly string[]; drafts?: boolean } = {}, +): Promise<MovePlan> { + const keep = new Set(opts.keep ?? []); + const plan: MovePlan = { moves: [], kept: [], emptied: [], refusals: [] }; + try { + await readArticlesIndex(paths); + } catch (e) { + plan.refusals.push((e as Error).message); + return plan; + } + const seen = new Map<string, string>(); + const sites: Site[] = listSiteIds(paths).map((id) => getSite(id, paths)); + const known = new Set<string>(); + for (const site of sites) { + const listed = siteList(site); + for (const id of listed) known.add(`${site.siteId}/${id}`); + const drafts = opts.drafts ? (await listReportDirs(paths, site.siteId)).filter((d) => !listed.includes(d)) : []; + let left = 0; + for (const [id, isListed] of [...listed.map((id) => [id, true] as const), ...drafts.map((id) => [id, false] as const)]) { + const key = `${site.siteId}/${id}`; + if (keep.has(key)) { + plan.kept.push(key); + if (isListed) left++; + continue; + } + if (!isReportId(id)) { + plan.refusals.push(`${key}: "${id}" is not a report id`); + continue; + } + const from = siteReportDir(paths, site.siteId, id); + const to = articleDir(paths, id); + if (seen.has(id)) plan.refusals.push(`${key}: "${id}" is also ${seen.get(id)} — two articles cannot share an id`); + seen.set(id, key); + if (await exists(to)) plan.refusals.push(`${key}: reports/${id}/ already exists`); + const read = await readJsonFile(path.join(from, "report.json")); + if (!read.ok) { + plan.refusals.push(`${key}: its report.json is ${read.reason}`); + continue; + } + const parsed = parseReport(read.value, { id }); + if (!parsed.ok) { + plan.refusals.push(`${key}: its report.json does not parse as a report (archilyzer reports check)`); + continue; + } + const sound = parsed.problems.length === 0; + plan.moves.push({ + site: site.siteId, + id, + listed: isListed, + from, + to, + publish: isListed && sound, + ...(isListed && !sound ? { draftBecause: `${parsed.problems.length} problem(s) in report.json` } : {}), + }); + } + if (isCitedSite(site) && listed.length > 0 && left === 0) plan.emptied.push(site.siteId); + } + for (const k of keep) if (!known.has(k)) plan.refusals.push(`--keep ${k}: no site lists that report`); + return plan; +} + +// APPLY a clean plan: move, mark private, publish, drop from the site. +export async function applyMove(paths: Paths, plan: MovePlan, log: (line: string) => void = console.log): Promise<void> { + if (plan.refusals.length > 0) throw new Error("the plan has refusals; nothing is moved"); + for (const m of plan.moves) { + await moveDir(m.from, m.to); + await patchArticle(m.id, { audience: "private" }, paths); + if (m.publish) await configureArticle(m.id, { published: true }, paths); + if (m.listed) { + await patchSite( + m.site, + (cur) => { + const pages = siteList(cur).filter((x) => x !== m.id); + // Its last page gone, a search-off site is retired (see above). + return pages.length === 0 && isCitedSite(cur) ? { pages, search: true } : { pages }; + }, + paths, + ); + } + log(`moved ${m.site}/${m.id} → reports/${m.id}/${m.publish ? " (published)" : " (draft)"}`); + } +} + +export function formatPlan(plan: MovePlan): string[] { + const out: string[] = []; + for (const m of plan.moves) { + out.push( + `move ${m.site}/${m.id} → reports/${m.id}/ ${m.publish ? "published" : "draft"}${m.draftBecause ? ` (${m.draftBecause})` : ""}, audience private`, + ); + } + for (const k of plan.kept) out.push(`keep ${k} (a page of its site)`); + for (const s of plan.emptied) { + out.push(`retire ${s}: search off and no pages left — saved with search on, as an empty site; delete it on /sites`); + } + for (const r of plan.refusals) out.push(`REFUSED ${r}`); + out.push( + `${plan.moves.length} to move (${plan.moves.filter((m) => m.publish).length} published), ${plan.kept.length} kept, ${plan.refusals.length} refusal(s).`, + ); + return out; +} + +// A site's published list: site.json `pages` (a legacy `reports` reads as it). +function siteList(site: Site): string[] { + return site.pages ?? []; +} + +const exists = async (p: string) => !!(await stat(p).catch(() => null)); + +async function moveDir(from: string, to: string): Promise<void> { + await mkdir(path.dirname(to), { recursive: true }); + try { + await rename(from, to); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "EXDEV") throw e; + await cp(from, to, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true }); + await rm(from, { recursive: true, force: true }); + } +} + +const USAGE = "usage: archilyzer reports move-to-articles [--keep <site>/<id>,…] [--drafts] [--apply]"; + +export async function main( + argv: string[], + paths: Paths = getPaths(), + out: { log: (line: string) => void } = console, +): Promise<number> { + const { positionals, flags } = parseArgv(argv, ["drafts", "apply", "help"]); + if (flags.help || positionals.length > 0) { + out.log(USAGE); + return flags.help ? 0 : 2; + } + const keep = + typeof flags.keep === "string" + ? flags.keep.split(",").map((k) => k.trim()).filter(Boolean) + : []; + const plan = await planMove(paths, { keep, drafts: flags.drafts === true }); + for (const line of formatPlan(plan)) out.log(line); + if (plan.refusals.length > 0) return 1; + if (flags.apply !== true) { + out.log("dry run: nothing moved (--apply to move)."); + return 0; + } + await applyMove(paths, plan, (l) => out.log(l)); + out.log("done. Prepare and export the articles: archilyzer reports prepare --article <id>."); + return 0; +} + +runIfEntryPoint(import.meta.url, () => main(process.argv.slice(2))); diff --git a/common/bin/reports-article.test.ts b/common/bin/reports-article.test.ts @@ -0,0 +1,168 @@ +// `archilyzer reports prepare|export|check|verify-quotes|attach-video +// --article <id>` (release 26 A6): the same work as a site's, over the +// ARTICLES — transcripts/reports/<id>/, staged under .export-index/articles/, +// any channel of the corpus citable. A temp corpus only. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/reports-article.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +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(), "reports-article-")); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + 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"), +}); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { articleFile, configureArticle, readArticlesIndex } = await import("../lib/report/registry"); +const { checkMain, verifyQuotesMain } = await import("./reports-check"); +const { main: prepareMain } = await import("./reports-prepare"); +const { main: exportMain } = await import("./reports-export"); +const { attachVideoMain } = await import("./reports-attach-video"); +const { readRevisionHead } = await import("../publish/reportHistory"); + +const paths = getPaths(); +const CHAN = "lone"; +const STAGING = path.join(paths.exportIndexDir, "articles"); + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, 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 vtt = (cues: [number, number, string][]) => + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + cues.map(([a, b, text]) => `${ts(a)} --> ${ts(b)} align:start position:0%\n${text}<${ts(a)}><c></c>\n`).join("\n"); + +function capture() { + const lines: string[] = []; + return { text: () => lines.join("\n"), out: { log: (s: string) => lines.push(s), error: (s: string) => lines.push(s) } }; +} + +const QUOTE = "The bridge opened in the spring, I was there for it."; +function article(id: string, quote = QUOTE) { + return { + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + citations: { c1: { kind: "video", channel: CHAN, id: "abc1", start: 10, end: 20, quote } }, + sections: [{ id: "s", title: "S", body: "Said [this](cite:c1)." }], + }; +} + +writeJson(paths.settingsFile, {}); +// A channel no site has. +writeJson(path.join(paths.channelsDir, CHAN, "config.json"), { handling: "youtube", name: "Lone", url: "https://www.youtube.com/@lone/videos" }); +const rec = path.join(paths.channelsDir, CHAN, "data", "abc1"); +writeJson(path.join(rec, "metadata.info.json"), { + id: "abc1", + title: "Stream abc1", + channel: CHAN, + upload_date: "20260110", + duration: 600, + webpage_url: "https://www.youtube.com/watch?v=abc1", + extractor_key: "Youtube", +}); +writeFileSync(path.join(rec, "transcript.en.vtt"), vtt([[10, 20, QUOTE]])); +writeJson(articleFile(paths, "pub"), article("pub")); +writeJson(articleFile(paths, "draft"), article("draft", "Words the record never had at all.")); +await configureArticle("pub", { published: true }, paths); + +test("check --article: as the homepage's compose would — a channel no site has is citable; a draft is checked by name", async () => { + const ok = capture(); + assert.equal(await checkMain({ article: "pub", paths, allowMissingMedia: true }, ok.out), 0, ok.text()); + assert.match(ok.text(), /reports check --article pub: 1 report\(s\), 1 moment\(s\) — compose would pass/); + const media = capture(); + assert.equal(await checkMain({ article: "pub", paths }, media.out), 1); + assert.match(media.text(), /missing-media: lone\/abc1\/10\.00-20\.00: no prepared media/); + const draft = capture(); + assert.equal(await checkMain({ article: "draft", paths, allowMissingMedia: true }, draft.out), 1); + assert.match(draft.text(), /quote-drift: draft#c1/); + const none = capture(); + assert.equal(await checkMain({ article: "nope", paths }, none.out), 2); + assert.match(none.text(), /no article "nope"/); +}); + +test("prepare --article: the articles' cache, every published article plus the one named; a missing clip is listed", async () => { + const c = capture(); + assert.equal(await prepareMain({ article: "draft", exportOptions: { paths } }, c.out), 1, c.text()); + const index = readJson<{ siteId: string; problems: { kind: string; citations: string[] }[] }>( + path.join(STAGING, "report-media", "index.json"), + ); + assert.equal(index.siteId, "articles"); + assert.deepEqual( + index.problems.map((p) => [p.kind, p.citations]), + [["missing-media", ["pub#c1", "draft#c1"]]], + ); + assert.match(c.text(), /reports prepare --article draft: 1 problem\(s\)/); + assert.equal(existsSync(path.join(paths.exportIndexDir, "sites")), false, "no site's staging touched"); +}); + +test("export --article: one article's files under .export-index/articles/, its history in reports/<id>/history-git", async () => { + const c = capture(); + assert.equal( + await exportMain({ article: "pub", paths, formats: ["html", "md"], allowMissingMedia: true }, c.out), + 0, + c.text(), + ); + const dir = path.join(STAGING, "report-exports", "pub"); + assert.ok(existsSync(path.join(dir, "report.html"))); + assert.ok(existsSync(path.join(dir, "report.md"))); + const manifest = readJson<{ siteId: string; revision?: { revision: number } }>(path.join(dir, "export.json")); + assert.equal(manifest.siteId, "articles"); + assert.equal(manifest.revision?.revision, 1); + const head = await readRevisionHead(path.join(path.dirname(articleFile(paths, "pub")), "history-git")); + assert.equal(head?.revision, 1); + const author = execFileSync("git", ["--git-dir", path.join(path.dirname(articleFile(paths, "pub")), "history-git"), "log", "-1", "--format=%an <%ae>"], { encoding: "utf8" }).trim(); + assert.equal(author, "Archilyzer <noreply@articles.invalid>"); + // An article that is not there. + const none = capture(); + assert.equal(await exportMain({ article: "nope", paths }, none.out), 2); +}); + +test("verify-quotes takes an article's file", async () => { + const c = capture(); + assert.equal(await verifyQuotesMain({ file: articleFile(paths, "pub"), paths }, c.out), 0, c.text()); +}); + +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +test("attach-video --article: `video` written through the registry, the audience kept", { skip: !hasFfmpeg && "no ffmpeg" }, async () => { + await configureArticle("pub", { audience: "public" }, paths); + const src = path.join(ROOT, "clip.mp4"); + execFileSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", "testsrc=size=640x360:rate=25", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", + "-t", "2", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", src, + ]); + const c = capture(); + assert.equal(await attachVideoMain({ article: "pub", video: src, caption: "Cut." }, c.out), 0, c.text()); + const doc = readJson<{ video: unknown; audience: string }>(articleFile(paths, "pub")); + assert.deepEqual(doc.video, { src: "video.mp4", poster: "poster.jpg", caption: "Cut." }); + assert.equal(doc.audience, "public"); + assert.match(c.text(), /reports attach-video: article pub video =/); + assert.deepEqual((await readArticlesIndex(paths)).published, ["pub"]); + const none = capture(); + assert.equal(await attachVideoMain({ article: "nope", video: src }, none.out), 1); +}); diff --git a/common/bin/reports-attach-video.ts b/common/bin/reports-attach-video.ts @@ -3,17 +3,24 @@ // the publish limit, written beside report.json as video.mp4 with a poster, // and `video` set in report.json (publish/reportVideo.ts). // +// `--article <id>` in place of <report.json> attaches to an ARTICLE +// (transcripts/reports/<id>/, release 26), its `video` written through the +// article registry (patchArticle: locked, and refused if it adds a problem). +// // Exit 0 when attached, 1 when it could not be (the reason printed: too long // to fit, not a report, ffmpeg's error), 2 for usage. import { getPaths } from "../lib/paths"; +import { articleFile, patchArticle } from "../lib/report/registry"; import { AttachVideoError, attachReportVideo } from "../publish/reportVideo"; type Out = { log: (s: string) => void; error: (s: string) => void }; export async function attachVideoMain( opts: { - reportFile: string; + // report.json, or `article` — an article id. + reportFile?: string; + article?: string; video: string; poster?: string; caption?: string; @@ -24,9 +31,22 @@ export async function attachVideoMain( out: Out = console, ): Promise<number> { const paths = getPaths(); + const article = opts.article; + const reportFile = article ? articleFile(paths, article) : opts.reportFile; + if (!reportFile) { + out.error("reports attach-video: give <report.json> or --article <id>"); + return 2; + } try { const done = await attachReportVideo({ - reportFile: opts.reportFile, + reportFile, + ...(article + ? { + setVideo: async (video) => { + if (!(await patchArticle(article, { video }, paths))) throw new AttachVideoError(`no article "${article}"`); + }, + } + : {}), video: opts.video, ...(opts.poster !== undefined ? { poster: opts.poster } : {}), ...(opts.caption !== undefined ? { caption: opts.caption } : {}), @@ -36,7 +56,7 @@ export async function attachVideoMain( onLog: out.log, }); out.log( - `reports attach-video: ${opts.reportFile} video = ${JSON.stringify(done.video)} ` + + `reports attach-video: ${article ? `article ${article}` : reportFile} video = ${JSON.stringify(done.video)} ` + `(${done.mode === "remux" ? "remuxed" : `encoded, ${done.attempts} pass(es)`}, ${(done.bytes / (1024 * 1024)).toFixed(2)} MiB)`, ); return 0; diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -19,6 +19,10 @@ // `en-orig` is not what the speaker said, and is reported as such, even // though compose (which takes the best track) would pass it. // +// `--article <id>` checks one ARTICLE (release 26: transcripts/reports/<id>/, +// published or a draft) as the homepage's compose would — any channel of the +// corpus citable, the articles' prepared media. +// // Exit 0 when there is nothing to report, 1 with the list, 2 for usage (an // unknown site, an unreadable file). @@ -39,8 +43,9 @@ import { formatComposeReportsProblems, quoteDriftMessage, readCitedRecord, - resolveSiteReports, + resolveReports, } from "../publish/composeReports"; +import { articlesWorkHost, siteReportHost, type ReportHost } from "../publish/reportHost"; type Out = { log: (s: string) => void; error: (s: string) => void }; @@ -48,7 +53,9 @@ type Out = { log: (s: string) => void; error: (s: string) => void }; export async function checkMain( opts: { - siteId: string; + // The site, or `article` — one article id. + siteId?: string; + article?: string; reports?: string[]; allowMissingMedia?: boolean; paths?: Paths; @@ -57,20 +64,32 @@ export async function checkMain( out: Out = console, ): Promise<number> { const paths = opts.paths ?? getPaths(); - if (!listSiteIds(paths).includes(opts.siteId)) { - out.error(`reports check: no site "${opts.siteId}" (sites/${opts.siteId}/site.json)`); - return 2; + const who = opts.article ? `--article ${opts.article}` : String(opts.siteId); + let host: ReportHost; + if (opts.article) { + try { + host = await articlesWorkHost(paths, [opts.article]); + } catch (err) { + out.error(`reports check: ${(err as Error).message}`); + return 2; + } + host = { ...host, published: [opts.article] }; + } else { + if (!opts.siteId || !listSiteIds(paths).includes(opts.siteId)) { + out.error(`reports check: no site "${opts.siteId}" (sites/${opts.siteId}/site.json)`); + return 2; + } + const site = getSite(opts.siteId, paths); + host = siteReportHost(paths, { ...site, pages: opts.reports ?? site.pages ?? [] }); } - const site = getSite(opts.siteId, paths); - const ids = opts.reports ?? site.pages ?? []; - if (ids.length === 0) { - out.log(`reports check ${opts.siteId}: the site publishes no reports — nothing to check.`); + if (host.published.length === 0) { + out.log(`reports check ${who}: the site publishes no reports — nothing to check.`); return 0; } try { - const resolved = await resolveSiteReports({ + const resolved = await resolveReports({ paths, - site: { ...site, pages: ids }, + host, allowMissingMedia: opts.allowMissingMedia === true, ...(opts.settings ? { settings: opts.settings } : {}), }); @@ -87,15 +106,15 @@ export async function checkMain( ); } out.log( - `reports check ${opts.siteId}: ${resolved.reports.length} report(s), ${resolved.moments.length} moment(s) — compose would pass.`, + `reports check ${who}: ${resolved.reports.length} report(s), ${resolved.moments.length} moment(s) — compose would pass.`, ); return 0; } catch (err) { if (!(err instanceof ComposeReportsError)) { - out.error(`reports check ${opts.siteId}: ${(err as Error).message}`); + out.error(`reports check ${who}: ${(err as Error).message}`); return 1; } - out.error(`reports check ${opts.siteId}: ${err.problems.length} problem(s) — compose would fail:`); + out.error(`reports check ${who}: ${err.problems.length} problem(s) — compose would fail:`); for (const line of formatComposeReportsProblems(err.problems)) out.error(` ${line}`); return 1; } diff --git a/common/bin/reports-export.ts b/common/bin/reports-export.ts @@ -8,7 +8,12 @@ // Exit 0 when every asked-for export was written (a PDF skipped for want of a // browser is a note, not a problem); 1 when any problem is listed; 2 for bad // arguments or a site or report that does not exist. +// +// `--article <id>` exports one ARTICLE (release 26) into +// `.export-index/articles/report-exports/<id>/`, published or a draft. +import { getPaths } from "../lib/paths"; +import { articlesWorkHost } from "../publish/reportHost"; import { exportSiteReports, formatReportExportProblems, @@ -18,12 +23,19 @@ import { type Out = { log: (s: string) => void; error: (s: string) => void }; export async function main( - opts: Omit<ExportSiteReportsOptions, "onLog">, + opts: Omit<ExportSiteReportsOptions, "onLog"> & { article?: string }, out: Out = console, ): Promise<number> { + const { article, ...rest } = opts; + const who = article ? `--article ${article}` : opts.siteId; let result; try { - result = await exportSiteReports({ ...opts, onLog: out.log }); + const host = article ? await articlesWorkHost(opts.paths ?? getPaths(), [article]) : undefined; + result = await exportSiteReports({ + ...rest, + ...(host ? { host, reportId: article } : {}), + onLog: out.log, + }); } catch (err) { out.error(`reports export: ${(err as Error).message}`); return opts.signal?.aborted ? 1 : 2; @@ -32,7 +44,7 @@ export async function main( for (const note of r.manifest.notes) out.log(` note: ${r.reportId}: ${note}`); } if (result.problems.length === 0) return 0; - out.error(`reports export ${opts.siteId}: ${result.problems.length} problem(s):`); + out.error(`reports export ${who}: ${result.problems.length} problem(s):`); for (const line of formatReportExportProblems(result.problems)) out.error(` ${line}`); return 1; } diff --git a/common/bin/reports-prepare.ts b/common/bin/reports-prepare.ts @@ -1,6 +1,8 @@ // `archilyzer reports prepare <siteId>` — cut and copy the evidence media of a // site's published reports into `.export-index/sites/<siteId>/report-media/`, -// before the site's build. The work is publish/reportMedia.ts's, the same the +// before the site's build. `--article <id>` does the same for the ARTICLES +// (release 26): every published article plus that one (a draft may be +// readied before it is published), into `.export-index/articles/report-media/`. The work is publish/reportMedia.ts's, the same the // editor's `reports-prepare` job runs; this file prints its log and its // problems. // @@ -11,42 +13,59 @@ // 1 when any problem is listed (the manifest is written either way, problems // included); 2 for a site that does not exist. +import { getPaths } from "../lib/paths"; import { formatReportMediaProblems, prepareReportMedia } from "../publish/reportMedia"; import { exportAfterPrepare, formatReportExportProblems, type ExportSiteReportsOptions } from "../publish/reportExports"; +import { articlesWorkHost, type ReportHost } from "../publish/reportHost"; type Out = { log: (s: string) => void; error: (s: string) => void }; export async function main( opts: { - siteId: string; + // The site, or `article` — one article id: the articles' run. + siteId?: string; + article?: string; signal?: AbortSignal; // Passed to the export at the end (tests inject the PDF printer and zip). exportOptions?: Partial<Pick<ExportSiteReportsOptions, "openPdfPrinter" | "zipBin" | "paths" | "settings">>; }, out: Out = console, ): Promise<number> { + const who = opts.article ? `--article ${opts.article}` : opts.siteId; let index; + let host: ReportHost | undefined; try { - index = await prepareReportMedia({ siteId: opts.siteId, signal: opts.signal, onLog: out.log }); + host = opts.article ? await articlesWorkHost(opts.exportOptions?.paths ?? getPaths(), [opts.article]) : undefined; + index = await prepareReportMedia({ + ...(host ? { host } : { siteId: opts.siteId }), + ...(opts.exportOptions?.paths ? { paths: opts.exportOptions.paths } : {}), + signal: opts.signal, + onLog: out.log, + }); } catch (err) { out.error(`reports prepare: ${(err as Error).message}`); return opts.signal?.aborted ? 1 : 2; } if (index.problems.length > 0) { - out.error(`reports prepare ${opts.siteId}: ${index.problems.length} problem(s):`); + out.error(`reports prepare ${who}: ${index.problems.length} problem(s):`); for (const line of formatReportMediaProblems(index.problems)) out.error(` ${line}`); out.error("reports prepare: the reports were not exported (the evidence media is not complete)."); return 1; } let exported; try { - exported = await exportAfterPrepare(index, { siteId: opts.siteId, signal: opts.signal, onLog: out.log, ...opts.exportOptions }); + exported = await exportAfterPrepare(index, { + ...(host ? { host } : { siteId: opts.siteId }), + signal: opts.signal, + onLog: out.log, + ...opts.exportOptions, + }); } catch (err) { out.error(`reports prepare: export: ${(err as Error).message}`); return 1; } if (!exported || exported.problems.length === 0) return 0; - out.error(`reports prepare ${opts.siteId}: export: ${exported.problems.length} problem(s):`); + out.error(`reports prepare ${who}: export: ${exported.problems.length} problem(s):`); for (const line of formatReportExportProblems(exported.problems)) out.error(` ${line}`); return 1; } diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -56,6 +56,7 @@ const DECLARED: EnvVarDecl[] = [ paths("TRANSCRIPTS_DIR", "`<repo>/transcripts`", "The corpus: channels, sites, the LMDB index, job logs, the saved-video store. umtool reads `<it>/channels` too, when its own `CHANNELS_DIR` is unset."), paths("SAVED_VIDEOS_DIR", "`<TRANSCRIPTS_DIR>/saved-videos`", "The persisted source-video store, when it should live on another disk."), paths("SITES_DIR", "`<TRANSCRIPTS_DIR>/sites`", "Per-site config (`<id>/site.json`, every key in [SITE.md](SITE.md)) and the homepage's `_homepage/`."), + paths("ARTICLES_DIR", "`<TRANSCRIPTS_DIR>/reports`", "The article store: one directory per article (`<id>/report.json`, [REPORT.md](REPORT.md)) and `index.json`, the published list. umtool reads it too."), paths("SETTINGS_FILE", "`<repo>/settings.json`", "The settings file (every key in [SETTINGS.md](SETTINGS.md))."), paths("EXPORT_PUBLIC_DIR", "`<repo>/export/public`", "The dir the export site serves at `/`, composed one site at a time."), paths("EXPORT_INDEX_DIR", "`.export-index` beside `EXPORT_PUBLIC_DIR`", "The build's staging area (not served): the shared index and per-site aggregates."), diff --git a/common/lib/paths.ts b/common/lib/paths.ts @@ -26,6 +26,12 @@ export type Paths = { // intentionally not a valid siteId (SITE_ID_RE), so listSiteIds() ignores it. // See common/lib/homepage.ts. homepageDir: string; + // The ARTICLE STORE (release 26): transcripts/reports/<id>/ — one directory + // per article (report.json and its siblings, as a site report's directory), + // and index.json, the published, ordered list. Written only through + // common/lib/report/registry.ts. The homepage publishes it; a site's own + // pages stay under sitesDir/<siteId>/reports/. + articlesDir: string; homepageConfigFile: string; homepageChartTemplatesFile: string; jobsDir: string; @@ -236,6 +242,7 @@ export function getPaths(): Paths { process.env.SAVED_VIDEOS_DIR ?? under(transcriptsDir, "saved-videos"), sitesDir, homepageDir, + articlesDir: process.env.ARTICLES_DIR ?? under(transcriptsDir, "reports"), homepageConfigFile: under(homepageDir, "homepage.json"), homepageChartTemplatesFile: under(homepageDir, "chart-templates.json"), jobsDir: under(transcriptsDir, ".jobs"), diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts @@ -33,16 +33,40 @@ export function renderReportMarkdown(): string { out.push(""); out.push( `One cited report, format \`"${REPORT_FORMAT}"\`, version ${REPORT_VERSION}, ` + - "persisted to `transcripts/sites/<siteId>/reports/<reportId>/report.json` beside " + - "its `stills/` and `sources/<sourceId>/`; a relative path in it is relative to " + - "that directory. A site's `pages` list in `site.json` is the published, " + - "ordered list, each served at `/pages/<id>/` — see [SITE.md](SITE.md); a report " + - "directory it does not name is a draft. The schema is `common/lib/report/schema.ts`; its citations and sources " + - "are the citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` " + - "beside it holds the operator's notes on the article (umtool, `umtool notes`; " + + "persisted as `report.json` in its own directory, beside its `stills/` and " + + "`sources/<sourceId>/`; a relative path in it is relative to that directory. " + + "The schema is `common/lib/report/schema.ts`; its citations and sources are the " + + "citation model's — see [CITATIONS.md](CITATIONS.md). A `notes.json` beside it " + + "holds the operator's notes on the article (umtool, `umtool notes`; " + "[umtool/docs/notes.md](umtool/docs/notes.md)) and is never published.", ); out.push(""); + out.push("A report lives in one of two stores:"); + out.push(""); + out.push( + "- **An article** — `transcripts/reports/<reportId>/report.json`, published by the " + + "project homepage. `transcripts/reports/index.json` — `{\"published\": [ids]}` — is " + + "the published, ordered list; an article directory it does not name is a draft. " + + "An article's `audience` (below) says which homepage build carries it: the public " + + "one only `\"public\"` articles, the private one every published article. An " + + "article may cite any channel of the corpus.", + ); + out.push( + "- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, " + + "published by its site at `/pages/<reportId>/`: the site's `pages` list in `site.json` " + + "is the published, ordered list — see [SITE.md](SITE.md). A page cites the site's " + + "`channels` and `citedChannels`.", + ); + out.push(""); + out.push( + "`index.json` and an article's `audience` are written ONLY through " + + "`common/lib/report/registry.ts` (`configureArticle`, `setPublished`, " + + "`setArticlesOrder`, `patchArticle`, `writeArticle`: locked, validated, atomic) and " + + "`pnpm ops articles-config` (`{\"id\", \"audience\"?, \"published\"?, " + + "\"position\"?}`), never by hand. Only a sound article (no problem below) is " + + "published; a patch may not add a problem to an article.", + ); + out.push(""); out.push( 'A **fact-check** (`"kind": "factcheck"`) is sections (chapters) of claims, each ' + 'with a verdict and its findings. A **sweep** (`"kind": "sweep"`) is sections ' + diff --git a/common/lib/report/exportHtml.ts b/common/lib/report/exportHtml.ts @@ -52,6 +52,7 @@ import { type SourceView, type SpanCitationView, } from "./views"; +import type { ReportBase } from "./routes"; // ─── The footer: which document this is ─── @@ -94,6 +95,9 @@ export type ReportExportOptions = { // The site's public URL (site.json `siteUrl`). Absent: no link to the site, // its moment pages or its clips (a private site has nowhere to link). siteUrl?: string; + // Where the build serves its reports (./routes.ts): the report's own page + // under `siteUrl`. A site's by default. + base?: ReportBase; footer: ReportExportFooter; }; @@ -606,7 +610,7 @@ export function reportExportHtml(view: ReportPageView, opts: ReportExportHtmlOpt const tally = isFactcheck ? verdictTally(view) : []; const groups = isFactcheck ? foundGroups(view) : []; const claimCount = view.sections.reduce((n, s) => n + s.claims.length, 0); - const pageUrl = siteLink(opts.siteUrl, reportPagePath(view.id)); + const pageUrl = siteLink(opts.siteUrl, reportPagePath(view.id, opts.base)); const ctx: ClaimContext = { view, subjectNoun, cite, opts }; // The heading, in the site's order: the series on one line and the title diff --git a/common/lib/report/exportMarkdown.ts b/common/lib/report/exportMarkdown.ts @@ -172,7 +172,7 @@ export function reportExportMarkdown(view: ReportPageView, opts: ReportExportOpt const out: string[] = []; const subject = view.subject ? view.sources[view.subject] : undefined; const subjectNoun = subject?.kind === "article" ? "article" : "source"; - const pageUrl = siteLink(opts.siteUrl, reportPagePath(view.id)); + const pageUrl = siteLink(opts.siteUrl, reportPagePath(view.id, opts.base)); const isFactcheck = view.kind === "factcheck"; // The series on its own line and the title as the heading (or the title diff --git a/common/lib/report/exportSlidesHtml.ts b/common/lib/report/exportSlidesHtml.ts @@ -45,6 +45,7 @@ import { type CitationView, type ReportPageView, } from "./views"; +import type { ReportBase } from "./routes"; export type ReportSlidesHtmlOptions = { // common/styles/slides.css, whole. @@ -52,6 +53,8 @@ export type ReportSlidesHtmlOptions = { // The site's accent on the light base (lib/accent.ts resolveAccent().light). accent: string; siteUrl?: string; + // Where the build serves its reports (./routes.ts); a site's by default. + base?: ReportBase; footer: ReportExportFooter; // A site-root image path → the <img src>, or undefined to leave it out. image: (sitePath: string) => string | undefined; @@ -271,7 +274,7 @@ function claimBody(s: ClaimSlide, x: Ctx): string { } function sourcesBody(s: SourcesSlide, x: Ctx): string { - const pageUrl = siteLink(x.opts.siteUrl, reportPagePath(x.view.id)); + const pageUrl = siteLink(x.opts.siteUrl, reportPagePath(x.view.id, x.opts.base)); return ( `<h2 class="rs-h">${escapeHtml(s.title)}</h2><div class="rs-figures">` + `<div class="rs-figure"><b>${s.references}</b><span>${s.references === 1 ? "reference" : "references"}</span></div>` + @@ -347,7 +350,7 @@ function slideHtml(s: SlideView, x: Ctx): string { break; } const mark = s.kind === "claim" && s.verdict ? verdictStyleOf(x.view, s.verdict).color : undefined; - const article = siteLink(x.opts.siteUrl, `${reportPagePath(x.view.id)}#${s.anchorId}`); + const article = siteLink(x.opts.siteUrl, `${reportPagePath(x.view.id, x.opts.base)}#${s.anchorId}`); return ( `<article class="rs-slide" data-slide="${escapeHtml(s.key)}" data-slide-kind="${s.kind}" data-layout="${s.layout}" data-fit="canvas"${style({ "--rs-mark": mark })}>` + `<span class="rs-band" aria-hidden="true"></span>${eyebrow(s, x.total)}<div class="rs-main">${body}</div>` + diff --git a/common/lib/report/feeds.ts b/common/lib/report/feeds.ts @@ -18,6 +18,7 @@ import { citationAnchor } from "../citations/inline"; import { reportDateMs } from "./entries"; import { markdownToHtml, siteLink } from "./exportHtml"; +import { SITE_REPORTS_BASE, type ReportBase } from "./routes"; import { REPORT_FEED_FORMATS, reportFeedPath, @@ -33,12 +34,14 @@ export const JSON_FEED_VERSION = "https://jsonfeed.org/version/1.1"; export type ReportFeedOptions = { // The site's public URL: absolute http(s) (lib/siteSchema.ts parseSiteUrl). siteUrl: string; + // Where the build serves its reports (./routes.ts); a site's by default. + base?: ReportBase; }; // A report's feed URLs on the site. -export function reportFeedUrls(siteUrl: string, reportId: string): ReportFeeds { +export function reportFeedUrls(siteUrl: string, reportId: string, base: ReportBase = SITE_REPORTS_BASE): ReportFeeds { return Object.fromEntries( - REPORT_FEED_FORMATS.map((f) => [f, siteLink(siteUrl, reportFeedPath(reportId, f))!]), + REPORT_FEED_FORMATS.map((f) => [f, siteLink(siteUrl, reportFeedPath(reportId, f, base))!]), ) as ReportFeeds; } @@ -79,21 +82,31 @@ export function rfc3339Date(v: string | undefined): string | undefined { } // The report's page on the site. -function pageUrlOf(view: Pick<ReportPageView, "id">, siteUrl: string): string { - return siteLink(siteUrl, reportPagePath(view.id))!; +function pageUrlOf(view: Pick<ReportPageView, "id">, siteUrl: string, base: ReportBase = SITE_REPORTS_BASE): string { + return siteLink(siteUrl, reportPagePath(view.id, base))!; } // An entry's permalink: the page at its anchor (a reference id is safe in a // fragment as it is). -export function entryUrl(view: Pick<ReportPageView, "id">, entry: Pick<EntryView, "id">, siteUrl: string): string { - return `${pageUrlOf(view, siteUrl)}#${entry.id}`; +export function entryUrl( + view: Pick<ReportPageView, "id">, + entry: Pick<EntryView, "id">, + siteUrl: string, + base: ReportBase = SITE_REPORTS_BASE, +): string { + return `${pageUrlOf(view, siteUrl, base)}#${entry.id}`; } // An entry's body as HTML for a feed reader: citation markers link to their // references on the report's page; a fragment link goes to the page; a // site-root link to the site. -export function entryContentHtml(view: Pick<ReportPageView, "id" | "citations">, entry: EntryView, siteUrl: string): string { - const page = pageUrlOf(view, siteUrl); +export function entryContentHtml( + view: Pick<ReportPageView, "id" | "citations">, + entry: EntryView, + siteUrl: string, + base: ReportBase = SITE_REPORTS_BASE, +): string { + const page = pageUrlOf(view, siteUrl, base); return markdownToHtml( entry.body, (id) => { @@ -120,8 +133,8 @@ function feedDate(view: ReportPageView): string | undefined { // RSS 2.0 (with an Atom self link, as validators ask). export function renderReportRss(view: ReportPageView, opts: ReportFeedOptions): string { - const page = pageUrlOf(view, opts.siteUrl); - const self = reportFeedUrls(opts.siteUrl, view.id).rss; + const page = pageUrlOf(view, opts.siteUrl, opts.base); + const self = reportFeedUrls(opts.siteUrl, view.id, opts.base).rss; const built = rfc822Date(feedDate(view)); const out: string[] = [ `<?xml version="1.0" encoding="UTF-8"?>`, @@ -135,7 +148,7 @@ export function renderReportRss(view: ReportPageView, opts: ReportFeedOptions): `<generator>Archilyzer</generator>`, ]; for (const e of view.entries ?? []) { - const url = entryUrl(view, e, opts.siteUrl); + const url = entryUrl(view, e, opts.siteUrl, opts.base); const pub = rfc822Date(e.date); out.push( `<item>`, @@ -143,7 +156,7 @@ export function renderReportRss(view: ReportPageView, opts: ReportFeedOptions): `<link>${escapeXml(url)}</link>`, `<guid isPermaLink="true">${escapeXml(url)}</guid>`, ...(pub ? [`<pubDate>${pub}</pubDate>`] : []), - `<description>${escapeXml(entryContentHtml(view, e, opts.siteUrl))}</description>`, + `<description>${escapeXml(entryContentHtml(view, e, opts.siteUrl, opts.base))}</description>`, `</item>`, ); } @@ -174,18 +187,18 @@ export function renderReportJsonFeed(view: ReportPageView, opts: ReportFeedOptio return { version: JSON_FEED_VERSION, title: reportFullTitle(view), - home_page_url: pageUrlOf(view, opts.siteUrl), - feed_url: reportFeedUrls(opts.siteUrl, view.id).json, + home_page_url: pageUrlOf(view, opts.siteUrl, opts.base), + feed_url: reportFeedUrls(opts.siteUrl, view.id, opts.base).json, description: feedDescription(view), items: (view.entries ?? []).map((e) => { - const url = entryUrl(view, e, opts.siteUrl); + const url = entryUrl(view, e, opts.siteUrl, opts.base); const published = rfc3339Date(e.date); const modified = rfc3339Date(e.updated); return { id: url, url, title: e.title, - content_html: entryContentHtml(view, e, opts.siteUrl), + content_html: entryContentHtml(view, e, opts.siteUrl, opts.base), ...(published ? { date_published: published } : {}), ...(modified ? { date_modified: modified } : {}), }; diff --git a/common/lib/report/registry.test.ts b/common/lib/report/registry.test.ts @@ -0,0 +1,236 @@ +// The article registry (release 26 A2): the one writer of +// transcripts/reports/index.json and an article's `audience`. Temp stores only. +// +// Run with: node_modules/.bin/tsx --test lib/report/registry.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import os from "node:os"; +import path from "node:path"; +import { + ARTICLES_LOCK_FILENAME, + ArticleRegistryError, + articleFile, + articlesIndexFile, + configureArticle, + listArticles, + patchArticle, + publishedArticleIds, + readArticleState, + readArticlesIndex, + setArticlesOrder, + setPublished, + writeArticle, +} from "./registry"; + +const ROOTS: string[] = []; +after(() => { + for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); +}); + +function store() { + const root = mkdtempSync(path.join(tmpdir(), "article-registry-")); + ROOTS.push(root); + return { articlesDir: path.join(root, "transcripts", "reports"), exportIndexDir: path.join(root, ".export-index") }; +} + +const doc = (id: string, over: Record<string, unknown> = {}) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "One", body: "Plain words." }], + ...over, +}); + +function put(paths: ReturnType<typeof store>, id: string, value: unknown) { + const file = articleFile(paths, id); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2)); +} + +const read = (file: string) => (existsSync(file) ? readFileSync(file, "utf8") : null); +const json = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>; + +test("an empty store: nothing published, nothing listed", async () => { + const paths = store(); + assert.deepEqual(await readArticlesIndex(paths), { published: [] }); + assert.deepEqual(await listArticles(paths), []); + assert.deepEqual(await publishedArticleIds("private", paths), []); + assert.equal(await readArticleState("nothing", paths), null); +}); + +test("publish, place, move and unpublish — index.json in order; drafts listed after", async () => { + const paths = store(); + for (const id of ["a", "b", "c", "d"]) put(paths, id, doc(id)); + await setPublished("a", true, {}, paths); + await setPublished("b", true, {}, paths); + assert.deepEqual(json(articlesIndexFile(paths)), { published: ["a", "b"] }); + await configureArticle("c", { published: true, position: 0 }, paths); + assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "a", "b"]); + // Moved: a published article's position alone. + const moved = await configureArticle("b", { position: 1 }, paths); + assert.equal(moved.position, 1); + assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "b", "a"]); + // Publishing an already-published one with no position keeps its place. + await setPublished("b", true, {}, paths); + assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "b", "a"]); + await setPublished("c", false, {}, paths); + assert.deepEqual((await readArticlesIndex(paths)).published, ["b", "a"]); + assert.ok(existsSync(articleFile(paths, "c")), "unpublishing keeps the article on disk"); + + const listed = await listArticles(paths); + assert.deepEqual( + listed.map((a) => [a.id, a.published, a.position]), + [ + ["b", true, 0], + ["a", true, 1], + ["c", false, null], + ["d", false, null], + ], + ); + assert.equal(listed[0].title, "Article b"); + assert.equal(listed[0].audience, "private", "absent = private"); + await setArticlesOrder(["a", "b"], paths); + assert.deepEqual((await readArticlesIndex(paths)).published, ["a", "b"]); +}); + +test("audience: written into report.json, absent = private; a public build carries only public articles", async () => { + const paths = store(); + for (const id of ["pub", "priv", "draft"]) put(paths, id, doc(id)); + await configureArticle("pub", { audience: "public", published: true }, paths); + await configureArticle("priv", { published: true }, paths); + await configureArticle("draft", { audience: "public" }, paths); + assert.equal(json(articleFile(paths, "pub")).audience, "public"); + assert.equal("audience" in json(articleFile(paths, "priv")), false, "no audience written unasked"); + assert.deepEqual(await publishedArticleIds("public", paths), ["pub"]); + assert.deepEqual(await publishedArticleIds("private", paths), ["pub", "priv"]); + // Back to private. + const st = await configureArticle("pub", { audience: "private" }, paths); + assert.equal(st.audience, "private"); + assert.deepEqual(await publishedArticleIds("public", paths), []); + // Unchanged audience: report.json's bytes are not rewritten. + const before = read(articleFile(paths, "priv")); + await configureArticle("priv", { audience: "private" }, paths); + assert.equal(read(articleFile(paths, "priv")), before); +}); + +test("refusals come before anything is written", async () => { + const paths = store(); + put(paths, "ok", doc("ok")); + put(paths, "bad", doc("bad", { sections: [{ id: "s1", title: "x", body: "[a](cite:nope)" }] })); + put(paths, "torn", "{ not json"); + await setPublished("ok", true, {}, paths); + const indexBefore = read(articlesIndexFile(paths)); + const okBefore = read(articleFile(paths, "ok")); + const cases: [() => Promise<unknown>, RegExp][] = [ + [() => configureArticle("Bad Id", { published: true }, paths), /not an article id/], + [() => configureArticle("missing", { published: true }, paths), /no article "missing"/], + [() => configureArticle("ok", { audience: "everyone" as never }, paths), /audience must be one of public, private/], + [() => configureArticle("bad", { published: true }, paths), /cannot be published while report.json has problems[\s\S]*cite:nope|cannot be published/], + [() => configureArticle("torn", { published: true }, paths), /unparseable/], + [() => configureArticle("bad", { position: 0 }, paths), /is a draft/], + [() => configureArticle("ok", { published: false, position: 0 }, paths), /not one being unpublished/], + [() => configureArticle("ok", { position: 5 }, paths), /position 5 is out of range: 0 \(first\) to 0/], + [() => configureArticle("ok", { audience: "public", position: -1 }, paths), /out of range/], + [() => setArticlesOrder(["ok", "ok"], paths), /every published article once/], + [() => setArticlesOrder(["bad"], paths), /every published article once/], + ]; + for (const [call, re] of cases) { + await assert.rejects(call, (e: unknown) => e instanceof ArticleRegistryError && re.test((e as Error).message), String(re)); + } + assert.equal(read(articlesIndexFile(paths)), indexBefore, "index.json untouched"); + assert.equal(read(articleFile(paths, "ok")), okBefore, "report.json untouched (audience + bad position refused whole)"); +}); + +test("an unreadable index.json is an error, never an empty list", async () => { + const paths = store(); + put(paths, "a", doc("a")); + mkdirSync(path.dirname(articlesIndexFile(paths)), { recursive: true }); + for (const bad of ['{"published": "a"}', '{"published": ["a", "a"]}', '{"published": [], "extra": 1}', "[]", "{"]) { + writeFileSync(articlesIndexFile(paths), bad); + await assert.rejects(readArticlesIndex(paths), ArticleRegistryError, bad); + await assert.rejects(setPublished("a", true, {}, paths), ArticleRegistryError, bad); + assert.equal(read(articlesIndexFile(paths)), bad, "not overwritten"); + } +}); + +test("unpublishing an article whose directory is gone tidies the index", async () => { + const paths = store(); + put(paths, "a", doc("a")); + await setPublished("a", true, {}, paths); + rmSync(path.dirname(articleFile(paths, "a")), { recursive: true }); + const listed = await listArticles(paths); + assert.deepEqual(listed.map((a) => [a.id, a.exists]), [["a", false]]); + await setPublished("a", false, {}, paths); + assert.deepEqual(await readArticlesIndex(paths), { published: [] }); +}); + +test("patchArticle: patched as on disk, a key given as undefined removed, never made worse", async () => { + const paths = store(); + put(paths, "a", doc("a", { subtitle: "old" })); + const r = await patchArticle("a", { title: "New title", subtitle: undefined }, paths); + assert.equal(r?.title, "New title"); + const onDisk = json(articleFile(paths, "a")); + assert.equal(onDisk.title, "New title"); + assert.equal("subtitle" in onDisk, false); + const fn = await patchArticle("a", (cur) => ({ title: `${cur.title}!` }), paths); + assert.equal(fn?.title, "New title!"); + assert.equal(await patchArticle("missing", { title: "x" }, paths), null); + const before = read(articleFile(paths, "a")); + await assert.rejects(patchArticle("a", { kind: "essay" as never }, paths), /would make report.json invalid/); + await assert.rejects( + patchArticle("a", { summary: "see [x](cite:nobody)" }, paths), + /would make report.json invalid[\s\S]*summary/, + ); + await assert.rejects(patchArticle("a", { id: "b" } as never, paths), /may not change "id"/); + assert.equal(read(articleFile(paths, "a")), before); + // A report that already has a problem may still be patched elsewhere. + put(paths, "b", doc("b", { summary: "see [x](cite:nobody)" })); + assert.equal((await patchArticle("b", { title: "Still a draft" }, paths))?.title, "Still a draft"); +}); + +test("writeArticle: only a sound document; a regenerated one keeps its audience", async () => { + const paths = store(); + await assert.rejects(writeArticle(doc("a", { kind: "essay" }), { paths }), /not a sound report/); + await assert.rejects(writeArticle(doc("Bad"), { paths }), /not an article id/); + assert.equal(existsSync(articleFile(paths, "a")), false); + await writeArticle(doc("a"), { paths }); + await configureArticle("a", { audience: "public", published: true }, paths); + await writeArticle(doc("a", { title: "Regenerated" }), { paths }); + assert.equal(json(articleFile(paths, "a")).audience, "public", "kept"); + assert.equal(json(articleFile(paths, "a")).title, "Regenerated"); + await writeArticle(doc("a"), { paths, keepAudience: false }); + assert.equal("audience" in json(articleFile(paths, "a")), false, "written as given"); + assert.deepEqual((await readArticlesIndex(paths)).published, ["a"], "the index is untouched by a write"); +}); + +test("the lock: parallel writes all land; a live holder is waited for; a dead one is taken over", async () => { + const paths = store(); + const ids = Array.from({ length: 12 }, (_, i) => `a${i}`); + for (const id of ids) put(paths, id, doc(id)); + await Promise.all(ids.map((id) => setPublished(id, true, {}, paths))); + assert.deepEqual([...(await readArticlesIndex(paths)).published].sort(), [...ids].sort()); + assert.equal(existsSync(path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME)), false, "released"); + + // A live holder (this process, fresh): the write waits until it is gone. + const lock = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME); + writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() })); + let released = false; + setTimeout(() => { + released = true; + rmSync(lock, { force: true }); + }, 300); + await setPublished("a0", false, {}, paths); + assert.equal(released, true, "it waited for the holder"); + + // A dead holder on this host: taken over at once. + writeFileSync(lock, JSON.stringify({ pid: 2 ** 22 + 12345, host: os.hostname(), since: Date.now() })); + const t0 = Date.now(); + await setPublished("a0", true, {}, paths); + assert.ok(Date.now() - t0 < 2000, "no wait for a dead holder"); + assert.equal(existsSync(lock), false); +}); diff --git a/common/lib/report/registry.ts b/common/lib/report/registry.ts @@ -0,0 +1,507 @@ +// THE ARTICLE REGISTRY — the one writer of the article store +// (`transcripts/reports/`, release 26; plans/reports-on-homepage.md, "The +// model"). The `patchSite` of articles: every write is LOCKED, VALIDATED and +// ATOMIC, and nothing else — not a generator, not a script, not a hand — writes +// `index.json` or an article's `audience`. +// +// transcripts/reports/index.json {"published": [ids]} — the +// published, ordered list; an +// article directory it does not +// name is a draft +// transcripts/reports/<id>/report.json the article (REPORT.md), with +// `audience` "public" | "private" +// (absent = private, D2) +// transcripts/reports/.registry.lock held while a write runs +// +// THE LOCK is two locks: withJsonFileLock (in-process: the editor's routes and +// server actions) around an O_EXCL lock file (across processes: a generator +// in ~/reports/* calling this beside a running editor). A lock file whose +// holder is gone — its pid does not answer on this host, or it is older than +// LOCK_STALE_MS — is taken over. A write waits for a live holder up to +// LOCK_WAIT_MS, then refuses. +// +// VALIDATED: an index names report ids, once each. Publishing needs a sound +// report.json (no problem lib/report/validate.ts names). A patch may not make +// a report worse: a patched report.json is written only when it parses and +// has no problem the report did not already have. A whole document +// (writeArticle) is written only when it has none. +// +// ATOMIC: each file is replaced whole (writeJsonAtomic). A call that writes +// both files (configureArticle) checks everything first and writes nothing +// when anything is refused. +// +// SERVER-ONLY (node:fs). + +import type { Dirent } from "node:fs"; +import { mkdir, open, readdir, readFile, rm, stat } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { getPaths, type Paths } from "../paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; +import type { Problem } from "../citations/validate"; +import { isReportId, REPORT_AUDIENCES, type Report, type ReportAudience } from "./schema"; +import { parseReport } from "./validate"; +import { articleReportStore, storeReportDir, storeReportFile } from "./store"; + +export const ARTICLES_INDEX_FILENAME = "index.json"; +export const ARTICLES_LOCK_FILENAME = ".registry.lock"; +// How long a write waits for another process's write, and when a lock file is +// stale whoever holds it (a write takes milliseconds). +export const LOCK_WAIT_MS = 10_000; +export const LOCK_STALE_MS = 60_000; +const LOCK_POLL_MS = 25; + +export type ArticlesIndex = { published: string[] }; + +// A refusal: nothing was written. `problems` lists a report's problems as +// `<path>: <message>` lines when that is why. +export class ArticleRegistryError extends Error { + constructor( + message: string, + readonly problems: string[] = [], + ) { + super(problems.length > 0 ? `${message}:\n${problems.map((p) => ` ${p}`).join("\n")}` : message); + this.name = "ArticleRegistryError"; + } +} + +// ─── Where ─── + +export function articlesIndexFile(paths: Pick<Paths, "articlesDir"> = getPaths()): string { + return path.join(paths.articlesDir, ARTICLES_INDEX_FILENAME); +} + +export function articleDir(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): string { + return storeReportDir(articleReportStore(paths), id); +} + +export function articleFile(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): string { + return storeReportFile(articleReportStore(paths), id); +} + +// ─── Reading ─── + +// Who may read an article: its `audience`, absent = private. +export function articleAudience(report: { audience?: unknown } | null | undefined): ReportAudience { + return report?.audience === "public" ? "public" : "private"; +} + +export function isReportAudience(v: unknown): v is ReportAudience { + return typeof v === "string" && (REPORT_AUDIENCES as readonly string[]).includes(v); +} + +// index.json's shape: `{"published": [ids]}`, ids once each, nothing else. +export function parseArticlesIndex(raw: unknown): { ok: true; index: ArticlesIndex } | { ok: false; problem: string } { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + return { ok: false, problem: 'is not an object {"published": [ids]}' }; + } + const extra = Object.keys(raw).filter((k) => k !== "published"); + if (extra.length > 0) return { ok: false, problem: `has unknown key(s): ${extra.join(", ")}` }; + const published = (raw as { published?: unknown }).published ?? []; + if (!Array.isArray(published)) return { ok: false, problem: '"published" is not a list of article ids' }; + const seen = new Set<string>(); + for (const id of published) { + if (!isReportId(id)) return { ok: false, problem: `"published" names ${JSON.stringify(id)}, which is not an article id` }; + if (seen.has(id)) return { ok: false, problem: `"published" names "${id}" twice` }; + seen.add(id); + } + return { ok: true, index: { published: [...published] as string[] } }; +} + +// The published list. No index.json = none published. An index that cannot be +// read is an error, never an empty list: a build must not publish nothing +// because a file is torn. +export async function readArticlesIndex(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<ArticlesIndex> { + const file = articlesIndexFile(paths); + const read = await readJsonFile(file); + if (!read.ok) { + if (read.reason === "absent") return { published: [] }; + throw new ArticleRegistryError(`reports/${ARTICLES_INDEX_FILENAME} is ${read.reason} (${file})`); + } + const parsed = parseArticlesIndex(read.value); + if (!parsed.ok) throw new ArticleRegistryError(`reports/${ARTICLES_INDEX_FILENAME} ${parsed.problem}`); + return parsed.index; +} + +// Every article directory, published or draft: a directory under +// `transcripts/reports/` whose name is an article id. Sorted. +export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> { + let entries: Dirent[]; + try { + entries = await readdir(paths.articlesDir, { withFileTypes: true }); + } catch { + return []; + } + return entries + .filter((e) => e.isDirectory() && isReportId(e.name)) + .map((e) => e.name) + .sort((a, b) => a.localeCompare(b)); +} + +// One article as the registry knows it. +export type ArticleState = { + id: string; + // report.json is there (an index may name an article whose directory is gone). + exists: boolean; + title: string | null; + audience: ReportAudience; + published: boolean; + // Its place in the published list (0 = first), or null for a draft. + position: number | null; + // What lib/report/validate.ts says about report.json (one entry when it is + // not readable JSON). + problems: Problem[]; +}; + +type ReadArticle = + | { ok: true; raw: Record<string, unknown>; problems: Problem[]; report: Report | null } + | { ok: false; reason: "absent" | "unreadable" | "unparseable" | "not-an-object" }; + +async function readArticle(paths: Pick<Paths, "articlesDir" | "exportIndexDir">, id: string): Promise<ReadArticle> { + const read = await readJsonFile(articleFile(paths, id)); + if (!read.ok) return { ok: false, reason: read.reason }; + if (!read.value || typeof read.value !== "object" || Array.isArray(read.value)) return { ok: false, reason: "not-an-object" }; + const raw = read.value as Record<string, unknown>; + const parsed = parseReport(raw, { id }); + return { ok: true, raw, problems: parsed.problems, report: parsed.ok ? parsed.value : null }; +} + +function stateOf(id: string, read: ReadArticle, index: ArticlesIndex): ArticleState { + const position = index.published.indexOf(id); + return { + id, + exists: read.ok, + title: read.ok && typeof read.raw.title === "string" ? read.raw.title : null, + audience: articleAudience(read.ok ? read.raw : null), + published: position >= 0, + position: position >= 0 ? position : null, + problems: read.ok + ? read.problems + : read.reason === "absent" + ? [] + : [{ path: "", message: `report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}` }], + }; +} + +// One article's state, or null when it has no directory and the index does +// not name it. +export async function readArticleState( + id: string, + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<ArticleState | null> { + if (!isReportId(id)) return null; + const index = await readArticlesIndex(paths); + const read = await readArticle(paths, id); + if (!read.ok && read.reason === "absent" && !index.published.includes(id)) { + const dir = await stat(articleDir(paths, id)).catch(() => null); + if (!dir?.isDirectory()) return null; + } + return stateOf(id, read, index); +} + +// Every article: the published ones in their order, then the drafts by id. +// An id the index names whose report.json is gone is listed (`exists` false). +export async function listArticles(paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths()): Promise<ArticleState[]> { + const index = await readArticlesIndex(paths); + const dirs = await listArticleDirs(paths); + const ids = [...index.published, ...dirs.filter((d) => !index.published.includes(d))]; + const out: ArticleState[] = []; + for (const id of ids) out.push(stateOf(id, await readArticle(paths, id), index)); + return out; +} + +// The published articles a build of `audience` carries, in order: a public +// build only those whose report.json says `audience: "public"`; a private build +// every published one. An article whose report.json cannot be read is kept +// (compose names its problem) by a private build and left out by a public one, +// which can never know it is public. +export async function publishedArticleIds( + audience: ReportAudience, + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<string[]> { + const index = await readArticlesIndex(paths); + if (audience === "private") return index.published; + const out: string[] = []; + for (const id of index.published) { + const read = await readArticle(paths, id); + if (read.ok && articleAudience(read.raw) === "public") out.push(id); + } + return out; +} + +// ─── The lock ─── + +type LockHolder = { pid: number; host: string; since: number }; + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +function pidAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (e) { + return (e as NodeJS.ErrnoException).code === "EPERM"; + } +} + +async function lockIsStale(file: string): Promise<boolean> { + let holder: LockHolder | null = null; + try { + holder = JSON.parse(await readFile(file, "utf8")) as LockHolder; + } catch { + holder = null; + } + if (!holder || typeof holder.since !== "number") { + // Torn (a taker died between creating and writing it): stale once old. + const st = await stat(file).catch(() => null); + return !st || Date.now() - st.mtimeMs > LOCK_STALE_MS; + } + if (Date.now() - holder.since > LOCK_STALE_MS) return true; + return holder.host === os.hostname() && typeof holder.pid === "number" && !pidAlive(holder.pid); +} + +// Run `fn` holding the article store's lock, in this process and across +// processes. Exported for a caller that writes several things as one. +export function withArticleStoreLock<T>( + fn: () => Promise<T>, + paths: Pick<Paths, "articlesDir"> = getPaths(), +): Promise<T> { + const file = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME); + return withJsonFileLock(file, async () => { + await mkdir(paths.articlesDir, { recursive: true }); + const deadline = Date.now() + LOCK_WAIT_MS; + for (;;) { + try { + const h = await open(file, "wx"); + try { + await h.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() } satisfies LockHolder)); + } finally { + await h.close(); + } + break; + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; + if (await lockIsStale(file)) { + await rm(file, { force: true }); + continue; + } + if (Date.now() > deadline) { + throw new ArticleRegistryError(`the article store is busy (${file} is held by another write) — try again`); + } + await sleep(LOCK_POLL_MS); + } + } + try { + return await fn(); + } finally { + await rm(file, { force: true }); + } + }); +} + +// ─── Writing ─── + +const problemLines = (problems: readonly Problem[]) => problems.map((p) => `${p.path || "(root)"}: ${p.message}`); +const problemKey = (p: Problem) => `${p.path}\u0000${p.message}`; + +function assertId(id: unknown): asserts id is string { + if (!isReportId(id)) { + throw new ArticleRegistryError(`"${String(id)}" is not an article id (a lowercase slug: [a-z0-9][a-z0-9-]*, at most 64)`); + } +} + +async function writeIndex(paths: Pick<Paths, "articlesDir">, index: ArticlesIndex): Promise<void> { + await writeJsonAtomic(articlesIndexFile(paths), { published: index.published }, { mkdir: true }); +} + +// Where an article goes in a published list: `position` (0 = first), else +// where it is, else last. +function placed(list: readonly string[], id: string, position: number | undefined): string[] { + const without = list.filter((x) => x !== id); + const at = position ?? (list.includes(id) ? list.indexOf(id) : without.length); + if (!Number.isInteger(at) || at < 0 || at > without.length) { + throw new ArticleRegistryError( + `position ${String(position)} is out of range: 0 (first) to ${without.length} (last) for "${id}"`, + ); + } + return [...without.slice(0, at), id, ...without.slice(at)]; +} + +// The change configureArticle and the ops action make. +export type ArticleConfigChange = { + audience?: ReportAudience; + // true publishes (at `position`, else where it is, else last); false + // unpublishes (it stays on disk, a draft). + published?: boolean; + // Its place in the published list, 0 = first. Moves a published article; + // with `published: true` places it. Refused on a draft or with `published: false`. + position?: number; +}; + +// Set an article's audience and its place in the published list, in one +// locked call: every refusal before anything is written. Answers the article +// as it now is. +export async function configureArticle( + id: string, + change: ArticleConfigChange, + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<ArticleState> { + assertId(id); + if (change.audience !== undefined && !isReportAudience(change.audience)) { + throw new ArticleRegistryError(`audience must be one of ${REPORT_AUDIENCES.join(", ")}`); + } + if (change.published === false && change.position !== undefined) { + throw new ArticleRegistryError(`"${id}": a position places a published article — not one being unpublished`); + } + return withArticleStoreLock(async () => { + const index = await readArticlesIndex(paths); + const read = await readArticle(paths, id); + if (!read.ok) { + // Unpublishing an article whose directory is gone tidies the index. + if (change.published === false && change.audience === undefined && index.published.includes(id)) { + const next = { published: index.published.filter((x) => x !== id) }; + await writeIndex(paths, next); + return stateOf(id, read, next); + } + throw new ArticleRegistryError( + read.reason === "absent" + ? `no article "${id}" (no reports/${id}/report.json)` + : `reports/${id}/report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}`, + ); + } + const wasPublished = index.published.includes(id); + const publish = change.published ?? wasPublished; + if (change.position !== undefined && !publish) { + throw new ArticleRegistryError(`"${id}" is a draft: give "published": true to place it`); + } + // Only a sound article is published (compose would refuse it anyway). + if (publish && !wasPublished && read.problems.length > 0) { + throw new ArticleRegistryError(`"${id}" cannot be published while report.json has problems`, problemLines(read.problems)); + } + const nextIndex: ArticlesIndex = publish + ? { published: placed(index.published, id, change.position) } + : { published: index.published.filter((x) => x !== id) }; + let raw = read.raw; + if (change.audience !== undefined && articleAudience(raw) !== change.audience) { + raw = { ...raw, audience: change.audience }; + const after = parseReport(raw, { id }); + const before = new Set(read.problems.map(problemKey)); + const worse = after.problems.filter((p) => !before.has(problemKey(p))); + if (!after.ok || worse.length > 0) { + throw new ArticleRegistryError(`"${id}": setting its audience would make report.json invalid`, problemLines(worse)); + } + await writeJsonAtomic(articleFile(paths, id), raw); + } + if (nextIndex.published.join("\n") !== index.published.join("\n")) await writeIndex(paths, nextIndex); + return stateOf(id, { ...read, raw }, nextIndex); + }, paths); +} + +// Publish (`true`) or unpublish (`false`) an article; `position` places it +// (0 = first; absent = where it is, else last). Answers the published list. +export async function setPublished( + id: string, + published: boolean, + opts: { position?: number } = {}, + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<ArticlesIndex> { + await configureArticle(id, { published, ...(opts.position !== undefined ? { position: opts.position } : {}) }, paths); + return readArticlesIndex(paths); +} + +// Replace the published order whole: `ids` must be the published articles, +// each once, in their new order. Answers the published list. +export async function setArticlesOrder( + ids: readonly string[], + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<ArticlesIndex> { + return withArticleStoreLock(async () => { + const index = await readArticlesIndex(paths); + const want = [...ids].sort().join("\n"); + if (new Set(ids).size !== ids.length || want !== [...index.published].sort().join("\n")) { + throw new ArticleRegistryError( + `an order must name every published article once (published: ${index.published.join(", ") || "none"})`, + ); + } + const next = { published: [...ids] }; + await writeIndex(paths, next); + return next; + }, paths); +} + +// The keys a patch may change: anything but what names the document. +export type ArticlePatch = Partial<Omit<Report, "format" | "version" | "id">>; + +// PATCH SOME KEYS OF AN ARTICLE'S report.json — read inside the lock and +// patched as it is now, so a patch never writes back keys read earlier. A key +// given as `undefined` is removed. A function patch is given the report as it +// is now. Written only when the result parses and has no problem the report +// did not already have. Null when the article has no report.json: a patch +// never creates one (writeArticle does). +export async function patchArticle( + id: string, + patch: ArticlePatch | ((current: Report) => ArticlePatch), + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<Report | null> { + assertId(id); + return withArticleStoreLock(async () => { + const read = await readArticle(paths, id); + if (!read.ok) { + if (read.reason === "absent") return null; + throw new ArticleRegistryError(`reports/${id}/report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}`); + } + let changes: ArticlePatch; + if (typeof patch === "function") { + if (!read.report) { + throw new ArticleRegistryError(`reports/${id}/report.json does not parse: fix it before a function patch`, problemLines(read.problems)); + } + changes = patch(read.report); + } else { + changes = patch; + } + for (const k of ["format", "version", "id"]) { + if (k in (changes as object)) throw new ArticleRegistryError(`"${id}": a patch may not change "${k}"`); + } + const next: Record<string, unknown> = { ...read.raw }; + for (const [k, v] of Object.entries(changes)) { + if (v === undefined) delete next[k]; + else next[k] = v; + } + const after = parseReport(next, { id }); + const before = new Set(read.problems.map(problemKey)); + const worse = after.problems.filter((p) => !before.has(problemKey(p))); + if (!after.ok || worse.length > 0) { + throw new ArticleRegistryError(`"${id}": the patch would make report.json invalid`, problemLines(worse)); + } + await writeJsonAtomic(articleFile(paths, id), next); + return after.value; + }, paths); +} + +// WRITE A WHOLE ARTICLE — a generator's report.json, created or replaced at +// `transcripts/reports/<doc.id>/report.json`. Written only when it has no +// problem. A document with no `audience` keeps the one on disk (regenerating a +// public article does not make it private); `keepAudience: false` writes it as +// given. Its place in the index is untouched: publish with setPublished. +export async function writeArticle( + doc: unknown, + opts: { paths?: Pick<Paths, "articlesDir" | "exportIndexDir">; keepAudience?: boolean } = {}, +): Promise<Report> { + const paths = opts.paths ?? getPaths(); + if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new ArticleRegistryError("an article is a JSON object"); + const id = (doc as { id?: unknown }).id; + assertId(id); + return withArticleStoreLock(async () => { + let next = doc as Record<string, unknown>; + if (opts.keepAudience !== false && next.audience === undefined) { + const read = await readArticle(paths, id); + if (read.ok && read.raw.audience !== undefined) next = { ...next, audience: read.raw.audience }; + } + const parsed = parseReport(next, { id }); + if (!parsed.ok || parsed.problems.length > 0) { + throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems)); + } + await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true }); + return parsed.value; + }, paths); +} diff --git a/common/lib/report/routes.ts b/common/lib/report/routes.ts @@ -19,6 +19,9 @@ export type ReportBase = `/${string}/`; // 26 A5; `/reports/` before it). export const SITE_REPORTS_BASE: ReportBase = "/pages/"; +// The homepage's articles (plans/reports-on-homepage.md, A3): `/articles/<id>/`. +export const ARTICLES_REPORTS_BASE: ReportBase = "/articles/"; + // Where a site's reports were published before release 26: compose still // clears it from a public dir an older compose wrote. export const LEGACY_SITE_REPORTS_DIR = "reports"; diff --git a/common/lib/report/schema.ts b/common/lib/report/schema.ts @@ -36,6 +36,14 @@ export const REPORT_VERSION = 1; export const REPORT_KINDS = ["factcheck", "sweep"] as const; export type ReportKind = (typeof REPORT_KINDS)[number]; +// Who may read an ARTICLE (a report in the article store, ./store.ts): the +// public homepage build carries only `public` ones; the private build every +// published one. Absent = private (release 26, D2) — going public is an +// explicit `articles-config` (./registry.ts). A site's page ignores it: it +// has its site's audience. +export const REPORT_AUDIENCES = ["public", "private"] as const; +export type ReportAudience = (typeof REPORT_AUDIENCES)[number]; + const text = z.string(); const verdict = z.enum(VERDICTS as unknown as [Verdict, ...Verdict[]]); @@ -104,6 +112,7 @@ export const reportSchema = z.strictObject({ version: z.literal(REPORT_VERSION), id: text, kind: z.enum(REPORT_KINDS), + audience: z.enum(REPORT_AUDIENCES).optional(), series: text.optional(), title: text, subtitle: text.optional(), @@ -143,6 +152,8 @@ export const REPORT_FIELD_DOCS: FieldDocs<Report> = { version: `\`${REPORT_VERSION}\`.`, id: "The report's id: a lowercase slug (`[a-z0-9][a-z0-9-]*`, at most 64), its directory name under `reports/` and the last segment of its page (on a site, `/pages/<id>/`). Must match the directory.", kind: '`"factcheck"` — sections of claims, each with a verdict — or `"sweep"` — sections with no verdicts, or bodies with inline citations.', + audience: + "Who may read the report when it is an ARTICLE (in `transcripts/reports/`, published by the homepage): `\"public\"` — the public homepage build carries it — or `\"private\"` — only the private build (`archilyzer build homepage --private`, never deployed) does. Absent = `\"private\"`: going public is an explicit `pnpm ops articles-config`. Ignored on a site's page, which has its site's audience.", series: "The series the report belongs to: a recurring name for its kind of report. It is shown on its own line above the title, in the accent colour, at the head of the report's page, its exports and the report list (where a report with no series shows its kind instead), and is joined to the title as `<series>: <title>` where one line names the report (a page title, a link, a cited-in entry).", title: "The report's title.", subtitle: "A line under the title.", diff --git a/common/lib/report/store.ts b/common/lib/report/store.ts @@ -0,0 +1,70 @@ +// WHERE A REPORT LIVES — the two stores of report directories (release 26, +// plans/reports-on-homepage.md, "The model"): +// +// a SITE's pages transcripts/sites/<siteId>/reports/<id>/ published by +// the site's `pages` list (site.json) +// the ARTICLES transcripts/reports/<id>/ published by +// transcripts/reports/index.json (./registry.ts) +// +// A report directory is the same in both: report.json, its stills/, sources/, +// video, history-git/ and notes.json. What differs is where the directories +// are, where their staging (prepared media, exports) goes, and how a message +// names one — which is all a ReportStore says. Nothing here reads a file: +// whether a report is published, who may read it and what it may cite is the +// host's (publish/reportHost.ts). + +import path from "node:path"; +import type { Paths } from "../paths"; + +export type ReportStoreKind = "site" | "articles"; + +// The id of the article store's staging (`.export-index/articles/`) and of its +// prepared-media manifest. A site id may be spelled the same; their staging +// dirs differ (`.export-index/sites/<siteId>/`), so they never meet. +export const ARTICLES_STORE_ID = "articles"; + +export type ReportStore = { + kind: ReportStoreKind; + // The site's id, or ARTICLES_STORE_ID. + id: string; + // The directory holding the report directories. + reportsDir: string; + // Staging, never served: `report-media/` and `report-exports/` go under it. + stagingDir: string; + // How a message names the reports directory, relative to the corpus: + // `sites/<siteId>/reports` or `reports`. + label: string; +}; + +export function siteReportStore(paths: Pick<Paths, "sitesDir" | "exportSitesIndexDir">, siteId: string): ReportStore { + return { + kind: "site", + id: siteId, + reportsDir: path.join(paths.sitesDir, siteId, "reports"), + stagingDir: path.join(paths.exportSitesIndexDir, siteId), + label: `sites/${siteId}/reports`, + }; +} + +export function articleReportStore(paths: Pick<Paths, "articlesDir" | "exportIndexDir">): ReportStore { + return { + kind: "articles", + id: ARTICLES_STORE_ID, + reportsDir: paths.articlesDir, + stagingDir: path.join(paths.exportIndexDir, ARTICLES_STORE_ID), + label: "reports", + }; +} + +// A report's directory, its report.json, and how a message names the file. +export function storeReportDir(store: Pick<ReportStore, "reportsDir">, reportId: string): string { + return path.join(store.reportsDir, reportId); +} + +export function storeReportFile(store: Pick<ReportStore, "reportsDir">, reportId: string): string { + return path.join(storeReportDir(store, reportId), "report.json"); +} + +export function storeReportLabel(store: Pick<ReportStore, "label">, reportId: string): string { + return `${store.label}/${reportId}/report.json`; +} diff --git a/common/lib/report/views.ts b/common/lib/report/views.ts @@ -481,6 +481,9 @@ export type ReportViewResolver = { history?: ReportHistoryRef; // The report's feeds (absolute URLs), carried only by a report with entries. feeds?: ReportFeeds; + // Where the build serves its reports (./routes.ts): the published path of a + // still or the report's video. A site's by default. + base?: ReportBase; }; function sourceView(id: string, s: Source): SourceView { @@ -565,7 +568,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver) sourceId: c.source, sourceTitle: s.title, sourceAccent: s.accent, - image: c.image ? reportAssetPath(report.id, c.image) : undefined, + image: c.image ? reportAssetPath(report.id, c.image, resolve.base) : undefined, href: s.url, }); break; @@ -608,8 +611,8 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver) subtitle: report.subtitle, video: report.video ? defined({ - src: reportAssetPath(report.id, report.video.src), - poster: report.video.poster ? reportAssetPath(report.id, report.video.poster) : undefined, + src: reportAssetPath(report.id, report.video.src, resolve.base), + poster: report.video.poster ? reportAssetPath(report.id, report.video.poster, resolve.base) : undefined, caption: report.video.caption, }) : undefined, @@ -790,7 +793,7 @@ export function foundGroups(view: Pick<ReportPageView, "sections">): FoundGroup[ } // The report's entry in the index. -export function reportIndexEntry(view: ReportPageView): ReportIndexEntry { +export function reportIndexEntry(view: ReportPageView, base: ReportBase = SITE_REPORTS_BASE): ReportIndexEntry { const tally = view.kind === "factcheck" ? verdictTally(view) : undefined; return defined({ id: view.id, @@ -800,7 +803,7 @@ export function reportIndexEntry(view: ReportPageView): ReportIndexEntry { subtitle: view.subtitle, published: view.published, updated: view.updated, - href: reportPagePath(view.id), + href: reportPagePath(view.id, base), citationCount: Object.keys(view.citations).length, claimCount: view.sections.reduce((n, s) => n + s.claims.length, 0), tally, diff --git a/common/lib/site.ts b/common/lib/site.ts @@ -21,6 +21,7 @@ import { siteChannelSlugs, sitePublishProblem, siteSearchProblem, + reservedSiteIdProblem, siteToDisk, type Site, } from "./siteSchema"; @@ -232,6 +233,8 @@ export async function writeSite( if (!isValidSiteId(site.siteId)) { throw new Error(`Invalid site id: ${String(site.siteId)}`); } + const reserved = reservedSiteIdProblem(site.siteId); + if (reserved) throw new Error(reserved); const groups = parseChannelGroups(site.groups); if (groups.length === 0) { throw new Error("At least one channel group is required"); diff --git a/common/lib/siteSchema.test.ts b/common/lib/siteSchema.test.ts @@ -24,6 +24,8 @@ import { sitePublishProblem, siteSearchProblem, siteToDisk, + RESERVED_SITE_IDS, + reservedSiteIdProblem, type Site, } from "./siteSchema"; import { getSite, patchSite, resolveRelatedSites, siteConfigFile, writeSite } from "./site"; @@ -376,6 +378,21 @@ test("pages: ordered slugs, invalid and repeated ids dropped, written only when assert.deepEqual(siteToDisk({ ...site, pages: ["ok", "NOPE", "ok"] }).pages, ["ok"]); }); +test("the reserved site ids are refused on save, and only those", async () => { + assert.deepEqual([...RESERVED_SITE_IDS], ["articles", "new"]); + const paths = scratchPaths(await mkdtemp(path.join(os.tmpdir(), "site-"))); + for (const id of RESERVED_SITE_IDS) { + assert.match(reservedSiteIdProblem(id) ?? "", /is reserved/); + await assert.rejects(writeSite(parseSite(id, {}), paths), /is reserved/, id); + assert.equal(fs.existsSync(siteConfigFile(paths, id)), false, id); + } + for (const id of ["articles-2", "news", "my-articles"]) { + assert.equal(reservedSiteIdProblem(id), null, id); + await writeSite(parseSite(id, {}), paths); + assert.ok(fs.existsSync(siteConfigFile(paths, id)), id); + } +}); + test("legacy reports (before release 26) reads as pages, is never written, and loses to pages", () => { const legacy = parseSite("s", { search: false, reports: ["one", "two"] }); assert.deepEqual(legacy.pages, ["one", "two"]); diff --git a/common/lib/siteSchema.ts b/common/lib/siteSchema.ts @@ -301,6 +301,18 @@ export function isValidSiteId(id: unknown): id is string { return typeof id === "string" && SITE_ID_RE.test(id); } +// Site ids a new site may not take (release 26, ruled): the editor's +// `/sites/articles` (the Articles tab) and `/sites/new` (the create form), and +// umtool's `articles/<id>`, would hide a site of that name. +export const RESERVED_SITE_IDS: readonly string[] = ["articles", "new"]; + +// Why a save of a site under this id is refused, or null. +export function reservedSiteIdProblem(id: string): string | null { + return RESERVED_SITE_IDS.includes(id) + ? `"${id}" is reserved (the editor's /sites/${id} and umtool's articles/ would hide a site of that name) — choose another id` + : null; +} + // THE ONE PREDICATE for `listed` (site.json's opt-out; absent = listed). Every // public output that enumerates the family's sites filters through it: the // homepage summary (lib/homepageSummary.ts), channel-sites.json and the pooled diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -7,8 +7,17 @@ // earlier compose — of this site or another, public/ is shared — left under // `reports/`, `m/` and `media/`, so a site with no reports ships none. // +// ONE STAGE, TWO HOSTS (release 26, plans/reports-on-homepage.md): the stage +// is a resolver over a HOST (./reportHost.ts — whose reports, what they may +// cite, where the record links go) and a writer into an OUTPUT ROOT. +// `composeReports` / `resolveSiteReports` are the site's (its `pages`, its +// `channels` + `citedChannels`, export/public); `composeHostReports` / +// `resolveReports` take any host — the articles (`articlesReportHost`: the +// whole corpus is citable, D4; the post visibility rule by the build's +// audience) into the homepage's public dir. +// // What it reads: -// - the site's `reports` (site.json, in order), each report.json parsed and +// - the site's `pages` (site.json, in order), each report.json parsed and // validated by the document's own checker (./reportMedia.ts // loadSiteReports); any problem fails the stage; // - per cited video/audio record: transcript.cues.json when it is fresh, @@ -66,13 +75,7 @@ import { publishFileSizeProblem } from "../lib/builtExport"; import type { Paths } from "../lib/paths"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { type Site } from "../lib/site"; -import { - isCitedOnlyChannel, - isCitedSite, - notInSiteMessage, - parseSiteUrl, - siteCitableChannelSlugs, -} from "../lib/siteSchema"; +import { storeReportDir } from "../lib/report/store"; import { getSettings } from "../lib/settings"; import { postsVisibleTo } from "../lib/postsVisibility"; import { assertChannelTextReadable } from "../lib/channelMedia"; @@ -111,7 +114,7 @@ import { MOMENTS_INDEX_PATH, REPORT_INDEX_FORMAT, REPORT_VIEWS_VERSION, - REPORTS_INDEX_PATH, + reportsIndexPath, buildReportPageView, citedInViews, evidenceClipPath, @@ -137,26 +140,27 @@ import { import { citedEvidenceSpan, isAudioOnlyPlatform, type EvidenceSpan } from "../lib/evidenceClip-server"; import { citedMoments, - loadSiteReports, - readReportMediaIndex, - reportMediaDir, - siteReportDir, + loadHostReports, + readStoreMediaIndex, + storeMediaDir, type ReportMediaEntry, } from "./reportMedia"; -import { publishableReportExports, reportFileSha256, type PublishableReportExports } from "./reportExportFiles"; -import { publishReportHistory, readReportHistoryView, reportHistoryGitDir, reportHistoryRef } from "./reportHistory"; +import { publishableStoreExports, storeReportFileSha256, type PublishableReportExports } from "./reportExportFiles"; +import { publishReportHistory, readReportHistoryView, reportHistoryRef, storeHistoryGitDir } from "./reportHistory"; +import { hostCorpusLink, siteReportHost, type ReportHost } from "./reportHost"; import type { ReportHistoryRef, ReportHistoryView } from "../lib/report/revisions"; -import { LEGACY_SITE_REPORTS_DIR, SITE_REPORTS_BASE, reportBaseDir } from "../lib/report/routes"; - -// The public dir's entries this stage owns. Every compose removes them first — -// and the dir a site's reports were published under before release 26, so an -// older compose's reports never outlive it. -export const REPORT_PUBLIC_ENTRIES: readonly string[] = [ - reportBaseDir(SITE_REPORTS_BASE), - LEGACY_SITE_REPORTS_DIR, - "m", - "media", -]; +import { LEGACY_SITE_REPORTS_DIR, SITE_REPORTS_BASE, reportBaseDir, type ReportBase } from "../lib/report/routes"; + +// The public dir's entries this stage owns for a host serving its reports +// under `base`: its reports, the moments, the cited media. Every compose +// removes them first — and the dir a site's reports were published under +// before release 26, so an older compose's reports never outlive it. +export function reportPublicEntries(base: ReportBase): string[] { + return [...new Set([reportBaseDir(base), LEGACY_SITE_REPORTS_DIR, "m", "media"])]; +} + +// A site's. +export const REPORT_PUBLIC_ENTRIES: readonly string[] = reportPublicEntries(SITE_REPORTS_BASE); // The transcript lines a moment page shows either side of its span, and at // most how many: bounded context, never the record (plans/report-sites.md, @@ -209,10 +213,20 @@ export type ComposeReportsProblem = { // The kinds `allowMissingMedia` lets through: the page renders without a clip. const MEDIA_PROBLEMS: ReadonlySet<ComposeReportsProblemKind> = new Set(["missing-media", "stale-media"]); +// What a refusal calls the reports it could not compose: a site's pages, or +// the articles. +export function composedReportsNoun(host: Pick<ReportHost, "kind">): string { + return host.kind === "site" ? "the site's pages" : "the articles"; +} + export class ComposeReportsError extends Error { - constructor(readonly problems: ComposeReportsProblem[]) { + constructor( + readonly problems: ComposeReportsProblem[], + // Whose reports: composedReportsNoun(host). + what = "the site's pages", + ) { super( - `the site's reports cannot be composed (${problems.length} problem(s)):\n` + + `${what} cannot be composed (${problems.length} problem(s)):\n` + formatComposeReportsProblems(problems).map((l) => ` ${l}`).join("\n"), ); this.name = "ComposeReportsError"; @@ -231,6 +245,10 @@ export type ComposeReportsOptions = { site: Site; // Default: paths.exportPublicDir. publicDir?: string; +} & ComposeStageOptions; + +// What the stage takes besides whose reports and where they go. +type ComposeStageOptions = { // Let a citation without prepared media through (`--allow-missing-media`). allowMissingMedia?: boolean; // `social.x.visibility` and friends; default the live settings. @@ -373,10 +391,6 @@ const isoDay = (uploadDate: string | undefined): string | undefined => ? `${uploadDate.slice(0, 4)}-${uploadDate.slice(4, 6)}-${uploadDate.slice(6, 8)}` : undefined; -// A record in this site's corpus — the viewer's `?v=` link (a FULL site only). -function corpusLink(slug: string, params: Record<string, string>): string { - return `/?${new URLSearchParams({ v: slug, ...params }).toString()}`; -} const cueLine = (text: string) => text.replace(/\s+/g, " ").trim(); @@ -462,7 +476,7 @@ const sameSpan = (a: EvidenceSpan, b: EvidenceSpan) => // ─── Resolving: the reports as views, nothing written ─── -export type ResolveSiteReportsOptions = Omit<ComposeReportsOptions, "publicDir"> & { +type ResolveViewOptions = { // Each report's downloads, as its view carries them. downloads?: (reportId: string) => ReportDownloads | undefined; // Each report's newest revision, as its view carries it. @@ -471,6 +485,11 @@ export type ResolveSiteReportsOptions = Omit<ComposeReportsOptions, "publicDir"> feeds?: (reportId: string) => ReportFeeds | undefined; }; +export type ResolveSiteReportsOptions = Omit<ComposeReportsOptions, "publicDir"> & ResolveViewOptions; + +// Any host's reports (./reportHost.ts). +export type ResolveReportsOptions = { paths: Paths; host: ReportHost } & ComposeStageOptions & ResolveViewOptions; + // The site's reports resolved against the corpus — verified, their views and // moment pages built, their prepared media matched — and nothing written. // compose writes what this answers; publish/reportExports.ts renders the same @@ -488,16 +507,23 @@ export type ResolvedSiteReports = { }; export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promise<ResolvedSiteReports> { - const { paths, site } = opts; + const { site, ...rest } = opts; + return resolveReports({ ...rest, host: siteReportHost(opts.paths, site) }); +} + +export async function resolveReports(opts: ResolveReportsOptions): Promise<ResolvedSiteReports> { + const { paths, host } = opts; const log = opts.log ?? (() => {}); const now = (opts.now?.() ?? new Date()).toISOString(); - const citedSite = isCitedSite(site); - // No corpus page to link a moment to: a cited site publishes none, and a - // cited-only channel (`citedChannels`) is not in the site's corpus. - const noCorpus = (slug: string) => citedSite || isCitedOnlyChannel(site, slug); + // A record's link into an archive (the host's corpus base), or none: a + // cited site and a cited-only channel have no corpus page to link to. + const corpusLink = (channel: string, slug: string, params: Record<string, string>) => + hostCorpusLink(host, channel, { v: slug, ...params }); + // How a refusal names who may not carry a post. + const carrier = host.kind === "site" ? "this site" : "the articles"; const problems: ComposeReportsProblem[] = []; - const loaded = await loadSiteReports(paths, site); + const loaded = await loadHostReports(host); for (const p of loaded.problems) { problems.push({ kind: p.kind === "missing-report" ? "missing-report" : "invalid-report", @@ -512,9 +538,6 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi const momentCues = new Map<string, Cue[]>(); const settings = opts.settings ?? getSettings(); - // What a report on this site may cite: the pool plus its cited-only - // channels. Never a publish set — only the cited moments publish. - const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug).catch(() => null)); @@ -550,13 +573,14 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi }; // Resolve and verify every citation the reports cite. A channel outside the - // site's citable set (`channels` plus `citedChannels`), or a post the site - // may not carry, is refused before its record is read. + // host's citable set (a site's `channels` plus `citedChannels`; for the + // articles the corpus), or a post the host may not carry, is refused before + // its record is read. Never a publish set — only the cited moments publish. const refusedChannel = new Set<string>(); for (const report of reports) { // The report's video and its poster: on disk, and small enough to publish. if (report.video) { - const dir = siteReportDir(paths, site.siteId, report.id); + const dir = storeReportDir(host, report.id); for (const rel of [report.video.src, report.video.poster]) { if (!rel) continue; const st = await stat(path.join(dir, rel)).catch(() => null); @@ -574,15 +598,16 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi if (c.kind === "source" || c.kind === "page") { delete c.verification; if (c.kind === "source" && c.image) { - const src = path.join(siteReportDir(paths, site.siteId, report.id), c.image); + const src = path.join(storeReportDir(host, report.id), c.image); if (!(await isFile(src))) { problems.push({ kind: "missing-still", citation: ref, report: report.id, message: `the still ${c.image} does not exist` }); } } continue; } - if (!citable.has(c.channel)) { - problems.push({ kind: "not-in-site", citation: ref, report: report.id, message: notInSiteMessage(c.channel) }); + const notCitable = host.citableProblem(c.channel); + if (notCitable) { + problems.push({ kind: "not-in-site", citation: ref, report: report.id, message: notCitable }); refusedChannel.add(c.channel); continue; } @@ -592,8 +617,8 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi continue; } if (c.kind === "post") { - if (!postsVisibleTo(site, await configOf(c.channel), settings)) { - problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `this site may not carry posts of "${c.channel}" (the post visibility rule)` }); + if (!postsVisibleTo(host, await configOf(c.channel), settings)) { + problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `${carrier} may not carry posts of "${c.channel}" (the post visibility rule)` }); continue; } const post = await postOf(c.channel, c.id); @@ -629,15 +654,15 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi } // The prepared media, per moment. - const media = await readReportMediaIndex(paths, site.siteId); - const cacheDir = reportMediaDir(paths, site.siteId); + const media = await readStoreMediaIndex(host); + const cacheDir = storeMediaDir(host); const citedIn = buildCitedIn(reports); const momentInfo = new Map(citedMoments(reports).map((m) => [m.key, m])); const mediaOf = new Map<string, ReportMediaEntry>(); for (const key of Object.keys(citedIn)) { const m = momentInfo.get(key); if (!m || refusedChannel.has(m.moment.channel)) continue; - const entry = media?.siteId === site.siteId ? media.moments[key] : undefined; + const entry = media?.siteId === host.id ? media.moments[key] : undefined; const citedBy = citedIn[key].map((e) => `${e.reportId}#${e.citationId}`); const missing = (kind: ComposeReportsProblemKind, message: string) => problems.push({ kind, moment: key, message: `${message} (cited by ${[...new Set(citedBy)].join(", ")})` }); @@ -668,7 +693,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi const allowed = opts.allowMissingMedia ? problems.filter((p) => MEDIA_PROBLEMS.has(p.kind)) : []; const fatal = problems.filter((p) => !allowed.includes(p)); - if (fatal.length > 0) throw new ComposeReportsError(fatal); + if (fatal.length > 0) throw new ComposeReportsError(fatal, composedReportsNoun(host)); for (const line of formatComposeReportsProblems(allowed)) log(`[reports] allowed (--allow-missing-media): ${line}`); // ─── The views ─── @@ -684,7 +709,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi date: post.createdAt.slice(0, 10), platform: post.platform, originalUrl: post.url, - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(`${c.channel}/${c.id}`, { vm: "post" }), + corpusUrl: corpusLink(c.channel, `${c.channel}/${c.id}`, { vm: "post" }), }); } const { summary, archiveOrg, wayback } = (await recordOf(c.channel, c.id))!; @@ -706,7 +731,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi originalUrl: links.original.url, originalLabel: links.original.label, downloads: [links.copy], - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: corpusLink(c.channel, summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); } if (summary.platform === "archiveorg") { @@ -723,7 +748,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi originalUrl: links.original?.url ?? (summary.webpageUrl || undefined), originalLabel: links.original?.label, downloads: links.downloads.length > 0 ? links.downloads : undefined, - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: corpusLink(c.channel, summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); } return defined({ @@ -738,7 +763,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi : (platformMomentUrl(summary.webpageUrl, summary.platform as Platform, c.start) ?? undefined), // The viewer keys a record by its PUBLISHED slug, which on a platform // with two ids is not the data dir's name. - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: corpusLink(c.channel, summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); }; // buildReportPageView's resolver is synchronous: resolve every cited @@ -765,13 +790,14 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi downloads: opts.downloads?.(report.id), history: opts.history?.(report.id), feeds: opts.feeds?.(report.id), + base: host.base, }), ); const index: ReportIndexView = { format: REPORT_INDEX_FORMAT, version: REPORT_VIEWS_VERSION, - reports: views.map(reportIndexEntry), + reports: views.map((v) => reportIndexEntry(v, host.base)), }; const moments: MomentPageView[] = []; @@ -794,7 +820,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi ...(c.speaker ? { speaker: c.speaker } : {}), ...(c.date ? { date: c.date } : {}), ...(c.verification ? { verification: c.verification } : {}), - citedIn: citedInViews(entries, views), + citedIn: citedInViews(entries, views, host.base), } as const; if (c.kind === "post") { const post = postsByChannel.get(c.channel)!.get(c.id)!; @@ -848,16 +874,34 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi // ─── The stage ─── export async function composeReports(opts: ComposeReportsOptions): Promise<ComposedReports> { - const { paths, site } = opts; - const publicDir = opts.publicDir ?? paths.exportPublicDir; + const { site, publicDir, ...rest } = opts; + return composeHostReports({ + ...rest, + host: siteReportHost(opts.paths, site), + publicDir: publicDir ?? opts.paths.exportPublicDir, + }); +} + +export type ComposeHostReportsOptions = { + paths: Paths; + host: ReportHost; + // The output root: `reports/`, `m/` and `media/` are written under it (and + // removed from it first). + publicDir: string; +} & ComposeStageOptions; + +// The stage for any host (./reportHost.ts), into any output root. +export async function composeHostReports(opts: ComposeHostReportsOptions): Promise<ComposedReports> { + const { paths, host, publicDir } = opts; const log = opts.log ?? (() => {}); // Whatever an earlier compose left. rm removes a link, never its target (a // worktree's public/ entries may be links into the primary checkout). - for (const entry of REPORT_PUBLIC_ENTRIES) { + const base = host.base; + for (const entry of reportPublicEntries(base)) { await rm(path.join(publicDir, entry), { recursive: true, force: true }); } - if ((site.pages ?? []).length === 0) { + if (host.published.length === 0) { log("[reports] none published."); return { reports: [], moments: [], allowed: [] }; } @@ -865,8 +909,8 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo // Each report's exports (publish/reportExports.ts), made from the report // as it is now and small enough to publish; the citations as files always. const exportsOf = new Map<string, PublishableReportExports>(); - for (const id of site.pages ?? []) { - const found = await publishableReportExports(paths, site.siteId, id); + for (const id of host.published) { + const found = await publishableStoreExports(host, id); exportsOf.set(id, found); for (const note of found.notes) log(`[reports] ${id}: ${note}`); } @@ -874,12 +918,12 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo // anything is written; a report never exported has none. const histories = new Map<string, { view: ReportHistoryView; ref: ReportHistoryRef; gitDir: string }>(); const historyProblems: ComposeReportsProblem[] = []; - for (const id of site.pages ?? []) { - const gitDir = reportHistoryGitDir(paths, site.siteId, id); + for (const id of host.published) { + const gitDir = storeHistoryGitDir(host, id); try { - const view = await readReportHistoryView(gitDir, { reportId: id, siteUrl: site.siteUrl }); + const view = await readReportHistoryView(gitDir, { reportId: id, siteUrl: host.siteUrl, base }); if (!view) continue; - const ref = reportHistoryRef(view, await reportFileSha256(paths, site.siteId, id)); + const ref = reportHistoryRef(view, await storeReportFileSha256(host, id), base); if (!ref.current) log(`[reports] ${id}: report.json changed since revision ${ref.revision} — export again to commit it`); histories.set(id, { view, ref, gitDir }); } catch (e) { @@ -890,38 +934,38 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo }); } } - if (historyProblems.length > 0) throw new ComposeReportsError(historyProblems); + if (historyProblems.length > 0) throw new ComposeReportsError(historyProblems, composedReportsNoun(host)); // A timeline's feeds link absolutely: a site with no public URL publishes none. - const siteUrl = parseSiteUrl(site.siteUrl); - const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveSiteReports({ + const siteUrl = host.siteUrl; + const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveReports({ ...opts, history: (id) => histories.get(id)?.ref, - feeds: siteUrl ? (id) => reportFeedUrls(siteUrl, id) : undefined, + feeds: siteUrl ? (id) => reportFeedUrls(siteUrl, id, base) : undefined, downloads: (id) => ({ ...Object.fromEntries( - REPORT_EXPORT_FORMATS.filter((f) => exportsOf.get(id)?.files[f]).map((f) => [f, reportExportDownloadPath(id, f)]), + REPORT_EXPORT_FORMATS.filter((f) => exportsOf.get(id)?.files[f]).map((f) => [f, reportExportDownloadPath(id, f, base)]), ), - json: reportCitationsDownloadPath(id, "json"), - csv: reportCitationsDownloadPath(id, "csv"), + json: reportCitationsDownloadPath(id, "json", base), + csv: reportCitationsDownloadPath(id, "csv", base), }), }); // ─── Writing ─── - await writeOut(publicDir, REPORTS_INDEX_PATH, json(index)); + await writeOut(publicDir, reportsIndexPath(base), json(index)); for (let i = 0; i < reports.length; i++) { const report = reports[i]; const view = views[i]; - await writeOut(publicDir, reportViewPath(report.id), json(view)); - await writeOut(publicDir, reportCitationsDownloadPath(report.id, "json"), json(citationSet(report, view))); - await writeOut(publicDir, reportCitationsDownloadPath(report.id, "csv"), citationsCsv(view)); + await writeOut(publicDir, reportViewPath(report.id, base), json(view)); + await writeOut(publicDir, reportCitationsDownloadPath(report.id, "json", base), json(citationSet(report, view))); + await writeOut(publicDir, reportCitationsDownloadPath(report.id, "csv", base), citationsCsv(view)); if (siteUrl && view.feeds) { - await writeOut(publicDir, reportFeedPath(report.id, "rss"), renderReportRss(view, { siteUrl })); - await writeOut(publicDir, reportFeedPath(report.id, "json"), json(renderReportJsonFeed(view, { siteUrl }))); + await writeOut(publicDir, reportFeedPath(report.id, "rss", base), renderReportRss(view, { siteUrl, base })); + await writeOut(publicDir, reportFeedPath(report.id, "json", base), json(renderReportJsonFeed(view, { siteUrl, base }))); log(`[reports] ${report.id}: feeds of ${view.entries?.length ?? 0} timeline entr${view.entries?.length === 1 ? "y" : "ies"}.`); } if (report.video && view.video) { - const dir = siteReportDir(paths, site.siteId, report.id); + const dir = storeReportDir(host, report.id); await copyOut(publicDir, path.join(dir, report.video.src), view.video.src); if (report.video.poster && view.video.poster) { await copyOut(publicDir, path.join(dir, report.video.poster), view.video.poster); @@ -930,16 +974,16 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo for (const c of orderedCitations(view)) { if (c.kind !== "source" || !c.image) continue; const rel = (report.citations![c.id] as { image: string }).image; - await copyOut(publicDir, path.join(siteReportDir(paths, site.siteId, report.id), rel), c.image); + await copyOut(publicDir, path.join(storeReportDir(host, report.id), rel), c.image); } const exported = exportsOf.get(report.id)?.files ?? {}; for (const f of REPORT_EXPORT_FORMATS) { const src = exported[f]; - if (src) await copyOut(publicDir, src, reportExportDownloadPath(report.id, f)); + if (src) await copyOut(publicDir, src, reportExportDownloadPath(report.id, f, base)); } const history = histories.get(report.id); if (history) { - const files = await publishReportHistory({ gitDir: history.gitDir, publicDir, view: history.view }); + const files = await publishReportHistory({ gitDir: history.gitDir, publicDir, view: history.view, base }); log(`[reports] ${report.id}: revision ${history.ref.revision}, history published (${files.length} repository files).`); } } @@ -987,12 +1031,15 @@ const defined = <T extends object>(o: T): T => // The site-root routes the reports add to a sitemap: each page (and its // history page, when it has one), each moment page. A site has no index of -// its pages (its header links each one). -export function reportRoutes(composed: Pick<ComposedReports, "reports" | "moments" | "histories">): string[] { +// its pages (its header links each one); a host under another base names it. +export function reportRoutes( + composed: Pick<ComposedReports, "reports" | "moments" | "histories">, + base: ReportBase = SITE_REPORTS_BASE, +): string[] { if (composed.reports.length === 0) return []; const histories = new Set(composed.histories ?? []); return [ - ...composed.reports.flatMap((r) => (histories.has(r.id) ? [r.href, reportHistoryPagePath(r.id)] : [r.href])), + ...composed.reports.flatMap((r) => (histories.has(r.id) ? [r.href, reportHistoryPagePath(r.id, base)] : [r.href])), ...composed.moments.map((k) => momentPath(k)), ]; } diff --git a/common/publish/composeReportsArticles.test.ts b/common/publish/composeReportsArticles.test.ts @@ -0,0 +1,264 @@ +// The reports stage over the ARTICLES host (release 26 A2): the same resolver +// and writer a site's compose runs, fed the article store +// (transcripts/reports/, index.json, `audience`) and written into another +// output root — the homepage's public dir. A temp corpus only. +// +// - the whole corpus is citable (D4): a channel no site has is cited; +// - a public build carries only `audience: "public"` articles; a private one +// every published article, in index.json's order; +// - the post visibility rule holds by the build's audience; +// - a record links into the archive the host names for its channel, or +// nowhere; +// - export/public is not touched. +// +// Run with: node_modules/.bin/tsx --test publish/composeReportsArticles.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "compose-articles-")); +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"), +}); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { writePosts } = await import("../lib/posts-server"); +const { setPublished, configureArticle, articleDir } = await import("../lib/report/registry"); +const { articlesReportHost, articleNotInCorpusMessage } = await import("./reportHost"); +const { composeHostReports, ComposeReportsError } = await import("./composeReports"); +const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION, storeMediaDir, storeMediaIndexFile } = await import("./reportMedia"); + +const paths = getPaths(); +const OUT = path.join(ROOT, "homepage-public"); +const LONE = "lone-channel"; +const X = "x-posts"; +const X_PRIVATE = { social: { x: { visibility: "private" } } }; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const readJson = <T = Record<string, unknown>>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T; + +function filesUnder(dir: string): string[] { + const out: string[] = []; + const walk = (d: string, rel: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const r = rel ? `${rel}/${e.name}` : e.name; + if (e.isDirectory()) walk(path.join(d, e.name), r); + else out.push(r); + } + }; + if (existsSync(dir)) walk(dir, ""); + return out.sort(); +} + +const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23); +const vtt = (cues: [number, number, string][]) => + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + cues.map(([a, b, text]) => `${ts(a)} --> ${ts(b)} align:start position:0%\n${text}<${ts(a)}><c></c>\n`).join("\n"); + +const SPAN = { kind: "video", channel: LONE, id: "abc123", start: 10, end: 20, quote: "The bridge opened in the spring, I was there for it." }; +const POST = { kind: "post", channel: X, id: "1800", quote: "Posted to settle it" }; + +function article(id: string, citations: Record<string, unknown>, over: Record<string, unknown> = {}) { + const cited = Object.keys(citations).map((c) => `[${c}](cite:${c})`).join(", "); + return { + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "What was said", body: `It was said: ${cited}.` }], + citations, + ...over, + }; +} + +function seedArticle(id: string, citations: Record<string, unknown>, over: Record<string, unknown> = {}) { + writeJson(path.join(articleDir(paths, id), "report.json"), article(id, citations, over)); +} + +async function seed() { + writeJson(paths.settingsFile, {}); + // A channel no site has: an article may cite it (D4). + writeJson(path.join(paths.channelsDir, LONE, "config.json"), { + handling: "youtube", + name: "Lone Channel", + url: "https://www.youtube.com/@lone/videos", + }); + const abc = path.join(paths.channelsDir, LONE, "data", "abc123"); + writeJson(path.join(abc, "metadata.info.json"), { + id: "abc123", + title: "A lone stream", + channel: LONE, + upload_date: "20260110", + duration: 600, + webpage_url: "https://www.youtube.com/watch?v=abc123", + extractor_key: "Youtube", + }); + writeFileSync( + path.join(abc, "transcript.en.vtt"), + vtt([ + [6, 10, "Let me be clear about this one."], + [10, 15, "The bridge opened in the spring,"], + [15, 20, "I was there for it."], + [20, 30, "Anyway, back to the mail."], + ]), + ); + // An X channel: its posts are private while `social.x.visibility` is. + writeJson(path.join(paths.channelsDir, X, "config.json"), { + handling: "youtube", + name: "Some X account", + url: "https://x.com/someone", + sourceKind: "social", + platform: "twitter", + socialHandle: "someone", + }); + await writePosts(path.join(paths.channelsDir, X), [ + { + id: "1800", + slug: `${X}/1800`, + channelSlug: X, + author: "someone", + authorName: "Someone", + createdAt: "2025-03-14T12:00:00.000Z", + uploadDate: "20250314", + text: "Posted to settle it. The bridge was open before I got there.", + url: "https://x.com/someone/status/1800", + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }, + ]); + + seedArticle("art-pub", { c01: SPAN }); + seedArticle("art-priv", { p01: POST }); + seedArticle("art-draft", { c01: SPAN }); + await setPublished("art-priv", true, {}, paths); + await configureArticle("art-pub", { published: true, audience: "public" }, paths); + + // What `archilyzer reports prepare --article` leaves. + const media = storeMediaDir({ stagingDir: path.join(paths.exportIndexDir, "articles") }); + const hash = "0".repeat(31) + "1"; + writeFileSync(path.join((mkdirSync(media, { recursive: true }), media), `${hash}.mp4`), "video-bytes"); + writeJson(path.join(media, `${hash}.json`), { span: { from: 10, to: 20 } }); + mkdirSync(path.join(media, "posts", X, "1800"), { recursive: true }); + writeFileSync(path.join(media, "posts", X, "1800", "shot.png"), "shot"); + writeJson(storeMediaIndexFile({ stagingDir: path.join(paths.exportIndexDir, "articles") }), { + format: REPORT_MEDIA_FORMAT, + version: REPORT_MEDIA_VERSION, + siteId: "articles", + preparedAt: "2026-10-11T00:00:00.000Z", + moments: { + [`${LONE}/abc123/10.00-20.00`]: { kind: "video", file: `${hash}.mp4`, bytes: 11, sha256: "f".repeat(64), width: null, height: null, durationSec: 15 }, + [`${X}/1800`]: { kind: "post", file: `posts/${X}/1800/shot.png`, bytes: 4, sha256: "e".repeat(64), width: null, height: null, durationSec: null, media: [] }, + }, + problems: [], + }); +} + +await seed(); + +const quiet = { log: () => {} }; + +test("a private build: every published article in index.json's order, any corpus channel, posts by its audience", async () => { + const host = await articlesReportHost(paths, { audience: "private" }); + assert.deepEqual(host.published, ["art-priv", "art-pub"]); + const composed = await composeHostReports({ paths, host, publicDir: OUT, settings: X_PRIVATE, ...quiet }); + assert.deepEqual(composed.reports.map((r) => r.id), ["art-priv", "art-pub"]); + assert.deepEqual(composed.moments, [`${LONE}/abc123/10.00-20.00`, `${X}/1800`]); + const index = readJson<{ reports: { id: string }[] }>(path.join(OUT, "articles", "index.json")); + assert.deepEqual(index.reports.map((r) => r.id), ["art-priv", "art-pub"]); + // Served under the homepage's base: every href and published path is /articles/. + const page = readJson<{ id: string }>(path.join(OUT, "articles", "art-priv", "page.json")); + assert.equal(page.id, "art-priv"); + assert.deepEqual( + readJson<{ reports: { href: string }[] }>(path.join(OUT, "articles", "index.json")).reports.map((r) => r.href), + ["/articles/art-priv/", "/articles/art-pub/"], + ); + assert.ok( + readJson<{ citedIn: { href: string }[] }>(path.join(OUT, "m", LONE, "abc123", "10.00-20.00", "moment.json")).citedIn.every((e) => + e.href.startsWith("/articles/"), + ), + ); + assert.equal(existsSync(path.join(OUT, "pages")), false); + assert.ok(existsSync(path.join(OUT, "media", "clips", LONE, "abc123", "10.00-20.00.mp4"))); + assert.ok(existsSync(path.join(OUT, "media", "posts", X, "1800", "shot.png"))); + // The draft is not published. + assert.equal(existsSync(path.join(OUT, "articles", "art-draft")), false); + // No archive named for the channel: the record links nowhere. + const moment = readJson<{ record: { corpusUrl?: string } }>(path.join(OUT, "m", LONE, "abc123", "10.00-20.00", "moment.json")); + assert.equal(moment.record.corpusUrl, undefined); + // Feeds and history use the homepage's base (PROJECT_URL by default). + assert.equal(host.siteUrl, "https://archilyzer.pages.dev"); + // export/public is not this stage's output root here. + assert.equal(existsSync(path.join(paths.exportPublicDir, "articles")), false); +}); + +test("a public build: only public articles; a record links into the listed site that publishes its channel", async () => { + const host = await articlesReportHost(paths, { + audience: "public", + channelSiteUrl: (slug) => (slug === LONE ? "https://lone.example.test/" : undefined), + }); + assert.deepEqual(host.published, ["art-pub"]); + const composed = await composeHostReports({ paths, host, publicDir: OUT, settings: X_PRIVATE, ...quiet }); + assert.deepEqual(composed.reports.map((r) => r.id), ["art-pub"]); + // The earlier build's output is gone, the private article's post with it. + assert.deepEqual( + filesUnder(OUT).filter((f) => !f.startsWith("articles/art-pub/")), + ["articles/index.json", "m/index.json", `m/${LONE}/abc123/10.00-20.00/moment.json`, `media/clips/${LONE}/abc123/10.00-20.00.mp4`], + ); + const moment = readJson<{ record: { corpusUrl?: string } }>(path.join(OUT, "m", LONE, "abc123", "10.00-20.00", "moment.json")); + assert.equal(moment.record.corpusUrl, `https://lone.example.test/?v=${encodeURIComponent(`${LONE}/abc123`)}&t=10`); +}); + +test("refused: an X post in a public build, a channel the corpus does not have", async () => { + seedArticle("art-pub", { c01: SPAN, p01: POST }, { audience: "public" }); + seedArticle("art-priv", { p01: POST, c09: { ...SPAN, channel: "no-such-channel" } }); + try { + const pub = await articlesReportHost(paths, { audience: "public" }); + await assert.rejects(composeHostReports({ paths, host: pub, publicDir: OUT, settings: X_PRIVATE, ...quiet }), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.citation, p.message]), + [["not-visible", "art-pub#p01", `the articles may not carry posts of "${X}" (the post visibility rule)`]], + ); + return true; + }); + // With X posts public, the same build carries the post. + await composeHostReports({ paths, host: pub, publicDir: OUT, settings: {}, ...quiet }); + assert.ok(existsSync(path.join(OUT, "m", X, "1800", "moment.json"))); + + const priv = await articlesReportHost(paths, { audience: "private" }); + await assert.rejects(composeHostReports({ paths, host: priv, publicDir: OUT, settings: X_PRIVATE, ...quiet }), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.citation, p.message]), + [["not-in-site", "art-priv#c09", articleNotInCorpusMessage("no-such-channel")]], + ); + return true; + }); + } finally { + seedArticle("art-pub", { c01: SPAN }, { audience: "public" }); + seedArticle("art-priv", { p01: POST }); + } +}); + +test("nothing published: the stage writes nothing and clears the output root's reports", async () => { + const host = await articlesReportHost(paths, { audience: "public", published: [] }); + const composed = await composeHostReports({ paths, host, publicDir: OUT, ...quiet }); + assert.deepEqual(composed, { reports: [], moments: [], allowed: [] }); + assert.deepEqual(filesUnder(OUT), []); +}); diff --git a/common/publish/reportExportFiles.ts b/common/publish/reportExportFiles.ts @@ -22,22 +22,31 @@ import { readJsonFile } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; import type { ReportExportFooter } from "../lib/report/exportHtml"; import { REPORT_EXPORT_FILENAMES, REPORT_EXPORT_FORMATS, type ReportExportFormat } from "../lib/report/views"; -import { siteIndexDir } from "../lib/site"; -import { siteReportFile } from "./reportMedia"; +import { siteReportStore, storeReportFile, type ReportStore } from "../lib/report/store"; export const REPORT_EXPORTS_DIRNAME = "report-exports"; export const REPORT_EXPORT_MANIFEST_FILENAME = "export.json"; export const REPORT_EXPORT_MANIFEST_FORMAT = "archilyzer-report-export"; export const REPORT_EXPORT_MANIFEST_VERSION = 1; +// `<staging>/report-exports/` of any store (lib/report/store.ts): a site's +// `.export-index/sites/<siteId>/`, the articles' `.export-index/articles/`. +export function storeExportsDir(store: Pick<ReportStore, "stagingDir">): string { + return path.join(store.stagingDir, REPORT_EXPORTS_DIRNAME); +} + +export function storeExportDir(store: Pick<ReportStore, "stagingDir">, reportId: string): string { + return path.join(storeExportsDir(store), reportId); +} + // `.export-index/sites/<siteId>/report-exports/`. export function reportExportsDir(paths: Paths, siteId: string): string { - return path.join(siteIndexDir(paths, siteId), REPORT_EXPORTS_DIRNAME); + return storeExportsDir(siteReportStore(paths, siteId)); } // `.export-index/sites/<siteId>/report-exports/<reportId>/`. export function reportExportDir(paths: Paths, siteId: string, reportId: string): string { - return path.join(reportExportsDir(paths, siteId), reportId); + return storeExportDir(siteReportStore(paths, siteId), reportId); } export type ReportExportFileEntry = { @@ -79,8 +88,12 @@ export function sha256Hex(data: string | Uint8Array): string { // The sha256 of a report.json as it is on disk, or null when it is unreadable. export async function reportFileSha256(paths: Paths, siteId: string, reportId: string): Promise<string | null> { + return storeReportFileSha256(siteReportStore(paths, siteId), reportId); +} + +export async function storeReportFileSha256(store: Pick<ReportStore, "reportsDir">, reportId: string): Promise<string | null> { try { - return sha256Hex(await readFile(siteReportFile(paths, siteId, reportId))); + return sha256Hex(await readFile(storeReportFile(store, reportId))); } catch { return null; } @@ -91,7 +104,14 @@ export async function readReportExportManifest( siteId: string, reportId: string, ): Promise<ReportExportManifest | null> { - const read = await readJsonFile(path.join(reportExportDir(paths, siteId, reportId), REPORT_EXPORT_MANIFEST_FILENAME)); + return readStoreExportManifest(siteReportStore(paths, siteId), reportId); +} + +export async function readStoreExportManifest( + store: Pick<ReportStore, "stagingDir">, + reportId: string, +): Promise<ReportExportManifest | null> { + const read = await readJsonFile(path.join(storeExportDir(store, reportId), REPORT_EXPORT_MANIFEST_FILENAME)); if (!read.ok) return null; const v = read.value as Partial<ReportExportManifest> | null; if (!v || v.format !== REPORT_EXPORT_MANIFEST_FORMAT || v.version !== REPORT_EXPORT_MANIFEST_VERSION) return null; @@ -113,16 +133,23 @@ export async function publishableReportExports( siteId: string, reportId: string, ): Promise<PublishableReportExports> { - const manifest = await readReportExportManifest(paths, siteId, reportId); + return publishableStoreExports(siteReportStore(paths, siteId), reportId); +} + +export async function publishableStoreExports( + store: Pick<ReportStore, "stagingDir" | "reportsDir">, + reportId: string, +): Promise<PublishableReportExports> { + const manifest = await readStoreExportManifest(store, reportId); if (!manifest) return { files: {}, notes: [] }; - const current = await reportFileSha256(paths, siteId, reportId); + const current = await storeReportFileSha256(store, reportId); if (current !== manifest.reportSha256) { return { files: {}, notes: ["its exports were made from another version of report.json — export again; none are published"], }; } - const dir = reportExportDir(paths, siteId, reportId); + const dir = storeExportDir(store, reportId); const files: PublishableReportExports["files"] = {}; const notes: string[] = []; for (const f of REPORT_EXPORT_FORMATS) { diff --git a/common/publish/reportExports.ts b/common/publish/reportExports.ts @@ -84,6 +84,7 @@ import { type ReportPageView, type SpanCitationView, } from "../lib/report/views"; +import type { ReportBase } from "../lib/report/routes"; import { importPlaywright } from "../social/playwrightRuntime"; import { citationSet, @@ -91,24 +92,26 @@ import { clipPath, ComposeReportsError, formatComposeReportsProblems, - resolveSiteReports, + resolveReports, type ResolvedSiteReports, } from "./composeReports"; import { REPORT_EXPORT_MANIFEST_FILENAME, REPORT_EXPORT_MANIFEST_FORMAT, REPORT_EXPORT_MANIFEST_VERSION, - reportExportDir, - reportExportsDir, + storeExportDir, + storeExportsDir, sha256Hex, type ReportExportFileEntry, type ReportExportManifest, } from "./reportExportFiles"; -import { siteReportDir, siteReportFile, type ReportMediaIndex } from "./reportMedia"; +import type { ReportMediaIndex } from "./reportMedia"; +import { storeReportDir, storeReportFile } from "../lib/report/store"; +import { siteReportHost, type ReportHost } from "./reportHost"; import { commitReportRevision, pendingRevision, - reportHistoryGitDir, + storeHistoryGitDir, revisionExports, } from "./reportHistory"; @@ -138,9 +141,12 @@ export type PdfPrinter = { export type OpenPdfPrinter = () => Promise<PdfPrinter | { missing: string }>; export type ExportSiteReportsOptions = { - siteId: string; + // The site whose pages to export, or `host` (./reportHost.ts) — the + // articles: articlesReportHost. + siteId?: string; + host?: ReportHost; paths?: Paths; - // One published report; default every one. + // One report the host publishes; default every one. reportId?: string; // Default: all of REPORT_EXPORT_FORMATS. formats?: readonly ReportExportFormat[]; @@ -315,11 +321,11 @@ function within(base: string, rel: string): string | undefined { return f.startsWith(b + path.sep) ? f : undefined; } -function reportFiles(paths: Paths, siteId: string, view: ReportPageView, resolved: ResolvedSiteReports): ReportFiles { - const own = reportPagePath(view.id); +function reportFiles(host: ReportHost, view: ReportPageView, resolved: ResolvedSiteReports): ReportFiles { + const own = reportPagePath(view.id, host.base); return { local: (p) => { - if (p.startsWith(own)) return within(siteReportDir(paths, siteId, view.id), p.slice(own.length)); + if (p.startsWith(own)) return within(storeReportDir(host, view.id), p.slice(own.length)); if (p.startsWith("/media/")) return within(resolved.cacheDir, p.slice("/media/".length)); return undefined; }, @@ -335,8 +341,8 @@ function reportFiles(paths: Paths, siteId: string, view: ReportPageView, resolve // A site-root path's place in the evidence pack: the site's media under // media/, the report's own files (its stills) under media/report/. -function packPathOf(view: ReportPageView, sitePath: string): string | undefined { - const own = reportPagePath(view.id); +function packPathOf(view: ReportPageView, sitePath: string, base?: ReportBase): string | undefined { + const own = reportPagePath(view.id, base); if (sitePath.startsWith(own)) return `media/report/${sitePath.slice(own.length)}`; if (sitePath.startsWith("/media/")) return sitePath.slice(1); return undefined; @@ -371,7 +377,7 @@ async function buildEvidencePack(o: { report: Report; view: ReportPageView; files: ReportFiles; - site: Pick<Site, "siteId" | "siteUrl">; + site: Pick<Site, "siteId" | "siteUrl"> & { base?: ReportBase }; footer: ReportExportFooter; markdown: string; outFile: string; @@ -392,7 +398,7 @@ async function buildEvidencePack(o: { const images = new Map<string, string>(); for (const p of [...viewImagePaths(o.view), ...(o.slides ? slidesOnlyImagePaths(o.view) : [])]) { const local = o.files.local(p); - const rel = packPathOf(o.view, p); + const rel = packPathOf(o.view, p, o.site.base); if (!local || !rel) continue; const data = await readFile(local).catch(() => null); if (!data) continue; @@ -404,7 +410,7 @@ async function buildEvidencePack(o: { if (c.kind !== "video" && c.kind !== "audio") continue; const clip = o.files.clip(c); if (!clip || clips.has(c.moment)) continue; - const rel = packPathOf(o.view, clip.sitePath); + const rel = packPathOf(o.view, clip.sitePath, o.site.base); const data = rel ? await readFile(clip.file).catch(() => null) : null; if (!rel || !data) continue; await put(rel, data); @@ -412,6 +418,7 @@ async function buildEvidencePack(o: { } const html = reportExportHtml(o.view, { siteUrl: o.site.siteUrl || undefined, + base: o.site.base, footer: o.footer, image: (p) => images.get(p), clip: (c) => clips.get(c.moment), @@ -423,6 +430,7 @@ async function buildEvidencePack(o: { reportSlidesHtml(o.view, { ...o.slides, siteUrl: o.site.siteUrl || undefined, + base: o.site.base, footer: o.footer, image: (p) => images.get(p), }), @@ -443,7 +451,7 @@ async function buildEvidencePack(o: { async function exportOneReport(o: { paths: Paths; - site: Site; + host: ReportHost; report: Report; view: ReportPageView; resolved: ResolvedSiteReports; @@ -454,16 +462,17 @@ async function exportOneReport(o: { log: (line: string) => void; signal?: AbortSignal; }): Promise<{ result?: ReportExportResult; problems: ReportExportProblem[] }> { - const { paths, site, report, view } = o; - const reportJson = await readFile(siteReportFile(paths, site.siteId, report.id)).catch(() => null); + const { paths, host, report, view } = o; + const reportJson = await readFile(storeReportFile(host, report.id)).catch(() => null); if (!reportJson) return { problems: [{ report: report.id, message: "its report.json cannot be read" }] }; return writeReportExports({ ...o, - dir: reportExportDir(paths, site.siteId, report.id), + site: { siteId: host.id, siteUrl: host.siteUrl, siteTitle: host.title, accent: host.accent, base: host.base }, + dir: storeExportDir(host, report.id), reportSha256: sha256Hex(reportJson), - files: reportFiles(paths, site.siteId, view, o.resolved), + files: reportFiles(host, view, o.resolved), ffmpegBin: paths.ffmpegBin, - history: { gitDir: reportHistoryGitDir(paths, site.siteId, report.id), reportJson }, + history: { gitDir: storeHistoryGitDir(host, report.id), reportJson }, }); } @@ -477,7 +486,9 @@ async function exportOneReport(o: { // changed report.json is committed as the next one. export async function writeReportExports(o: { dir: string; - site: Pick<Site, "siteId" | "siteUrl" | "siteTitle"> & { accent?: unknown }; + // `base`: where the build serves these reports (lib/report/routes.ts); a + // site's by default. + site: Pick<Site, "siteId" | "siteUrl" | "siteTitle"> & { accent?: unknown; base?: ReportBase }; report: Report; view: ReportPageView; reportSha256: string; @@ -518,6 +529,7 @@ export async function writeReportExports(o: { } const htmlOpts = { siteUrl, + base: site.base, footer, image: (p: string) => dataUris.get(p), clip: (c: SpanCitationView) => { @@ -541,12 +553,12 @@ export async function writeReportExports(o: { } } const slidesHtml = slidesLook - ? reportSlidesHtml(view, { ...slidesLook, siteUrl, footer, image: (p) => dataUris.get(p) }) + ? reportSlidesHtml(view, { ...slidesLook, siteUrl, base: site.base, footer, image: (p) => dataUris.get(p) }) : undefined; // The PDF prints what the page folds away (the evidence the document under // review gave itself) open. const printHtml = reportExportHtml(view, { ...htmlOpts, print: true }); - const markdown = reportExportMarkdown(view, { siteUrl, footer }); + const markdown = reportExportMarkdown(view, { siteUrl, base: site.base, footer }); const dir = o.dir; await rm(dir, { recursive: true, force: true }); @@ -687,20 +699,29 @@ export async function writeReportExports(o: { export async function exportSiteReports(opts: ExportSiteReportsOptions): Promise<ExportSiteReportsResult> { const paths = opts.paths ?? getPaths(); const log = opts.onLog ?? (() => {}); - const { siteId } = opts; - if (!listSiteIds(paths).includes(siteId)) throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); - const site = getSite(siteId, paths); - const published = site.pages ?? []; + let host: ReportHost; + if (opts.host) { + host = opts.host; + } else { + const siteId = opts.siteId; + if (!siteId || !listSiteIds(paths).includes(siteId)) throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); + host = siteReportHost(paths, getSite(siteId, paths)); + } + const published = host.published; if (opts.reportId && !published.includes(opts.reportId)) { - throw new Error(`site "${siteId}" does not publish a report "${opts.reportId}" (only a published report is exported)`); + throw new Error( + host.kind === "site" + ? `site "${host.id}" does not publish a report "${opts.reportId}" (only a published report is exported)` + : `article "${opts.reportId}" is not one this run exports`, + ); } const formats = opts.formats ?? REPORT_EXPORT_FORMATS; let resolved: ResolvedSiteReports; try { - resolved = await resolveSiteReports({ + resolved = await resolveReports({ paths, - site, + host, allowMissingMedia: opts.allowMissingMedia, settings: opts.settings, now: opts.now, @@ -718,8 +739,8 @@ export async function exportSiteReports(opts: ExportSiteReportsOptions): Promise // A report no longer published keeps no exports. if (!opts.reportId) { - for (const name of await readdir(reportExportsDir(paths, siteId)).catch(() => [] as string[])) { - if (!published.includes(name)) await rm(path.join(reportExportsDir(paths, siteId), name), { recursive: true, force: true }); + for (const name of await readdir(storeExportsDir(host)).catch(() => [] as string[])) { + if (!published.includes(name)) await rm(path.join(storeExportsDir(host), name), { recursive: true, force: true }); } } @@ -729,7 +750,7 @@ export async function exportSiteReports(opts: ExportSiteReportsOptions): Promise const now = opts.now?.() ?? new Date(); const exported: ReportExportResult[] = []; const problems: ReportExportProblem[] = []; - log(`${siteId}: exporting ${opts.reportId ?? `${resolved.reports.length} report(s)`} as ${formats.join(", ")}.`); + log(`${host.id}: exporting ${opts.reportId ?? `${resolved.reports.length} report(s)`} as ${formats.join(", ")}.`); try { for (let i = 0; i < resolved.reports.length; i++) { const report = resolved.reports[i]; @@ -737,7 +758,7 @@ export async function exportSiteReports(opts: ExportSiteReportsOptions): Promise if (opts.signal?.aborted) throw new Error("export cancelled"); const r = await exportOneReport({ paths, - site, + host, report, view: resolved.views[i], resolved, diff --git a/common/publish/reportHistory.ts b/common/publish/reportHistory.ts @@ -68,10 +68,12 @@ import { type ReportHistoryView, type ReportRevisionView, } from "../lib/report/revisions"; +import { SITE_REPORTS_BASE, type ReportBase } from "../lib/report/routes"; import { cleanGitEnv } from "./sourceAudit"; export { REPORT_HISTORY_REPO_FILE_RE }; import { siteReportDir } from "./reportMedia"; +import { storeReportDir, type ReportStore } from "../lib/report/store"; export const REPORT_HISTORY_GIT_DIRNAME = "history-git"; export const REVISION_EXPORTS_FILENAME = "exports.json"; @@ -88,6 +90,12 @@ export function reportHistoryGitDir(paths: Paths, siteId: string, reportId: stri return path.join(siteReportDir(paths, siteId, reportId), REPORT_HISTORY_GIT_DIRNAME); } +// `<report dir>/history-git/` in any store (lib/report/store.ts): an article's +// is `reports/<reportId>/history-git/`. +export function storeHistoryGitDir(store: Pick<ReportStore, "reportsDir">, reportId: string): string { + return path.join(storeReportDir(store, reportId), REPORT_HISTORY_GIT_DIRNAME); +} + // ─── git, with nothing of the operator's ─── export type HistoryIdentity = { name: string; email: string }; @@ -352,7 +360,9 @@ function emptyReport(like: Report): Report { // no revisions. `clone` is what `git clone` takes. export async function readReportHistoryView( gitDir: string, - o: { reportId: string; siteUrl?: string }, + // `base`: where the build serves its reports (lib/report/routes.ts); a + // site's by default. + o: { reportId: string; siteUrl?: string; base?: ReportBase }, ): Promise<ReportHistoryView | null> { const stored = await readStoredRevisions(gitDir); if (stored.length === 0) return null; @@ -373,7 +383,7 @@ export async function readReportHistoryView( prev = report; } const base = o.siteUrl?.trim().replace(/\/+$/, ""); - const repo = reportHistoryRepoPath(o.reportId); + const repo = reportHistoryRepoPath(o.reportId, o.base); return { format: REPORT_HISTORY_FORMAT, version: REPORT_HISTORY_VERSION, @@ -388,12 +398,16 @@ export async function readReportHistoryView( // What the report's page shows: the newest revision, current when the // report.json now is that revision's. -export function reportHistoryRef(view: ReportHistoryView, currentSha256: string | null): ReportHistoryRef { +export function reportHistoryRef( + view: ReportHistoryView, + currentSha256: string | null, + base: ReportBase = SITE_REPORTS_BASE, +): ReportHistoryRef { const last = view.revisions[view.revisions.length - 1]; return { revision: last.revision, date: last.date, - href: reportHistoryPagePath(view.reportId), + href: reportHistoryPagePath(view.reportId, base), current: currentSha256 === last.reportSha256, }; } @@ -450,16 +464,18 @@ export async function stageReportHistoryRepo(gitDir: string, destDir: string): P } // Publish a report's history under `publicDir`: history.json and the clone, -// at `reports/<id>/history/`. Answers the clone's files. +// at `<base><id>/history/` (a site's `pages/<id>/history/`). Answers the +// clone's files. export async function publishReportHistory(o: { gitDir: string; publicDir: string; view: ReportHistoryView; + base?: ReportBase; }): Promise<string[]> { - const viewFile = path.join(o.publicDir, ...reportHistoryViewPath(o.view.reportId).split("/").filter(Boolean)); + const viewFile = path.join(o.publicDir, ...reportHistoryViewPath(o.view.reportId, o.base).split("/").filter(Boolean)); await mkdir(path.dirname(viewFile), { recursive: true }); await writeFile(viewFile, `${JSON.stringify(o.view, null, 2)}\n`); - const repoDir = path.join(o.publicDir, ...reportHistoryRepoPath(o.view.reportId).split("/").filter(Boolean)); + const repoDir = path.join(o.publicDir, ...reportHistoryRepoPath(o.view.reportId, o.base).split("/").filter(Boolean)); return stageReportHistoryRepo(o.gitDir, repoDir); } diff --git a/common/publish/reportHost.ts b/common/publish/reportHost.ts @@ -0,0 +1,171 @@ +// WHO PUBLISHES A SET OF REPORTS — the one thing the reports stage +// (./composeReports.ts), prepare (./reportMedia.ts), export +// (./reportExports.ts) and check (bin/reports-check.ts) need to know about +// whoever publishes the reports they work on (release 26, +// plans/reports-on-homepage.md, "The model"): +// +// a SITE (its pages) the ARTICLES (the homepage) +// files sites/<id>/reports/<r>/ reports/<r>/ +// published site.json `pages` reports/index.json, narrowed +// to `audience: "public"` for a +// public build +// may cite its `channels` + `citedChannels` any channel in the corpus (D4) +// posts the visibility rule, by the the same rule, by the +// site's audience build's audience +// corpus link its own corpus, relative (none the listed public site that +// on a cited site or for a publishes the channel, +// cited-only channel) absolute; none without one +// served under /pages/<r>/ /articles/<r>/ +// staging .export-index/sites/<id>/ .export-index/articles/ +// history identity the site's title, PROJECT_NAME, +// noreply@<id>.invalid noreply@articles.invalid +// +// A host is built once per run and carries no I/O of its own but the +// articles' corpus check (a channel directory exists). + +import { existsSync, statSync } from "node:fs"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { PROJECT_NAME, PROJECT_URL } from "../lib/project"; +import { + isCitedOnlyChannel, + isCitedSite, + isPrivateSite, + notInSiteMessage, + parseSiteUrl, + siteCitableChannelSlugs, + type Site, +} from "../lib/siteSchema"; +import { publishedArticleIds } from "../lib/report/registry"; +import { ARTICLES_REPORTS_BASE, SITE_REPORTS_BASE, type ReportBase } from "../lib/report/routes"; +import { isReportId, type ReportAudience } from "../lib/report/schema"; +import { articleReportStore, siteReportStore, storeReportFile, type ReportStore } from "../lib/report/store"; + +export type ReportHost = ReportStore & { + // Where the build serves these reports (lib/report/routes.ts): a site's + // `/pages/`, the homepage's `/articles/`. Every published path and href of + // theirs hangs off it. + base: ReportBase; + // A history commit's author (./reportHistory.ts) and an export's heading. + title: string; + // The public base a feed, an export's links and the history clone use + // (absolute, no trailing slash), or undefined: none. + siteUrl?: string; + // The site's accent (slides), when it has one. + accent?: unknown; + // Whose post-visibility rule applies (lib/postsVisibility.ts). + audience: ReportAudience; + // The published reports, in order. + published: readonly string[]; + // How a message names the list: `the site lists report "x"`. + listedBy: (reportId: string) => string; + // Why a channel may not be cited here, or null when it may. + citableProblem: (slug: string) => string | null; + // Where a moment's record opens in an archive: "" (this site's own corpus, + // a site-root link), an absolute archive base, or null (no link). + corpusBase: (slug: string) => string | null; + // The site, for a site host. + site?: Site; +}; + +// A site's pages. +export function siteReportHost(paths: Pick<Paths, "sitesDir" | "exportSitesIndexDir">, site: Site): ReportHost { + const citable = siteCitableChannelSlugs(site); + const cited = isCitedSite(site); + return { + ...siteReportStore(paths, site.siteId), + base: SITE_REPORTS_BASE, + title: site.siteTitle?.trim() || site.siteId, + siteUrl: parseSiteUrl(site.siteUrl), + accent: site.accent, + audience: isPrivateSite(site) ? "private" : "public", + published: site.pages ?? [], + listedBy: (id) => `the site lists report "${id}"`, + citableProblem: (slug) => (citable.has(slug) ? null : notInSiteMessage(slug)), + // No corpus page to link a moment to: a cited site publishes none, and a + // cited-only channel (`citedChannels`) is not in the site's corpus. + corpusBase: (slug) => (cited || isCitedOnlyChannel(site, slug) ? null : ""), + site, + }; +} + +export type ArticlesHostOptions = { + // The build's audience: "public" carries only `audience: "public"` articles, + // "private" every published one. Default "private". + audience?: ReportAudience; + // The homepage's public base. Default PROJECT_URL; null = none. + siteUrl?: string | null; + // channel slug → the base URL of the listed public site that publishes it + // (the homepage's `channel-sites.json` with each site's `siteUrl`); a + // moment of a channel it does not answer for gets no archive link. + channelSiteUrl?: (slug: string) => string | undefined; + // The published ids, when the caller has them (a check of named drafts); + // default index.json narrowed to the audience. + published?: readonly string[]; +}; + +export function articleNotInCorpusMessage(slug: string): string { + return `channel "${slug}" is not a channel of the corpus (no channels/${slug}/)`; +} + +// The articles, as the homepage publishes them. +export async function articlesReportHost( + paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "channelsDir">, + opts: ArticlesHostOptions = {}, +): Promise<ReportHost> { + const audience = opts.audience ?? "private"; + const isChannel = new Map<string, boolean>(); + return { + ...articleReportStore(paths), + base: ARTICLES_REPORTS_BASE, + title: PROJECT_NAME, + siteUrl: opts.siteUrl === null ? undefined : (parseSiteUrl(opts.siteUrl ?? PROJECT_URL) ?? undefined), + audience, + published: opts.published ?? (await publishedArticleIds(audience, paths)), + listedBy: (id) => `reports/index.json lists article "${id}"`, + citableProblem: (slug) => { + if (!isChannel.has(slug)) { + let dir = false; + try { + dir = /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) && statSync(path.join(paths.channelsDir, slug)).isDirectory(); + } catch { + dir = false; + } + isChannel.set(slug, dir); + } + return isChannel.get(slug) ? null : articleNotInCorpusMessage(slug); + }, + corpusBase: (slug) => parseSiteUrl(opts.channelSiteUrl?.(slug)) ?? null, + }; +} + +// A record's link into an archive: `<base>/?v=<slug>&…`, or undefined when +// the host has none for the channel. +export function hostCorpusLink(host: ReportHost, channel: string, params: Record<string, string>): string | undefined { + const base = host.corpusBase(channel); + if (base === null) return undefined; + return `${base}/?${new URLSearchParams(params).toString()}`; +} + +// The articles as the tools that WORK on them see them — prepare, export, +// check, the editor's Articles tab: every published article (the private +// build's set, which holds the public one's), plus each id in `include` that +// is not published yet (a draft being readied). Its prepared media and +// exports therefore serve both homepage builds. An included id with no +// report.json is refused. +export async function articlesWorkHost( + paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "channelsDir">, + include: readonly string[] = [], +): Promise<ReportHost> { + for (const id of include) { + if (!isReportId(id)) throw new Error(`"${id}" is not an article id`); + if (!existsSync(storeReportFile(articleReportStore(paths), id))) { + throw new Error(`no article "${id}" (no reports/${id}/report.json)`); + } + } + const published = await publishedArticleIds("private", paths); + return articlesReportHost(paths, { + audience: "private", + published: [...published, ...include.filter((id) => !published.includes(id))], + }); +} diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -48,15 +48,15 @@ import path from "node:path"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; +import { getSite, listSiteIds, type Site } from "../lib/site"; import { - getSite, - listSiteIds, - notInSiteMessage, - siteCitableChannelSlugs, - siteDir, - siteIndexDir, - type Site, -} from "../lib/site"; + siteReportStore, + storeReportDir, + storeReportFile, + storeReportLabel, + type ReportStore, +} from "../lib/report/store"; +import { siteReportHost, type ReportHost } from "./reportHost"; import { postsVisibleTo } from "../lib/postsVisibility"; import { inspectChannelMedia } from "../lib/channelMedia"; import type { ChannelConfig } from "../lib/channelConfig"; @@ -85,22 +85,33 @@ export const REPORT_MEDIA_VERSION = 1; export const REPORT_MEDIA_DIRNAME = "report-media"; export const REPORT_MEDIA_INDEX_FILENAME = "index.json"; -// `.export-index/sites/<siteId>/report-media/`: the prepared media, not served. +// `<staging>/report-media/`: the prepared media, not served — +// `.export-index/sites/<siteId>/` for a site, `.export-index/articles/` for +// the articles (lib/report/store.ts). +export function storeMediaDir(store: Pick<ReportStore, "stagingDir">): string { + return path.join(store.stagingDir, REPORT_MEDIA_DIRNAME); +} + +export function storeMediaIndexFile(store: Pick<ReportStore, "stagingDir">): string { + return path.join(storeMediaDir(store), REPORT_MEDIA_INDEX_FILENAME); +} + +// `.export-index/sites/<siteId>/report-media/`: a site's prepared media. export function reportMediaDir(paths: Paths, siteId: string): string { - return path.join(siteIndexDir(paths, siteId), REPORT_MEDIA_DIRNAME); + return storeMediaDir(siteReportStore(paths, siteId)); } export function reportMediaIndexFile(paths: Paths, siteId: string): string { - return path.join(reportMediaDir(paths, siteId), REPORT_MEDIA_INDEX_FILENAME); + return storeMediaIndexFile(siteReportStore(paths, siteId)); } // `sites/<siteId>/reports/<reportId>/`: a report's directory. export function siteReportDir(paths: Paths, siteId: string, reportId: string): string { - return path.join(siteDir(paths, siteId), "reports", reportId); + return storeReportDir(siteReportStore(paths, siteId), reportId); } export function siteReportFile(paths: Paths, siteId: string, reportId: string): string { - return path.join(siteReportDir(paths, siteId, reportId), "report.json"); + return storeReportFile(siteReportStore(paths, siteId), reportId); } // Every report directory of a site, published or draft: a directory under @@ -108,9 +119,14 @@ export function siteReportFile(paths: Paths, siteId: string, reportId: string): // stray file, a bad name) is not a report. Sorted. Whether one is PUBLISHED is // the site's `reports` list (site.json), not anything on disk. export async function listReportDirs(paths: Paths, siteId: string): Promise<string[]> { + return listStoreReportDirs(siteReportStore(paths, siteId)); +} + +// The same over any store (the articles: lib/report/registry.ts listArticleDirs). +export async function listStoreReportDirs(store: Pick<ReportStore, "reportsDir">): Promise<string[]> { let entries: Dirent[]; try { - entries = await readdir(path.join(siteDir(paths, siteId), "reports"), { withFileTypes: true }); + entries = await readdir(store.reportsDir, { withFileTypes: true }); } catch { return []; } @@ -159,6 +175,7 @@ export type ReportMediaProblem = { export type ReportMediaIndex = { format: typeof REPORT_MEDIA_FORMAT; version: typeof REPORT_MEDIA_VERSION; + // The site's id, or "articles" (the store's id, lib/report/store.ts). siteId: string; preparedAt: string; moments: Record<string, ReportMediaEntry>; @@ -183,10 +200,17 @@ export async function loadSiteReports( paths: Paths, site: Site, ): Promise<{ reports: Report[]; problems: ReportMediaProblem[] }> { + return loadHostReports(siteReportHost(paths, site)); +} + +// The same for any host (./reportHost.ts): its published reports, in order. +export async function loadHostReports( + host: Pick<ReportHost, "published" | "listedBy" | "reportsDir" | "label">, +): Promise<{ reports: Report[]; problems: ReportMediaProblem[] }> { const reports: Report[] = []; const problems: ReportMediaProblem[] = []; - for (const id of site.pages ?? []) { - const file = siteReportFile(paths, site.siteId, id); + for (const id of host.published) { + const file = storeReportFile(host, id); const read = await readJsonFile(file); if (!read.ok) { problems.push({ @@ -194,8 +218,8 @@ export async function loadSiteReports( report: id, message: read.reason === "absent" - ? `the site lists report "${id}", but sites/${site.siteId}/reports/${id}/report.json does not exist` - : `sites/${site.siteId}/reports/${id}/report.json is not readable JSON`, + ? `${host.listedBy(id)}, but ${storeReportLabel(host, id)} does not exist` + : `${storeReportLabel(host, id)} is not readable JSON`, }); continue; } @@ -233,7 +257,10 @@ export function citedMoments(reports: readonly Report[]): CitedMoment[] { } export type PrepareReportMediaOptions = { - siteId: string; + // The site whose pages to prepare, or `host` (./reportHost.ts) — the + // articles: articlesReportHost. + siteId?: string; + host?: ReportHost; paths?: Paths; onLog?: (line: string) => void; signal?: AbortSignal; @@ -247,20 +274,14 @@ const mib = (n: number) => `${(n / 1024 / 1024).toFixed(1)} MiB`; export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promise<ReportMediaIndex> { const paths = opts.paths ?? getPaths(); const log = opts.onLog ?? (() => {}); - const { siteId } = opts; - if (!listSiteIds(paths).includes(siteId)) { - throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); - } - const site = getSite(siteId, paths); + const host = opts.host ?? siteHostFor(paths, opts.siteId); const settings = opts.settings ?? getSettings(); - const cacheDir = reportMediaDir(paths, siteId); + const cacheDir = storeMediaDir(host); - const { reports, problems } = await loadSiteReports(paths, site); - log(`${siteId}: ${site.pages?.length ?? 0} published report(s), ${reports.length} readable.`); + const { reports, problems } = await loadHostReports(host); + log(`${host.id}: ${host.published.length} published report(s), ${reports.length} readable.`); const moments = citedMoments(reports); log(`${moments.length} cited moment(s) with media.`); - - const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug)); @@ -276,13 +297,14 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi for (const m of moments) { if (opts.signal?.aborted) throw new Error("prepare cancelled"); const slug = m.moment.channel; - if (!citable.has(slug)) { - fail(m, "not-in-site", notInSiteMessage(slug)); + const notCitable = host.citableProblem(slug); + if (notCitable) { + fail(m, "not-in-site", notCitable); continue; } const config = await configOf(slug); if (m.kind === "post") { - if (!postsVisibleTo(site, config, settings)) { + if (!postsVisibleTo(host, config, settings)) { fail(m, "not-visible", `this site may not carry posts of "${slug}" (the post visibility rule)`); continue; } @@ -346,12 +368,12 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi const index: ReportMediaIndex = { format: REPORT_MEDIA_FORMAT, version: REPORT_MEDIA_VERSION, - siteId, + siteId: host.id, preparedAt: (opts.now?.() ?? new Date()).toISOString(), moments: Object.fromEntries(Object.keys(entries).sort().map((k) => [k, entries[k]])), problems, }; - await writeJsonAtomic(reportMediaIndexFile(paths, siteId), index, { mkdir: true }); + await writeJsonAtomic(storeMediaIndexFile(host), index, { mkdir: true }); const bytes = Object.values(entries).reduce( (n, e) => n + e.bytes + (e.kind === "post" ? e.media.reduce((s, f) => s + f.bytes, 0) : 0), 0, @@ -394,7 +416,11 @@ export function formatReportMediaProblems(problems: readonly ReportMediaProblem[ // Read a prepared manifest, or null when there is none (never prepared, or // unreadable). export async function readReportMediaIndex(paths: Paths, siteId: string): Promise<ReportMediaIndex | null> { - const read = await readJsonFile(reportMediaIndexFile(paths, siteId)); + return readStoreMediaIndex(siteReportStore(paths, siteId)); +} + +export async function readStoreMediaIndex(store: Pick<ReportStore, "stagingDir">): Promise<ReportMediaIndex | null> { + const read = await readJsonFile(storeMediaIndexFile(store)); if (!read.ok) return null; const v = read.value as Partial<ReportMediaIndex> | null; if (!v || v.format !== REPORT_MEDIA_FORMAT || v.version !== REPORT_MEDIA_VERSION) return null; @@ -460,25 +486,21 @@ export type MissingEvidenceWindows = { const floor2 = (n: number) => Math.floor(n * 100 + 1e-6) / 100; const ceil2 = (n: number) => Math.ceil(n * 100 - 1e-6) / 100; -export async function missingEvidenceWindows(paths: Paths, siteId: string): Promise<MissingEvidenceWindows> { - if (!listSiteIds(paths).includes(siteId)) { - throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); - } - const site = getSite(siteId, paths); - const { reports, problems } = await loadSiteReports(paths, site); +export async function missingEvidenceWindows(paths: Paths, siteOrHost: string | ReportHost): Promise<MissingEvidenceWindows> { + const host = typeof siteOrHost === "string" ? siteHostFor(paths, siteOrHost) : siteOrHost; + const { reports, problems } = await loadHostReports(host); const quotes = new Map<string, string>(); for (const report of reports) { for (const [cid, c] of Object.entries(report.citations ?? {})) { if (typeof c.quote === "string" && c.quote.trim()) quotes.set(`${report.id}#${cid}`, c.quote.trim()); } } - const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug)); return configs.get(slug) ?? null; }; - const out: MissingEvidenceWindows = { siteId, missing: [], unfetchable: [], onDisk: 0, problems }; + const out: MissingEvidenceWindows = { siteId: host.id, missing: [], unfetchable: [], onDisk: 0, problems }; for (const m of citedMoments(reports)) { if (m.kind === "post" || m.moment.kind !== "span") continue; @@ -499,8 +521,9 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom const unfetchable = (why: UnfetchableReason, message: string) => out.unfetchable.push({ ...window, why, message }); - if (!citable.has(slug)) { - unfetchable("not-in-site", notInSiteMessage(slug)); + const notCitable = host.citableProblem(slug); + if (notCitable) { + unfetchable("not-in-site", notCitable); continue; } const config = await configOf(slug); @@ -542,3 +565,12 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom } return out; } + +// A site's host, or the refusal for a site that is not there. +function siteHostFor(paths: Paths, siteId: string | undefined): ReportHost { + if (!siteId) throw new Error("give a site id or a host"); + if (!listSiteIds(paths).includes(siteId)) { + throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); + } + return siteReportHost(paths, getSite(siteId, paths)); +} diff --git a/common/publish/reportVideo.ts b/common/publish/reportVideo.ts @@ -144,6 +144,11 @@ export type AttachVideoOptions = { ffprobeBin: string; limitBytes?: number; onLog?: (line: string) => void; + // Who writes `video` into report.json, once the files are in place; default + // a direct atomic rewrite of `reportFile`. An ARTICLE's goes through the + // article registry (lib/report/registry.ts patchArticle), which refuses a + // write that adds a problem. + setVideo?: (video: AttachedVideo["video"]) => Promise<void>; }; export type AttachedVideo = { @@ -244,8 +249,12 @@ export async function attachReportVideo(opts: AttachVideoOptions): Promise<Attac const first = videoProblems[0] ?? parsed.problems[0]; throw new AttachVideoError(`report.json would not validate with the video: ${first ? `${first.path}: ${first.message}` : "?"}`); } - const tmpJson = `${opts.reportFile}.${process.pid}.tmp`; - await writeFile(tmpJson, `${JSON.stringify(next, null, 2)}\n`); - await rename(tmpJson, opts.reportFile); + if (opts.setVideo) { + await opts.setVideo(video); + } else { + const tmpJson = `${opts.reportFile}.${process.pid}.tmp`; + await writeFile(tmpJson, `${JSON.stringify(next, null, 2)}\n`); + await rename(tmpJson, opts.reportFile); + } return { video, bytes, mode: plan.mode, attempts }; } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -150,6 +150,11 @@ - **A report video's cards can be narrated by a stock synthetic voice.** A card may carry `narration: {text, voice?, engine?}` — the author's words, never derived from the card — and `seconds: "auto"`, its words' length plus a lead and a tail; `render.narration` sets the engine and voice (Kokoro, `af_heart`, by default), speed, level (−17.7 LUFS, with the clips) and the quiet around the words. The voice is synthesized by the editor (`pnpm ops tts`), never by umtool: the build chain's new step, `narrate-via-editor.mjs`, asks for every narration not yet kept and keeps each in the project's `out/narration/`, and the build plays it under its card. A number of seconds shorter than the words need is a lint error. A narrated cut says "Narration: synthetic voice (Kokoro-82M · af_heart)" — the editor's own line — in its file's metadata and at the end of its description and chapters exports. Stock voices only; a manifest without narration builds exactly as before. - **A report video can be exported as a podcast.** The project page's export row has a **podcast** button per cut (`build-podcast.mjs <manifest>` on the command line): the built cut as sound only — the clips, the narrated cards and the teasers' hits, each silent card left out (`render.podcast.skipSilentCards`) — levelled to −16 LUFS, as `out/<variant>/podcast.m4a` and `podcast.mp3` with the video's chapter titles at the podcast's own times, and `show-notes.md`: the chapters, every cited source's link and, for a narrated cut, the disclosure line. It is made from the segments of the last build, so build the cut first. - **A report video's narration is reviewed card by card before it is synthesized.** umtool's project page links **Narration — N** when a card is narrated: each card's words beside what it shows on screen, its voice, **Approve**, **Reject** (with a note saying what is wrong), the words edited in place, and **Play** — the editor synthesizes that one card and it plays on the page. Verdicts are kept in `narration.review.json` beside the manifest, each on the words and voice it was given on, so new words or a new voice need approving again. Once that file exists a build refuses any narrated card not approved (`--narration-unreviewed` builds unreviewed and edited ones; a rejected one never); a narrated cut with no review at all builds as before, with a lint warning. The MCP's sweep plan now carries the rule for drafting narration: storytelling and emotion live in the delivery, never in the claims. +- **Articles: reports the homepage publishes, not a site.** An article is a report in `transcripts/reports/<id>/` (report.json and its siblings, as a site's report); `transcripts/reports/index.json` — `{"published": [ids]}` — is the published, ordered list, and an article's `audience` (`"public"` or `"private"`, private when absent) says which homepage build carries it. An article may cite any channel of the corpus. Both files are written only through the article registry (`common/lib/report/registry.ts`: locked across processes, validated, atomic) and `pnpm ops articles-config {"id", "audience"?, "published"?, "position"?}`, which refuses before writing anything: an unknown article, a position out of range or on a draft, publishing an article whose report.json has problems (listed). REPORT.md describes both stores. Needs a restart of the editor. +- **The editor's Articles tab.** `/sites/articles` (an **Articles** button on /sites) lists every article — published in order, then drafts — with its problems and audience: Publish, Unpublish, ↑/↓ and Make public / Make private write through the registry. Fetch missing evidence, Prepare evidence media and Export articles are the Reports tab's over the articles, on the same queue (`pnpm ops reports-prepare {"articles": true}`, `reports-export {"articles": true}`). A site's own pages stay on its Reports tab. Needs a restart of the editor. +- **`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`. ## [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/editor/app/api/ops/articles-config/route.test.ts b/editor/app/api/ops/articles-config/route.test.ts @@ -0,0 +1,87 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/articles-config/route.test.ts" +// +// `articles-config` (release 26 A2): an article's audience and its place in +// the published list (transcripts/reports/index.json), written through the +// article registry. Every refusal comes before anything is written. + +const corpus = await setupOpsCorpus(null); +const reports = path.join(corpus.transcripts, "reports"); +const article = (id: string, over: Record<string, unknown> = {}) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "One", body: "Plain words." }], + ...over, +}); +for (const id of ["first", "second"]) { + await mkdir(path.join(reports, id), { recursive: true }); + await writeFile(path.join(reports, id, "report.json"), JSON.stringify(article(id), null, 2)); +} +await mkdir(path.join(reports, "broken"), { recursive: true }); +await writeFile( + path.join(reports, "broken", "report.json"), + JSON.stringify(article("broken", { summary: "see [x](cite:nobody)" }), null, 2), +); + +const { POST } = await import("./route"); +test.after(() => corpus.cleanup()); + +const index = async () => + JSON.parse(await readFile(path.join(reports, "index.json"), "utf8").catch(() => '{"published":[]}')) as { + published: string[]; + }; +const reportJson = async (id: string) => + JSON.parse(await readFile(path.join(reports, id, "report.json"), "utf8")) as Record<string, unknown>; + +test("publishes, places, makes public, moves and unpublishes — the answer is what was saved", async () => { + const a = await callPost(POST, { id: "first", published: true }); + assert.equal(a.status, 200, JSON.stringify(a.body)); + assert.deepEqual(a.body, { ok: true, id: "first", audience: "private", published: true, position: 0 }); + const b = await callPost(POST, { id: "second", published: true, position: 0, audience: "public" }); + assert.deepEqual(b.body, { ok: true, id: "second", audience: "public", published: true, position: 0 }); + assert.deepEqual(await index(), { published: ["second", "first"] }); + assert.equal((await reportJson("second")).audience, "public"); + + const moved = await callPost(POST, { id: "second", position: 1 }); + assert.deepEqual(moved.body, { ok: true, id: "second", audience: "public", published: true, position: 1 }); + assert.deepEqual(await index(), { published: ["first", "second"] }); + + const off = await callPost(POST, { id: "first", published: false }); + assert.deepEqual(off.body, { ok: true, id: "first", audience: "private", published: false, position: null }); + assert.deepEqual(await index(), { published: ["second"] }); +}); + +test("refusals, each before anything is written", async () => { + const before = await index(); + const brokenBefore = await reportJson("broken"); + const cases: [Record<string, unknown>, RegExp][] = [ + [{ id: "first", audience: "public", listed: true }, /unknown key\(s\): listed — this route accepts id, audience, published, position/], + [{ audience: "public" }, /"id" is required/], + [{ id: "Bad Id", published: true }, /not an article id/], + [{ id: "missing", published: true }, /no article "missing"/], + [{ id: "first", audience: "everyone" }, /"audience" must be one of public, private/], + [{ id: "first", published: "yes" }, /"published" must be a boolean/], + [{ id: "first", position: -1 }, /"position" must be a whole number, zero or above/], + [{ id: "first", position: 0 }, /"first" is a draft/], + [{ id: "second", position: 7 }, /position 7 is out of range/], + [{ id: "broken", published: true }, /cannot be published while report.json has problems:[\s\S]*summary/], + [{ id: "first" }, /nothing to change/], + ]; + for (const [body, re] of cases) { + const r = await callPost(POST, body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(r.body.error ?? "", re, JSON.stringify(body)); + } + assert.deepEqual(await index(), before, "index.json untouched by any refusal"); + assert.deepEqual(await reportJson("broken"), brokenBefore); + assert.equal((await callPost(POST, { id: "first", published: true }, {})).status, 401); +}); diff --git a/editor/app/api/ops/articles-config/route.ts b/editor/app/api/ops/articles-config/route.ts @@ -0,0 +1,62 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + ArticleRegistryError, + configureArticle, + isReportAudience, + type ArticleConfigChange, +} from "yt-dlp-transcript-common/lib/report/registry"; +import { REPORT_AUDIENCES } from "yt-dlp-transcript-common/lib/report/schema"; +import { OpsInputError, ops, optBool, optNonNegativeInt, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { +// id: string, // the article: transcripts/reports/<id>/ +// audience?: "public" | "private", // report.json `audience` +// published?: boolean, // in reports/index.json, or a draft +// position?: number, // its place in the published list, 0 = first +// } +// — at least one of the three (release 26 A2). The article store's one writer +// over HTTP: THROUGH configureArticle (lib/report/registry.ts), so locked, +// validated and atomic, as a generator calling the registry is. Publishing +// with no position keeps a published article where it is, else puts it last; +// a position alone moves a published article. +// +// Every refusal is said before anything is written: an unknown key (ops()), +// an id that is not one, an article that is not there, an audience that is +// not one, a position out of range or on a draft, publishing an article whose +// report.json has problems (each listed). The answer is the article as saved. +export async function POST(request: Request) { + return ops(request, ["id", "audience", "published", "position"], async (body) => { + const id = reqString(body, "id"); + const audience = body.audience; + if (audience !== undefined && !isReportAudience(audience)) { + throw new OpsInputError(`"audience" must be one of ${REPORT_AUDIENCES.join(", ")}`); + } + const published = optBool(body, "published"); + const position = optNonNegativeInt(body, "position"); + if (audience === undefined && published === undefined && position === undefined) { + throw new OpsInputError('nothing to change — give "audience", "published" or "position"'); + } + const change: ArticleConfigChange = { + ...(audience !== undefined ? { audience } : {}), + ...(published !== undefined ? { published } : {}), + ...(position !== undefined ? { position } : {}), + }; + let saved; + try { + saved = await configureArticle(id, change, getPaths()); + } catch (err) { + if (err instanceof ArticleRegistryError) throw new OpsInputError(err.message); + throw err; + } + return NextResponse.json({ + ok: true, + id: saved.id, + audience: saved.audience, + published: saved.published, + position: saved.position, + }); + }); +} diff --git a/editor/app/api/ops/reports-export/route.test.ts b/editor/app/api/ops/reports-export/route.test.ts @@ -53,3 +53,14 @@ test("a site that does not exist is refused before any job", async () => { assert.equal(r.status, 400); assert.match(r.error, /No site "demo-site"/); }); + +// The articles' (release 26): `articles: true` in place of a site. +test("articles: true or a site, never both; an article that is not there is refused before any job", async () => { + const both = await post({ siteId: "demo-site", articles: true }); + assert.equal(both.status, 400); + assert.match(both.error, /give "siteId" or "articles", not both/); + assert.match((await post({ articles: false })).error, /"articles" is true when given/); + const none = await post({ articles: true, reportId: "nope" }); + assert.equal(none.status, 400); + assert.match(none.error, /no article "nope"/); +}); diff --git a/editor/app/api/ops/reports-export/route.ts b/editor/app/api/ops/reports-export/route.ts @@ -1,4 +1,5 @@ import { reportsExportAction } from "../../../sites/lib/reportsExportAction"; +import { articlesExportAction } from "../../../sites/lib/articlesActions"; import { jobResponse, OpsInputError, ops, optString, optSubset, reqString } from "../_lib"; import { isValidSiteId } from "yt-dlp-transcript-common/lib/site"; import { REPORT_EXPORT_FORMATS } from "yt-dlp-transcript-common/lib/report/views"; @@ -6,6 +7,7 @@ import { REPORT_EXPORT_FORMATS } from "yt-dlp-transcript-common/lib/report/views export const dynamic = "force-dynamic"; // POST { siteId: string, reportId?: string, formats?: ("html"|"pdf"|"md"|"zip")[] } +// | { articles: true, reportId?: string, formats?: … } // -> { ok: true, jobId } // // An adapter: one call to the action the site's Reports tab posts. Writes each @@ -13,21 +15,28 @@ export const dynamic = "force-dynamic"; // and an evidence pack (or the formats named) into the site's report-exports // staging, as one `reports-export` job on prepare's queue. The job fails, // naming each, when an export cannot be written. +// +// `articles: true` is the Articles tab's (release 26): each published article +// (or `reportId`, published or a draft) into .export-index/articles/. export async function POST(request: Request) { - return ops(request, ["siteId", "reportId", "formats"], async (body) => { + return ops(request, ["siteId", "reportId", "formats", "articles"], async (body) => { + const reportId = optString(body, "reportId"); + const formats = optSubset(body, "formats", REPORT_EXPORT_FORMATS, "the export formats"); + const opts = { + ...(reportId !== undefined ? { reportId } : {}), + ...(formats ? { formats } : {}), + }; + if (body.articles !== undefined) { + if (body.articles !== true) throw new OpsInputError('"articles" is true when given'); + if (body.siteId !== undefined) throw new OpsInputError('give "siteId" or "articles", not both'); + return jobResponse(await articlesExportAction(opts)); + } const siteId = reqString(body, "siteId"); if (!isValidSiteId(siteId)) { throw new OpsInputError( `"${siteId}" is not a valid site id (lowercase letters, digits and "-"; must start with a letter or digit)`, ); } - const reportId = optString(body, "reportId"); - const formats = optSubset(body, "formats", REPORT_EXPORT_FORMATS, "the export formats"); - return jobResponse( - await reportsExportAction(siteId, { - ...(reportId !== undefined ? { reportId } : {}), - ...(formats ? { formats } : {}), - }), - ); + return jobResponse(await reportsExportAction(siteId, opts)); }); } diff --git a/editor/app/api/ops/reports-prepare/route.test.ts b/editor/app/api/ops/reports-prepare/route.test.ts @@ -47,3 +47,14 @@ test("a site that does not exist is refused before any job", async () => { assert.equal(r.status, 400); assert.match(r.error, /No site "demo-site"/); }); + +// The articles' (release 26): `articles: true`, or `article` (that one too). +test("the articles in place of a site, never both; an article that is not there is refused before any job", async () => { + const both = await post({ siteId: "demo-site", articles: true }); + assert.equal(both.status, 400); + assert.match(both.error, /give "siteId" or the articles, not both/); + assert.match((await post({ articles: "yes" })).error, /"articles" is true when given/); + const none = await post({ article: "nope" }); + assert.equal(none.status, 400); + assert.match(none.error, /no article "nope"/); +}); diff --git a/editor/app/api/ops/reports-prepare/route.ts b/editor/app/api/ops/reports-prepare/route.ts @@ -1,17 +1,30 @@ import { reportsPrepareAction } from "../../../sites/lib/reportsPrepareAction"; -import { jobResponse, OpsInputError, ops, reqString } from "../_lib"; +import { articlesPrepareAction } from "../../../sites/lib/articlesActions"; +import { jobResponse, OpsInputError, ops, optString, reqString } from "../_lib"; import { isValidSiteId } from "yt-dlp-transcript-common/lib/site"; export const dynamic = "force-dynamic"; -// POST { siteId: string } -> { ok: true, jobId } +// POST { siteId: string } | { articles: true } | { article: string } -> { ok: true, jobId } // // An adapter: one call to the action the site's Reports tab posts. Cuts every // clip and copies every post capture the site's published reports cite into // its report-media cache, as one `reports-prepare` job on its own queue. The // job fails, naming each citation, when any lacks its media. +// +// `articles: true` is the Articles tab's (release 26): every published +// article's, into .export-index/articles/; `article` the same plus that one +// (a draft being readied), as `archilyzer reports prepare --article <id>`. export async function POST(request: Request) { - return ops(request, ["siteId"], async (body) => { + return ops(request, ["siteId", "articles", "article"], async (body) => { + const article = optString(body, "article"); + if (body.articles !== undefined && body.articles !== true) { + throw new OpsInputError('"articles" is true when given'); + } + if (body.articles === true || article !== undefined) { + if (body.siteId !== undefined) throw new OpsInputError('give "siteId" or the articles, not both'); + return jobResponse(await articlesPrepareAction(article)); + } const siteId = reqString(body, "siteId"); if (!isValidSiteId(siteId)) { throw new OpsInputError( diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -39,6 +39,7 @@ import { type UnfetchableEvidenceWindow, } from "yt-dlp-transcript-common/publish/reportMedia"; import { isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site"; +import { articlesWorkHost } from "yt-dlp-transcript-common/publish/reportHost"; import { heldPlatformRefusal, platformCooldownRemainingMs, @@ -451,7 +452,29 @@ export async function fetchMissingEvidenceAction( if (!isValidSiteId(id)) return { ok: false, error: `"${id}" is not a valid site id` }; const paths = getPaths(); if (!listSiteIds(paths).includes(id)) return { ok: false, error: `No site "${id}"` }; - const need = await missingEvidenceWindows(paths, id); + return fetchMissingFor(await missingEvidenceWindows(paths, id), id, { ...opts, siteId: id }); +} + +// The same for the ARTICLES (release 26: transcripts/reports/, every +// published article): the Articles tab's "Fetch missing evidence". +export async function fetchMissingArticleEvidenceAction( + opts: { dryRun?: boolean; maxHeight?: number } = {}, +): Promise<FetchMissingEvidenceResult> { + const paths = getPaths(); + let host; + try { + host = await articlesWorkHost(paths); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + return fetchMissingFor(await missingEvidenceWindows(paths, host), host.id, opts); +} + +async function fetchMissingFor( + need: Awaited<ReturnType<typeof missingEvidenceWindows>>, + id: string, + opts: { dryRun?: boolean; maxHeight?: number; siteId?: string }, +): Promise<FetchMissingEvidenceResult> { const extra = { siteId: id, onDisk: need.onDisk, unfetchable: need.unfetchable }; if (need.missing.length === 0) { return { @@ -477,7 +500,7 @@ export async function fetchMissingEvidenceAction( })), requestedBy: "reports", manifest: id, - siteId: id, + ...(opts.siteId ? { siteId: opts.siteId } : {}), maxHeight: opts.maxHeight, dryRun: opts.dryRun, }); diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -61,6 +61,7 @@ import { fetchWindowsJobAction } from "../channels/[slug]/videos/fetchWindowsAct import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows"; import { reportsPrepareAction } from "../sites/lib/reportsPrepareAction"; import { reportsExportAction } from "../sites/lib/reportsExportAction"; +import { articlesExportAction, articlesPrepareAction } from "../sites/lib/articlesActions"; import { enqueueStage, stageRequestFromSpec, @@ -148,6 +149,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { // cache does not already hold. "reports-prepare": (spec) => { const { p } = params(spec); + // The articles' (release 26): `params.articles`, and the draft it readied. + if (p.articles === true) return articlesPrepareAction(str(p.article)); return reportsPrepareAction(str(p.siteId) ?? spec.slug); }, // A report site's exports: the same site, report and formats, from the @@ -156,6 +159,12 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { const { p } = params(spec); const reportId = str(p.reportId); const formats = strings(p.formats); + if (p.articles === true) { + return articlesExportAction({ + ...(reportId ? { reportId } : {}), + ...(formats ? { formats } : {}), + }); + } return reportsExportAction(str(p.siteId) ?? spec.slug, { ...(reportId ? { reportId } : {}), ...(formats ? { formats } : {}), diff --git a/editor/app/sites/[siteId]/reports/page.tsx b/editor/app/sites/[siteId]/reports/page.tsx @@ -32,7 +32,7 @@ export const dynamic = "force-dynamic"; export const metadata: Metadata = { title: "Reports" }; // A SITE'S REPORTS: every report directory under `sites/<siteId>/reports/`, -// whether the site publishes it (site.json `reports`, in order) or it is a +// whether the site publishes it (site.json `pages`, in order) or it is a // draft, and what is wrong with it — the report's own checker, so this lists // what prepare and the build would refuse. Publish, unpublish and reorder write // that one key (lib/reportsActions.ts). The evidence media the published diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts @@ -15,6 +15,7 @@ import { writeSite, deleteSite, isValidSiteId, + reservedSiteIdProblem, parseRelatedSites, parseSiteChannels, parseSiteUrl, @@ -51,6 +52,10 @@ export async function saveSiteAction( values, }; } + // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses + // them too): said here, before anything else is read. + const reserved = reservedSiteIdProblem(siteId); + if (reserved) return { ok: false, error: reserved, values }; const siteTitle = String(formData.get("siteTitle") ?? "").trim(); const headerTitle = String(formData.get("headerTitle") ?? "").trim(); if (!siteTitle) { diff --git a/editor/app/sites/articles/page.tsx b/editor/app/sites/articles/page.tsx @@ -0,0 +1,289 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { formatBytes } from "yt-dlp-transcript-common/lib/format"; +import { + REPORT_EXPORT_FILENAMES, + REPORT_EXPORT_FORMATS, +} from "yt-dlp-transcript-common/lib/report/views"; +import { ArticleRowActions } from "../components/ArticleRowActions"; +import { ExportArticlesButton, PrepareArticlesMediaButton } from "../components/ArticlesJobButtons"; +import { FetchMissingEvidenceButton } from "../components/FetchMissingEvidenceButton"; +import { publishRefusal, reportMediaSummary, type ReportMediaSummary } from "../lib/reportList"; +import type { ReportExportsRow } from "../lib/reportListServer"; +import { + latestArticlesJob, + readArticleExports, + readArticleRows, + readArticlesMediaIndex, + type ArticleRow, +} from "../lib/articlesServer"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "Articles — Sites" }; + +// THE ARTICLES (release 26): every article directory under +// `transcripts/reports/`, published by the project homepage — not by a site — +// in `reports/index.json`'s order, then the drafts. Each article's audience +// says which homepage build carries it: the public one only "public" +// articles, the private (local-only) one every published article. Publish, +// unpublish, reorder and the audience are written through the article +// registry (lib/report/registry.ts), as `pnpm ops articles-config` writes +// them. The evidence media and the exports are a site's Reports tab's, over +// the articles, on the same queue. A site's own pages stay on its Reports tab. +// +// A static segment beside /sites/[siteId]: a site named "articles" is not +// reachable here, as one named "new" is not. +export default async function ArticlesPage() { + const paths = getPaths(); + const { rows, indexError } = await readArticleRows(paths); + const published = rows.filter((r) => r.position !== null).map((r) => r.id); + const [mediaIndex, exportRows, lastJob, lastExportJob] = await Promise.all([ + readArticlesMediaIndex(paths), + readArticleExports(paths, published), + latestArticlesJob(paths, "reports-prepare"), + latestArticlesJob(paths, "reports-export"), + ]); + const publicCount = rows.filter((r) => r.position !== null && r.audience === "public").length; + + return ( + <div className="flex flex-col gap-8 max-w-4xl"> + <div className="flex flex-col gap-2"> + <div className="flex items-center gap-2 text-sm text-muted-foreground"> + <Link href="/sites" className="underline hover:text-foreground"> + Sites + </Link> + <span>/</span> + <span>Articles</span> + </div> + <h1 className="text-2xl font-semibold">Articles</h1> + <p className="text-sm"> + {published.length} published ({publicCount} public), {rows.length - published.length} draft + {rows.length - published.length === 1 ? "" : "s"} + </p> + {indexError && ( + <p role="alert" className="text-sm text-destructive"> + {indexError} + </p> + )} + </div> + + <section className="flex flex-col gap-3" aria-label="Articles"> + {rows.length === 0 ? ( + <p className="rounded-md border border-dashed px-3 py-6 text-center text-sm text-muted-foreground"> + No articles yet. Put one at <code>reports/&lt;articleId&gt;/report.json</code>. + </p> + ) : ( + <ul className="flex flex-col gap-3"> + {rows.map((row) => ( + <ArticleListItem key={row.id} row={row} publishedCount={published.length} /> + ))} + </ul> + )} + </section> + + <section className="flex flex-col gap-3 border-t border-border pt-6" aria-label="Evidence media"> + <h2 className="text-lg font-semibold">Evidence media</h2> + <FetchMissingEvidenceButton articles /> + <PrepareArticlesMediaButton /> + <p className="text-sm text-muted-foreground"> + Last prepare job:{" "} + {lastJob ? ( + <Link href={`/jobs/${lastJob.id}`} className="underline font-mono"> + {lastJob.id} + </Link> + ) : ( + "none among recent jobs" + )} + {lastJob && <> ({lastJob.status})</>} + </p> + {mediaIndex ? ( + <MediaSummary summary={reportMediaSummary(mediaIndex)} /> + ) : ( + <p className="text-sm text-muted-foreground">Not prepared yet.</p> + )} + </section> + + <section className="flex flex-col gap-3 border-t border-border pt-6" aria-label="Exports"> + <h2 className="text-lg font-semibold">Exports</h2> + <ExportArticlesButton /> + <p className="text-sm text-muted-foreground"> + Last export job:{" "} + {lastExportJob ? ( + <Link href={`/jobs/${lastExportJob.id}`} className="underline font-mono"> + {lastExportJob.id} + </Link> + ) : ( + "none among recent jobs" + )} + {lastExportJob && <> ({lastExportJob.status})</>} + </p> + {exportRows.length === 0 ? ( + <p className="text-sm text-muted-foreground">No published article to export.</p> + ) : ( + <ul className="flex flex-col gap-2" aria-label="Article exports"> + {exportRows.map((row) => ( + <ExportSummary key={row.reportId} row={row} /> + ))} + </ul> + )} + </section> + </div> + ); +} + +const STATUS_TEXT: Record<ArticleRow["status"], string> = { + ok: "No problems", + problems: "Has problems", + invalid: "Not a valid report", + missing: "Missing", +}; + +function ArticleListItem({ row, publishedCount }: { row: ArticleRow; publishedCount: number }) { + const dates = [ + row.publishedDate ? `published ${row.publishedDate}` : null, + row.updatedDate ? `updated ${row.updatedDate}` : null, + ].filter(Boolean); + return ( + <li + data-testid="article-row" + data-article={row.id} + data-audience={row.audience} + className="flex flex-col gap-2 rounded-lg border bg-card/60 px-3 py-3" + > + <div className="flex flex-wrap items-start justify-between gap-2"> + <div className="flex flex-col gap-0.5"> + <span className="font-medium"> + {row.position !== null && <span className="text-muted-foreground">{row.position + 1}. </span>} + {row.title ?? row.id} + </span> + {row.subtitle && <span className="text-sm text-muted-foreground">{row.subtitle}</span>} + <span className="text-xs text-muted-foreground"> + <code>{row.id}</code> + {row.kind && <> · {row.kind === "factcheck" ? "fact-check" : "sweep"}</>} + {dates.length > 0 && <> · {dates.join(", ")}</>} + </span> + </div> + <div className="flex flex-col items-end gap-1"> + <span className="text-xs"> + <span className={row.position !== null ? "text-success" : "text-muted-foreground"}> + {row.position !== null ? "Published" : "Draft"} + </span> + {" · "} + <span className={row.audience === "public" ? "text-warning" : "text-muted-foreground"}> + {row.audience === "public" ? "Public" : "Private"} + </span> + </span> + <ArticleRowActions + articleId={row.id} + position={row.position} + publishedCount={publishedCount} + publishable={publishRefusal(row)} + audience={row.audience} + /> + </div> + </div> + {(row.status === "ok" || row.status === "problems") && ( + <p className="text-sm"> + {row.sections} section{row.sections === 1 ? "" : "s"} · {row.claims} claim + {row.claims === 1 ? "" : "s"} · {row.citations} citation{row.citations === 1 ? "" : "s"} + </p> + )} + {row.problems.length === 0 ? ( + <span className="text-xs text-muted-foreground">{STATUS_TEXT[row.status]}</span> + ) : ( + <details> + <summary className="cursor-pointer select-none text-xs text-warning"> + {STATUS_TEXT[row.status]} — {row.problems.length} problem{row.problems.length === 1 ? "" : "s"} + </summary> + <ul className="mt-2 flex flex-col gap-1 text-xs"> + {row.problems.map((p, i) => ( + <li key={i}> + {p.path && <code className="text-muted-foreground">{p.path}</code>} + {p.path && ": "} + {p.message} + </li> + ))} + </ul> + </details> + )} + </li> + ); +} + +function MediaSummary({ summary }: { summary: ReportMediaSummary }) { + return ( + <div className="flex flex-col gap-2 rounded-md border border-border bg-card px-4 py-3 text-sm"> + <p> + Prepared {new Date(summary.preparedAt).toLocaleString()}: {summary.moments} moment + {summary.moments === 1 ? "" : "s"} + {summary.momentsByKind.length > 0 && <> ({summary.momentsByKind.map((k) => `${k.count} ${k.kind}`).join(", ")})</>} + , {formatBytes(summary.totalBytes)}. + </p> + {summary.problems.length === 0 ? ( + <p className="text-success">No problems.</p> + ) : ( + <details> + <summary className="cursor-pointer select-none text-warning"> + {summary.problems.length} problem{summary.problems.length === 1 ? "" : "s"}:{" "} + {summary.problemsByKind.map((k) => `${k.count} ${k.kind}`).join(", ")} + </summary> + <ul className="mt-2 flex flex-col gap-1 text-xs"> + {summary.problems.map((p, i) => ( + <li key={i}> + <code className="text-muted-foreground">{p.kind}</code> <code>{p.moment ?? p.report ?? "?"}</code> + {p.citations && p.citations.length > 0 && ( + <span className="text-muted-foreground"> (cited by {p.citations.join(", ")})</span> + )} + : {p.message} + </li> + ))} + </ul> + </details> + )} + </div> + ); +} + +function ExportSummary({ row }: { row: ReportExportsRow }) { + const { manifest, publishable } = row; + return ( + <li + data-testid="article-export" + data-article={row.reportId} + className="flex flex-col gap-1 rounded-md border border-border bg-card px-4 py-3 text-sm" + > + <p> + <code>{row.reportId}</code>{" "} + <span className="text-muted-foreground"> + {manifest ? `exported ${new Date(manifest.exportedAt).toLocaleString()}` : "not exported yet"} + </span> + </p> + {manifest?.revision && ( + <p className="text-xs"> + Revision {manifest.revision.revision} · {manifest.revision.date.slice(0, 10)} ·{" "} + <code title={manifest.revision.commit}>{manifest.revision.commit.slice(0, 12)}</code> + </p> + )} + {manifest && ( + <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs"> + {REPORT_EXPORT_FORMATS.filter((f) => manifest.files[f]).map((f) => ( + <li key={f}> + <code>{REPORT_EXPORT_FILENAMES[f]}</code> {formatBytes(manifest.files[f]!.bytes)}{" "} + {publishable.files[f] ? ( + <span className="text-success">published on build</span> + ) : ( + <span className="text-warning">local only</span> + )} + </li> + ))} + </ul> + )} + {[...(manifest?.notes ?? []), ...publishable.notes].map((note, i) => ( + <p key={i} className="text-xs text-muted-foreground"> + {note} + </p> + ))} + </li> + ); +} diff --git a/editor/app/sites/components/ArticleRowActions.tsx b/editor/app/sites/components/ArticleRowActions.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { + moveArticleAction, + publishArticleAction, + setArticleAudienceAction, + unpublishArticleAction, + type ArticlesActionResult, +} from "../lib/articlesActions"; + +// One article's buttons on the Articles tab: Publish for a draft; Up, Down and +// Unpublish for a published one; and its audience — Make public / Make +// private. Each is one write through the article registry +// (lib/articlesActions.ts); the action revalidates the tab. +export function ArticleRowActions({ + articleId, + position, + publishedCount, + publishable, + audience, +}: { + articleId: string; + // Its place in the published list, or null for a draft. + position: number | null; + publishedCount: number; + // Why it may not be published, or null when it may. + publishable: string | null; + audience: "public" | "private"; +}) { + const [pending, start] = useTransition(); + const [error, setError] = useState<string | null>(null); + const run = (fn: () => Promise<ArticlesActionResult>) => { + setError(null); + start(async () => { + const res = await fn(); + if (!res.ok) setError(res.error); + }); + }; + const btn = "rounded border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50"; + const other = audience === "public" ? "private" : "public"; + + return ( + <span className="flex flex-wrap items-center gap-2"> + {position === null ? ( + <button + type="button" + disabled={pending || publishable !== null} + title={publishable ?? undefined} + aria-label={`Publish article ${articleId}`} + onClick={() => run(() => publishArticleAction(articleId))} + className={btn} + > + {pending ? "Working…" : "Publish"} + </button> + ) : ( + <> + <button + type="button" + disabled={pending || position === 0} + aria-label={`Move article ${articleId} up`} + onClick={() => run(() => moveArticleAction(articleId, -1))} + className={btn} + > + ↑ + </button> + <button + type="button" + disabled={pending || position >= publishedCount - 1} + aria-label={`Move article ${articleId} down`} + onClick={() => run(() => moveArticleAction(articleId, 1))} + className={btn} + > + ↓ + </button> + <button + type="button" + disabled={pending} + aria-label={`Unpublish article ${articleId}`} + onClick={() => run(() => unpublishArticleAction(articleId))} + className={btn} + > + Unpublish + </button> + </> + )} + <button + type="button" + disabled={pending} + aria-label={`Make article ${articleId} ${other}`} + onClick={() => run(() => setArticleAudienceAction(articleId, other))} + className={btn} + > + Make {other} + </button> + {error && ( + <span role="alert" className="text-xs text-destructive"> + {error} + </span> + )} + </span> + ); +} diff --git a/editor/app/sites/components/ArticlesJobButtons.tsx b/editor/app/sites/components/ArticlesJobButtons.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { articlesExportAction, articlesPrepareAction } from "../lib/articlesActions"; +import { cancelJobAction } from "../../jobs/actions"; + +// The Articles tab's two jobs, on the reports queue: "Prepare evidence media" +// (every published article's clips and captures, then their exports) and +// "Export articles". Each streams its log; when it settles the tab re-renders +// with what the job wrote. +export function PrepareArticlesMediaButton() { + const router = useRouter(); + return ( + <StreamActionLog + trigger={() => articlesPrepareAction()} + cancelAction={cancelJobAction} + buttonLabel="Prepare evidence media" + runningLabel="Preparing evidence media…" + onSettled={(started) => { + if (started) router.refresh(); + }} + /> + ); +} + +export function ExportArticlesButton() { + const router = useRouter(); + return ( + <StreamActionLog + trigger={() => articlesExportAction()} + cancelAction={cancelJobAction} + buttonLabel="Export articles" + runningLabel="Exporting articles…" + onSettled={(started) => { + if (started) router.refresh(); + }} + /> + ); +} diff --git a/editor/app/sites/components/FetchMissingEvidenceButton.tsx b/editor/app/sites/components/FetchMissingEvidenceButton.tsx @@ -4,6 +4,7 @@ import Link from "next/link"; import { useState, useTransition } from "react"; import { Button } from "yt-dlp-transcript-common/components/ui/button"; import { + fetchMissingArticleEvidenceAction, fetchMissingEvidenceAction, type FetchMissingEvidenceResult, } from "../../channels/[slug]/videos/fetchWindowsAction"; @@ -13,12 +14,17 @@ import { // (fetch-windows). Preview answers the same question without starting // anything. It is not a streamed log because a run can start two jobs (YouTube // and Rumble side by side); each is linked, and its log is on /jobs. -export function FetchMissingEvidenceButton({ siteId }: { siteId: string }) { +// `articles` instead of a site: the published articles' (release 26). +export function FetchMissingEvidenceButton(props: { siteId: string } | { articles: true }) { const [pending, start] = useTransition(); const [result, setResult] = useState<FetchMissingEvidenceResult | null>(null); const run = (dryRun: boolean) => { start(async () => { - setResult(await fetchMissingEvidenceAction(siteId, { dryRun })); + setResult( + "siteId" in props + ? await fetchMissingEvidenceAction(props.siteId, { dryRun }) + : await fetchMissingArticleEvidenceAction({ dryRun }), + ); }); }; return ( diff --git a/editor/app/sites/components/ReportRowActions.tsx b/editor/app/sites/components/ReportRowActions.tsx @@ -9,7 +9,7 @@ import { } from "../lib/reportsActions"; // One report's buttons on the Reports tab: Publish for a draft; Up, Down and -// Unpublish for a published report. Each is one write of site.json `reports` +// Unpublish for a published report. Each is one write of site.json `pages` // (lib/reportsActions.ts); the action revalidates the tab, which re-renders // with the list as written. export function ReportRowActions({ diff --git a/editor/app/sites/lib/articlesActions.ts b/editor/app/sites/lib/articlesActions.ts @@ -0,0 +1,196 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + ArticleRegistryError, + configureArticle, + isReportAudience, + readArticlesIndex, + setArticlesOrder, + type ArticleConfigChange, +} from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { + REPORT_EXPORT_FORMATS, + type ReportExportFormat, +} from "yt-dlp-transcript-common/lib/report/views"; +import { + runManagedFunction, + type StreamActionResult, +} from "yt-dlp-transcript-common/jobs/streamCommand"; +import { formatReportMediaProblems, prepareReportMedia } from "yt-dlp-transcript-common/publish/reportMedia"; +import { + exportAfterPrepare, + exportSiteReports, + formatReportExportProblems, +} from "yt-dlp-transcript-common/publish/reportExports"; +import { articlesWorkHost } from "yt-dlp-transcript-common/publish/reportHost"; +import { withReportMoved } from "./reportList"; +import { REPORTS_PREPARE_QUEUE } from "./reportsQueue"; + +// THE ARTICLES TAB'S WRITES AND JOBS (release 26 A6): the article store, +// `transcripts/reports/` — published by the project homepage, not a site. +// +// Every write goes through the article registry (lib/report/registry.ts: +// locked, validated, atomic), the one writer of `reports/index.json` and an +// article's `audience`, as `pnpm ops articles-config` does. The jobs are a +// site's prepare and export over the articles' host (publish/reportHost.ts +// articlesWorkHost: every published article, plus a named draft), on the +// same queue: an export reads the media cache a prepare writes and prunes. +// A job's spec carries `params.articles: true`; its slug is "articles" (a +// spec needs one, and the job belongs to no channel and no site). + +export type ArticlesActionResult = { ok: true } | { ok: false; error: string }; + +async function configure(id: string, change: ArticleConfigChange): Promise<ArticlesActionResult> { + if (!isReportId(id)) return { ok: false, error: `"${id}" is not a valid article id` }; + try { + await configureArticle(id, change, getPaths()); + } catch (err) { + return { ok: false, error: err instanceof ArticleRegistryError || err instanceof Error ? err.message : String(err) }; + } + revalidatePath("/sites/articles"); + return { ok: true }; +} + +// Publish a draft (last in the list). Refused by the registry unless its +// report.json is sound — read now, not when the tab rendered. +export async function publishArticleAction(id: string): Promise<ArticlesActionResult> { + return configure(id, { published: true }); +} + +// Unpublish: off the list, back to a draft. Its directory is not touched. +export async function unpublishArticleAction(id: string): Promise<ArticlesActionResult> { + return configure(id, { published: false }); +} + +// Who may read it: the public homepage build carries only "public" articles. +export async function setArticleAudienceAction(id: string, audience: string): Promise<ArticlesActionResult> { + if (!isReportAudience(audience)) return { ok: false, error: `"${audience}" is not an audience` }; + return configure(id, { audience }); +} + +// One place up (-1) or down (1) in the published order, applied to the order +// as it is on disk inside the registry's lock. +export async function moveArticleAction(id: string, dir: -1 | 1): Promise<ArticlesActionResult> { + if (dir !== -1 && dir !== 1) return { ok: false, error: "An article moves one place up or down." }; + if (!isReportId(id)) return { ok: false, error: `"${id}" is not a valid article id` }; + const paths = getPaths(); + try { + const index = await readArticlesIndex(paths); + if (!index.published.includes(id)) return { ok: false, error: `"${id}" is not published` }; + const position = withReportMoved(index.published, id, dir).indexOf(id); + await configureArticle(id, { position }, paths); + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + revalidatePath("/sites/articles"); + return { ok: true }; +} + +// The whole published order at once (a caller that reorders by dragging). +export async function setArticlesOrderAction(ids: string[]): Promise<ArticlesActionResult> { + try { + await setArticlesOrder(ids, getPaths()); + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + revalidatePath("/sites/articles"); + return { ok: true }; +} + +// PREPARE THE ARTICLES' EVIDENCE MEDIA as a job: every clip the published +// articles (plus `article`, a draft being readied) cite, cut from the media on +// disk, and every cited post capture, into `.export-index/articles/report-media/`; +// then, when nothing is missing, their exports. As the site's prepare: the job +// FAILS when a citation lacks its media, the log naming each. +export async function articlesPrepareAction(article?: string): Promise<StreamActionResult> { + const paths = getPaths(); + const include = article?.trim() ? [article.trim()] : []; + let host; + try { + host = await articlesWorkHost(paths, include); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + return runManagedFunction({ + kind: "reports-prepare", + queueKey: REPORTS_PREPARE_QUEUE, + paths, + spec: { kind: "reports-prepare", slug: "articles", params: { articles: true, ...(include[0] ? { article: include[0] } : {}) } }, + fn: async (onLog, signal) => { + const index = await prepareReportMedia({ host, paths, onLog, signal }); + if (index.problems.length > 0) { + for (const line of formatReportMediaProblems(index.problems)) onLog(line); + throw new Error(`${index.problems.length} problem(s): the articles' evidence media is not complete`); + } + const exported = await exportAfterPrepare(index, { host, paths, onLog, signal }); + for (const r of exported?.exported ?? []) { + for (const note of r.manifest.notes) onLog(`note: ${r.reportId}: ${note}`); + } + if (!exported || exported.problems.length === 0) return; + for (const line of formatReportExportProblems(exported.problems)) onLog(line); + throw new Error(`${exported.problems.length} problem(s): the articles were not all exported`); + }, + }); +} + +// EXPORT THE ARTICLES as a job: each published article (or the one named, +// published or a draft) as files, into `.export-index/articles/report-exports/`, +// where the homepage's compose publishes them from. +export async function articlesExportAction( + opts: { reportId?: string; formats?: string[] } = {}, +): Promise<StreamActionResult> { + const paths = getPaths(); + if (opts.reportId !== undefined && !isReportId(opts.reportId)) { + return { ok: false, error: `"${opts.reportId}" is not an article id` }; + } + let formats: ReportExportFormat[] | undefined; + if (opts.formats !== undefined) { + const bad = opts.formats.filter((f) => !(REPORT_EXPORT_FORMATS as readonly string[]).includes(f)); + if (bad.length > 0 || opts.formats.length === 0) { + return { + ok: false, + error: `formats are some of ${REPORT_EXPORT_FORMATS.join(", ")}${bad.length ? ` (not ${bad.join(", ")})` : ""}`, + }; + } + formats = REPORT_EXPORT_FORMATS.filter((f) => opts.formats!.includes(f)); + } + let host; + try { + host = await articlesWorkHost(paths, opts.reportId ? [opts.reportId] : []); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + return runManagedFunction({ + kind: "reports-export", + queueKey: REPORTS_PREPARE_QUEUE, + paths, + spec: { + kind: "reports-export", + slug: "articles", + params: { + articles: true, + ...(opts.reportId ? { reportId: opts.reportId } : {}), + ...(formats ? { formats } : {}), + }, + }, + fn: async (onLog, signal) => { + const result = await exportSiteReports({ + host, + paths, + onLog, + signal, + ...(opts.reportId ? { reportId: opts.reportId } : {}), + ...(formats ? { formats } : {}), + }); + for (const r of result.exported) { + for (const note of r.manifest.notes) onLog(`note: ${r.reportId}: ${note}`); + } + if (result.problems.length === 0) return; + for (const line of formatReportExportProblems(result.problems)) onLog(line); + throw new Error(`${result.problems.length} problem(s): the articles were not all exported`); + }, + }); +} diff --git a/editor/app/sites/lib/articlesServer.ts b/editor/app/sites/lib/articlesServer.ts @@ -0,0 +1,85 @@ +import "server-only"; +import type { Paths } from "yt-dlp-transcript-common/lib/paths"; +import { readJsonFile } from "yt-dlp-transcript-common/lib/jsonFile-server"; +import { + articleAudience, + articleFile, + listArticleDirs, + readArticlesIndex, +} from "yt-dlp-transcript-common/lib/report/registry"; +import type { ReportAudience } from "yt-dlp-transcript-common/lib/report/schema"; +import { articleReportStore } from "yt-dlp-transcript-common/lib/report/store"; +import { readStoreMediaIndex, type ReportMediaIndex } from "yt-dlp-transcript-common/publish/reportMedia"; +import { + publishableStoreExports, + readStoreExportManifest, +} from "yt-dlp-transcript-common/publish/reportExportFiles"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { listAllJobs, type JobListEntry } from "yt-dlp-transcript-common/jobs/listJobs"; +import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta"; +import { reportRows, type ReportFileRead, type ReportRow } from "./reportList"; +import type { ReportExportsRow } from "./reportListServer"; + +// THE ARTICLES TAB, read: every article directory under +// `transcripts/reports/`, published (reports/index.json, in order) then +// drafts, each read and validated as a site's report is (reportList.ts), with +// its audience; the articles' prepared media; their exports; the last jobs. + +export type ArticleRow = ReportRow & { audience: ReportAudience }; + +// An index.json that cannot be read is the tab's error to show, not an empty +// list (lib/report/registry.ts readArticlesIndex). +export async function readArticleRows(paths: Paths): Promise<{ rows: ArticleRow[]; indexError: string | null }> { + let published: string[] = []; + let indexError: string | null = null; + try { + published = (await readArticlesIndex(paths)).published; + } catch (err) { + indexError = (err as Error).message; + } + const dirIds = await listArticleDirs(paths); + const ids = [...new Set([...published, ...dirIds])]; + const reads = new Map<string, ReportFileRead>( + await Promise.all(ids.map(async (id) => [id, await readJsonFile(articleFile(paths, id))] as const)), + ); + const rows = reportRows(published, dirIds, reads).map((row) => { + const read = reads.get(row.id); + return { ...row, audience: articleAudience(read?.ok ? (read.value as { audience?: unknown }) : null) }; + }); + return { rows, indexError }; +} + +export async function readArticlesMediaIndex(paths: Paths): Promise<ReportMediaIndex | null> { + return readStoreMediaIndex(articleReportStore(paths)); +} + +// Each published article's exports: the last export's manifest and which +// files the homepage's compose would publish now. +export async function readArticleExports(paths: Paths, published: readonly string[]): Promise<ReportExportsRow[]> { + const store = articleReportStore(paths); + return Promise.all( + published.map(async (reportId) => ({ + reportId, + manifest: await readStoreExportManifest(store, reportId), + publishable: await publishableStoreExports(store, reportId), + })), + ); +} + +const JOB_LOOKBACK = 100; + +// The newest articles job of `kind` (its spec says `params.articles`), live or +// from an earlier server lifetime, or null. +export async function latestArticlesJob( + paths: Paths, + kind: "reports-prepare" | "reports-export", +): Promise<JobListEntry | null> { + const page = await listAllJobs(paths, { limit: JOB_LOOKBACK }); + const registry = getRegistry(); + for (const entry of page.entries) { + if (entry.kind !== kind) continue; + const spec = registry.get(entry.id)?.spec ?? (await readJobMeta(paths, entry.id))?.spec; + if ((spec?.params as { articles?: unknown } | undefined)?.articles === true) return entry; + } + return null; +} diff --git a/editor/app/sites/lib/reportList.ts b/editor/app/sites/lib/reportList.ts @@ -36,7 +36,7 @@ export type ReportRowStatus = "ok" | "problems" | "invalid" | "missing"; export type ReportRow = { id: string; - // Its place in the site's published list (site.json `reports`), or null for + // Its place in the site's published list (site.json `pages`), or null for // a draft. position: number | null; status: ReportRowStatus; diff --git a/editor/app/sites/lib/reportsActions.ts b/editor/app/sites/lib/reportsActions.ts @@ -14,7 +14,7 @@ import { withReportUnpublished, } from "./reportList"; -// THE REPORTS TAB'S WRITES: site.json `reports`, the site's published list. +// THE REPORTS TAB'S WRITES: site.json `pages`, the site's published list. // Each goes through patchSite, which reads the site inside the file lock and // applies the edit to the list as it is THEN — never a list the tab read // earlier — and writes the rest of the site back untouched. diff --git a/editor/app/sites/page.tsx b/editor/app/sites/page.tsx @@ -77,12 +77,21 @@ export default async function SitesPage() { <section className="flex flex-col gap-4"> <div className="flex items-center justify-between gap-2"> <h1 className="text-2xl font-semibold">Sites</h1> - <Link - href="/sites/new" - className="px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90" - > - + New site - </Link> + <div className="flex items-center gap-2"> + {/* The articles the homepage publishes (release 26). */} + <Link + href="/sites/articles" + className="px-3 py-2 rounded-md border border-border text-sm font-medium hover:bg-muted" + > + Articles + </Link> + <Link + href="/sites/new" + className="px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90" + > + + New site + </Link> + </div> </div> {sites.length === 0 && ( <div className="flex flex-col gap-3 rounded border border-border p-4"> diff --git a/editor/e2e/articles.spec.ts b/editor/e2e/articles.spec.ts @@ -0,0 +1,67 @@ +import { test, expect } from "@playwright/test"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { resetData, testPaths } from "./helpers"; + +// The Articles tab (release 26 A6): /sites/articles lists the article store +// (transcripts/reports/), and its buttons write reports/index.json and an +// article's `audience` through the article registry. Invented fixture ids +// only. + +const reportsDir = () => join(testPaths().transcriptsDir, "reports"); +const article = (id: string, over: Record<string, unknown> = {}) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Fixture article ${id}`, + sections: [{ id: "s1", title: "One", body: "Plain words." }], + ...over, +}); + +async function putArticle(id: string, over: Record<string, unknown> = {}) { + await mkdir(join(reportsDir(), id), { recursive: true }); + await writeFile(join(reportsDir(), id, "report.json"), JSON.stringify(article(id, over), null, 2)); +} + +const readIndex = async () => + JSON.parse(await readFile(join(reportsDir(), "index.json"), "utf8").catch(() => '{"published":[]}')) as { + published: string[]; + }; +const readArticle = async (id: string) => + JSON.parse(await readFile(join(reportsDir(), id, "report.json"), "utf8")) as { audience?: string }; + +test("publish, reorder, make public and unpublish articles; one with problems cannot be published", async ({ page }) => { + await resetData("empty"); + await putArticle("fixture-one"); + await putArticle("fixture-two"); + await putArticle("fixture-broken", { summary: "see [x](cite:nobody)" }); + + await page.goto("/sites"); + await page.getByRole("link", { name: "Articles", exact: true }).click(); + await expect(page).toHaveURL(/\/sites\/articles$/); + await expect(page.getByRole("heading", { name: "Articles", level: 1 })).toBeVisible(); + const row = (id: string) => page.locator(`[data-testid="article-row"][data-article="${id}"]`); + await expect(page.getByTestId("article-row")).toHaveCount(3); + await expect(row("fixture-broken").getByRole("button", { name: "Publish article fixture-broken" })).toBeDisabled(); + + await row("fixture-one").getByRole("button", { name: "Publish article fixture-one" }).click(); + await expect(row("fixture-one").getByRole("button", { name: "Unpublish article fixture-one" })).toBeVisible(); + await row("fixture-two").getByRole("button", { name: "Publish article fixture-two" }).click(); + await expect(row("fixture-two").getByRole("button", { name: "Unpublish article fixture-two" })).toBeVisible(); + await expect.poll(readIndex).toEqual({ published: ["fixture-one", "fixture-two"] }); + + await row("fixture-two").getByRole("button", { name: "Move article fixture-two up" }).click(); + await expect.poll(readIndex).toEqual({ published: ["fixture-two", "fixture-one"] }); + + // Private by default; going public is explicit and lands in report.json. + await expect(row("fixture-one")).toHaveAttribute("data-audience", "private"); + await row("fixture-one").getByRole("button", { name: "Make article fixture-one public" }).click(); + await expect(row("fixture-one")).toHaveAttribute("data-audience", "public"); + await expect.poll(async () => (await readArticle("fixture-one")).audience).toBe("public"); + await expect(page.getByText("2 published (1 public), 1 draft")).toBeVisible(); + + await row("fixture-two").getByRole("button", { name: "Unpublish article fixture-two" }).click(); + await expect.poll(readIndex).toEqual({ published: ["fixture-one"] }); + await expect(page.locator('[data-testid="article-export"]')).toHaveCount(1); +}); diff --git a/plans/reports-on-homepage.md b/plans/reports-on-homepage.md @@ -99,3 +99,78 @@ private-data grep, a public homepage build whose audit passes with zero articles homepage, as a cited site's are today). *Recommended yes*, with the post-visibility rule unchanged. - **D5** — Which current reports are site pages: proposed `jeralyzer-private/cohosts` only; every other listed report becomes an article. + +## Record + +### A2, as shipped + +The article store and its one writer, and the reports stage split into a resolver over a host and a writer into +an output root (branch `r26/store`, Lane B). + +- **Store.** `paths.articlesDir` = `ARTICLES_DIR`, else `<TRANSCRIPTS_DIR>/reports` (ENVIRONMENT.md). An article is + `reports/<id>/` (report.json and its siblings, as a site's report); `reports/index.json` `{"published": [ids]}` + is the ordered published list; report.json `audience` `"public" | "private"`, absent = private (D2). + `common/lib/report/store.ts` names where a store's report directories and staging live (`ReportStore`: a site's, + `.export-index/sites/<id>/`; the articles', `.export-index/articles/`). +- **Writer.** `common/lib/report/registry.ts` — locked (withJsonFileLock in-process around an O_EXCL + `reports/.registry.lock` across processes; a dead or 60 s-old holder is taken over; a live one waited for up to + 10 s), validated (an index names ids once; only a sound article is published; a patch may not add a problem; a + whole document must be sound), atomic (writeJsonAtomic; configureArticle checks everything before writing either + file). API: `configureArticle(id, {audience?, published?, position?})`, `setPublished(id, bool, {position?})`, + `setArticlesOrder(ids)`, `patchArticle(id, patch | fn)`, `writeArticle(doc, {keepAudience?})`; readers + `readArticlesIndex`, `listArticles`, `readArticleState`, `publishedArticleIds(audience)`, `listArticleDirs`; + `ArticleRegistryError` for every refusal. +- **Ops.** `pnpm ops articles-config {"id", "audience"?, "published"?, "position"?}` → configureArticle; usage, + COMMANDS.md. REPORT.md (generated) documents both stores and the writer. +- **Compose split.** `common/publish/reportHost.ts`: `siteReportHost(paths, site)` (its `reports`, `channels` + + `citedChannels`, its audience, relative corpus links) and `articlesReportHost(paths, {audience, siteUrl?, + channelSiteUrl?, published?})` (index.json narrowed to the build's audience, any channel of the corpus — D4 —, + the post visibility rule by the build's audience, absolute archive links only where `channelSiteUrl` names a + site, PROJECT_URL as the base). `resolveReports({paths, host})` / `composeHostReports({paths, host, + publicDir})`; `resolveSiteReports` / `composeReports` are the site's wrappers. reportMedia, reportExportFiles and + reportHistory gained store-based twins of their site paths. Every existing compose test passes unedited. + +| Commit | What | +|---|---| +| d1975fcf | common: the article store, index.json, audience, the registry writer, REPORT.md | +| 9e33e439 | publish: the reports stage over a host, into any output root | +| 490c1ca9 | editor: `pnpm ops articles-config` | + +### A6, as shipped + +| Commit | What | +|---|---| +| ec53dcb8 | cli: `reports prepare|export|check|verify-quotes|attach-video --article <id>` | +| c0f0f894 | editor: the Articles tab, `/sites/articles`; prepare/export jobs over the articles | +| 2e1fd460 | umtool: `/articles`, the article page and evidence walk shared with `/sites`, notes on `articles/<id>` | +| 47a31113 | cli: `reports move-to-articles` — A7's script, dry run by default | + +- **CLI.** `--article <id>` in place of a site or a report.json. prepare and export work over `articlesWorkHost`: + every published article plus the named one (a draft may be readied), so one cache serves both homepage builds; + an article's history commits as "Archilyzer <noreply@articles.invalid>"; attach-video writes `video` through + `patchArticle`. +- **Editor.** `/sites/articles` — a static segment beside `/sites/[siteId]`, linked from `/sites` (no nav entry: + "fold, do not add"); a site named `articles` is shadowed there, as one named `new` is. Rows, publish/unpublish, + ↑/↓, Make public/private through the registry; Fetch missing evidence, Prepare evidence media, Export articles on + the reports queue, spec `params.articles: true` (slug `articles`), replayed as such. The ops `reports-prepare` + and `reports-export` routes take `{"articles": true}` (prepare also `{"article": id}`). +- **umtool.** `ARTICLES_DIR` beside `SITES_DIR`; an article is `articles/<id>` to every reader — the media and + evidence routes (`?site=articles`), notes targets and `umtool notes articles/<id>`, a manifest's `"article"`. + The nav's "articles" opens `/articles` (`/sites` still marks it). The article page and the evidence walk are + shared components. A site named `articles` is shadowed in umtool. The existing notes tests now pass a temp + article store of their own. +- **A7 script, not run.** `archilyzer reports move-to-articles [--keep <site>/<id>,…] [--drafts] [--apply]`; + tested on a temp corpus only. + +**Gates.** tsc, every package: clean per commit. common 3793/3793 (an earlier full run had one +`relocateChannelMedia.test.ts` reconcile failure under load; that file alone 44/44 twice); editor unit 264/264; +test:scripts 836 (834 pass, 2 skipped); mcp 306/306; export unit 118/118; homepage unit 23/23. umtool capped +build with the corpus linked: compiled in 17.4 s, rc 0. e2e (single specs, foreground): editor `articles.spec.ts` +1/1 (its run built the editor, 79 s); umtool `articles.spec.ts` + `sites.spec.ts` 6/6, `article-notes.spec.ts` + +`article-evidence.spec.ts` 12/12; export `e2e:report` `report-site.spec.ts` 23/23. No export or homepage build: +neither app's code changed. + +**Left for the merge.** View hrefs are `/reports/…` (lib/report/views.ts); the homepage's `/articles/` (A3) and a +site's `/pages/` (A5) need the base decided there. A5's `reports` → `pages`: the move script reads `pages ?? reports` +and writes `reports` with patchSite, and a search-off site emptied by the move would be refused by A5's validation — +the merge adapts both. REPORT.md still names site.json `reports`. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -53,6 +53,8 @@ // pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}' // pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}' // pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}' +// pnpm ops articles-config --json '{"id":"demo-article","published":true}' +// pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}' // pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}' // pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}' // pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}' @@ -77,6 +79,7 @@ // pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait // pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait // pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait +// pnpm ops reports-prepare --json '{"articles":true}' --wait // pnpm ops get channel the-quartering // pnpm ops get channels // pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}' @@ -240,6 +243,9 @@ const ACTIONS = [ // A site's cited-only channels and its publish policy ({siteId, // citedChannels?, publishAuto?}), through the site form's own writer. "site-config", + // An article's audience and its place in the published list ({id, + // audience?, published?, position?}), through the article registry. + "articles-config", // The channel's lifecycle: the New channel form, and the channel page's // Danger → Rename and Danger → Delete. Synchronous; no job. "create-channel", @@ -760,11 +766,14 @@ export function usage() { ' published reports cite into its report-media cache, before its build:', ' {"siteId"}. The job fails, naming each one, when a citation lacks media.', ' When nothing is missing it then exports the reports, as reports-export.', + ' {"articles": true} does it for the published articles (transcripts/', + ' reports/, the homepage\'s); {"article": "<id>"} adds that one (a draft).', "", 'reports-export writes each published report as report.html, report.pdf,', ' report.md, slides.html, slides.pdf and evidence-pack.zip for the site\'s', ' build to publish: {"siteId", "reportId"?, "formats"?: ["html","pdf","md",', - ' "slides","slides-pdf","zip"]}.', + ' "slides","slides-pdf","zip"]}; {"articles": true, "reportId"?, …} the', + ' articles\' (reportId: one article, published or a draft).', "", 'settings patches settings.json through the editor\'s one writer:', ' {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block\'s keys', @@ -891,6 +900,16 @@ export function usage() { ' unknown site or channel is refused before anything is written. Answers', ' the saved values.', "", + 'articles-config sets an article\'s audience and its place in the published', + ' list (transcripts/reports/index.json), through the article registry:', + ' {"id"} and any of "audience" ("public" | "private"; absent in report.json', + ' = private), "published" (true = listed, false = a draft) and "position"', + ' (its place in the list, 0 = first; publishing with none keeps a listed', + ' article where it is, else puts it last). Refused before anything is', + ' written: an unknown article, a position on a draft or out of range,', + ' publishing an article whose report.json has problems (listed). Answers', + ' the article as saved.', + "", 'create-channel is the New channel form: {"fields": {"name", "handling":', ' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,', ' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else', diff --git a/umtool/app/api/sites/evidence/route.ts b/umtool/app/api/sites/evidence/route.ts @@ -1,5 +1,5 @@ import { citationEvidence } from "@/lib/articles/evidence"; -import { readReportFile, siteById } from "@/lib/articles/sites"; +import { isReportHost, readReportFile } from "@/lib/articles/sites"; export const dynamic = "force-dynamic"; @@ -10,7 +10,7 @@ export async function GET(request: Request) { const site = url.searchParams.get("site") ?? ""; const reportId = url.searchParams.get("report") ?? ""; const cite = url.searchParams.get("cite") ?? ""; - if (!siteById(site)) return Response.json({ error: `no site ${site}` }, { status: 404 }); + if (!isReportHost(site)) return Response.json({ error: `no site ${site}` }, { status: 404 }); const read = await readReportFile(site, reportId); if (!read.report) return Response.json({ error: read.problems[0]?.message ?? "no report" }, { status: 404 }); const ev = await citationEvidence(site, read.report, cite); diff --git a/umtool/app/api/sites/media/route.ts b/umtool/app/api/sites/media/route.ts @@ -1,9 +1,9 @@ import { readFile, realpath, stat } from "node:fs/promises"; import path from "node:path"; -import { reportMediaDir, reportMediaIndexFile, siteReportDir } from "yt-dlp-transcript-common/publish/reportMedia"; +import { storeMediaDir, storeMediaIndexFile } from "yt-dlp-transcript-common/publish/reportMedia"; import { rangeResponse } from "@/lib/report/serve.mjs"; -import { CHANNELS_DIR, REPORTS_ROOT, SITES_DIR, inside } from "@/lib/paths"; -import { sitesPaths } from "@/lib/articles/sites"; +import { ARTICLES_DIR, CHANNELS_DIR, REPORTS_ROOT, SITES_DIR, inside } from "@/lib/paths"; +import { reportDirFor, storeFor } from "@/lib/articles/sites"; export const dynamic = "force-dynamic"; @@ -13,7 +13,8 @@ export const dynamic = "force-dynamic"; // // ?site&report&file a file in the report's directory: video.mp4, // poster.jpg, stills/… -- relative, no `..`, a media type, -// and its real path under SITES_DIR (or REPORTS_ROOT: a +// and its real path under SITES_DIR or ARTICLES_DIR +// (`site=articles`: the article store) or REPORTS_ROOT (a // generator may link a take's preview in) // ?site&moment the site's PREPARED evidence clip for a moment, found // through report-media/index.json -- never a client path @@ -54,22 +55,22 @@ async function serve(request: Request, abs: string): Promise<Response> { async function reportFile(site: string, report: string, rel: string): Promise<string | null> { if (!SEGMENT.test(site) || !SEGMENT.test(report)) return null; if (!rel || rel.includes("\0") || rel.startsWith("/") || rel.split("/").some((s) => s === ".." || s === "" || s === ".")) return null; - const dir = siteReportDir(sitesPaths(), site, report); + const dir = reportDirFor(site, report); const abs = path.join(/* turbopackIgnore: true */ dir, rel); if (!inside(dir, abs)) return null; const real = await realpath(/* turbopackIgnore: true */ abs).catch(() => null); if (!real) return null; - const roots = await Promise.all([SITES_DIR, REPORTS_ROOT].map((r) => realpath(/* turbopackIgnore: true */ r).catch(() => r))); + const roots = await Promise.all([SITES_DIR, ARTICLES_DIR, REPORTS_ROOT].map((r) => realpath(/* turbopackIgnore: true */ r).catch(() => r))); return roots.some((r) => inside(r, real)) ? real : null; } async function preparedFile(site: string, moment: string): Promise<string | null> { if (!SEGMENT.test(site)) return null; try { - const index = JSON.parse(await readFile(/* turbopackIgnore: true */ reportMediaIndexFile(sitesPaths(), site), "utf8")); + const index = JSON.parse(await readFile(/* turbopackIgnore: true */ storeMediaIndexFile(storeFor(site)), "utf8")); const entry = index?.moments?.[moment]; if (!entry || typeof entry.file !== "string") return null; - const dir = reportMediaDir(sitesPaths(), site); + const dir = storeMediaDir(storeFor(site)); const abs = path.resolve(/* turbopackIgnore: true */ dir, entry.file); return inside(dir, abs) ? abs : null; } catch { diff --git a/umtool/app/articles/[report]/evidence/page.tsx b/umtool/app/articles/[report]/evidence/page.tsx @@ -0,0 +1,18 @@ +import EvidencePage from "@/components/articles/EvidencePage"; +import { ARTICLES_KEY } from "@/lib/paths"; + +export const dynamic = "force-dynamic"; + +// Every citation of one article of the homepage's store, one per screen. +// `?c=<citationId>` opens on that citation. +export default async function StoreEvidencePage({ + params, + searchParams, +}: { + params: Promise<{ report: string }>; + searchParams: Promise<{ c?: string }>; +}) { + const { report: reportId } = await params; + const { c } = await searchParams; + return <EvidencePage site={ARTICLES_KEY} reportId={reportId} c={c} crumbs={[{ href: "/articles", label: "articles" }]} />; +} diff --git a/umtool/app/articles/[report]/page.tsx b/umtool/app/articles/[report]/page.tsx @@ -0,0 +1,32 @@ +import ArticlePage, { type ArticleSearch } from "@/components/articles/ArticlePage"; +import { ARTICLES_KEY } from "@/lib/paths"; +import { sitesPaths } from "@/lib/articles/sites"; +import { readArticlesIndex } from "yt-dlp-transcript-common/lib/report/registry"; + +export const dynamic = "force-dynamic"; + +// One article of the homepage's store (transcripts/reports/<id>/, release +// 26): the shared article page, its notes beside its report.json. +export default async function StoreArticlePage({ + params, + searchParams, +}: { + params: Promise<{ report: string }>; + searchParams: Promise<ArticleSearch>; +}) { + const { report: reportId } = await params; + const sp = await searchParams; + const published = await readArticlesIndex(sitesPaths()) + .then((i) => i.published.includes(reportId)) + .catch(() => false); + return ( + <ArticlePage + site={ARTICLES_KEY} + reportId={reportId} + sp={sp} + home={{ href: "/articles", label: "articles" }} + crumbs={[{ href: "/articles", label: "articles" }]} + published={published} + /> + ); +} diff --git a/umtool/app/articles/page.tsx b/umtool/app/articles/page.tsx @@ -0,0 +1,79 @@ +import Link from "next/link"; +import BrowseHeader from "@/components/BrowseHeader"; +import ArticleTable from "@/components/articles/ArticleTable"; +import { badgeVariants } from "@/components/ui/badge"; +import { readStoreRow, type ArticleRow } from "@/lib/articles/sites"; + +export const dynamic = "force-dynamic"; + +// The homepage's articles (transcripts/reports/, release 26): published in +// reports/index.json's order, then drafts, each with its audience, notes, +// video project and source. Zero client JS: the filters are links. A site's +// own pages are on /sites. + +type Search = { status?: string; notes?: string; audience?: string }; + +export default async function ArticlesPage({ searchParams }: { searchParams: Promise<Search> }) { + const sp = await searchParams; + const store = await readStoreRow(); + const keep = (a: ArticleRow) => + (!sp.status || a.status === sp.status) && + (!sp.audience || a.audience === sp.audience) && + (sp.notes !== "open" || a.openNotes > 0); + const shown = store.articles.filter(keep); + const qs = (next: Partial<Search>) => { + const p = new URLSearchParams(); + for (const [k, v] of Object.entries({ ...sp, ...next })) if (v) p.set(k, String(v)); + const s = p.toString(); + return `/articles${s ? `?${s}` : ""}`; + }; + const count = (f: (a: ArticleRow) => boolean) => store.articles.filter(f).length; + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + active="articles" + crumbs={[{ label: "articles" }]} + note={`${store.published} published (${store.publicCount} public) · ${store.drafts} drafts · ${store.openNotes} open notes`} + /> + <main className="deck-main flex-1 p-4"> + <div className="mb-3 flex flex-wrap items-center gap-1.5"> + <span className="micro">status</span> + <Chip href={qs({ status: "" })} on={!sp.status} label="all" /> + <Chip href={qs({ status: "published" })} on={sp.status === "published"} label={`published ${store.published}`} /> + <Chip href={qs({ status: "draft" })} on={sp.status === "draft"} label={`draft ${store.drafts}`} /> + <span className="micro ml-3">audience</span> + <Chip href={qs({ audience: "" })} on={!sp.audience} label="all" /> + <Chip href={qs({ audience: "public" })} on={sp.audience === "public"} label={`public ${count((a) => a.audience === "public")}`} /> + <Chip href={qs({ audience: "private" })} on={sp.audience === "private"} label={`private ${count((a) => a.audience === "private")}`} /> + <span className="micro ml-3">notes</span> + <Chip href={qs({ notes: "" })} on={sp.notes !== "open"} label="all" /> + <Chip href={qs({ notes: "open" })} on={sp.notes === "open"} label={`open ${count((a) => a.openNotes > 0)}`} /> + <Link href="/sites" className="ml-auto text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> + site pages + </Link> + </div> + {store.indexError && ( + <p role="alert" className="mb-3 text-[12px] text-[var(--color-bad)]"> + {store.indexError} + </p> + )} + {store.articles.length === 0 ? ( + <p className="text-[12px] text-[var(--color-dim)]">no articles</p> + ) : shown.length === 0 ? ( + <p className="text-[12px] text-[var(--color-dim)]">nothing matches that filter</p> + ) : ( + <ArticleTable articles={shown} /> + )} + </main> + </div> + ); +} + +function Chip({ href, on, label }: { href: string; on: boolean; label: string }) { + return ( + <Link href={href} aria-current={on ? "true" : undefined} className={badgeVariants({ variant: on ? "on" : "neutral" })}> + {label} + </Link> + ); +} diff --git a/umtool/app/sites/[site]/[report]/evidence/page.tsx b/umtool/app/sites/[site]/[report]/evidence/page.tsx @@ -1,17 +1,11 @@ import { notFound } from "next/navigation"; -import { reportCitationNumbers } from "yt-dlp-transcript-common/lib/report/uses"; -import BrowseHeader from "@/components/BrowseHeader"; -import EvidenceWalk, { type WalkItem } from "@/components/articles/EvidenceWalk"; -import { readArticleNotes, readReportFile, siteById } from "@/lib/articles/sites"; -import { corpusNotesFile } from "@/lib/paths"; -import { linkedProjects } from "@/lib/articles/links.mjs"; -import { sourceFor } from "@/lib/articles/sources.mjs"; -import type { NotesRead } from "@/lib/annotations/types"; +import EvidencePage from "@/components/articles/EvidencePage"; +import { siteById } from "@/lib/articles/sites"; export const dynamic = "force-dynamic"; -// Every citation of one article, one per screen, in the article's own -// numbering. `?c=<citationId>` opens on that citation. +// Every citation of one of a site's reports, one per screen, in the article's +// own numbering. `?c=<citationId>` opens on that citation. export default async function EvidenceWalkPage({ params, searchParams, @@ -23,38 +17,15 @@ export default async function EvidenceWalkPage({ const { c } = await searchParams; const site = siteById(siteId); if (!site) notFound(); - const read = await readReportFile(site.siteId, reportId); - if (!read.report) notFound(); - const r = read.report; - const numbers = reportCitationNumbers(r); - const items: WalkItem[] = [...numbers.entries()] - .sort((a, b) => a[1] - b[1]) - .map(([id, number]) => ({ id, number, kind: r.citations?.[id]?.kind ?? "?", quote: r.citations?.[id]?.quote ?? "" })); - const at = Math.max(0, items.findIndex((i) => i.id === c)); - const [notes, source] = await Promise.all([readArticleNotes(site.siteId, reportId), sourceFor(site.siteId, reportId)]); - const links = await linkedProjects(site.siteId, reportId, { workspace: source?.workspace ?? null }); - const initialNotes: NotesRead = { - subject: { kind: "article", site: site.siteId, report: reportId }, - file: corpusNotesFile(site.siteId, reportId) ?? "", - token: notes.token, - doc: notes.doc, - source: notes.doc?.source ?? null, - }; return ( - <div className="flex h-full flex-col"> - <BrowseHeader - active="articles" - crumbs={[ - { href: "/sites", label: "articles" }, - { href: `/sites/${site.siteId}`, label: site.siteId }, - { href: `/sites/${site.siteId}/${reportId}`, label: reportId }, - { label: "evidence" }, - ]} - note={`${items.length} citations`} - /> - <EvidenceWalk site={site.siteId} report={reportId} items={items} initial={at} initialNotes={initialNotes} - videoProjects={links.linked.map((p: { id: string; title: string; generatedBy: string | null }) => ({ id: p.id, title: p.title, generatedBy: p.generatedBy }))} - /> - </div> + <EvidencePage + site={site.siteId} + reportId={reportId} + c={c} + crumbs={[ + { href: "/sites", label: "articles" }, + { href: `/sites/${site.siteId}`, label: site.siteId }, + ]} + /> ); } diff --git a/umtool/app/sites/[site]/[report]/page.tsx b/umtool/app/sites/[site]/[report]/page.tsx @@ -1,212 +1,33 @@ -import path from "node:path"; -import Link from "next/link"; import { notFound } from "next/navigation"; -import { readRevisionHead, REPORT_HISTORY_GIT_DIRNAME } from "yt-dlp-transcript-common/publish/reportHistory"; -import { siteReportDir } from "yt-dlp-transcript-common/publish/reportMedia"; -import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides"; -import BrowseHeader from "@/components/BrowseHeader"; -import ArticleReader from "@/components/articles/ArticleReader"; -import WorkspacePanel from "@/components/articles/WorkspacePanel"; -import { badgeVariants } from "@/components/ui/badge"; -import { articleView } from "@/lib/articles/article"; -import { articleWorkspaceListing, openWorkspaceFile } from "@/lib/articles/files"; -import { linkedProjects } from "@/lib/articles/links.mjs"; -import { readArticleNotes, readReportFile, siteById, sitesPaths } from "@/lib/articles/sites"; -import { sourceFor } from "@/lib/articles/sources.mjs"; -import { corpusNotesFile } from "@/lib/paths"; -import type { NotesRead } from "@/lib/annotations/types"; +import ArticlePage, { type ArticleSearch } from "@/components/articles/ArticlePage"; +import { siteById } from "@/lib/articles/sites"; export const dynamic = "force-dynamic"; -// One article: the reader with its notes (default), or `?tab=source` -- the -// workspace files it was written from, its draft marked, and what would make -// its slides read badly (lib/report/slides.ts slideLint, and the validator's -// slide problems). -// -// ?rv=slides|iso the article as slides, or the overview (the -// reader's own switch; the place is the hash) -// ?status=open|resolved|all the notes filter it opens with -// ?note=<id> the note it opens on (the decisions inbox links here) -// ?ws=&rel= a workspace file open on the source tab - -type Search = { tab?: string; status?: string; note?: string; ws?: string; rel?: string }; - -export default async function ArticlePage({ +// One of a site's own reports: the shared article page (its reader, notes, +// source tab) with the site as its home. +export default async function SiteArticlePage({ params, searchParams, }: { params: Promise<{ site: string; report: string }>; - searchParams: Promise<Search>; + searchParams: Promise<ArticleSearch>; }) { const { site: siteId, report: reportId } = await params; const sp = await searchParams; const site = siteById(siteId); if (!site) notFound(); - const read = await readReportFile(site.siteId, reportId); - if (!read.report && read.problems[0]?.message === "no report.json") notFound(); - - const [notes, source] = await Promise.all([readArticleNotes(site.siteId, reportId), sourceFor(site.siteId, reportId)]); - const links = await linkedProjects(site.siteId, reportId, { workspace: source?.workspace ?? null }); - const gitDir = path.join(/* turbopackIgnore: true */ siteReportDir(sitesPaths(), site.siteId, reportId), REPORT_HISTORY_GIT_DIRNAME); - const head = await readRevisionHead(gitDir).catch(() => null); - const published = (site.pages ?? []).includes(reportId); - const r = read.report; - const tab = sp.tab === "source" ? "source" : "article"; - const base = `/sites/${site.siteId}/${reportId}`; - const media = (file: string) => - `/api/sites/media?site=${encodeURIComponent(site.siteId)}&report=${encodeURIComponent(reportId)}&file=${encodeURIComponent(file)}`; - - const meta = ( - <div data-article-meta className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-[var(--color-dim)]"> - <Link href={`/sites/${site.siteId}`} className="hover:text-[var(--color-text)]"> - {site.siteTitle || site.siteId} - </Link> - <span data-status={published ? "published" : "draft"} className={badgeVariants({ variant: published ? "on" : "neutral", size: "sm" })}> - {published ? "published" : "draft"} - </span> - {r?.published && <span>published {r.published}</span>} - {r?.updated && <span>updated {r.updated}</span>} - {head && <span data-revisions={head.revision}>{head.revision} revision{head.revision === 1 ? "" : "s"}</span>} - {links.linked.map((p: { id: string }) => ( - <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="font-mono text-[var(--color-sel)] hover:underline"> - {p.id} - </Link> - ))} - {links.possible.map((p: { id: string }) => ( - <Link key={p.id} href={`/browse/${p.id}`} className="font-mono hover:underline" title="shares the slug; not linked"> - {p.id} (possible) - </Link> - ))} - <nav className="ml-auto flex gap-2" aria-label="article views"> - <Link href={base} aria-current={tab === "article" ? "page" : undefined} className={tab === "article" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}> - article - </Link> - <Link href={`${base}?tab=source`} aria-current={tab === "source" ? "page" : undefined} className={tab === "source" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}> - source - </Link> - <Link href={`${base}/evidence`} className="hover:text-[var(--color-text)]"> - evidence - </Link> - </nav> - {source && ( - <div className="w-full font-mono text-[11px]" title={source.how}> - {source.draft && <span>draft {source.draft}</span>} - {source.generator && <span className="ml-3">generator {source.generator}</span>} - </div> - )} - </div> - ); - - const header = ( - <BrowseHeader - active="articles" - crumbs={[{ href: "/sites", label: "articles" }, { href: `/sites/${site.siteId}`, label: site.siteId }, { label: reportId }]} - note={`${notes.doc?.notes.filter((n) => n.status === "open").length ?? 0} open notes`} - /> - ); - - if (!r) { - return ( - <div className="flex h-full flex-col"> - {header} - <main className="deck-main flex-1 p-4"> - <div className="mx-auto max-w-[72ch] space-y-3"> - {meta} - <p className="text-[13px] text-[var(--color-bad)]">report.json does not read as a report:</p> - <ul className="list-disc pl-5 text-[12px] text-[var(--color-dim)]"> - {read.problems.slice(0, 20).map((p, i) => ( - <li key={i}>{p.message}</li> - ))} - </ul> - </div> - </main> - </div> - ); - } - - if (tab === "source") { - const ws = await articleWorkspaceListing(source?.workspace); - const opened = - sp.ws && sp.rel - ? await openWorkspaceFile(sp.ws, sp.rel) - : ws && source?.draft - ? await openWorkspaceFile(ws.name, path.relative(ws.dir, source.draft)) - : null; - const draftRel = ws && source?.draft ? `${ws.name}/${path.relative(ws.dir, source.draft)}` : null; - const { view: slideView } = await articleView(r); - const lint = hasSlides(slideView) ? slideLint(slideView) : []; - const slideProblems = read.problems.filter((p) => /(^|\.)slides?(\.|\[|$)/.test(p.path ?? "")); - return ( - <div className="flex h-full flex-col"> - {header} - <main className="deck-main flex-1 p-4"> - <div className="space-y-4"> - {meta} - {hasSlides(slideView) && ( - <section data-slide-lint={lint.length + slideProblems.length} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]"> - <div className="micro">slides</div> - {lint.length + slideProblems.length === 0 ? ( - <p className="mt-1 text-[var(--color-dim)]">nothing to fix</p> - ) : ( - <ul className="mt-1 space-y-1"> - {slideProblems.map((p, i) => ( - <li key={`p${i}`} data-lint="problem" className="text-[var(--color-bad)]"> - <code className="font-mono text-[11px]">{p.path}</code> {p.message} - </li> - ))} - {lint.map((l, i) => ( - <li key={`l${i}`} data-lint={l.key}> - <Link href={`${base}?rv=slides#${l.anchorId}`} className="font-mono text-[11px] text-[var(--color-sel)] hover:underline"> - {l.key} - </Link>{" "} - <span className="text-[var(--color-text)]">{l.message}</span> - </li> - ))} - </ul> - )} - </section> - )} - <WorkspacePanel - workspaces={ws ? [ws] : []} - opened={opened} - highlight={draftRel} - hrefFor={(w, rel) => `${base}?${new URLSearchParams({ tab: "source", ws: w, rel })}`} - /> - </div> - </main> - </div> - ); - } - - const { view, error } = await articleView(r); - const initialNotes: NotesRead = { - subject: { kind: "article", site: site.siteId, report: reportId }, - file: corpusNotesFile(site.siteId, reportId) ?? "", - token: notes.token, - doc: notes.doc, - source: notes.doc?.source ?? source ?? null, - ...(notes.error ? { error: notes.error } : {}), - }; - const status = sp.status === "resolved" || sp.status === "all" ? sp.status : "open"; - const video = r.video - ? { file: r.video.src, src: media(r.video.src), poster: r.video.poster ? media(r.video.poster) : undefined, caption: r.video.caption } - : null; - return ( - <div className="flex h-full flex-col"> - {header} - <ArticleReader - site={site.siteId} - report={reportId} - view={view} - viewError={error} - initialNotes={initialNotes} - initialFilter={status} - initialNote={sp.note ?? null} - meta={meta} - video={video} - videoProjects={links.linked.map((p: { id: string; title: string; generatedBy: string | null }) => ({ id: p.id, title: p.title, generatedBy: p.generatedBy }))} - /> - </div> + <ArticlePage + site={site.siteId} + reportId={reportId} + sp={sp} + home={{ href: `/sites/${site.siteId}`, label: site.siteTitle || site.siteId }} + crumbs={[ + { href: "/sites", label: "articles" }, + { href: `/sites/${site.siteId}`, label: site.siteId }, + ]} + published={(site.pages ?? []).includes(reportId)} + /> ); } diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -31,11 +31,12 @@ export default function AppNav({ active }: { active: string }) { // The worklist across every project, not a sixth pile. It sits beside // browse because that is where every decision it names gets settled. { href: "/browse/decisions", label: "decisions" }, - // Every site's articles -- published and drafts -- with their notes, their - // evidence and the workspace they were written in. Named for what it lists: - // the editor's /sites is the sites themselves, and two "sites" a tab apart - // were two places with one name. The URL stays /sites. - { href: "/sites", label: "articles" }, + // The articles -- the homepage's (/articles, release 26) and every site's + // own pages (/sites, linked from it) -- published and drafts, with their + // notes, their evidence and the workspace they were written in. Both pages + // mark this entry: the editor's /sites is the sites themselves, and two + // "sites" a tab apart were two places with one name. + { href: "/articles", label: "articles" }, { href: "/mix", label: "mix" }, // Every occurrence of a word across the corpus. It sits with browse because // what it retrieves is raw material for a build, not a pile to judge. diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -0,0 +1,218 @@ +import path from "node:path"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { readRevisionHead, REPORT_HISTORY_GIT_DIRNAME } from "yt-dlp-transcript-common/publish/reportHistory"; +import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides"; +import BrowseHeader, { type Crumb } from "@/components/BrowseHeader"; +import ArticleReader from "@/components/articles/ArticleReader"; +import WorkspacePanel from "@/components/articles/WorkspacePanel"; +import { badgeVariants } from "@/components/ui/badge"; +import { articleView } from "@/lib/articles/article"; +import { articleHref } from "@/lib/articles/href"; +import { articleWorkspaceListing, openWorkspaceFile } from "@/lib/articles/files"; +import { linkedProjects } from "@/lib/articles/links.mjs"; +import { readArticleNotes, readReportFile, reportDirFor } from "@/lib/articles/sites"; +import { sourceFor } from "@/lib/articles/sources.mjs"; +import { corpusNotesFile } from "@/lib/paths"; +import type { NotesRead } from "@/lib/annotations/types"; + +// ONE ARTICLE's page, wherever it lives: a site's report +// (/sites/<site>/<report>) or one of the article store's (/articles/<id>, +// release 26) -- `site` is the site's id or ARTICLES_KEY. The reader with its +// notes (default), or `?tab=source` -- the workspace files it was written +// from, its draft marked, and what would make its slides read badly +// (lib/report/slides.ts slideLint, and the validator's slide problems). +// +// ?rv=slides|iso the article as slides, or the overview (the +// reader's own switch; the place is the hash) +// ?status=open|resolved|all the notes filter it opens with +// ?note=<id> the note it opens on (the decisions inbox links here) +// ?ws=&rel= a workspace file open on the source tab + +export type ArticleSearch = { tab?: string; status?: string; note?: string; ws?: string; rel?: string }; + +export default async function ArticlePage({ + site, + reportId, + sp, + home, + crumbs, + published, +}: { + // The site's id, or ARTICLES_KEY. + site: string; + reportId: string; + sp: ArticleSearch; + // The meta line's first link: the site, or the article list. + home: { href: string; label: string }; + // The header's crumbs before the article's own. + crumbs: Crumb[]; + published: boolean; +}) { + const read = await readReportFile(site, reportId); + if (!read.report && read.problems[0]?.message === "no report.json") notFound(); + + const [notes, source] = await Promise.all([readArticleNotes(site, reportId), sourceFor(site, reportId)]); + const links = await linkedProjects(site, reportId, { workspace: source?.workspace ?? null }); + const gitDir = path.join(/* turbopackIgnore: true */ reportDirFor(site, reportId), REPORT_HISTORY_GIT_DIRNAME); + const head = await readRevisionHead(gitDir).catch(() => null); + const r = read.report; + const tab = sp.tab === "source" ? "source" : "article"; + const base = articleHref({ site, id: reportId }); + const media = (file: string) => + `/api/sites/media?site=${encodeURIComponent(site)}&report=${encodeURIComponent(reportId)}&file=${encodeURIComponent(file)}`; + + const meta = ( + <div data-article-meta className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-[var(--color-dim)]"> + <Link href={home.href} className="hover:text-[var(--color-text)]"> + {home.label} + </Link> + <span data-status={published ? "published" : "draft"} className={badgeVariants({ variant: published ? "on" : "neutral", size: "sm" })}> + {published ? "published" : "draft"} + </span> + {r?.published && <span>published {r.published}</span>} + {r?.updated && <span>updated {r.updated}</span>} + {head && <span data-revisions={head.revision}>{head.revision} revision{head.revision === 1 ? "" : "s"}</span>} + {links.linked.map((p: { id: string }) => ( + <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="font-mono text-[var(--color-sel)] hover:underline"> + {p.id} + </Link> + ))} + {links.possible.map((p: { id: string }) => ( + <Link key={p.id} href={`/browse/${p.id}`} className="font-mono hover:underline" title="shares the slug; not linked"> + {p.id} (possible) + </Link> + ))} + <nav className="ml-auto flex gap-2" aria-label="article views"> + <Link href={base} aria-current={tab === "article" ? "page" : undefined} className={tab === "article" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}> + article + </Link> + <Link href={`${base}?tab=source`} aria-current={tab === "source" ? "page" : undefined} className={tab === "source" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}> + source + </Link> + <Link href={`${base}/evidence`} className="hover:text-[var(--color-text)]"> + evidence + </Link> + </nav> + {source && ( + <div className="w-full font-mono text-[11px]" title={source.how}> + {source.draft && <span>draft {source.draft}</span>} + {source.generator && <span className="ml-3">generator {source.generator}</span>} + </div> + )} + </div> + ); + + const header = ( + <BrowseHeader + active="articles" + crumbs={[...crumbs, { label: reportId }]} + note={`${notes.doc?.notes.filter((n) => n.status === "open").length ?? 0} open notes`} + /> + ); + + if (!r) { + return ( + <div className="flex h-full flex-col"> + {header} + <main className="deck-main flex-1 p-4"> + <div className="mx-auto max-w-[72ch] space-y-3"> + {meta} + <p className="text-[13px] text-[var(--color-bad)]">report.json does not read as a report:</p> + <ul className="list-disc pl-5 text-[12px] text-[var(--color-dim)]"> + {read.problems.slice(0, 20).map((p, i) => ( + <li key={i}>{p.message}</li> + ))} + </ul> + </div> + </main> + </div> + ); + } + + if (tab === "source") { + const ws = await articleWorkspaceListing(source?.workspace); + const opened = + sp.ws && sp.rel + ? await openWorkspaceFile(sp.ws, sp.rel) + : ws && source?.draft + ? await openWorkspaceFile(ws.name, path.relative(ws.dir, source.draft)) + : null; + const draftRel = ws && source?.draft ? `${ws.name}/${path.relative(ws.dir, source.draft)}` : null; + const { view: slideView } = await articleView(r); + const lint = hasSlides(slideView) ? slideLint(slideView) : []; + const slideProblems = read.problems.filter((p) => /(^|\.)slides?(\.|\[|$)/.test(p.path ?? "")); + return ( + <div className="flex h-full flex-col"> + {header} + <main className="deck-main flex-1 p-4"> + <div className="space-y-4"> + {meta} + {hasSlides(slideView) && ( + <section data-slide-lint={lint.length + slideProblems.length} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]"> + <div className="micro">slides</div> + {lint.length + slideProblems.length === 0 ? ( + <p className="mt-1 text-[var(--color-dim)]">nothing to fix</p> + ) : ( + <ul className="mt-1 space-y-1"> + {slideProblems.map((p, i) => ( + <li key={`p${i}`} data-lint="problem" className="text-[var(--color-bad)]"> + <code className="font-mono text-[11px]">{p.path}</code> {p.message} + </li> + ))} + {lint.map((l, i) => ( + <li key={`l${i}`} data-lint={l.key}> + <Link href={`${base}?rv=slides#${l.anchorId}`} className="font-mono text-[11px] text-[var(--color-sel)] hover:underline"> + {l.key} + </Link>{" "} + <span className="text-[var(--color-text)]">{l.message}</span> + </li> + ))} + </ul> + )} + </section> + )} + <WorkspacePanel + workspaces={ws ? [ws] : []} + opened={opened} + highlight={draftRel} + hrefFor={(w, rel) => `${base}?${new URLSearchParams({ tab: "source", ws: w, rel })}`} + /> + </div> + </main> + </div> + ); + } + + const { view, error } = await articleView(r); + const initialNotes: NotesRead = { + subject: { kind: "article", site: site, report: reportId }, + file: corpusNotesFile(site, reportId) ?? "", + token: notes.token, + doc: notes.doc, + source: notes.doc?.source ?? source ?? null, + ...(notes.error ? { error: notes.error } : {}), + }; + const status = sp.status === "resolved" || sp.status === "all" ? sp.status : "open"; + const video = r.video + ? { file: r.video.src, src: media(r.video.src), poster: r.video.poster ? media(r.video.poster) : undefined, caption: r.video.caption } + : null; + + return ( + <div className="flex h-full flex-col"> + {header} + <ArticleReader + site={site} + report={reportId} + view={view} + viewError={error} + initialNotes={initialNotes} + initialFilter={status} + initialNote={sp.note ?? null} + meta={meta} + video={video} + videoProjects={links.linked.map((p: { id: string; title: string; generatedBy: string | null }) => ({ id: p.id, title: p.title, generatedBy: p.generatedBy }))} + /> + </div> + ); +} diff --git a/umtool/components/articles/ArticleReader.tsx b/umtool/components/articles/ArticleReader.tsx @@ -17,6 +17,7 @@ import type { VideoProjectLink } from "./AddToVideo"; import { blockText, selectionIn, unwrapMarks, wrapRange } from "./anchorDom"; import EvidencePanel, { useEvidence } from "./EvidencePanel"; import { Composer, NoteCard, anchorLabel } from "./NoteCards"; +import { articleHref } from "@/lib/articles/href"; // The article, its notes, and its evidence, in one screen: the text in a // ~70ch column, the notes in a rail beside it (a drawer below 1100px). @@ -465,7 +466,7 @@ export default function ArticleReader({ <section data-evidence-rail className="space-y-2 rounded border border-[var(--color-line)] p-2"> <div className="flex items-center"> <span className="micro">citation [{numbers[cite] ?? cite}]</span> - <a href={`/sites/${site}/${report}/evidence?c=${encodeURIComponent(cite)}`} className="ml-auto text-[11px] text-[var(--color-dim)] hover:text-[var(--color-sel)]"> + <a href={`${articleHref({ site, id: report })}/evidence?c=${encodeURIComponent(cite)}`} className="ml-auto text-[11px] text-[var(--color-dim)] hover:text-[var(--color-sel)]"> walk → </a> <button type="button" aria-label="close evidence" onClick={() => setCite(null)} className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> diff --git a/umtool/components/articles/ArticleTable.tsx b/umtool/components/articles/ArticleTable.tsx @@ -2,6 +2,7 @@ import Link from "next/link"; import { badgeVariants } from "@/components/ui/badge"; import { fmtAgo } from "@/lib/format"; import type { ArticleRow } from "@/lib/articles/sites"; +import { articleHref } from "@/lib/articles/href"; // One row per article: what it is, where it stands, what is waiting on it, // and where it came from. Server-rendered, zero JS -- the /browse idiom. @@ -11,9 +12,7 @@ const posterUrl = (a: ArticleRow) => const baseName = (p: string) => p.split("/").pop() ?? p; -export function articleHref(a: { site: string; id: string }) { - return `/sites/${a.site}/${a.id}`; -} +export { articleHref }; export default function ArticleTable({ articles }: { articles: ArticleRow[] }) { if (articles.length === 0) return <p className="text-[12px] text-[var(--color-dim)]">no articles</p>; @@ -61,6 +60,11 @@ export default function ArticleTable({ articles }: { articles: ArticleRow[] }) { <span className={badgeVariants({ variant: a.status === "published" ? "on" : "neutral", size: "sm" })}> {a.status} </span> + {a.audience && ( + <span data-audience={a.audience} className={`ml-1 ${badgeVariants({ variant: a.audience === "public" ? "neutral" : "meter", size: "sm" })}`}> + {a.audience} + </span> + )} </td> <td className="num py-1.5 pr-3 text-[var(--color-dim)]"> {a.updated ?? (a.mtimeMs ? fmtAgo(a.mtimeMs) : "—")} diff --git a/umtool/components/articles/EvidencePage.tsx b/umtool/components/articles/EvidencePage.tsx @@ -0,0 +1,56 @@ +import { notFound } from "next/navigation"; +import { reportCitationNumbers } from "yt-dlp-transcript-common/lib/report/uses"; +import BrowseHeader, { type Crumb } from "@/components/BrowseHeader"; +import EvidenceWalk, { type WalkItem } from "@/components/articles/EvidenceWalk"; +import { articleHref } from "@/lib/articles/href"; +import { readArticleNotes, readReportFile } from "@/lib/articles/sites"; +import { corpusNotesFile } from "@/lib/paths"; +import { linkedProjects } from "@/lib/articles/links.mjs"; +import { sourceFor } from "@/lib/articles/sources.mjs"; +import type { NotesRead } from "@/lib/annotations/types"; + +// Every citation of one article, one per screen, in the article's own +// numbering, wherever the article lives (`site` is a site's id or +// ARTICLES_KEY). `c` opens on that citation. +export default async function EvidencePage({ + site, + reportId, + c, + crumbs, +}: { + site: string; + reportId: string; + c?: string; + // The header's crumbs before the article's own. + crumbs: Crumb[]; +}) { + const read = await readReportFile(site, reportId); + if (!read.report) notFound(); + const r = read.report; + const numbers = reportCitationNumbers(r); + const items: WalkItem[] = [...numbers.entries()] + .sort((a, b) => a[1] - b[1]) + .map(([id, number]) => ({ id, number, kind: r.citations?.[id]?.kind ?? "?", quote: r.citations?.[id]?.quote ?? "" })); + const at = Math.max(0, items.findIndex((i) => i.id === c)); + const [notes, source] = await Promise.all([readArticleNotes(site, reportId), sourceFor(site, reportId)]); + const links = await linkedProjects(site, reportId, { workspace: source?.workspace ?? null }); + const initialNotes: NotesRead = { + subject: { kind: "article", site, report: reportId }, + file: corpusNotesFile(site, reportId) ?? "", + token: notes.token, + doc: notes.doc, + source: notes.doc?.source ?? null, + }; + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + active="articles" + crumbs={[...crumbs, { href: articleHref({ site, id: reportId }), label: reportId }, { label: "evidence" }]} + note={`${items.length} citations`} + /> + <EvidenceWalk site={site} report={reportId} items={items} initial={at} initialNotes={initialNotes} + videoProjects={links.linked.map((p: { id: string; title: string; generatedBy: string | null }) => ({ id: p.id, title: p.title, generatedBy: p.generatedBy }))} + /> + </div> + ); +} diff --git a/umtool/components/articles/EvidenceWalk.tsx b/umtool/components/articles/EvidenceWalk.tsx @@ -7,6 +7,7 @@ import type { NotesRead } from "@/lib/annotations/types"; import { useNotes } from "@/lib/annotations/useNotes"; import EvidencePanel, { useEvidence, type EvidenceHandle } from "./EvidencePanel"; import { Composer, NoteCard } from "./NoteCards"; +import { articleHref } from "@/lib/articles/href"; // Every citation of one article, one per screen: the evidence on the left, its // notes on the right. j/k (or ←/→) move, space plays, n notes it, Esc cancels. @@ -119,7 +120,7 @@ export default function EvidenceWalk({ </button> )} <div className="pt-2"> - <Link href={`/sites/${site}/${report}`} className="text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> + <Link href={articleHref({ site, id: report })} className="text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> ← article </Link> </div> diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md @@ -1,19 +1,21 @@ # Notes: the operator writes them in umtool, an agent acts on them -A note is a sentence or two the operator leaves on an **article** (a report on a -site, `/sites/<site>/<report>`) or on a **report-video project** (a timeline row, a +A note is a sentence or two the operator leaves on an **article** (one of the +homepage's, `/articles/<id>`, or a site's own page, `/sites/<site>/<report>`) or on +a **report-video project** (a timeline row, a take, a moment in a rendered cut). It is saved where the agent that made the thing can read it back, act on the right SOURCE file, and reply or resolve. ```sh umtool notes --all --open # every notes file with an open note -umtool notes candalyzer/polemic-israel # one article's open notes, as markdown +umtool notes articles/polemic-israel # one article's open notes, as markdown +umtool notes candalyzer/polemic-israel # a site page's umtool notes candace/polemic-israel # one video project's (plus every take's verdict) umtool notes reply n_mgk3x0a1b2 "Changed 'said' to 'claimed' in drafts/israel.json" --resolve umtool notes resolve | wontfix | reopen n_mgk3x0a1b2 ``` -Run it from the repo checkout (or with `TRANSCRIPTS_DIR`/`SITES_DIR` and +Run it from the repo checkout (or with `TRANSCRIPTS_DIR`/`SITES_DIR`/`ARTICLES_DIR` and `REPORTS_DIR` set): like `CHANNELS_DIR`, the sites directory is found by walking up from the working directory to the checkout. @@ -53,12 +55,15 @@ checkout, then of the main worktree, that names it — the editor's own token, a | Subject | File | |---|---| -| An article | `transcripts/sites/<site>/reports/<report>/notes.json`, beside `report.json` | +| An article | `transcripts/reports/<id>/notes.json`, beside `report.json` (target `articles/<id>`) | +| A site's page | `transcripts/sites/<site>/reports/<report>/notes.json`, beside `report.json` | | A report-video project | `<project>/notes.json`, beside `video.manifest.json` | The article file is the one corpus file umtool writes, and only through -`isCorpusNotesFile` (`lib/paths.mjs`): exactly `sites/<site>/reports/<id>/notes.json`, -in an existing report directory that is not a symlink out of its site. The +`isCorpusNotesFile` (`lib/paths.mjs`): exactly `reports/<id>/notes.json` or +`sites/<site>/reports/<id>/notes.json`, in an existing report directory that is not a +symlink out of its store. `articles/<id>` always names the article store, so a site +whose id is `articles` is shadowed in umtool. The generators overwrite only `report.json`, `video.mp4` and `poster.jpg` in a report directory, so notes survive a regenerate; compose and the report history never read it (`common/publish/composeReports.test.ts` holds that), so a note is never published. diff --git a/umtool/docs/sites.md b/umtool/docs/sites.md @@ -17,7 +17,7 @@ the one file it writes there is a report's `notes.json` (docs/notes.md). - **Site and reports**: common's `listSites`/`getSite` (site.json, the editor's defaults), `listReportDirs` (the enumerator the editor's Reports tab uses), each `report.json` through the report validator. **Published** = named in site.json - `reports`, in that order; every other report directory is a **draft**. + `pages`, in that order; every other report directory is a **draft**. - **Source** (`lib/articles/sources.mjs`): the draft under `~/reports/<ws>/polemics/drafts/` whose `id` or file name is the report id, `polemic-` allowed on either side, preferring a workspace whose generator names diff --git a/umtool/e2e/articles.spec.ts b/umtool/e2e/articles.spec.ts @@ -0,0 +1,81 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// /articles (release 26): the homepage's article store, ARTICLES_DIR -- its +// list, an article's page, its evidence, and its notes beside its report.json. +// +// delta published, public, cites sitechan/sv1 (plays from a clip window) +// epsilon a draft +// WRITES articles/delta/notes.json (e2e/fixtures/sites-fixture.mjs) +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const NOTES = path.join(HERE, "..", ".e2e-song", "articles", "delta", "notes.json"); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [ + "/articles", + "/articles/delta", + "/articles/delta/evidence", + "/api/notes?article=articles/delta", + "/api/sites/evidence?site=articles&report=delta&cite=c1", + ]); +}); +test.beforeEach(() => rmSync(NOTES, { force: true })); +test.afterAll(() => rmSync(NOTES, { force: true })); + +test("/articles lists the store: published in index.json's order, drafts after, each with its audience", async ({ page }) => { + const res = await page.goto("/articles"); + expect(res?.status()).toBe(200); + await expect(page.getByRole("link", { name: "articles", exact: true }).first()).toHaveAttribute("aria-current", "page"); + const rows = page.locator("[data-article]"); + await expect(rows).toHaveCount(2); + await expect(rows.nth(0)).toHaveAttribute("data-article", "articles/delta"); + await expect(rows.nth(0)).toHaveAttribute("data-status", "published"); + await expect(rows.nth(0).locator("[data-audience]")).toHaveAttribute("data-audience", "public"); + await expect(rows.nth(1)).toHaveAttribute("data-article", "articles/epsilon"); + await expect(rows.nth(1)).toHaveAttribute("data-status", "draft"); + await expect(rows.nth(1).locator("[data-audience]")).toHaveAttribute("data-audience", "private"); + + await page.getByRole("link", { name: /^public \d+$/ }).click(); + await expect(page).toHaveURL(/audience=public/); + await expect(page.locator("[data-article]")).toHaveCount(1); + + // A site's own pages are a link away. + await page.getByRole("link", { name: "site pages" }).click(); + await expect(page).toHaveURL(/\/sites$/); +}); + +test("an article's page reads, its evidence plays, and a note lands beside its report.json", async ({ page, request }) => { + await page.goto("/articles"); + await page.getByRole("link", { name: "Delta: an article of the homepage" }).click(); + await expect(page).toHaveURL(/\/articles\/delta$/); + await expect(page.locator("[data-article-meta] [data-status]")).toHaveAttribute("data-status", "published"); + + const ev = await request.get("/api/sites/evidence?site=articles&report=delta&cite=c1"); + expect(ev.status()).toBe(200); + const body = (await ev.json()) as { play?: { url: string } }; + expect(body.play?.url).toBeTruthy(); + + await page.goto("/articles/delta/evidence"); + await expect(page.getByRole("link", { name: "delta", exact: true })).toHaveAttribute("href", "/articles/delta"); + + const read = await request.get("/api/notes?article=articles/delta"); + expect(read.status()).toBe(200); + const { token } = (await read.json()) as { token: string }; + const w = await request.post("/api/notes?article=articles/delta", { + data: { token, op: { op: "add", text: "Check the date.", anchor: { kind: "whole" } } }, + }); + expect(w.status()).toBe(200); + const doc = JSON.parse(readFileSync(NOTES, "utf8")); + expect(doc.subject).toEqual({ kind: "article", site: "articles", report: "delta" }); + expect(doc.notes[0]).toMatchObject({ status: "open", author: "operator", text: "Check the date." }); + + await page.goto("/articles?notes=open"); + await expect(page.locator("[data-article='articles/delta'] [data-open-notes]")).toHaveAttribute("data-open-notes", "1"); +}); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1906,10 +1906,11 @@ writeProject("timeline-fixture", { posts: [{ id: "p1", platform: "x", author: "Someone", handle: "@someone", date: "2024-01-02", text: "A post.", url: "https://x.com/someone/status/1", attachTo: "a02" }], }); -const { sites: SITES } = makeSitesFixture({ dest, reports, channels: CHANNELS }); +const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, channels: CHANNELS }); console.log(`fixture at ${dest}`); console.log(` SITES_DIR=${SITES}`); +console.log(` ARTICLES_DIR=${ARTICLES}`); console.log(` video-notes-fixture (generated, built, schedule + take alt), timeline-fixture (teaser, a01-a03, post p1)`); if (planned) console.log(` planned clip (used in a build): ${planned}`); console.log(` videos/: alpha (4 cuts, 3 variants), beta (2 cuts), deck (1 cut, 2 variants)`); diff --git a/umtool/e2e/fixtures/sites-fixture.mjs b/umtool/e2e/fixtures/sites-fixture.mjs @@ -21,6 +21,11 @@ // the article's report-video project: a manifest whose slug // is polemic-alpha, two takes, one verdict // channels/sitechan/data/{sv1,sv2} the cited records +// articles/ the ARTICLE STORE (ARTICLES_DIR, release 26): +// index.json {"published": ["delta"]} +// delta PUBLISHED, audience public, cites sitechan/sv1 (plays +// from its clip window) +// epsilon a DRAFT (private: no audience) import { spawnSync } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; @@ -172,5 +177,31 @@ export function makeSitesFixture({ dest, channels }) { } put(path.join(proj, "takes", "verdicts.json"), { deck: { verdict: "like", note: "", at: "2026-10-07T00:00:00Z" } }); - return { sites, workspace: ws, project: proj }; + // ---- the article store (release 26) --------------------------------------- + const articles = path.join(dest, "articles"); + put(path.join(articles, "index.json"), { published: ["delta"] }); + put(path.join(articles, "delta", "report.json"), { + format: "archilyzer-report", + version: 1, + id: "delta", + kind: "sweep", + audience: "public", + title: "Delta: an article of the homepage", + summary: "An article that belongs to no site.", + published: "2026-10-10", + citations: { + c1: { kind: "video", channel: "sitechan", id: "sv1", start: 3, end: 6, quote: "The vote was rigged and everybody knew.", speaker: "Site Channel", date: "2024-03-15" }, + }, + sections: [{ id: "d1", title: "The claim", body: "She said [the vote was rigged](cite:c1), and the clip shows it." }], + }); + put(path.join(articles, "epsilon", "report.json"), { + format: "archilyzer-report", + version: 1, + id: "epsilon", + kind: "sweep", + title: "Epsilon: a draft article", + sections: [{ id: "e1", title: "Draft", body: "Not published yet." }], + }); + + return { sites, articles, workspace: ws, project: proj }; } diff --git a/umtool/lib/annotations/cli.mjs b/umtool/lib/annotations/cli.mjs @@ -5,25 +5,26 @@ // operator's page from losing a reply (docs/notes.md). // // umtool notes [--all] every notes file, with open counts -// umtool notes <site>/<report> | <project> the digest (open notes) +// umtool notes <site>/<report> | articles/<id> | <project> the digest (open notes) // [--open | --resolved | --all-status] [--json] // umtool notes reply <id> "<text>" [--resolve] [--in <target>] // umtool notes resolve | wontfix | reopen <id> [--in <target>] // umtool notes source <target> [--draft P] [--generator P] [--how T] -import { REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; +import { ARTICLES_DIR, REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; import { digest } from "./digest.mjs"; import { readNotes } from "./store.mjs"; import { articleTarget, listNotesFiles, projectTarget, resolveTarget, writeNote } from "./targets.mjs"; const USAGE = [ "usage: umtool notes [--all] every notes file and its open count", - " umtool notes <site>/<report> | <project> the notes, as markdown (open ones)", + " umtool notes <site>/<report> | articles/<id> | <project>", + " the notes, as markdown (open ones)", " [--open | --resolved | --all-status] [--json]", " umtool notes reply <id> \"<text>\" [--resolve] answer a note (and close it)", " umtool notes resolve | wontfix | reopen <id>", " umtool notes source <target> [--draft P] [--generator P] [--how T]", "", - "Notes are the operator's, written in umtool (/sites, a video project). Act on one", + "Notes are the operator's, written in umtool (/articles, /sites, a video project). Act on one", "by editing its SOURCE file and regenerating; never edit notes.json by hand.", ].join("\n"); @@ -31,10 +32,10 @@ class CliError extends Error {} /** * @param {string[]} args everything after `notes` - * @param {{ sitesDir?: string, reportsRoot?: string, log?: (s: string) => void }} [opts] + * @param {{ sitesDir?: string, articlesDir?: string, reportsRoot?: string, log?: (s: string) => void }} [opts] * @returns {Promise<number>} exit code */ -export async function notesCommand(args, { sitesDir = SITES_DIR, reportsRoot = REPORTS_ROOT, log = console.log } = {}) { +export async function notesCommand(args, { sitesDir = SITES_DIR, articlesDir = ARTICLES_DIR, reportsRoot = REPORTS_ROOT, log = console.log } = {}) { const flags = new Set(args.filter((a) => a.startsWith("--"))); const val = (n) => { const i = args.indexOf(n); @@ -43,7 +44,7 @@ export async function notesCommand(args, { sitesDir = SITES_DIR, reportsRoot = R const VALUED = new Set(["--in", "--draft", "--generator", "--how"]); const pos = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && VALUED.has(args[i - 1]))); const json = flags.has("--json"); - const opts = { sitesDir, reportsRoot }; + const opts = { sitesDir, articlesDir, reportsRoot }; const print = (v) => log(json ? JSON.stringify(v, null, 2) : v); try { @@ -116,7 +117,7 @@ export async function notesCommand(args, { sitesDir = SITES_DIR, reportsRoot = R log(`no notes on ${target.id} (${target.file})`); return 0; } - log(await digest(entry, { status, sitesDir, reportsRoot, projectDir: target.dir })); + log(await digest(entry, { status, reportsRoot, projectDir: target.dir })); return 0; } catch (err) { console.error(err instanceof Error ? err.message : String(err)); diff --git a/umtool/lib/annotations/cli.test.mjs b/umtool/lib/annotations/cli.test.mjs @@ -39,7 +39,8 @@ async function fixture() { JSON.stringify({ schemaVersion: 1, slug: "polemic-x", generatedBy: "polemics/make-site.py", timeline: [{ type: "clip", id: "e1", channel: "ch", video: "v1", start: 10, end: 20, quote: "I never said X", onscreen: { title: "Denial" } }] }), ); clearSourcesCache(); - return { root, sites, reports, opts: { sitesDir: sites, reportsRoot: reports } }; + // An empty article store of its own: never the real one. + return { root, sites, reports, opts: { sitesDir: sites, reportsRoot: reports, articlesDir: path.join(root, "articles") } }; } async function run(args, opts) { diff --git a/umtool/lib/annotations/digest.mjs b/umtool/lib/annotations/digest.mjs @@ -18,7 +18,7 @@ // (takes/verdicts.json): the agent that rendered the takes reads them here. import { readFile } from "node:fs/promises"; import path from "node:path"; -import { REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; +import { REPORTS_ROOT } from "../paths.mjs"; import { listTakes, readVerdicts } from "../report/takes.mjs"; import { locateQuote, sentenceAround } from "./anchor.mjs"; @@ -155,16 +155,16 @@ const STATUS = { open: (n) => n.status === "open", resolved: (n) => n.status !== * The digest of one notes file. * * @param {{ kind: "article" | "video-project", id: string, file: string, doc: any, error?: string }} entry - * @param {{ status?: "open" | "resolved" | "all", sitesDir?: string, reportsRoot?: string, projectDir?: string }} [opts] + * @param {{ status?: "open" | "resolved" | "all", reportsRoot?: string, projectDir?: string }} [opts] */ -export async function digest(entry, { status = "open", sitesDir = SITES_DIR, reportsRoot = REPORTS_ROOT, projectDir } = {}) { +export async function digest(entry, { status = "open", reportsRoot = REPORTS_ROOT, projectDir } = {}) { const lines = []; const doc = entry.doc; const ctx = { kind: entry.kind, report: null, manifest: null, takes: null, verdicts: null }; let heading; if (entry.kind === "article") { - const [site, report] = entry.id.split("/"); - ctx.report = await readJson(path.join(/* turbopackIgnore: true */ sitesDir, site, "reports", report, "report.json")); + // report.json is beside the notes, a site's report or an article alike. + ctx.report = await readJson(path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ entry.file), "report.json")); heading = `# Notes on ${entry.id}${ctx.report?.title ? ` — ${ctx.report.title}` : ""}`; } else { const dir = projectDir ?? path.dirname(/* turbopackIgnore: true */ entry.file); diff --git a/umtool/lib/annotations/store.test.mjs b/umtool/lib/annotations/store.test.mjs @@ -9,7 +9,7 @@ import test from "node:test"; import { corpusNotesFile, isCorpusNotesFile } from "../paths.mjs"; import { NoteError, applyOp, emptyDoc, parseNotesDoc, validateAnchor } from "./shape.mjs"; import { NotesUnreadable, StaleNotes, readNotes, withNotesLock, writeOp } from "./store.mjs"; -import { articleTarget, listNotesFiles, writeNote } from "./targets.mjs"; +import { articleTarget, listNotesFiles, resolveTarget, writeNote } from "./targets.mjs"; const SUBJECT = { kind: "article", site: "s1", report: "r1" }; @@ -189,7 +189,8 @@ test("articleTarget: writes land beside report.json with the discovered source; await mkdir(path.join(reports, "ws", "polemics", "drafts"), { recursive: true }); await writeFile(path.join(reports, "ws", "polemics", "drafts", "r1.json"), JSON.stringify({ id: "r1" })); await writeFile(path.join(reports, "ws", "polemics", "make-site.py"), 'OUT = "sites/s1/reports"\nfor d in drafts: pass\n'); - const opt = { sitesDir: sites, reportsRoot: reports }; + // An empty article store of its own: never the real one. + const opt = { sitesDir: sites, reportsRoot: reports, articlesDir: path.join(root, "articles") }; const t = await articleTarget("s1/r1", opt); const w = await writeNote(t, { op: "add", text: "x", anchor: { kind: "whole" } }, { by: "operator" }); @@ -204,3 +205,35 @@ test("articleTarget: writes land beside report.json with the discovered source; await assert.rejects(articleTarget("s1", opt), (e) => e.status === 400); await rm(root, { recursive: true }); }); + +// The article store (release 26): `articles/<id>` is ARTICLES_DIR/<id>/notes.json, +// by the same rules as a site's report. +test("articles/<id>: notes beside the article's report.json; the same refusals; listed with the rest", async () => { + const root = await mkdtemp(path.join(tmpdir(), "umtool-notes-articles-")); + const sites = path.join(root, "sites"); + const articles = path.join(root, "articles"); + await mkdir(path.join(articles, "a1"), { recursive: true }); + await writeFile(path.join(articles, "a1", "report.json"), "{}"); + const outside = path.join(root, "outside", "a2"); + await mkdir(outside, { recursive: true }); + await symlink(outside, path.join(articles, "a2")); + const opt = { sitesDir: sites, articlesDir: articles, reportsRoot: path.join(root, "reports") }; + + const good = path.join(articles, "a1", "notes.json"); + assert.equal(corpusNotesFile("articles", "a1", opt), good); + assert.equal(await isCorpusNotesFile(good, opt), true); + assert.equal(await isCorpusNotesFile(path.join(articles, "a1", "report.json"), opt), false); + assert.equal(await isCorpusNotesFile(path.join(articles, "a1", "x", "notes.json"), opt), false); + assert.equal(await isCorpusNotesFile(path.join(articles, "a2", "notes.json"), opt), false, "a symlinked article dir"); + assert.equal(await isCorpusNotesFile(path.join(articles, "a9", "notes.json"), opt), false, "no such article"); + + const t = await articleTarget("articles/a1", opt); + assert.equal(t.file, good); + assert.deepEqual(t.subject, { kind: "article", site: "articles", report: "a1" }); + await writeNote(t, { op: "add", text: "x", anchor: { kind: "whole" } }, { by: "operator" }); + assert.deepEqual((await listNotesFiles(opt)).map((l) => [l.kind, l.id]), [["article", "articles/a1"]]); + assert.equal((await resolveTarget("articles/a1", opt)).file, good); + await assert.rejects(articleTarget("articles/a9", opt), (e) => e.status === 404); + await assert.rejects(articleTarget("articles/a2", opt), (e) => e.status === 403); + await rm(root, { recursive: true }); +}); diff --git a/umtool/lib/annotations/targets.mjs b/umtool/lib/annotations/targets.mjs @@ -7,13 +7,15 @@ // survives a regenerate; the compose stage and the report // history never read it (common/publish tests hold that), so // it is never published. The ONE corpus file umtool writes, -// and only through isCorpusNotesFile. +// and only through isCorpusNotesFile. An ARTICLE of the +// homepage's store (release 26) is `articles/<report>`: +// `ARTICLES_DIR/<report>/notes.json`, by the same rules. // video-project `<project>/notes.json`, beside video.manifest.json. A // report-video project under REPORTS_ROOT, found by the same // walk `umtool ls` uses. import { readdir, readFile, realpath, stat } from "node:fs/promises"; import path from "node:path"; -import { NOTES_FILENAME, REPORTS_ROOT, SEGMENT_RE, SITES_DIR, corpusNotesFile, inside, isCorpusNotesFile } from "../paths.mjs"; +import { ARTICLES_DIR, ARTICLES_KEY, NOTES_FILENAME, REPORTS_ROOT, SEGMENT_RE, SITES_DIR, corpusNotesFile, inside, isCorpusNotesFile } from "../paths.mjs"; import { projectRefs, resolveProject } from "../projects/core.mjs"; import { kindTakesNotes } from "../projects/kinds.mjs"; import { sourceFor, tildify } from "../articles/sources.mjs"; @@ -37,14 +39,14 @@ export class TargetError extends Error { * @param {string} spec `<site>/<report>` * @param {{ sitesDir?: string, reportsRoot?: string }} [opts] */ -export async function articleTarget(spec, { sitesDir = SITES_DIR, reportsRoot = REPORTS_ROOT } = {}) { +export async function articleTarget(spec, { sitesDir = SITES_DIR, articlesDir = ARTICLES_DIR, reportsRoot = REPORTS_ROOT } = {}) { const [site, report, ...rest] = String(spec ?? "").split("/"); if (rest.length || !SEGMENT_RE.test(site ?? "") || !SEGMENT_RE.test(report ?? "")) { - throw new TargetError(`not an article: ${JSON.stringify(spec)} (want <site>/<report>)`); + throw new TargetError(`not an article: ${JSON.stringify(spec)} (want <site>/<report> or articles/<id>)`); } - const file = corpusNotesFile(site, report, { sitesDir }); + const file = corpusNotesFile(site, report, { sitesDir, articlesDir }); if (!file || !(await exists(path.dirname(/* turbopackIgnore: true */ file)))) throw new TargetError(`no report ${site}/${report}`, 404); - if (!(await isCorpusNotesFile(file, { sitesDir }))) throw new TargetError(`refusing to write ${file}`, 403); + if (!(await isCorpusNotesFile(file, { sitesDir, articlesDir }))) throw new TargetError(`refusing to write ${file}`, 403); return { kind: "article", id: `${site}/${report}`, @@ -137,22 +139,32 @@ export async function projectSource(dir, reportsRoot = REPORTS_ROOT) { export async function resolveTarget(spec, opts = {}) { const parts = String(spec ?? "").split("/"); if (parts.length === 2 && parts.every((s) => SEGMENT_RE.test(s))) { - const dir = path.join(/* turbopackIgnore: true */ opts.sitesDir ?? SITES_DIR, parts[0], "reports", parts[1]); + const dir = + parts[0] === ARTICLES_KEY + ? path.join(/* turbopackIgnore: true */ opts.articlesDir ?? ARTICLES_DIR, parts[1]) + : path.join(/* turbopackIgnore: true */ opts.sitesDir ?? SITES_DIR, parts[0], "reports", parts[1]); if (await exists(dir)) return articleTarget(spec, opts); } return projectTarget(spec, opts); } /** - * Every notes.json there is: articles under SITES_DIR, projects under + * Every notes.json there is: articles under ARTICLES_DIR and SITES_DIR, projects under * REPORTS_ROOT. `{ target, file, doc, error? }` each; sorted by id. * * @param {{ sitesDir?: string, reportsRoot?: string }} [opts] */ -export async function listNotesFiles({ sitesDir = SITES_DIR, reportsRoot = REPORTS_ROOT } = {}) { +export async function listNotesFiles({ sitesDir = SITES_DIR, articlesDir = ARTICLES_DIR, reportsRoot = REPORTS_ROOT } = {}) { const out = []; + for (const report of await readdir(/* turbopackIgnore: true */ articlesDir).catch(() => [])) { + if (!SEGMENT_RE.test(report)) continue; + const file = path.join(/* turbopackIgnore: true */ articlesDir, report, NOTES_FILENAME); + if (!(await exists(file))) continue; + out.push({ kind: "article", id: `${ARTICLES_KEY}/${report}`, file, ...(await readNotes(file)) }); + } for (const site of await readdir(/* turbopackIgnore: true */ sitesDir).catch(() => [])) { if (!SEGMENT_RE.test(site)) continue; + if (site === ARTICLES_KEY) continue; for (const report of await readdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ sitesDir, site, "reports")).catch(() => [])) { if (!SEGMENT_RE.test(report)) continue; const file = path.join(/* turbopackIgnore: true */ sitesDir, site, "reports", report, NOTES_FILENAME); diff --git a/umtool/lib/articles/evidence.ts b/umtool/lib/articles/evidence.ts @@ -3,11 +3,11 @@ import path from "node:path"; import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; import { momentKeyOf } from "yt-dlp-transcript-common/lib/citations/moments"; import { evidenceSpan, resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip-server"; -import { reportMediaDir, reportMediaIndexFile } from "yt-dlp-transcript-common/publish/reportMedia"; +import { storeMediaDir, storeMediaIndexFile } from "yt-dlp-transcript-common/publish/reportMedia"; import { readCues } from "@/lib/projects/report.mjs"; import { CHANNELS_DIR } from "@/lib/paths"; import { channelPosts, corpusMediaUrl, postShotFile, recordDir, recordMeta } from "./article"; -import { sitesPaths } from "./sites"; +import { storeFor } from "./sites"; // What a citation's EVIDENCE panel shows: the cited seconds with the transcript // around them, and something to play -- found, never fetched. @@ -84,10 +84,10 @@ async function preparedClip(siteId: string, c: Cite): Promise<EvidencePlay | nul const key = momentKeyOf(c); if (!key) return null; try { - const index = JSON.parse(await readFile(/* turbopackIgnore: true */ reportMediaIndexFile(sitesPaths(), siteId), "utf8")); + const index = JSON.parse(await readFile(/* turbopackIgnore: true */ storeMediaIndexFile(storeFor(siteId)), "utf8")); const entry = index?.moments?.[key]; if (!entry || (entry.kind !== "video" && entry.kind !== "audio") || typeof entry.file !== "string") return null; - const abs = path.join(/* turbopackIgnore: true */ reportMediaDir(sitesPaths(), siteId), entry.file); + const abs = path.join(/* turbopackIgnore: true */ storeMediaDir(storeFor(siteId)), entry.file); let from = evidenceSpan(c).from; try { const side = JSON.parse(await readFile(/* turbopackIgnore: true */ abs.replace(/\.(mp4|m4a)$/, ".json"), "utf8")); diff --git a/umtool/lib/articles/href.ts b/umtool/lib/articles/href.ts @@ -0,0 +1,16 @@ +import { ARTICLES_KEY } from "./key.mjs"; + +// Where an article opens in umtool: `/articles/<id>` for one of the article +// store's (release 26), `/sites/<site>/<id>` for a site's own page. Pure, so a +// client component can link with it. +export function articleHref(a: { site: string; id: string }): string { + return a.site === ARTICLES_KEY ? `/articles/${a.id}` : `/sites/${a.site}/${a.id}`; +} + +// The same from a notes target id, `<site>/<report>`. +export function articleHrefOf(targetId: string): string { + const [site, id] = targetId.split("/"); + return articleHref({ site, id }); +} + +export { ARTICLES_KEY }; diff --git a/umtool/lib/articles/key.mjs b/umtool/lib/articles/key.mjs @@ -0,0 +1,6 @@ +// The reserved "site" that names the ARTICLE STORE (release 26: +// `transcripts/reports/<id>/`, the reports the project homepage publishes). +// In umtool an article is `<site>/<report>` either way: `articles/<id>` is +// one of the store's. Plain ESM with no imports, so lib/paths.mjs (node) and +// a client component (./href.ts) share the one spelling. +export const ARTICLES_KEY = "articles"; diff --git a/umtool/lib/articles/sites.ts b/umtool/lib/articles/sites.ts @@ -2,10 +2,13 @@ import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; import { getSite, isListedSite, isPrivateSite, listSites, type Site } from "yt-dlp-transcript-common/lib/site"; -import { listReportDirs, siteReportDir } from "yt-dlp-transcript-common/publish/reportMedia"; +import { listReportDirs } from "yt-dlp-transcript-common/publish/reportMedia"; +import { articleReportStore, siteReportStore, storeReportDir, type ReportStore } from "yt-dlp-transcript-common/lib/report/store"; +import { articleAudience, listArticleDirs, readArticlesIndex } from "yt-dlp-transcript-common/lib/report/registry"; +import type { ReportAudience } from "yt-dlp-transcript-common/lib/report/schema"; import { parseReport } from "yt-dlp-transcript-common/lib/report/validate"; import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; -import { CHANNELS_DIR, REPORTS_ROOT, SITES_DIR } from "@/lib/paths"; +import { ARTICLES_DIR, ARTICLES_KEY, CHANNELS_DIR, REPORTS_ROOT, SITES_DIR } from "@/lib/paths"; import { readNotes } from "@/lib/annotations/store.mjs"; import { corpusNotesFile } from "@/lib/paths"; import type { NotesDoc } from "@/lib/annotations/types"; @@ -16,15 +19,30 @@ import { linkedProjects, videoProjects } from "./links.mjs"; // (site.json through getSite, so a default is the editor's default), each // report directory through common's listReportDirs (the editor's report tab // uses the same enumerator), each report.json through the report document's -// own validator, and published-or-draft from the site's `reports` order. Plus +// own validator, and published-or-draft from the site's `pages` order. Plus // what only umtool knows: its notes, its source draft, its video project. // // READ-ONLY. The one thing umtool writes under SITES_DIR is a notes.json, and // that goes through lib/annotations, never here. -/** common's Paths, with the two roots umtool resolves itself (and e2e confines). */ +/** common's Paths, with the three roots umtool resolves itself (and e2e confines). */ export function sitesPaths(): Paths { - return { ...getPaths(), sitesDir: SITES_DIR, channelsDir: CHANNELS_DIR }; + return { ...getPaths(), sitesDir: SITES_DIR, channelsDir: CHANNELS_DIR, articlesDir: ARTICLES_DIR }; +} + +/** + * Where `<site>/<report>` lives: a site's report store, or -- for the reserved + * key ARTICLES_KEY -- the article store (`transcripts/reports/`, release 26). + * Every umtool reader of a report directory, its prepared media and its notes + * goes through this, so `articles/<id>` is one more "site" to the article + * pages, the media route and the notes. + */ +export function storeFor(site: string): ReportStore { + return site === ARTICLES_KEY ? articleReportStore(sitesPaths()) : siteReportStore(sitesPaths(), site); +} + +export function reportDirFor(site: string, report: string): string { + return storeReportDir(storeFor(site), report); } export type ArticleStatus = "published" | "draft"; @@ -47,6 +65,8 @@ export type ArticleRow = { openNotes: number; hasVideo: boolean; hasPoster: boolean; + /** An article's audience (the article store's only; a site's report has its site's). */ + audience?: ReportAudience; /** report.json missing, unparseable, or invalid: the first problem, else null. */ problem: string | null; problems: number; @@ -76,7 +96,7 @@ export type ArticleRead = { /** One report.json, read and validated; never throws. */ export async function readReportFile(siteId: string, reportId: string): Promise<ArticleRead> { - const file = path.join(/* turbopackIgnore: true */ siteReportDir(sitesPaths(), siteId, reportId), "report.json"); + const file = path.join(/* turbopackIgnore: true */ reportDirFor(siteId, reportId), "report.json"); let text: string; let mtimeMs: number | null = null; try { @@ -103,18 +123,18 @@ export async function readArticleNotes(siteId: string, reportId: string): Promis return readNotes(file); } -async function articleRow(site: Site, id: string, published: Set<string>, projects: Awaited<ReturnType<typeof videoProjects>>): Promise<ArticleRow> { +async function articleRow(siteId: string, id: string, published: Set<string>, projects: Awaited<ReturnType<typeof videoProjects>>): Promise<ArticleRow> { const [read, notes, source] = await Promise.all([ - readReportFile(site.siteId, id), - readArticleNotes(site.siteId, id), - sourceFor(site.siteId, id, { reportsRoot: REPORTS_ROOT }), + readReportFile(siteId, id), + readArticleNotes(siteId, id), + sourceFor(siteId, id, { reportsRoot: REPORTS_ROOT }), ]); - const dir = siteReportDir(sitesPaths(), site.siteId, id); + const dir = reportDirFor(siteId, id); const r = read.report; - const links = await linkedProjects(site.siteId, id, { workspace: source?.workspace ?? null, projects }); + const links = await linkedProjects(siteId, id, { workspace: source?.workspace ?? null, projects }); const row = (p: { id: string; title: string; slug: string }) => ({ id: p.id, title: p.title, slug: p.slug }); return { - site: site.siteId, + site: siteId, id, title: r?.title ?? id, series: r?.series ?? null, @@ -132,6 +152,7 @@ async function articleRow(site: Site, id: string, published: Set<string>, projec problems: read.problems.length, source, projects: { linked: links.linked.map(row), possible: links.possible.map(row) }, + ...(siteId === ARTICLES_KEY ? { audience: articleAudience(r) } : {}), }; } @@ -145,7 +166,7 @@ export async function readSiteRow(site: Site, projects?: Awaited<ReturnType<type const published = new Set(site.pages ?? []); const dirs = await listReportDirs(sitesPaths(), site.siteId); const ids = [...(site.pages ?? []), ...dirs.filter((d) => !published.has(d))]; - const articles = await Promise.all(ids.map((id) => articleRow(site, id, published, all))); + const articles = await Promise.all(ids.map((id) => articleRow(site.siteId, id, published, all))); return { siteId: site.siteId, title: site.siteTitle || site.siteId, @@ -175,3 +196,43 @@ export function siteById(siteId: string): Site | null { return null; } } + +/** The article store (/articles): every article, published (index.json's order) then drafts. */ +export type StoreRow = { + published: number; + drafts: number; + publicCount: number; + openNotes: number; + articles: ArticleRow[]; + /** index.json could not be read: what is wrong (nothing is then published). */ + indexError: string | null; +}; + +export async function readStoreRow(projects?: Awaited<ReturnType<typeof videoProjects>>): Promise<StoreRow> { + const all = projects ?? (await videoProjects(REPORTS_ROOT)); + const paths = sitesPaths(); + let order: string[] = []; + let indexError: string | null = null; + try { + order = (await readArticlesIndex(paths)).published; + } catch (err) { + indexError = (err as Error).message; + } + const published = new Set(order); + const dirs = await listArticleDirs(paths); + const ids = [...order, ...dirs.filter((d) => !published.has(d))]; + const articles = await Promise.all(ids.map((id) => articleRow(ARTICLES_KEY, id, published, all))); + return { + published: articles.filter((a) => a.status === "published").length, + drafts: articles.filter((a) => a.status === "draft").length, + publicCount: articles.filter((a) => a.status === "published" && a.audience === "public").length, + openNotes: articles.reduce((n, a) => n + a.openNotes, 0), + articles, + indexError, + }; +} + +/** Is `site` a real site, or the article store's key? */ +export function isReportHost(site: string): boolean { + return site === ARTICLES_KEY || siteById(site) !== null; +} diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -6,6 +6,7 @@ import { readSpec, validateSpec } from "./spec"; import { readNotes, type NoteMap } from "./notes"; import { listNotesFiles } from "./annotations/targets.mjs"; import { acceptedFor, readThumbAccepted, readThumbManifest, thumbNamesFor } from "./thumbs"; +import { articleHrefOf } from "./articles/href"; // --------------------------------------------------------------------------- // Everything undecided, in one worklist. @@ -343,7 +344,7 @@ export async function noteDecisions(): Promise<Decision[]> { for (const f of files) { const article = f.kind === "article"; const project = article ? `sites/${f.id}` : f.id; - const page = article ? `/sites/${f.id}` : `/browse/${f.id}`; + const page = article ? articleHrefOf(f.id) : `/browse/${f.id}`; if (f.error || !f.doc) { out.push({ kind: "unreadable-notes", diff --git a/umtool/lib/paths.mjs b/umtool/lib/paths.mjs @@ -9,6 +9,7 @@ import { lstat, realpath } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { SONG_DATA, SONG_REPORTS } from "../song/paths.mjs"; +import { ARTICLES_KEY } from "./articles/key.mjs"; // SONG_REPORTS -- the um-song deliverables tree, and BROWSE_ROOT's parent -- is // defined in song/paths.mjs beside SONG_DATA, because the song scripts that @@ -250,10 +251,29 @@ export const SITES_DIR = path.resolve( : path.join(/* turbopackIgnore: true */ REPO_ROOT, "transcripts", "sites")), ); +// The ARTICLES -- `transcripts/reports/<id>/` (release 26), the reports the +// project homepage publishes, and `index.json`, the published list. Resolved +// as common/lib/paths.ts resolves its articlesDir (`ARTICLES_DIR`, else +// `<TRANSCRIPTS_DIR>/reports`), so one `ARTICLES_DIR` confines both. Readable +// only, but for an article's notes.json (isCorpusNotesFile). +// +// In umtool an article is named as a site's report is, with the reserved +// "site" ARTICLES_KEY: `articles/<id>` (a notes target, a manifest's +// `"article"`, the media route's `?site=articles`). A site whose id is +// `articles` is shadowed by it here. +export const ARTICLES_DIR = path.resolve( + /* turbopackIgnore: true */ + process.env.ARTICLES_DIR ?? + (process.env.TRANSCRIPTS_DIR + ? path.join(/* turbopackIgnore: true */ process.env.TRANSCRIPTS_DIR, "reports") + : path.join(/* turbopackIgnore: true */ REPO_ROOT, "transcripts", "reports")), +); +export { ARTICLES_KEY }; + export const READ_ROOTS = dedupe( process.env.MIX_ROOTS ? process.env.MIX_ROOTS.split(":").filter(Boolean) - : [SONG_REPORTS, REPORTS_ROOT, SONG_DATA, SONG_SCRATCH, CHANNELS_DIR, MEDIA_ROOT, SITES_DIR], + : [SONG_REPORTS, REPORTS_ROOT, SONG_DATA, SONG_SCRATCH, CHANNELS_DIR, MEDIA_ROOT, SITES_DIR, ARTICLES_DIR], ); /** A site id or a report id: one lowercase url-safe segment (common/lib/report/schema.ts REPORT_ID_RE). */ @@ -261,7 +281,8 @@ export const SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; export const NOTES_FILENAME = "notes.json"; /** - * The ONE corpus path umtool may write: `SITES_DIR/<site>/reports/<id>/notes.json`. + * The ONE corpus path umtool may write: `SITES_DIR/<site>/reports/<id>/notes.json` + * -- or an article's, `ARTICLES_DIR/<id>/notes.json`, by the same rules. * * Lexically: exactly four segments under SITES_DIR, the second `reports`, the * site and report ids in the report-id grammar, the file named notes.json, and @@ -277,9 +298,10 @@ export const NOTES_FILENAME = "notes.json"; * @param {{ sitesDir?: string }} [opts] * @returns {Promise<boolean>} */ -export async function isCorpusNotesFile(abs, { sitesDir = SITES_DIR } = {}) { +export async function isCorpusNotesFile(abs, { sitesDir = SITES_DIR, articlesDir = ARTICLES_DIR } = {}) { if (typeof abs !== "string" || !path.isAbsolute(abs) || abs.includes("\0")) return false; if (path.resolve(/* turbopackIgnore: true */ abs) !== abs) return false; + if (await isArticleNotesFile(abs, articlesDir)) return true; const root = path.resolve(/* turbopackIgnore: true */ sitesDir); const rel = path.relative(/* turbopackIgnore: true */ root, abs); if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false; @@ -299,9 +321,31 @@ export async function isCorpusNotesFile(abs, { sitesDir = SITES_DIR } = {}) { return !st || st.isFile(); } -/** `SITES_DIR/<site>/reports/<report>/notes.json`, or null for a bad id. */ -export function corpusNotesFile(site, report, { sitesDir = SITES_DIR } = {}) { +/** `ARTICLES_DIR/<report>/notes.json`: two segments, the report dir real and already there. */ +async function isArticleNotesFile(abs, articlesDir) { + const root = path.resolve(/* turbopackIgnore: true */ articlesDir); + const rel = path.relative(/* turbopackIgnore: true */ root, abs); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false; + const parts = rel.split(path.sep); + if (parts.length !== 2 || !SEGMENT_RE.test(parts[0]) || parts[1] !== NOTES_FILENAME) return false; + const [realRoot, realDir] = await Promise.all([ + realpath(/* turbopackIgnore: true */ root).catch(() => null), + realpath(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ abs)).catch(() => null), + ]); + if (!realRoot || !realDir || realDir !== path.join(/* turbopackIgnore: true */ realRoot, parts[0])) return false; + const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null); + return !st || st.isFile(); +} + +/** + * `SITES_DIR/<site>/reports/<report>/notes.json` -- `ARTICLES_DIR/<report>/notes.json` + * when `site` is ARTICLES_KEY -- or null for a bad id. + */ +export function corpusNotesFile(site, report, { sitesDir = SITES_DIR, articlesDir = ARTICLES_DIR } = {}) { if (!SEGMENT_RE.test(String(site)) || !SEGMENT_RE.test(String(report))) return null; + if (site === ARTICLES_KEY) { + return path.join(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ articlesDir), report, NOTES_FILENAME); + } return path.join(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ sitesDir), site, "reports", report, NOTES_FILENAME); } diff --git a/umtool/lib/paths.ts b/umtool/lib/paths.ts @@ -19,6 +19,8 @@ import path from "node:path"; // command line and this app can never disagree about which directory is which. // --------------------------------------------------------------------------- export { + ARTICLES_DIR, + ARTICLES_KEY, CACHE_DIR, CHANNELS_DIR, cacheFile, diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -126,6 +126,9 @@ export default defineConfig({ // transcripts/sites -- the one corpus file umtool writes is a report's // notes.json, and the suite writes them. `SITES_DIR=${FIXTURE}/sites ` + + // The article store (/articles, release 26): the fixture's own, for the + // same reason -- an article's notes.json is written beside it. + `ARTICLES_DIR=${FIXTURE}/articles ` + // The cache (the project index, posters, analyses) is no longer under // SONG_DIR (release 17): its default is the user's ~/.cache, which a // suite must never write. The fixture's own, rebuilt with it every run.