import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { currentIteration, readIterations } from "yt-dlp-transcript-common/lib/report/iterations"; import { refreshBasis } from "yt-dlp-transcript-common/lib/report/draft/refresh/basis"; import { deltaCandidates, type EnumerateFn } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta"; import type { RefreshOutcome } from "yt-dlp-transcript-common/lib/report/draft/refresh/types"; import { enumerate, SourceRegistry, type ShardSource } from "yt-dlp-transcript-mcp/research"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { sitesPaths } from "@/lib/articles/sites"; import { articleHref } from "@/lib/hrefs"; import type { Decision } from "@/lib/decisions"; import { lifecycleOf, type LifecycleRead } from "@/lib/lifecycle"; import { isMuted, type MutesRead } from "@/lib/mutes"; import { REPORTS_ROOT } from "@/lib/paths"; import type { Piece, PieceGraph } from "@/lib/pieces"; import { localDir, openSource } from "@/lib/research/sources"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // --------------------------------------------------------------------------- // A REFRESH, SUGGESTED (plans/umtool-redesign.md, R4) -- two Inbox kinds: // // refresh-available a cheap daily check per active article with a current // report: its recorded enumerations run again over the // corpus it read (its build, else Research's local // corpus) -- stage 2's enumerate ONLY, common's // deltaCandidates: no fetch, no model -- and "3 new // recordings mention this since ". Its action is // Refresh (the article's Overview, the plan open). // refresh-held a refresh the cap held (refresh.json `held-by-cap`): // Your call, with the delta and the estimate, until a // later iteration supersedes it. // // The check is CACHED a day (UTC) per article and its current iteration, in // REPORTS_ROOT/.umtool/refresh-check.json (umtool's own state; one writer, // temp + rename). The Inbox only READS the cache; a stale one is checked in // the background, one article at a time, never twice at once // (`kickRefreshChecks`); `POST /api/articles/refresh/check` and // `umtool refresh --check` run it now. Muted, parked and done pieces are // skipped; so is an article a refresh newer than the check already covers. // // THE COVERAGE RULE — no silent zeros. A check reads the build the iteration // read when it is on this machine and holds every channel of its scope; else // Research's local corpus, when THAT holds every channel. When neither does, // the article is `unchecked`, with the reason ("the build holding harbor-radio // is not on this machine; channels not in the research corpus: x, y") — never // "0 new" — and it gets no card; `umtool refresh --check` prints it. // // SERVER-ONLY. // --------------------------------------------------------------------------- export const REFRESH_AVAILABLE = "refresh-available"; export const REFRESH_HELD = "refresh-held"; export const CHECK_FILE = () => path.join(/* turbopackIgnore: true */ REPORTS_ROOT, ".umtool", "refresh-check.json"); const CHECK_FORMAT = "umtool-refresh-check"; // A check runs the enumerations of an article, at most this many. export const MAX_CHECK_QUERIES = 12; export type CheckEntry = { article: string; // checked: a real answer (`corpus` says over which); unchecked: no corpus here // holds the scope (`reason`), so nothing is claimed. status: "checked" | "unchecked"; corpus?: string; reason?: string; // The iteration checked (the current report's) and when it was made. iteration: number; since: string; day: string; checkedAt: string; newCount: number; newIds: string[]; titles: string[]; source: string; // R6.1: the check's scan hit a cap — `unreached` what it did not read. A // partial check never claims "nothing new" (it raises the card, saying so). partial: boolean; unreached?: string[]; error?: string; }; type CheckFile = { format: typeof CHECK_FORMAT; version: 1; articles: Record }; const utcDay = (d = new Date()) => d.toISOString().slice(0, 10); export async function readRefreshChecks(): Promise { try { const f = JSON.parse(await readFile(/* turbopackIgnore: true */ CHECK_FILE(), "utf8")) as CheckFile; if (f?.format === CHECK_FORMAT && f.articles && typeof f.articles === "object") return f; } catch { // none yet, or torn: checked again } return { format: CHECK_FORMAT, version: 1, articles: {} }; } // One writer at a time, in this process (temp + rename: a reader never sees half). let writing: Promise = Promise.resolve(); function saveCheck(entry: CheckEntry): Promise { const next = writing.then(async () => { const f = await readRefreshChecks(); f.articles[entry.article] = entry; const file = CHECK_FILE(); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(f, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); }); writing = next.catch(() => {}); return next; } // enumerate_matches over a live source, as data (the MCP's own scan). function enumerateOver(source: ShardSource): EnumerateFn { return async (args) => { const e = await enumerate(source, args); if ("error" in e) throw new Error(e.error); return { rows: e.result.hits.map((h) => ({ id: h.videoId, kind: h.contentType === "post" ? "post" : "video", channel: h.channelName ?? null, date: h.uploadDate ?? null, matches: typeof h.matches === "number" ? h.matches : null, title: h.title ?? null, })), partial: e.result.truncated, unreached: [ ...(e.result.coverage?.channelStopped ? [`${e.result.coverage.channelStopped.channel} (stopped at page ${e.result.coverage.channelStopped.page} of ${e.result.coverage.channelStopped.pages})`] : []), ...(e.result.coverage?.channelsNotReached ?? []), ], }; }; } // The channels a composed dir holds (its corpus.json), or null when it is not there. async function heldChannels(dir: string): Promise { try { const c = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(dir, "corpus.json"), "utf8")) as { channels?: { slug?: unknown }[] }; return (c.channels ?? []).map((x) => x?.slug).filter((x): x is string => typeof x === "string"); } catch { return null; } } type Picked = { ok: true; handle: string; source: ShardSource; corpus: string } | { ok: false; reason: string }; // The corpus an article's check reads (the coverage rule, above): the build its // iteration read when it is here and holds the scope, else Research's local // corpus when it holds the scope, else none — with why. export async function pickCheckCorpus(recorded: string | null, channels: readonly string[]): Promise { const lacking = (held: string[]) => channels.filter((c) => !held.includes(c)); let own: string; if (recorded?.startsWith("local:")) { const dir = recorded.slice("local:".length); const held = await heldChannels(dir); if (held && !lacking(held).length) { const reg = new SourceRegistry({ kind: "local", dir }); return { ok: true, handle: recorded, source: (await reg.resolve(undefined)).source, corpus: `its own build (${recorded})` }; } own = held ? `its build does not hold ${lacking(held).join(", ")}` : `the build holding ${channels.join(", ")} is not on this machine`; } else { own = recorded ? `it read ${recorded}, not a build on this machine` : "it recorded no corpus"; } const dir = localDir(); const held = await heldChannels(dir); if (!held) return { ok: false, reason: `${own}; the research corpus (${dir}) is not there` }; const missing = lacking(held); if (missing.length) return { ok: false, reason: `${own}; channels not in the research corpus: ${missing.join(", ")}` }; const opened = await openSource(null); return { ok: true, handle: opened.option.handle, source: opened.source, corpus: `the research corpus (${opened.option.handle})` }; } /** The articles a check is for: the store's, active (not parked, done or muted). */ export function checkable(graph: PieceGraph, life: LifecycleRead, mutes: MutesRead): Piece[] { return graph.pieces.filter( (p) => p.kind === "article" && p.site === ARTICLES_KEY && p.report && lifecycleOf(life, p.id) === "active" && !isMuted(mutes, p.id, REFRESH_AVAILABLE), ); } /** Check one article now: its current report's enumerations again (no fetch, no model). */ export async function checkArticle(article: string, now = new Date()): Promise { const cur = await currentIteration(article, sitesPaths()).catch(() => null); if (cur?.report == null) return null; const n = cur.report; const base = { article, iteration: n, day: utcDay(now), checkedAt: now.toISOString() }; try { // Since the newest refresh of the current report, when one has looked // (its refresh.json holds what it saw), else since the report itself. const its = (await readIterations(article, sitesPaths()).catch(() => null))?.iterations ?? []; const looked = its.filter((it) => it.kind === "refresh" && it.parent === n && it.status === "done").sort((a, b) => b.n - a.n)[0]; const basis = await refreshBasis(article, looked?.n ?? n, sitesPaths()); const picked = await pickCheckCorpus(basis.source, basis.scope.channels); if (!picked.ok) { return { ...base, status: "unchecked", reason: picked.reason, since: basis.at, newCount: 0, newIds: [], titles: [], source: "", partial: false }; } const { handle, source } = picked; const c = await deltaCandidates({ queries: basis.queries.slice(0, MAX_CHECK_QUERIES), scope: basis.scope }, enumerateOver(source), { ...(basis.knownComplete ? { known: basis.known } : { since: basis.at }), }); const newIds = c.newIds.filter((id) => !(id in basis.known)); return { ...base, status: "checked", corpus: picked.corpus, since: basis.at, newCount: newIds.length, newIds: newIds.slice(0, 20), titles: newIds.slice(0, 5).map((id) => c.rows.get(id)?.title ?? id), source: handle, partial: c.partial, ...(c.partial ? { unreached: c.unreached } : {}), }; } catch (e) { return { ...base, status: "unchecked", reason: (e as Error).message, since: "", newCount: 0, newIds: [], titles: [], source: "", partial: false, error: (e as Error).message }; } } /** Every checkable article whose check is not today's (or `force`): checked, one at a time, and kept. */ export async function runRefreshChecks( pieces: Piece[], o: { force?: boolean; only?: string; now?: Date } = {}, ): Promise<{ checked: CheckEntry[]; skipped: { article: string; why: string }[] }> { const kept = await readRefreshChecks(); const now = o.now ?? new Date(); const checked: CheckEntry[] = []; const skipped: { article: string; why: string }[] = []; for (const p of pieces) { const article = p.report!; if (o.only && article !== o.only) continue; const cur = await currentIteration(article, sitesPaths()).catch(() => null); if (cur?.report == null) { skipped.push({ article, why: "no current report" }); continue; } const had = kept.articles[article]; if (!o.force && had && had.day === utcDay(now) && had.iteration === cur.report) { skipped.push({ article, why: "checked today" }); continue; } const entry = await checkArticle(article, now); if (!entry) continue; await saveCheck(entry); checked.push(entry); } return { checked, skipped }; } // The background check: one at a time, never awaited by a page. const g = globalThis as typeof globalThis & { __umtoolRefreshCheck?: Promise | null }; /** Check the stale articles in the background (a page never waits on it). */ export function kickRefreshChecks(pieces: Piece[], kept: CheckFile, now = new Date()): void { if (g.__umtoolRefreshCheck) return; const day = utcDay(now); const stale = pieces.filter((p) => kept.articles[p.report!]?.day !== day); if (!stale.length) return; g.__umtoolRefreshCheck = runRefreshChecks(stale) .catch(() => null) .finally(() => { g.__umtoolRefreshCheck = null; }); } const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; /** * The two kinds' rows for the Inbox. `refresh-available` from the cache (and * the stale ones checked in the background); `refresh-held` from each * article's latest refresh iteration. */ export async function refreshDecisions(graph: PieceGraph, life: LifecycleRead, mutes: MutesRead, o: { background?: boolean } = {}): Promise { const pieces = checkable(graph, life, mutes); const kept = await readRefreshChecks(); // In the app's server only (a CLI's read must not wait on a check), and not // where it is switched off (UMTOOL_REFRESH_CHECK=0: the e2e server). if (o.background !== false && process.env.NEXT_RUNTIME && process.env.UMTOOL_REFRESH_CHECK !== "0") kickRefreshChecks(pieces, kept); const out: Decision[] = []; for (const p of graph.pieces.filter((x) => x.kind === "article" && x.site === ARTICLES_KEY && x.report)) { const article = p.report!; const read = await readIterations(article, sitesPaths()).catch(() => null); if (!read) continue; const its = read.iterations; const row = { project: `sites/${ARTICLES_KEY}/${article}`, projectKind: "article", projectTitle: p.title, piece: p.id }; const href = articleHref({ site: ARTICLES_KEY, id: article }, { refresh: true }); // A refresh the cap held, nothing after it. const latest = [...its].filter((it) => it.kind === "refresh").sort((a, b) => b.n - a.n)[0]; const outcome = latest ? ((latest as { refresh?: RefreshOutcome }).refresh ?? null) : null; if (latest && outcome?.status === "held-by-cap" && !its.some((x) => x.n > latest.n && x.status !== "failed" && x.status !== "cancelled")) { out.push({ ...row, kind: REFRESH_HELD, target: `i${latest.n}`, why: `i${latest.n} ${outcome.summary}`, href, severity: "open", at: Date.parse(latest.endedAt ?? latest.updatedAt) || 0, } as Decision); } // New recordings since the current report, by today's check. if (!pieces.includes(p)) continue; const c = kept.articles[article]; // An unchecked article (no corpus here holds its scope) claims nothing: no card. // R6.1: a partial check with nothing new is NOT "nothing new": it raises // the card, saying what the check did not reach. if (!c || c.error || c.status === "unchecked" || (c.newCount <= 0 && !c.partial) || c.iteration !== read.current.report) continue; // A refresh made after the check already looked (or is looking). if (its.some((it) => it.kind === "refresh" && it.parent === c.iteration && Date.parse(it.createdAt) >= Date.parse(c.checkedAt))) continue; if (its.some((it) => it.kind === "refresh" && (it.status === "queued" || it.status === "running"))) continue; out.push({ ...row, kind: REFRESH_AVAILABLE, target: `i${c.iteration}`, why: [ c.newCount > 0 ? `${c.partial ? "at least " : ""}${plural(c.newCount, "new recording")} mention${c.newCount === 1 ? "s" : ""} this since ${c.since.slice(0, 10)}${c.titles.length ? `: ${c.titles.slice(0, 3).join(", ")}${c.newCount > 3 ? ", …" : ""}` : ""}` : `nothing new since ${c.since.slice(0, 10)} in what the check read`, c.partial ? `the check was partial — ${c.unreached?.length ? `not reached: ${c.unreached.join(", ")}` : "a cap was hit"}; a Refresh reads the rest` : null, ] .filter(Boolean) .join(" · "), href, severity: "open", at: Date.parse(c.checkedAt) || 0, } as Decision); } return out; }