Archilyzer · Source

archilyzer

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

commit 1356cf8fb16e7ab72344b099c8ec5fa61a4722c4
parent 051ab2fd9e1a71de05c8c4784ad8f214e49439b7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 11:41:54 -0400

common: report-draft refresh (fetch, what changed, update), the sweep's ids restriction, R2's word check in common

A refresh iteration (kind refresh, refresh.json) runs as one report-draft
job on draft:refresh: stage 1 fetches the parent's scope through the
editor's own sync / refresh-report / transcribe-bucket / fetch-posts
(a held or cooling platform skipped) and builds its site locally;
stage 2 re-runs the parent's recorded enumerations and re-reads every
cited quote; stage 3 sweeps only the new and changed recordings and
revises the parent's report, within the caps (held-by-cap otherwise).
The editor route takes task refresh (dryRun answers the plan).

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

Diffstat:
Mcommon/controller/reportDraft.ts | 68+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Acommon/controller/reportRefresh.ts | 488+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/queueKeys.ts | 4++++
Acommon/lib/report/draft/refresh/basis.ts | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/refresh/delta.ts | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/refresh/fetch.ts | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/refresh/index.ts | 14++++++++++++++
Acommon/lib/report/draft/refresh/refresh.test.ts | 398+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/refresh/task.ts | 322+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/refresh/types.ts | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 6++++++
Acommon/lib/report/draft/tasks/restrict.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/revise-report.ts | 4+++-
Mcommon/lib/report/draft/tasks/sweep-agent.ts | 48+++++++++++++++++++++++++++++++++---------------
Mcommon/lib/report/draft/tasks/sweep-pipeline.ts | 23++++++++++++++++++++++-
Mcommon/lib/report/draft/tasks/trace.test.ts | 13++++++++++++-
Mcommon/lib/report/draft/tasks/trace.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/report/draft/tasks/types.ts | 6+++++-
Mcommon/lib/report/iterations.ts | 23++++++++++++++++++-----
Acommon/lib/report/quoteWords.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/draft/corpus.d.mts | 4+++-
Mcommon/testing/draft/corpus.mjs | 21++++++++++++++++++---
Meditor/app/api/ops/_researchEditor.ts | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Meditor/app/api/ops/report-draft/route.ts | 36+++++++++++++++++++++++++++++-------
Amcp/src/refreshTask.test.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/research/boards.ts | 45+++++++++++++++------------------------------
26 files changed, 2859 insertions(+), 102 deletions(-)

diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -31,6 +31,14 @@ // autonomy a research run's: propose | limits | auto (default: // settings.generation.research.autonomy; the limits are the // settings') +// ids a sweep restricted to these recordings (umtool R4; kept in its +// scope): an enumeration shows only them, a read of another is +// refused +// +// task "refresh" (umtool R4, ./reportRefresh.ts): re-fetch, see what changed, +// update — `iteration` (default: the current report's), `model`, +// `extractorModel`, `maxUsd`; `fetch: false` skips the fetch and the build; +// `dryRun: true` answers the plan and writes nothing. // // The iteration is created `queued` before the job, and the job's id set on it; // the job runs the S5 task in process. Its queue is the model's provider's: @@ -103,6 +111,9 @@ export const REPORT_DRAFT_BODY_KEYS = [ "force", "autonomy", "seed", + "ids", + "fetch", + "dryRun", ] as const; // A seed's size: a board of a few hundred quotes, with room. @@ -110,8 +121,13 @@ export const SEED_MAX_CHARS = 200_000; export class ReportDraftInputError extends Error {} +// A refresh (umtool R4) is a report-draft task with no route of its own: its +// update runs on the sweep route's model. +export const REFRESH_TASK = "refresh" as const; +export type ReportDraftTask = GenerationTask | typeof REFRESH_TASK; + export type ReportDraftBody = { - task: GenerationTask; + task: ReportDraftTask; article: string; iteration?: number; model?: string; @@ -130,6 +146,9 @@ export type ReportDraftBody = { force?: boolean; autonomy?: Autonomy; seed?: string; + ids?: string[]; + fetch?: boolean; + dryRun?: boolean; }; // A Claude model the price table knows: one of its ids, or a dated id of one @@ -138,7 +157,7 @@ export function isKnownApiModel(model: string): boolean { return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`)); } -const TASKS: readonly GenerationTask[] = GENERATION_TASKS; +const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS, REFRESH_TASK]; const ymd = /^\d{4}-\d{2}-\d{2}$/; function fail(msg: string): never { @@ -148,7 +167,7 @@ function fail(msg: string): never { // The body, judged without touching the disk. export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBody { const task = b.task; - if (typeof task !== "string" || !TASKS.includes(task as GenerationTask)) fail(`"task" is one of ${TASKS.join(", ")}`); + if (typeof task !== "string" || !TASKS.includes(task as ReportDraftTask)) fail(`"task" is one of ${TASKS.join(", ")}`); const article = b.article; if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)'); const int = (k: string) => { @@ -170,7 +189,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string" && x.trim())) fail(`"${k}" is a list of names`); return (arr as string[]).map((x) => x.trim()); }; - const out: ReportDraftBody = { task: task as GenerationTask, article: article as string }; + const out: ReportDraftBody = { task: task as ReportDraftTask, article: article as string }; const set = <K extends keyof ReportDraftBody>(k: K, v: ReportDraftBody[K] | undefined) => { if (v !== undefined) out[k] = v; }; @@ -182,7 +201,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod if (!isKnownApiModel(extractor)) { fail(`"extractorModel" is a Claude model id (${Object.keys(PRICES).filter((m) => m.startsWith("claude-")).join(", ")}): an API sweep's extractor runs on the API`); } - if (task !== "sweep") fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)'); + if (task !== "sweep" && task !== REFRESH_TASK) fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)'); out.extractorModel = extractor; } set("feedback", text("feedback")); @@ -216,6 +235,23 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod if (out.task !== "sweep" || out.iteration !== undefined || out.copyOf !== undefined) fail('"seed" starts a new sweep: no "iteration", no "copyOf"'); out.seed = b.seed; } + for (const k of ["fetch", "dryRun"] as const) { + if (b[k] === undefined || b[k] === null) continue; + if (typeof b[k] !== "boolean") fail(`"${k}" is true or false`); + if (out.task !== REFRESH_TASK) fail(`"${k}" is a refresh's`); + out[k] = b[k] as boolean; + } + const ids = list("ids"); + if (ids !== undefined) { + if (out.task !== "sweep") fail('"ids" is a sweep\'s: the recordings it is restricted to'); + if (!ids.length) fail('"ids" names at least one recording'); + if (ids.length > 2000) fail('"ids" is at most 2,000 recordings'); + out.ids = [...new Set(ids)]; + } + if (out.task === REFRESH_TASK) { + const extra = (["question", "channels", "from", "to", "feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy"] as const).filter((k) => out[k] !== undefined); + if (extra.length) fail(`a refresh takes its question and scope from the iteration it refreshes — not ${extra.join(", ")}`); + } if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:<dir>, remote:<url> or hub:<url>'); if (out.source && out.build) fail('give "source" or "build", not both'); // What each task needs. @@ -288,6 +324,12 @@ export function llmConfigOf(gen: GenerationSettings, paths: Pick<Paths, "ollamaU export type ReportDraftDeps = { paths: Paths; + // A refresh's editor (umtool R4): its ops actions in process — sync, + // fetch-posts, refresh-report, transcribe-bucket, publish (the editor's + // route passes itself). Without it a refresh is refused. + refreshEditor?: ResearchEditor; + // A refresh's polling and waits (the tests shorten them). + refreshTiming?: { pollMs?: number; waitMs?: number; sleep?: (ms: number, signal?: AbortSignal) => Promise<void> }; // The MCP's corpus tools over a source handle (mcp/src/callTool.ts). corpusTools: (source: string) => Promise<CorpusToolsLike & { close(): Promise<void> }>; settings?: () => { generation: GenerationSettings }; @@ -343,6 +385,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep return { result: { ok: false, error: (e as Error).message } }; } const refuse = (error: string) => ({ result: { ok: false as const, error } }); + if (body.task === REFRESH_TASK) { + if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)'); + try { + const { enqueueRefresh } = await import("./reportRefresh"); + return await enqueueRefresh(body, deps); + } catch (e) { + return refuse((e as Error).message); + } + } try { // The model, and from it the lane; the copy's source tells a copy's kind. const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null; @@ -409,7 +460,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep model, parent: cont.research.n, question: cont.question, - scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}) }, + scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) }, }, paths, ) @@ -422,7 +473,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep kind: kindOf(body.task), model, ...(body.task === "sweep" || body.task === "research" - ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } } + ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}) } } : { parent: body.iteration!, feedback: body.feedback }), }, paths, @@ -534,6 +585,9 @@ async function runReportDraft( const extractor = body.extractorModel ?? gen.models.extractor; let input: TaskInput; switch (body.task) { + case "refresh": + // A refresh is its own job (./reportRefresh.ts), never this one. + throw new Error("a refresh runs as its own job"); case "sweep": input = provider === "api" diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts @@ -0,0 +1,488 @@ +// `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 { access } 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 { 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 { readCitedRecord } from "../publish/composeReports"; +import { diskPostChannelOf } from "../lib/report/convert-server"; +import { readAllPosts } from "../lib/posts-server"; +import { + createIteration, + currentIteration, + 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 { 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, + 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<number> { + 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<ReportDraftBody, "model" | "maxUsd" | "extractorModel">): { 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:<exportBuildsDir>/<id>/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<ReportDraftDeps["paths"], "exportBuildsDir">): Promise<CorpusBuild | null> { + 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<RefreshPlan> { + 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<string, unknown>])); + 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 = typeof c.platform === "string" ? c.platform : null; + 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.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, + }; +} + +const isPostsChannel = (c: Record<string, unknown>) => c.sourceKind === "posts" || (typeof c.postFetcher === "string" && !!c.postFetcher); + +// 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<string | null> { + 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<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> { + 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: (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) ─── + +/** 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<string, unknown>])); + return { + editor: deps.refreshEditor, + jobOf: deps.jobOf ?? jobOfPaths(paths), + channelOf: async (slug) => { + const c = (await configs()).get(slug); + if (!c) return null; + return { kind: isPostsChannel(c) ? "posts" : "video", ...(typeof c.platform === "string" ? { platform: c.platform } : {}) }; + }, + platformRefusal: (platform) => platformRefusalOf(platform, paths), + bucketOf: async (slug) => { + const snap = await readChannelSnapshot(paths, slug).catch(() => null); + return snap ? [...(snap.buckets.downloadedNoTranscript ?? [])] : null; + }, + 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<FetchAndBuild> { + 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<void> }) | null = null; + get source() { + return this.current?.source ?? ""; + } + get tools() { + return this.current?.tools ?? []; + } + call(name: string, args?: Record<string, unknown>): Promise<string> { + 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<void> }) { + 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<void> { + 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<string, Promise<Map<string, string>>>(); + 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) => { + const b = body.source ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths); + const source = body.source ?? (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) : fallback; + return { source, origin, ...(b ? { build: b.build } : {}) }; + }, + recordOf: async (channel, id) => { + const rec = await readCitedRecord(disk, channel, id).catch(() => null); + if (!rec) { + const cues = await cuesOf(channel, id); + return cues ? { cues } : null; + } + const dir = await resolveVideoDir(disk, channel, id).catch(() => null); + const avail = dir ? await resolveEffectiveAvailability(dir).catch(() => null) : null; + const state = stateFromAvailability(avail); + return { cues: rec.cues, tracks: rec.tracks, ...(state !== "available" ? { state } : {}) }; + }, + 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<ReturnType<typeof refreshTask>> | null = null; + try { + result = await refreshTask( + { article: body.article, n, model, extractorModel: o.extractor, maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY, ...(body.fetch === false ? { fetch: false } : {}) }, + 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 refresh iteration's refresh.json, or null. */ +export async function readRefreshFile(article: string, n: number, paths: ReportDraftDeps["paths"]): Promise<RefreshFile | null> { + 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); +} diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts @@ -24,6 +24,10 @@ export const DIGEST_REMOTE_QUEUE = "digest:remote"; // that must not wait behind it. Each runs one job at a time. export const DRAFT_LOCAL_QUEUE = "draft:local"; export const DRAFT_API_QUEUE = "draft:api"; +// A refresh (umtool R4) waits on the editor's own fetches and a site build — +// hours, sometimes — before any model runs: its own lane, so it never holds +// `draft:api` or `draft:local` while it waits. One refresh at a time. +export const DRAFT_REFRESH_QUEUE = "draft:refresh"; // The backfill lane (controller/operationBatch.ts). Its own key for exactly the // reason the two digest keys have theirs: registry.ts submits every non-empty diff --git a/common/lib/report/draft/refresh/basis.ts b/common/lib/report/draft/refresh/basis.ts @@ -0,0 +1,240 @@ +// WHAT AN ITERATION WAS BUILT FROM (umtool R4): the enumerations to run again, +// the scope, the recordings it matched, and the quotes its report cites — +// read from the iteration and, for a revision, from the sweep it descends +// from. In order of preference: +// +// refresh.json a refresh's own record: its basis's queries, and the match +// set it saw (which includes what it found new) +// trace.jsonl a sweep's trace (R3): each `enumerate` (query, ids, counts) +// under the `scope` +// turns.jsonl a run before the trace: the agent's enumerate_matches calls +// (their arguments; their answers' rows when an import kept +// them) or the pipeline's `enumerate` terms +// the question nothing recorded: the question as the one query (said so) +// +// The report's own cited recordings are always in the known set. +// +// SERVER-ONLY (the iterations store). + +import { lineage, readIteration, readIterationFile, reportSourceOf, type Iteration } from "../../iterations"; +import { enumerateOf } from "../tasks/trace"; +import type { StorePaths } from "../tasks/types"; +import { REFRESH_FORMAT, type BasisFrom, type CitedQuote, type RefreshBasis, type RefreshFile, type RefreshQuery } from "./types"; + +type Json = Record<string, unknown>; + +const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined); +const strs = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && !!x.trim()) : typeof v === "string" && v.trim() ? [v.trim()] : []); + +function jsonLines(text: string | null): Json[] { + if (!text) return []; + const out: Json[] = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + const v = JSON.parse(line) as unknown; + if (v && typeof v === "object" && !Array.isArray(v)) out.push(v as Json); + } catch { + // a torn line is skipped + } + } + return out; +} + +/** One query's identity: the same enumeration twice is run once. */ +export const queryKey = (q: RefreshQuery) => JSON.stringify([q.query, !!q.regex, [...(q.channels ?? [])].sort(), q.from ?? "", q.to ?? ""]); + +// What one iteration's records say (null: nothing recorded there). +type Found = { from: BasisFrom; queries: RefreshQuery[]; perQuery: Map<string, Record<string, number | null>>; scope?: RefreshBasis["scope"]; source: string | null; known?: Record<string, number | null> }; + +function addRows(perQuery: Found["perQuery"], key: string, rows: Record<string, number | null>) { + const had = perQuery.get(key); + // The same query run twice: the later answer stands (it is what was read). + perQuery.set(key, had ? { ...had, ...rows } : rows); +} + +/** A refresh.json, as a basis. */ +export function fromRefreshFile(f: RefreshFile): Found { + const known: Record<string, number | null> = { ...(f.basis.known ?? {}) }; + for (const [id, c] of Object.entries(f.delta?.matchedSet ?? {})) known[id] = c; + return { from: "refresh", queries: f.basis.queries, perQuery: new Map(), scope: f.basis.scope, source: f.corpus?.source ?? f.basis.source ?? null, known }; +} + +/** A trace.jsonl's text, as a basis (null: it holds no enumeration). Its LAST run is the one read. */ +export function fromTrace(text: string | null): Found | null { + const events = jsonLines(text); + if (!events.length) return null; + const last = Math.max(...events.map((e) => (typeof e.run === "number" ? e.run : 1))); + const mine = events.filter((e) => (typeof e.run === "number" ? e.run : 1) === last); + const scope = mine.find((e) => e.t === "scope"); + const enums = mine.filter((e) => e.t === "enumerate" && str(e.query)); + if (!enums.length) return null; + const sc: RefreshBasis["scope"] = { + channels: strs(scope?.channels), + ...(str(scope?.from) ? { from: str(scope?.from)! } : {}), + ...(str(scope?.to) ? { to: str(scope?.to)! } : {}), + }; + const queries: RefreshQuery[] = []; + const perQuery: Found["perQuery"] = new Map(); + for (const e of enums) { + const q: RefreshQuery = { query: str(e.query)! }; + const key = queryKey(q); + if (!perQuery.has(key)) queries.push(q); + const ids = strs(e.ids); + const counts = (e.counts && typeof e.counts === "object" ? e.counts : {}) as Record<string, unknown>; + addRows(perQuery, key, Object.fromEntries(ids.map((id) => [id, typeof counts[id] === "number" ? (counts[id] as number) : null]))); + } + return { from: "trace", queries, perQuery, scope: sc, source: str(scope?.source) ?? null }; +} + +/** A turns.jsonl's text, as a basis (null: it holds no enumeration). */ +export function fromTurns(text: string | null): Found | null { + const entries = jsonLines(text); + const queries: RefreshQuery[] = []; + const perQuery: Found["perQuery"] = new Map(); + const add = (q: RefreshQuery, rows: Record<string, number | null>) => { + const key = queryKey(q); + if (!perQuery.has(key)) { + queries.push(q); + perQuery.set(key, {}); + } + addRows(perQuery, key, rows); + }; + for (const e of entries) { + if (e.kind === "tool" && e.name === "enumerate_matches") { + const i = (e.input ?? {}) as Json; + const query = str(i.query); + if (!query) continue; + const channels = strs(i.channels ?? i.channel); + const q: RefreshQuery = { + query, + ...(i.regex === true ? { regex: true } : {}), + ...(channels.length ? { channels } : {}), + ...(str(i.date_from) ? { from: str(i.date_from)! } : {}), + ...(str(i.date_to) ? { to: str(i.date_to)! } : {}), + }; + const result = str(e.result); + const rows: Record<string, number | null> = {}; + if (result) for (const r of enumerateOf(result).rows) rows[r.id] = r.matches; + add(q, rows); + } else if (e.kind === "enumerate" && str(e.term)) { + add({ query: str(e.term)! }, {}); + } + } + return queries.length ? { from: "turns", queries, perQuery, source: null } : null; +} + +// Every recording matched, summed over the distinct queries; a recording a +// query matched without its count reads null. +export function knownOf(perQuery: Found["perQuery"]): Record<string, number | null> { + const out: Record<string, number | null> = {}; + for (const rows of perQuery.values()) { + for (const [id, c] of Object.entries(rows)) { + if (!(id in out)) out[id] = c; + else out[id] = out[id] === null || c === null ? null : out[id]! + c; + } + } + return out; +} + +/** The quoted citations of a report. */ +export function citedQuotes(report: unknown): CitedQuote[] { + const cites = ((report ?? {}) as { citations?: Record<string, Json> }).citations ?? {}; + const out: CitedQuote[] = []; + for (const [citation, c] of Object.entries(cites)) { + const kind = c.kind; + if (kind !== "video" && kind !== "audio" && kind !== "post") continue; + const channel = str(c.channel); + const id = str(c.id); + const quote = str(c.quote); + if (!channel || !id || !quote) continue; + out.push({ + citation, + kind, + channel, + id, + ...(typeof c.start === "number" ? { start: c.start } : {}), + ...(typeof c.end === "number" ? { end: c.end } : {}), + quote, + }); + } + return out; +} + +async function foundAt(article: string, n: number, it: Iteration, paths: StorePaths | undefined): Promise<Found | null> { + if (it.kind === "refresh") { + const text = await readIterationFile(article, n, "refresh.json", paths); + if (text) { + try { + const f = JSON.parse(text) as RefreshFile; + if (f?.format === REFRESH_FORMAT && Array.isArray(f.basis?.queries)) return fromRefreshFile(f); + } catch { + // not a refresh record: read on + } + } + } + return fromTrace(await readIterationFile(article, n, "trace.jsonl", paths)) ?? fromTurns(await readIterationFile(article, n, "turns.jsonl", paths)); +} + +export class NothingToRefreshError extends Error {} + +/** + * The basis of iteration `n` of `article`: its own records, else those of the + * nearest ancestor that has them (a revision's sweep), else its question. + */ +export async function refreshBasis(article: string, n: number, paths?: StorePaths): Promise<RefreshBasis> { + const it = await readIteration(article, n, paths); + if (!it) throw new NothingToRefreshError(`"${article}" has no iteration i${n}`); + const from = await reportSourceOf(article, n, paths).catch(() => null); + const reportText = from === null ? null : await readIterationFile(article, from, "report.json", paths); + if (!reportText) throw new NothingToRefreshError(`"${article}" i${n} carries no report to refresh`); + const cited = citedQuotes(JSON.parse(reportText) as unknown); + + // The records: this iteration's, else up its lineage. + const line = await lineage(article, n, paths).catch(() => [n]); + let found: Found | null = null; + let queriesOf = n; + let base: Iteration = it; + for (let i = line.length - 1; i >= 0 && !found; i--) { + const at = i === line.length - 1 ? it : await readIteration(article, line[i]!, paths); + if (!at) continue; + found = await foundAt(article, line[i]!, at, paths); + if (found) { + queriesOf = line[i]!; + base = at; + } + } + // The question and scope: the iteration's, else the one the records are of. + const question = it.question ?? base.question ?? null; + const scopeIt = it.scope?.channels?.length ? it.scope : base.scope; + const citedChannels = [...new Set(cited.map((c) => c.channel))]; + const channels = [...new Set([...(found?.scope?.channels ?? []), ...(scopeIt?.channels ?? []), ...citedChannels])]; + const from_ = found?.scope?.from ?? scopeIt?.from; + const to = found?.scope?.to ?? scopeIt?.to; + const scope: RefreshBasis["scope"] = { channels, ...(from_ ? { from: from_ } : {}), ...(to ? { to } : {}) }; + + let queries = found?.queries ?? []; + let fromKind: BasisFrom = found?.from ?? "question"; + if (!queries.length) { + if (!question) throw new NothingToRefreshError(`"${article}" i${n} records no enumeration and names no question: nothing to search again`); + queries = [{ query: question }]; + fromKind = "question"; + } + const known: Record<string, number | null> = found?.known ? { ...found.known } : found ? knownOf(found.perQuery) : {}; + const knownComplete = !!found && (found.from === "refresh" || found.from === "trace" || [...found.perQuery.values()].some((rows) => Object.keys(rows).length > 0)); + for (const c of cited) if (c.kind !== "post" && !(c.id in known)) known[c.id] = null; + return { + article, + n, + queriesOf, + question, + scope, + queries, + from: fromKind, + known, + knownComplete, + cited, + source: found?.source ?? null, + at: it.endedAt ?? it.updatedAt, + }; +} diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts @@ -0,0 +1,240 @@ +// WHAT CHANGED (umtool R4, stage 2 — deterministic, no model): the basis's +// enumerations run again over the corpus as it is now, and every quote the +// report cites read again at its cite. +// +// candidates deltaCandidates(basis-like, corpus, {known?, since?}): +// the match set now, the recordings new against `known` +// (or, without one, uploaded on or after `since`), the ones +// whose matching lines changed, the ones no longer matched. +// Callable on its own with a scope and a "since" point — +// umtool's daily suggestion and R6's tier 0 are exactly it. +// quotes recheckQuotes(cited, readers): R2's word check +// (lib/report/quoteWords.ts) at each cite, on every track the +// record has; a source gone from the archive or from its +// platform; en vs en-orig. +// computeDelta both, as one RefreshDelta. +// +// 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 type { CorpusToolsLike } from "../tasks/types"; +import { queryKey } from "./basis"; +import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types"; + +export type CandidateScope = { channels: string[]; from?: string; to?: string }; + +export type Candidates = { + // The match set now: each recording with its matching lines, summed over the queries. + matchedSet: Record<string, number | null>; + rows: Map<string, MatchedRow>; + newIds: string[]; + changed: string[]; + unmatched: string[]; + partial: boolean; + unreached: string[]; + // Each query's own answer (its matched count), for the log. + perQuery: { query: string; n: number; partial: boolean; error?: string }[]; +}; + +/** 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; + const from = q.from ?? scope.from; + const to = q.to ?? scope.to; + return { + query: q.query, + ...(channels.length ? { channels } : {}), + ...(from ? { date_from: from } : {}), + ...(to ? { date_to: to } : {}), + ...(q.regex ? { regex: true } : {}), + }; +} + +// An upload date as YYYY-MM-DD ("20260105", "2026-01-05", …), or null. +const ymdOf = (d: string | null | undefined): string | null => { + const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "").trim()); + return m ? `${m[1]}-${m[2]}-${m[3]}` : null; +}; + +/** + * The candidates: every query run once over `scope`; new = matched now and + * not in `known` (and, when `since` is given, uploaded on or after it — with + * no `known`, `since` alone decides); changed = in both, their counts known + * and different; unmatched = known, not matched now (only said of a complete + * scan). + */ +export async function deltaCandidates( + basis: { queries: readonly RefreshQuery[]; scope: CandidateScope }, + corpus: Pick<CorpusToolsLike, "call">, + o: { known?: Record<string, number | null>; since?: string | null; signal?: AbortSignal } = {}, +): Promise<Candidates> { + const seen = new Set<string>(); + const perId = new Map<string, number | null>(); + const rows = new Map<string, MatchedRow>(); + const perQuery: Candidates["perQuery"] = []; + let partial = false; + const unreached = new Set<string>(); + for (const q of basis.queries) { + o.signal?.throwIfAborted(); + const key = queryKey(q); + if (seen.has(key)) continue; + seen.add(key); + let text: string; + try { + text = await corpus.call("enumerate_matches", enumerateArgs(q, basis.scope)); + } catch (e) { + // 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 }); + 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 }); + for (const r of e.rows) { + if (r.kind === "post") continue; + const had = perId.get(r.id); + perId.set(r.id, had === undefined ? r.matches : had === null || r.matches === null ? null : had + r.matches); + if (!rows.has(r.id)) rows.set(r.id, { id: r.id, channel: r.channel, date: ymdOf(r.date), title: r.title, matches: null }); + } + } + const matchedSet = Object.fromEntries(perId); + for (const [id, row] of rows) row.matches = perId.get(id) ?? null; + const known = o.known; + const since = o.since ? ymdOf(o.since) : null; + const isNew = (id: string) => { + if (known && id in known) return false; + if (since) { + const d = rows.get(id)?.date; + return !!d && d >= since; + } + return !!known; + }; + const newIds = [...perId.keys()].filter(isNew); + const changed = known + ? [...perId.keys()].filter((id) => { + if (!(id in known)) return false; + const was = known[id]; + const now = perId.get(id); + return was !== null && was !== undefined && now !== null && now !== undefined && was !== now; + }) + : []; + const unmatched = known && !partial ? Object.keys(known).filter((id) => !perId.has(id)) : []; + return { matchedSet, rows, newIds, changed, unmatched, partial, unreached: [...unreached].sort(), perQuery }; +} + +// ─── the quotes ─── + +// A recording as a refresh reads it: its cues (the primary track) and every +// track it has (named: `transcript.en.vtt`, `transcript.en-orig.vtt`, +// `transcript.json` …), and its platform state when it is not available. +export type RecordRead = { cues: readonly WordCue[]; tracks?: { name: string; cues: readonly WordCue[] }[]; state?: string | null }; + +export type QuoteReaders = { + // The recording (the disk, the build); null: not in the archive. + recordOf: (channel: string, id: string) => Promise<RecordRead | null>; + // A post's text; null: not in the archive. Absent: posts are not read. + postTextOf?: (channel: string, id: string) => Promise<string | null>; +}; + +// The states a recording is "gone" in, for the delta's `deleted`. +const GONE_STATES = new Set(["deleted", "private"]); + +const isEn = (name: string) => /(^|[./])en\.vtt$/.test(name) || /\.en\.vtt$/.test(name); +const isEnOrig = (name: string) => /en-orig/.test(name); + +/** Every quoted citation, read again at its cite. */ +export async function recheckQuotes(cited: readonly CitedQuote[], readers: QuoteReaders, o: { span?: number; signal?: AbortSignal } = {}): Promise<QuoteRecheck[]> { + const span = o.span ?? 30; + const out: QuoteRecheck[] = []; + const records = new Map<string, Promise<RecordRead | null>>(); + for (const c of cited) { + o.signal?.throwIfAborted(); + const base = { citation: c.citation, kind: c.kind, channel: c.channel, id: c.id, ...(c.start !== undefined ? { start: c.start } : {}), quote: c.quote }; + try { + if (c.kind === "post") { + if (!readers.postTextOf) { + out.push({ ...base, status: "unreadable", message: "posts are not read here" }); + continue; + } + const text = await readers.postTextOf(c.channel, c.id); + if (text === null) out.push({ ...base, status: "missing", message: `no post ${c.id} in ${c.channel} now` }); + else out.push(holdsWords(text, c.quote) ? { ...base, status: "ok" } : { ...base, status: "drifted", now: text.slice(0, 3000) }); + continue; + } + const key = `${c.channel}/${c.id}`; + let p = records.get(key); + if (!p) { + p = readers.recordOf(c.channel, c.id); + records.set(key, p); + } + const rec = await p; + if (!rec || (!rec.cues.length && !(rec.tracks ?? []).some((t) => t.cues.length))) { + out.push({ ...base, status: "missing", message: rec ? `${key} has no transcript now` : `${key} is not in the archive now` }); + continue; + } + const state = rec.state && GONE_STATES.has(rec.state) ? rec.state : undefined; + const t = c.start ?? 0; + const cite = { t, end: c.end ?? t }; + // The primary first, then every other track: the words on any of them stand. + const tracks = [rec.cues, ...(rec.tracks ?? []).map((x) => x.cues)].filter((x) => x.length); + let verdict = checkWordsInWindow(c.quote, cite, windowAround(tracks[0]!, t, span)); + for (let i = 1; i < tracks.length && verdict.status !== "ok"; i++) { + const v = checkWordsInWindow(c.quote, cite, windowAround(tracks[i]!, t, span)); + if (v.status === "ok") verdict = v; + } + const en = (rec.tracks ?? []).find((x) => isEn(x.name) && !isEnOrig(x.name)); + const orig = (rec.tracks ?? []).find((x) => isEnOrig(x.name)); + const enOrig = en && orig ? enOrigDifference(en.cues, orig.cues, cite) : null; + const extra = { ...(state ? { state } : {}), ...(enOrig ? { enOrig } : {}) }; + if (verdict.status === "ok") { + out.push(verdict.nowAt !== undefined ? { ...base, status: "moved", nowAt: verdict.nowAt, ...extra } : { ...base, status: "ok", ...extra }); + } else { + out.push({ ...base, status: "drifted", now: verdict.now, ...(verdict.nowAt !== undefined ? { nowAt: verdict.nowAt } : {}), ...(verdict.empty ? { message: `no cues within ${span} s of the cite now` } : {}), ...extra }); + } + } catch (e) { + if (o.signal?.aborted) throw e; + out.push({ ...base, status: "unreadable", message: (e as Error).message }); + } + } + return out; +} + +/** Stage 2: the candidates and the quotes, as one delta. */ +export async function computeDelta( + basis: RefreshBasis, + corpus: Pick<CorpusToolsLike, "call">, + readers: QuoteReaders, + o: { now?: Date; signal?: AbortSignal } = {}, +): Promise<RefreshDelta> { + const cand = await deltaCandidates(basis, corpus, { + known: basis.knownComplete ? basis.known : undefined, + since: basis.knownComplete ? null : basis.at, + ...(o.signal ? { signal: o.signal } : {}), + }); + // Without the whole old set, "new" is by upload date; the cited are never new. + const newIds = cand.newIds.filter((id) => !(id in basis.known)); + const quotes = await recheckQuotes(basis.cited, readers, o.signal ? { signal: o.signal } : {}); + const drifted = quotes.filter((q) => q.status === "drifted").map((q) => q.citation); + const deleted = [...new Set(quotes.filter((q) => q.status === "missing" || q.state).map((q) => `${q.channel}/${q.id}`))]; + const enOrig = quotes.filter((q) => q.enOrig).map((q) => q.citation); + const status = newIds.length || cand.changed.length || drifted.length || deleted.length ? "changed" : "no-change"; + return { + at: (o.now ?? new Date()).toISOString(), + status, + matched: Object.keys(cand.matchedSet).length, + newIds, + new: newIds.map((id) => cand.rows.get(id)!).filter(Boolean), + changed: cand.changed, + unmatched: cand.unmatched, + drifted, + deleted, + enOrig, + quotes, + partial: cand.partial, + unreached: cand.unreached, + matchedSet: cand.matchedSet, + }; +} diff --git a/common/lib/report/draft/refresh/fetch.ts b/common/lib/report/draft/refresh/fetch.ts @@ -0,0 +1,244 @@ +// A REFRESH'S STAGE 1 — fetch what is new, then build (umtool R4), on its own: +// a refresh runs it first (./task.ts), and R5's recurring reports run it on a +// tick before a series' edition. No model, nothing written but what the +// editor's own actions write. +// +// per channel a video channel: `sync`, then `refresh-report` (its report, +// so the bucket is current) and `transcribe-bucket` for the +// recordings that LANDED (the bucket against the one before — +// never the channel's whole backlog); a posts channel: +// `fetch-posts`. A platform held or cooling down is skipped, +// and says so (polite scraping). Channels run side by side; +// the editor's platform queues pace them. +// the build the site whose build holds the channels, `publish build` +// (never forced: a fresh build is not rebuilt; through the +// publish lock; never a deploy), waited for. +// +// Every action's job is waited for (polled; a step still going after +// `waitMs` is left running and said). Each step is logged and traced. + +import type { JobOf } from "../research/state"; +import type { ResearchEditor } from "../research/tools"; +import type { TraceInput, TraceStepStatus } from "../tasks/trace"; +import type { QuoteReaders } from "./delta"; +import type { BuildStep, FetchStep } from "./types"; + +// What a refresh asks of the editor (the controller passes the editor's own, +// in process — controller/reportRefresh.ts refreshHooksOf; the tests stub them). +export type RefreshHooks = { + // One ops action (the research run's door: the same refusals, same words). + editor: ResearchEditor; + jobOf: JobOf; + // A channel of this editor: what it is and on which platform; null: none. + channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string } | null>; + // Why a fetch on this platform would be refused now (held, cooling down), or null. + platformRefusal?: (platform: string) => Promise<string | null>; + // A channel's "downloaded, not transcribed" recordings (its report's bucket), or null. + bucketOf?: (slug: string) => Promise<string[] | null>; + // The site to build so a build holds the channels (the parent's corpus + // first); null with why when there is none to build. + siteOf: (channels: string[], prefer: string | null) => Promise<{ site: string | null; reason?: string }>; + // When the build that holds the channels was made (ms), to say whether it moved. + builtAt?: (channels: string[], prefer: string | null) => Promise<number | null>; + // Open the corpus the delta and the update read (deps.corpus becomes it). + openCorpus: (channels: string[], prefer: string | null) => Promise<{ source: string; origin: string; build?: string }>; + // A recording on disk (every track, its platform state), else the build's cues. + recordOf?: QuoteReaders["recordOf"]; + // Why an update of about `usd` would be refused by a cap now, or null. + capRefusal: (usd: number) => Promise<string | null>; + // Polling (default 5 s) and how long one step is waited for (default 6 h). + pollMs?: number; + waitMs?: number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; +}; + +// Stage 1 needs only the editor's side. +export type FetchHooks = Pick<RefreshHooks, "editor" | "jobOf" | "channelOf" | "platformRefusal" | "bucketOf" | "siteOf" | "builtAt" | "pollMs" | "waitMs" | "sleep">; + +export type FetchAndBuild = { fetch: FetchStep[]; build: BuildStep | null; warnings: string[] }; + +const sleeper = (ms: number, signal?: AbortSignal) => + new Promise<void>((resolve, reject) => { + if (signal?.aborted) return reject(signal.reason ?? new Error("cancelled")); + const t = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + reject(signal?.reason ?? new Error("cancelled")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); + +const ENDED = new Set(["done", "failed", "cancelled", "archived"]); + +/** Stage 1 over `scope.channels`: each channel's fetches, then the build (see the head of this file). */ +export async function fetchAndBuild( + scope: { channels: readonly string[] }, + hooks: FetchHooks, + o: { + // The corpus the work was read from (its build is preferred). + prefer?: string | null; + signal?: AbortSignal; + log?: (line: string) => void; + trace?: (e: TraceInput) => void; + // After the fetches, before the build (a refresh keeps them on disk). + onFetched?: (steps: FetchStep[]) => void | Promise<void>; + // false: fetch, no build. + build?: boolean; + } = {}, +): Promise<FetchAndBuild> { + const channels = [...scope.channels]; + const prefer = o.prefer ?? null; + const log = (l: string) => o.log?.(l); + const trace = (e: TraceInput) => o.trace?.(e); + const sleep = hooks.sleep ?? sleeper; + const poll = hooks.pollMs ?? 5000; + const waitMs = hooks.waitMs ?? 6 * 3600_000; + const warnings: string[] = []; + + // Every job ended (or the wait's limit): each job's status, "waiting" for one still going. + const waitJobs = async (ids: string[]): Promise<Record<string, string>> => { + const out: Record<string, string> = {}; + const t0 = Date.now(); + for (;;) { + o.signal?.throwIfAborted(); + let pending = 0; + for (const id of ids) { + if (out[id] && out[id] !== "waiting") continue; + const j = await hooks.jobOf(id).catch(() => null); + if (!j) out[id] = "unknown"; + else if (ENDED.has(j.status)) out[id] = j.status; + else { + out[id] = "waiting"; + pending++; + } + } + if (!pending || Date.now() - t0 >= waitMs) return out; + await sleep(poll, o.signal); + } + }; + + // One action, then its job waited for. + const runAndWait = async (channel: string, action: string, args: Record<string, unknown>): Promise<FetchStep> => { + let answer: Record<string, unknown>; + try { + answer = await hooks.editor.run(action, args); + } catch (e) { + const step: FetchStep = { channel, action, status: "refused", reason: (e as Error).message }; + trace({ t: "fetch", ...step }); + log(`${channel}: ${action} refused — ${step.reason}`); + return step; + } + const jobId = typeof answer.jobId === "string" ? answer.jobId : undefined; + const ids = Array.isArray(args.ids) ? (args.ids as string[]) : undefined; + if (!jobId) { + const step: FetchStep = { channel, action, status: "done", reason: "nothing queued" }; + trace({ t: "fetch", ...step }); + return step; + } + trace({ t: "fetch", channel, action, status: "queued", jobId, ...(ids ? { ids } : {}) }); + log(`${channel}: ${action} queued (job ${jobId})`); + const st = (await waitJobs([jobId]))[jobId] ?? "unknown"; + const status: TraceStepStatus = st === "done" ? "done" : st === "cancelled" ? "cancelled" : st === "waiting" ? "waiting" : "failed"; + const step: FetchStep = { + channel, + action, + status, + jobId, + ...(ids ? { ids } : {}), + ...(status === "done" ? {} : { reason: st === "waiting" ? `still running after ${Math.round(waitMs / 60_000)} min: read what is there` : `the job ended ${st}` }), + }; + trace({ t: "fetch", ...step }); + log(`${channel}: ${action} ${status}${step.reason ? ` (${step.reason})` : ""}`); + return step; + }; + + const skip = (channel: string, action: string, reason: string): FetchStep => { + const step: FetchStep = { channel, action, status: "skipped", reason }; + trace({ t: "fetch", ...step }); + log(`${channel}: ${action} skipped — ${reason}`); + return step; + }; + + const fetchChannel = async (slug: string): Promise<FetchStep[]> => { + const ch = await hooks.channelOf(slug).catch(() => null); + if (!ch) return [skip(slug, "sync", "not a channel of this editor")]; + const first = ch.kind === "posts" ? "fetch-posts" : "sync"; + if (ch.platform && hooks.platformRefusal) { + const no = await hooks.platformRefusal(ch.platform).catch(() => null); + if (no) return [skip(slug, first, no)]; + } + if (ch.kind === "posts") return [await runAndWait(slug, "fetch-posts", { slug })]; + const steps: FetchStep[] = []; + const before = hooks.bucketOf ? await hooks.bucketOf(slug).catch(() => null) : null; + const sync = await runAndWait(slug, "sync", { slug }); + steps.push(sync); + if (sync.status !== "done" || !hooks.bucketOf) return steps; + // What landed: the channel's report again, its bucket against the one before. + steps.push(await runAndWait(slug, "refresh-report", { slug })); + const after = await hooks.bucketOf(slug).catch(() => null); + if (before === null || after === null) { + steps.push(skip(slug, "transcribe-bucket", before === null ? "no channel report before the sync: what landed is not known" : "the channel's report does not read")); + return steps; + } + const had = new Set(before); + const landed = after.filter((id) => !had.has(id)); + if (!landed.length) { + steps.push(skip(slug, "transcribe-bucket", "nothing new to transcribe")); + return steps; + } + steps.push(await runAndWait(slug, "transcribe-bucket", { slug, ids: landed })); + return steps; + }; + + const fetch = (await Promise.all(channels.map((c) => fetchChannel(c)))).flat(); + for (const s of fetch) if (s.status === "failed" || s.status === "waiting") warnings.push(`${s.channel}: ${s.action} ${s.status}${s.reason ? ` — ${s.reason}` : ""}`); + await o.onFetched?.(fetch); + if (o.build === false) return { fetch, build: null, warnings }; + + // The build: the site whose build holds the channels, built if stale. + const target = await hooks.siteOf(channels, prefer).catch((e: Error) => ({ site: null, reason: e.message })); + let build: BuildStep; + if (!target.site) { + build = { site: null, status: "skipped", reason: target.reason ?? "no site's build holds these channels" }; + } else { + const was = hooks.builtAt ? await hooks.builtAt(channels, prefer).catch(() => null) : null; + let answer: Record<string, unknown> | null = null; + build = { site: target.site, status: "refused" }; + try { + answer = await hooks.editor.run("publish", { verb: "build", siteId: target.site, force: false }); + } catch (e) { + build = { site: target.site, status: "refused", reason: (e as Error).message }; + } + if (answer) { + const jobs = Array.isArray(answer.jobs) ? (answer.jobs as { jobId?: unknown }[]).map((j) => j.jobId).filter((x): x is string => typeof x === "string") : []; + if (!jobs.length) { + const skipped = Array.isArray(answer.skipped) ? (answer.skipped as { reason?: unknown }[]).map((s) => String(s.reason ?? "")).filter(Boolean) : []; + build = { site: target.site, status: "skipped", reason: skipped[0] ?? "nothing to build" }; + } else { + trace({ t: "build", site: target.site, status: "queued", jobIds: jobs }); + log(`build ${target.site}: queued (${jobs.join(", ")})`); + const st = await waitJobs(jobs); + const bad = jobs.filter((j) => st[j] !== "done"); + const worst = bad.length ? st[bad[0]!]! : "done"; + build = bad.length + ? { + site: target.site, + status: worst === "waiting" ? "waiting" : worst === "cancelled" ? "cancelled" : "failed", + jobIds: jobs, + reason: `job ${bad[0]} ${worst === "waiting" ? "still running" : `ended ${worst}`}: the corpus is read as it stands`, + } + : { site: target.site, status: "done", jobIds: jobs }; + } + } + const is = hooks.builtAt ? await hooks.builtAt(channels, prefer).catch(() => null) : null; + if (is) build.builtAt = new Date(is).toISOString(); + if (build.status === "done" && was !== null && is !== null && is <= was) build.reason = "the build was current: nothing to rebuild"; + } + trace({ t: "build", ...build }); + log(`build: ${build.site ?? "none"} ${build.status}${build.reason ? ` — ${build.reason}` : ""}`); + if (build.status !== "done" && build.status !== "skipped") warnings.push(`the build ${build.site ?? ""} ${build.status}: ${build.reason ?? ""}`.trim()); + return { fetch, build, warnings }; +} diff --git a/common/lib/report/draft/refresh/index.ts b/common/lib/report/draft/refresh/index.ts @@ -0,0 +1,14 @@ +// 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 { fetchAndBuild, type FetchAndBuild, type FetchHooks, type RefreshHooks } from "./fetch"; +export { + DEFAULT_REVISION_USD, + DEFAULT_USD_PER_RECORDING, + estimateUpdateUsd, + findingsOf, + refresh, + refreshFeedback, + type RefreshInput, +} from "./task"; diff --git a/common/lib/report/draft/refresh/refresh.test.ts b/common/lib/report/draft/refresh/refresh.test.ts @@ -0,0 +1,398 @@ +// A refresh (umtool R4): the basis read from an iteration's records, the +// candidates against a stubbed corpus, the quotes read again, and the task's +// stages over stubbed editor actions — no change ($0), a cap's hold, and the +// fetch steps (a held platform skipped, a posts channel, what landed sent to +// transcription, the build waited for). The update over the MCP's own corpus +// tools and the fake Anthropic is mcp/src/refreshTask.test.ts. Temp stores +// only. + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { createIteration, iterationFile, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { checkWordsInWindow, enOrigDifference, holdsWords, windowAround, wordsOf } from "../../quoteWords"; +import { restrictEnumerateText, restrictTools } from "../tasks/restrict"; +import type { AgentTool } from "../agentTool"; +import type { CorpusToolsLike, TaskDeps } from "../tasks/types"; +import { fromTrace, fromTurns, knownOf, refreshBasis } from "./basis"; +import { deltaCandidates, recheckQuotes, type RecordRead } from "./delta"; +import { estimateUpdateUsd, refresh, refreshFeedback, type RefreshHooks } from "./task"; +import { deltaLine, type RefreshFile } from "./types"; + +const tmp = await mkdtemp(path.join(os.tmpdir(), "refresh-")); +after(() => rm(tmp, { recursive: true, force: true })); +let k = 0; +const store = () => { + k++; + return { articlesDir: path.join(tmp, `reports-${k}`), exportIndexDir: path.join(tmp, `idx-${k}`) }; +}; + +// ─── a corpus, stubbed: enumerate_matches and get_transcript as the MCP answers them ─── + +type Rec = { channel: string; name: string; id: string; date: string; title: string; lines: string[] }; + +const BASE: Rec[] = [ + { channel: "synth-kitchen", name: "Synth Kitchen", id: "pie-02", date: "20260210", title: "Pie stream", lines: ["a lot of you asked about the contest", "I did not enter the contest this year", "the judges were friends of mine"] }, + { channel: "synth-kitchen", name: "Synth Kitchen", id: "bread-01", date: "20260105", title: "Bread day", lines: ["welcome back", "the contest rumor again", "I paid for the new mixer myself"] }, + { channel: "synth-kitchen", name: "Synth Kitchen", id: "qa-03", date: "20260301", title: "Q and A", lines: ["no mention here", "only flour and water"] }, +]; + +function fakeCorpus(recs: Rec[]): CorpusToolsLike & { calls: { name: string; args: Record<string, unknown> }[] } { + const calls: { name: string; args: Record<string, unknown> }[] = []; + return { + source: "local:/fake/build/out", + tools: [], + calls, + async call(name, args = {}) { + calls.push({ name, args }); + if (name === "enumerate_matches") { + const q = String(args.query).toLowerCase(); + const chans = Array.isArray(args.channels) ? (args.channels as string[]) : null; + const rows = recs + .filter((r) => !chans || chans.includes(r.channel)) + .map((r) => ({ r, n: r.lines.filter((l) => l.toLowerCase().includes(q)).length })) + .filter((x) => x.n > 0); + if (!rows.length) return `No matches for "${args.query}".\n\n(complete set: yes; 0 match(es))`; + const date = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`; + return ( + `${rows.length} match(es) for "${args.query}" — the complete worklist:\n\n` + + rows.map(({ r, n }) => `- ${r.id} | video | ${r.name} | ${date(r.date)} | ${n} match(es) | ${r.title}`).join("\n") + + `\n\n(complete set: yes; ${rows.length} match(es); 1 batch(es) of 8)` + ); + } + throw new Error(`the stub has no ${name}`); + }, + }; +} + +const cuesOfRec = (r: Rec) => r.lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text })); +const recordReader = (recs: Rec[], extra: Partial<Record<string, Partial<RecordRead>>> = {}) => async (channel: string, id: string): Promise<RecordRead | null> => { + const r = recs.find((x) => x.channel === channel && x.id === id); + if (!r) return null; + return { cues: cuesOfRec(r), ...(extra[id] ?? {}) }; +}; + +// ─── a done sweep with its trace and report ─── + +const REPORT = { + format: "archilyzer-report", + version: 1, + id: "synth", + kind: "sweep", + title: "The contest", + summary: "What she says.", + citations: { + c1: { kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" }, + c2: { kind: "video", channel: "synth-kitchen", id: "bread-01", start: 10, end: 14.8, quote: "I paid for the new mixer myself" }, + c3: { kind: "post", channel: "synth-social", id: "1700", quote: "No, I did not enter the pie contest." }, + }, + sections: [{ id: "s1", title: "The contest", body: "She [did not enter](cite:c1). [Mixer](cite:c2). [Post](cite:c3)." }], +}; + +const TRACE = [ + { t: "run", at: "2026-10-01T10:00:00.000Z", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }, + { t: "scope", at: "2026-10-01T10:00:01.000Z", run: 1, source: "local:/fake/build/out", channels: ["synth-kitchen", "synth-other"], question: "What does she say about the contest?", model: "claude-sonnet-5-5" }, + { t: "enumerate", at: "2026-10-01T10:00:02.000Z", run: 1, query: "contest", n: 2, ids: ["pie-02", "bread-01"], partial: false, unreached: [], counts: { "pie-02": 2, "bread-01": 1 } }, + { t: "run", at: "2026-10-01T10:05:00.000Z", run: 1, phase: "end", status: "done", summary: "ok", usd: 0.8, minutes: 5, coverage: { matched: 2, read: 2, partial: false, unreached: [] } }, +]; + +async function doneSweep(paths: ReturnType<typeof store>, article = "synth") { + await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does she say about the contest?", scope: { channels: ["synth-kitchen", "synth-other"] } }, paths); + await writeIterationFile(article, 1, "report.json", REPORT, paths); + await writeIterationFile(article, 1, "trace.jsonl", TRACE.map((e) => JSON.stringify(e)).join("\n") + "\n", paths); + await updateIteration(article, 1, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.8, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 2, read: 2, partial: false, unreached: [] } }, paths); +} + +// ─── the words ─── + +test("quoteWords: R2's check — words, the window, ok / moved / drifted, en vs en-orig", () => { + assert.equal(wordsOf("I’d NEVER, ever!"), "i'd never ever"); + assert.ok(holdsWords("so I did not enter the contest this year, ok", "I did not enter the contest")); + assert.ok(!holdsWords("I did not enter", "I did not enter the contest")); + const cues = [ + { start: 0, end: 4, text: "a lot of you asked" }, + { start: 5, end: 9, text: "I did not enter" }, + { start: 10, end: 14, text: "the contest this year" }, + ]; + assert.deepEqual(checkWordsInWindow("I did not enter the contest", { t: 5, end: 14 }, windowAround(cues, 5)), { status: "ok" }); + assert.deepEqual(checkWordsInWindow("I did not enter the contest", { t: 0, end: 9 }, windowAround(cues, 0)), { status: "ok", nowAt: 5 }); + const drift = checkWordsInWindow("I never entered", { t: 5, end: 9 }, windowAround(cues, 5)); + assert.equal(drift.status, "drifted"); + assert.equal(drift.status === "drifted" && drift.now, "I did not enter"); + assert.deepEqual(checkWordsInWindow("x", { t: 500, end: 501 }, windowAround(cues, 500)), { status: "drifted", now: "", empty: true }); + assert.equal(enOrigDifference(cues, cues, { t: 5, end: 9 }), null); + assert.deepEqual(enOrigDifference(cues, [{ start: 5, end: 9, text: "I did enter" }], { t: 5, end: 9 }), { en: "I did not enter", orig: "I did enter" }); +}); + +// ─── the sweep's ids restriction ─── + +test("restrict: an enumeration answers only the given rows; reads outside are refused; search is not offered", async () => { + const text = '3 match(es) for "contest" — the complete worklist:\n\n- a | video | C | 2026-01-01 | 1 match(es) | A\n- b | video | C | 2026-01-02 | 2 match(es) | B\n- c | video | C | 2026-01-03 | 1 match(es) | C\n\n(complete set: yes)'; + const out = restrictEnumerateText(text, new Set(["b"])); + assert.ok(out.includes("- b | video")); + assert.ok(!out.includes("- a | video") && !out.includes("- c | video")); + assert.match(out, /restricted to 1 recording\(s\): 1 of the 3 row\(s\) above are kept/); + const seen: unknown[] = []; + const tool = (name: string): AgentTool => ({ name, description: name, inputSchema: { type: "object" }, run: async (i: unknown) => (seen.push(i), name === "enumerate_matches" ? text : "ok") }); + const tools = restrictTools([tool("enumerate_matches"), tool("search_transcripts"), tool("get_transcripts"), tool("get_transcript"), tool("list_channels")], ["b"]); + assert.deepEqual(tools.map((t) => t.name), ["enumerate_matches", "get_transcripts", "get_transcript", "list_channels"]); + const byName = Object.fromEntries(tools.map((t) => [t.name, t])); + assert.ok(!(await byName.enumerate_matches!.run({ query: "contest" }, {})).includes("- a |")); + assert.match(await byName.get_transcripts!.run({ video_ids: ["a", "b"] }, {}), /not read — outside this sweep's recordings: a/); + assert.deepEqual(seen.at(-1), { video_ids: ["b"] }); + await assert.rejects(byName.get_transcripts!.run({ video_ids: ["a"] }, {}), /restricted: a is not one of/); + await assert.rejects(byName.get_transcript!.run({ video_id: "c" }, {}), /restricted: c/); + assert.equal(await byName.get_transcript!.run({ video_id: "b" }, {}), "ok"); + assert.equal(restrictTools([tool("search_transcripts")], undefined).length, 1, "no ids: the tools as they are"); +}); + +// ─── the basis ─── + +test("basis: a trace's last run (its queries, counts and scope); turns' calls; known summed over queries", () => { + const two = [...TRACE, { t: "run", run: 2, phase: "start" }, { t: "scope", run: 2, channels: ["synth-other"], question: "q", source: "local:/b2" }, { t: "enumerate", run: 2, query: "oven", ids: ["x9"], counts: { x9: 3 } }]; + const f = fromTrace(two.map((e) => JSON.stringify(e)).join("\n") + "\n{torn"); + assert.equal(f?.from, "trace"); + assert.deepEqual(f?.queries, [{ query: "oven" }]); + assert.deepEqual(f?.scope?.channels, ["synth-other"]); + assert.equal(f?.source, "local:/b2"); + assert.deepEqual(knownOf(f!.perQuery), { x9: 3 }); + assert.equal(fromTrace('{"t":"run","phase":"start"}'), null, "no enumeration: nothing to read"); + + const turns = [ + { kind: "response", turn: 0, content: [] }, + { kind: "tool", name: "enumerate_matches", input: { query: "contest", channels: ["synth-kitchen"], date_from: "2026-01-01" }, result: "- pie-02 | video | Synth Kitchen | 2026-02-10 | 2 match(es) | Pie stream" }, + { kind: "tool", name: "enumerate_matches", input: { query: "mixer" } }, + { kind: "enumerate", term: "oven", videos: 3 }, + ]; + const t = fromTurns(turns.map((e) => JSON.stringify(e)).join("\n")); + assert.deepEqual(t?.queries, [{ query: "contest", channels: ["synth-kitchen"], from: "2026-01-01" }, { query: "mixer" }, { query: "oven" }]); + assert.deepEqual(knownOf(t!.perQuery), { "pie-02": 2 }); +}); + +test("refreshBasis: the iteration's trace, the report's quotes; a revision reads its sweep's; no records → the question", async () => { + const paths = store(); + await doneSweep(paths); + const b = await refreshBasis("synth", 1, paths); + assert.equal(b.from, "trace"); + assert.equal(b.queriesOf, 1); + assert.deepEqual(b.queries, [{ query: "contest" }]); + assert.deepEqual(b.scope.channels, ["synth-kitchen", "synth-other", "synth-social"], "the trace's scope, plus every channel cited"); + assert.deepEqual(b.known, { "pie-02": 2, "bread-01": 1 }); + assert.equal(b.knownComplete, true); + assert.deepEqual(b.cited.map((c) => c.citation), ["c1", "c2", "c3"]); + assert.equal(b.source, "local:/fake/build/out"); + + // A revision: its own report, its sweep's records. + await createIteration("synth", { kind: "revise-report", model: "claude-sonnet-5-5", parent: 1, feedback: "tighten" }, paths); + await writeIterationFile("synth", 2, "report.json", { ...REPORT, citations: { c1: REPORT.citations.c1 } }, paths); + await updateIteration("synth", 2, { status: "done" }, paths); + const r = await refreshBasis("synth", 2, paths); + assert.equal(r.queriesOf, 1); + assert.deepEqual(r.cited.map((c) => c.citation), ["c1"]); + assert.equal(r.question, "What does she say about the contest?"); + + // Nothing recorded: the question, and new only by upload date. + const p2 = store(); + await createIteration("bare", { kind: "sweep", model: "qwen3:8b", question: "contest", scope: { channels: ["synth-kitchen"] } }, p2); + await writeIterationFile("bare", 1, "report.json", { ...REPORT, id: "bare" }, p2); + await updateIteration("bare", 1, { status: "done" }, p2); + const q = await refreshBasis("bare", 1, p2); + assert.equal(q.from, "question"); + assert.deepEqual(q.queries, [{ query: "contest" }]); + assert.equal(q.knownComplete, false); + assert.deepEqual(Object.keys(q.known).sort(), ["bread-01", "pie-02"], "the cited are known"); +}); + +// ─── the candidates ─── + +test("deltaCandidates: new against known, changed by matching lines, unmatched; `since` without known (R6's tier 0)", async () => { + const recs = [ + ...BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: [...r.lines, "the contest came up twice"] } : r)), + { channel: "synth-kitchen", name: "Synth Kitchen", id: "late-04", date: "20250101", title: "An old one, transcribed late", lines: ["the contest was rigged"] }, + { channel: "synth-kitchen", name: "Synth Kitchen", id: "new-05", date: "20261012", title: "New stream", lines: ["the contest again"] }, + ]; + const corpus = fakeCorpus(recs); + const c = await deltaCandidates({ queries: [{ query: "contest" }, { query: "contest" }], scope: { channels: ["synth-kitchen"], from: "2020-01-01" } }, corpus, { known: { "pie-02": 2, "bread-01": 1, "gone-09": 1 } }); + assert.equal(corpus.calls.length, 1, "the same query twice runs once"); + assert.deepEqual(corpus.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"], date_from: "2020-01-01" }); + assert.deepEqual(c.newIds.sort(), ["late-04", "new-05"]); + assert.deepEqual(c.changed, ["bread-01"]); + assert.deepEqual(c.unmatched, ["gone-09"]); + assert.equal(c.rows.get("new-05")?.date, "2026-10-12"); + const since = await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, fakeCorpus(recs), { since: "2026-10-01T00:00:00Z" }); + assert.deepEqual(since.newIds, ["new-05"], "uploaded on or after the day"); +}); + +test("recheckQuotes: ok, moved, drifted, missing, gone from its platform, en-orig, a post", async () => { + const recs = BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: ["welcome back", "the contest rumor again", "I bought the mixer with sponsor money"] } : r)); + const cited = [ + { citation: "c1", kind: "video" as const, channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" }, + { citation: "c2", kind: "video" as const, channel: "synth-kitchen", id: "bread-01", start: 10, end: 14.8, quote: "I paid for the new mixer myself" }, + { citation: "c4", kind: "video" as const, channel: "synth-kitchen", id: "pie-02", start: 0, end: 4, quote: "the judges were friends of mine" }, + { citation: "c5", kind: "video" as const, channel: "synth-kitchen", id: "nope", start: 0, end: 1, quote: "x" }, + { citation: "c3", kind: "post" as const, channel: "synth-social", id: "1700", quote: "No, I did not enter the pie contest." }, + ]; + const out = await recheckQuotes(cited, { + recordOf: recordReader(recs, { "pie-02": { state: "deleted", tracks: [{ name: "transcript.en.vtt", cues: cuesOfRec(recs[0]!) }, { name: "transcript.en-orig.vtt", cues: [{ start: 5, end: 9.8, text: "I did enter the contest this year" }] }] } }), + postTextOf: async () => "No, I did not enter the pie contest. The judges are my friends.", + }); + const by = Object.fromEntries(out.map((q) => [q.citation, q])); + assert.equal(by.c1!.status, "ok"); + assert.equal(by.c1!.state, "deleted"); + assert.deepEqual(by.c1!.enOrig, { en: "I did not enter the contest this year", orig: "I did enter the contest this year" }); + assert.equal(by.c2!.status, "drifted"); + assert.equal(by.c2!.now, "I bought the mixer with sponsor money"); + assert.equal(by.c4!.status, "moved"); + assert.equal(by.c4!.nowAt, 10); + assert.equal(by.c5!.status, "missing"); + assert.equal(by.c3!.status, "ok"); +}); + +// ─── the task ─── + +type Call = { action: string; args: Record<string, unknown> }; + +function harness(o: { recs: Rec[]; refusal?: string | null; held?: string[] }) { + const calls: Call[] = []; + const polls = new Map<string, number>(); + let n = 0; + const holder = { source: "", tools: [] as AgentTool[], call: (_: string, __?: Record<string, unknown>) => Promise.reject(new Error("not open")) } as CorpusToolsLike; + const corpus = fakeCorpus(o.recs); + const buckets: Record<string, string[]> = { "synth-kitchen": ["old-1"] }; + const hooks: RefreshHooks = { + editor: { + async run(action, args) { + calls.push({ action, args }); + if (action === "sync") buckets["synth-kitchen"] = ["old-1", "landed-7"]; + if (action === "publish") return { ok: true, jobs: [{ target: "synth", kind: "build-site", jobId: `job-${++n}` }] }; + return { ok: true, jobId: `job-${++n}` }; + }, + }, + // A job runs for one poll, then is done. + jobOf: async (id) => { + const k = (polls.get(id) ?? 0) + 1; + polls.set(id, k); + return { status: k < 2 ? "running" : "done", endedAt: Date.now() }; + }, + channelOf: async (slug) => (slug === "synth-kitchen" ? { kind: "video", platform: "youtube" } : slug === "synth-social" ? { kind: "posts", platform: "x" } : slug === "synth-other" ? { kind: "video", platform: "rumble" } : null), + platformRefusal: async (p) => ((o.held ?? []).includes(p) ? `${p} is held` : null), + bucketOf: async (slug) => buckets[slug] ?? null, + siteOf: async () => ({ site: "synth" }), + openCorpus: async () => { + Object.assign(holder, { source: corpus.source, tools: corpus.tools, call: corpus.call.bind(corpus) }); + return { source: corpus.source, origin: "https://synth.example", build: "synth" }; + }, + recordOf: recordReader(o.recs), + capRefusal: async () => o.refusal ?? null, + pollMs: 1, + sleep: async () => {}, + }; + const lines: string[] = []; + const deps = (paths: ReturnType<typeof store>): TaskDeps => ({ + llm: { anthropic: { baseUrl: "http://127.0.0.1:9", env: {} }, ollama: { baseUrl: "http://127.0.0.1:9" } }, + corpus: holder, + cuesOf: async () => null, + postTextOf: async () => "No, I did not enter the pie contest.", + paths, + log: (l) => lines.push(l), + refresh: hooks, + }); + return { calls, deps, lines, corpus }; +} + +const readJson = async (file: string) => JSON.parse(await readFile(file, "utf8")); +const traceOf = async (paths: ReturnType<typeof store>, n: number) => + (await readFile(iterationFile(paths, "synth", n, "trace.jsonl"), "utf8")) + .trim() + .split("\n") + .map((l) => JSON.parse(l) as Record<string, unknown>); + +test("refresh, nothing changed: the fetches and the build waited for, the delta $0, the iteration done with no report", async () => { + const paths = store(); + await doneSweep(paths); + await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); + const h = harness({ recs: BASE, held: ["rumble"] }); + const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3 }, h.deps(paths)); + assert.equal(out.status, "done", h.lines.join("\n")); + assert.equal(out.usd, 0); + assert.match(out.summary, /^Nothing new since 2026-/); + // The actions, in order per channel: a sync, its report, what landed to transcription; the posts; the build. + // (The channels run side by side: the posts channel's one action lands between.) + assert.deepEqual( + h.calls.map((c) => c.action).filter((a) => a !== "fetch-posts"), + ["sync", "refresh-report", "transcribe-bucket", "publish"], + ); + assert.equal(h.calls.filter((c) => c.action === "fetch-posts").length, 1); + assert.deepEqual(h.calls.find((c) => c.action === "transcribe-bucket")!.args, { slug: "synth-kitchen", ids: ["landed-7"] }); + assert.deepEqual(h.calls.find((c) => c.action === "publish")!.args, { verb: "build", siteId: "synth", force: false }); + const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile; + assert.equal(f.status, "no-change"); + assert.equal(f.parent, 1); + assert.deepEqual(f.fetch.find((s) => s.channel === "synth-other"), { channel: "synth-other", action: "sync", status: "skipped", reason: "rumble is held" }); + assert.equal(f.build?.status, "done"); + assert.equal(f.delta?.status, "no-change"); + assert.deepEqual(f.delta?.matchedSet, { "pie-02": 2, "bread-01": 1 }); + assert.equal(f.update, undefined); + const it = await readIteration("synth", 2, paths); + assert.equal(it?.status, "done"); + assert.deepEqual((it as { refresh?: unknown }).refresh, { status: "no-change", newIds: 0, changed: 0, drifted: 0, deleted: 0, summary: f.summary }); + await assert.rejects(readFile(iterationFile(paths, "synth", 2, "report.json")), /ENOENT/); + const trace = await traceOf(paths, 2); + assert.deepEqual(trace.map((e) => e.t).filter((t) => t !== "note"), ["run", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "build", "build", "delta", "run"]); + assert.equal(trace.at(-1)!.status, "done"); +}); + +test("refresh, something new but the cap refuses: held-by-cap with the delta and the estimate, no model called", async () => { + const paths = store(); + await doneSweep(paths); + await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); + const recs = [ + ...BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: ["welcome back", "the contest rumor again", "I bought the mixer with sponsor money"] } : r)), + { channel: "synth-kitchen", name: "Synth Kitchen", id: "new-05", date: "20261012", title: "New stream", lines: ["about the contest", "it was rigged"] }, + ]; + const h = harness({ recs, refusal: "the day's Claude API spend is $20.00, at the daily cap" }); + const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, h.deps(paths)); + assert.equal(out.status, "done"); + assert.equal(out.usd, 0); + assert.deepEqual(h.calls, [], "fetch: false runs no editor action"); + const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile; + assert.equal(f.status, "held-by-cap"); + assert.deepEqual(f.delta?.newIds, ["new-05"]); + assert.deepEqual(f.delta?.drifted, ["c2"]); + assert.equal(f.update?.refusal, "the day's Claude API spend is $20.00, at the daily cap"); + // The parent spent $0.80 reading 2 recordings: one more is $0.40, and a revision. + assert.equal(f.update?.estimateUsd, 0.7); + assert.equal(f.summary, "1 new recording matches · 1 quote changed — held by the cap (about $0.70 to update): the day's Claude API spend is $20.00, at the daily cap"); + assert.equal(deltaLine(f.delta!), "1 new recording matches · 1 quote changed"); +}); + +test("the estimate and the revision's feedback", () => { + assert.equal(estimateUpdateUsd({ recordings: 4, model: "claude-sonnet-5-5" }), 0.62); + assert.equal(estimateUpdateUsd({ recordings: 4, model: "qwen3:8b" }), 0); + assert.equal(estimateUpdateUsd({ recordings: 0, model: "claude-sonnet-5-5" }), 0.3); + const fb = refreshFeedback({ + parent: 3, + since: "2026-10-01T10:05:00.000Z", + findings: "## New\n\n- She says it was rigged: \"it was rigged\" — [New stream @ 0:05](https://synth.example/?v=synth-kitchen%2Fnew-05&t=5)", + delta: { + quotes: [ + { citation: "c2", kind: "video", channel: "synth-kitchen", id: "bread-01", start: 10, status: "drifted", quote: "I paid for the new mixer myself", now: "I bought the mixer" }, + { citation: "c1", kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, status: "ok", quote: "q", state: "deleted" }, + ], + } as never, + }); + assert.match(fb, /^A REFRESH of i3 \(made 2026-10-01\)/); + assert.match(fb, /NEW FINDINGS[\s\S]*it was rigged/); + assert.match(fb, /QUOTES THAT CHANGED[\s\S]*"I paid for the new mixer myself" \(synth-kitchen\/bread-01 @ 0:10\) — now: "I bought the mixer"/); + assert.match(fb, /SOURCES GONE FROM THEIR PLATFORM[\s\S]*synth-kitchen\/pie-02 \(deleted\)/); +}); + +test("a refresh iteration names its parent; refresh.json is an iteration file", async () => { + const paths = store(); + await doneSweep(paths); + await assert.rejects(createIteration("synth", { kind: "refresh", model: "m" }, paths), /needs the iteration it refreshes/); + await createIteration("synth", { kind: "refresh", model: "m", parent: 1 }, paths); + await writeIterationFile("synth", 2, "refresh.json", { ok: 1 }, paths); +}); diff --git a/common/lib/report/draft/refresh/task.ts b/common/lib/report/draft/refresh/task.ts @@ -0,0 +1,322 @@ +// 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 { 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, + 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 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})`), + ].join("\n"), + ); + } + return parts.join("\n\n"); +} + +// ─── the job ─── + +export async function refresh(input: RefreshInput, deps: TaskDeps): Promise<TaskResult> { + 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<TaskOutcome> { + 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, + 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.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<RecordRead | null> => { + 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<TaskOutcome> => { + 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) } }; + }; + + if (delta.status === "no-change") return finish("no-change", line); + + // ─── stage 3: the update ─── + + const ids = [...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 } : {}) }); + 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) { + return finish("no-change", `${line} — ${ids.length} recording(s) read; nothing in them for the question`); + } + + // 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 ?? {}) } }; +} diff --git a/common/lib/report/draft/refresh/types.ts b/common/lib/report/draft/refresh/types.ts @@ -0,0 +1,251 @@ +// A REFRESH, as data (umtool R4, plans/umtool-redesign.md "R4 — Refresh"): +// what an iteration was built from (its BASIS), what is different now (the +// DELTA), and the record the refresh keeps — `refresh.json` beside the new +// iteration — which the next refresh reads as its basis, the umtool page shows, +// and R5's scheduler and R6's triage log read. Plain JSON, versioned. + +import type { TraceStepStatus } from "../tasks/trace"; + +export const REFRESH_FORMAT = "archilyzer-refresh" as const; +export const REFRESH_VERSION = 1 as const; + +// One enumeration to run again: the query and the arguments it was run with +// (absent: the basis scope's). +export type RefreshQuery = { query: string; regex?: boolean; channels?: string[]; from?: string; to?: string }; + +// A quoted citation of the report refreshed. +export type CitedQuote = { + citation: string; + kind: "video" | "audio" | "post"; + channel: string; + id: string; + start?: number; + end?: number; + quote: string; +}; + +// Where the queries came from: a refresh's own record, a sweep's trace, its +// turns.jsonl (a run before the trace), or — nothing recorded — the question. +export type BasisFrom = "refresh" | "trace" | "turns" | "question"; + +// What an iteration was built from. +export type RefreshBasis = { + article: string; + // The iteration refreshed, and the one whose enumerations the queries are + // (itself, or the sweep it descends from). + n: number; + queriesOf: number; + question: string | null; + scope: { channels: string[]; from?: string; to?: string }; + queries: RefreshQuery[]; + from: BasisFrom; + // Every recording matched then, with its matching lines when they were + // recorded (null: not recorded), summed over the queries. The report's own + // cited recordings are in it. + known: Record<string, number | null>; + // Whether `known` is the whole match set then. When it is not (a run whose + // answers were not kept, or the question alone), a recording counts as new + // only when it was uploaded on or after `at`'s day. + knownComplete: boolean; + cited: CitedQuote[]; + // The corpus it read (a handle), when recorded. + source: string | null; + // When it was made (its end). + at: string; +}; + +// One recording an enumeration matched now. +export type MatchedRow = { id: string; channel: string | null; date: string | null; title: string | null; matches: number | null }; + +// A quote against the transcript as it is now. +export type QuoteRecheckStatus = + | "ok" + // the words are there, starting a second or more from the cited one + | "moved" + // the words are not there now + | "drifted" + // the recording or post is not in the archive now + | "missing" + // it could not be read (a channel's text not readable, a corpus error) + | "unreadable"; + +export type QuoteRecheck = { + citation: string; + kind: CitedQuote["kind"]; + channel: string; + id: string; + start?: number; + status: QuoteRecheckStatus; + quote: string; + // drifted: the words over the quote's seconds now; moved: where they start now + now?: string; + nowAt?: number; + // The recording's platform state when it is gone from the platform (deleted, private). + state?: string; + // The en track and the en-orig track's words over the cite, when they differ. + enOrig?: { en: string; orig: string }; + message?: string; +}; + +export type DeltaStatus = "no-change" | "changed"; + +// Stage 2's answer. +export type RefreshDelta = { + at: string; + status: DeltaStatus; + // Distinct recordings matched now. + matched: number; + // Matched now and not before (old videos that only now have a transcript among them). + newIds: string[]; + new: MatchedRow[]; + // Matched before and now, their matching lines changed (a transcript replaced or re-cut). + changed: string[]; + // Matched before, not now (with a complete scan). + unmatched: string[]; + // Citations whose words are not at their cite now. + drifted: string[]; + // The cited sources (`<channel>/<id>`) that are gone: not in the archive, + // or deleted / private on their platform. + deleted: string[]; + // Citations whose en and en-orig tracks differ over the cite. + enOrig: string[]; + quotes: QuoteRecheck[]; + partial: boolean; + unreached: string[]; + // The full match set now, with matching lines: the next refresh's `known`. + matchedSet: Record<string, number | null>; +}; + +// One editor action of stage 1. +export type FetchStep = { + channel: string; + action: string; + status: TraceStepStatus; + jobId?: string; + reason?: string; + // transcribe-bucket: the recordings that landed. + ids?: string[]; +}; + +export type BuildStep = { site: string | null; status: TraceStepStatus; jobIds?: string[]; reason?: string; builtAt?: string }; + +export type RefreshStatus = "running" | "no-change" | "updated" | "held-by-cap" | "failed" | "cancelled"; + +export type RefreshUpdate = { + model: string; + estimateUsd: number; + capUsd: number | null; + // The cap's refusal, when it held the update. + refusal?: string; + // The restricted sweep over the new and changed recordings. + sweep?: { ids: string[]; status: string; summary: string; findings: number }; + // The revision of the parent's report. + revision?: { status: string; summary: string }; + usd?: number; +}; + +// refresh.json. +export type RefreshFile = { + format: typeof REFRESH_FORMAT; + version: typeof REFRESH_VERSION; + article: string; + n: number; + parent: number; + status: RefreshStatus; + // One line: "4 new recordings match · 2 quotes changed · 1 source deleted", + // or "Nothing new since <date>". + summary: string; + startedAt: string; + endedAt?: string; + basis: Omit<RefreshBasis, "known" | "cited"> & { knownCount: number; citedCount: number; known: Record<string, number | null> }; + fetch: FetchStep[]; + build: BuildStep | null; + corpus?: { source: string; build?: string; origin: string }; + delta?: RefreshDelta; + update?: RefreshUpdate; + warnings: string[]; +}; + +// What the job's last log line carries (`@@report-draft {…, refresh}`), and +// what iteration.json keeps as `refresh`. +export type RefreshOutcome = { + status: RefreshStatus; + newIds: number; + changed: number; + drifted: number; + deleted: number; + summary: string; +}; + +export function outcomeOf(f: Pick<RefreshFile, "status" | "summary" | "delta">): RefreshOutcome { + return { + status: f.status, + newIds: f.delta?.newIds.length ?? 0, + changed: f.delta?.changed.length ?? 0, + drifted: f.delta?.drifted.length ?? 0, + deleted: f.delta?.deleted.length ?? 0, + summary: f.summary, + }; +} + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + +/** The delta in one line, as the umtool page shows it. */ +export function deltaLine(d: Pick<RefreshDelta, "newIds" | "changed" | "drifted" | "deleted">, since?: string | null): string { + const parts = [ + d.newIds.length ? `${plural(d.newIds.length, "new recording")} ${d.newIds.length === 1 ? "matches" : "match"}` : null, + d.changed.length ? `${plural(d.changed.length, "recording")} changed` : null, + d.drifted.length ? `${plural(d.drifted.length, "quote")} changed` : null, + d.deleted.length ? `${plural(d.deleted.length, "source")} deleted` : null, + ].filter(Boolean); + return parts.length ? parts.join(" · ") : `Nothing new${since ? ` since ${since.slice(0, 10)}` : ""}`; +} + +// ─── the plan (what a Refresh would do; nothing written) ─── + +export type RefreshPlanChannel = { + slug: string; + // video | posts; null: not a channel of this editor (skipped) + kind: "video" | "posts" | null; + platform: string | null; + // The editor actions it would run, in order ("sync", "refresh-report", + // "transcribe-bucket (what lands)"; "fetch-posts"). + actions: string[]; + // Why it is skipped (held, cooling down, not a channel here). + skip?: string; + localOnly?: boolean; +}; + +export type RefreshPlan = { + article: string; + // The iteration refreshed. + parent: { + n: number; + kind: string; + model: string; + question: string | null; + at: string; + from: BasisFrom; + queries: string[]; + knownCount: number; + knownComplete: boolean; + citedCount: number; + }; + scope: { channels: string[]; from?: string; to?: string }; + fetch: boolean; + channels: RefreshPlanChannel[]; + // The site built (never deployed), or null with why. + build: { site: string | null; reason?: string; builtAt?: string | null }; + // The corpus the delta reads now. + corpus: { source: string | null; build?: string | null }; + model: string; + provider: "api" | "local"; + extractor: string | null; + // The update's cap (null: a local model), the day's spend against the daily cap. + capUsd: number | null; + daily: { usd: number; cap: number } | null; + // What an update costs per recording read (the parent's rate, else the default) and the revision. + estimate: { perRecordingUsd: number; revisionUsd: number; from: "parent" | "default" }; + refusals: string[]; + warnings: string[]; +}; diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -17,6 +17,7 @@ import { TaskInputError, runOnIteration } from "./run"; import { threads } from "./threads"; import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types"; import { youtube } from "./youtube"; +import { refresh, type RefreshInput } from "../refresh/task"; export * from "./types"; export { TaskInputError, runOnIteration, usageOf } from "./run"; @@ -60,6 +61,8 @@ export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, ty export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; export { checkQuotes, convertSweepText, dropFailedFindings, type QuoteProblem } from "./quotes"; export { projectDirOf } from "./project"; +// umtool R4: the sweep's `ids` restriction (a general sweep option). +export { restrictEnumerateText, restrictTools } from "./restrict"; // umtool R3: a sweep's trace (trace.jsonl). export { TRACE_FILE, enumerateOf, openTrace, runStartsOf, type TraceCite, type TraceEvent, type TraceInput } from "./trace"; @@ -70,6 +73,7 @@ export type TaskInput = | ({ task: "revise-video" } & ReviseVideoInput) | ({ task: "narrate" } & NarrateInput) | ({ task: "research" } & ResearchInput) + | ({ task: "refresh" } & RefreshInput) | ({ task: "cut" } & CutInput) | ({ task: "onscreen" } & OnscreenInput) | ({ task: "teaser" } & TeaserInput) @@ -89,6 +93,8 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { return narrate(input, deps); case "research": return research(input, deps); + case "refresh": + return refresh(input, deps); case "flips": return flips(input, deps); case "threads": diff --git a/common/lib/report/draft/tasks/restrict.ts b/common/lib/report/draft/tasks/restrict.ts @@ -0,0 +1,85 @@ +// A SWEEP RESTRICTED TO GIVEN RECORDINGS (umtool R4; a general sweep option — +// a refresh's new recordings, R6's escalation). The agent keeps its corpus +// tools, narrowed: +// +// enumerate_matches answers only the rows of the given ids (and says so) +// get_transcripts, the given ids only: the others are dropped from the +// extract_batch call (and the answer says which); none left refuses +// get_transcript, an id outside refuses +// get_post, get_thread +// search_transcripts not offered (its hits are the whole corpus's) +// +// Pure over the tools it is handed. + +import type { AgentTool } from "../agentTool"; + +const ROW = /^- (\S+) \| (?:video|post|audio) \| /; + +/** enumerate_matches' answer with only the rows of `only` kept, and a line saying so. */ +export function restrictEnumerateText(text: string, only: ReadonlySet<string>): string { + let kept = 0; + let dropped = 0; + const lines: string[] = []; + for (const raw of text.split("\n")) { + const m = ROW.exec(raw.trim()); + if (m) { + if (only.has(m[1]!)) { + kept++; + lines.push(raw); + } else dropped++; + continue; + } + lines.push(raw); + } + return `${lines.join("\n")}\n\n(this sweep is restricted to ${only.size} recording(s): ${kept} of the ${kept + dropped} row(s) above are kept)`; +} + +const idsOf = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []); + +/** A tool narrowed to `only` (see the head of this file); null: not offered. */ +export function restrictedTool(t: AgentTool, only: ReadonlySet<string>): AgentTool | null { + const outside = (id: string) => `restricted: ${id} is not one of this sweep's ${only.size} recording(s) (${[...only].slice(0, 20).join(", ")})`; + switch (t.name) { + case "search_transcripts": + return null; + case "enumerate_matches": + return { ...t, run: async (input: unknown, ctx) => restrictEnumerateText(await t.run(input, ctx), only) }; + case "get_transcripts": + case "extract_batch": + return { + ...t, + run: async (input: unknown, ctx) => { + const i = (input ?? {}) as Record<string, unknown>; + const ids = idsOf(i.video_ids); + const keep = ids.filter((id) => only.has(id)); + const drop = ids.filter((id) => !only.has(id)); + if (!keep.length) throw new Error(ids.length ? outside(ids[0]!) : `${t.name} needs video_ids`); + const out = await t.run({ ...i, video_ids: keep }, ctx); + return drop.length ? `${out}\n\n(not read — outside this sweep's recordings: ${drop.join(", ")})` : out; + }, + }; + case "get_transcript": + case "get_post": + case "get_thread": { + const key = t.name === "get_transcript" ? "video_id" : "post_id"; + return { + ...t, + run: async (input: unknown, ctx) => { + const i = (input ?? {}) as Record<string, unknown>; + const id = typeof i[key] === "string" ? (i[key] as string) : typeof i.thread_id === "string" ? (i.thread_id as string) : ""; + if (id && !only.has(id)) throw new Error(outside(id)); + return t.run(input, ctx); + }, + }; + } + default: + return t; + } +} + +/** Every tool narrowed to `only` (none given: the tools as they are). */ +export function restrictTools(tools: readonly AgentTool[], only: readonly string[] | undefined): AgentTool[] { + if (!only?.length) return [...tools]; + const set = new Set(only); + return tools.map((t) => restrictedTool(t, set)).filter((t): t is AgentTool => t !== null); +} diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts @@ -167,7 +167,9 @@ export async function reviseReport(input: ReviseReportInput, deps: TaskDeps): Pr ); } -async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promise<TaskOutcome> { +// The revision's body over a handle (exported: a refresh runs it on its own +// iteration with the feedback it composes — draft/refresh/task.ts). +export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promise<TaskOutcome> { const { deps, iteration } = h; const model = input.model ?? iteration.model; const feedback = (input.feedback ?? iteration.feedback ?? "").trim(); diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts @@ -35,8 +35,9 @@ import { plainAnswer, userCharsFor } from "./llmText"; import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; import { checkQuotes, convertSweepText, describeProblems, dropFailedFindings, titleOfSweep, type QuoteProblem } from "./quotes"; import { reportFile } from "./reportFile"; +import { restrictTools } from "./restrict"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; -import { CoverageTally, enumerateOf, idsReadBy, linesOf, traceReport, type TraceCite } from "./trace"; +import { CoverageTally, countsOf, enumerateOf, idsReadBy, linesOf, traceReport, type TraceCite } from "./trace"; import type { TaskDeps, TaskResult } from "./types"; // The corpus reads the agent may make (no fetch_clip, enqueue, notes or jobs: @@ -74,14 +75,21 @@ export type SweepAgentInput = { batchSize?: number; maxTurns?: number; terms?: string[]; + // Only these recordings (umtool R4: a refresh's new ones; R6's escalation): + // an enumeration shows only them, a read of any other is refused, and the + // free-text search is not offered. Default: the iteration's scope.ids. + ids?: string[]; // The web: Claude's server search (max uses) plus the deps' web_fetch; a // local model gets the deps' web tools. Default on. web?: boolean; webSearchMaxUses?: number; }; -function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from?: string; to?: string }): string { +function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from?: string; to?: string; ids?: string[] }): string { const terms = o.terms?.length ? ` The operator chose these terms: ${o.terms.join(", ")} — use them.` : ""; + const only = o.ids?.length + ? `\n- THIS SWEEP IS RESTRICTED to ${o.ids.length} recording(s): ${o.ids.join(", ")}. Read only these — enumerate_matches shows only them, and a read of any other is refused. Report what they say; nothing else is in scope.` + : ""; const dates = o.from || o.to ? `\n- The scope is dated${o.from ? ` from ${o.from}` : ""}${o.to ? ` to ${o.to}` : ""}: pass date_from / date_to on every enumerate and search.` @@ -94,7 +102,7 @@ function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from "- `extract_batch` IS the plan's extractor subagent: give it the batch's video ids, the sweep's queries and the directive; it returns the verbatim lines. You may call it for several batches in one turn.", "- `write_report` / `edit_report` / `read_report` are your Write/Edit tools, for the report file only.", "- You cannot fetch clips, enqueue jobs or write notes here: skip those steps (the clips for every citation are fetched after you finish).", - `- The plan's \`query\` is the request's own wording. Search with real terms instead — a few words or phrases the question is about (and their obvious variants), not the sentence.${terms}${dates}`, + `- The plan's \`query\` is the request's own wording. Search with real terms instead — a few words or phrases the question is about (and their obvious variants), not the sentence.${terms}${dates}${only}`, "- Your context is trimmed as you go: a tool result older than the last few is dropped once you have merged it. Merge each fragment into the report BEFORE asking for many more, and use read_report rather than memory.", "", "The report must convert as a sweep:", @@ -207,13 +215,16 @@ export async function sweepAgent(input: SweepAgentInput, deps: TaskDeps): Promis ); } -async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<TaskOutcome> { +// The sweep's body over a handle (exported: a refresh runs it on its own +// iteration, restricted to its new recordings — draft/refresh/task.ts). +export async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<TaskOutcome> { const { deps, iteration } = h; const question = (input.question ?? iteration.question ?? "").trim(); const channels = input.channels ?? iteration.scope?.channels ?? []; const model = input.model ?? iteration.model; const from = input.from ?? iteration.scope?.from; const to = input.to ?? iteration.scope?.to; + const only = input.ids ?? iteration.scope?.ids; if (!question) throw new TaskInputError("a sweep needs its question"); if (!channels.length) throw new TaskInputError("a sweep needs its channels"); const origin = input.origin.replace(/\/+$/, ""); @@ -241,23 +252,28 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta maxUsd: input.maxUsd, batchSize: batch, ...(seed ? { seed: { chars: seed.length } } : {}), + ...(only?.length ? { ids: only } : {}), }); - h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}`); + h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}${only?.length ? `, restricted to ${only.length} recording(s)` : ""}`); const request = `${question} channels=${channels.join(",")} batch_size=${batch} parse_model=${input.extractorModel} report=sweep.md`; const plan = await deps.corpus.call("sweep_plan", { request }); - const corpusTools = deps.corpus.tools - .filter((t) => (SWEEP_READ_TOOLS as readonly string[]).includes(t.name)) - .map((t) => - t.name === "get_transcripts" - ? { ...t, run: async (i: unknown, c: { signal?: AbortSignal }) => rewrite(await t.run(i, c)) } - : t, - ) - .map((t) => watched(h, t, watch)); + // A restricted sweep's tools are narrowed BEFORE they are watched: the trace + // records what the agent was answered. + const corpusTools = restrictTools( + deps.corpus.tools + .filter((t) => (SWEEP_READ_TOOLS as readonly string[]).includes(t.name)) + .map((t) => + t.name === "get_transcripts" + ? { ...t, run: async (i: unknown, c: { signal?: AbortSignal }) => rewrite(await t.run(i, c)) } + : t, + ), + only, + ).map((t) => watched(h, t, watch)); const web = input.web === false ? [] : (deps.web ?? []); - const tools = [...corpusTools, extractTool(h, input, rewrite, extracts, watch), ...file.tools, ...web]; + const tools = [...corpusTools, ...restrictTools([extractTool(h, input, rewrite, extracts, watch)], only), ...file.tools, ...web]; const isApi = providerOf(model) === "api"; const maxTurns = input.maxTurns ?? 150; // The job's progress: every model turn, the repair round's included. @@ -291,7 +307,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta const run = await runAgent({ llm: deps.llm, model, - system: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to }), + system: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to, ...(only?.length ? { ids: only } : {}) }), user: seed ? `${plan}\n\n${SEED_NOTE}` : plan, tools, meter: h.meter, @@ -430,6 +446,7 @@ function watched(h: TaskHandle, t: AgentTool, w: Watch): AgentTool { const e = enumerateOf(out); w.cov.enumerated(e.ids, e.partial, e.unreached); const q = (input as { query?: unknown } | null)?.query; + const counts = countsOf(e.rows); h.trace({ t: "enumerate", query: typeof q === "string" ? q : "", @@ -439,6 +456,7 @@ function watched(h: TaskHandle, t: AgentTool, w: Watch): AgentTool { unreached: e.unreached, ...(e.total !== null ? { total: e.total } : {}), ...(e.posts ? { posts: e.posts } : {}), + ...(counts ? { counts } : {}), turn, phase, }); diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -127,6 +127,10 @@ export type SweepPipelineInput = { terms?: string[]; maxVideos?: number; maxClaims?: number; + // Only these recordings (umtool R4; a general sweep option): the worklist is + // the enumeration's rows of these ids, and any of them the terms did not + // find is read too. Default: the iteration's scope.ids. + ids?: string[]; }; // ─── Pure helpers (exported for the tests) ─── @@ -290,6 +294,12 @@ async function ask<T>(h: TaskHandle, model: string, system: string, user: string return out; } +// The pipeline's body over a handle (exported: a refresh runs it on its own +// iteration, restricted to its new recordings — draft/refresh/task.ts). +export async function sweepPipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> { + return pipelineBody(h, input); +} + async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> { const { deps, iteration } = h; const question = (input.question ?? iteration.question ?? "").trim(); @@ -300,13 +310,14 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const origin = input.origin.replace(/\/+$/, ""); const maxVideos = input.maxVideos ?? 40; const maxClaims = input.maxClaims ?? 40; + const only = input.ids ?? iteration.scope?.ids; if (!question) throw new TaskInputError("a sweep needs its question"); if (!channels.length) throw new TaskInputError("a sweep needs its channels"); const event = (e: Record<string, unknown>) => h.turns([e]); h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}`); const cov = new CoverageTally(); h.setCoverage(() => cov.value()); - h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin }); + h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin, ...(only?.length ? { ids: only } : {}) }); // 1. terms (the model, unless given) let terms: string[] = []; @@ -352,6 +363,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T unreached: e.unreached, ...(e.total !== null ? { total: e.total } : {}), ...(e.posts ? { posts: e.posts } : {}), + counts: Object.fromEntries(vids.map((v) => [v.id, v.hits[term] ?? 0])), }); for (const v of vids) { const had = found.get(v.id); @@ -379,6 +391,15 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T terms = [...terms.filter((t) => hit.has(t)), ...extra.filter((w) => hitNow.has(w))].slice(0, 8); } } + if (only?.length) { + // A restricted sweep: only these recordings, each read even when the + // terms did not find it (its windows are what the terms match in it). + const set = new Set(only); + for (const id of [...found.keys()]) if (!set.has(id)) found.delete(id); + for (const id of only) if (!found.has(id)) found.set(id, { id, channel: channels.length === 1 ? channels[0]! : "", date: "", title: id, hits: {} }); + h.log(`restricted to ${only.length} recording(s)`); + h.trace({ t: "note", text: `restricted to ${only.length} recording(s): ${only.slice(0, 20).join(", ")}` }); + } const nEnum = found.size; const weight = new Map(terms.map((t, i) => [t, 1 / (i + 1)])); const order = [...found.values()].sort((a, b) => { diff --git a/common/lib/report/draft/tasks/trace.test.ts b/common/lib/report/draft/tasks/trace.test.ts @@ -17,6 +17,7 @@ import { TRACE_MAX_LINES, boundEvent, citeOfCitation, + countsOf, enumerateOf, idsReadBy, linesOf, @@ -58,7 +59,17 @@ test("enumerateOf: the rows' ids, partial, the channels never reached, the total assert.deepEqual(e.unreached, ["synth-other", "synth-third"]); assert.equal(e.total, 3); const whole = enumerateOf('1 match(es) for "x" — the complete worklist:\n\n- a1 | video | C | 2024-01-01 | 1 match(es) | T\n\n(complete set: yes; 1 match(es); …)'); - assert.deepEqual(whole, { ids: ["a1"], videos: 1, posts: 0, partial: false, unreached: [], total: 1 }); + assert.deepEqual(whole, { + ids: ["a1"], + videos: 1, + posts: 0, + partial: false, + unreached: [], + total: 1, + // umtool R4: each row as it reads (a refresh compares the matching lines). + rows: [{ id: "a1", kind: "video", channel: "C", date: "2024-01-01", matches: 1, title: "T" }], + }); + assert.deepEqual(countsOf(enumerateOf(PARTIAL).rows), { "pie-stream-02": 2, "bread-day-01": 1, "17": 1 }); assert.deepEqual(enumerateOf('No matches for "x".(complete set: yes; 0 match(es); 0 batch(es) of 10)').ids, []); }); diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts @@ -16,6 +16,15 @@ // {t: "note", text} // {t: "run", phase: "end", status, summary, usd, minutes, coverage?} // +// A REFRESH (umtool R4, draft/refresh) adds its stages' own: +// {t: "fetch", channel, action, status, jobId?, reason?, ids?} +// one editor action of stage 1 +// {t: "build", site, status, jobIds?, reason?} the local build it waited on +// {t: "delta", status, matched, newIds, changed, drifted, deleted, partial, +// unreached} stage 2's answer +// and an enumeration may carry `counts` (each id's matching lines), so the +// next refresh can tell a recording whose transcript changed. +// // Every line also carries `at` (ISO time) and `run` (1 for the file's first // run; a resumed job's run is 2, …). An agent's events carry `turn` and // `phase` ("agent" or "repair") so a step can be put on the turn that made it. @@ -72,15 +81,34 @@ export type TraceInput = maxUsd?: number; batchSize?: number; seed?: { chars: number }; + // A sweep restricted to these recordings (umtool R4). + ids?: string[]; } | { t: "terms"; terms: string[]; extra?: boolean } - | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; turn?: number; phase?: string; error?: string } + | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; counts?: Record<string, number>; turn?: number; phase?: string; error?: string } | { t: "read"; tool: string; ids: string[]; turn?: number; phase?: string } | { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number; cut?: boolean; turn?: number; phase?: string } | { t: "cost"; step: string; usd: number; model: string; total: number; turn?: number; phase?: string; calls?: string[]; text?: string } | { t: "check"; quote: string; cite: TraceCite; ok: boolean; reason?: string; stage: CheckStage; dropped?: boolean; claim?: string; round?: number } | { t: "finding"; section: string; claim: string; cites: TraceCite[] } - | { t: "note"; text: string; turn?: number; phase?: string }; + | { t: "note"; text: string; turn?: number; phase?: string } + // A refresh's stages (umtool R4). + | { t: "fetch"; channel: string; action: string; status: TraceStepStatus; jobId?: string; reason?: string; ids?: string[] } + | { t: "build"; site: string | null; status: TraceStepStatus; jobIds?: string[]; reason?: string } + | { + t: "delta"; + status: string; + matched: number; + newIds: string[]; + changed: string[]; + drifted: string[]; + deleted: string[]; + partial: boolean; + unreached: string[]; + }; + +// How one of a refresh's editor steps went. +export type TraceStepStatus = "queued" | "running" | "done" | "failed" | "cancelled" | "skipped" | "refused" | "waiting"; export type TraceEvent = TraceInput & { at: string; run: number }; @@ -101,6 +129,11 @@ const cut = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}… export function boundEvent(e: TraceInput): TraceInput { const o = { ...e } as Record<string, unknown>; if (Array.isArray(o.ids)) o.ids = (o.ids as string[]).slice(0, TRACE_MAX_IDS); + for (const k of ["newIds", "changed", "drifted", "deleted"]) if (Array.isArray(o[k])) o[k] = (o[k] as string[]).slice(0, TRACE_MAX_IDS); + if (o.counts && typeof o.counts === "object") { + const entries = Object.entries(o.counts as Record<string, number>); + if (entries.length > TRACE_MAX_IDS) o.counts = Object.fromEntries(entries.slice(0, TRACE_MAX_IDS)); + } if (Array.isArray(o.lines)) { const lines = (o.lines as string[]).map((l) => cut(l, TRACE_LINE_CHARS)); o.lines = lines.length > TRACE_MAX_LINES ? [...lines.slice(0, TRACE_MAX_LINES), `(+${lines.length - TRACE_MAX_LINES} more lines)`] : lines; @@ -175,19 +208,36 @@ export async function openTrace(o: { // ─── Reading what the corpus tools answered (pure; the tests use them) ─── const ENUM_ROW = /^- (\S+) \| (video|post|audio) \| /; +// The whole row: id | kind | channel | date | N match(es) | title[ | mirrors]. +const ENUM_FULL = /^- (\S+) \| (video|post|audio) \| (.*?) \| ([^|]*?) \| (\d+) match\(es\) \| (.*)$/; + +// One row of enumerate_matches' answer, as far as it reads. +export type EnumeratedRow = { id: string; kind: "video" | "post" | "audio"; channel: string | null; date: string | null; matches: number | null; title: string | null }; // enumerate_matches' answer: its rows' ids, whether the scan was capped, and -// the channels a capped scan never reached. -export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; total: number | null } { +// the channels a capped scan never reached; `rows` each row as it reads (its +// channel's name, date, matching lines and title). +export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; total: number | null; rows: EnumeratedRow[] } { const ids: string[] = []; + const rows: EnumeratedRow[] = []; let videos = 0; let posts = 0; for (const raw of text.split("\n")) { - const m = ENUM_ROW.exec(raw.trim()); + const line = raw.trim(); + const m = ENUM_ROW.exec(line); if (!m) continue; ids.push(m[1]!); if (m[2] === "post") posts++; else videos++; + const f = ENUM_FULL.exec(line); + rows.push({ + id: m[1]!, + kind: m[2] as EnumeratedRow["kind"], + channel: f ? f[3]!.trim() : null, + date: f ? f[4]!.trim() || null : null, + matches: f ? Number(f[5]) : null, + title: f ? f[6]!.replace(/ \| ⧉ .*$/, "").trim() : null, + }); } const partial = /COVERAGE PARTIAL/.test(text); const unreached: string[] = []; @@ -195,7 +245,20 @@ export function enumerateOf(text: string): { ids: string[]; videos: number; post // The list ends the sentence: its last name carries the full stop. if (nr) for (const c of nr[1]!.trim().replace(/\.$/, "").split(",")) if (c.trim()) unreached.push(c.trim()); const total = /^(\d+) match\(es\) for /m.exec(text) ?? /\(complete set: [^;]+; (\d+) match\(es\)/.exec(text); - return { ids, videos, posts, partial, unreached, total: total ? Number(total[1]) : null }; + return { ids, videos, posts, partial, unreached, total: total ? Number(total[1]) : null, rows }; +} + +// Each row's matching lines, by id (a row whose count does not read is left +// out); undefined when none reads. +export function countsOf(rows: readonly EnumeratedRow[]): Record<string, number> | undefined { + const out: Record<string, number> = {}; + let any = false; + for (const r of rows) { + if (r.matches === null) continue; + out[r.id] = r.matches; + any = true; + } + return any ? out : undefined; } // The ids a corpus read names (get_transcripts' video_ids, get_transcript's diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -15,6 +15,7 @@ import type { readIteration } from "../../iterations"; import type { Report } from "../../schema"; import type { ResearchEditor } from "../research/tools"; import type { DeckChecks } from "./deckChecks"; +import type { RefreshHooks } from "../refresh/fetch"; // The iterations store's paths (S4 takes them on every call). export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>; @@ -57,6 +58,9 @@ export type TaskDeps = { editor?: ResearchEditor; // The editor's channels (a research run imports into these first). editorChannels?: () => Promise<EditorChannel[]>; + // A refresh's editor (umtool R4): its fetches, build, corpus and caps + // (draft/refresh/task.ts). Without it a refresh is refused. + refresh?: RefreshHooks; // The iterations store (default: getPaths()). paths?: StorePaths; now?: () => Date; @@ -88,5 +92,5 @@ export type TaskResult = { // The media tasks (narrate first; release 28's cut, onscreen, teaser, flips, // threads and youtube) are generationSettings' MEDIA_STEP_TASKS: each a step // on a done iteration (./media.ts). -export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "research", ...MEDIA_STEP_TASKS] as const; +export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "research", "refresh", ...MEDIA_STEP_TASKS] as const; export type TaskName = (typeof TASK_NAMES)[number]; diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts @@ -59,7 +59,10 @@ export const ITERATION_FILENAME = "iteration.json"; export const ITERATIONS_CURRENT_FILENAME = "current.json"; export const ITERATIONS_CURRENT_FORMAT = "archilyzer-iterations-current"; -export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research"] as const; +// `refresh` (umtool R4, draft/refresh): fetch what is new, say what changed +// against its parent, and fold it in — a revision of its parent that names no +// feedback of its own. +export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research", "refresh"] as const; export type IterationKind = (typeof ITERATION_KINDS)[number]; // `queued`: created for a job that has not started; the rest as a job ends. export const ITERATION_STATUSES = ["queued", "running", "done", "failed", "cancelled"] as const; @@ -72,11 +75,15 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number]; // `seed.md`: a seeded sweep's starting report (a research board, umtool R2). // `trace.jsonl`: a sweep's structured trace, appended as it runs (umtool R3, // draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl. -export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl"] as const; +// `refresh.json`: a refresh's fetches, build and delta (umtool R4, +// draft/refresh/types.ts RefreshFile). +export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json"] as const; export type IterationFile = (typeof ITERATION_FILES)[number]; -// A revision needs something to revise. +// A revision needs something to revise (and feedback saying how); a refresh +// needs the iteration it refreshes (its feedback is what it finds). const NEEDS_PARENT: readonly IterationKind[] = ["revise-report", "revise-video"]; +const NEEDS_PARENT_ONLY: readonly IterationKind[] = ["refresh"]; // ─── The schema ─── @@ -124,6 +131,8 @@ export const iterationScopeSchema = z.looseObject({ channels: z.array(channelSlug).optional(), from: ymd.optional(), to: ymd.optional(), + // A sweep restricted to these recordings (umtool R4: a refresh's new ones). + ids: z.array(z.string().min(1)).optional(), }); export type IterationScope = z.infer<typeof iterationScopeSchema>; @@ -215,6 +224,7 @@ export function parseIteration( if (it.parent !== null && it.parent >= it.n) problems.push(`parent: i${it.parent} is not an earlier iteration`); if (it.copyOf !== null && it.copyOf >= it.n) problems.push(`copyOf: i${it.copyOf} is not an earlier iteration`); if (NEEDS_PARENT.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} revises an iteration`); + if (NEEDS_PARENT_ONLY.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} names the iteration it refreshes`); return problems.length ? { ok: false, problems } : { ok: true, value: it }; } @@ -427,6 +437,9 @@ async function createLocked(id: string, input: NewIteration, paths: StorePaths, if (parent === null) throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it revises (parent)`); if (!input.feedback?.trim()) throw new ArticleRegistryError(`a ${input.kind} iteration needs feedback: say what to change`); } + if (NEEDS_PARENT_ONLY.includes(input.kind) && parent === null) { + throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it refreshes (parent)`); + } if ((input.kind === "sweep" || input.kind === "research") && parent === null && !input.question?.trim() && copyOf === null) { throw new ArticleRegistryError(`a ${input.kind} iteration needs its question`); } @@ -625,7 +638,7 @@ export async function addIterationUsage( } function fileText(name: IterationFile, data: string | Uint8Array | object, id: string): string | Buffer { - if (name === "report.json" || name === "proposals.json") { + if (name === "report.json" || name === "proposals.json" || name === "refresh.json") { let value: unknown; if (typeof data === "string" || data instanceof Uint8Array) { try { @@ -645,7 +658,7 @@ function fileText(name: IterationFile, data: string | Uint8Array | object, id: s throw new ArticleRegistryError(`the iteration's report.json is "${String((value as { id?: unknown }).id)}", not "${id}"`); } } else if (!value || typeof value !== "object") { - throw new ArticleRegistryError("proposals.json is a JSON object or list"); + throw new ArticleRegistryError(`${name} is a JSON object or list`); } return `${JSON.stringify(value, null, 2)}\n`; } diff --git a/common/lib/report/quoteWords.ts b/common/lib/report/quoteWords.ts @@ -0,0 +1,108 @@ +// A QUOTE AGAINST THE TRANSCRIPT AS IT IS NOW — the word-level re-verify a +// research board runs on a pinned quote (umtool R2, lib/research/boards.ts +// verifyQuote) and a refresh runs on every quote its parent report cites +// (umtool R4, draft/refresh). Pure: the caller reads the cues (a board through +// the MCP engine, a refresh through the editor's corpus); this says what they +// hold. +// +// wordsOf / holdsWords the comparison: case, punctuation and spacing +// aside, whole words, in order +// windowAround the cues within ±span s of the cite, the one +// starting nearest the cite lit (R1's windowOf) +// checkWordsInWindow ok (and where the words start now, when they +// moved a second or more) or drifted (with the +// words over the quote's own seconds now) +// enOrigDifference the words of the `en` and the `en-orig` tracks +// over the cite, when they differ — the served `en` +// track can rewrite what was said + +export type WordCue = { start: number; end?: number; text: string }; +export type WindowCue = { t: number; end?: number; text: string }; + +/** The words of a text, for comparing: lowercase, apostrophes kept, everything else a space. */ +export function wordsOf(text: string | null | undefined): string { + return String(text ?? "") + .toLowerCase() + .replace(/[‘’ʼ`]/g, "'") + .replace(/[^\p{L}\p{N}' ]+/gu, " ") + .replace(/'+/g, "'") + .replace(/\s+/g, " ") + .trim(); +} + +/** Do `inside`'s words hold `quote`'s, in order and whole? */ +export function holdsWords(inside: string, quote: string): boolean { + const q = wordsOf(quote); + if (!q) return false; + return ` ${wordsOf(inside)} `.includes(` ${q} `); +} + +/** Cue texts joined as one line. */ +export const joinedCues = (cs: readonly { text: string }[]): string => cs.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" "); + +/** The cues starting within ±span s of `t`, and which of them is the one starting nearest `t` (-1: none in the window). */ +export function windowAround(all: readonly WordCue[], t: number, span = 30): { cues: WindowCue[]; lit: number } { + let litAll = -1; + let best = Infinity; + for (let i = 0; i < all.length; i++) { + const d = Math.abs(all[i]!.start - t); + if (d < best) { + best = d; + litAll = i; + } + } + const cues: WindowCue[] = []; + let lit = -1; + for (let i = 0; i < all.length; i++) { + const c = all[i]!; + if (c.start < t - span || c.start > t + span) continue; + if (i === litAll) lit = cues.length; + cues.push({ t: c.start, ...(c.end !== undefined ? { end: c.end } : {}), text: c.text }); + } + return { cues, lit }; +} + +export type WordsVerdict = + | { status: "ok"; nowAt?: number } + // `now`: the words over the quote's own seconds now ("" when the window is empty). + | { status: "drifted"; now: string; nowAt?: number; empty?: boolean }; + +/** The longest run of cues a quote is looked for in (a pin spans at most this many). */ +export const MAX_QUOTE_CUES = 12; + +/** + * The quote against the window around its cite: its words found → ok, with + * where they start now when that is a second or more from `t`; else drifted, + * with what the transcript says over the quote's seconds now. + */ +export function checkWordsInWindow(quote: string, cite: { t: number; end: number }, win: { cues: readonly WindowCue[]; lit: number }): WordsVerdict { + const cues = win.cues; + if (!cues.length) return { status: "drifted", now: "", empty: true }; + if (holdsWords(joinedCues(cues), quote)) { + // Where the words start now: the cue the shortest run holding them starts + // with -- a run that still holds them without its first cue started too early. + let nowAt: number | null = null; + for (let i = 0; i < cues.length && nowAt === null; i++) { + for (let k = i; k < Math.min(cues.length, i + MAX_QUOTE_CUES); k++) { + if (!holdsWords(joinedCues(cues.slice(i, k + 1)), quote)) continue; + if (k === i || !holdsWords(joinedCues(cues.slice(i + 1, k + 1)), quote)) nowAt = cues[i]!.t; + break; + } + } + return nowAt !== null && Math.abs(nowAt - cite.t) >= 1 ? { status: "ok", nowAt } : { status: "ok" }; + } + const lit = win.lit >= 0 ? win.lit : 0; + const length = Math.max(0, cite.end - cite.t); + const over = cues.slice(lit).filter((x, i) => i === 0 || x.t <= cues[lit]!.t + length - 0.25); + return { status: "drifted", now: joinedCues(over).slice(0, 3000), nowAt: cues[lit]!.t }; +} + +/** The `en` and `en-orig` words over a cite, when they differ (else null). */ +export function enOrigDifference(en: readonly WordCue[], orig: readonly WordCue[], cite: { t: number; end: number }): { en: string; orig: string } | null { + const over = (cues: readonly WordCue[]) => + joinedCues(cues.filter((x) => (x.end ?? x.start + 1) > cite.t + 0.25 && x.start < Math.max(cite.end, cite.t + 1) - 0.25)); + const a = over(en); + const b = over(orig); + if (wordsOf(a) === wordsOf(b)) return null; + return { en: a, orig: b }; +} diff --git a/common/testing/draft/corpus.d.mts b/common/testing/draft/corpus.d.mts @@ -29,4 +29,6 @@ export function momentHref(channel: string, id: string, seconds: number, encode? export function postHref(channel: string, id: string): string; export function recordOf(channel: string, id: string): FixtureRecord | null; export function cuesOf(channel: string, id: string): Promise<FixtureCue[] | null>; -export function writeDraftCorpus(dir: string): Promise<string>; +export const LATE_RECORD: FixtureRecord; +export function withRecords(extra: FixtureRecord[]): FixtureChannel[]; +export function writeDraftCorpus(dir: string, opts?: { channels?: FixtureChannel[] }): Promise<string>; diff --git a/common/testing/draft/corpus.mjs b/common/testing/draft/corpus.mjs @@ -154,16 +154,31 @@ export async function cuesOf(channel, id) { // The shard file name the index build writes (common/lib/manifest.ts pageFileName). const pageFile = (n) => `page-${String(n).padStart(4, "0")}.json`; +// A recording that is not in the corpus until a test adds it: a refresh's +// "new recording" (umtool R4). +export const LATE_RECORD = video("synth-kitchen", "Synth Kitchen", "contest-stream-04", "Contest results", "20261012", [ + "the contest results came out today", // 0 + "I was not a judge at the contest this year either", // 5 + "congratulations to the winner", // 10 +]); + +// CHANNELS with `extra` records added to their channels (a later build). +export function withRecords(extra) { + return CHANNELS.map((c) => ({ ...c, records: [...c.records, ...extra.filter((r) => r.channelSlug === c.slug)] })); +} + // A composed public dir: corpus.json, and per channel a manifest and one shard. -export async function writeDraftCorpus(dir) { +// `channels`: another set than CHANNELS (withRecords: a later build). +export async function writeDraftCorpus(dir, opts = {}) { + const CHANNELS_ = opts.channels ?? CHANNELS; await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "corpus.json"), JSON.stringify({ - channels: CHANNELS.map((c) => ({ slug: c.slug, name: c.name, videoCount: c.records.length })), + channels: CHANNELS_.map((c) => ({ slug: c.slug, name: c.name, videoCount: c.records.length })), }), ); - for (const c of CHANNELS) { + for (const c of CHANNELS_) { const chDir = path.join(dir, "transcripts", c.slug); await mkdir(chDir, { recursive: true }); await writeFile( diff --git a/editor/app/api/ops/_researchEditor.ts b/editor/app/api/ops/_researchEditor.ts @@ -29,30 +29,60 @@ const ROUTES: Record<string, () => Promise<{ POST: Post }>> = { export const RESEARCH_EDITOR_ACTIONS = Object.keys(ROUTES); -export const researchEditor: ResearchEditor = { +// An in-process door over `routes`: each action is its route's POST with a +// Request carrying the editor's own worker token. `who` names the caller in +// the refusal of an action it may not ask for. +export function inProcessEditor(routes: Record<string, () => Promise<{ POST: Post }>>, who: string): ResearchEditor { + return { + async run(action, args) { + const load = routes[action]; + if (!load) throw new Error(`"${action}" is not an action ${who} may ask the editor for`); + const token = getWorkerToken(); + if (!token) throw new Error("the editor's ops actions are off (WORKER_TOKEN is unset)"); + const { POST } = await load(); + const res = await POST( + new Request(`http://localhost/api/ops/${action}`, { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + body: JSON.stringify(args), + }), + ); + let body: Record<string, unknown> = {}; + try { + const j = await res.json(); + if (j && typeof j === "object" && !Array.isArray(j)) body = j as Record<string, unknown>; + } catch { + // not JSON: refused below with the status + } + if (res.status < 200 || res.status >= 300 || body.ok === false) { + throw new Error(typeof body.error === "string" && body.error ? body.error : `HTTP ${res.status}`); + } + return body; + }, + }; +} + +export const researchEditor: ResearchEditor = inProcessEditor(ROUTES, "a research run"); + +// A REFRESH'S EDITOR (umtool R4, controller/reportRefresh.ts): the fetches it +// runs — sync, fetch-posts, refresh-report, transcribe-bucket — and the build +// (`publish {verb: "build"}`; a refresh never deploys), through the same door. +const REFRESH_ROUTES: Record<string, () => Promise<{ POST: Post }>> = { + sync: () => import("./sync/route"), + "fetch-posts": () => import("./fetch-posts/route"), + "refresh-report": () => import("./refresh-report/route"), + "transcribe-bucket": () => import("./transcribe-bucket/route"), + publish: () => import("./publish/route"), +}; + +export const REFRESH_EDITOR_ACTIONS = Object.keys(REFRESH_ROUTES); + +const refreshDoor = inProcessEditor(REFRESH_ROUTES, "a refresh"); + +export const refreshEditor: ResearchEditor = { async run(action, args) { - const load = ROUTES[action]; - if (!load) throw new Error(`"${action}" is not an action a research run may ask the editor for`); - const token = getWorkerToken(); - if (!token) throw new Error("the editor's ops actions are off (WORKER_TOKEN is unset)"); - const { POST } = await load(); - const res = await POST( - new Request(`http://localhost/api/ops/${action}`, { - method: "POST", - headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, - body: JSON.stringify(args), - }), - ); - let body: Record<string, unknown> = {}; - try { - const j = await res.json(); - if (j && typeof j === "object" && !Array.isArray(j)) body = j as Record<string, unknown>; - } catch { - // not JSON: refused below with the status - } - if (res.status < 200 || res.status >= 300 || body.ok === false) { - throw new Error(typeof body.error === "string" && body.error ? body.error : `HTTP ${res.status}`); - } - return body; + // A refresh builds; it never deploys (nor runs Publish now). + if (action === "publish" && (args as { verb?: unknown }).verb !== "build") throw new Error("a refresh only builds: publish {verb: \"build\"}"); + return refreshDoor.run(action, args); }, }; diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -1,9 +1,10 @@ import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft } from "yt-dlp-transcript-common/controller/reportDraft"; +import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft"; +import { planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh"; import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; -import { jobResponse, ops } from "../_lib"; -import { researchEditor } from "../_researchEditor"; +import { jobResponse, ops, opsFail } from "../_lib"; +import { refreshEditor, researchEditor } from "../_researchEditor"; export const dynamic = "force-dynamic"; @@ -30,7 +31,17 @@ export const dynamic = "force-dynamic"; // - "sweep" with `iteration` N: CONTINUES research run N — its question and // its channels widened by what it acquired, the sweep's parent N (refused // while N still waits, unless `force`); -// - `copyOf` N: iteration N again on `model` (same kind and inputs). +// - `copyOf` N: iteration N again on `model` (same kind and inputs); +// - "refresh" (umtool R4): re-fetch the iteration's scope (`iteration`, +// default the current report's) through this editor's own sync / +// fetch-posts / refresh-report / transcribe-bucket, build its site +// locally (never a deploy), search again for what changed, and — when +// something did, within the caps — sweep the new recordings and revise +// the report: a new `refresh` iteration, one job on `draft:refresh`. +// `fetch: false` skips the fetch and the build; `dryRun: true` answers +// `{ ok, plan }` and writes nothing. The log ends `@@report-draft {…, +// refresh: {status, newIds, changed, drifted, deleted, summary}}`; +// - `ids` on a sweep: only those recordings (kept in its scope). // `model` defaults to settings.generation's route for the task (a task routed // to `code` needs one named). `extractorModel` is an API sweep's extractor // (a Claude model id; default settings.generation.models.extractor). An API job's cap is `maxUsd`, else the task's @@ -44,11 +55,22 @@ export const dynamic = "force-dynamic"; // the corpus tools are the MCP's own, in process (mcp/src/callTool.ts). export async function POST(request: Request) { return ops(request, REPORT_DRAFT_BODY_KEYS, async (body) => { - const out = await enqueueReportDraft(body, { + const deps = { paths: getPaths(), - corpusTools: (source) => createCorpusTools({ source }), + corpusTools: (source: string) => createCorpusTools({ source }), researchEditor, - }); + refreshEditor, + }; + if (body.task === "refresh" && body.dryRun === true) { + // The plan: what a refresh would do, nothing written. + try { + const plan = await planRefresh(parseReportDraftBody(body), deps); + return NextResponse.json({ ok: true, plan }); + } catch (e) { + return opsFail((e as Error).message); + } + } + const out = await enqueueReportDraft(body, deps); if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result); void out.result.stream.cancel(); return NextResponse.json({ diff --git a/mcp/src/refreshTask.test.ts b/mcp/src/refreshTask.test.ts @@ -0,0 +1,117 @@ +// A refresh's update end to end (umtool R4): the task over the MCP's own corpus +// tools (a later build of the synthetic draft corpus holding one recording +// more), the fake Anthropic, a temp iterations store. The parent is a done +// sweep with its trace; the refresh finds the new recording, sweeps ONLY it +// (the sweep's `ids` restriction: the enumeration answers its row alone), and +// revises the parent's report with the finding. Stage 1's fetches and build +// are common's tests (lib/report/draft/refresh/refresh.test.ts); here they +// are skipped (`fetch: false`). + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { LATE_RECORD, ORIGIN, POSTS, withRecords, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; +import { createIteration, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; +import { corpusCuesOf } from "yt-dlp-transcript-common/lib/report/draft/tasks/corpusCues"; +import type { RefreshFile } from "yt-dlp-transcript-common/lib/report/draft/refresh/types"; +import { createCorpusTools, type CorpusTools } from "./callTool"; + +const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft"); + +let tmp: string; +let later: CorpusTools; +let api: FakeAnthropic; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "refresh-task-")); + const dir = await writeDraftCorpus(path.join(tmp, "later"), { channels: withRecords([LATE_RECORD]) }); + later = await createCorpusTools({ source: `local:${dir}` }); + api = await startFakeAnthropic(); +}); + +after(async () => { + await later.close(); + await api.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const article = "synth-basic"; + +test("refresh: the new recording found, a sweep restricted to it, the report revised with its finding — updated", async () => { + const paths = { articlesDir: path.join(tmp, "reports"), exportIndexDir: path.join(tmp, "idx") }; + // i1: the basic sweep, done, with the trace of the enumeration it ran. + await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does the baker say about the contest?", scope: { channels: ["synth-kitchen"] } }, paths); + await writeIterationFile(article, 1, "sweep.md", await readFile(path.join(DRAFT, "sweeps", "basic.md"), "utf8"), paths); + await writeIterationFile(article, 1, "report.json", JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")), paths); + const trace = [ + { t: "run", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }, + { t: "scope", run: 1, source: "local:/the/first/build", channels: ["synth-kitchen"], question: "What does the baker say about the contest?" }, + { t: "enumerate", run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } }, + ]; + await writeIterationFile(article, 1, "trace.jsonl", trace.map((e) => JSON.stringify(e)).join("\n") + "\n", paths); + await updateIteration(article, 1, { status: "done" }, paths); + await createIteration(article, { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); + + const finding = `- She says she was not a judge: "I was not a judge at the contest this year either" [Contest results @ 0:05](${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5)`; + api.push( + // The restricted sweep: one enumeration (its answer the new row only), the report, done. + toolTurn("enumerate_matches", { query: "contest", channels: ["synth-kitchen"] }), + toolTurn("write_report", { markdown: `# New on the contest\n\nOne new stream mentions it.\n\n## The contest\n\n${finding}\n` }), + textTurn("sweep.md: 1 finding."), + // The revision: the finding added, as given. + toolTurn("apply_ops", { + ops: [{ op: "add", section: "The contest", text: "She says she was not a judge", quote: "I was not a judge at the contest this year either", link: `${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5` }], + }), + textTurn("Added the new finding."), + ); + const lines: string[] = []; + const deps: TaskDeps = { + llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, ollama: { baseUrl: "http://127.0.0.1:9" } }, + corpus: later, + cuesOf: corpusCuesOf(later), + postTextOf: async (channel, id) => POSTS.find((p) => p.channelSlug === channel && p.id === id)?.text ?? null, + paths, + log: (l) => lines.push(l), + refresh: { + editor: { run: async () => assert.fail("fetch: false runs no editor action") }, + jobOf: async () => null, + channelOf: async () => null, + siteOf: async () => ({ site: null }), + openCorpus: async () => ({ source: later.source, origin: ORIGIN, build: "later" }), + capRefusal: async () => null, + }, + }; + const out = await runTask({ task: "refresh", article, n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, deps); + assert.equal(out.status, "done", `${out.summary}\n${lines.join("\n")}`); + assert.equal(api.remaining(), 0, "every scripted turn was used"); + assert.ok(out.usd > 0); + + const f = JSON.parse((await readIterationFile(article, 2, "refresh.json", paths))!) as RefreshFile; + assert.equal(f.status, "updated"); + assert.deepEqual(f.delta?.newIds, ["contest-stream-04"]); + assert.equal(f.delta?.drifted.length, 0); + assert.deepEqual(f.update?.sweep, { ids: ["contest-stream-04"], status: "done", summary: f.update!.sweep!.summary, findings: 1 }); + assert.equal(f.update?.revision?.status, "done"); + assert.match(f.summary, /^1 new recording matches — updated: 1 op\(s\) applied/); + + // The sweep was restricted: its scope says so, and its enumeration answered the new row alone. + const events = (await readIterationFile(article, 2, "trace.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(events.find((e) => e.t === "scope")?.ids, ["contest-stream-04"]); + assert.deepEqual(events.find((e) => e.t === "enumerate")?.ids, ["contest-stream-04"]); + assert.equal(events.find((e) => e.t === "delta")?.status, "changed"); + assert.equal(events.at(-1).t, "run"); + assert.equal(events.at(-1).status, "done"); + + // The report: the parent's findings, and the new one. + const report = JSON.parse((await readIterationFile(article, 2, "report.json", paths))!); + const quotes = Object.values(report.citations as Record<string, { quote?: string; id?: string }>); + assert.ok(quotes.some((c) => c.id === "contest-stream-04" && c.quote === "I was not a judge at the contest this year either")); + assert.ok(quotes.some((c) => c.quote === "I did not enter the contest this year"), "the parent's findings stay"); + const it = await readIteration(article, 2, paths); + assert.equal(it?.status, "done"); + assert.deepEqual((it as { refresh?: unknown }).refresh, { status: "updated", newIds: 1, changed: 0, drifted: 0, deleted: 0, summary: f.summary }); +}); diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts @@ -4,7 +4,8 @@ import { momentUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl import { clock } from "yt-dlp-transcript-common/lib/search/window"; import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId"; import { REPORTS_ROOT } from "../paths.mjs"; -import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes, wordsOf } from "./board.mjs"; +import { checkWordsInWindow, enOrigDifference } from "yt-dlp-transcript-common/lib/report/quoteWords"; +import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes } from "./board.mjs"; import { CaseError, addQuote, @@ -205,7 +206,6 @@ export async function pinQuote(id: string, body: PinBody): Promise<{ case: CaseD export type VerifyResult = { id: string; verify: QuoteVerify }; -const joined = (cs: { text: string }[]) => cs.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" "); /** * One quote against the CURRENT transcript at its cite: R1's window (±30 s) @@ -232,29 +232,16 @@ export async function verifyQuote(q: Quote, now = new Date()): Promise<QuoteVeri if (e instanceof SourceError && e.status === 404) return { status: "missing", at, message: e.message }; throw e; } - const cues = win.cues; - let status: QuoteVerify = { status: "ok", at }; - if (!cues.length) { + // The words, against the window: common's check (lib/report/quoteWords.ts), + // shared with a refresh's re-verify (R4). + const v = checkWordsInWindow(q.text, { t: c.t, end: c.end }, win); + let status: QuoteVerify; + if (v.status === "ok") { + status = v.nowAt !== undefined ? { status: "ok", at, nowAt: v.nowAt, message: `the words now start at ${clock(v.nowAt)} (pinned at ${clock(c.t)})` } : { status: "ok", at }; + } else if (v.empty) { status = { status: "drifted", at, now: "", message: `no cues within 30 s of ${clock(c.t)}${c.trackId ? ` on the ${c.trackId} track` : ""} now` }; - } else if (holdsWords(joined(cues), q.text)) { - // Where the words start now: the cue the shortest run holding them - // starts with -- a run that still holds them without its first cue - // started too early. - let nowAt: number | null = null; - for (let i = 0; i < cues.length && nowAt === null; i++) { - for (let k = i; k < Math.min(cues.length, i + MAX_PIN_CUES); k++) { - if (!holdsWords(joined(cues.slice(i, k + 1)), q.text)) continue; - if (k === i || !holdsWords(joined(cues.slice(i + 1, k + 1)), q.text)) nowAt = cues[i].t; - break; - } - } - if (nowAt !== null && Math.abs(nowAt - c.t) >= 1) status = { status: "ok", at, nowAt, message: `the words now start at ${clock(nowAt)} (pinned at ${clock(c.t)})` }; } else { - // What the transcript says over the quote's own seconds now. - const lit = win.lit >= 0 ? win.lit : 0; - const length = Math.max(0, c.end - c.t); - const over = cues.slice(lit).filter((x, i) => i === 0 || x.t <= cues[lit].t + length - 0.25); - status = { status: "drifted", at, now: joined(over).slice(0, 3000), nowAt: cues[lit].t }; + status = { status: "drifted", at, now: v.now, ...(v.nowAt !== undefined ? { nowAt: v.nowAt } : {}) }; } const enOrig = await enOrigCheck(opened.source, q); return enOrig ? { ...status, enOrig } : status; @@ -273,13 +260,11 @@ async function enOrigCheck(source: Awaited<ReturnType<typeof openSource>>["sourc const enId = ids.find((t) => t === "en"); const origId = ids.find((t) => trackKind(t) === "original"); if (!enId || !origId) return undefined; - const textOn = (track: string) => { - const cues = (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[]; - return joined(cues.filter((x) => x.end > c.t + 0.25 && x.start < Math.max(c.end, c.t + 1) - 0.25)); - }; - const en = textOn(enId); - const orig = textOn(origId); - if (wordsOf(en) === wordsOf(orig)) return undefined; + const cuesOn = (track: string) => (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[]; + const diff = enOrigDifference(cuesOn(enId), cuesOn(origId), { t: c.t, end: c.end }); + if (!diff) return undefined; + const orig = diff.orig; + const en = diff.en; const quoted = c.trackId ?? rec.track; return { text: orig, quoted, other: en }; }