// 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; 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>; scope?: RefreshBasis["scope"]; source: string | null; known?: Record }; function addRows(perQuery: Found["perQuery"], key: string, rows: Record) { 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 = { ...(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; 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) => { 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 = {}; 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 { const out: Record = {}; 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 }).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 { 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 { 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 = found?.known ? { ...found.known } : found ? knownOf(found.perQuery) : {}; const countsKnown = !!found && (found.from === "refresh" ? Object.values(known).some((c) => c !== null) : [...found.perQuery.values()].some((rows) => Object.values(rows).some((c) => c !== null))); 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, countsKnown, cited, source: found?.source ?? null, at: it.endedAt ?? it.updatedAt, }; }