import { test, expect, type APIRequestContext } from "@playwright/test"; import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; // By relative path, as digest.spec.ts imports common: the test kit's fakes and // the synthetic corpus are plain .mjs. import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; import { jsonReply, startFakeOllama, type FakeOllama } from "../../common/testing/llm/fakeOllama.mjs"; import { LATE_RECORD, ORIGIN, withRecords, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs"; import { baseUrl } from "./baseUrl"; import { resetData, testPaths, writeChannelConfig, writeSettings } from "./helpers"; // `pnpm ops report-draft` end to end (release 27 S6): the editor against the // fake Anthropic (started here, on loopback; settings point at it with a // mode-600 key file holding the fake's key), over the synthetic draft corpus // written as a composed build into the test server's .export-builds/ (the // newest build holding the channels is the one a job picks). The usage ledger // is the test server's GENERATION_USAGE_FILE, inside test-transcripts/, so a // reset clears it. const AUTH = { authorization: "Bearer test-worker-token" }; const RUNS = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "common", "testing", "draft", "runs"); let api: FakeAnthropic; let keyDir: string; test.beforeAll(async () => { api = await startFakeAnthropic(); keyDir = await mkdtemp(join(os.tmpdir(), "e2e-report-draft-")); }); test.afterAll(async () => { await api?.close(); await rm(keyDir, { recursive: true, force: true }); }); async function setup(caps: Record = {}, fixture: string | null = null) { await resetData(fixture); const keyFile = join(keyDir, "anthropic.env"); await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); await chmod(keyFile, 0o600); await writeSettings({ minFreeDiskGB: 0, generation: { apiKeyFile: keyFile, anthropicBaseUrl: api.url, citationOrigin: ORIGIN, projectsRoot: join(keyDir, "projects"), caps: { sweep: 3, revision: 2, narration: 1, daily: 20, max: 5, ...caps }, }, }); const t = testPaths().transcriptsDir; await writeDraftCorpus(join(t, ".export-builds", "draft-e2e", "out")); } async function draft(request: APIRequestContext, data: Record) { const res = await request.post(`${baseUrl}/api/ops/report-draft`, { headers: AUTH, data }); return { status: res.status(), body: (await res.json()) as { ok?: boolean; error?: string; jobId?: string; iteration?: number } }; } async function jobUntil(request: APIRequestContext, id: string, done: (s: string) => boolean, ms = 60_000) { const t0 = Date.now(); let last = ""; while (Date.now() - t0 < ms) { const res = await request.get(`${baseUrl}/api/ops/job/${id}?tail=40`, { headers: AUTH }); const body = (await res.json()) as { job?: { status?: string }; status?: string; tail?: string[] }; last = body.job?.status ?? body.status ?? ""; if (done(last)) return body; await new Promise((r) => setTimeout(r, 300)); } throw new Error(`job ${id} is still ${last}`); } const iterationJson = async (article: string, n: number) => JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", article, "iterations", String(n), "iteration.json"), "utf8")); const run = async (name: string) => JSON.parse(await readFile(join(RUNS, `${name}.json`), "utf8")); test.describe.configure({ mode: "serial" }); test("a sweep draft: enqueued over ops, followed to done, its iteration read back; its model log on the job page", async ({ request, page }) => { test.setTimeout(120_000); await setup(); const r = await run("sweep-agent"); api.push(...r.turns); const { status, body } = await draft(request, { task: "sweep", article: "synth-e2e", model: r.model, question: r.question, channels: r.channels, }); expect(status, body.error).toBe(200); expect(body.ok).toBe(true); expect(body.iteration).toBe(1); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); // The job's progress (release 28 F3): the agent's model turns, against its turn cap. expect((job.job as { progress?: unknown } | undefined)?.progress).toMatchObject({ metric: "turns", initial: 0, current: 6, target: 150 }); const it = await iterationJson("synth-e2e", 1); expect(it.status).toBe("done"); expect(it.jobId).toBe(body.jobId); expect(it.usage["claude-sonnet-5-5"].usd).toBeGreaterThan(0); const report = JSON.parse( await readFile(join(testPaths().transcriptsDir, "reports", "synth-e2e", "iterations", "1", "report.json"), "utf8"), ); expect(Object.keys(report.citations)).toHaveLength(3); const ledger = await readFile(join(testPaths().transcriptsDir, ".generation-usage.jsonl"), "utf8"); expect(ledger).toContain(body.jobId!); expect(ledger).not.toContain(FAKE_KEY); expect(api.remaining()).toBe(0); // The job page's model log (demo epic D3): the agent's turns and the // extractor's batches, each opening to what was asked; no key anywhere. const view = await (await request.get(`${baseUrl}/api/jobs/${body.jobId}/model-log`)).json(); expect(view.where).toEqual({ article: "synth-e2e", n: 1 }); expect(view.view.summary.calls).toBeGreaterThanOrEqual(6); expect(view.view.groups.map((g: { phase: string }) => g.phase)).toEqual(expect.arrayContaining(["reading", "agent"])); await page.goto(`${baseUrl}/jobs/${body.jobId}`); const log = page.locator("[data-job-model-log]"); await expect(log).toHaveAttribute("data-job-model-log", "calls"); await expect(log.locator("[data-model-log-count]")).toHaveAttribute("data-model-log-count", String(view.view.summary.calls)); await expect(log.locator("[data-phase=agent] [data-call]").first()).toBeVisible(); await log.locator("[data-phase=agent] [data-call] button").first().click(); await expect(log.locator("[data-call-open] [data-call-prompt]").first()).toContainText(r.question); expect(await page.content()).not.toContain(FAKE_KEY); if (process.env.E2E_MODEL_LOG_SHOTS) await page.screenshot({ path: join(process.env.E2E_MODEL_LOG_SHOTS, "editor-job-page.png"), fullPage: true }); }); test("a cancel mid-run: job cancel stops the draft and its iteration ends cancelled", async ({ request }) => { test.setTimeout(120_000); await setup(); let release!: () => void; const held = new Promise((r) => (release = r)); const before = api.requests.length; api.push(async () => { await held; return textTurn("too late"); }); const { body } = await draft(request, { task: "sweep", article: "synth-cancel", model: "claude-sonnet-5-5", question: "What does she say about the contest?", channels: ["synth-kitchen"], }); expect(body.ok, body.error).toBe(true); await expect.poll(() => api.requests.length, { timeout: 30_000 }).toBeGreaterThan(before); const cancel = await request.post(`${baseUrl}/api/ops/job`, { headers: AUTH, data: { verb: "cancel", ids: [body.jobId] } }); expect(cancel.status()).toBe(200); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); release(); expect(job.job?.status ?? job.status).toBe("cancelled"); await expect.poll(async () => (await iterationJson("synth-cancel", 1)).status, { timeout: 10_000 }).toBe("cancelled"); }); test("the daily cap: a job that would start past the day's API total is refused, naming it", async ({ request }) => { await setup({ daily: 4 }); const day = new Date().toISOString().slice(0, 10); await writeFile( join(testPaths().transcriptsDir, ".generation-usage.jsonl"), `${JSON.stringify({ at: new Date().toISOString(), day, jobId: "earlier", article: "x", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 4.5 })}\n`, ); const { status, body } = await draft(request, { task: "sweep", article: "synth-daily", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], }); expect(status).toBe(400); expect(body.error).toContain("the day's Claude API spend is $4.50"); expect(body.error).toContain("$4.00 daily cap"); await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-daily", "iterations", "1", "iteration.json"))).rejects.toThrow(/ENOENT/); }); test("a media draft (release 28 M3): a teaser on the API, a step on the done iteration, checked by the build's own validator loaded in the editor", async ({ request }) => { test.setTimeout(120_000); await setup(); // A done sweep iteration whose project holds the kit's basic cut and report. const kit = join(RUNS, ".."); const article = "synth-teaser"; const project = join(keyDir, "projects", article, "i1"); const report = JSON.parse(await readFile(join(kit, "reports", "basic.report.json"), "utf8")); const itDir = join(testPaths().transcriptsDir, "reports", article, "iterations", "1"); await mkdir(itDir, { recursive: true }); await mkdir(project, { recursive: true }); const at = new Date().toISOString(); await writeFile( join(itDir, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article, n: 1, kind: "sweep", parent: null, copyOf: null, model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] }, status: "done", usage: {}, steps: [], projectDir: project, createdAt: at, updatedAt: at, endedAt: at, }), ); await writeFile(join(itDir, "report.json"), JSON.stringify(report)); await writeFile(join(project, "report.json"), JSON.stringify(report)); await writeFile(join(project, "video.manifest.json"), await readFile(join(kit, "manifests", "basic.video.manifest.json"), "utf8")); api.push(toolTurn("answer", { lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] })); const { status, body } = await draft(request, { task: "teaser", article, iteration: 1, model: "claude-sonnet-5-5" }); expect(status, body.error).toBe(200); expect(body.iteration).toBe(1); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); expect((job.job as { progress?: unknown } | undefined)?.progress).toMatchObject({ metric: "entries", initial: 0, current: 1, target: 1 }); const it = await iterationJson(article, 1); expect(it.steps.find((s: { task: string }) => s.task === "teaser")).toMatchObject({ status: "done", jobId: body.jobId }); const m = JSON.parse(await readFile(join(project, "video.manifest.json"), "utf8")); expect(m.timeline.at(-1)).toMatchObject({ type: "teaser", id: "teaser", lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] }); expect(m.timeline.at(-1).drafted.lines).toMatchObject({ task: "teaser", model: "claude-sonnet-5-5", iteration: 1, attempt: 1 }); // The editor ran the build's validateTeaser (a teaser it cannot check is not written). const draftFile = JSON.parse(await readFile(join(project, "teaser-draft.json"), "utf8")); expect(draftFile.units.teaser.applied).toBe("applied"); expect(api.remaining()).toBe(0); }); // ─── a refresh (umtool R4) ─── const KIT = join(RUNS, ".."); // i1 of `article`: the kit's basic sweep, done, with the trace of the one // enumeration it ran (over `channel`, read from `build`). async function doneBasicSweep(article: string, o: { channel?: string; report?: unknown; build?: string } = {}) { const channel = o.channel ?? "synth-kitchen"; const itDir = join(testPaths().transcriptsDir, "reports", article, "iterations", "1"); await mkdir(itDir, { recursive: true }); const at = new Date().toISOString(); await writeFile( join(itDir, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article, n: 1, kind: "sweep", parent: null, copyOf: null, model: "claude-sonnet-5-5", question: "What does the baker say about the contest?", scope: { channels: [channel] }, status: "done", usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 1, read: 2, partial: false, unreached: [] }, steps: [], createdAt: at, updatedAt: at, endedAt: at, }), ); const report = o.report ?? { ...JSON.parse(await readFile(join(KIT, "reports", "basic.report.json"), "utf8")), id: article }; await writeFile(join(itDir, "report.json"), JSON.stringify(report)); await writeFile(join(itDir, "sweep.md"), await readFile(join(KIT, "sweeps", "basic.md"), "utf8")); const build = o.build ?? join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"); const trace = [ { t: "run", at, run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }, { t: "scope", at, run: 1, source: `local:${build}`, channels: [channel], question: "What does the baker say about the contest?" }, { t: "enumerate", at, run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } }, ]; await writeFile(join(itDir, "trace.jsonl"), trace.map((e) => JSON.stringify(e)).join("\n") + "\n"); } test("a refresh over ops: the plan (dryRun, nothing written), then the job — the fetch skipped where it cannot run, no change, $0", async ({ request }) => { test.setTimeout(120_000); await setup(); await doneBasicSweep("synth-refresh"); const planned = await request.post(`${baseUrl}/api/ops/report-draft`, { headers: AUTH, data: { task: "refresh", article: "synth-refresh", dryRun: true } }); expect(planned.status()).toBe(200); const { plan } = (await planned.json()) as { plan: { parent: { n: number; queries: string[] }; channels: { slug: string; skip?: string }[]; build: { site: string | null; reason?: string }; capUsd: number } }; expect(plan.parent).toMatchObject({ n: 1, queries: ["contest"] }); expect(plan.channels).toEqual([{ slug: "synth-kitchen", kind: null, platform: null, actions: [], skip: "not a channel of this editor" }]); expect(plan.build).toMatchObject({ site: null, reason: "the build draft-e2e is not a site's: it is read as it stands" }); expect(plan.capUsd).toBe(3); await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-refresh", "iterations", "2", "iteration.json"))).rejects.toThrow(/ENOENT/); const before = api.requests.length; const { status, body } = await draft(request, { task: "refresh", article: "synth-refresh" }); expect(status, body.error).toBe(200); expect(body.iteration).toBe(2); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); const tail = (job.tail ?? []).join("\n"); expect(job.job?.status ?? job.status, tail).toBe("done"); expect(tail).toContain('"task":"refresh"'); expect(tail).toMatch(/"refresh":\{"status":"no-change","newIds":0,"changed":0,"drifted":0,"deleted":0,"summary":"Nothing new since 20\d\d-/); expect(api.requests.length, "no model was asked").toBe(before); const it = await iterationJson("synth-refresh", 2); expect(it).toMatchObject({ kind: "refresh", parent: 1, status: "done", jobId: body.jobId, refresh: { status: "no-change" } }); const f = JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", "synth-refresh", "iterations", "2", "refresh.json"), "utf8")); expect(f.fetch).toEqual([{ channel: "synth-kitchen", action: "sync", status: "skipped", reason: "not a channel of this editor" }]); expect(f.build).toMatchObject({ site: null, status: "skipped" }); expect(f.delta.quotes).toHaveLength(6); }); test("a refresh that finds a new recording: a sweep restricted to it, then the report revised — a new iteration with its finding", async ({ request }) => { test.setTimeout(120_000); await setup(); await doneBasicSweep("synth-refreshed"); // A later build holds one recording more. await writeDraftCorpus(join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"), { channels: withRecords([LATE_RECORD]) }); const link = `${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5`; api.push( 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- She says she was not a judge: "I was not a judge at the contest this year either" [Contest results @ 0:05](${link})\n` }), textTurn("sweep.md: 1 finding."), 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 }] }), textTurn("Added the new finding."), ); const { status, body } = await draft(request, { task: "refresh", article: "synth-refreshed", model: "claude-sonnet-5-5", fetch: false }); expect(status, body.error).toBe(200); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); const tail = (job.tail ?? []).join("\n"); expect(job.job?.status ?? job.status, tail).toBe("done"); expect(tail).toMatch(/"refresh":\{"status":"updated","newIds":1,"changed":0,"drifted":0,"deleted":0/); expect(api.remaining()).toBe(0); const dir = join(testPaths().transcriptsDir, "reports", "synth-refreshed", "iterations", "2"); const f = JSON.parse(await readFile(join(dir, "refresh.json"), "utf8")); expect(f).toMatchObject({ status: "updated", delta: { newIds: ["contest-stream-04"] }, update: { sweep: { ids: ["contest-stream-04"], findings: 1 }, revision: { status: "done" } } }); const report = JSON.parse(await readFile(join(dir, "report.json"), "utf8")); expect(Object.values(report.citations).some((c) => (c as { id?: string }).id === "contest-stream-04")).toBe(true); const ledger = await readFile(join(testPaths().transcriptsDir, ".generation-usage.jsonl"), "utf8"); expect(ledger).toContain('"task":"refresh"'); }); test("a refresh through the editor's own door: the channel's sync and its report run as jobs, then the delta", async ({ request }) => { test.setTimeout(150_000); await setup({}, "two-slow-channels"); // slow-b without its --test-slow flag: a sync that finishes in seconds. await writeChannelConfig("slow-b", { name: "Slow B", url: "https://www.youtube.com/@slow-b/videos" }); // A composed build holding slow-b, and an article citing it. const rec = { ...LATE_RECORD, channelSlug: "slow-b", channel: "Slow B", slug: "slow-b/contest-stream-04" }; const build = join(testPaths().transcriptsDir, ".export-builds", "slowb", "out"); await writeDraftCorpus(build, { channels: [{ slug: "slow-b", name: "Slow B", platform: "youtube", records: [rec] }] }); const report = { format: "archilyzer-report", version: 1, id: "slowb-refresh", kind: "sweep", title: "Slow B on the contest", summary: "One finding.", citations: { c1: { kind: "video", channel: "slow-b", id: "contest-stream-04", start: 5, end: 9.8, quote: "I was not a judge at the contest this year either" } }, sections: [{ id: "s1", title: "The contest", body: "She [was not a judge](cite:c1)." }], }; await doneBasicSweep("slowb-refresh", { channel: "slow-b", report, build }); const { status, body } = await draft(request, { task: "refresh", article: "slowb-refresh" }); expect(status, body.error).toBe(200); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 120_000); const tail = (job.tail ?? []).join("\n"); expect(job.job?.status ?? job.status, tail).toBe("done"); const f = JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", "slowb-refresh", "iterations", "2", "refresh.json"), "utf8")); const sync = f.fetch.find((s: { action: string }) => s.action === "sync"); expect(sync, JSON.stringify(f.fetch)).toMatchObject({ channel: "slow-b", status: "done" }); expect(sync.jobId).toBeTruthy(); expect(f.fetch.find((s: { action: string }) => s.action === "refresh-report")).toMatchObject({ status: "done" }); expect(f.status).toBe("no-change"); }); // ─── recurring reports, wired to R4 (umtool R5) ─── // // `report-schedule` tick-now over the fake model: a SERIES edition (stage 1 // through the editor's own door — the channel's sync as a job, the build not // a site's and read as it stands, said as a warning — the window check over // the build, then the sweep with from/to) and a LIVING report's refresh (its // own stage 1, then what changed: no change, $0). The window is yesterday on // UTC (daily, tz UTC), the build holding a recording from yesterday. async function schedule(request: APIRequestContext, data: Record) { const res = await request.post(`${baseUrl}/api/ops/report-schedule`, { headers: AUTH, data }); return { status: res.status(), body: (await res.json()) as Record & { ok?: boolean; error?: string; jobId?: string } }; } const reportsDir = () => join(testPaths().transcriptsDir, "reports"); const seriesJson = async (id: string) => JSON.parse(await readFile(join(reportsDir(), ".series", id, "series.json"), "utf8")); test("a recurring series ticks over the fake model: stage 1 through the editor's door, then an edition over yesterday", async ({ request }) => { test.setTimeout(180_000); await setup(); // The channel is this editor's (a sync runs the fake yt-dlp); the build holds a recording from yesterday (UTC). await writeChannelConfig("synth-kitchen", { name: "Synth Kitchen" }); const y = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10); await writeDraftCorpus(join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"), { channels: withRecords([{ ...LATE_RECORD, id: "contest-stream-y", slug: "synth-kitchen/contest-stream-y", uploadDate: y.replace(/-/g, "") }]), }); const r = await run("sweep-agent"); api.push(...r.turns); const made = await schedule(request, { action: "create", shape: "series", id: "r5-wired", topic: "Contest", question: r.question, channels: r.channels, cadence: "daily 06:00", tz: "UTC", model: r.model }); expect(made.status, made.body.error).toBe(200); const tick = await schedule(request, { action: "tick-now", id: "r5-wired" }); expect(tick.status, tick.body.error).toBe(200); const job = await jobUntil(request, tick.body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 150_000); const tail = (job.tail ?? []).join("\n"); expect(job.job?.status ?? job.status, tail).toBe("done"); const s = await seriesJson("r5-wired"); const t = s.ticks.at(-1); expect(t, tail).toMatchObject({ status: "done", edition: 1, article: `r5-wired-${new Date().toISOString().slice(0, 10)}` }); expect(t.usd).toBeGreaterThan(0); // The build is no site's: read as it stands, said on the tick. expect((t.warnings ?? []).join("\n")).toMatch(/draft-e2e/); expect(s.editions[0]).toMatchObject({ n: 1, status: "done", window: { from: y, to: y }, title: `Contest · ${y}`, iteration: 1 }); const it = await iterationJson(t.article, 1); expect(it).toMatchObject({ kind: "sweep", status: "done", scope: { channels: ["synth-kitchen"], from: y, to: y } }); const report = JSON.parse(await readFile(join(reportsDir(), t.article, "iterations", "1", "report.json"), "utf8")); expect(report.title).toBe(`Contest · ${y}`); // Stage 1 ran the channel's sync through the editor (a job of its own). expect(tail).toMatch(/stage 1: [1-9]\d* fetch(es)? done/); expect(api.remaining()).toBe(0); }); test("a living report ticks: R4's refresh runs its own stage 1, then nothing changed — no change, $0, nothing made current", async ({ request }) => { test.setTimeout(180_000); await setup(); await writeChannelConfig("synth-kitchen", { name: "Synth Kitchen" }); await doneBasicSweep("r5-living"); // The current report: i1. await writeFile(join(reportsDir(), "r5-living", "iterations", "current.json"), JSON.stringify({ format: "archilyzer-iterations-current", version: 1, report: 1, reportFrom: 1, video: null })); const made = await schedule(request, { action: "create", shape: "living", article: "r5-living", topic: "The contest", channels: ["synth-kitchen"], cadence: "weekly mon 06:00", tz: "UTC", autoMakeCurrent: true }); expect(made.status, made.body.error).toBe(200); const tick = await schedule(request, { action: "tick-now", id: "r5-living" }); expect(tick.status, tick.body.error).toBe(200); const job = await jobUntil(request, tick.body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 150_000); const tail = (job.tail ?? []).join("\n"); expect(job.job?.status ?? job.status, tail).toBe("done"); const s = JSON.parse(await readFile(join(reportsDir(), "r5-living", "schedule.json"), "utf8")); expect(s.ticks.at(-1), tail).toMatchObject({ status: "no-change", usd: 0, iteration: 2, article: "r5-living" }); expect(s.ticks.at(-1).reason).toMatch(/^Nothing new since/); const f = JSON.parse(await readFile(join(reportsDir(), "r5-living", "iterations", "2", "refresh.json"), "utf8")); expect(f.status).toBe("no-change"); expect(f.fetch.find((x: { action: string }) => x.action === "sync")).toMatchObject({ channel: "synth-kitchen", status: "done" }); // autoMakeCurrent acts only on `updated`. const cur = JSON.parse(await readFile(join(reportsDir(), "r5-living", "iterations", "current.json"), "utf8")); expect(cur.report).toBe(1); }); // ─── triage first: a watch (umtool R6) ─── // // `report-schedule` tick-now on a WATCH over the fake models: stage 1 through // the editor's own door, then the triage — `report-draft {"task":"triage"}` on // draft:local, the window judge on a fake OLLAMA (started here; the GPU // arbiter in front of it), $0 — then, at or above the threshold, the sweep of // the flagged ids on the fake Anthropic. Tick 1: a recording from yesterday // is a candidate, the judge calls its line a mention only: below the // threshold, no article, $0, the triage on the tick line. Tick 2: a recording // UPLOADED LONG AGO is new BY ID (its transcript "landed late"), the judge // flags it strong: escalated — a sweep restricted to it, as the watch's // article, its trace's first line after the start the triage's tiers. test("a watch ticks over the fake models: below the threshold (a mention only) — no article, $0; a late transcript new by id, flagged strong — escalated to a sweep of it", async ({ request }) => { test.setTimeout(240_000); let ol: FakeOllama | null = null; try { ol = await startFakeOllama(); await setup(); // The triage runs on the local model: the fake ollama. const settings = JSON.parse(await readFile(testPaths().settingsFile, "utf8")); await writeSettings({ ...settings, generation: { ...settings.generation, ollamaUrl: ol.url } }); await writeChannelConfig("synth-kitchen", { name: "Synth Kitchen" }); const build = join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"); const y = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10); await writeDraftCorpus(build, { channels: withRecords([{ ...LATE_RECORD, uploadDate: y.replace(/-/g, "") }]) }); const made = await schedule(request, { action: "create", shape: "watch", id: "r6-watch", topic: "Contest watch", question: "Did she judge the contest?", channels: ["synth-kitchen"], terms: "contest", cadence: "daily 06:00", tz: "UTC", model: "claude-sonnet-5-5" }); expect(made.status, made.body.error).toBe(200); // Tick 1: the judge calls the new line a mention only. ol.push(jsonReply({ relevant: true, items: [{ quote: "the contest results came out today", claim: "She mentions the results.", on_topic: true, strength: 1 }] })); const before = api.requests.length; const t1 = await schedule(request, { action: "tick-now", id: "r6-watch" }); expect(t1.status, t1.body.error).toBe(200); const job1 = await jobUntil(request, t1.body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 150_000); const tail1 = (job1.tail ?? []).join("\n"); expect(job1.job?.status ?? job1.status, tail1).toBe("done"); let s = await seriesJson("r6-watch"); const below = s.ticks.at(-1); expect(below, tail1).toMatchObject({ status: "no-change", usd: 0, triage: { k: 1, status: "done", candidates: 1, flagged: 0, dismissed: 1, escalated: false } }); expect(below.article).toBeUndefined(); expect(below.reason).toMatch(/^triage: no flag \(threshold: 1 strong or 3 weak\) — below the threshold/); expect(api.requests.length, "no API call below the threshold").toBe(before); expect(ol.unloads.length).toBeGreaterThan(0); const f1 = JSON.parse(await readFile(join(reportsDir(), ".triage", "r6-watch", "1", "triage.json"), "utf8")); expect(f1).toMatchObject({ status: "done", provider: "local", cost: { tier0: 0, tier1: 0 }, tier0: { newBy: "date", candidates: [{ id: "contest-stream-04" }] } }); expect(f1.tier1.dismissed[0]).toMatchObject({ id: "contest-stream-04", stage: "score", reason: "a mention only — She mentions the results." }); const seen = JSON.parse(await readFile(join(reportsDir(), ".triage", "r6-watch", "seen.json"), "utf8")); expect(seen.ids).toContain("contest-stream-04"); // Tick 2: an old recording whose transcript landed late — new by id; flagged strong. const late = { ...LATE_RECORD, id: "contest-old-05", slug: "synth-kitchen/contest-old-05", title: "An old contest stream", uploadDate: "20250301", cues: [ { start: 0, end: 4.8, text: "back then the contest was smaller" }, { start: 5, end: 9.8, text: "I judged the contest that year myself" }, { start: 10, end: 14.8, text: "we baked forty pies" }, ] }; await writeDraftCorpus(build, { channels: withRecords([{ ...LATE_RECORD, uploadDate: y.replace(/-/g, "") }, late]) }); ol.push(jsonReply({ relevant: true, items: [{ quote: "I judged the contest that year myself", claim: "She says she judged the contest that year.", on_topic: true, strength: 3 }] })); const link = `${ORIGIN}/?v=synth-kitchen%2Fcontest-old-05&t=5`; api.push( toolTurn("enumerate_matches", { query: "contest", channels: ["synth-kitchen"] }), toolTurn("write_report", { markdown: `# She judged it once\n\nAn old stream, newly transcribed.\n\n## The contest\n\n- She says she judged the contest that year: "I judged the contest that year myself" [An old contest stream @ 0:05](${link})\n` }), textTurn("sweep.md: 1 finding."), ); const t2 = await schedule(request, { action: "tick-now", id: "r6-watch" }); expect(t2.status, t2.body.error).toBe(200); const job2 = await jobUntil(request, t2.body.jobId!, (st) => ["done", "failed", "cancelled"].includes(st), 180_000); const tail2 = (job2.tail ?? []).join("\n"); expect(job2.job?.status ?? job2.status, tail2).toBe("done"); s = await seriesJson("r6-watch"); const up = s.ticks.at(-1); const article = `r6-watch-${new Date().toISOString().slice(0, 10)}`; expect(up, tail2).toMatchObject({ status: "done", article, iteration: 1, triage: { k: 2, candidates: 1, flagged: 1, escalated: true, ids: ["contest-old-05"], usd: { tier1: 0 } } }); expect(up.usd).toBeGreaterThan(0); expect(up.triage.top[0]).toMatchObject({ id: "contest-old-05", line: "I judged the contest that year myself", score: 3 }); const f2 = JSON.parse(await readFile(join(reportsDir(), ".triage", "r6-watch", "2", "triage.json"), "utf8")); expect(f2).toMatchObject({ tier0: { newBy: "id", candidates: [{ id: "contest-old-05", date: "2025-03-01" }] }, escalation: { escalate: true, strong: 1 } }); expect(f2.tier1.flags[0]).toMatchObject({ f: "f1", id: "contest-old-05", strength: "strong", checked: "cues", at: 5 }); // The sweep: restricted to the flagged id, the triage named, its trace's first line after the start the tiers. const it = await iterationJson(article, 1); expect(it).toMatchObject({ kind: "sweep", status: "done", scope: { ids: ["contest-old-05"], triage: { owner: "r6-watch", k: 2 } } }); const trace = (await readFile(join(reportsDir(), article, "iterations", "1", "trace.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); expect(trace[0]).toMatchObject({ t: "run", phase: "start" }); expect(trace[1]).toMatchObject({ t: "triage", owner: "r6-watch", k: 2, flagged: ["contest-old-05"], escalated: true }); const report = JSON.parse(await readFile(join(reportsDir(), article, "iterations", "1", "report.json"), "utf8")); expect(report.title).toBe(`Contest watch · ${new Date().toISOString().slice(0, 10)}`); expect(Object.values(report.citations).map((c) => (c as { id?: string }).id)).toEqual(["contest-old-05"]); expect(api.remaining()).toBe(0); expect(ol.remaining()).toBe(0); } finally { await ol?.close(); } }); // ─── learned spellings (umtool R6.3) ─── // // A watch whose terms name someone ("Pia Tartlet": invented) over the fake // ollama. Its create starts the proposal pass (a report-draft job on // draft:local): the model proposes two spellings; the code counts each in // scope over the build (one is there, one is not: dropped "no-hits"); the // judge says the found one means her, quoting the line — checked verbatim in // the window and the cues — and learned.json keeps it. The next tick's // candidate query carries it ("terms + 1 learned"): a recording only the // learned spelling matches is a candidate, named for it. test("a watch learns a spelling over the fake model: proposed, counted in scope, confirmed by the judge quoting the line; the next tick's query carries it", async ({ request }) => { test.setTimeout(240_000); let ol: FakeOllama | null = null; try { ol = await startFakeOllama(); await setup(); const settings = JSON.parse(await readFile(testPaths().settingsFile, "utf8")); await writeSettings({ ...settings, generation: { ...settings.generation, ollamaUrl: ol.url } }); await writeChannelConfig("synth-kitchen", { name: "Synth Kitchen" }); const build = join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"); const y = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10); const guest = { ...LATE_RECORD, id: "pia-guest-06", slug: "synth-kitchen/pia-guest-06", title: "Guest judge night", uploadDate: y.replace(/-/g, ""), cues: [ { start: 0, end: 4.8, text: "welcome to the pie stream" }, { start: 5, end: 9.8, text: "tonight pia tart lit is judging the contest" }, { start: 10, end: 14.8, text: "she runs the bakery downtown" }, ], }; // Two older streams name her the same way (not new to the tick: before its window). const older = (id: string, date: string, line: string) => ({ ...LATE_RECORD, id, slug: `synth-kitchen/${id}`, title: `Older stream ${id}`, uploadDate: date, cues: [ { start: 0, end: 4.8, text: "good evening chat" }, { start: 5, end: 9.8, text: line }, ], }); await writeDraftCorpus(build, { channels: withRecords([guest, older("pia-old-07", "20260301", "last time pia tart lit brought cherry pies"), older("pia-old-08", "20260401", "pia tart lit says hello to everyone")]) }); // The model, by what it is asked: proposals, the confirmation, the window judge. const sys = (b: { messages?: { role: string; content: string }[] }) => b.messages?.find((m) => m.role === "system")?.content ?? ""; const route = (b: { messages?: { role: string; content: string }[] }) => { const s = sys(b); if (/mishears names\. Given a name/.test(s)) return jsonReply({ spellings: ["pia tart lit", "Pea Tartlet", "Pia Tartlet"] }); if (/whether the given spelling/.test(s)) { // The excerpt's line holding the spelling, as an honest judge quotes it. const user = b.messages?.find((m) => m.role === "user")?.content ?? ""; const line = user.split("\n").map((l) => l.replace(/^\[[\d:]+\]\s*/, "")).find((l) => /pia tart lit/.test(l) && !l.includes(":") && !l.includes("?")) ?? ""; return jsonReply({ means: true, quote: line, reason: "the guest judge, named" }); } return jsonReply({ relevant: false, items: [], heard: [] }); }; for (let i = 0; i < 12; i++) ol.push(route); const made = await schedule(request, { action: "create", shape: "watch", id: "r63-watch", topic: "Guest watch", question: "Who judged the contest?", channels: ["synth-kitchen"], terms: "Pia Tartlet", cadence: "daily 06:00", tz: "UTC" }); expect(made.status, made.body.error).toBe(200); const learn = made.body.learn as { jobId?: string; names?: string[]; refused?: string }; expect(learn, JSON.stringify(made.body)).toMatchObject({ names: ["Pia Tartlet"] }); const lj = await jobUntil(request, learn.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 150_000); const ltail = (lj.tail ?? []).join("\n"); expect(lj.job?.status ?? lj.status, ltail).toBe("done"); expect(ltail).toMatch(/@@report-draft .*"task":"learn"/); const learned = JSON.parse(await readFile(join(reportsDir(), ".series", "r63-watch", "learned.json"), "utf8")); expect(learned, ltail).toMatchObject({ owner: "r63-watch", termsKey: "lit:Pia Tartlet", passes: [{ trigger: "create", status: "done", names: ["Pia Tartlet"], proposed: 2, kept: 1 }] }); expect(learned.learned).toHaveLength(1); // Confirmed in all three windows (at least 2 needed); the newest is its proving line. expect(learned.learned[0]).toMatchObject({ spelling: "pia tart lit", means: "Pia Tartlet", quote: "tonight pia tart lit is judging the contest", recording: "pia-guest-06", channel: "synth-kitchen", start: 5, hits: 3, source: "proposed" }); expect(learned.learned[0].windows.map((w: { recording: string; means: boolean; verbatim: boolean }) => [w.recording, w.means, w.verbatim])).toEqual([ ["pia-guest-06", true, true], ["pia-old-08", true, true], ["pia-old-07", true, true], ]); expect(learned.dropped).toMatchObject([{ spelling: "Pea Tartlet", reason: "no-hits" }]); expect(ol.unloads.length).toBeGreaterThan(0); // The next tick: no pass due (proposed just now, the same terms); the learned spelling brings the candidate. const t = await schedule(request, { action: "tick-now", id: "r63-watch" }); expect(t.status, t.body.error).toBe(200); const tj = await jobUntil(request, t.body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 150_000); const ttail = (tj.tail ?? []).join("\n"); expect(tj.job?.status ?? tj.status, ttail).toBe("done"); const s = await seriesJson("r63-watch"); expect(s.ticks.at(-1), ttail).toMatchObject({ status: "no-change", usd: 0, triage: { k: 1, candidates: 1, learned: 1 } }); expect(s.ticks.at(-1).learn).toBeUndefined(); const f = JSON.parse(await readFile(join(reportsDir(), ".triage", "r63-watch", "1", "triage.json"), "utf8")); expect(f).toMatchObject({ learned: { n: 1, spellings: ["pia tart lit"] }, tier0: { candidates: [{ id: "pia-guest-06", by: ["learned"], learned: ["pia tart lit"] }], learned: { spellings: ["pia tart lit"], matched: 1 } } }); expect(f.summary).toMatch(/· terms \+ 1 learned —/); // The judge was told which names to listen for. const judged = ol.requests.find((b) => /The transcript may mishear these watched names: "Pia Tartlet"/.test(sys(b as never))); expect(judged, "the window judge was asked for heard spans").toBeTruthy(); // Its use is on the spelling (one candidate, none flagged). const after = JSON.parse(await readFile(join(reportsDir(), ".series", "r63-watch", "learned.json"), "utf8")); expect(after.learned[0].uses).toMatchObject([{ k: 1, candidates: 1, flagged: 0 }]); } finally { await ol?.close(); } });