// `report-draft {"task": "refresh", "article", "iteration"?}` — re-fetch, see // what changed, update (umtool R4; plans/umtool-redesign.md "R4 — Refresh"). // The task is draft/refresh/task.ts; this is the editor's side of it: // // planRefresh what a refresh would do, nothing written (the ops route's // `dryRun: true`; umtool's plan-then-confirm): the iteration // refreshed and what it was built from, each channel's // actions (or why one is skipped), the site built, the // model and the cap // enqueueRefresh the `refresh` iteration (queued, its parent the one // refreshed), then ONE `report-draft` job on its own lane // (`draft:refresh`: it waits on fetches and a build before // any model runs, so it never holds `draft:api`) // the job the task over the editor's own hooks: its ops actions in // process (the research run's door), its job registry, its // channels, the platform holds, the builds, the disk's // records, and the caps. The log ends `@@report-draft {…, // refresh: {status, newIds, changed, drifted, deleted, // summary}}`. // // The iteration refreshed: `iteration` when given, else the current report's // (current.json), else the newest done iteration that carries a report. import { modelLogged } from "./jobModelLog"; import { access, readFile } from "node:fs/promises"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; import { heldPlatformRefusal, platformCooldownRemainingMs } from "../jobs/downloadBackoff"; import { getWorkerPool } from "../jobs/workerPool"; import { DRAFT_REFRESH_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { capFor, type GenerationSettings } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; import { providerOf, unloadOllama } from "../lib/llm"; import { webTools } from "../lib/web/tools"; import { stateFromAvailability } from "../lib/availability"; import { resolveEffectiveAvailability } from "../lib/availability-server"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { detectPlatform } from "../lib/detectPlatform.mjs"; import { WHISPER_FILENAME, englishVttsByPreference } from "../lib/videoStatus"; import { parseVtt } from "../lib/vtt"; import { isStoredTextReadError, readStoredText, readdirLogical } from "../lib/storedText-server"; import { parseTranscriptJson } from "../lib/whisper"; import { isCuesJsonFresh, readNormalizedTranscript } from "./normalizeTranscript"; import { diskPostChannelOf } from "../lib/report/convert-server"; import { readAllPosts } from "../lib/posts-server"; import { createIteration, currentIteration, lineageSource, listIterations, readIteration, readIterationFile, updateIteration, } from "../lib/report/iterations"; import { listCorpusBuilds, pickCorpusBuild, siteOriginOf, type CorpusBuild } from "../lib/report/draft/tasks/corpusSource"; import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues"; import type { CorpusToolsLike, TaskDeps } from "../lib/report/draft/tasks/types"; import { refresh as refreshTask, type RefreshHooks } from "../lib/report/draft/refresh/task"; import { fetchAndBuild, type FetchAndBuild, type FetchHooks } from "../lib/report/draft/refresh/fetch"; import { NothingToRefreshError, refreshBasis } from "../lib/report/draft/refresh/basis"; import type { RecordRead } from "../lib/report/draft/refresh/delta"; import { DEFAULT_REVISION_USD, DEFAULT_USD_PER_RECORDING } from "../lib/report/draft/refresh/task"; import { REFRESH_FORMAT, outcomeOf, type RefreshFile, type RefreshPlan, type RefreshPlanChannel } from "../lib/report/draft/refresh/types"; import type { ResearchEditor } from "../lib/report/draft/research/tools"; import { verifyReportQuotes } from "../bin/reports-check"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { listChannelConfigs, readChannelSnapshot } from "./channels"; import { jobOfPaths } from "./researchRuns"; import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, citationOriginFor, llmConfigOf, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued, } from "./reportDraft"; // The editor actions a refresh runs (its in-process door must offer them). export const REFRESH_EDITOR_ACTIONS = ["sync", "fetch-posts", "refresh-report", "transcribe-bucket", "publish"] as const; export class RefreshInputError extends Error {} // ─── which iteration ─── /** The iteration a refresh of `article` refreshes: the one asked, else the current report's, else the newest done one with a report. */ export async function refreshTarget(article: string, asked: number | undefined, paths: ReportDraftDeps["paths"]): Promise { if (asked !== undefined) { const it = await readIteration(article, asked, paths); if (!it) throw new RefreshInputError(`"${article}" has no iteration i${asked}`); if (it.status !== "done") throw new RefreshInputError(`"${article}" i${asked} is ${it.status}: only a done iteration is refreshed`); return asked; } const cur = await currentIteration(article, paths).catch(() => null); if (cur?.report != null) return cur.report; const its = (await listIterations(article, paths).catch(() => [])).filter((i) => i.status === "done").sort((a, b) => b.n - a.n); for (const it of its) { if ((await readIterationFile(article, it.n, "report.json", paths)) !== null) return it.n; } throw new RefreshInputError(`"${article}" has no report to refresh: no iteration is current and none that is done carries a report`); } // The model and cap an update runs on: the asked model, else the sweep // route's (a sweep routed to Claude Code runs the API model here — said so). export function refreshModel(gen: GenerationSettings, body: Pick): { model: string; provider: "api" | "local"; capUsd: number | null; extractor: string; note?: string } { const route = gen.routes.sweep; const model = body.model ?? (route === "local" ? gen.models.local : gen.models.api); const provider = providerOf(model) === "local" ? "local" : "api"; return { model, provider, capUsd: provider === "api" ? capFor(gen.caps, "sweep", body.maxUsd) : null, extractor: body.extractorModel ?? gen.models.extractor, ...(!body.model && route === "code" ? { note: "sweeps are routed to Claude Code: the update runs the API model here" } : {}), }; } // ─── the builds and the corpus ─── // The composed build a handle names (`local://out`), or null. function buildOfSource(source: string | null, builds: CorpusBuild[]): CorpusBuild | null { if (!source?.startsWith("local:")) return null; const dir = path.resolve(source.slice("local:".length)); return builds.find((b) => path.resolve(b.dir) === dir) ?? null; } /** The build a refresh reads and rebuilds: the parent's own when it still holds the channels, else the newest that holds them all. */ export async function refreshBuild(channels: string[], prefer: string | null, paths: Pick): Promise { const builds = await listCorpusBuilds(paths.exportBuildsDir); const mine = buildOfSource(prefer, builds); if (mine && channels.every((c) => mine.channels.includes(c))) return mine; return pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir }).catch(() => mine); } const exists = (p: string) => access(p).then(() => true, () => false); // ─── the plan ─── export async function planRefresh(body: ReportDraftBody, deps: ReportDraftDeps): Promise { const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; const n = await refreshTarget(body.article, body.iteration, paths); const it = (await readIteration(body.article, n, paths))!; const basis = await refreshBasis(body.article, n, paths).catch((e: Error) => { throw new RefreshInputError(e.message); }); const refusals: string[] = []; const warnings: string[] = []; const fetch = body.fetch !== false; const configs = new Map((await listChannelConfigs(paths).catch(() => [])).map((c) => [c.slug, c.config as Record])); const channels: RefreshPlanChannel[] = []; for (const slug of basis.scope.channels) { const c = configs.get(slug); if (!c) { channels.push({ slug, kind: null, platform: null, actions: [], skip: "not a channel of this editor" }); continue; } const kind = isPostsChannel(c) ? "posts" : "video"; const platform = platformOfConfig(c); const skip = fetch && platform ? await platformRefusalOf(platform, paths) : null; channels.push({ slug, kind, platform, actions: !fetch ? [] : kind === "posts" ? ["fetch-posts"] : ["sync", "refresh-report", "transcribe-bucket (what lands)"], ...(skip ? { skip } : {}), }); } const build = await refreshBuild(basis.scope.channels, basis.source, paths); let site: RefreshPlan["build"] = { site: null, reason: "no composed build holds these channels" }; if (build) { site = (await exists(path.join(paths.sitesDir, build.build, "site.json"))) ? { site: build.build, builtAt: new Date(build.mtimeMs).toISOString() } : { site: null, reason: `the build ${build.build} is not a site's: it is read as it stands`, builtAt: new Date(build.mtimeMs).toISOString() }; } else { refusals.push(`no composed build holds ${basis.scope.channels.join(", ")} — publish build the site that carries them first`); } if (!fetch) site = { site: null, reason: "no fetch: the corpus is read as it stands", ...(build ? { builtAt: new Date(build.mtimeMs).toISOString() } : {}) }; const m = refreshModel(gen, body); if (m.note) warnings.push(m.note); if (basis.from === "question") warnings.push(`i${n} recorded no enumeration: its question is searched again as one query`); if (!basis.countsKnown) warnings.push(`changed recordings are not tracked before ${basis.at.slice(0, 10)}: i${n} recorded no matching-line counts (new ones are still found)`); if (!basis.knownComplete) warnings.push(`i${n} kept no whole match set: a recording counts as new only when it was uploaded on or after ${basis.at.slice(0, 10)}`); const parentIt = basis.queriesOf === n ? it : await readIteration(body.article, basis.queriesOf, paths).catch(() => null); const parentUsd = parentIt ? Object.values(parentIt.usage).reduce((s, u) => s + u.usd, 0) : 0; const read = parentIt?.coverage?.read ?? 0; const day = m.provider === "api" ? await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())).catch(() => null) : null; return { article: body.article, parent: { n, kind: it.kind, model: it.model, question: basis.question, at: basis.at, from: basis.from, queries: basis.queries.map((q) => q.query), knownCount: Object.keys(basis.known).length, knownComplete: basis.knownComplete, citedCount: basis.cited.length, }, scope: basis.scope, fetch, channels, build: site, corpus: { source: build ? `local:${build.dir}` : null, build: build?.build ?? null }, model: m.model, provider: m.provider, extractor: m.provider === "api" ? m.extractor : null, capUsd: m.capUsd, daily: day ? { usd: day.usd, cap: gen.caps.daily } : null, estimate: parentUsd > 0 && read > 0 ? { perRecordingUsd: Math.round((parentUsd / read) * 1000) / 1000, revisionUsd: DEFAULT_REVISION_USD, from: "parent" } : { perRecordingUsd: DEFAULT_USD_PER_RECORDING, revisionUsd: DEFAULT_REVISION_USD, from: "default" }, refusals, warnings, }; } // A social channel's posts are fetched (fetch-posts); a video channel is synced. const isPostsChannel = (c: Record) => c.sourceKind === "social" || (typeof c.postFetcher === "string" && !!c.postFetcher); // The platform a channel's fetches are paced (and held) under: its config's, else its URL's. const platformOfConfig = (c: Record): string | null => typeof c.platform === "string" && c.platform ? c.platform : detectPlatform(typeof c.url === "string" ? c.url : null); // Why a fetch on `platform` is refused now: held (its probe still ahead), or cooling down. async function platformRefusalOf(platform: string, paths: ReportDraftDeps["paths"]): Promise { const held = await heldPlatformRefusal(platform, "A refresh's fetch", paths).catch(() => null); if (held) return held; const ms = await platformCooldownRemainingMs(platform, paths).catch(() => 0); return ms > 0 ? `${platform} is cooling down after a rate limit (${Math.max(1, Math.ceil(ms / 60_000))} min left): skipped, as polite scraping asks` : null; } // ─── enqueue ─── export async function enqueueRefresh(body: ReportDraftBody, deps: ReportDraftDeps): Promise { const refuse = (error: string) => ({ result: { ok: false as const, error } }); const paths = deps.paths; if (!deps.refreshEditor) return refuse("a refresh runs in the editor (its fetches and build are the editor's own actions)"); const gen = (deps.settings ?? getSettings)().generation; let n: number; let plan: RefreshPlan; try { n = await refreshTarget(body.article, body.iteration, paths); plan = await planRefresh({ ...body, iteration: n }, deps); } catch (e) { if (e instanceof RefreshInputError || e instanceof NothingToRefreshError) return refuse(e.message); throw e; } if (plan.refusals.length) return refuse(plan.refusals.join("; ")); const m = refreshModel(gen, body); const parent = (await readIteration(body.article, n, paths))!; const it = await createIteration( body.article, { kind: "refresh", model: m.model, parent: n, ...(plan.parent.question ? { question: plan.parent.question } : parent.question ? { question: parent.question } : {}), scope: plan.scope, }, paths, ); const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: DRAFT_REFRESH_QUEUE, paths, fn: modelLogged({ paths, task: "refresh" }, (onLog, signal, setProgress, ctx) => runRefreshJob({ body, n: it.n, model: m.model, capUsd: m.capUsd, extractor: m.extractor, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); if (!result.ok) { await updateIteration(body.article, it.n, { status: "failed", error: result.error }, paths).catch(() => {}); return { result }; } await updateIteration(body.article, it.n, { jobId: result.jobId }, paths).catch(() => {}); void result.done.then(async (d) => { const cur = await readIteration(body.article, it.n, paths).catch(() => null); if (cur?.status === "queued") { await updateIteration(body.article, it.n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {}); } }); return { result, iteration: it.n, ...(plan.warnings.length ? { warnings: plan.warnings } : {}) }; } // ─── stage 1 on its own (R5's seam) ─── /** * R4.1: why transcription would not run now — the worker pool's own state * (the live one, never the stored flag: lib/pauseGates.ts): paused, or no * worker enabled. Null: it would run. */ export async function transcriptionHeldNow(): Promise { const pool = getWorkerPool(); if (pool.isPaused()) return "the transcription workers are paused"; if (!pool.enabledIds().length) return "no transcription worker is enabled"; return null; } /** The editor's side of a refresh's stage 1: its actions (deps.refreshEditor), jobs, channels, holds, reports and builds. */ export function fetchHooksOf(deps: ReportDraftDeps): FetchHooks { const paths = deps.paths; if (!deps.refreshEditor) throw new RefreshInputError("a refresh's fetch runs in the editor (its own actions): no refreshEditor"); const configs = async () => new Map((await listChannelConfigs(paths).catch(() => [])).map((c) => [c.slug, c.config as Record])); return { editor: deps.refreshEditor, jobOf: deps.jobOf ?? jobOfPaths(paths), channelOf: async (slug) => { const c = (await configs()).get(slug); if (!c) return null; const platform = platformOfConfig(c); const localLibrary = !!c.localMedia && !(typeof c.url === "string" && c.url.trim()); return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}), ...(localLibrary ? { localLibrary: true as const } : {}) }; }, platformRefusal: (platform) => platformRefusalOf(platform, paths), bucketOf: async (slug) => { const snap = await readChannelSnapshot(paths, slug).catch(() => null); return snap ? [...(snap.buckets.downloadedNoTranscript ?? [])] : null; }, transcriptionHeld: deps.transcriptionHeld ?? transcriptionHeldNow, siteOf: async (channels, prefer) => { const b = await refreshBuild(channels, prefer, paths); if (!b) return { site: null, reason: `no composed build holds ${channels.join(", ")}` }; if (!(await exists(path.join(paths.sitesDir, b.build, "site.json")))) return { site: null, reason: `the build ${b.build} is not a site's: it is read as it stands` }; return { site: b.build }; }, builtAt: async (channels, prefer) => { const b = await refreshBuild(channels, prefer, paths); return b ? b.mtimeMs : null; }, ...(deps.refreshTiming ?? {}), }; } /** * R5's SEAM — a refresh's stage 1 for any scope, awaited: each channel's * fetches (sync → refresh-report → transcribe-bucket for what landed; or * fetch-posts), a held or cooling platform skipped and said, then the local * build of the site whose build holds the channels (never a deploy). Answers * what was fetched, built or refused. `deps.refreshEditor` is the editor's * in-process door (editor/app/api/ops/_researchEditor.ts refreshEditor). */ export function fetchScope( scope: { channels: string[]; from?: string; to?: string }, deps: ReportDraftDeps, o: { prefer?: string | null; signal?: AbortSignal; log?: (line: string) => void; build?: boolean } = {}, ): Promise { return fetchAndBuild(scope, fetchHooksOf(deps), o); } // ─── the job ─── // The corpus a refresh reads: opened after its build (deps.corpus is this // holder; a call before it is open is refused). class CorpusHolder implements CorpusToolsLike { current: (CorpusToolsLike & { close(): Promise }) | null = null; get source() { return this.current?.source ?? ""; } get tools() { return this.current?.tools ?? []; } call(name: string, args?: Record): Promise { if (!this.current) return Promise.reject(new Error("the corpus is not open yet")); return this.current.call(name, args); } async swap(next: CorpusToolsLike & { close(): Promise }) { const was = this.current; this.current = next; await was?.close().catch(() => {}); } } async function runRefreshJob( o: { body: ReportDraftBody; n: number; model: string; capUsd: number | null; extractor: string; jobId: string; onLog: (l: string) => void; signal: AbortSignal; setProgress?: (snap: JobProgress) => void; }, deps: ReportDraftDeps, ): Promise { const { body, n, model, onLog, signal } = o; const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; const provider = providerOf(model); onLog(`refresh of ${body.article} (i${n}) — the update on ${model} (${provider === "api" ? `the Claude API, cap $${o.capUsd}` : "the local model"})`); const holder = new CorpusHolder(); const fallback = gen.citationOrigin || PROJECT_URL; const disk = paths.channelsDir; const posts = new Map>>(); const postText = (ch: string, id: string) => { let p = posts.get(ch); if (!p) { p = readAllPosts(path.join(disk, ch)).then((all) => new Map(all.map((x) => [x.id, x.text])), () => new Map()); posts.set(ch, p); } return p.then((m) => m.get(id) ?? null); }; const cuesOf = corpusCuesOf(holder); const hooks: RefreshHooks = { ...fetchHooksOf(deps), openCorpus: async (channels, prefer) => { // A refresh of a sweep over a published archive reads (and cites) that // archive (demo epic D1): the source named, else the lineage's. const named = body.source ?? (body.build ? null : await lineageSource(body.article, n, paths).catch(() => null)); const b = named ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths); const source = named ?? (b ? `local:${b.dir}` : null); if (!source) throw new Error(`no composed build holds ${channels.join(", ")} — publish build the site that carries them`); const missing = b ? channels.filter((c) => !b.channels.includes(c)) : []; if (missing.length) onLog(`the build ${b!.build} does not hold ${missing.join(", ")}: those are not searched`); await holder.swap(await deps.corpusTools(source)); const origin = b ? ((await siteOriginOf(b.build, paths.sitesDir)) ?? fallback) : citationOriginFor(source, gen); return { source, origin, ...(b ? { build: b.build } : {}) }; }, recordOf: async (channel, id) => { const rec = await diskRecordOf(disk, channel, id).catch(() => null); if (rec) return rec; const cues = await cuesOf(channel, id); return cues ? { cues } : null; }, capRefusal: async (usd) => { if (provider !== "api") return null; if (o.capUsd !== null && usd > o.capUsd) { return `the update would cost about $${usd.toFixed(2)}, over this job's $${o.capUsd.toFixed(2)} cap (settings.generation.caps.sweep; maxUsd raises it, up to caps.max)`; } const day = await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())); const refused = dailyCapRefusal(day, gen.caps.daily); if (refused) return refused; if (gen.caps.daily > 0 && day.usd + usd > gen.caps.daily) { return `the day's Claude API spend is $${day.usd.toFixed(2)} (${day.day}, UTC): about $${usd.toFixed(2)} more would pass the $${gen.caps.daily.toFixed(2)} daily cap (settings.generation.caps.daily)`; } return null; }, }; const taskDeps: TaskDeps = { llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined), corpus: holder, web: webTools({ ...(gen.web.searchUrl ? { searchUrl: gen.web.searchUrl } : {}) }), cuesOf, postTextOf: postText, postChannelOf: diskPostChannelOf(disk), verifyReport: async (report) => (await verifyReportQuotes(report, { paths }).catch(() => [])) .filter((r) => r.status === "drift" || r.status === "en-orig-drift") .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })), paths, log: onLog, progress: (p) => o.setProgress?.({ metric: p.metric, initial: 0, target: Math.max(p.total ?? p.current, p.current), current: p.current }), signal, refresh: hooks, ...(deps.now ? { now: deps.now } : {}), }; let result: Awaited> | null = null; try { result = await refreshTask( { article: body.article, n, model, extractorModel: o.extractor, maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY, localSweep: gen.localSweep, ...(body.fetch === false ? { fetch: false } : {}), ...(body.ids?.length ? { ids: body.ids } : {}), }, taskDeps, ); } catch (e) { const cur = await readIteration(body.article, n, paths).catch(() => null); if (cur && (cur.status === "queued" || cur.status === "running")) { await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {}); } throw e; } finally { await holder.current?.close().catch(() => {}); if (provider === "local") { await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } if (provider === "api" && result) await recordUsage(body.article, n, o.jobId, paths, deps.now?.() ?? new Date()).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } const file = await readRefreshFile(body.article, n, paths); const refresh = file ? outcomeOf(file) : null; onLog( `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: n, task: "refresh", status: result.status, summary: result.summary, usd: result.usd, minutes: result.minutes, ...(refresh ? { refresh } : {}) })}`, ); if (result.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (result.status === "failed") throw new Error(result.summary); } // A cited recording on disk, as a refresh reads it: every transcript track it // has (the normalized cues, our transcription, each English caption track, // en-orig first) and its platform state when it is not available; null when the // archive holds no directory for it. (publish/composeReports' readCitedRecord // reads the same files; a controller may not import publish.) export async function diskRecordOf(channelsDir: string, slug: string, id: string): Promise { const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null); if (!dir) return null; // LOGICAL (lib/storedText.ts): a stored caption is a track under its name. const entries = await readdirLogical(dir); if (!entries.length) return null; const tracks: { name: string; cues: { start: number; end: number; text: string }[] }[] = []; const fresh = await isCuesJsonFresh(dir).catch(() => ({ fresh: false as const })); if (fresh.fresh && "cuesPath" in fresh) { const n = await readNormalizedTranscript(fresh.cuesPath).catch(() => null); if (n?.cues?.length) tracks.push({ name: path.basename(fresh.cuesPath), cues: n.cues }); } if (entries.includes(WHISPER_FILENAME)) { const w = await readFile(path.join(dir, WHISPER_FILENAME), "utf8").then((t) => parseTranscriptJson(t), () => []); if (w.length) tracks.push({ name: WHISPER_FILENAME, cues: w }); } for (const name of englishVttsByPreference(entries)) { // A stored track that does not decode is an error, never "no cues" (REVIEW-1 F3). const v = await readStoredText(dir, name, "utf8").then( (t) => parseVtt(t), (err: unknown) => { if (isStoredTextReadError(err)) throw err; return []; }, ); if (v.length) tracks.push({ name, cues: v }); } const state = stateFromAvailability(await resolveEffectiveAvailability(dir).catch(() => null)); // The platform a deletion is said on: its metadata's page. const meta = entries.includes("metadata.info.json") ? await readFile(path.join(dir, "metadata.info.json"), "utf8").then((t) => JSON.parse(t) as { webpage_url?: unknown }, () => null) : null; const platform = detectPlatform(typeof meta?.webpage_url === "string" ? meta.webpage_url : null); return { cues: tracks[0]?.cues ?? [], tracks, ...(state !== "available" ? { state, ...(platform ? { platform } : {}) } : {}) }; } /** A refresh iteration's refresh.json, or null. */ export async function readRefreshFile(article: string, n: number, paths: ReportDraftDeps["paths"]): Promise { const text = await readIterationFile(article, n, "refresh.json", paths).catch(() => null); if (!text) return null; try { const f = JSON.parse(text) as RefreshFile; return f?.format === REFRESH_FORMAT ? f : null; } catch { return null; } } async function recordUsage(article: string, n: number, jobId: string, paths: ReportDraftDeps["paths"], now: Date) { const it = await readIteration(article, n, paths); if (!it) return; const base = { at: now.toISOString(), day: utcDay(now), jobId, article, iteration: n, task: "refresh" }; const rows: GenerationUsageRow[] = Object.entries(it.usage) .filter(([m, u]) => providerOf(m) === "api" && (u.usd > 0 || (u.calls ?? 0) > 0)) .map(([m, u]) => ({ ...base, model: m, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens ?? 0, cacheWriteTokens: u.cacheWriteTokens ?? 0, usd: Math.round(u.usd * 10_000) / 10_000, })); await appendGenerationUsage(paths.generationUsageFile, rows); }