// TASK refresh — re-fetch, see what changed, update (umtool R4; plans/ // umtool-redesign.md "R4 — Refresh"). ONE editor job over a `refresh` // iteration whose parent is the iteration refreshed, in three stages, each // logged, traced (trace.jsonl: `fetch`, `build`, `delta`, and the sweep's own // events) and kept in the iteration's refresh.json: // // 1 fetch (Archilyzer, no model) the parent's scope plus every channel its // citations touch: the editor's own paced actions — `sync`, then // `refresh-report` and `transcribe-bucket` for what landed, per // video channel; `fetch-posts` per posts channel — each refused // for a platform held or cooling down (skipped, said); waited // for. Then a LOCAL BUILD of the site whose build holds the // channels (`publish build`, never forced, through the publish // lock; never a deploy), waited for — a sweep reads a composed // build (corpusSource.ts), and what was fetched is invisible to // it until a build holds it. // 2 delta (deterministic, no model) the parent's enumerations again over // the build (./basis.ts, ./delta.ts): new recordings, changed // ones, and every cited quote read again. Nothing changed: the // iteration ends `no-change`, $0. // 3 update (the model, on its own) within the policy's caps — a cap's // refusal ends it `held-by-cap` with the delta and the estimate — // a sweep RESTRICTED to the new and changed recordings over the // parent's question, then a revision of the parent's report with // its findings and the drift fixes. The result is the iteration's // report: made current only by the operator. // // The iteration ENDS `done` whatever the refresh's own status (no-change, // held-by-cap, updated); only an update that fails, or a cancel, ends it // failed or cancelled. A done refresh without a report is never offered as // current (it has nothing to offer). import type { GenerationLocalSweep } from "../../../generationSettings"; import { providerOf } from "../../../llm"; import { iterationLabel, readIteration, readIterationFile, writeIterationFile } from "../../iterations"; import { reviseReportBody } from "../tasks/revise-report"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "../tasks/run"; import { sweepAgentBody } from "../tasks/sweep-agent"; import { sweepPipelineBody } from "../tasks/sweep-pipeline"; import type { TaskDeps, TaskResult } from "../tasks/types"; import { refreshBasis } from "./basis"; import { fetchAndBuild } from "./fetch"; import { computeDelta, type QuoteReaders, type RecordRead } from "./delta"; import { REFRESH_FORMAT, REFRESH_VERSION, deltaLine, outcomeOf, platformName, type BuildStep, type FetchStep, type RefreshBasis, type RefreshDelta, type RefreshFile, type RefreshStatus, } from "./types"; // The editor's side (./fetch.ts): its actions, jobs, channels, builds, corpus and caps. export type { RefreshHooks } from "./fetch"; export type RefreshInput = { article: string; n: number; // The update's model, its extractor (an API sweep's) and the job's cap // (Infinity on a local model). model: string; extractorModel: string; maxUsd: number; // false: no stage 1 (read the corpus as it stands). fetch?: boolean; // The recordings the update reads (umtool R6: what a triage flagged), // instead of the new and changed ones; the update runs even when the delta // found nothing else. ids?: string[]; // A local update's sweep: its claim form and read-aloud rule // (settings.generation.localSweep, as a first sweep on the local route has // them). Absent: the pipeline's own defaults (sentence, off). localSweep?: GenerationLocalSweep; }; // ─── the estimate ─── // A recording read in an API sweep, and a revision, when nothing better is // known (the parent's own spend per recording read is preferred). export const DEFAULT_USD_PER_RECORDING = 0.08; export const DEFAULT_REVISION_USD = 0.3; /** About what the update costs: the recordings to read at the parent's rate, and a revision. */ export function estimateUpdateUsd(o: { recordings: number; model: string; parentUsd?: number | null; parentRead?: number | null; revisionUsd?: number }): number { if (providerOf(o.model) !== "api") return 0; const rate = o.parentUsd && o.parentRead ? o.parentUsd / o.parentRead : DEFAULT_USD_PER_RECORDING; const usd = (o.recordings ? Math.max(0.05, rate * o.recordings) : 0) + (o.revisionUsd ?? DEFAULT_REVISION_USD); return Math.round(usd * 100) / 100; } // ─── the feedback the revision is given ─── const clock = (s: number | undefined) => { const t = Math.max(0, Math.floor(s ?? 0)); const h = Math.floor(t / 3600); const m = Math.floor((t % 3600) / 60); const sec = t % 60; return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`; }; // The findings of the restricted sweep's markdown: everything after its title // and summary (its sections, with their findings and links). export function findingsOf(md: string): string { const i = md.indexOf("\n## "); return (i >= 0 ? md.slice(i + 1) : md).trim(); } export function refreshFeedback(o: { parent: number; since: string; delta: RefreshDelta; findings: string | null }): string { const parts: string[] = [ `A REFRESH of i${o.parent} (made ${o.since.slice(0, 10)}): the corpus was fetched and searched again. Fold in what changed; keep everything else as it is.`, ]; if (o.findings) { parts.push( [ "NEW FINDINGS — a sweep of the new and changed recordings found these. Add each that bears on the question with an `add` op, its quote and link EXACTLY as given, in the section it fits (or a new one). Do not duplicate a finding the report already has.", o.findings, ].join("\n"), ); } const drifted = o.delta.quotes.filter((q) => q.status === "drifted"); if (drifted.length) { parts.push( [ "QUOTES THAT CHANGED — the transcript no longer holds these words at their cite. Drop each finding quoting them; if its claim still stands on what the transcript says now, add it again with those words (verbatim) and the same link.", ...drifted.map((q) => `- "${q.quote}" (${q.channel}/${q.id} @ ${clock(q.start)}) — now: "${(q.now ?? "").slice(0, 400)}"`), ].join("\n"), ); } const gone = o.delta.quotes.filter((q) => q.status === "missing"); const deleted = o.delta.quotes.filter((q) => q.status !== "missing" && q.state); if (gone.length) { parts.push(["SOURCES NOT IN THE ARCHIVE NOW — drop the findings that quote them:", ...gone.map((q) => `- "${q.quote}" (${q.channel}/${q.id})`)].join("\n")); } if (deleted.length) { parts.push( [ "SOURCES GONE FROM THEIR PLATFORM (the archive keeps them; their quotes still verify) — keep their findings, and say in the summary that these were since removed:", ...[...new Map(deleted.map((q) => [`${q.channel}/${q.id}`, q])).values()].map((q) => `- ${q.channel}/${q.id} (${q.state} on ${platformName(q.platform)})`), ].join("\n"), ); } return parts.join("\n\n"); } // ─── the job ─── export async function refresh(input: RefreshInput, deps: TaskDeps): Promise { return runOnIteration( { article: input.article, n: input.n, deps, maxUsd: Number.isFinite(input.maxUsd) ? input.maxUsd : undefined, kinds: ["refresh"], trace: { task: "refresh", model: input.model } }, (h) => refreshBody(h, input), ); } async function refreshBody(h: TaskHandle, input: RefreshInput): Promise { const { deps, iteration } = h; const hooks = deps.refresh; if (!hooks) throw new TaskInputError("a refresh runs in the editor (its fetches and build are the editor's actions)"); const parent = iteration.parent; if (parent === null) throw new TaskInputError(`"${h.article}" ${iterationLabel(h.n)} names no iteration to refresh`); const now = () => (deps.now ?? (() => new Date()))(); const basis: RefreshBasis = await refreshBasis(h.article, parent, h.paths).catch((e: Error) => { throw new TaskInputError(e.message); }); const channels = basis.scope.channels; const warnings: string[] = []; const file: RefreshFile = { format: REFRESH_FORMAT, version: REFRESH_VERSION, article: h.article, n: h.n, parent, status: "running", summary: "", startedAt: now().toISOString(), basis: { article: basis.article, n: basis.n, queriesOf: basis.queriesOf, question: basis.question, scope: basis.scope, queries: basis.queries, from: basis.from, knownComplete: basis.knownComplete, countsKnown: basis.countsKnown, source: basis.source, at: basis.at, knownCount: Object.keys(basis.known).length, citedCount: basis.cited.length, known: basis.known, }, fetch: [], build: null, warnings, }; const save = () => writeIterationFile(h.article, h.n, "refresh.json", file, h.paths).catch((e: Error) => h.log(`refresh.json not kept: ${e.message}`)); await save(); h.log(`refresh of ${h.article} ${iterationLabel(parent)}: ${basis.queries.length} quer${basis.queries.length === 1 ? "y" : "ies"} (from its ${basis.from}), ${channels.length} channel(s), ${basis.cited.length} cited quote(s)`); if (basis.from === "question") warnings.push(`i${parent} 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${parent} recorded no matching-line counts (new ones are still found)`); if (!basis.knownComplete) warnings.push(`i${parent} kept no whole match set: a recording counts as new only when it was uploaded on or after ${basis.at.slice(0, 10)}`); h.trace({ t: "note", text: `refresh of ${iterationLabel(parent)}: ${basis.queries.map((q) => q.query).join(", ")} over ${channels.join(", ")}` }); const stages = input.fetch === false ? 2 : 4; let stage = 0; const progress = () => h.progress({ metric: "entries", current: Math.min(stage, stages), total: stages }); progress(); // ─── stage 1: fetch, then build (./fetch.ts) ─── if (input.fetch !== false) { h.log(`stage 1: fetch ${channels.join(", ")}`); const got = await fetchAndBuild({ channels }, hooks, { prefer: basis.source, ...(deps.signal ? { signal: deps.signal } : {}), log: h.log, trace: h.trace, onFetched: async (steps) => { file.fetch = steps; stage = 1; progress(); await save(); }, }); file.fetch = got.fetch; file.build = got.build; warnings.push(...got.warnings); stage = 2; progress(); await save(); } // ─── stage 2: what changed ─── const opened = await hooks.openCorpus(channels, basis.source); file.corpus = opened; h.log(`stage 2: corpus ${opened.source}${opened.build ? ` (build ${opened.build})` : ""}; links on ${opened.origin}`); const readers: QuoteReaders = { recordOf: hooks.recordOf ?? (async (channel, id): Promise => { const cues = await deps.cuesOf(channel, id); return cues ? { cues } : null; }), ...(deps.postTextOf ? { postTextOf: deps.postTextOf } : {}), }; const delta = await computeDelta(basis, deps.corpus, readers, { now: now(), ...(deps.signal ? { signal: deps.signal } : {}) }); file.delta = delta; if (delta.partial) warnings.push(`the search again was partial${delta.unreached.length ? ` (not reached: ${delta.unreached.join(", ")})` : ""}`); h.trace({ t: "delta", status: delta.status, matched: delta.matched, newIds: delta.newIds, changed: delta.changed, drifted: delta.drifted, deleted: delta.deleted, partial: delta.partial, unreached: delta.unreached }); const line = deltaLine(delta, basis.at); h.log(`delta: ${line} (${delta.matched} recording(s) matched)`); stage = input.fetch === false ? 1 : 3; progress(); const finish = async (status: RefreshStatus, summary: string, outcome: TaskOutcome["status"] = "done"): Promise => { file.status = status; file.summary = summary; file.endedAt = now().toISOString(); if (file.update) file.update.usd = Math.round(h.meter.usd * 10_000) / 10_000; await save(); stage = stages; progress(); return { status: outcome, summary, patch: { refresh: outcomeOf(file) } }; }; // R6.1: nothing found by a capped search is not "no change". const partialWhy = delta.partial ? `partial — ${delta.unreached.length ? `not reached: ${delta.unreached.join(", ")}` : "a cap was hit"}` : null; const flagged = input.ids?.length ? [...new Set(input.ids)] : null; if (delta.status === "no-change" && !flagged) return partialWhy ? finish("partial", `${partialWhy}; ${line} in what was read`) : finish("no-change", line); if (flagged) { h.log(`the update reads the ${flagged.length} recording(s) a triage flagged`); h.trace({ t: "note", text: `the update reads the ${flagged.length} recording(s) a triage flagged: ${flagged.slice(0, 20).join(", ")}` }); } // ─── stage 3: the update ─── const ids = flagged ?? [...new Set([...delta.newIds, ...delta.changed])]; const parentIt = await readIteration(h.article, basis.queriesOf, h.paths).catch(() => null); const parentUsd = parentIt ? Object.values(parentIt.usage).reduce((s, u) => s + u.usd, 0) : null; const estimate = estimateUpdateUsd({ recordings: ids.length, model: input.model, parentUsd, parentRead: parentIt?.coverage?.read ?? null }); file.update = { model: input.model, estimateUsd: estimate, capUsd: Number.isFinite(input.maxUsd) ? input.maxUsd : null }; const refusal = await hooks.capRefusal(estimate); if (refusal) { file.update.refusal = refusal; h.log(`update held by the cap: ${refusal}`); h.trace({ t: "note", text: `update held by the cap: ${refusal}` }); return finish("held-by-cap", `${line} — held by the cap (about $${estimate.toFixed(2)} to update): ${refusal}`); } h.log(`stage 3: update on ${input.model} (about $${estimate.toFixed(2)}${Number.isFinite(input.maxUsd) ? `, cap $${input.maxUsd.toFixed(2)}` : ""})`); // 3a. a sweep restricted to the new and changed recordings. let findings: string | null = null; if (ids.length) { const sweepIn = { article: h.article, n: h.n, question: basis.question ?? basis.queries.map((q) => q.query).join(", "), channels, ...(basis.scope.from ? { from: basis.scope.from } : {}), ...(basis.scope.to ? { to: basis.scope.to } : {}), model: input.model, origin: opened.origin, ids, terms: basis.queries.map((q) => q.query), }; const isApi = providerOf(input.model) === "api"; const capped = Number.isFinite(input.maxUsd) ? input.maxUsd * 0.7 : Number.POSITIVE_INFINITY; const out = isApi ? await sweepAgentBody(h, { ...sweepIn, extractorModel: input.extractorModel, maxUsd: capped }) : await sweepPipelineBody(h, { ...sweepIn, ...(Number.isFinite(capped) ? { maxUsd: capped } : {}), ...(input.localSweep ? { claimForm: input.localSweep.claimForm, readAloud: input.localSweep.readAloud } : {}), }); if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; const md = out.status === "done" ? await readIterationFile(h.article, h.n, "sweep.md", h.paths) : null; findings = md ? findingsOf(md) : null; const n = findings ? (findings.match(/^\s*-\s/gm) ?? []).length : 0; file.update.sweep = { ids, status: out.status, summary: out.summary, findings: n }; h.log(`the sweep of ${ids.length} recording(s): ${out.status} — ${out.summary}`); if (!n) findings = null; await save(); } if (!findings && !delta.drifted.length && !delta.deleted.length) { const said = `${line} — ${ids.length} recording(s) read; nothing in them for the question`; return partialWhy && !flagged ? finish("partial", `${partialWhy}; ${said}`) : finish("no-change", said); } // 3b. the revision of the parent's report. const feedback = refreshFeedback({ parent, since: basis.at, delta, findings }); const rev = await reviseReportBody(h, { article: h.article, n: h.n, model: input.model, feedback, origin: opened.origin, maxUsd: Number.isFinite(input.maxUsd) ? input.maxUsd : Number.POSITIVE_INFINITY, channels }); file.update.revision = { status: rev.status, summary: rev.summary }; if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; if (rev.status !== "done") { const r = await finish("failed", `${line} — the revision failed: ${rev.summary}`, "failed"); return { ...r, patch: { ...(rev.patch ?? {}), ...(r.patch ?? {}) } }; } const r = await finish("updated", `${line} — updated: ${rev.summary}`); return { ...r, patch: { ...(rev.patch ?? {}), ...(r.patch ?? {}) } }; }