Archilyzer · Source

archilyzer

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

commit de85933803824aa207adc571bbf12156792f6266
parent 74f2fd79620456e52e308073b4ad0b91d34a7167
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 00:04:03 -0400

umtool: the inbox engine — pieces, the generation era's decisions, lifecycle routes, `umtool inbox`

lib/pieces.ts: every article (sites, the store, in the making) with its linked
projects, and every project no article claims; stage, looks-done reasons; the
article side memoised 15 s and dropped with the links cache. lib/inbox.ts:
openDecisions() plus iteration-ready, iteration-failed, research-proposal
(readResearchState, never the editor), link-ambiguous and looks-done, each row
annotated (piece, category, group, action, lifecycle, hidden) and ranked.
GET /api/browse/decisions keeps items[] one row per decision and adds groups
and hidden; GET /api/pieces; POST /api/pieces/lifecycle. `umtool inbox`
prints the grouped list through tsx.

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

Diffstat:
Mumtool/app/api/browse/decisions/route.ts | 23+++++++++++++++++++----
Aumtool/app/api/pieces/lifecycle/route.ts | 38++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/pieces/route.ts | 32++++++++++++++++++++++++++++++++
Aumtool/bin/inbox.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 27+++++++++++++++++++++++++++
Mumtool/lib/decisions.ts | 15+++++++++++++++
Aumtool/lib/inbox.ts | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces.ts | 292+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 739 insertions(+), 4 deletions(-)

diff --git a/umtool/app/api/browse/decisions/route.ts b/umtool/app/api/browse/decisions/route.ts @@ -1,5 +1,5 @@ -import { countBySeverity, decisionsForSong } from "@/lib/decisions"; -import { openDecisions } from "@/lib/projects"; +import { countBySeverity } from "@/lib/decisions"; +import { readInbox } from "@/lib/inbox"; import { isSegment } from "@/lib/browse"; export const dynamic = "force-dynamic"; @@ -12,17 +12,32 @@ export const dynamic = "force-dynamic"; // // `?project=` narrows to one. The parameter is deliberately not called `song`, // because nothing else in this route knows what a song is. +// +// `items[]` is ONE ROW PER DECISION, never grouped and never filtered: the MCP +// reads it (mcp/src/archivalTools.ts: `open-note` rows, `project` as the notes +// target, `href` ending in `note=<id>`). The inbox's fields on each row -- +// `piece`, `category`, `group`, `action`, `lifecycle`, `hidden` -- are +// additive (lib/inbox.ts), and so is `groups`, the same rows as per-group +// cards, and `hidden`, how many rows sit on parked or done pieces. export async function GET(request: Request) { const project = new URL(request.url).searchParams.get("project"); if (project && !isSegment(project)) { return Response.json({ error: "bad project" }, { status: 400 }); } - const items = project ? await decisionsForSong(project) : await openDecisions(); + const inbox = await readInbox({ project }); + const items = inbox.items; const projects = new Set(items.map((d) => d.project)).size; return Response.json( - { items, projects, counts: countBySeverity(items) }, + { + items, + projects, + counts: countBySeverity(items), + groups: inbox.groups, + hidden: inbox.hidden, + ...(inbox.lifecycleError ? { lifecycleError: inbox.lifecycleError } : {}), + }, { headers: { "cache-control": "no-store" } }, ); } diff --git a/umtool/app/api/pieces/lifecycle/route.ts b/umtool/app/api/pieces/lifecycle/route.ts @@ -0,0 +1,38 @@ +import { isLifecycleState, LifecycleError, setLifecycle } from "@/lib/lifecycle"; +import { parsePieceId, readPieceGraph } from "@/lib/pieces"; + +export const dynamic = "force-dynamic"; + +// Park a piece, mark it done, or make it active again (lib/lifecycle.ts). +// +// POST { piece: "a:<site>/<report>" | "p:<project>", state: "active" | "parked" | "done" } +// → { piece, state, at, by } +// +// 400 for a body that is not a piece id and a state; 404 for a piece nothing on +// disk is (a research case `c:` is reserved until research boards exist); 409 +// when lifecycle.json does not parse (it is never overwritten). A "looks done" +// signal never comes through here: only this POST sets a lifecycle. +const NO_STORE = { "cache-control": "no-store" }; +const fail = (status: number, error: string) => Response.json({ error }, { status, headers: NO_STORE }); + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as { piece?: unknown; state?: unknown } | null; + if (!body || typeof body !== "object") return fail(400, "the body is { piece, state }"); + const parsed = parsePieceId(body.piece); + if (!parsed) return fail(400, `not a piece id: ${JSON.stringify(body.piece ?? null)} (a:<site>/<report> or p:<project>)`); + if (!isLifecycleState(body.state)) return fail(400, `state is active | parked | done, not ${JSON.stringify(body.state ?? null)}`); + if (parsed.kind === "case") return fail(404, "research cases have no lifecycle yet"); + const graph = await readPieceGraph(); + if (!graph.byId.has(body.piece as string)) { + // A project an article claims is part of that article's piece. + const owner = parsed.kind === "project" ? graph.pieceOfProject.get(parsed.project) : undefined; + return fail(404, owner ? `${body.piece} is part of ${owner}: set that piece's lifecycle` : `no piece ${body.piece}`); + } + try { + const entry = await setLifecycle(body.piece as string, body.state, "operator"); + return Response.json({ piece: entry.id, state: entry.state, at: entry.at, by: entry.by ?? null }, { headers: NO_STORE }); + } catch (err) { + if (err instanceof LifecycleError) return fail((err as LifecycleError & { status: number }).status, err.message); + return fail(500, (err as Error).message); + } +} diff --git a/umtool/app/api/pieces/route.ts b/umtool/app/api/pieces/route.ts @@ -0,0 +1,32 @@ +import { readInbox } from "@/lib/inbox"; +import { listPieces } from "@/lib/pieces"; +import { readLifecycle } from "@/lib/lifecycle"; + +export const dynamic = "force-dynamic"; + +// Every piece (lib/pieces.ts): an article with its linked video projects, or a +// project no article claims. Each with its kind, title, site, stage, lifecycle, +// linked projects, and how many decisions wait on it -- per inbox group, the +// visible ones, plus how many are hidden (a parked or done piece's). +// +// GET { pieces: [...], lifecycleError? } +export async function GET() { + const life = await readLifecycle(); + const [pieces, inbox] = await Promise.all([listPieces(life), readInbox()]); + const counts = new Map<string, { total: number; hidden: number; byGroup: Record<string, number> }>(); + for (const d of inbox.items) { + if (!d.piece) continue; + let c = counts.get(d.piece); + if (!c) counts.set(d.piece, (c = { total: 0, hidden: 0, byGroup: {} })); + c.total += 1; + if (d.hidden) c.hidden += 1; + else if (d.group) c.byGroup[d.group] = (c.byGroup[d.group] ?? 0) + 1; + } + return Response.json( + { + pieces: pieces.map((p) => ({ ...p, decisions: counts.get(p.id) ?? { total: 0, hidden: 0, byGroup: {} } })), + ...(life.error ? { lifecycleError: life.error } : {}), + }, + { headers: { "cache-control": "no-store" } }, + ); +} diff --git a/umtool/bin/inbox.ts b/umtool/bin/inbox.ts @@ -0,0 +1,71 @@ +// `umtool inbox` -- the inbox's grouped list, from a terminal (lib/inbox.ts). +// +// TypeScript, because the inbox is: the song reducer, the article side and the +// iteration readers are the app's own modules, and printing them from a second +// implementation is the thing lib/projects/core.mjs exists to avoid. So +// bin/umtool.mjs runs this file through tsx, from umtool/ (the `@/` paths). +// +// umtool inbox [--all] [--json] +// +// Per group: its cards (one per piece and kind), the decisions they hold, and +// how many are hidden on parked or done pieces. `--all` lists the hidden ones +// too, and the quiet group's cards. Read-only. +import { readInbox, type GroupCard, type GroupSummary } from "../lib/inbox"; +import { summarizeGroups } from "../lib/inbox/groups.mjs"; + +const args = process.argv.slice(2); +const all = args.includes("--all"); +const json = args.includes("--json"); + +const inbox = await readInbox(); +const visible = inbox.items.filter((d) => !d.hidden); + +if (json) { + console.log( + JSON.stringify( + { + groups: inbox.groups, + hidden: inbox.hidden, + decisions: visible.length, + ...(inbox.lifecycleError ? { lifecycleError: inbox.lifecycleError } : {}), + ...(all ? { items: inbox.items } : {}), + }, + null, + 2, + ), + ); + process.exit(0); +} + +const clip = (s: string, n = 110) => (s.length > n ? `${s.slice(0, n - 1)}…` : s); +const card = (c: GroupCard) => + ` ${c.severity === "blocking" ? "BLOCKING " : ""}${c.piece ?? c.project} ${c.kind}${c.count > 1 ? ` ×${c.count}` : ""}` + + `\n ${clip(c.why)}\n → ${c.action.label} ${c.action.href}`; + +// The hidden rows, carded as if visible, for --all. +const hiddenGroups = all + ? (summarizeGroups(inbox.items.filter((d) => d.hidden).map((d) => ({ ...d, hidden: false }))) as GroupSummary[]) + : []; + +let cards = 0; +for (const g of inbox.groups) { + if (!g.decisions && !g.hidden) continue; + cards += g.cards.length; + const hidden = g.hidden ? ` · ${g.hidden} hidden` : ""; + console.log(`\n## ${g.label} — ${g.cards.length} card${g.cards.length === 1 ? "" : "s"}, ${g.decisions} decision${g.decisions === 1 ? "" : "s"}${hidden}`); + if (g.collapsed && !all) { + if (g.decisions) console.log(" (collapsed; --all lists it)"); + } else { + for (const c of g.cards) console.log(card(c)); + } + const h = hiddenGroups.find((x) => x.id === g.id); + if (h?.cards.length) { + console.log(" hidden (parked or done):"); + for (const c of h.cards) console.log(card(c).replace(/^ {2}/gm, " ")); + } +} +console.log( + `\n${visible.length} decision${visible.length === 1 ? "" : "s"} in ${cards} card${cards === 1 ? "" : "s"}` + + (inbox.hidden ? ` · ${inbox.hidden} hidden on parked or done pieces${all ? "" : " (--all lists them)"}` : ""), +); +if (inbox.lifecycleError) console.log(`lifecycle: ${inbox.lifecycleError} — every piece reads as active`); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -15,6 +15,7 @@ // umtool show <project> [--json] // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool decisions [--json] +// umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them // umtool folders [--json] // umtool kinds [--json] // umtool window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] @@ -685,6 +686,8 @@ function usage() { " umtool show <project> [--json]", " umtool check [<project>] [--json] exit 1 on anything blocking", " umtool decisions [--json]", + " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them", + " (--all: the hidden ones on parked/done pieces, and the quiet group)", " umtool folders [--json]", " umtool kinds [--json]", " umtool window <project> <clip> [--start S] [--end E] [--lock|--lock-end|…]", @@ -742,9 +745,33 @@ const COMMANDS = { export: cmdExport, "check-sources": cmdCheckSources, notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))), + inbox: cmdInbox, help: usage, }; +// `umtool inbox`: bin/inbox.ts, through tsx -- the inbox is the app's +// TypeScript (lib/inbox.ts), run from umtool/ so its `@/` paths resolve. +async function cmdInbox() { + const { createRequire } = await import("node:module"); + const { fileURLToPath } = await import("node:url"); + const here = path.dirname(fileURLToPath(import.meta.url)); + let cli; + try { + cli = createRequire(import.meta.url).resolve("tsx/cli"); + } catch { + die("umtool inbox needs tsx (the workspace's devDependency): run `pnpm install` at the repo root"); + } + const code = await new Promise((resolve) => { + const child = spawn(process.execPath, [cli, path.join(here, "inbox.ts"), ...argv.slice(argv.indexOf("inbox") + 1)], { + cwd: path.dirname(here), + stdio: "inherit", + }); + child.on("error", () => resolve(1)); + child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); + }); + process.exit(code); +} + const run = COMMANDS[cmd]; if (!run) die(`unknown command "${cmd}"\n\nRun \`umtool help\`.`); await run(); diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -76,6 +76,21 @@ export type Decision = { severity: Severity; /** Newest evidence first. */ at: number; + + // ---- The inbox's fields (lib/inbox.ts). ADDITIVE: a row without them is + // still a decision, and the reducers above never set them. ---- + /** The piece it belongs to (lib/pieces/ids.mjs): `a:<site>/<report>` or `p:<project>`. */ + piece?: string; + /** What kind of thing it is (lib/inbox/groups.mjs CATEGORIES): spend, review, fix, note, choose, finish, info. */ + category?: string; + /** Where the inbox puts it (lib/inbox/groups.mjs GROUPS). */ + group?: string; + /** The ONE primary action; its label names the result. `href` is the row's own (a note's ends in `note=<id>`). */ + action?: { label: string; href: string }; + /** The piece's lifecycle (lib/lifecycle.ts); absent from the file is `active`. */ + lifecycle?: "active" | "parked" | "done"; + /** On a parked or done piece: kept in the list, out of the way. */ + hidden?: boolean; }; export const SEVERITIES: Severity[] = ["blocking", "open", "info"]; diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -0,0 +1,245 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { readResearchState } from "yt-dlp-transcript-common/lib/report/draft/research/state"; +import { ARTICLES_KEY } from "./paths"; +import { readArticleIterations, type IterationRow } from "./articles/generation"; +import { sitesPaths } from "./articles/sites"; +import { decisionsForSong, type Decision } from "./decisions"; +import { openDecisions } from "./projects"; +import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces"; +import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle"; +import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs"; + +// --------------------------------------------------------------------------- +// THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the +// projects' and the notes'), plus the generation era's, read from disk -- +// +// iteration-ready a finished iteration that is not current and is newer +// than the current one: make it current, or not +// iteration-failed a failed run nothing later has superseded, with what +// it spent +// research-proposal an acquisition a research run proposed, waiting on a +// yes or no (common's readResearchState: a READ of +// proposals.json -- never readResearch(), which POSTs to +// the editor and may rewrite the file) +// link-ambiguous an article whose video only a slug suggests +// looks-done a piece every signal says is finished (a suggestion: +// it never sets the lifecycle) +// +// -- each row given its piece, category, group, one action, lifecycle and +// `hidden` (lib/inbox/groups.mjs), ranked. One row per decision, never dropped: +// the MCP reads `items[]` (mcp/src/archivalTools.ts). +// +// No editor call anywhere here: there is no "waiting on a cap" state (the daily +// cap refuses at start, a per-job cap ends the run), and running jobs are +// P2b's. +// +// SERVER ONLY. +// --------------------------------------------------------------------------- + +export type GroupCard = { + piece: string | null; + project: string; + title: string; + kind: string; + severity: Decision["severity"]; + count: number; + why: string; + action: { label: string; href: string }; + at: number; +}; +export type GroupSummary = { + id: string; + label: string; + collapsed: boolean; + /** Visible decisions in the group. */ + decisions: number; + /** Decisions on parked or done pieces. */ + hidden: number; + cards: GroupCard[]; +}; + +export type Inbox = { + items: Decision[]; + groups: GroupSummary[]; + hidden: number; + /** lifecycle.json could not be read: every piece reads as active. */ + lifecycleError?: string; +}; + +export const INBOX_GROUPS = GROUPS as { id: string; label: string; collapsed: boolean }[]; + +const iterationsHref = (article: string) => `/articles/${article}?tab=iterations`; +const timeOf = (iso: string | null | undefined) => { + const ms = iso ? Date.parse(iso) : NaN; + return Number.isFinite(ms) ? ms : 0; +}; +const usd = (n: number) => `$${n.toFixed(2)}`; + +/** The store's articles: published, drafts and those in the making. */ +const storeArticles = (graph: PieceGraph): Piece[] => graph.pieces.filter((p) => p.kind === "article" && p.site === ARTICLES_KEY); + +const articleRow = (piece: Piece) => ({ + project: `sites/${piece.site}/${piece.report}`, + projectKind: "article", + projectTitle: piece.title, + piece: piece.id, +}); + +/** + * Iteration decisions for one article: ready, failed, and its research runs' + * proposals. `spend` joins the ledger's rows on the iteration's job when the + * iteration itself recorded no usage. + */ +async function iterationDecisions(piece: Piece, spendOfJob: Map<string, number>): Promise<Decision[]> { + const article = piece.report as string; + const its = await readArticleIterations(article).catch(() => null); + if (!its) return []; + const out: Decision[] = []; + const base = articleRow(piece); + const href = iterationsHref(article); + const cur = its.current; + const spent = (r: IterationRow) => (r.usd > 0 ? r.usd : r.jobId ? (spendOfJob.get(r.jobId) ?? 0) : 0); + const live = (r: IterationRow) => r.status === "queued" || r.status === "running" || r.status === "done"; + + for (const r of its.iterations) { + const at = timeOf(r.endedAt ?? r.createdAt); + if (r.status === "done" && r.kind !== "research") { + // A video revision competes with the current video; anything else with + // the current report. Only something that could BE current is ready. + const video = r.kind === "revise-video"; + const against = video ? cur.video : cur.report; + const makeable = video ? r.hasManifest : r.hasReport; + if (makeable && (against === null || r.n > against)) { + out.push({ + ...base, + kind: "iteration-ready", + target: r.label, + why: + `${r.label} (${r.kind} on ${r.model}) is done and newer than the current ${video ? "video" : "report"}` + + `${against === null ? " (none yet)" : ` (i${against})`}${spent(r) ? ` · ${usd(spent(r))}` : ""}`, + href, + severity: "open", + at, + }); + } + } + if (r.status === "failed") { + // A failed run is a decision until something after it runs. + const superseded = its.iterations.some((o) => o.n > r.n && live(o)); + if (!superseded) { + out.push({ + ...base, + kind: "iteration-failed", + target: r.label, + why: `${r.label} (${r.kind} on ${r.model}) failed${r.error ? `: ${r.error}` : ""}${spent(r) ? ` · ${usd(spent(r))} spent` : ""}`, + href, + severity: "open", + at, + }); + } + } + if (r.kind === "research") { + const state = await readResearchState(article, r.n, sitesPaths()).catch(() => null); + for (const p of state?.proposals ?? []) { + if (p.status !== "proposed") continue; + const est = p.estimate + ? [ + p.estimate.items ? `${p.estimate.items} item${p.estimate.items === 1 ? "" : "s"}` : null, + p.estimate.gb ? `${p.estimate.gb} GB` : null, + p.estimate.transcribeHours ? `${p.estimate.transcribeHours} h to transcribe` : null, + ] + .filter(Boolean) + .join(", ") + : ""; + out.push({ + ...base, + kind: "research-proposal", + target: `${r.label} ${p.id}`, + why: `${p.action}${p.reason ? `: ${p.reason}` : ""}${est ? ` (${est})` : ""}`, + href, + severity: "open", + at, + }); + } + } + } + return out; +} + +/** Decisions only the pieces can see: ambiguous links and pieces that look done. */ +function pieceDecisions(graph: PieceGraph, life: LifecycleRead): Decision[] { + const out: Decision[] = []; + for (const p of graph.pieces) { + const base = + p.kind === "article" + ? articleRow(p) + : { project: p.project as string, projectTitle: p.title, piece: p.id }; + if (p.kind === "article" && !p.projects.length && p.possible.length) { + out.push({ + ...base, + kind: "link-ambiguous", + target: p.possible.map((x) => x.id).join(", "), + why: + p.possible.length === 1 + ? `${p.possible[0].id} shares its slug but is not linked — name the article in its manifest to link it` + : `${p.possible.length} projects share its slug and none is linked: ${p.possible.map((x) => x.id).join(", ")}`, + href: p.href, + severity: "open", + at: p.newestMs, + }); + } + if (p.looksDone.length && lifecycleOf(life, p.id) !== "done") { + out.push({ + ...base, + kind: "looks-done", + target: p.id, + why: `looks done: ${p.looksDone.join("; ")}`, + href: p.href, + severity: "open", + at: p.newestMs, + }); + } + } + return out; +} + +/** The ledger's spend per job id, for an iteration that recorded none itself. */ +async function spendByJob(): Promise<Map<string, number>> { + const rows = await readGenerationUsage(getPaths().generationUsageFile).catch(() => []); + const out = new Map<string, number>(); + for (const r of rows) if (r.jobId) out.set(r.jobId, (out.get(r.jobId) ?? 0) + r.usd); + return out; +} + +/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done. */ +export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> { + const spend = await spendByJob(); + const perArticle = await Promise.all(storeArticles(graph).map((p) => iterationDecisions(p, spend))); + return [...perArticle.flat(), ...pieceDecisions(graph, life)]; +} + +/** + * The inbox. `project` narrows to one song's reducer (the decisions route's + * `?project=`), annotated the same way, with no disk sources added. + */ +export async function readInbox({ project }: { project?: string | null } = {}): Promise<Inbox> { + const [base, graph, life] = await Promise.all([ + project ? decisionsForSong(project) : openDecisions(), + readPieceGraph(), + readLifecycle(), + ]); + const extra = project ? [] : await diskDecisions(graph, life); + const items = rankDecisions( + annotate([...base, ...extra], { + pieceOf: (d: Decision) => pieceOfDecision(d, graph), + lifecycleOf: (id: string) => lifecycleOf(life, id), + }), + ) as Decision[]; + return { + items, + groups: summarizeGroups(items) as GroupSummary[], + hidden: items.filter((d) => d.hidden).length, + ...(life.error ? { lifecycleError: life.error } : {}), + }; +} diff --git a/umtool/lib/pieces.ts b/umtool/lib/pieces.ts @@ -0,0 +1,292 @@ +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 type { Decision } from "./decisions"; + +export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId } from "./pieces/ids.mjs"; + +// --------------------------------------------------------------------------- +// PIECES (plans/umtool-redesign.md): the unit the operator works on. +// +// an ARTICLE piece `a:<site>/<report>` -- a site's report, or one of the +// article store's (`articles/<id>`, 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:<id>` -- a project under REPORTS_ROOT linked to no +// article: a song, a hand-made report video, a sweep +// +// 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. 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"; + +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; + /** + * Where it is. An article: research (in the making) → article (no video) → + * video → deliver (looks done). A project: its own state (draft, windows, + * fetched, built, shipped, stale). + */ + stage: string; + 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; +}; + +export type PieceWithLifecycle = Piece & { lifecycle: LifecycleState; lifecycleAt: string | null; lifecycleBy: string | null }; + +export type PieceGraph = { + pieces: Piece[]; + byId: Map<string, Piece>; + /** Project id → the piece it belongs to. */ + pieceOfProject: Map<string, string>; + /** A project's basename → its id, when the name is unique (the song routes' alias). */ + projectByName: Map<string, string>; +}; + +const MEMO_MS = 15_000; +let memo: { at: number; epoch: number; value: Promise<PieceGraph> } | null = null; + +/** Drop the memo (a test, or a write that changed what an article links). */ +export function clearPiecesCache(): void { + memo = null; +} + +export function readPieceGraph(): Promise<PieceGraph> { + const epoch = linksCacheEpoch(); + if (memo && memo.epoch === epoch && Date.now() - memo.at < MEMO_MS) return memo.value; + const value = buildGraph(); + const entry = { at: Date.now(), epoch, value }; + memo = entry; + value.catch(() => { + if (memo === entry) 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"]; + 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, + 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(): Promise<ArticleIn[]> { + 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, + title: id, + status: "in the making" as const, + 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<string | null> { + // 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<PieceGraph> { + const [sites, store, pending, summaries, its] = await Promise.all([ + listSiteRows(), + readStoreRow(), + pendingArticles(), + listProjects(), + iterationProjects(), + ]); + 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<string, string>(); + 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<string, Promise<string | null>>(); + 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: `/browse/${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)); + pieces.push({ + id, + kind: "article", + title: a.title, + site: a.site, + report: a.id, + project: null, + href: articleHref({ site: a.site, id: a.id }), + status: a.status, + stage: a.status === "in the making" ? "research" : !projects.length ? "article" : looksDone.length ? "deliver" : "video", + projects, + possible: a.possible, + unreachable: a.unreachable, + looksDone, + newestMs, + }); + } + + for (const p of summaries) { + if (pieceOfProject.has(p.id)) continue; + const why = await looksDoneOf(p.id); + pieces.push({ + id: projectPieceId(p.id), + kind: "project", + title: p.title, + site: null, + report: null, + project: p.id, + href: `/browse/${p.id}`, + status: null, + stage: p.state, + projects: [], + possible: [], + unreachable: [], + looksDone: why ? [why] : [], + newestMs: p.newestMtimeMs, + }); + pieceOfProject.set(p.id, projectPieceId(p.id)); + } + + const names = new Map<string, string[]>(); + 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<PieceWithLifecycle[]> { + 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 }; + }); +}