Archilyzer · Source

archilyzer

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

commit ba8c08403fa5e07d893ddd693130bf0dabce7e99
parent a8e6f1bfba2702caf72b2186334f64fadb247580
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 14:12:32 -0400

umtool: /articles — the homepage's article store, its pages, evidence and notes

Release 26 A6. umtool reads the article store (ARTICLES_DIR, else
<TRANSCRIPTS_DIR>/reports — common's getPaths takes the same ARTICLES_DIR,
ENVIRONMENT.md regenerated) beside the sites:

- /articles: every article, published in reports/index.json's order then
  drafts, with its audience, notes, video project and source; filters by
  status, audience and open notes; "site pages" links /sites. The nav's
  "articles" now opens /articles (/sites still marks it).
- /articles/<id> and /articles/<id>/evidence: the article page and the
  evidence walk, now shared components (ArticlePage, EvidencePage) that a
  site's /sites/<site>/<report> pages render too.
- An article is `articles/<id>` to every umtool reader: the media and
  evidence routes (?site=articles), the notes target and CLI (`umtool notes
  articles/<id>`), a manifest's "article" link. Its notes.json is beside its
  report.json, through isCorpusNotesFile's same rules. A site whose id is
  `articles` is shadowed in umtool (documented).

Unit: notes targets over the store; the existing notes tests now use a temp
article store of their own. e2e: articles.spec.ts, the fixture gains
articles/ (delta published+public, epsilon a draft).

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

Diffstat:
MENVIRONMENT.md | 1+
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/paths.ts | 2+-
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++++++++++++-------
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 | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mumtool/lib/decisions.ts | 3++-
Mumtool/lib/paths.mjs | 54+++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/paths.ts | 2++
Mumtool/playwright.config.ts | 3+++
33 files changed, 819 insertions(+), 316 deletions(-)

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/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 @@ -242,7 +242,7 @@ export function getPaths(): Paths { process.env.SAVED_VIDEOS_DIR ?? under(transcriptsDir, "saved-videos"), sitesDir, homepageDir, - articlesDir: under(transcriptsDir, "reports"), + 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/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.reports ?? []).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.reports ?? []).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/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"; @@ -22,9 +25,24 @@ import { linkedProjects, videoProjects } from "./links.mjs"; // 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.reports ?? []); const dirs = await listReportDirs(sitesPaths(), site.siteId); const ids = [...(site.reports ?? []), ...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.