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, projectRefs, summariseProject, type ProjectRef } from "./projects"; import { readManifest, reportSignature } from "./projects/report.mjs"; import { draftsView } from "./report/drafts.mjs"; import { articleHref, generationPolicyHref, reviewHref, triageHref } from "./hrefs"; import { awaitingReview, draftsDecisions } from "./inbox/drafts.mjs"; import { unreadableProposalsDecision, verdictsDecisions } from "./inbox/verdicts.mjs"; import { readArticleProposals } from "./articles/verdicts"; import { readFieldProvenance } from "./report/draft-provenance.mjs"; import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces"; import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle"; import { isMuted, readMutes } from "./mutes"; import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs"; import { currentIteration, readIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; import { ensureTriageBoards, triageBoardId } from "./research/triage"; import { marksOfRun, readMarks } from "./research/triage-marks.mjs"; import { readCase } from "./research/boards"; import { REPORTS_ROOT } from "./paths.mjs"; import { scheduleDecisions } from "./inbox/schedules.mjs"; import { readSchedules } from "./schedules"; import type { ScheduleView } from "./schedule-types"; import { refreshDecisions } from "./inbox/refresh"; import { sourceWatchDecisions } from "./inbox/sourceWatch"; import { projectCallsAll } from "./inbox/projectCalls"; import { caseCuesDecisions } from "./inbox/caseCues"; import { decisionIsPrivate, type PrivateFilter } from "./privacy"; // --------------------------------------------------------------------------- // 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) // tick-failed, a recurring report's tick that failed or was held by a // tick-held, cap (Your call), and a series' finished edition with // edition-ready nothing current yet (Review) -- lib/inbox/schedules.mjs; // an edition's article raises no iteration cards of its // own (they are its series') // worth-researching a watch's tick whose triage escalated (R6): Your call, // its board (made here the first time, by umtool, the // one writer of case files -- lib/research/triage.ts); // its article raises no iteration cards of its own // refresh-available new recordings match an active article's current // refresh-held report since it was made (a cached daily check); a // refresh the cap held (lib/inbox/refresh.ts, R4) // drafts-unreviewed a report cut's field a model drafted that nobody has // reviewed (r28's draftsView; lib/inbox/drafts.mjs), one // row per field, kept per project against // reportSignature -- which signs the review files, so an // approve drops the card on the next read // verdict-proposed a model's proposed verdict for a fact-check's unruled // claim (release 29 M8; the article's // verdicts.proposed.json, lib/inbox/verdicts.mjs), one row // per proposal, gone once approved or rejected (or the // claim ruled by hand, or changed: a stale proposal) // unreadable-proposals that file does not read: one Blocking row // version-unjudged a rendered version (or legacy take) with no verdict: // Play and judge (lib/inbox/versions.mjs, umtool // redesign L4 "What needs you") // clips-unwalked the draft's clips nobody walked, on a draft with a // render or a walk begun (lib/inbox/walk.mjs) // quote-check-stale clips the quote check no longer vouches for, with // Run quote-check in place (lib/inbox/checks.mjs) // case-new-cues a live research case's scope has new transcripts // since its last candidate scan (lib/inbox/caseCues.mjs) // // (X's login when X work waits on it -- x-jar-stale, lib/inbox/xJar.mjs -- is a // MACHINE call, lib/machine.ts, beside a missing tool: it is no piece's.) // // -- 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 // home's Running list (lib/activity.ts readRunning). // // SERVER ONLY. // --------------------------------------------------------------------------- export type GroupCard = { piece: string | null; project: string; title: string; kind: string; severity: Decision["severity"]; count: number; why: string; /** The card's own title when its decisions name one (drafts), else null: the page labels it by kind. */ what: string | null; action: { label: string; href: string }; at: number; /** The one-press settle the card offers in place, when its rows agree on one (groups.mjs mergeSettle). */ settle: Decision["settle"] | null; }; 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[]; /** Rows hidden for any reason: a parked or done piece, or a mute. */ hidden: number; /** Of those, the muted ones (on active pieces). */ muted: number; /** lifecycle.json could not be read: every piece reads as active. */ lifecycleError?: string; /** mutes.json could not be read: nothing reads as muted. */ mutesError?: 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): Promise { 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 === "hand" ? "by hand" : `${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> { const rows = await readGenerationUsage(getPaths().generationUsageFile).catch(() => []); const out = new Map(); for (const r of rows) if (r.jobId) out.set(r.jobId, (out.get(r.jobId) ?? 0) + r.usd); return out; } // One project's drafts decisions, kept against its reportSignature (on // globalThis: one cache per process, not per Next bundle). type DraftsMemo = Map; const gd = globalThis as typeof globalThis & { __umtoolDraftsMemo?: DraftsMemo }; const draftsMemo: DraftsMemo = (gd.__umtoolDraftsMemo ??= new Map()); async function projectDrafts(ref: ProjectRef): Promise { const sig = String(await reportSignature(ref.dir)); const hit = draftsMemo.get(ref.id); if (hit && hit.sig === sig) return hit.value; let value: Decision[] = []; const manifest = await readManifest(ref.dir); if (manifest) { const view = await draftsView(ref.dir, manifest); // Who drafted a field with no mark: its task's draft file (release 25's narration). const provenance = view.rows.some((r) => r.state === "unreviewed" || r.state === "edited") ? await readFieldProvenance(ref.dir, manifest) : {}; if (awaitingReview(view.rows, provenance).length) { const title = (await summariseProject(ref)).title; // When: the manifest's mtime (reportSignature's first field) -- a draft is written there. const at = Number(sig.split(":")[0]) || Date.now(); value = draftsDecisions({ project: ref.id, projectTitle: title, href: reviewHref(ref.id), at, view, provenance }).map((d) => ({ ...d, projectKind: ref.kind, })) as Decision[]; } } draftsMemo.set(ref.id, { sig, value }); return value; } /** Every project's unreviewed drafts. A project that cannot be read adds nothing. */ export async function draftsDecisionsAll(): Promise { const refs = await projectRefs(); const live = new Set(refs.map((r) => r.id)); for (const id of draftsMemo.keys()) if (!live.has(id)) draftsMemo.delete(id); const per = await Promise.all(refs.map((r) => projectDrafts(r).catch(() => [] as Decision[]))); return per.flat(); } /** The recurring reports' decisions (R5): failed and held ticks, finished editions not yet current. */ async function recurringDecisions(views: ScheduleView[]): Promise { const editions = views.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.status === "done" && e.article ? [e.article] : []))); const current = new Map(); await Promise.all( editions.map(async (a) => { const cur = await currentIteration(a, sitesPaths()).catch(() => null); current.set(a, cur?.report ?? null); }), ); const worth = await worthOf(views).catch(() => new Map()); return scheduleDecisions(views, { current: (a: string) => current.get(a) ?? null, articleHref: (a: string) => articleHref({ site: ARTICLES_KEY, id: a }, { tab: "iterations" }), settingsHref: generationPolicyHref(), worth: (schedule: string, k: number) => worth.get(`${schedule}/${k}`) ?? null, }) as Decision[]; } /** * A watch's escalated ticks (R6): each board (made now when it is not yet -- * umtool is the one writer of case files), whether it is settled (a hand-off * made from it, or every flag of the run marked), and what the sweep kept. */ async function worthOf(views: ScheduleView[]): Promise> { const out = new Map(); const watches = views.filter((v) => v.shape === "watch" && v.ticks.some((t) => t.triage?.escalated && t.status === "done" && t.article)); if (!watches.length) return out; const boards = await ensureTriageBoards(watches); for (const v of watches) { const marks = await readMarks(REPORTS_ROOT, v.id).catch(() => null); for (const t of v.ticks) { if (!t.triage?.escalated || t.status !== "done" || !t.article) continue; const key = `${v.id}/${t.triage.k}`; const board = await readCase(triageBoardId(v, t.triage.k)).catch(() => null); const marked = marks ? Object.keys(marksOfRun(marks, t.triage.k)).length : 0; const settled = !!board?.handoffs.length || (t.triage.flagged > 0 && marked >= t.triage.flagged); let findings: number | null = null; if (t.iteration) { const text = await readIterationFile(t.article, t.iteration, "report.json", sitesPaths()).catch(() => null); if (text) { try { findings = Object.values((JSON.parse(text) as { citations?: Record }).citations ?? {}).filter((c) => c?.quote).length; } catch { findings = null; } } } out.set(key, { href: boards.get(key) ?? triageHref(v.id, t.triage.k), settled, findings }); } } return out; } /** The store's fact-checks' proposed verdicts (release 29 M8), waiting on the operator. */ async function proposalDecisions(graph: PieceGraph): Promise { const per = await Promise.all( storeArticles(graph).map(async (p) => { const got = await readArticleProposals(p.report as string).catch(() => null); const href = articleHref({ site: ARTICLES_KEY, id: p.report as string }, { tab: "article" }); if (got?.error) return [unreadableProposalsDecision({ base: articleRow(p), href, error: got.error, at: p.newestMs })] as Decision[]; if (!got?.waiting.length) return [] as Decision[]; return verdictsDecisions({ base: articleRow(p), href, waiting: got.waiting }) as Decision[]; }), ); return per.flat(); } /** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done, drafts, verdict proposals, recurring reports. */ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise { const [spend, drafts, schedules, proposals] = await Promise.all([ spendByJob(), draftsDecisionsAll().catch(() => [] as Decision[]), readSchedules().catch(() => ({ schedules: [] as ScheduleView[] })), proposalDecisions(graph).catch(() => [] as Decision[]), ]); // An edition's article is its series' piece's business (one Review card there). // A watch's tick article is its watch's (one Worth researching card there). const editionArticles = new Set([ ...schedules.schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [e.article] : []))), ...schedules.schedules.flatMap((v) => (v.shape === "watch" ? v.ticks.flatMap((t) => (t.article ? [t.article] : [])) : [])), ]); const perArticle = await Promise.all( storeArticles(graph) .filter((p) => !editionArticles.has(p.report as string)) .map((p) => iterationDecisions(p, spend)), ); const recurring = await recurringDecisions(schedules.schedules).catch(() => [] as Decision[]); const refresh = await readMutes() .then((mutes) => refreshDecisions(graph, life, mutes)) .catch(() => [] as Decision[]); // Re-sweep when complete (UI notes item 16): a report video's source watch that fired. const sources = await sourceWatchDecisions().catch(() => [] as Decision[]); // What needs you (L4): versions to judge, clips to walk, stale quote checks, a live case's new transcripts. const [calls, cases] = await Promise.all([projectCallsAll().catch(() => [] as Decision[]), caseCuesDecisions().catch(() => [] as Decision[])]); return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring, ...sources, ...calls, ...cases]; } /** * 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, hide = null }: { project?: string | null; hide?: PrivateFilter | null } = {}): Promise { const [base, graph, life, mutes] = await Promise.all([ project ? decisionsForSong(project) : openDecisions(), readPieceGraph(), readLifecycle(), readMutes(), ]); // A disk source that cannot be read adds nothing; it never hides the rest. const extra = project ? [] : await diskDecisions(graph, life).catch(() => [] as Decision[]); // settings.privacy.hidePrivateSites (lib/privacy.ts): a page that passes the // filter leaves the private sites' decisions out; null leaves every one in. const all = [...base, ...extra]; const kept = hide ? all.filter((d) => !decisionIsPrivate(d, graph, hide)) : all; const items = rankDecisions( annotate(kept, { pieceOf: (d: Decision) => pieceOfDecision(d, graph), lifecycleOf: (id: string) => lifecycleOf(life, id), isMuted: (piece: string, kind: string) => isMuted(mutes, piece, kind), }), ) as Decision[]; return { items, groups: summarizeGroups(items) as GroupSummary[], hidden: items.filter((d) => d.hidden).length, muted: items.filter((d) => d.hiddenBy === "muted").length, ...(life.error ? { lifecycleError: life.error } : {}), ...(mutes.error ? { mutesError: mutes.error } : {}), }; }