import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; import { ARTICLES_KEY, REPORTS_ROOT } from "./paths"; import { articleHref } from "./articles/href"; import { listSiteRows, readStoreRow, sitesPaths, type ArticleRow } from "./articles/sites"; import { iterationProjects, linkedProjects, linksCacheEpoch, videoProjects } from "./articles/links.mjs"; import { listProjects } from "./projects"; import type { ProjectSummary } from "./project-types"; import { listBatches } from "./report/deliver.mjs"; import { articleOfDecisionProject, articlePieceId, projectPieceId } from "./pieces/ids.mjs"; import { lifecycleOf, readLifecycle, type LifecycleRead, type LifecycleState } from "./lifecycle"; import { boardOfArticle, boardOfProject } from "./pieces/board.mjs"; import { readCases } from "./pieces/cases"; import { stageOfPiece } from "./pieces/tabs.mjs"; import { kindById } from "./projects/kinds.mjs"; import type { Decision } from "./decisions"; import { chipOf, readSchedules } from "./schedules"; import type { ScheduleChipData, ScheduleView } from "./schedule-types"; export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId, seriesPieceId } from "./pieces/ids.mjs"; // --------------------------------------------------------------------------- // PIECES (plans/umtool-redesign.md): the unit the operator works on. // // an ARTICLE piece `a:/` -- a site's report, or one of the // article store's (`articles/`, published, draft or // still in the making) -- plus every video project linked // to it (lib/articles/links.mjs: its iterations, then a // manifest that names it, then a unique slug) // a PROJECT piece `p:` -- a project under REPORTS_ROOT linked to no // article: a song, a hand-made report video, a sweep // a SERIES piece `s:` -- a recurring report's dated editions (R5, // lib/schedules.ts); each edition is a store article that // names its series (`series`), and Work lists the series, // not its editions. A living report is its article's // piece, with the schedule's chip (`schedule`). // // A project linked to two articles belongs to the first that claims it, by // strength (iteration, then manifest, then slug) and then in list order -- // private sites first, as /sites lists them. // // SERVER ONLY. The article side re-reads every report.json (lib/articles/ // sites.ts), so the graph is memoised for MEMO_MS -- and dropped at once by // anything that clears the links cache (a project or an article deleted), the // way clearLinksCache already drops the links, or by a change in the article // store's directory list (an article started by the editor's generation). The lifecycle is NOT memoised: // it is one small file, and a park has to show on the next read. // --------------------------------------------------------------------------- export type PieceKind = "article" | "project" | "series"; export type PieceProject = { id: string; title: string; via: "iteration" | "manifest" | "slug"; /** The one the article's Cut opens (current.video's, else the first linked). */ cut: boolean; /** The project's state (draft … built, shipped, stale), or null when the walk did not summarise it. */ state: string | null; href: string; }; export type Piece = { id: string; kind: PieceKind; title: string; /** An article's site (`articles` for the store), else null. */ site: string | null; report: string | null; /** A project piece's project id, else null. */ project: string | null; href: string; /** An article's: published, draft, or in the making (iterations, no report.json). */ status: "published" | "draft" | "in the making" | null; /** A store article's audience (public | private); a site's report and a project have none. */ audience: string | null; /** * Where it is. An article: the step its stepper has current, by the one * stage rule (lib/pieces/tabs.mjs pieceSteps over `reached`). A project: its * own state (draft, windows, fetched, built, shipped, stale) -- Work's stage * facet reads `reached` for it too. */ stage: string; /** * The stepper the piece walks (lib/pieces/tabs.mjs pieceSteps' `kind`): `article`, * `project` (a report video's four stages), or the flow its project's kind * declares (a song's Spec → Cuts → Done, lib/pieces/song-tabs.mjs). */ flow: string; /** What the piece has reached, the one stage rule's facts (lib/pieces/tabs.mjs pieceSteps). */ reached: Reached; projects: PieceProject[]; /** Slug matches nobody has chosen between (link-ambiguous). */ possible: { id: string; title: string }[]; /** Iterations whose project is outside REPORTS_ROOT: not reachable here. */ unreachable: { n: number; dir: string }[]; /** Why it looks done, when it does. A suggestion: it never sets the lifecycle. */ looksDone: string[]; newestMs: number; /** A recurring report's schedule (R5): a series', or a living report's on its article; else null. */ schedule: ScheduleChipData | null; /** The series an edition's article belongs to (R5), else null. */ series: string | null; }; /** The one stage rule's facts: the four stages, and a song's own three (lib/pieces/song-tabs.mjs). */ export type Reached = { research: boolean; article: boolean; video: boolean; deliver: boolean; spec?: boolean; cuts?: boolean; done?: boolean; }; export type PieceWithLifecycle = Piece & { lifecycle: LifecycleState; lifecycleAt: string | null; lifecycleBy: string | null }; export type PieceGraph = { pieces: Piece[]; byId: Map; /** Project id → the piece it belongs to. */ pieceOfProject: Map; /** A project's basename → its id, when the name is unique (the song routes' alias). */ projectByName: Map; }; const MEMO_MS = 15_000; type Memo = { at: number; epoch: number; sig: string; value: Promise }; // On globalThis, not in module scope: each Next bundle has its own copy of this // module, and the epoch it compares (links.mjs) is per process. const MEMO = ((globalThis as { __umtoolPieces?: { memo: Memo | null } }).__umtoolPieces ??= { memo: null }); /** Drop the memo (a test, or a write that changed what an article links). */ export function clearPiecesCache(): void { MEMO.memo = null; } /** * The article store's directory names: one readdir. An article started (or * deleted) by a route this module never hears from -- the editor's generation * writes the store itself -- changes it, so a new article is listed at once * rather than when the memo runs out. */ async function storeSignature(): Promise { let store = ""; try { store = (await readdir(/* turbopackIgnore: true */ sitesPaths().articlesDir)).sort().join("\u0000"); } catch { store = ""; } // The research cases too (R2): a board's hand-off makes a piece's Research // stage, so a new hand-off is seen at once (one stat per case; cases are few). const dir = path.join(/* turbopackIgnore: true */ REPORTS_ROOT, ".umtool", "research"); const cases = await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[]); const stamps = await Promise.all( cases.sort().map((c) => stat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, c, "case.json")).then( (st) => `${c}:${st.mtimeMs}`, () => "", ), ), ); return `${store}\u0001${stamps.join("\u0000")}`; } /** How many iterations the article store holds for an article (a readdir). */ async function hasIterations(id: string): Promise { const names = await readdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ sitesPaths().articlesDir, id, "iterations")).catch( () => [] as string[], ); return names.some((n) => /^[1-9][0-9]*$/.test(n)); } export async function readPieceGraph(): Promise { const epoch = linksCacheEpoch(); const sig = await storeSignature(); const memo = MEMO.memo; if (memo && memo.epoch === epoch && memo.sig === sig && Date.now() - memo.at < MEMO_MS) return memo.value; const value = buildGraph(); const entry = { at: Date.now(), epoch, sig, value }; MEMO.memo = entry; value.catch(() => { if (MEMO.memo === entry) MEMO.memo = null; }); return value; } type LinkRow = { id: string; title: string; via?: "iteration" | "manifest" | "slug" }; type ArticleIn = { site: string; id: string; title: string; status: Piece["status"]; audience: string | null; hasVideo: boolean; mtimeMs: number; linked: LinkRow[]; possible: { id: string; title: string }[]; cut: string | null; unreachable: { n: number; dir: string }[]; }; const STRENGTH = { iteration: 0, manifest: 1, slug: 2 } as const; function fromRow(a: ArticleRow): ArticleIn { return { site: a.site, id: a.id, title: a.title, status: a.status, audience: a.audience ?? null, hasVideo: a.hasVideo, mtimeMs: a.mtimeMs ?? 0, linked: a.projects.linked, possible: a.projects.possible.map((p) => ({ id: p.id, title: p.title })), cut: a.projects.cut ?? null, unreachable: a.projects.unreachable ?? [], }; } async function pendingArticles(topics: Map = new Map()): Promise { const ids = await listPendingArticles(sitesPaths()).catch(() => [] as string[]); const projects = await videoProjects(REPORTS_ROOT); return Promise.all( ids.map(async (id) => { const links = await linkedProjects(ARTICLES_KEY, id, { projects }); return { site: ARTICLES_KEY, id, // A living report waiting for its first tick is named by its topic (R5). title: topics.get(id) ?? id, status: "in the making" as const, audience: null, hasVideo: false, mtimeMs: 0, linked: links.linked as LinkRow[], possible: (links.possible as LinkRow[]).map((p) => ({ id: p.id, title: p.title })), cut: links.cut ?? null, unreachable: links.unreachable ?? [], }; }), ); } /** Why a project looks finished, or null. Kind-blind: it reads the shared state vocabulary. */ async function projectLooksDone(p: ProjectSummary): Promise { // A song's derived `shipped` (every cut present, lib/projects/song.mjs). if (p.state === "shipped") return `${p.id}: every cut shipped`; // A final video, current with its manifest, AND a share batch made from it. if (p.state === "built") { const batches = await listBatches(p.dir).catch(() => [] as { name: string }[]); if (batches.length) return `${p.id}: final video and ${batches.map((b: { name: string }) => b.name).join(", ")}`; } return null; } async function buildGraph(): Promise { // The article side must never take the decisions down with it: a site whose // site.json does not read is an article list without that site, not a 500. // The recurring reports (R5) first: a living report's topic names its // article while it is in the making. const schedules = (await readSchedules().catch(() => ({ schedules: [] as ScheduleView[] }))).schedules; const living = new Map(schedules.filter((v) => v.shape === "living").map((v) => [v.article ?? v.id, v])); // A series' edition, and what a watch's escalation wrote (R6), are the schedule's. const editionOf = new Map([ ...schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [[e.article, v.id] as const] : []))), ...schedules.flatMap((v) => (v.shape === "watch" ? v.ticks.flatMap((t) => (t.article ? [[t.article, v.id] as const] : [])) : [])), ]); const [sites, store, pending, summaries, its, cases] = await Promise.all([ listSiteRows().catch(() => []), readStoreRow().catch(() => ({ articles: [] as ArticleRow[] })), pendingArticles(new Map([...living].map(([a, v]) => [a, v.topic]))).catch(() => [] as ArticleIn[]), listProjects(), iterationProjects().catch(() => new Map()), readCases().catch(() => []), ]); const articles: ArticleIn[] = [ ...sites.flatMap((s) => s.articles.map(fromRow)), ...store.articles.map(fromRow), ...pending, ]; const summaryOf = new Map(summaries.map((p) => [p.id, p])); // Who owns each linked project: the strongest link, then list order. const pieceOfProject = new Map(); const claims = articles.flatMap((a, order) => a.linked.map((p) => ({ project: p.id, piece: articlePieceId(a.site, a.id), strength: STRENGTH[p.via ?? "slug"], order })), ); claims.sort((x, y) => x.strength - y.strength || x.order - y.order); for (const c of claims) if (!pieceOfProject.has(c.project)) pieceOfProject.set(c.project, c.piece); const doneCache = new Map>(); const looksDoneOf = (id: string) => { const s = summaryOf.get(id); if (!s) return Promise.resolve(null); let hit = doneCache.get(id); if (!hit) doneCache.set(id, (hit = projectLooksDone(s))); return hit; }; const pieces: Piece[] = []; for (const a of articles) { const id = articlePieceId(a.site, a.id); const projects: PieceProject[] = a.linked.map((p) => ({ id: p.id, title: p.title, via: p.via ?? "slug", cut: p.id === a.cut, state: summaryOf.get(p.id)?.state ?? null, href: `/projects/${p.id}`, })); const looksDone: string[] = []; const currentVideo = a.site === ARTICLES_KEY && (its.get(a.id) ?? []).some((x: { current: boolean }) => x.current); if (a.status === "published" && (a.hasVideo || currentVideo)) looksDone.push("published with its video"); for (const p of projects) { if (pieceOfProject.get(p.id) !== id) continue; const why = await looksDoneOf(p.id); if (why) looksDone.push(why); } const newestMs = Math.max(a.mtimeMs, ...projects.map((p) => summaryOf.get(p.id)?.newestMtimeMs ?? 0)); const href = articleHref({ site: a.site, id: a.id }); const owned = projects.filter((p) => pieceOfProject.get(p.id) === id).length; const reached = { research: (a.site === ARTICLES_KEY && (a.status === "in the making" || (await hasIterations(a.id)))) || !!boardOfArticle(href, cases), article: a.status !== "in the making", video: owned > 0 || a.unreachable.length > 0 || a.hasVideo || currentVideo, deliver: looksDone.length > 0, }; pieces.push({ id, kind: "article", flow: "article", title: a.title, site: a.site, report: a.id, project: null, href, status: a.status, audience: a.audience, stage: stageOfPiece({ kind: "article", reached }), reached, projects, possible: a.possible, unreachable: a.unreachable, looksDone, newestMs, schedule: a.site === ARTICLES_KEY && living.has(a.id) ? chipOf(living.get(a.id)!) : null, series: a.site === ARTICLES_KEY ? (editionOf.get(a.id) ?? null) : null, }); } // A series (R5): its editions are store articles; the series is the piece // Work lists and the Inbox's edition and tick cards are on. for (const v of schedules) { if (v.shape === "living") continue; const done = (v.editions ?? []).some((e) => e.status === "done") || v.ticks.some((t) => t.article && t.triage?.escalated); const reached = { research: (v.editions ?? []).length > 0 || v.ticks.length > 0, article: done, video: false, deliver: false }; pieces.push({ id: v.piece, kind: "series", flow: "article", title: v.topic, site: null, report: null, project: null, href: v.href, status: null, audience: null, stage: stageOfPiece({ kind: "article", reached }), reached, projects: [], possible: [], unreachable: [], looksDone: [], newestMs: Math.max(Date.parse(v.updatedAt) || 0, Date.parse(v.lastTick ?? "") || 0), schedule: chipOf(v), series: null, }); } for (const p of summaries) { if (pieceOfProject.has(p.id)) continue; const why = await looksDoneOf(p.id); // The stepper the project's kind declares (a song's Spec → Cuts → Done) and // the facts that light it; else a report video's four stages. const declared = (kindById(p.kind) as { piece?: { flow: string; reached?: (s: ProjectSummary) => Promise> } } | null)?.piece; const own = declared?.reached ? await declared.reached(p).catch(() => ({})) : {}; pieces.push({ id: projectPieceId(p.id), kind: "project", flow: declared?.flow ?? "project", title: p.title, site: null, report: null, project: p.id, href: `/projects/${p.id}`, status: null, audience: null, stage: p.state, reached: { research: !!boardOfProject(p.id, cases), article: false, video: true, deliver: !!why || p.state === "shipped", ...own }, projects: [], possible: [], unreachable: [], looksDone: why ? [why] : [], newestMs: p.newestMtimeMs, schedule: null, series: null, }); pieceOfProject.set(p.id, projectPieceId(p.id)); } const names = new Map(); for (const p of summaries) names.set(p.name, [...(names.get(p.name) ?? []), p.id]); const projectByName = new Map([...names].filter(([, ids]) => ids.length === 1).map(([n, ids]) => [n, ids[0]])); pieces.sort((a, b) => b.newestMs - a.newestMs || a.id.localeCompare(b.id)); return { pieces, byId: new Map(pieces.map((p) => [p.id, p])), pieceOfProject, projectByName }; } /** The piece a decision row is about, or null when nothing on disk owns it. */ export function pieceOfDecision(d: Decision, graph: PieceGraph): string | null { if (d.piece) return d.piece; if (d.projectKind === "article") { const a = articleOfDecisionProject(d.project); return a ? articlePieceId(a.site, a.report) : null; } const id = graph.pieceOfProject.has(d.project) ? d.project : graph.projectByName.get(d.project); return id ? (graph.pieceOfProject.get(id) ?? null) : null; } /** Every piece, with its lifecycle (read now, never memoised). */ export async function listPieces(read?: LifecycleRead): Promise { const [graph, life] = await Promise.all([readPieceGraph(), read ? Promise.resolve(read) : readLifecycle()]); return graph.pieces.map((p) => { const e = life.pieces[p.id]; return { ...p, lifecycle: lifecycleOf(life, p.id), lifecycleAt: e?.at ?? null, lifecycleBy: e?.by ?? null }; }); }