Archilyzer · Source

archilyzer

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

commit 986646c70247675aee021160d4119089f0bb5015
parent f527f538607c36aa07a06798ce0c750fcc651bd6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 12:00:28 -0400

umtool: Refresh — the plan from the ⋯ menu and the Next card, the Overview's summary, refresh-available and refresh-held in the Inbox, umtool refresh, the stub and refresh.spec

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

Diffstat:
Mcommon/lib/report/draft/refresh/delta.ts | 31+++++++++++++++++++++++--------
Mcommon/lib/report/draft/refresh/index.ts | 14+++++++++++++-
Aumtool/app/api/articles/refresh/check/route.ts | 30++++++++++++++++++++++++++++++
Aumtool/app/api/articles/refresh/route.ts | 39+++++++++++++++++++++++++++++++++++++++
Aumtool/bin/refresh.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 27+++++++++++++++++++++++++++
Mumtool/components/articles/ArticleOverview.tsx | 6+++++-
Mumtool/components/articles/ArticlePage.tsx | 6++++++
Aumtool/components/articles/RefreshDialog.tsx | 241+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/RefreshSummary.tsx | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/RefreshWatch.tsx | 17+++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/refresh-fixture.mjs | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/refresh.spec.ts | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/generation.ts | 3++-
Aumtool/lib/articles/refresh.ts | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 3++-
Mumtool/lib/inbox.ts | 9++++++++-
Mumtool/lib/inbox/groups.mjs | 8+++++++-
Aumtool/lib/inbox/refresh.test.ts | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/refresh.ts | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/what.mjs | 2++
Mumtool/package.json | 2+-
Mumtool/playwright.config.ts | 4++++
24 files changed, 1460 insertions(+), 15 deletions(-)

diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts @@ -17,7 +17,7 @@ // Pure over the corpus tools and readers it is handed. import { checkWordsInWindow, enOrigDifference, holdsWords, windowAround, type WordCue } from "../../quoteWords"; -import { enumerateOf } from "../tasks/trace"; +import { enumerateOf, type EnumeratedRow } from "../tasks/trace"; import type { CorpusToolsLike } from "../tasks/types"; import { queryKey } from "./basis"; import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types"; @@ -37,6 +37,21 @@ export type Candidates = { perQuery: { query: string; n: number; partial: boolean; error?: string }[]; }; +// One enumeration's answer, as data: its rows, whether the scan was capped, +// the channels a capped scan never reached. +export type EnumeratedAnswer = { rows: EnumeratedRow[]; partial: boolean; unreached: string[] }; +// enumerate_matches as a function: the corpus tools' (enumerateViaTools), or +// a caller's own over the MCP's engine (umtool's daily check). +export type EnumerateFn = (args: Record<string, unknown>) => Promise<EnumeratedAnswer>; + +/** enumerate_matches through the corpus tools, its answer read back as data. */ +export const enumerateViaTools = + (corpus: Pick<CorpusToolsLike, "call">): EnumerateFn => + async (args) => { + const e = enumerateOf(await corpus.call("enumerate_matches", args)); + return { rows: e.rows, partial: e.partial, unreached: e.unreached }; + }; + /** The enumerate_matches arguments of one query under a scope. */ export function enumerateArgs(q: RefreshQuery, scope: CandidateScope): Record<string, unknown> { const channels = q.channels?.length ? q.channels : scope.channels; @@ -66,9 +81,10 @@ const ymdOf = (d: string | null | undefined): string | null => { */ export async function deltaCandidates( basis: { queries: readonly RefreshQuery[]; scope: CandidateScope }, - corpus: Pick<CorpusToolsLike, "call">, + corpus: Pick<CorpusToolsLike, "call"> | EnumerateFn, o: { known?: Record<string, number | null>; since?: string | null; signal?: AbortSignal } = {}, ): Promise<Candidates> { + const run = typeof corpus === "function" ? corpus : enumerateViaTools(corpus); const seen = new Set<string>(); const perId = new Map<string, number | null>(); const rows = new Map<string, MatchedRow>(); @@ -80,19 +96,18 @@ export async function deltaCandidates( const key = queryKey(q); if (seen.has(key)) continue; seen.add(key); - let text: string; + let e: EnumeratedAnswer; try { - text = await corpus.call("enumerate_matches", enumerateArgs(q, basis.scope)); - } catch (e) { + e = await run(enumerateArgs(q, basis.scope)); + } catch (err) { // One query that cannot run is said, and makes the scan partial. partial = true; - perQuery.push({ query: q.query, n: 0, partial: true, error: (e as Error).message }); + perQuery.push({ query: q.query, n: 0, partial: true, error: (err as Error).message }); continue; } - const e = enumerateOf(text); if (e.partial) partial = true; for (const c of e.unreached) unreached.add(c); - perQuery.push({ query: q.query, n: e.ids.length, partial: e.partial }); + perQuery.push({ query: q.query, n: e.rows.length, partial: e.partial }); for (const r of e.rows) { if (r.kind === "post") continue; const had = perId.get(r.id); diff --git a/common/lib/report/draft/refresh/index.ts b/common/lib/report/draft/refresh/index.ts @@ -1,7 +1,19 @@ // A refresh (umtool R4): re-fetch, see what changed, update. See ./task.ts. export * from "./types"; export { NothingToRefreshError, citedQuotes, fromRefreshFile, fromTrace, fromTurns, knownOf, queryKey, refreshBasis } from "./basis"; -export { computeDelta, deltaCandidates, enumerateArgs, recheckQuotes, type CandidateScope, type Candidates, type QuoteReaders, type RecordRead } from "./delta"; +export { + computeDelta, + deltaCandidates, + enumerateArgs, + enumerateViaTools, + recheckQuotes, + type CandidateScope, + type Candidates, + type EnumerateFn, + type EnumeratedAnswer, + type QuoteReaders, + type RecordRead, +} from "./delta"; export { fetchAndBuild, type FetchAndBuild, type FetchHooks, type RefreshHooks } from "./fetch"; export { DEFAULT_REVISION_USD, diff --git a/umtool/app/api/articles/refresh/check/route.ts b/umtool/app/api/articles/refresh/check/route.ts @@ -0,0 +1,30 @@ +import { checkable, readRefreshChecks, runRefreshChecks } from "@/lib/inbox/refresh"; +import { readLifecycle } from "@/lib/lifecycle"; +import { readMutes } from "@/lib/mutes"; +import { readPieceGraph } from "@/lib/pieces"; + +export const dynamic = "force-dynamic"; + +// THE DAILY REFRESH CHECK (plans/umtool-redesign.md, R4; lib/inbox/refresh.ts): +// each active article's current report's enumerations again over the corpus +// it read -- no fetch, no model -- kept a day. The Inbox reads what it kept and +// checks a stale one in the background; this runs it NOW. +// +// GET what is kept (refresh-check.json) +// POST { article?, force? } check (only `article`; `force`: even +// one checked today) -> { checked, skipped } +const headers = { "cache-control": "no-store" }; + +export async function GET() { + return Response.json(await readRefreshChecks(), { headers }); +} + +export async function POST(request: Request) { + const body = ((await request.json().catch(() => null)) ?? {}) as { article?: unknown; force?: unknown }; + const [graph, life, mutes] = await Promise.all([readPieceGraph(), readLifecycle(), readMutes()]); + const out = await runRefreshChecks(checkable(graph, life, mutes), { + force: body.force === true, + ...(typeof body.article === "string" && body.article ? { only: body.article } : {}), + }); + return Response.json(out, { headers }); +} diff --git a/umtool/app/api/articles/refresh/route.ts b/umtool/app/api/articles/refresh/route.ts @@ -0,0 +1,39 @@ +import { errorResponse } from "@/lib/articles/generation"; +import { planArticleRefresh, readRefreshes, startArticleRefresh } from "@/lib/articles/refresh"; + +export const dynamic = "force-dynamic"; + +// A REFRESH of an article (plans/umtool-redesign.md, R4): re-fetch its scope, +// see what changed, update -- planned, then confirmed. The editor plans and +// runs it (`report-draft {"task": "refresh"}`); umtool writes nothing here. +// +// GET ?article=<id> { refreshes }: each refresh +// iteration, newest first, with +// what its refresh.json kept +// POST { article, iteration?, fetch? } { plan }: what it would do +// POST { article, iteration?, fetch?, confirm: true } +// { jobId, iteration, href } +const ID = /^[a-z0-9][a-z0-9-]{0,63}$/; +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const article = new URL(request.url).searchParams.get("article") ?? ""; + if (!ID.test(article)) return Response.json({ error: "name the article (?article=<id>)" }, { status: 400, headers }); + return Response.json({ refreshes: await readRefreshes(article) }, { headers }); +} + +export async function POST(request: Request) { + try { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "send { article }" }, { status: 400, headers }); + const article = typeof body.article === "string" ? body.article : ""; + if (!ID.test(article)) return Response.json({ error: '"article" is an article id' }, { status: 400, headers }); + const iteration = body.iteration === undefined || body.iteration === null ? undefined : Number(body.iteration); + if (iteration !== undefined && !(Number.isInteger(iteration) && iteration > 0)) return Response.json({ error: '"iteration" is an iteration number' }, { status: 400, headers }); + const o = { ...(iteration ? { iteration } : {}), ...(body.fetch === false ? { fetch: false } : {}) }; + if (body.confirm === true) return Response.json({ ok: true, ...(await startArticleRefresh(article, o)) }, { headers }); + return Response.json({ plan: await planArticleRefresh(article, o) }, { headers }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/bin/refresh.ts b/umtool/bin/refresh.ts @@ -0,0 +1,85 @@ +// `umtool refresh` -- an article's Refresh from a terminal (plans/umtool- +// redesign.md, R4; lib/articles/refresh.ts, lib/inbox/refresh.ts). Run by +// bin/umtool.mjs through tsx, from umtool/ (the `@/` paths). +// +// umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json] +// the plan (the editor's dry run: the iteration refreshed, its queries, +// each channel's fetches or why skipped, the site built, the model and +// the cap); --yes starts it -- one editor job -- and prints where to +// follow it +// umtool refresh --check [<article>] [--force] [--json] +// the daily suggestion check now: each active article's current report's +// enumerations again (no fetch, no model), kept a day +import { planArticleRefresh, startArticleRefresh } from "../lib/articles/refresh"; +import { checkable, runRefreshChecks } from "../lib/inbox/refresh"; +import { readLifecycle } from "../lib/lifecycle"; +import { readMutes } from "../lib/mutes"; +import { readPieceGraph } from "../lib/pieces"; + +const args = process.argv.slice(2); +const has = (f: string) => args.includes(f); +const val = (f: string) => { + const i = args.indexOf(f); + return i >= 0 ? args[i + 1] : undefined; +}; +const json = has("--json"); +const positional = args.filter((a, i) => !a.startsWith("--") && args[i - 1] !== "--iteration"); +const die = (msg: string): never => { + console.error(`umtool refresh: ${msg}`); + process.exit(1); +}; + +if (has("--check")) { + const [graph, life, mutes] = await Promise.all([readPieceGraph(), readLifecycle(), readMutes()]); + const out = await runRefreshChecks(checkable(graph, life, mutes), { force: has("--force"), ...(positional[0] ? { only: positional[0] } : {}) }); + if (json) { + console.log(JSON.stringify(out, null, 2)); + process.exit(0); + } + for (const c of out.checked) { + console.log( + c.error + ? `${c.article} i${c.iteration}: not checked — ${c.error}` + : `${c.article} i${c.iteration}: ${c.newCount} new recording${c.newCount === 1 ? "" : "s"} since ${c.since.slice(0, 10)}${c.titles.length ? ` (${c.titles.join(", ")})` : ""}${c.partial ? " — partial" : ""}`, + ); + } + for (const s of out.skipped) console.log(`${s.article}: ${s.why}`); + if (!out.checked.length && !out.skipped.length) console.log("no active article with a current report"); + process.exit(0); +} + +const article = positional[0]; +if (!article) die("usage: umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json] | umtool refresh --check [<article>] [--force]"); +const iteration = val("--iteration") ? Number(val("--iteration")) : undefined; +if (iteration !== undefined && !(Number.isInteger(iteration) && iteration > 0)) die("--iteration is an iteration number"); +const o = { ...(iteration ? { iteration } : {}), ...(has("--no-fetch") ? { fetch: false } : {}) }; + +try { + if (has("--yes")) { + const r = await startArticleRefresh(article!, o); + if (json) console.log(JSON.stringify(r, null, 2)); + else console.log(`${article} i${r.iteration}: the refresh is running (job ${r.jobId}) — ${r.href}`); + process.exit(0); + } + const p = await planArticleRefresh(article!, o); + if (json) { + console.log(JSON.stringify(p, null, 2)); + process.exit(0); + } + console.log(`# Refresh ${p.article} — i${p.parent.n} (${p.parent.kind}, made ${p.parent.at.slice(0, 10)})`); + if (p.parent.question) console.log(` question ${p.parent.question}`); + console.log(` searched ${p.parent.queries.map((q) => `"${q}"`).join(", ")} (from its ${p.parent.from}; ${p.parent.knownCount} matched then, ${p.parent.citedCount} cited quotes read again)`); + if (!p.fetch) console.log(" fetch none: the corpus is read as it stands"); + for (const c of p.channels) console.log(` fetch ${c.slug}${c.platform ? ` (${c.platform})` : ""}: ${c.skip ? `skipped — ${c.skip}` : c.actions.join(" → ")}`); + console.log(` build ${p.build.site ? `${p.build.site}, locally (never deployed)` : (p.build.reason ?? "none")}`); + console.log( + ` update ${p.model}${p.capUsd !== null ? `, up to $${p.capUsd.toFixed(2)}` : " (local, no cap)"} — about $${p.estimate.perRecordingUsd.toFixed(2)} a new recording + $${p.estimate.revisionUsd.toFixed(2)}, only when something changed` + + (p.daily ? `; today $${p.daily.usd.toFixed(2)} of $${p.daily.cap.toFixed(2)}` : ""), + ); + for (const w of p.warnings) console.log(` note ${w}`); + for (const r of p.refusals) console.log(` REFUSED ${r}`); + console.log(p.refusals.length ? "\nNothing was started." : `\nNothing was started. \`umtool refresh ${article}${iteration ? ` --iteration ${iteration}` : ""}${has("--no-fetch") ? " --no-fetch" : ""} --yes\` runs it.`); + process.exit(p.refusals.length ? 1 : 0); +} catch (e) { + die((e as Error).message); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -700,6 +700,10 @@ function usage() { " umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)", " umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)", " umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>", + " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", + " re-fetch an article's scope, see what changed, update: the plan (the editor's);", + " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", + " umtool refresh --check [<article>] [--force] [--json] the daily suggestion check, now", "", `reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`, "", @@ -730,9 +734,32 @@ const COMMANDS = { "check-sources": cmdCheckSources, notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))), inbox: cmdInbox, + refresh: () => tsxCommand("refresh"), help: usage, }; +// `umtool refresh`: bin/refresh.ts through tsx, as `inbox` (R4). +async function tsxCommand(name) { + 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 ${name} 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, `${name}.ts`), ...argv.slice(argv.indexOf(name) + 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); +} + // `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() { diff --git a/umtool/components/articles/ArticleOverview.tsx b/umtool/components/articles/ArticleOverview.tsx @@ -4,6 +4,8 @@ import NextCard, { NextCardShell } from "@/components/piece/NextCard"; import { IterationsSummary, ProjectDecisions } from "@/components/projects/report/OverviewTab"; import { hms, type ClipDetail } from "@/components/projects/report/shared"; import { readArticleIterations } from "@/lib/articles/generation"; +import { readRefreshes } from "@/lib/articles/refresh"; +import RefreshSummary from "./RefreshSummary"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { projectHref } from "@/lib/hrefs"; import { decisionsForProject } from "@/lib/projects"; @@ -40,9 +42,10 @@ export default async function ArticleOverview({ tabHref: Href; }) { const store = site === ARTICLES_KEY; - const [iterations, decisions] = await Promise.all([ + const [iterations, decisions, refreshes] = await Promise.all([ store ? readArticleIterations(frame.report).catch(() => null) : Promise.resolve(null), videoRef ? decisionsForProject(videoRef).catch(() => []) : Promise.resolve([]), + store ? readRefreshes(frame.report).catch(() => []) : Promise.resolve([]), ]); const rows = iterations?.iterations ?? []; const asked = rows.find((r) => r.currentReport && r.question) ?? rows.find((r) => r.question) ?? null; @@ -86,6 +89,7 @@ export default async function ArticleOverview({ )} </section> )} + {refreshes[0] && <RefreshSummary row={refreshes[0]} iterationsHref={tabHref("iterations")} />} {videoRef && <ProjectDecisions project={videoRef.id} decisions={decisions} />} </div> diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -7,6 +7,7 @@ import { readRevisionHead, REPORT_HISTORY_GIT_DIRNAME } from "yt-dlp-transcript- import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides"; import type { Crumb } from "@/components/shell/AppHeader"; import DeleteArticle from "@/components/articles/DeleteArticle"; +import { RefreshHost, RefreshMenuItem } from "@/components/articles/RefreshDialog"; import ArticleOverview from "@/components/articles/ArticleOverview"; import ArticleReader from "@/components/articles/ArticleReader"; import WorkspacePanel from "@/components/articles/WorkspacePanel"; @@ -58,6 +59,8 @@ import type { NotesRead } from "@/lib/annotations/types"; // ?ws=&rel= a workspace file open on the source view // ?project=<id> another video project the article owns // ?all=1 the cut's every quote +// ?refresh=1 the Refresh plan open (R4: the suggestion +// card's action) export type ArticleSearch = { tab?: string; @@ -68,6 +71,7 @@ export type ArticleSearch = { rv?: string; all?: string; project?: string; + refresh?: string; }; type TabHref = (t: string, q?: { all?: boolean; project?: string }) => string; @@ -180,6 +184,7 @@ export default async function ArticlePage({ more={ <> <span className="px-2 pb-1 pt-0.5 font-mono text-[11px] text-muted">{frame.pieceId}</span> + {store && hasIterations && r && <RefreshMenuItem article={reportId} />} {store && <DeleteArticle article={reportId} published={published} />} {videoRef && ( <> @@ -192,6 +197,7 @@ export default async function ArticlePage({ </> } > + {store && hasIterations && r && <RefreshHost article={reportId} initialOpen={sp.refresh === "1"} href={tabHref(tab)} />} {tab === "overview" && ( <ArticleOverview site={site} diff --git a/umtool/components/articles/RefreshDialog.tsx b/umtool/components/articles/RefreshDialog.tsx @@ -0,0 +1,241 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import type { RefreshPlan } from "yt-dlp-transcript-common/lib/report/draft/refresh/types"; + +// --------------------------------------------------------------------------- +// REFRESH, plan then confirm (plans/umtool-redesign.md, R4). The plan is the +// editor's dry run (`report-draft {"task": "refresh", "dryRun": true}`, through +// /api/articles/refresh): the iteration refreshed and what it is searched +// again with, each channel's fetches (or why one is skipped), the site built +// locally, the model and the cap. Nothing is written until **Refresh** -- +// then it is one editor job (the Running list), and the Overview shows what +// it found. +// +// The ⋯ menu's item (RefreshMenuItem) and the Next card's action (`?refresh=1`) +// open the one dialog the page holds (RefreshHost): a menu item's own dialog +// would close with the menu. +// --------------------------------------------------------------------------- + +const OPEN_EVENT = "umtool:refresh"; + +const usd = (n: number) => `$${n.toFixed(2)}`; +const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 10) : ""); + +function Row({ k, children }: { k: string; children: React.ReactNode }) { + return ( + <> + <dt className="text-muted">{k}</dt> + <dd className="m-0 min-w-0 break-words text-text-2">{children}</dd> + </> + ); +} + +function PlanBody({ p }: { p: RefreshPlan }) { + const fetched = p.channels.filter((c) => !c.skip); + return ( + <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 text-[12.5px]" data-refresh-plan={p.article}> + <Row k="Refreshes"> + <span className="font-mono">i{p.parent.n}</span> ({p.parent.kind}, made {day(p.parent.at)}) + {p.parent.question ? <span className="block text-muted">{p.parent.question}</span> : null} + </Row> + <Row k="Searched again"> + <span data-refresh-queries="">{p.parent.queries.map((q) => `“${q}”`).join(", ")}</span> + <span className="block text-muted"> + against {p.parent.knownCount.toLocaleString("en-US")} recording{p.parent.knownCount === 1 ? "" : "s"} matched then · {p.parent.citedCount} cited quote{p.parent.citedCount === 1 ? "" : "s"} read again + </span> + </Row> + <Row k="Fetch"> + {!p.fetch ? ( + "none: the corpus is read as it stands" + ) : ( + <ul className="m-0 grid list-none gap-1 p-0" data-refresh-fetches={fetched.length}> + {p.channels.map((c) => ( + <li key={c.slug} data-refresh-channel={c.slug} data-skip={c.skip ? "" : undefined}> + <span className="font-mono">{c.slug}</span> + {c.platform ? <span className="text-muted"> · {c.platform}</span> : null} + {c.skip ? <span className="block text-doubt-text">skipped — {c.skip}</span> : <span className="block text-muted">{c.actions.join(" → ")}</span>} + </li> + ))} + </ul> + )} + </Row> + <Row k="Build"> + <span data-refresh-build={p.build.site ?? ""}> + {p.build.site ? ( + <> + <span className="font-mono">{p.build.site}</span>, locally, if anything changed — never deployed + </> + ) : ( + (p.build.reason ?? "none") + )} + {p.build.builtAt ? <span className="block text-muted">built {day(p.build.builtAt)}</span> : null} + </span> + </Row> + <Row k="Update"> + <span data-refresh-cap={p.capUsd ?? "local"}> + <span className="font-mono">{p.model}</span> + {p.extractor ? ( + <> + {" "} + · extractor <span className="font-mono">{p.extractor}</span> + </> + ) : null} + {p.capUsd !== null ? ( + <> + {" "} + · spends up to <span className="font-mono text-meter">{usd(p.capUsd)}</span> + </> + ) : ( + " · the local model, no cap" + )} + <span className="block text-muted"> + only when something changed: a sweep of the new recordings, then a revision · about {usd(p.estimate.perRecordingUsd)} a recording + {p.estimate.from === "parent" ? ` (i${p.parent.n}'s rate)` : ""} + {usd(p.estimate.revisionUsd)} + {p.daily ? ` · today ${usd(p.daily.usd)} of ${usd(p.daily.cap)}` : ""} + </span> + </span> + </Row> + </dl> + ); +} + +async function post<T>(body: unknown): Promise<T> { + const r = await fetch("/api/articles/refresh", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j as T; +} + +export function RefreshDialog({ article, open, onClose, onDone }: { article: string; open: boolean; onClose: () => void; onDone: (what: string) => void }) { + const [plan, setPlan] = useState<RefreshPlan | null>(null); + const [error, setError] = useState<string | null>(null); + const [working, setWorking] = useState(false); + useEffect(() => { + setPlan(null); + setError(null); + if (!open) return; + let live = true; + post<{ plan: RefreshPlan }>({ article }) + .then((r) => live && setPlan(r.plan)) + .catch((e: Error) => live && setError(e.message)); + return () => { + live = false; + }; + }, [article, open]); + + const confirm = async () => { + if (!plan) return; + setWorking(true); + setError(null); + try { + const r = await post<{ jobId: string; iteration: number }>({ article, iteration: plan.parent.n, confirm: true }); + onDone(`Refresh i${r.iteration} is running (job ${r.jobId})`); + } catch (e) { + setError((e as Error).message); + } finally { + setWorking(false); + } + }; + + const blocked = !plan || plan.refusals.length > 0; + return ( + <Dialog open={open} onClose={onClose} title="Refresh: fetch what's new, see what changed" data-refresh-dialog={article}> + {!plan && !error && ( + <p role="status" className="text-[12.5px] text-text-2"> + Reading the plan… + </p> + )} + {plan && <PlanBody p={plan} />} + {plan && plan.refusals.length > 0 && ( + <ul data-refusals="" className="mt-3 grid list-none gap-1 p-0 text-[12.5px] text-reject-text"> + {plan.refusals.map((r) => ( + <li key={r}>{r}</li> + ))} + </ul> + )} + {plan && plan.warnings.length > 0 && ( + <ul data-warnings="" className="mt-3 grid list-none gap-1 p-0 text-[12px] text-doubt-text"> + {plan.warnings.map((w) => ( + <li key={w}>{w}</li> + ))} + </ul> + )} + {error && ( + <p role="alert" className="mt-3 text-[12.5px] text-reject-text"> + {error} + </p> + )} + <div className="mt-4 flex items-center justify-end gap-2"> + <button type="button" className={buttonVariants({ variant: "quiet" })} onClick={onClose}> + Cancel + </button> + <button type="button" data-confirm="" disabled={blocked || working} className={buttonVariants({ variant: "go" })} onClick={confirm}> + {working ? "Starting…" : "Refresh"} + </button> + </div> + </Dialog> + ); +} + +/** The ⋯ menu's item: opens the page's one Refresh dialog. */ +export function RefreshMenuItem({ article }: { article: string }) { + const hydrated = useHydrated(); + return ( + <button + type="button" + disabled={!hydrated} + data-refresh-open="" + className={buttonVariants({ variant: "quiet", size: "sm", className: "justify-start" })} + onClick={() => window.dispatchEvent(new CustomEvent(OPEN_EVENT, { detail: { article } }))} + > + Refresh… + </button> + ); +} + +/** The page's Refresh dialog: opened by the menu item, or on arrival with `?refresh=1` (the Next card's action). */ +export function RefreshHost({ article, initialOpen = false, href }: { article: string; initialOpen?: boolean; href: string }) { + const router = useRouter(); + const [open, setOpen] = useState(initialOpen); + const [said, setSaid] = useState<string | null>(null); + useEffect(() => { + const onOpen = (e: Event) => { + if ((e as CustomEvent<{ article?: string }>).detail?.article === article) { + setSaid(null); + setOpen(true); + } + }; + window.addEventListener(OPEN_EVENT, onOpen); + return () => window.removeEventListener(OPEN_EVENT, onOpen); + }, [article]); + const close = () => { + setOpen(false); + // The address no longer opens it. + if (initialOpen) router.replace(href, { scroll: false }); + }; + return ( + <> + <RefreshDialog + article={article} + open={open} + onClose={close} + onDone={(what) => { + setSaid(what); + setOpen(false); + router.replace(href, { scroll: false }); + router.refresh(); + }} + /> + {said && ( + <p role="status" data-refresh-started="" className="px-4 pt-2 text-[12.5px] text-signal-text"> + {said} + </p> + )} + </> + ); +} diff --git a/umtool/components/articles/RefreshSummary.tsx b/umtool/components/articles/RefreshSummary.tsx @@ -0,0 +1,85 @@ +import Link from "next/link"; +import { badgeVariants } from "@/components/ui/badge"; +import { Card } from "@/components/ui/panel"; +import type { RefreshRow } from "@/lib/articles/refresh"; +import RefreshWatch from "./RefreshWatch"; + +// --------------------------------------------------------------------------- +// The newest REFRESH on an article's Overview (plans/umtool-redesign.md, R4): +// what its refresh.json kept, in one line — "4 new recordings match · 2 quotes +// changed · 1 source deleted", or "Nothing new since <date>" — then the new +// recordings, the quotes that changed and what was fetched and built; the +// update's spend, or the cap that held it. While it runs, the page reads +// again every few seconds (RefreshWatch). +// --------------------------------------------------------------------------- + +const STATUS: Record<string, { label: string; variant: "neutral" | "on" | "blocking" | "open" | "info" | "meter" }> = { + running: { label: "running", variant: "meter" }, + "no-change": { label: "no change", variant: "info" }, + updated: { label: "updated", variant: "on" }, + "held-by-cap": { label: "held by the cap", variant: "open" }, + failed: { label: "failed", variant: "blocking" }, + cancelled: { label: "cancelled", variant: "info" }, +}; + +const usd = (n: number) => `$${n.toFixed(2)}`; + +export default function RefreshSummary({ row, iterationsHref }: { row: RefreshRow; iterationsHref: string }) { + const live = row.status === "queued" || row.status === "running"; + const state = live ? "running" : (row.refresh ?? (row.status === "failed" ? "failed" : row.status === "cancelled" ? "cancelled" : "running")); + const s = STATUS[state] ?? STATUS.running!; + const fetched = row.fetch.filter((f) => f.status === "done").length; + const skipped = row.fetch.filter((f) => f.status === "skipped" || f.status === "refused"); + return ( + <section data-refresh-summary={row.n} data-refresh-state={state}> + <div className="mb-2 flex items-baseline gap-3"> + <h2 className="micro">Refresh · i{row.n}</h2> + <span className={badgeVariants({ variant: s.variant, size: "sm" })} data-refresh-status={state}> + {s.label} + </span> + <Link href={iterationsHref} prefetch={false} className="ink-link ml-auto text-[12px]"> + {row.hasReport ? "Review in Iterations →" : "Iterations →"} + </Link> + </div> + <Card className="space-y-2"> + <p className="text-[15px] font-semibold leading-snug" data-refresh-line=""> + {live ? "Fetching and searching again…" : row.summary.split(" — ")[0]} + </p> + {!live && row.summary.includes(" — ") && <p className="text-[12.5px] text-muted">{row.summary.split(" — ").slice(1).join(" — ")}</p>} + {row.news.length > 0 && ( + <ul className="m-0 grid list-none gap-0.5 p-0 text-[12.5px]" data-refresh-new={row.counts.newIds}> + {row.news.map((r) => ( + <li key={r.id} className="truncate"> + <span className="font-mono text-[11.5px] text-muted-2">{r.date ?? ""}</span> {r.title ?? r.id} + </li> + ))} + {row.counts.newIds > row.news.length && <li className="text-muted">and {row.counts.newIds - row.news.length} more</li>} + </ul> + )} + {row.drifted.length > 0 && ( + <ul className="m-0 grid list-none gap-1 p-0 text-[12.5px]" data-refresh-drifted={row.counts.drifted}> + {row.drifted.map((d) => ( + <li key={d.citation}> + <span className="text-muted-2">{d.citation}</span> <span className="font-serif">“{d.quote}”</span> + {d.now !== null && <span className="block text-muted">now: “{d.now.slice(0, 200)}”</span>} + </li> + ))} + </ul> + )} + {row.deleted.length > 0 && ( + <p className="text-[12.5px] text-doubt-text" data-refresh-deleted={row.deleted.length}> + Gone: <span className="font-mono">{row.deleted.join(", ")}</span> + </p> + )} + <p className="text-[12px] text-muted" data-refresh-steps=""> + {row.fetch.length ? `${fetched} fetch${fetched === 1 ? "" : "es"} done` : "no fetch"} + {skipped.length ? ` · skipped: ${skipped.map((f) => `${f.channel} (${f.reason ?? f.status})`).join("; ")}` : ""} + {row.build ? ` · build ${row.build.site ?? "none"} ${row.build.status}${row.build.reason ? ` (${row.build.reason})` : ""}` : ""} + {row.update?.usd ? ` · ${usd(row.update.usd)} spent` : !live && row.refresh === "no-change" && !row.update ? " · $0" : ""} + {row.update?.refusal ? ` · about ${usd(row.update.estimateUsd)} to update` : ""} + </p> + </Card> + {live && <RefreshWatch />} + </section> + ); +} diff --git a/umtool/components/articles/RefreshWatch.tsx b/umtool/components/articles/RefreshWatch.tsx @@ -0,0 +1,17 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +// While a refresh runs, the page reads again every few seconds (only while the +// tab is visible): its Overview then shows what the refresh found. +export default function RefreshWatch({ everyMs = 4000 }: { everyMs?: number }) { + const router = useRouter(); + useEffect(() => { + const t = setInterval(() => { + if (document.visibilityState === "visible") router.refresh(); + }, everyMs); + return () => clearInterval(t); + }, [router, everyMs]); + return null; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -112,6 +112,12 @@ function writeWindow(dir, name, seconds) { // the stub's acquisition jobs, then // approved (a job: running after 1 s, // done after 3 s) or rejected +// A `refresh` report-draft (R4): `dryRun` answers a plan (the iteration +// refreshed, a fetch per channel and one held platform skipped, a site built, +// the policy's model and cap); else a `refresh` iteration, running after 1 s, +// done after 3 s with its refresh.json — `updated` (one new recording, one +// quote changed, a report.json), or `no-change` for an article whose id ends +// in "-quiet". // A `research` report-draft proposes three acquisitions (an archive.org import // waits, a new channel waits, a Twitch VOD refused); a `sweep` with // `iteration` continues a research run, as the editor does. @@ -643,6 +649,134 @@ function startDraft(body) { return { jobId: id, iteration: n }; } +// ─── a refresh (R4) ─── + +// The iteration a refresh refreshes: the one named, else the current report's, +// else the newest done one with a report.json. +function refreshTarget(article, asked) { + if (asked) return Number(asked); + try { + const cur = JSON.parse(readFileSync(path.join(ARTICLES, article, "iterations", "current.json"), "utf8")); + if (cur.report) return cur.report; + } catch { + // none: the newest done one + } + const dir = path.join(ARTICLES, article, "iterations"); + const ns = existsSync(dir) ? readdirSync(dir).filter((d) => /^\d+$/.test(d)).map(Number).sort((a, b) => b - a) : []; + for (const n of ns) if (readIt(article, n).status === "done" && existsSync(path.join(itDir(article, n), "report.json"))) return n; + throw new Error(`"${article}" has no report to refresh: no iteration is current and none that is done carries a report`); +} + +function refreshPlan(body) { + const n = refreshTarget(body.article, body.iteration); + const it = readIt(body.article, n); + const fetch = body.fetch !== false; + const channels = it.scope?.channels?.length ? it.scope.channels : ["sitechan"]; + return { + article: body.article, + parent: { n, kind: it.kind, model: it.model, question: it.question ?? null, at: it.endedAt ?? it.updatedAt, from: "trace", queries: ["lighthouse budget"], knownCount: 4, knownComplete: true, citedCount: 1 }, + scope: { channels }, + fetch, + channels: [ + ...channels.map((slug) => ({ slug, kind: "video", platform: "youtube", actions: fetch ? ["sync", "refresh-report", "transcribe-bucket (what lands)"] : [] })), + ...(fetch ? [{ slug: "otherchan", kind: "video", platform: "rumble", actions: [], skip: "rumble is held: its rate limit outlasted the cooldown cap (3 failures in a row)" }] : []), + ], + build: fetch ? { site: "priv", builtAt: "2026-10-13T22:00:00.000Z" } : { site: null, reason: "no fetch: the corpus is read as it stands" }, + corpus: { source: "local:/stub/.export-builds/priv/out", build: "priv" }, + model: generation.models.api, + provider: "api", + extractor: generation.models.extractor, + capUsd: generation.caps.sweep, + daily: { usd: 1.2, cap: generation.caps.daily }, + estimate: { perRecordingUsd: 0.1, revisionUsd: 0.3, from: "parent" }, + refusals: [], + warnings: [], + }; +} + +function startRefresh(body) { + const { article } = body; + const parent = refreshTarget(article, body.iteration); + const p = readIt(article, parent); + const now = new Date().toISOString(); + const id = `stub-draft-${nextJob++}`; + const n = nextN(article); + mkdirSync(itDir(article, n), { recursive: true }); + writeIt({ format: "archilyzer-iteration", version: 1, article, n, kind: "refresh", parent, copyOf: null, ...(p.question ? { question: p.question } : {}), scope: p.scope ?? { channels: ["sitechan"] }, model: body.model ?? generation.models.api, status: "queued", usage: {}, steps: [], jobId: id, createdAt: now, updatedAt: now }); + const job = { id, article, n, task: "refresh", status: "queued", at: Date.now(), log: [`report-draft refresh ${article} i${n} (stub)`], timers: [] }; + draftJobs.set(id, job); + job.timers.push( + setTimeout(() => { + job.status = "running"; + job.log.push("stage 1: fetch (stub)"); + patchIt(article, n, { status: "running" }); + }, 1000), + ); + job.timers.push(setTimeout(() => finishRefresh(job, parent, p), 3000)); + return { jobId: id, iteration: n }; +} + +function finishRefresh(job, parent, p) { + const { article, n } = job; + if (readIt(article, n).status === "cancelled") return; + const quiet = article.endsWith("-quiet"); + const at = new Date().toISOString(); + const since = p.endedAt ?? p.updatedAt; + const quote = "the lighthouse budget was never approved"; + const delta = quiet + ? { at, status: "no-change", matched: 4, newIds: [], new: [], changed: [], unmatched: [], drifted: [], deleted: [], enOrig: [], quotes: [{ citation: "c1", kind: "video", channel: "harbor-radio", id: "hr-2019a", start: 600, status: "ok", quote }], partial: false, unreached: [], matchedSet: { "hr-2019a": 1, "hr-2022a": 1, "hr-2024a": 1, "hr-2026a": 1 } } + : { + at, + status: "changed", + matched: 5, + newIds: ["hr-2021a"], + new: [{ id: "hr-2021a", channel: "Harbor Radio", date: "2021-09-07", title: "Harbor Radio 52: storm season", matches: 2 }], + changed: [], + unmatched: [], + drifted: ["c1"], + deleted: [], + enOrig: [], + quotes: [{ citation: "c1", kind: "video", channel: "harbor-radio", id: "hr-2019a", start: 600, status: "drifted", quote, now: "the lighthouse budget was not approved that year", nowAt: 600 }], + partial: false, + unreached: [], + matchedSet: { "hr-2019a": 1, "hr-2021a": 2, "hr-2022a": 1, "hr-2024a": 1, "hr-2026a": 1 }, + }; + const line = quiet ? `Nothing new since ${String(since).slice(0, 10)}` : "1 new recording matches · 1 quote changed"; + const status = quiet ? "no-change" : "updated"; + const summary = quiet ? line : `${line} — updated: 2 op(s) applied, 0 refused — “Refreshed”`; + const file = { + format: "archilyzer-refresh", + version: 1, + article, + n, + parent, + status, + summary, + startedAt: at, + endedAt: at, + basis: { article, n: parent, queriesOf: parent, question: p.question ?? null, scope: p.scope ?? { channels: [] }, queries: [{ query: "lighthouse budget" }], from: "trace", knownComplete: true, source: null, at: since, knownCount: 4, citedCount: 1, known: {} }, + fetch: [ + { channel: "harbor-radio", action: "sync", status: "done", jobId: "stub-sync" }, + { channel: "harbor-radio", action: "refresh-report", status: "done", jobId: "stub-report" }, + { channel: "harbor-radio", action: "transcribe-bucket", status: "skipped", reason: "nothing new to transcribe" }, + ], + build: { site: "priv", status: "done", jobIds: ["stub-build"] }, + corpus: { source: "local:/stub/.export-builds/priv/out", build: "priv", origin: "https://archive.example" }, + delta, + ...(quiet ? {} : { update: { model: readIt(article, n).model, estimateUsd: 0.4, capUsd: generation.caps.sweep, sweep: { ids: ["hr-2021a"], status: "done", summary: "1 finding", findings: 1 }, revision: { status: "done", summary: "2 op(s) applied" }, usd: 0.31 } }), + warnings: [], + }; + writeFileSync(path.join(itDir(article, n), "refresh.json"), JSON.stringify(file, null, 2) + "\n"); + const patch = { status: "done", minutes: 0.1, endedAt: at, refresh: { status, newIds: delta.newIds.length, changed: 0, drifted: delta.drifted.length, deleted: 0, summary } }; + if (!quiet) { + writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, "Refreshed", " One recording more."), null, 2) + "\n"); + patch.usage = { [readIt(article, n).model]: { usd: 0.31, inputTokens: 21000, outputTokens: 900, calls: 4 } }; + } + patchIt(article, n, patch); + job.status = "done"; + job.log.push(`refresh: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task: "refresh", status: "done", summary, refresh: patch.refresh })}`); +} + function cancelDraft(id) { const job = draftJobs.get(id); if (!job || !["queued", "running"].includes(job.status)) return false; @@ -714,6 +848,10 @@ function generationRoute(req, res, url, auth) { if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" }); if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" }); try { + if (body.task === "refresh") { + if (body.dryRun === true) return json(res, 200, { ok: true, plan: refreshPlan(body) }); + return json(res, 202, { ok: true, ...startRefresh(body) }); + } return json(res, 202, { ok: true, ...startDraft(body) }); } catch (err) { return json(res, 400, { ok: false, error: String(err.message) }); diff --git a/umtool/e2e/fixtures/refresh-fixture.mjs b/umtool/e2e/fixtures/refresh-fixture.mjs @@ -0,0 +1,90 @@ +// The REFRESH fixture (plans/umtool-redesign.md, R4): an article whose current +// report was made by a traced sweep over Research's local corpus, and which +// one recording there now matches that the sweep did not see. +// +// refreshfix/report.json the article (a draft), i1's report +// refreshfix/iterations/1 a done sweep over harbor-radio: its +// trace's enumeration of the research +// phrase matched four recordings — +// hr-2021a ("storm season") is not +// among them, so the daily check finds +// it new +// refreshfix/iterations/current.json report i1 +// +// e2e/refresh.spec.ts plans and starts a Refresh against the editor stub +// (which writes the refresh iteration and its refresh.json), and runs the +// daily check through /api/articles/refresh/check. Synthetic, like every +// fixture: the words are the research fixture's invented lines. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { RESEARCH_PHRASE } from "./research-fixture.mjs"; + +export const REFRESH_ARTICLE = "refreshfix"; +export const REFRESH_QUESTION = "What did Harbor Radio say about the lighthouse budget?"; +/** The recording the check finds new (in the research fixture, not in i1's enumeration). */ +export const REFRESH_NEW = { id: "hr-2021a", title: "Harbor Radio 52: storm season" }; +const AT = "2026-10-14T09:00:00.000Z"; + +const put = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`); +}; + +const QUOTE = `the ${RESEARCH_PHRASE} was never approved`; + +export const REFRESH_REPORT = { + format: "archilyzer-report", + version: 1, + id: REFRESH_ARTICLE, + kind: "sweep", + title: "The lighthouse budget, on Harbor Radio", + summary: "What the station said about it.", + citations: { + c1: { kind: "video", channel: "harbor-radio", id: "hr-2019a", start: 600, end: 604, quote: QUOTE, label: "Harbor Radio 1: the old pier", date: "2019-03-14" }, + }, + sections: [{ id: "the-budget", title: "The budget", claims: [{ id: "k1", text: "The budget was never approved", citations: ["c1"] }] }], +}; + +export function makeRefreshFixture({ articles, source }) { + const it1 = path.join(articles, REFRESH_ARTICLE, "iterations", "1"); + put(path.join(it1, "iteration.json"), { + format: "archilyzer-iteration", + version: 1, + article: REFRESH_ARTICLE, + n: 1, + kind: "sweep", + parent: null, + copyOf: null, + model: "claude-sonnet-5-5", + question: REFRESH_QUESTION, + scope: { channels: ["harbor-radio"] }, + status: "done", + usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 20000, outputTokens: 1000, calls: 3 } }, + coverage: { matched: 4, read: 4, partial: false, unreached: [] }, + steps: [], + createdAt: AT, + updatedAt: AT, + endedAt: AT, + }); + const ev = (e) => JSON.stringify({ at: AT, run: 1, ...e }); + put( + path.join(it1, "trace.jsonl"), + [ + ev({ t: "run", phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }), + ev({ t: "scope", source, channels: ["harbor-radio"], question: REFRESH_QUESTION, model: "claude-sonnet-5-5" }), + ev({ t: "enumerate", query: RESEARCH_PHRASE, n: 4, ids: ["hr-2019a", "hr-2022a", "hr-2024a", "hr-2026a"], partial: false, unreached: [], counts: { "hr-2019a": 1, "hr-2022a": 1, "hr-2024a": 1, "hr-2026a": 1 } }), + ev({ t: "run", phase: "end", status: "done", summary: "ok", usd: 0.4, minutes: 1 }), + ].join("\n") + "\n", + ); + put(path.join(it1, "report.json"), REFRESH_REPORT); + put(path.join(articles, REFRESH_ARTICLE, "report.json"), REFRESH_REPORT); + put(path.join(articles, REFRESH_ARTICLE, "iterations", "current.json"), { + format: "archilyzer-iterations-current", + version: 1, + report: 1, + reportFrom: 1, + video: null, + reportAt: AT, + }); + return { article: REFRESH_ARTICLE }; +} diff --git a/umtool/e2e/refresh.spec.ts b/umtool/e2e/refresh.spec.ts @@ -0,0 +1,128 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { REFRESH_ARTICLE, REFRESH_NEW, makeRefreshFixture } from "./fixtures/refresh-fixture.mjs"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// Refresh (plans/umtool-redesign.md, R4) on the refresh fixture +// (e2e/fixtures/refresh-fixture.mjs, written here and removed after): the +// plan from the article's ⋯ menu — the iteration refreshed and its queries, +// each channel's fetches (a held platform skipped), the site built, the cap — +// with nothing written until Refresh; the daily check finding the recording +// the report's sweep never saw, the Inbox's suggestion card and the Next +// card, whose action opens the plan; then the refresh run as one editor job +// (the stub: running, then done with its refresh.json), and the Overview's +// summary of what it found. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ARTICLES = path.join(FIXTURE, "articles"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const CHECK_FILE = path.join(FIXTURE, ".umtool", "refresh-check.json"); +const PIECE = `a:articles/${REFRESH_ARTICLE}`; +const page_ = () => urls.articleHref({ site: "articles", id: REFRESH_ARTICLE }); + +const stubAsked = (): Record<string, unknown>[] => { + try { + return JSON.parse(readFileSync(STUB_LOG, "utf8")) as Record<string, unknown>[]; + } catch { + return []; + } +}; +const dialog = (page: Page) => page.locator(`dialog[data-refresh-dialog='${REFRESH_ARTICLE}']`); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + makeRefreshFixture({ articles: ARTICLES, source: `local:${path.join(FIXTURE, "research-public")}` }); + await warm(playwright, [page_(), "/", "/api/articles/refresh?article=refreshfix", "/api/articles/refresh/check"]); +}); + +test.afterAll(() => { + rmSync(path.join(ARTICLES, REFRESH_ARTICLE), { recursive: true, force: true }); + rmSync(CHECK_FILE, { force: true }); +}); + +test("the ⋯ menu's Refresh: the plan — the iteration, its queries, the fetches (a held platform skipped), the build, the cap — and nothing written until Refresh", async ({ page }) => { + await page.goto(page_()); + await page.getByRole("button", { name: "More" }).click(); + await page.getByRole("button", { name: "Refresh…" }).click(); + const d = dialog(page); + await expect(d).toBeVisible(); + const plan = d.locator(`[data-refresh-plan='${REFRESH_ARTICLE}']`); + await expect(plan).toContainText("i1"); + await expect(plan.locator("[data-refresh-queries]")).toHaveText("“lighthouse budget”"); + await expect(plan.locator("[data-refresh-channel='harbor-radio']")).toContainText("sync → refresh-report → transcribe-bucket (what lands)"); + await expect(plan.locator("[data-refresh-channel='otherchan']")).toContainText("skipped — rumble is held"); + await expect(plan.locator("[data-refresh-build='priv']")).toContainText("locally, if anything changed — never deployed"); + await expect(plan.locator("[data-refresh-cap]")).toContainText("spends up to $5.00"); + // The plan was the editor's dry run; no iteration was made. + expect(stubAsked().filter((r) => r.route === "report-draft" && r.task === "refresh").at(-1)).toMatchObject({ article: REFRESH_ARTICLE, dryRun: true }); + expect(existsSync(path.join(ARTICLES, REFRESH_ARTICLE, "iterations", "2"))).toBe(false); + await d.getByRole("button", { name: "Cancel" }).click(); + await expect(d).toBeHidden(); +}); + +test("the daily check finds the recording the sweep never saw: the Inbox's suggestion card, and the Next card, open the plan", async ({ page, request }) => { + const r = await request.post("/api/articles/refresh/check", { data: { article: REFRESH_ARTICLE, force: true } }); + expect(r.ok()).toBe(true); + const out = (await r.json()) as { checked: { article: string; newCount: number; newIds: string[]; titles: string[]; since: string }[] }; + expect(out.checked).toHaveLength(1); + expect(out.checked[0]).toMatchObject({ article: REFRESH_ARTICLE, newCount: 1, newIds: [REFRESH_NEW.id], titles: [REFRESH_NEW.title] }); + + await page.goto(urls.homeHref()); + const card = page.locator(`[data-lit-line][data-piece='${PIECE}'][data-card='refresh-available']`); + await expect(card).toBeVisible(); + await expect(card).toContainText(`1 new recording mentions this since 2026-10-14: ${REFRESH_NEW.title}`); + await expect(page.locator(`[data-group=review] [data-piece='${PIECE}'][data-card='refresh-available']`)).toBeVisible(); + const action = card.locator("[data-action-link]"); + await expect(action).toHaveText("Refresh"); + await expect(action).toHaveAttribute("href", `/articles/${REFRESH_ARTICLE}?refresh=1`); + + // The piece's Next card is the same call, and its action opens the plan. + await page.goto(page_()); + await expect(page.locator("[data-next-kind='refresh-available']")).toBeVisible(); + await page.locator("[data-next-action] a").click(); + await expect(page).toHaveURL(new RegExp(`/articles/${REFRESH_ARTICLE}\\?refresh=1$`)); + await expect(dialog(page)).toBeVisible(); + await expect(dialog(page).locator("[data-refresh-queries]")).toHaveText("“lighthouse budget”"); + await dialog(page).getByRole("button", { name: "Cancel" }).click(); + await expect(page).toHaveURL(new RegExp(`/articles/${REFRESH_ARTICLE}$`)); +}); + +test("Refresh: one editor job, then the Overview says what it found — the new recording, the quote that changed; the Review card", async ({ page }) => { + test.setTimeout(60_000); + await page.goto(urls.articleHref({ site: "articles", id: REFRESH_ARTICLE }, { refresh: true })); + await expect(dialog(page).locator("[data-refresh-plan]")).toBeVisible(); + await dialog(page).getByRole("button", { name: "Refresh", exact: true }).click(); + await expect(page.locator("[data-refresh-started]")).toContainText("Refresh i2 is running"); + expect(stubAsked().filter((r) => r.route === "report-draft" && r.task === "refresh").at(-1)).toMatchObject({ article: REFRESH_ARTICLE, iteration: 1 }); + // The Overview follows it (it reads again while the refresh runs). + const summary = page.locator("[data-refresh-summary='2']"); + await expect(summary).toBeVisible(); + await expect(summary).toHaveAttribute("data-refresh-state", "updated", { timeout: 20_000 }); + await expect(summary.locator("[data-refresh-line]")).toHaveText("1 new recording matches · 1 quote changed"); + await expect(summary.locator("[data-refresh-new]")).toContainText(REFRESH_NEW.title); + await expect(summary.locator("[data-refresh-drifted]")).toContainText("now: “the lighthouse budget was not approved that year”"); + await expect(summary.locator("[data-refresh-steps]")).toContainText("build priv done"); + await expect(summary.getByRole("link", { name: "Review in Iterations →" })).toHaveAttribute("href", `/articles/${REFRESH_ARTICLE}?tab=iterations`); + // A refresh with a report is a finished iteration to review; the suggestion is spent. + await page.goto(urls.homeHref()); + await expect(page.locator(`[data-lit-line][data-piece='${PIECE}'][data-card='iteration-ready']`)).toBeVisible(); + await expect(page.locator(`[data-lit-line][data-piece='${PIECE}'][data-card='refresh-available']`)).toHaveCount(0); +}); + +test("1366×768: the plan fits without scrolling the page", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + await page.goto(urls.articleHref({ site: "articles", id: REFRESH_ARTICLE }, { refresh: true })); + const d = dialog(page); + await expect(d.locator("[data-refresh-plan]")).toBeVisible(); + const box = await d.boundingBox(); + expect(box).not.toBeNull(); + expect(box!.y).toBeGreaterThanOrEqual(0); + expect(box!.y + box!.height).toBeLessThanOrEqual(768); + await expect(d.getByRole("button", { name: "Refresh", exact: true })).toBeInViewport(); +}); diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -299,7 +299,8 @@ export async function cancelDraftJob(id: string): Promise<void> { // (the editor refuses an unknown key; this refuses it first, by name). `source` // and `seed` are a research board's hand-off (R2, lib/research/handoff.ts): the // corpus the board was read through, and the board as the sweep's seed.md. -const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy", "source", "seed"]; +// `fetch` is a refresh's (R4: false skips its fetch and build). +const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy", "source", "seed", "fetch"]; export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> { const out: Record<string, unknown> = {}; diff --git a/umtool/lib/articles/refresh.ts b/umtool/lib/articles/refresh.ts @@ -0,0 +1,103 @@ +import { readIterationFile, readIterations, type Iteration } from "yt-dlp-transcript-common/lib/report/iterations"; +import { REFRESH_FORMAT, deltaLine, type RefreshFile, type RefreshPlan } from "yt-dlp-transcript-common/lib/report/draft/refresh/types"; +import { articleHref } from "@/lib/hrefs"; +import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; +import { askEditor, enqueueDraft } from "./generation"; +import { sitesPaths } from "./sites"; + +// --------------------------------------------------------------------------- +// A REFRESH, AS UMTOOL SEES IT (plans/umtool-redesign.md, R4): re-fetch an +// article's scope, see what changed, update. The editor plans it and runs it +// (`report-draft {"task": "refresh"}`, common's controller/reportRefresh.ts); +// umtool asks for the plan, confirms it, and reads what each refresh kept +// (its iteration's refresh.json) -- it writes nothing of the article store. +// +// SERVER-ONLY. +// --------------------------------------------------------------------------- + +export type { RefreshPlan }; + +/** What a refresh of `article` would do (the editor's `dryRun`): nothing is written. */ +export async function planArticleRefresh(article: string, o: { iteration?: number; fetch?: boolean } = {}): Promise<RefreshPlan> { + const answer = await askEditor<{ plan: RefreshPlan }>("/api/ops/report-draft", { + method: "POST", + body: { task: "refresh", article, dryRun: true, ...(o.iteration ? { iteration: o.iteration } : {}), ...(o.fetch === false ? { fetch: false } : {}) }, + }); + return answer.plan; +} + +/** Start it: one editor job. Answers its job, the new iteration, and where to watch it. */ +export async function startArticleRefresh(article: string, o: { iteration?: number; fetch?: boolean } = {}): Promise<{ jobId: string; iteration: number; href: string }> { + const out = await enqueueDraft({ task: "refresh", article, ...(o.iteration ? { iteration: o.iteration } : {}), ...(o.fetch === false ? { fetch: false } : {}) }); + return { ...out, href: articleHref({ site: ARTICLES_KEY, id: article }) }; +} + +/** One refresh iteration, as a page shows it. */ +export type RefreshRow = { + n: number; + parent: number | null; + status: Iteration["status"]; + // The refresh's own: running, no-change, updated, held-by-cap, failed, cancelled. + refresh: RefreshFile["status"] | null; + summary: string; + counts: { newIds: number; changed: number; drifted: number; deleted: number }; + // The new recordings' titles (up to 8), the quotes that changed. + news: { id: string; title: string | null; date: string | null }[]; + drifted: { citation: string; quote: string; now: string | null }[]; + deleted: string[]; + fetch: { channel: string; action: string; status: string; reason: string | null }[]; + build: { site: string | null; status: string; reason: string | null } | null; + update: { estimateUsd: number; capUsd: number | null; refusal: string | null; usd: number | null; model: string } | null; + since: string | null; + at: string; + endedAt: string | null; + jobId: string | null; + hasReport: boolean; + warnings: string[]; +}; + +function rowOf(it: Iteration, f: RefreshFile | null, hasReport: boolean): RefreshRow { + const d = f?.delta; + return { + n: it.n, + parent: it.parent, + status: it.status, + refresh: f?.status ?? null, + summary: f?.summary || (d ? deltaLine(d, f?.basis.at) : it.status === "queued" ? "Queued" : it.status === "running" ? "Fetching and searching again…" : (it.error ?? "")), + counts: { newIds: d?.newIds.length ?? 0, changed: d?.changed.length ?? 0, drifted: d?.drifted.length ?? 0, deleted: d?.deleted.length ?? 0 }, + news: (d?.new ?? []).slice(0, 8).map((r) => ({ id: r.id, title: r.title, date: r.date })), + drifted: (d?.quotes ?? []).filter((q) => q.status === "drifted").slice(0, 8).map((q) => ({ citation: q.citation, quote: q.quote, now: q.now ?? null })), + deleted: d?.deleted ?? [], + fetch: (f?.fetch ?? []).map((s) => ({ channel: s.channel, action: s.action, status: s.status, reason: s.reason ?? null })), + build: f?.build ? { site: f.build.site, status: f.build.status, reason: f.build.reason ?? null } : null, + update: f?.update ? { estimateUsd: f.update.estimateUsd, capUsd: f.update.capUsd, refusal: f.update.refusal ?? null, usd: f.update.usd ?? null, model: f.update.model } : null, + since: f?.basis.at ?? null, + at: it.createdAt, + endedAt: it.endedAt ?? null, + jobId: it.jobId ?? null, + hasReport, + warnings: f?.warnings ?? [], + }; +} + +/** A refresh iteration's refresh.json, or null. */ +export async function readRefreshFile(article: string, n: number): Promise<RefreshFile | null> { + const text = await readIterationFile(article, n, "refresh.json", sitesPaths()).catch(() => null); + if (!text) return null; + try { + const f = JSON.parse(text) as RefreshFile; + return f?.format === REFRESH_FORMAT ? f : null; + } catch { + return null; + } +} + +/** Every refresh of an article, newest first. */ +export async function readRefreshes(article: string): Promise<RefreshRow[]> { + const read = await readIterations(article, sitesPaths()).catch(() => null); + if (!read) return []; + const its = read.iterations.filter((it) => it.kind === "refresh").sort((a, b) => b.n - a.n); + return Promise.all( + its.map(async (it) => rowOf(it, await readRefreshFile(article, it.n), (await readIterationFile(article, it.n, "report.json", sitesPaths()).catch(() => null)) !== null)), + ); +} diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -210,7 +210,8 @@ export type ArticleRef = { site: string; id: string }; * `project` the video project the video tabs show when it is not the one the * article's Cut opens (an article that claims two); `all` the cut's every quote. */ -export type ArticleQuery = { tab?: string; status?: string; ws?: string; rel?: string; project?: string; all?: boolean } & NoteOpt; +// `refresh`: the Overview opens the Refresh plan (R4; the suggestion card's action). +export type ArticleQuery = { tab?: string; status?: string; ws?: string; rel?: string; project?: string; all?: boolean; refresh?: boolean } & NoteOpt; function articleBase(a: ArticleRef): string { return a.site === ARTICLES_KEY diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -14,6 +14,7 @@ import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./ import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle"; import { isMuted, readMutes } from "./mutes"; import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs"; +import { refreshDecisions } from "./inbox/refresh"; // --------------------------------------------------------------------------- // THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the @@ -30,6 +31,9 @@ import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups // 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) +// 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 @@ -270,7 +274,10 @@ export async function draftsDecisionsAll(): Promise<Decision[]> { export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> { const [spend, drafts] = await Promise.all([spendByJob(), draftsDecisionsAll().catch(() => [] as Decision[])]); const perArticle = await Promise.all(storeArticles(graph).map((p) => iterationDecisions(p, spend))); - return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts]; + const refresh = await readMutes() + .then((mutes) => refreshDecisions(graph, life, mutes)) + .catch(() => [] as Decision[]); + return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...refresh]; } /** diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -48,6 +48,10 @@ const KIND_CATEGORY = { "unreadable-notes": "fix", "link-ambiguous": "choose", "looks-done": "finish", + // R4: a refresh the cap held is money waiting on a yes or no; new + // recordings since the current report are something to review. + "refresh-held": "spend", + "refresh-available": "review", }; const CATEGORY_GROUP = { @@ -76,7 +80,7 @@ export function groupOf(d) { // Within a group: the brief's order first (proposals before failed runs), then // everything else as equals. -const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0 }; +const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0, "refresh-held": 2, "refresh-available": 2 }; const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; // ONE primary action per decision, its button copy naming the result. @@ -115,6 +119,8 @@ const ACTION_LABEL = { "shadowed-name": "Rename the project", "unroutable-name": "Rename the project", "ambiguous-project": "Fix the project's files", + "refresh-held": "Refresh", + "refresh-available": "Refresh", }; const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" }; diff --git a/umtool/lib/inbox/refresh.test.ts b/umtool/lib/inbox/refresh.test.ts @@ -0,0 +1,138 @@ +// Refresh, as umtool sees it (R4): the daily check over the refresh fixture +// (an article whose sweep never saw one recording of Research's local corpus), +// the two Inbox kinds it adds (refresh-available, refresh-held) and when they +// go, and the plan and start asked of a stand-in editor. +// +// Run with: pnpm --filter umtool exec tsx --test lib/inbox/refresh.test.ts +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +let tmp: string; +let editor: Server; +const asked: Record<string, unknown>[] = []; +let mod: { + refresh: typeof import("./refresh"); + articles: typeof import("../articles/refresh"); + pieces: typeof import("../pieces"); + lifecycle: typeof import("../lifecycle"); + mutes: typeof import("../mutes"); + groups: typeof import("./groups.mjs"); +}; +let fixture: typeof import("../../e2e/fixtures/refresh-fixture.mjs"); + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-refresh-")); + const research = await import("../../e2e/fixtures/research-fixture.mjs"); + const { pub } = research.makeResearchFixture({ dest: tmp, channels: path.join(tmp, "channels") }); + fixture = await import("../../e2e/fixtures/refresh-fixture.mjs"); + fixture.makeRefreshFixture({ articles: path.join(tmp, "articles"), source: `local:${pub}` }); + // The stand-in editor: report-draft's dry run answers a plan; a start, a job. + editor = createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + const body = JSON.parse(raw || "{}") as Record<string, unknown>; + asked.push(body); + res.setHeader("content-type", "application/json"); + if (body.dryRun) return res.end(JSON.stringify({ ok: true, plan: { article: body.article, parent: { n: 1 }, refusals: [], warnings: [] } })); + res.end(JSON.stringify({ ok: true, jobId: "job-1", iteration: 2 })); + }); + }); + await new Promise<void>((r) => editor.listen(0, "127.0.0.1", r)); + process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${(editor.address() as AddressInfo).port}`; + process.env.WORKER_TOKEN = "t"; + process.env.TRANSCRIPT_LOCAL_DIR = pub; + process.env.CHANNELS_DIR = path.join(tmp, "channels"); + process.env.SITES_DIR = path.join(tmp, "sites"); + process.env.ARTICLES_DIR = path.join(tmp, "articles"); + process.env.REPORTS_DIR = path.join(tmp, "reports"); + process.env.SETTINGS_FILE = path.join(tmp, "settings.json"); + delete process.env.TRANSCRIPT_HUB_URL; + await mkdir(process.env.REPORTS_DIR, { recursive: true }); + mod = { + refresh: await import("./refresh"), + articles: await import("../articles/refresh"), + pieces: await import("../pieces"), + lifecycle: await import("../lifecycle"), + mutes: await import("../mutes"), + groups: await import("./groups.mjs"), + }; +}); + +after(async () => { + editor?.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const ctx = async () => { + mod.pieces.clearPiecesCache(); + return Promise.all([mod.pieces.readPieceGraph(), mod.lifecycle.readLifecycle(), mod.mutes.readMutes()]); +}; + +test("the daily check: the current report's enumeration again over the corpus it read — the one recording it never saw, kept a day", async () => { + const [graph, life, mutes] = await ctx(); + const pieces = mod.refresh.checkable(graph, life, mutes); + assert.ok(pieces.some((p) => p.report === fixture.REFRESH_ARTICLE)); + const first = await mod.refresh.runRefreshChecks(pieces, { only: fixture.REFRESH_ARTICLE }); + assert.equal(first.checked.length, 1); + const c = first.checked[0]!; + assert.equal(c.error, undefined, c.error); + assert.deepEqual({ newCount: c.newCount, newIds: c.newIds, titles: c.titles, iteration: c.iteration }, { newCount: 1, newIds: [fixture.REFRESH_NEW.id], titles: [fixture.REFRESH_NEW.title], iteration: 1 }); + assert.match(c.source, /^local:.*research-public$/); + // Kept: today's is not checked again. + const again = await mod.refresh.runRefreshChecks(pieces, { only: fixture.REFRESH_ARTICLE }); + assert.deepEqual(again, { checked: [], skipped: [{ article: fixture.REFRESH_ARTICLE, why: "checked today" }] }); + assert.equal((await mod.refresh.readRefreshChecks()).articles[fixture.REFRESH_ARTICLE]?.newCount, 1); +}); + +test("the Inbox's cards: refresh-available in Review (action Refresh, the plan open); gone once a refresh looks; refresh-held is Your call", async () => { + let [graph, life, mutes] = await ctx(); + let rows = await mod.refresh.refreshDecisions(graph, life, mutes, { background: false }); + const avail = rows.find((r) => r.kind === "refresh-available")!; + assert.ok(avail, JSON.stringify(rows)); + assert.equal(avail.why, `1 new recording mentions this since 2026-10-14: ${fixture.REFRESH_NEW.title}`); + assert.equal(avail.href, `/articles/${fixture.REFRESH_ARTICLE}?refresh=1`); + const [a] = mod.groups.annotate([avail], { pieceOf: () => `a:articles/${fixture.REFRESH_ARTICLE}`, lifecycleOf: () => "active" }); + assert.deepEqual({ group: a.group, label: a.action.label }, { group: "review", label: "Refresh" }); + + // A refresh after the check, held by the cap: the suggestion is spent, the hold is the call. + const dir = path.join(process.env.ARTICLES_DIR!, fixture.REFRESH_ARTICLE, "iterations", "2"); + await mkdir(dir, { recursive: true }); + const at = new Date(Date.now() + 1000).toISOString(); + await writeFile( + path.join(dir, "iteration.json"), + JSON.stringify({ + format: "archilyzer-iteration", version: 1, article: fixture.REFRESH_ARTICLE, n: 2, kind: "refresh", parent: 1, copyOf: null, model: "claude-sonnet-5-5", + status: "done", usage: {}, steps: [], createdAt: at, updatedAt: at, endedAt: at, + refresh: { status: "held-by-cap", newIds: 1, changed: 0, drifted: 0, deleted: 0, summary: "1 new recording matches — held by the cap (about $0.40 to update): the daily cap" }, + }), + ); + [graph, life, mutes] = await ctx(); + rows = await mod.refresh.refreshDecisions(graph, life, mutes, { background: false }); + assert.deepEqual(rows.map((r) => r.kind), ["refresh-held"]); + assert.equal(rows[0]!.why, "i2 1 new recording matches — held by the cap (about $0.40 to update): the daily cap"); + const [h] = mod.groups.annotate([rows[0]!], { pieceOf: () => `a:articles/${fixture.REFRESH_ARTICLE}`, lifecycleOf: () => "active" }); + assert.deepEqual({ group: h.group, label: h.action.label }, { group: "your-call", label: "Refresh" }); + // Parked: no check is for it. + await mod.lifecycle.setLifecycle(`a:articles/${fixture.REFRESH_ARTICLE}`, "parked"); + [graph, life, mutes] = await ctx(); + assert.equal(mod.refresh.checkable(graph, life, mutes).some((p) => p.report === fixture.REFRESH_ARTICLE), false); + await mod.lifecycle.setLifecycle(`a:articles/${fixture.REFRESH_ARTICLE}`, "active"); +}); + +test("the plan and the start are the editor's: a dry run, then report-draft refresh", async () => { + const plan = await mod.articles.planArticleRefresh(fixture.REFRESH_ARTICLE, { fetch: false }); + assert.equal(plan.article, fixture.REFRESH_ARTICLE); + assert.deepEqual(asked.at(-1), { task: "refresh", article: fixture.REFRESH_ARTICLE, dryRun: true, fetch: false }); + const started = await mod.articles.startArticleRefresh(fixture.REFRESH_ARTICLE, { iteration: 1 }); + assert.deepEqual(started, { jobId: "job-1", iteration: 2, href: `/articles/${fixture.REFRESH_ARTICLE}` }); + assert.deepEqual(asked.at(-1), { task: "refresh", article: fixture.REFRESH_ARTICLE, iteration: 1 }); + // What the refreshes kept, newest first. + const rows = await mod.articles.readRefreshes(fixture.REFRESH_ARTICLE); + assert.deepEqual(rows.map((r) => [r.n, r.status, r.refresh]), [[2, "done", null]]); +}); diff --git a/umtool/lib/inbox/refresh.ts b/umtool/lib/inbox/refresh.ts @@ -0,0 +1,266 @@ +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 { openSource } from "@/lib/research/sources"; + +// --------------------------------------------------------------------------- +// 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 <date>". 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. +// +// 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; + // 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; + partial: boolean; + error?: string; +}; +type CheckFile = { format: typeof CHECK_FORMAT; version: 1; articles: Record<string, CheckEntry> }; + +const utcDay = (d = new Date()) => d.toISOString().slice(0, 10); + +export async function readRefreshChecks(): Promise<CheckFile> { + 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<unknown> = Promise.resolve(); +function saveCheck(entry: CheckEntry): Promise<void> { + 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 = `${file}.${process.pid}.tmp`; + 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?.channelsNotReached ?? [], + }; + }; +} + +// The corpus an article's check reads: the build its iteration read, when it +// is on this machine, else Research's local corpus. +async function sourceFor(recorded: string | null): Promise<{ handle: string; source: ShardSource }> { + if (recorded?.startsWith("local:")) { + const dir = recorded.slice("local:".length); + const ok = await stat(/* turbopackIgnore: true */ path.join(dir, "corpus.json")).then(() => true, () => false); + if (ok) { + const reg = new SourceRegistry({ kind: "local", dir }); + return { handle: recorded, source: (await reg.resolve(undefined)).source }; + } + } + const opened = await openSource(null); + return { handle: opened.option.handle, source: opened.source }; +} + +/** 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<CheckEntry | null> { + 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 { handle, source } = await sourceFor(basis.source); + 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, + 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, + }; + } catch (e) { + return { ...base, 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<unknown> | 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<Decision[]> { + 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]; + if (!c || c.error || c.newCount <= 0 || 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: `${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 ? ", …" : ""}` : ""}`, + href, + severity: "open", + at: Date.parse(c.checkedAt) || 0, + } as Decision); + } + return out; +} diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -12,6 +12,8 @@ export const WHAT = { "unreadable-notes": "notes.json does not read", "link-ambiguous": "video not linked", "looks-done": "looks done", + "refresh-available": "new recordings since", + "refresh-held": "refresh held by the cap", "claim-unadjudicated": "claims never ruled", "claim-incoherent": "claims that don't hold together", "clip-no-cues": "clips with no cues", diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/research/*.test.ts", + "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -166,6 +166,10 @@ export default defineConfig({ // the middle of a job and prove that cancelling abandons the rest while // the next run resumes. Read only by bin/cut-from-cache.mjs. `E2E_UMTOOL_CUT_DELAY_MS=2000 ` + + // No background refresh check (R4, lib/inbox/refresh.ts): an Inbox read + // would otherwise enumerate every fixture article's corpus and add cards + // other specs count. refresh.spec runs the check itself, through its route. + `UMTOOL_REFRESH_CHECK=0 ` + APP_SERVER, port: PORT, reuseExistingServer: false,