// The release 27 test kit proves itself: the fake Anthropic and ollama servers // enforce what they claim to, and the synthetic fixtures convert cleanly and // match the committed derived files. import { 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 { fileURLToPath } from "node:url"; import { FAKE_KEY, errorTurn, pauseTurn, startFakeAnthropic, textTurn, thinkingBlock, toolTurn, turn, textBlock, webSearchBlocks, imagesOf, imageTokens, } from "./llm/fakeAnthropic.mjs"; import { faultReply, jsonReply, startFakeOllama, toolCallsReply, imagesOf as ollamaImagesOf } from "./llm/fakeOllama.mjs"; import { execFileSync } from "node:child_process"; import { CHANNELS, cuesOf, writeDraftCorpus } from "./draft/corpus.mjs"; import { DERIVED, SWEEPS, convertFixture, deriveFixture } from "./draft/derive"; import { validateReport } from "../lib/report/validate"; import { pageFileName } from "../lib/manifest"; const HERE = path.dirname(fileURLToPath(import.meta.url)); async function post(url: string, body: unknown, headers: Record = {}) { const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), }); return { status: res.status, json: (await res.json()) as any }; } const auth = { "x-api-key": FAKE_KEY, "anthropic-version": "2023-06-01" }; const user = (text: string) => ({ role: "user", content: text }); // ─── Fake Anthropic ─── test("fake Anthropic: a wrong key is a 401; a scripted turn answers; an empty script is a 500", async () => { const api = await startFakeAnthropic({ turns: [textTurn("hello")] }); try { const base = { model: "claude-opus-5-5", max_tokens: 100, messages: [user("hi")] }; assert.equal((await post(`${api.url}/v1/messages`, base, { ...auth, "x-api-key": "nope" })).status, 401); const ok = await post(`${api.url}/v1/messages`, base, auth); assert.equal(ok.status, 200); assert.equal(ok.json.content[0].text, "hello"); assert.equal(ok.json.stop_reason, "end_turn"); const done = await post(`${api.url}/v1/messages`, base, auth); assert.equal(done.status, 500); assert.match(done.json.error.message, /script exhausted/); } finally { await api.close(); } }); test("fake Anthropic: Sonnet 5.5 refuses temperature, a forced tool_choice and thinking disabled", async () => { const api = await startFakeAnthropic({ turns: [textTurn("a"), textTurn("b")] }); try { const base = { model: "claude-sonnet-5-5", max_tokens: 100, messages: [user("hi")] }; for (const extra of [ { temperature: 0.2 }, { tool_choice: { type: "tool", name: "answer" } }, { tool_choice: { type: "any" } }, { thinking: { type: "disabled" } }, ]) { const r = await post(`${api.url}/v1/messages`, { ...base, ...extra }, auth); assert.equal(r.status, 400, JSON.stringify(extra)); assert.equal(r.json.error.type, "invalid_request_error"); } const ok = await post( `${api.url}/v1/messages`, { ...base, thinking: { type: "between_tools" }, tool_choice: { type: "auto" } }, auth, ); assert.equal(ok.status, 200); // Another model takes a temperature. const opus = await post(`${api.url}/v1/messages`, { ...base, model: "claude-opus-5-5", temperature: 0.2 }, auth); assert.equal(opus.status, 200); } finally { await api.close(); } }); test("fake Anthropic: a signed thinking block holds while history is append-only, and is refused once edited", async () => { const api = await startFakeAnthropic({ turns: [turn([thinkingBlock("plan"), textBlock("first")]), textTurn("second"), textTurn("never")], }); try { const m1 = [user("one")]; const r1 = await post(`${api.url}/v1/messages`, { model: "claude-sonnet-5-5", max_tokens: 100, messages: m1 }, auth); assert.ok(r1.json.content[0].signature); const m2 = [...m1, { role: "assistant", content: r1.json.content }, user("two")]; const r2 = await post(`${api.url}/v1/messages`, { model: "claude-sonnet-5-5", max_tokens: 100, messages: m2 }, auth); assert.equal(r2.status, 200); const edited = [user("one, edited"), ...m2.slice(1)]; const r3 = await post(`${api.url}/v1/messages`, { model: "claude-sonnet-5-5", max_tokens: 100, messages: edited }, auth); assert.equal(r3.status, 400); assert.match(r3.json.error.message, /signature/); } finally { await api.close(); } }); test("fake Anthropic: tool_use, server web search, pause_turn, scripted errors and functions", async () => { const api = await startFakeAnthropic({ turns: [ toolTurn("search_transcripts", { query: "oven" }), pauseTurn(webSearchBlocks("synth kitchen", [{ url: "https://web.example/a", title: "A" }])), errorTurn(529, "overloaded_error", "overloaded", { "retry-after": "1" }), (body) => textTurn(`saw ${body.messages.length}`), ], }); try { const base = { model: "claude-opus-5-5", max_tokens: 100, messages: [user("hi")] }; const a = await post(`${api.url}/v1/messages`, base, auth); assert.equal(a.json.stop_reason, "tool_use"); assert.equal(a.json.content[0].name, "search_transcripts"); const b = await post(`${api.url}/v1/messages`, base, auth); assert.equal(b.json.stop_reason, "pause_turn"); assert.deepEqual( b.json.content.map((x: any) => x.type), ["server_tool_use", "web_search_tool_result"], ); const c = await post(`${api.url}/v1/messages`, base, auth); assert.equal(c.status, 529); const d = await post(`${api.url}/v1/messages`, { ...base, messages: [user("a"), user("b")] }, auth); assert.equal(d.json.content[0].text, "saw 2"); assert.equal(api.requests.length, 4); } finally { await api.close(); } }); test("fake Anthropic: with cache_control, a request extending a cached one reads its prefix", async () => { const api = await startFakeAnthropic({ turns: [textTurn("one"), textTurn("two")] }); try { const base = { model: "claude-opus-5-5", max_tokens: 100, system: "rules ".repeat(200), cache_control: { type: "ephemeral" } }; const m1 = [user("first question")]; const r1 = await post(`${api.url}/v1/messages`, { ...base, messages: m1 }, auth); assert.equal(r1.json.usage.cache_read_input_tokens, 0); assert.ok(r1.json.usage.cache_creation_input_tokens > 0); const m2 = [...m1, { role: "assistant", content: r1.json.content }, user("next")]; const r2 = await post(`${api.url}/v1/messages`, { ...base, messages: m2 }, auth); assert.ok(r2.json.usage.cache_read_input_tokens >= r1.json.usage.cache_creation_input_tokens); } finally { await api.close(); } }); // ─── Fake ollama ─── test("fake ollama: format and tool replies, the 8k and num_ctx caps, stream refused, a fault, the unload", async () => { const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] }), toolCallsReply([{ name: "search", arguments: { q: "oven" } }]), faultReply()], }); try { const base = { model: "qwen3:8b", stream: false, think: false, messages: [user("terms?")] }; const a = await post(`${ol.url}/api/chat`, { ...base, format: { type: "object" } }); assert.deepEqual(JSON.parse(a.json.message.content), { terms: ["oven"] }); const b = await post(`${ol.url}/api/chat`, { ...base, tools: [{ type: "function", function: { name: "search" } }] }); assert.equal(b.json.message.tool_calls[0].function.name, "search"); assert.equal((await post(`${ol.url}/api/chat`, { ...base, options: { num_ctx: 13800 } })).status, 400); assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [user("x".repeat(40_000))] })).status, 400); assert.equal((await post(`${ol.url}/api/chat`, { ...base, stream: true })).status, 400); const f = await post(`${ol.url}/api/chat`, base); assert.equal(f.json.done, false); assert.deepEqual(ol.loaded(), ["qwen3:8b"]); const u = await post(`${ol.url}/api/chat`, { model: "qwen3:8b", messages: [], keep_alive: 0 }); assert.equal(u.json.done_reason, "unload"); assert.deepEqual(ol.unloads, ["qwen3:8b"]); assert.deepEqual(ol.loaded(), []); assert.equal((await post(`${ol.url}/api/chat`, { ...base, model: "qwen3:14b" })).status, 404); } finally { await ol.close(); } }); // ─── Images (release 30, the frame scan) ─── // A tiny real JPEG and PNG, made by ffmpeg (no binary fixture in the tree). function tinyImage(kind: "mjpeg" | "png"): string { return execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=64x36:d=1", "-frames:v", "1", "-c:v", kind, "-f", "image2pipe", "pipe:1"]).toString("base64"); } test("fake Anthropic: an image block must be base64 of the type it names, in a user turn; usage counts it by size", async () => { const jpeg = tinyImage("mjpeg"); const png = tinyImage("png"); const api = await startFakeAnthropic({ turns: [textTurn("ok")] }); try { const img = (media_type: string, data: string) => ({ type: "image", source: { type: "base64", media_type, data } }); const ask = (content: unknown[], role = "user") => post(`${api.url}/v1/messages`, { model: "claude-haiku-4-5", max_tokens: 10, messages: [{ role, content }] }, auth); assert.equal((await ask([img("image/jpeg", png)])).status, 400); assert.equal((await ask([img("image/png", "not base64!")])).status, 400); assert.equal((await ask([img("image/tiff", jpeg)])).status, 400); const ok = await ask([img("image/jpeg", jpeg), { type: "text", text: "read it" }]); assert.equal(ok.status, 200); assert.ok(ok.json.usage.input_tokens >= imageTokens(64, 36) && ok.json.usage.input_tokens < 100, String(ok.json.usage.input_tokens)); assert.deepEqual(imagesOf(api.requests[api.requests.length - 1]).map((i) => [i.mediaType, i.width, i.height]), [["image/jpeg", 64, 36]]); assert.equal(imageTokens(1280, 720), 1229); } finally { await api.close(); } }); test("fake ollama: a message's images must be base64 images, each counted at a fixed cost against the cap", async () => { const jpeg = tinyImage("mjpeg"); const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: [jsonReply({ ok: true })] }); try { const base = { model: "qwen2.5vl:7b", stream: false, messages: [{ role: "user", content: "read", images: [jpeg] }] }; assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [{ role: "user", content: "read", images: ["!!"] }] })).status, 400); assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [{ role: "user", content: "read", images: Array(7).fill(jpeg) }] })).status, 400); const ok = await post(`${ol.url}/api/chat`, base); assert.equal(ok.status, 200); assert.ok(ok.json.prompt_eval_count >= 1200 && ok.json.prompt_eval_count < 1300); assert.equal(ollamaImagesOf(ol.requests[ol.requests.length - 1])[0].width, 64); } finally { await ol.close(); } }); // ─── Fixtures ─── test("fixtures: every sweep converts with no problems, and every report validates", async () => { for (const name of SWEEPS) { const { report, problems } = await convertFixture(name); assert.deepEqual(problems, [], name); assert.deepEqual(validateReport(report), [], name); } }); test("fixtures: the committed reports and manifests are what the converters make today (else run regenerate.ts)", async () => { for (const name of DERIVED) { const { report, manifest } = await deriveFixture(name); const committed = (dir: string, file: string) => readFile(path.join(HERE, "draft", dir, file), "utf8").then(JSON.parse); assert.deepEqual(report, await committed("reports", `${name}.report.json`), `${name} report`); assert.deepEqual(manifest, await committed("manifests", `${name}.video.manifest.json`), `${name} manifest`); } }); test("fixtures: the corpus has cues for every record and writes the shard layout the MCP reads", async () => { for (const c of CHANNELS) for (const r of c.records) assert.ok((await cuesOf(c.slug, r.id))?.length, r.slug); assert.equal(await cuesOf("synth-kitchen", "nope"), null); const dir = await mkdtemp(path.join(os.tmpdir(), "draft-corpus-")); try { await writeDraftCorpus(dir); const shard = JSON.parse(await readFile(path.join(dir, "transcripts", "synth-kitchen", pageFileName(0)), "utf8")); assert.equal(shard.length, 3); const corpus = JSON.parse(await readFile(path.join(dir, "corpus.json"), "utf8")); assert.deepEqual( corpus.channels.map((c: any) => c.slug), ["synth-kitchen", "synth-other"], ); } finally { await rm(dir, { recursive: true, force: true }); } }); test("fixtures: the ruled fact-check (release 28) validates, carries every verdict, and quotes the corpus", async () => { const report = JSON.parse(await readFile(path.join(HERE, "draft", "reports", "ruled.report.json"), "utf8")); assert.deepEqual(validateReport(report), []); const claims = report.sections.flatMap((s: any) => s.claims ?? []); assert.deepEqual( [...new Set(claims.map((c: any) => c.verdict))].sort(), ["CONTRADICTED", "CORROBORATED", "NOT_FOUND", "PARTLY", "UNTESTABLE"], ); for (const [id, c] of Object.entries(report.citations)) { const cue = (await cuesOf(c.channel, c.id))?.find((q: any) => q.start === c.start); assert.equal(cue?.text, c.quote, id); } }); // ─── Release 29: Bluesky, Wayback, a gone recording ─── test("fake Bluesky: handle → DID, getPosts answers only live posts with fullsize images, the page and its images serve", async () => { const { startFakeBluesky, ACCOUNTS, BSKY_POSTS } = await import("./social/fakeBluesky.mjs"); const bsky = await startFakeBluesky({ busyTimes: 1 }); try { const [acct] = ACCOUNTS; const resolve = `https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${acct.handle}`; assert.equal((await bsky.fetch(resolve)).status, 429); assert.equal(((await (await bsky.fetch(resolve)).json()) as any).did, acct.did); const uris = BSKY_POSTS.map((p) => `at://${acct.did}/app.bsky.feed.post/${p.rkey}`); const q = new URLSearchParams(); for (const u of uris) q.append("uris", u); const got = (await (await bsky.fetch(`https://public.api.bsky.app/xrpc/app.bsky.feed.getPosts?${q}`)).json()) as any; assert.equal(got.posts.length, BSKY_POSTS.filter((p) => !p.deleted).length); const withImages = got.posts.find((p: any) => p.embed?.images?.length); const img = await bsky.fetch(withImages.embed.images[0].fullsize); assert.equal(img.headers.get("content-type"), "image/png"); const page = await (await fetch(bsky.pageUrl(acct.handle, BSKY_POSTS[0].rkey))).text(); assert.match(page, new RegExp(`data-testid="postThreadItem-by-${acct.handle.replace(/\./g, "\\.")}"`)); const gone = BSKY_POSTS.find((p) => p.deleted)!; assert.match(await (await fetch(bsky.pageUrl(acct.handle, gone.rkey))).text(), /Post not found/); } finally { await bsky.close(); } }); test("fake Wayback: CDX json rows oldest first with a header, [] for none, a status filter, captures serve", async () => { const { startFakeWayback } = await import("./web/fakeWayback.mjs"); const { GONE_RECORD } = await import("./draft/corpus.mjs"); const wb = await startFakeWayback({ busyTimes: 1 }); try { const cdx = (url: string, extra = "") => wb.fetch(`https://web.archive.org/cdx/search/cdx?url=${encodeURIComponent(url)}&output=json${extra}`); assert.equal((await cdx(GONE_RECORD.webpageUrl)).status, 429); const rows = (await (await cdx(GONE_RECORD.webpageUrl)).json()) as string[][]; assert.equal(rows[0][1], "timestamp"); assert.equal(rows.length, 2); const ts = rows[1][1]; assert.deepEqual(await (await cdx("https://video.example/watch?v=never")).json(), []); const bread = (await (await cdx("https://video.example/watch?v=bread-day-01", "&filter=statuscode:200")).json()) as string[][]; assert.equal(bread.length, 2); const cap = await wb.fetch(`https://web.archive.org/web/${ts}/${GONE_RECORD.webpageUrl}`); assert.equal(cap.status, 200); } finally { await wb.close(); } }); test("the gone recording: deleted on its platform, cues kept, an availability.json that isPermanentlyGone", async () => { const { GONE_RECORD, GONE_AVAILABILITY, CHANNELS: base } = await import("./draft/corpus.mjs"); const { isPermanentlyGone } = await import("../lib/availability"); assert.equal(GONE_RECORD.state, "deleted"); assert.ok(GONE_RECORD.cues.length > 0); assert.ok(!base.some((c) => c.records.some((r) => r.id === GONE_RECORD.id))); assert.ok(isPermanentlyGone(GONE_AVAILABILITY.availability as any)); });