// `report-schedule` for umtool's e2e editor stub (umtool R5): the REAL ops // action and store over the fixture's article store, with a tick's steps // stubbed -- what umtool/e2e/fixtures/editor-stub.mjs runs for each // `POST /api/ops/report-schedule`. Test-only; synthetic. // // tsx common/testing/schedule/opsStub.ts --articles \ // --channels a,b --generation '' --job [--now ] [--quiet] // (the body on stdin; --now is the clock a spec set, --quiet makes the // next window quiet) // // Prints the action's answer as one JSON line; `tick-now` runs the tick to // its end in this process (its claim, its record) and answers {jobId, tick}. // The stubbed steps, by what the schedule asks: // fetchAndBuild ok ("fetched (stub)") // refresh no change, $0 // generateEdition terms or question with "held" → held by the daily cap; // "fail" → failed; --quiet, or "quiet" → quiet; else a // done iteration with a two-section report, $0.37 (with // `ids`, R6's escalation: one finding citing the first // flagged recording, and a trace whose first line after the // start is the triage's tiers) // triage (R6) a real triage run in reports/.triage/// — // "quiet" in the terms or question → candidates, no flag // (below the threshold); "partial" → the same, tier 0 // partial (a channel not reached: the tick is partial, // R6.1); a quiet run also lists two recordings without // a transcript yet (R6.2); else a strong flag and a weak one // on sitechan/sv1 and sv2, an invented line dismissed as // not verbatim, a window not relevant; $0 (local). With // learned spellings (R6.3), sv3 is a candidate a learned // spelling alone brought, and the run says "terms + N // learned" // learn (R6.3, a create of a watch whose terms name someone, a // change of terms, `learn`) the pass runs here at once: two // spellings of the first name kept — "Vote Rigg" (proposed, // sv1) and "Vote Rick" (heard in triage 1, sv2; its // candidates dismissed four runs running: suggest removing) // — and "Boat Rig" dropped (no hits), through the real // writer (a blocked spelling stays out). promote-alias and // unlearn are the real ones: the alias file is // /search-aliases.json, the sites /sites import { mkdir } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../../lib/paths"; import { sanitizeGeneration } from "../../lib/generationSettings"; import { createIteration, updateIteration, writeIterationFile } from "../../lib/report/iterations"; import { claimTick } from "../../controller/reportSchedule"; import { createTriageRun, writeTriageFile } from "../../lib/report/draft/triage/store"; import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, partialWords, triageLine, type TriageCandidate, type TriageFile, type TriageFlag } from "../../lib/report/draft/triage/types"; import { writeFile } from "node:fs/promises"; import { iterationFile } from "../../lib/report/iterations"; import { runTick, type TickDeps, type TickSteps } from "../../controller/reportTick"; import { reportScheduleAction, type EnqueueLearnFn } from "../../controller/reportScheduleOps"; import { recordLearnPass } from "../../controller/learnedSpellings"; import { planLearn } from "../../controller/reportLearn"; import { readLearned } from "../../lib/report/draft/triage/learnedStore"; import { activeLearned, namesOf, type LearnedSpelling } from "../../lib/report/draft/triage/learned"; import { readSchedule } from "../../lib/report/schedule/store"; const argv = process.argv.slice(2); const flag = (name: string) => { const i = argv.indexOf(`--${name}`); return i < 0 ? undefined : argv[i + 1]; }; const articlesDir = flag("articles") ?? ""; if (!articlesDir) { console.error("usage: opsStub.ts --articles [--channels a,b] [--generation json] [--job id]"); process.exit(2); } const channels = (flag("channels") ?? "").split(",").filter(Boolean); const generation = sanitizeGeneration(JSON.parse(flag("generation") ?? "{}")); const jobId = flag("job") ?? `stub-tick-${Date.now()}`; const nowIso = flag("now"); const quietNext = argv.includes("--quiet"); const root = path.dirname(articlesDir); const paths = { articlesDir, exportIndexDir: path.join(root, ".export-index-schedule"), generationUsageFile: path.join(root, ".generation-usage.jsonl"), jobsDir: path.join(root, ".jobs-schedule"), globalAliasesFile: path.join(root, "search-aliases.json"), sitesDir: path.join(root, "sites"), } as unknown as Paths; await mkdir(articlesDir, { recursive: true }); const words = (s: { question: string; scope: { terms?: string } }) => `${s.question} ${s.scope.terms ?? ""}`.toLowerCase(); // R6: the triage's flags (sitechan's fixture lines: sites-fixture.mjs). const ORIGIN = "https://priv.example"; const FLAGS: TriageFlag[] = [ { f: "f1", id: "sv1", channel: "sitechan", title: "Site video one", date: "2024-03-15", window: { start: 0, end: 12 }, line: "The vote was rigged and everybody knew.", at: 3, score: 3, strength: "strong", reason: "The speaker says the vote was rigged (stub).", checked: "cues", url: `${ORIGIN}/?v=sitechan%2Fsv1&t=3` }, { f: "f2", id: "sv2", channel: "sitechan", title: "Site video two", date: "2024-03-15", window: { start: 5, end: 15 }, line: "Then she said the opposite.", at: 8, score: 2, strength: "weak", reason: "She contradicts an earlier claim (stub).", checked: "cues", url: `${ORIGIN}/?v=sitechan%2Fsv2&t=8` }, ]; const steps: TickSteps = { fetchAndBuild: async (_scope, ctx) => { ctx.log("fetched (stub)"); return { ok: true }; }, refresh: async () => ({ status: "no-change", usd: 0, reason: "nothing new matches (stub)" }), generateEdition: async (input, ctx) => { const w = words(input.schedule); if (/held/.test(w)) return { status: "held-by-cap", usd: 0, estimateUsd: generation.caps.sweep, reason: `the day's Claude API spend is $${generation.caps.daily.toFixed(2)} (stub), at or past the $${generation.caps.daily.toFixed(2)} daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC` }; if (/fail/.test(w)) return { status: "failed", usd: 0, reason: "the corpus build is gone (stub)" }; if (input.quietCheck && (quietNext || /quiet/.test(w))) { return { status: "quiet", usd: 0, matched: 0, reason: `nothing in ${input.window.from} … ${input.window.to} matches (stub)` }; } const model = input.schedule.model ?? generation.models.api; const it = await createIteration( input.article, { kind: "sweep", model, question: input.schedule.question, scope: { channels: input.schedule.scope.channels, ...(input.ids?.length ? { ids: input.ids } : { from: input.window.from, to: input.window.to }), ...(input.triage ? { triage: input.triage } : {}) }, }, paths, ); if (input.ids?.length) { // R6: the escalation's sweep of the flagged recordings — one finding, and its trace. const at = (nowIso ? new Date(nowIso) : new Date()).toISOString(); const flag = FLAGS.find((f) => f.id === input.ids![0]) ?? FLAGS[0]!; await writeIterationFile( input.article, it.n, "report.json", { format: "archilyzer-report", version: 1, id: input.article, kind: "sweep", title: input.title ?? input.schedule.topic, summary: "One flagged recording holds it (stub).", citations: { c1: { kind: "video", channel: flag.channel, id: flag.id, start: flag.at, end: flag.at + 3, quote: flag.line } }, sections: [{ id: "s1", title: "What was found", body: `The speaker [says so](cite:c1).`, claims: [{ id: "k1", text: flag.reason, citations: ["c1"] }] }], }, paths, ); const lines = [ { t: "run", at, run: 1, phase: "start", task: "sweep-agent", model }, { t: "triage", at, run: 1, owner: input.triage?.owner ?? input.schedule.id, k: input.triage?.k ?? 1, candidates: ["sv1", "sv2", "sv3", "sv4"], flagged: input.ids, dismissed: 2, escalated: true, why: "1 strong flag, 1 weak flag (threshold: 1 strong or 3 weak)", cost: { tier0: 0, tier1: 0 }, model: generation.models.local }, { t: "scope", at, run: 1, source: "local:/stub/out", channels: input.schedule.scope.channels, question: input.schedule.question, model, ids: input.ids }, { t: "cost", at, run: 1, step: "turn 0", usd: 0.37, model, total: 0.37, turn: 0, phase: "agent", calls: ["get_transcripts"], tier: 2 }, { t: "finding", at, run: 1, section: "What was found", claim: flag.reason, cites: [{ citation: "c1", channel: flag.channel, video: flag.id, start: flag.at, quote: flag.line }] }, { t: "check", at, run: 1, quote: flag.line, cite: { citation: "c1", channel: flag.channel, video: flag.id, start: flag.at }, ok: true, stage: "final", reason: "verbatim (strict)" }, { t: "run", at, run: 1, phase: "end", status: "done", summary: "1 finding (stub)", usd: 0.37, minutes: 0.1, coverage: { matched: input.ids.length, read: input.ids.length, partial: false, unreached: [] } }, ]; await writeFile(iterationFile(paths, input.article, it.n, "trace.jsonl"), lines.map((l) => JSON.stringify(l)).join("\n") + "\n"); await updateIteration(input.article, it.n, { status: "done", usage: { [model]: { usd: 0.37, inputTokens: 1200, outputTokens: 300, calls: 4 } }, coverage: { matched: input.ids.length, read: input.ids.length, partial: false, unreached: [] } }, paths); ctx.log(`sweep ${input.article} i${it.n} (the flagged ids): ~$0.37 so far`); return { status: "done", iteration: it.n, usd: 0.37, jobId: `${jobId}-sweep` }; } await writeIterationFile( input.article, it.n, "report.json", { format: "archilyzer-report", version: 1, id: input.article, kind: "sweep", title: input.title ?? input.schedule.topic, sections: [ { id: "s1", title: "What was said", body: `Two recordings in ${input.window.from} … ${input.window.to} mention it (stub).` }, { id: "s2", title: "What changed", body: "Nothing contradicts the last edition (stub)." }, ], }, paths, ); await updateIteration(input.article, it.n, { status: "done", usage: { [model]: { usd: 0.37, inputTokens: 1200, outputTokens: 300, calls: 4 } } }, paths); ctx.log(`sweep ${input.article} i${it.n}: ~$0.37 so far`); return { status: "done", iteration: it.n, usd: 0.37, matched: 2, jobId: `${jobId}-sweep` }; }, triage: async (input, ctx) => { const s = input.schedule; // R6.3: the learned spellings its query carries. const lf = await readLearned(paths, s).catch(() => null); const learnt = activeLearned(lf, namesOf(s.scope.terms ?? null, s.scope.regex === true)).map((l) => l.spelling); // "partial" (R6.1): tier 0 hit a cap — a channel not reached — and nothing flagged. const partial = /partial/.test(words(s)); const quiet = partial || /quiet/.test(words(s)); const at = (nowIso ? new Date(nowIso) : new Date()).toISOString(); const threshold = s.triage?.threshold ?? { strong: generation.triage.strong ?? DEFAULT_TRIAGE_THRESHOLD.strong, weak: generation.triage.weak ?? DEFAULT_TRIAGE_THRESHOLD.weak }; const run = await createTriageRun( (k): TriageFile => ({ format: TRIAGE_FORMAT, version: TRIAGE_VERSION, owner: s.id, k, status: "done", jobId: `${jobId}-triage`, model: generation.models.local, provider: "local", question: s.question, scope: { channels: input.scope.channels }, terms: s.scope.terms ?? null, regex: s.scope.regex === true, topics: s.scope.topics ?? [], threshold, since: input.since, knownCount: 12, createdAt: at, startedAt: at, endedAt: at, tier0: { candidates: ["sv1", "sv2", "sv3", "sv4"].map((id, i) => ({ id, channel: "Site Channel", title: `Site video ${["one", "two", "three", "four"][i]}`, date: "2024-03-15", matches: 2 - (i % 2), by: i === 3 ? ["topics"] : i === 2 && learnt.length ? ["learned"] : ["terms"], ...(i === 3 ? { tags: ["elections"] } : {}), ...(i === 2 && learnt.length ? { learned: [learnt[0]!] } : {}), })) as TriageCandidate[], scanned: 16, newCount: 4, cut: [], partial, unreached: partial ? ["Site Other (stopped at page 2 of 5)"] : [], perQuery: [{ query: "(every recording, listed)", n: 16, partial }], newBy: "id", listedBy: "manifests", // R6.2: a quiet run lists two recordings whose transcripts have not landed (not seen). ...(quiet && !partial ? { untranscribed: 2, untranscribedIds: ["sv5", "sv6"] } : {}), ...(learnt.length ? { learned: { spellings: learnt, matched: 1 } } : {}), }, ...(learnt.length ? { learned: { n: learnt.length, spellings: learnt } } : {}), tier1: { model: generation.models.local, flags: quiet ? [] : FLAGS, dismissed: [ { id: "sv3", title: "Site video three", channel: "sitechan", window: { start: 0, end: 30 }, line: "Everybody rigged the count on purpose.", at: 5, score: 3, stage: "verbatim", reason: "not verbatim in its window" }, { id: "sv4", title: "Site video four", channel: "sitechan", window: { start: 0, end: 40 }, stage: "judge", reason: "not relevant to the question" }, ...(quiet ? [{ id: "sv1", title: "Site video one", channel: "sitechan", window: { start: 0, end: 12 }, line: "The vote was rigged and everybody knew.", at: 3, score: 1, stage: "score" as const, reason: "a mention only — it names the vote (stub)" }] : []), ], read: 4, windows: 4, chunks: 5, usd: 0, }, escalation: escalationOf(quiet ? [] : FLAGS, threshold), cost: { tier0: 0, tier1: 0 }, summary: "", warnings: [], }), paths, s.id, ); const part = partialWords(run.tier0); const f = { ...run, summary: `${part ? `partial (${part}) · ` : ""}${triageLine(run)} — ${run.escalation!.escalate ? "escalate" : "below the threshold"}: ${run.escalation!.why}` }; await writeTriageFile(f, paths); ctx.log(`triage ${s.id}/${f.k} (stub): ${f.summary}`); return { status: "done", file: f, jobId: `${jobId}-triage` }; }, }; // R6.3: the proposal pass, at once (no model): two spellings of the first name kept, one dropped. const enqueueLearn: EnqueueLearnFn = async (id, trigger) => { const plan = await planLearn(id, { paths, settings: () => ({ generation }), ...(nowIso ? { now: () => new Date(nowIso) } : {}) }); if (plan.refused) return { ok: false, error: plan.refused, plan }; const s = (await readSchedule(id, paths))!; const at = (nowIso ? new Date(nowIso) : new Date()).toISOString(); const name = plan.names[0]!; const kept: LearnedSpelling[] = [ { spelling: "Vote Rigg", means: name, quote: "The vote was rigged and everybody knew.", recording: "sv1", channel: "sitechan", title: "Site video one", start: 3, url: `${ORIGIN}/?v=sitechan%2Fsv1&t=3`, hits: 2, lines: 3, source: "proposed", at, windows: [ { recording: "sv1", start: 3, means: true, verbatim: true, reason: "the watched name (stub)", quote: "The vote was rigged and everybody knew." }, { recording: "sv2", start: 8, means: false, verbatim: true, reason: "another person (stub)" }, { recording: "sv3", start: 5, means: true, verbatim: true, reason: "the watched name (stub)", quote: "Vote Rigg was on the panel." }, ] }, { spelling: "Vote Rick", means: name, quote: "Then she said the opposite.", recording: "sv2", channel: "sitechan", title: "Site video two", start: 8, url: `${ORIGIN}/?v=sitechan%2Fsv2&t=8`, hits: 1, source: "heard", k: 1, at, uses: [1, 2, 3, 4].map((k) => ({ k, at, candidates: 1, flagged: 0 })), }, ]; await recordLearnPass( s, { pass: { at, trigger, status: "done", model: generation.models.local, names: plan.names, notAsked: plan.notAsked, proposed: 3, kept: 0, dropped: 0, usd: 0, jobId: `${jobId}-learn` }, kept, dropped: [{ spelling: "Boat Rig", means: name, source: "proposed", reason: "no-hits", why: "does not occur in scope (16 recordings counted)", at }], termsKey: s.scope.terms ? `${s.scope.regex ? "re" : "lit"}:${s.scope.terms}` : null, }, paths, new Date(at), ); return { ok: true, jobId: `${jobId}-learn`, plan }; }; const deps: TickDeps = { paths, ...(nowIso ? { now: () => new Date(nowIso) } : {}), settings: () => ({ generation }), knownChannels: async () => channels, steps, }; let raw = ""; for await (const chunk of process.stdin) raw += chunk; const body = JSON.parse(raw || "{}") as Record; const log: string[] = []; if (body.action === "tick-now") { const id = String(body.id ?? ""); const claimed = await claimTick(id, { jobId, trigger: "now" }, deps).catch((e: Error) => ({ error: e.message })); if (!claimed) { console.log(JSON.stringify({ ok: false, status: 409, error: `a tick of "${id}" is already queued or running` })); } else if ("error" in claimed) { console.log(JSON.stringify({ ok: false, status: 404, error: (claimed as { error: string }).error })); } else { const tick = await runTick(id, { trigger: "now", jobId }, deps, { log: (l) => log.push(l), signal: new AbortController().signal }); console.log(JSON.stringify({ ok: true, jobId, tick, log })); } } else { const out = await reportScheduleAction(body, { ...deps, lane: () => ({ held: false, armed: true }), enqueueLearn }); console.log(JSON.stringify(out)); }