Archilyzer · Source

archilyzer

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

commit 8ba7657eb1df378dff0949f8901ff54792ff9220
parent 00b99fdd8d86005c4433af36d5ce322a181f69ca
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 10:17:20 -0400

common: the release 27 test kit — fake Anthropic and ollama servers, a synthetic corpus and sweep fixtures

common/testing/llm: a fake Messages API (scripted turns, pause_turn, server web search blocks, signed
thinking that refuses an edited history, the Sonnet 5.5 400s, cache usage) and a fake ollama (format
and tools, the 8k prompt and 12k num_ctx caps, the done:false fault, the keep_alive 0 unload).
common/testing/draft: two invented channels with cues, invented posts, six sweep.md variants and the
reports and manifests the converters make of three of them (regenerate.ts; fakes.test.ts checks them).
Exported as yt-dlp-transcript-common/testing/*; the common test glob reaches three levels.

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

Diffstat:
Mcommon/package.json | 5+++--
Acommon/testing/README.md | 22++++++++++++++++++++++
Acommon/testing/draft/corpus.d.mts | 32++++++++++++++++++++++++++++++++
Acommon/testing/draft/corpus.mjs | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/derive.ts | 38++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/manifests/basic.video.manifest.json | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/manifests/paragraphs.video.manifest.json | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/manifests/posts-only.video.manifest.json | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/regenerate.ts | 20++++++++++++++++++++
Acommon/testing/draft/reports/basic.report.json | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/reports/paragraphs.report.json | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/reports/posts-only.report.json | 48++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/sweeps/basic.md | 15+++++++++++++++
Acommon/testing/draft/sweeps/inexact.md | 10++++++++++
Acommon/testing/draft/sweeps/multi-quote.md | 10++++++++++
Acommon/testing/draft/sweeps/paragraphs.md | 23+++++++++++++++++++++++
Acommon/testing/draft/sweeps/posts-only.md | 8++++++++
Acommon/testing/draft/sweeps/quotes-in-claims.md | 9+++++++++
Acommon/testing/fakes.test.ts | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/llm/fakeAnthropic.d.mts | 35+++++++++++++++++++++++++++++++++++
Acommon/testing/llm/fakeAnthropic.mjs | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/llm/fakeOllama.d.mts | 34++++++++++++++++++++++++++++++++++
Acommon/testing/llm/fakeOllama.mjs | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
23 files changed, 1540 insertions(+), 2 deletions(-)

diff --git a/common/package.json b/common/package.json @@ -49,10 +49,11 @@ "./ytdlp/*": "./ytdlp/*.ts", "./bin/*": "./bin/*.ts", "./styles/*.css": "./styles/*.css", - "./styles/*": "./styles/*.ts" + "./styles/*": "./styles/*.ts", + "./testing/*": "./testing/*" }, "scripts": { - "test": "tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin}/*/*.test.ts\"" + "test": "tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\"" }, "dependencies": { "@aws-sdk/client-s3": "^3.1080.0", diff --git a/common/testing/README.md b/common/testing/README.md @@ -0,0 +1,22 @@ +# Test kit + +Helpers for tests only; nothing in an app imports from here. Importable from every package as +`yt-dlp-transcript-common/testing/<path>` (the `.mjs` files carry `.d.mts` types, so the umtool +`node --test` suites can use them too). + +## Generation (release 27) + +Everything here is **synthetic**: invented channels, recordings, lines and posts. No real +transcript, channel or person goes in these fixtures, ever. + +| File | What it is | +| --- | --- | +| `llm/fakeAnthropic.mjs` | A fake Messages API: scripted turns (`textTurn`, `toolTurn`, `pauseTurn`, `webSearchBlocks`, `thinkingBlock`, `errorTurn`, or a function of the request). It enforces the Sonnet 5.5 400s (temperature, forced `tool_choice`, `thinking: disabled`), signs thinking blocks so an edited history is refused, needs `x-api-key` = `FAKE_KEY`, and estimates usage, cache reads included. | +| `llm/fakeOllama.mjs` | A fake ollama: `/api/chat` with `format` or tools, the 8k prompt cap and the 12k `num_ctx` cap as 400s, `stream: true` refused, `faultReply()` (`done: false`), the `keep_alive: 0` unload, `/api/tags`, `/api/ps`. | +| `draft/corpus.mjs` | Two channels of recordings with cues (`CHANNELS`), posts (`POSTS`), `ORIGIN`, `momentHref`, `postHref`, `cuesOf`, `recordOf`, and `writeDraftCorpus(dir)` — a composed public dir for the MCP's `--local`. | +| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one). | +| `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. | +| `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | + +As committed (S0), the `paragraphs` manifest shows two owed bugs that release 27 S7 fixes: the title +card has no `foot`, and the Coverage section becomes a bare chapter card. S7 regenerates it. diff --git a/common/testing/draft/corpus.d.mts b/common/testing/draft/corpus.d.mts @@ -0,0 +1,32 @@ +export type FixtureCue = { start: number; end: number; text: string }; + +export type FixtureRecord = { + slug: string; + id: string; + channelSlug: string; + title: string; + uploadDate: string; + duration: number; + channel: string; + description: string; + tags: string[]; + isLivestream: boolean; + ageRestricted: boolean; + platform: string; + webpageUrl: string; + cues: FixtureCue[]; +}; + +export type FixtureChannel = { slug: string; name: string; platform: string; records: FixtureRecord[] }; + +export type FixturePost = { channelSlug: string; id: string; author: string; date: string; text: string }; + +export const ORIGIN: string; +export const CUE_STEP: number; +export const CHANNELS: FixtureChannel[]; +export const POSTS: FixturePost[]; +export function momentHref(channel: string, id: string, seconds: number, encode?: boolean): string; +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>; diff --git a/common/testing/draft/corpus.mjs b/common/testing/draft/corpus.mjs @@ -0,0 +1,183 @@ +// A SYNTHETIC corpus for the generation tests (release 27): two channels of +// invented recordings with cues, and a few invented posts. Nothing here is a +// real transcript, channel or person — every line was written for these tests. +// +// It is plain JS (with corpus.d.mts beside it) so the TS suites (tsx), the +// umtool `.mjs` suites (node --test) and the Playwright specs can all import it. +// +// CHANNELS the records, cues included +// ORIGIN the citation origin the fixture sweeps link against +// momentHref() `${ORIGIN}/?v=<channel>%2F<id>&t=<seconds>` +// postHref() `${ORIGIN}/?v=<channel>%2F<id>&vm=post` +// cuesOf() the ConvertContext reader (`common/lib/report/convertShared.ts`) +// recordOf() one record by channel and id +// writeDraftCorpus a composed public dir (corpus.json + shards), the shape +// the MCP reads with --local / TRANSCRIPT_LOCAL_DIR + +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const ORIGIN = "https://synth.example"; + +// One cue per line, CUE_STEP seconds apart, each 0.2 s short of the next. +export const CUE_STEP = 5; + +const cues = (lines) => lines.map((text, i) => ({ start: i * CUE_STEP, end: i * CUE_STEP + CUE_STEP - 0.2, text })); + +// The lines the fixture sweeps quote are marked by comment with their second. +const BREAD_DAY = [ + "welcome back to the kitchen everyone", // 0 + "today we are making a sourdough loaf", // 5 + "the starter has been going for a week", // 10 + "I would never sell the bakery to a chain", // 15 + "people keep asking me about that rumor", // 20 + "we never said that about the old oven", // 25 + "the oven was fine it just ran hot", // 30 + "let the dough rest for an hour", // 35 + "fold it four times on the counter", // 40 + "I paid for the new mixer myself", // 45 + "nobody sponsored this kitchen", // 50 + "the crust should be dark and crackly", // 55 + "slice it only when it has cooled", // 60 + "thanks for watching see you next week", // 65 +]; + +const PIE_STREAM = [ + "good evening chat welcome to the pie stream", // 0 + "a lot of you asked about the contest", // 5 + "I did not enter the contest this year", // 10 + "the judges were friends of mine so it felt wrong", // 15 + "next year maybe I will enter again", // 20 + "the filling is apples and a little lemon", // 25 + "I have never met the other finalist", // 30 + "honestly the drama around it is silly", // 35 + "my lawyer told me not to talk about the lease", // 40 + "so I will not talk about the lease", // 45 + "the pie needs forty minutes at this heat", // 50 + "that is all for tonight goodnight chat", // 55 +]; + +// Long enough that a quote two hundred seconds from its link is in the record +// but outside the strict check's ±90 s. +const QA_LONG = [ + "this is the question and answer episode", // 0 + "first question is about the bread machine", // 5 + "I do not use a bread machine at all", // 10 + ...Array.from({ length: 37 }, (_, i) => `filler line ${i + 1} about flour and water`), // 15 … 195 + "the last question is about the second shop", // 200 + "we opened the second shop in the spring", // 205 + "it was always going to be a small place", // 210 + "that is everything thank you all", // 215 +]; + +const OTHER_CHANNEL = [ + "hello from the other kitchen", // 0 + "we tried the sourdough recipe from last week", // 5 + "it came out flat the first time", // 10 + "the second loaf rose much better", // 15 +]; + +const video = (channelSlug, channel, id, title, uploadDate, lines, extra = {}) => ({ + slug: `${channelSlug}/${id}`, + id, + channelSlug, + title, + uploadDate, + duration: lines.length * CUE_STEP, + channel, + description: "", + tags: [], + isLivestream: false, + ageRestricted: false, + platform: "youtube", + webpageUrl: `https://video.example/watch?v=${id}`, + cues: cues(lines), + ...extra, +}); + +export const CHANNELS = [ + { + slug: "synth-kitchen", + name: "Synth Kitchen", + platform: "youtube", + records: [ + video("synth-kitchen", "Synth Kitchen", "bread-day-01", "Bread day", "20260105", BREAD_DAY), + video("synth-kitchen", "Synth Kitchen", "pie-stream-02", "Pie stream", "20260210", PIE_STREAM, { + isLivestream: true, + }), + video("synth-kitchen", "Synth Kitchen", "qa-long-03", "Questions and answers", "20260301", QA_LONG), + ], + }, + { + slug: "synth-other", + name: "Synth Other Kitchen", + platform: "youtube", + records: [video("synth-other", "Synth Other Kitchen", "flat-loaf-01", "The flat loaf", "20260112", OTHER_CHANNEL)], + }, +]; + +// Invented posts, as an archive keeps them (`?v=<channel>%2F<id>&vm=post`). +export const POSTS = [ + { + channelSlug: "synth-social", + id: "1700000000000000001", + author: "synthbaker", + date: "2026-02-11", + text: "No, I did not enter the pie contest. The judges are my friends.", + }, + { + channelSlug: "synth-social", + id: "1700000000000000002", + author: "synthbaker", + date: "2026-03-02", + text: "The second shop opens in the spring. Small place, big oven.", + }, +]; + +export const momentHref = (channel, id, seconds, encode = true) => + `${ORIGIN}/?v=${encode ? encodeURIComponent(`${channel}/${id}`) : `${channel}/${id}`}&t=${seconds}`; + +export const postHref = (channel, id) => `${ORIGIN}/?v=${encodeURIComponent(`${channel}/${id}`)}&vm=post`; + +export function recordOf(channel, id) { + for (const c of CHANNELS) { + if (c.slug !== channel) continue; + for (const r of c.records) if (r.id === id) return r; + } + return null; +} + +export async function cuesOf(channel, id) { + return recordOf(channel, id)?.cues ?? null; +} + +// The shard file name the index build writes (common/lib/manifest.ts pageFileName). +const pageFile = (n) => `page-${String(n).padStart(4, "0")}.json`; + +// A composed public dir: corpus.json, and per channel a manifest and one shard. +export async function writeDraftCorpus(dir) { + 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 })), + }), + ); + for (const c of CHANNELS) { + const chDir = path.join(dir, "transcripts", c.slug); + await mkdir(chDir, { recursive: true }); + await writeFile( + path.join(chDir, "manifest.json"), + JSON.stringify({ + version: 1, + channelSlug: c.slug, + pageCount: 1, + maxPageBytes: 1_000_000, + generatedAt: "2026-10-13", + slugToPage: Object.fromEntries(c.records.map((r) => [r.id, 0])), + }), + ); + await writeFile(path.join(chDir, pageFile(0)), JSON.stringify(c.records)); + } + return dir; +} diff --git a/common/testing/draft/derive.ts b/common/testing/draft/derive.ts @@ -0,0 +1,38 @@ +// How the derived fixtures are made from the sweeps (regenerate.ts writes them, +// fixtures.test.ts checks the committed files still match). + +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { sweepToReport } from "../../lib/report/convertSweep"; +import { reportToManifest, type PostOf } from "../../lib/report/convertManifest"; +import { cuesOf, ORIGIN, POSTS } from "./corpus.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +export const SWEEPS = ["basic", "quotes-in-claims", "multi-quote", "posts-only", "paragraphs", "inexact"] as const; +export type SweepName = (typeof SWEEPS)[number]; + +// The sweeps whose report and manifest are committed. +export const DERIVED = ["basic", "posts-only", "paragraphs"] as const satisfies readonly SweepName[]; + +export const readSweep = (name: SweepName) => readFile(path.join(HERE, "sweeps", `${name}.md`), "utf8"); + +export const postOf: PostOf = async (channel, id) => { + const p = POSTS.find((x) => x.channelSlug === channel && x.id === id); + return p + ? { platform: "x", url: `https://x.example/${p.author}/status/${p.id}`, createdAt: `${p.date}T12:00:00Z`, author: p.author } + : null; +}; + +export async function convertFixture(name: SweepName) { + return sweepToReport(await readSweep(name), { cuesOf, id: `synth-${name}` }); +} + +export async function deriveFixture(name: SweepName) { + const { report, problems } = await convertFixture(name); + if (problems.length) throw new Error(`${name}: ${JSON.stringify(problems)}`); + const m = await reportToManifest(report, { siteOrigin: ORIGIN, postOf, today: "2026-10-13" }); + if (!m.ok) throw new Error(`${name}: ${JSON.stringify(m.problems)}`); + return { report, manifest: m.manifest }; +} diff --git a/common/testing/draft/manifests/basic.video.manifest.json b/common/testing/draft/manifests/basic.video.manifest.json @@ -0,0 +1,129 @@ +{ + "schemaVersion": 1, + "slug": "synth-basic", + "title": "Synth Kitchen — what the baker says about the bakery", + "subtitle": "", + "generatedOn": "2026-10-13", + "provenance": { + "siteOrigin": "https://synth.example", + "channelSlug": "synth-kitchen", + "channel": "" + }, + "render": { + "width": 1920, + "height": 1080, + "fps": 30, + "audioRate": 48000, + "audioChannels": 2, + "maxHeightSource": 1080, + "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf", + "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf", + "palette": { + "bg": "#12100c", + "fg": "#f6f1e6", + "muted": "#a2957f", + "accent": "#c8752a", + "amber": "#ffc860" + }, + "transition": 0.4, + "fetchPad": 3, + "snapWindow": 1.6, + "silenceMinDur": 0.09, + "silenceRelDb": 6, + "headerHeight": 56, + "footerHeight": 0, + "crf": 21, + "preset": "slow", + "qr": { + "scale": 4, + "quiet": 3, + "ecc": "M", + "margin": 28 + } + }, + "timelineNodes": [], + "timeline": [ + { + "type": "card", + "id": "title", + "style": "title", + "seconds": 4, + "heading": "Synth Kitchen — what the baker says about the bakery", + "sub": "" + }, + { + "type": "card", + "id": "the-bakery", + "style": "chapter", + "seconds": 3.5, + "heading": "The bakery" + }, + { + "type": "clip", + "id": "c01", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 15, + "end": 19.8, + "cite": 15, + "quote": "I would never sell the bakery to a chain" + }, + { + "type": "clip", + "id": "c02", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 25, + "end": 29.8, + "cite": 25, + "quote": "we never said that about the old oven" + }, + { + "type": "clip", + "id": "c03", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 45, + "end": 49.8, + "cite": 45, + "quote": "I paid for the new mixer myself" + }, + { + "type": "card", + "id": "the-contest", + "style": "chapter", + "seconds": 3.5, + "heading": "The contest" + }, + { + "type": "clip", + "id": "c04", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 10, + "end": 14.8, + "cite": 10, + "quote": "I did not enter the contest this year" + }, + { + "type": "clip", + "id": "c05", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 15, + "end": 19.8, + "cite": 15, + "quote": "the judges were friends of mine so it felt wrong" + }, + { + "type": "clip", + "id": "c06", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 40, + "end": 44.8, + "cite": 40, + "quote": "my lawyer told me not to talk about the lease" + } + ] +} diff --git a/common/testing/draft/manifests/paragraphs.video.manifest.json b/common/testing/draft/manifests/paragraphs.video.manifest.json @@ -0,0 +1,89 @@ +{ + "schemaVersion": 1, + "slug": "synth-paragraphs", + "title": "Paragraphs between findings", + "subtitle": "", + "generatedOn": "2026-10-13", + "provenance": { + "siteOrigin": "https://synth.example", + "channelSlug": "synth-kitchen", + "channel": "" + }, + "render": { + "width": 1920, + "height": 1080, + "fps": 30, + "audioRate": 48000, + "audioChannels": 2, + "maxHeightSource": 1080, + "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf", + "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf", + "palette": { + "bg": "#12100c", + "fg": "#f6f1e6", + "muted": "#a2957f", + "accent": "#c8752a", + "amber": "#ffc860" + }, + "transition": 0.4, + "fetchPad": 3, + "snapWindow": 1.6, + "silenceMinDur": 0.09, + "silenceRelDb": 6, + "headerHeight": 56, + "footerHeight": 0, + "crf": 21, + "preset": "slow", + "qr": { + "scale": 4, + "quiet": 3, + "ecc": "M", + "margin": 28 + } + }, + "timelineNodes": [], + "timeline": [ + { + "type": "card", + "id": "title", + "style": "title", + "seconds": 4, + "heading": "Paragraphs between findings", + "sub": "" + }, + { + "type": "card", + "id": "the-second-shop", + "style": "chapter", + "seconds": 3.5, + "heading": "The second shop" + }, + { + "type": "clip", + "id": "c01", + "channel": "synth-kitchen", + "video": "qa-long-03", + "start": 205, + "end": 209.8, + "cite": 205, + "quote": "we opened the second shop in the spring" + }, + { + "type": "clip", + "id": "c02", + "channel": "synth-other", + "video": "flat-loaf-01", + "start": 5, + "end": 9.8, + "cite": 5, + "quote": "we tried the sourdough recipe from last week" + }, + { + "type": "card", + "id": "coverage", + "style": "chapter", + "seconds": 3.5, + "heading": "Coverage" + } + ] +} diff --git a/common/testing/draft/manifests/posts-only.video.manifest.json b/common/testing/draft/manifests/posts-only.video.manifest.json @@ -0,0 +1,86 @@ +{ + "schemaVersion": 1, + "slug": "synth-posts-only", + "title": "Posts only", + "subtitle": "", + "generatedOn": "2026-10-13", + "provenance": { + "siteOrigin": "https://synth.example", + "channelSlug": "", + "channel": "" + }, + "render": { + "width": 1920, + "height": 1080, + "fps": 30, + "audioRate": 48000, + "audioChannels": 2, + "maxHeightSource": 1080, + "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf", + "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf", + "palette": { + "bg": "#12100c", + "fg": "#f6f1e6", + "muted": "#a2957f", + "accent": "#c8752a", + "amber": "#ffc860" + }, + "transition": 0.4, + "fetchPad": 3, + "snapWindow": 1.6, + "silenceMinDur": 0.09, + "silenceRelDb": 6, + "headerHeight": 56, + "footerHeight": 0, + "crf": 21, + "preset": "slow", + "qr": { + "scale": 4, + "quiet": 3, + "ecc": "M", + "margin": 28 + } + }, + "timelineNodes": [], + "timeline": [ + { + "type": "card", + "id": "title", + "style": "title", + "seconds": 4, + "heading": "Posts only", + "sub": "" + }, + { + "type": "card", + "id": "posts", + "style": "chapter", + "seconds": 3.5, + "heading": "Posts" + } + ], + "posts": [ + { + "id": "p01", + "platform": "x", + "handle": "synthbaker", + "date": "2026-02-11", + "text": "No, I did not enter the pie contest.", + "url": "https://x.example/synthbaker/status/1700000000000000001", + "attachTo": null, + "siteChannel": "synth-social", + "postId": "1700000000000000001" + }, + { + "id": "p02", + "platform": "x", + "handle": "synthbaker", + "date": "2026-03-02", + "text": "The second shop opens in the spring.", + "url": "https://x.example/synthbaker/status/1700000000000000002", + "attachTo": null, + "siteChannel": "synth-social", + "postId": "1700000000000000002" + } + ] +} diff --git a/common/testing/draft/regenerate.ts b/common/testing/draft/regenerate.ts @@ -0,0 +1,20 @@ +// Regenerates reports/*.report.json and manifests/*.video.manifest.json from +// sweeps/*.md with today's converters. Run after a converter change, review the +// diff, commit it: cd common && pnpm exec tsx testing/draft/regenerate.ts +// fixtures.test.ts fails until the committed files match the converters. + +import { writeFile, mkdir } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { DERIVED, deriveFixture } from "./derive"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +for (const name of DERIVED) { + const { report, manifest } = await deriveFixture(name); + await mkdir(path.join(HERE, "reports"), { recursive: true }); + await mkdir(path.join(HERE, "manifests"), { recursive: true }); + await writeFile(path.join(HERE, "reports", `${name}.report.json`), JSON.stringify(report, null, 2) + "\n"); + await writeFile(path.join(HERE, "manifests", `${name}.video.manifest.json`), JSON.stringify(manifest, null, 2) + "\n"); + console.log(`wrote ${name}`); +} diff --git a/common/testing/draft/reports/basic.report.json b/common/testing/draft/reports/basic.report.json @@ -0,0 +1,120 @@ +{ + "format": "archilyzer-report", + "version": 1, + "id": "synth-basic", + "kind": "sweep", + "title": "Synth Kitchen — what the baker says about the bakery", + "sections": [ + { + "id": "the-bakery", + "title": "The bakery", + "claims": [ + { + "id": "k01", + "text": "She says she would not sell: \"I would never sell the bakery to a chain\"", + "citations": [ + "c01" + ] + }, + { + "id": "k02", + "text": "She denies the oven story: \"we never said that about the old oven\"", + "citations": [ + "c02" + ] + }, + { + "id": "k03", + "text": "She says she paid for the mixer: \"I paid for the new mixer myself\"", + "citations": [ + "c03" + ] + } + ] + }, + { + "id": "the-contest", + "title": "The contest", + "claims": [ + { + "id": "k04", + "text": "She says she did not enter: \"I did not enter the contest this year\"", + "citations": [ + "c04" + ] + }, + { + "id": "k05", + "text": "She gives a reason: \"the judges were friends of mine so it felt wrong\"", + "citations": [ + "c05" + ] + }, + { + "id": "k06", + "text": "She will not discuss the lease: \"my lawyer told me not to talk about the lease\"", + "citations": [ + "c06" + ] + } + ] + } + ], + "summary": "Scope: channel `synth-kitchen`, uploads from 2026-01-01 on. N = 3 recordings, all read. 2 are cited.", + "citations": { + "c01": { + "kind": "video", + "channel": "synth-kitchen", + "id": "bread-day-01", + "start": 15, + "end": 19.8, + "quote": "I would never sell the bakery to a chain", + "label": "Bread day" + }, + "c02": { + "kind": "video", + "channel": "synth-kitchen", + "id": "bread-day-01", + "start": 25, + "end": 29.8, + "quote": "we never said that about the old oven", + "label": "Bread day" + }, + "c03": { + "kind": "video", + "channel": "synth-kitchen", + "id": "bread-day-01", + "start": 45, + "end": 49.8, + "quote": "I paid for the new mixer myself", + "label": "Bread day" + }, + "c04": { + "kind": "video", + "channel": "synth-kitchen", + "id": "pie-stream-02", + "start": 10, + "end": 14.8, + "quote": "I did not enter the contest this year", + "label": "Pie stream" + }, + "c05": { + "kind": "video", + "channel": "synth-kitchen", + "id": "pie-stream-02", + "start": 15, + "end": 19.8, + "quote": "the judges were friends of mine so it felt wrong", + "label": "Pie stream" + }, + "c06": { + "kind": "video", + "channel": "synth-kitchen", + "id": "pie-stream-02", + "start": 40, + "end": 44.8, + "quote": "my lawyer told me not to talk about the lease", + "label": "Pie stream" + } + } +} diff --git a/common/testing/draft/reports/paragraphs.report.json b/common/testing/draft/reports/paragraphs.report.json @@ -0,0 +1,56 @@ +{ + "format": "archilyzer-report", + "version": 1, + "id": "synth-paragraphs", + "kind": "sweep", + "title": "Paragraphs between findings", + "sections": [ + { + "id": "the-second-shop", + "title": "The second shop", + "body": "She talks about it near the end of a long episode.\n\n### A sub-heading inside a section\n\nThe other kitchen mentions the recipe, not the shop.", + "claims": [ + { + "id": "k01", + "text": "She says it opened in the spring: \"we opened the second shop in the spring\"", + "citations": [ + "c01" + ] + }, + { + "id": "k02", + "text": "The other kitchen tried the recipe: \"we tried the sourdough recipe from last week\"", + "citations": [ + "c02" + ] + } + ] + }, + { + "id": "coverage", + "title": "Coverage", + "body": "N = 4 recordings read across 2 channels. Not read: none." + } + ], + "summary": "Scope: channels `synth-kitchen` and `synth-other`. The question was the second shop.\n\nHeadlines:\n\n- **The second shop (spring 2026):** she says it opened in the spring.\n\n- **The recipe:** the other kitchen tried it.", + "citations": { + "c01": { + "kind": "video", + "channel": "synth-kitchen", + "id": "qa-long-03", + "start": 205, + "end": 209.8, + "quote": "we opened the second shop in the spring", + "label": "Questions and answers" + }, + "c02": { + "kind": "video", + "channel": "synth-other", + "id": "flat-loaf-01", + "start": 5, + "end": 9.8, + "quote": "we tried the sourdough recipe from last week", + "label": "The flat loaf" + } + } +} diff --git a/common/testing/draft/reports/posts-only.report.json b/common/testing/draft/reports/posts-only.report.json @@ -0,0 +1,48 @@ +{ + "format": "archilyzer-report", + "version": 1, + "id": "synth-posts-only", + "kind": "sweep", + "title": "Posts only", + "sections": [ + { + "id": "posts", + "title": "Posts", + "claims": [ + { + "id": "k01", + "text": "The account says it did not enter: \"No, I did not enter the pie contest.\"", + "citations": [ + "p01" + ] + }, + { + "id": "k02", + "text": "On the second shop: \"The second shop opens in the spring.\"", + "citations": [ + "p02" + ] + } + ] + } + ], + "summary": "What the account posted about the contest and the shop.", + "citations": { + "p01": { + "kind": "post", + "channel": "synth-social", + "id": "1700000000000000001", + "quote": "No, I did not enter the pie contest.", + "label": "post by synthbaker, 2026-02-11", + "date": "2026-02-11" + }, + "p02": { + "kind": "post", + "channel": "synth-social", + "id": "1700000000000000002", + "quote": "The second shop opens in the spring.", + "label": "post by synthbaker, 2026-03-02", + "date": "2026-03-02" + } + } +} diff --git a/common/testing/draft/sweeps/basic.md b/common/testing/draft/sweeps/basic.md @@ -0,0 +1,15 @@ +# Synth Kitchen — what the baker says about the bakery + +Scope: channel `synth-kitchen`, uploads from 2026-01-01 on. N = 3 recordings, all read. 2 are cited. + +## The bakery + +- She says she would not sell: "I would never sell the bakery to a chain" [Bread day @ 0:15](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15) +- She denies the oven story: "we never said that about the old oven" [Bread day @ 0:25](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25) +- She says she paid for the mixer: "I paid for the new mixer myself" [Bread day @ 0:45](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=45) + +## The contest + +- She says she did not enter: "I did not enter the contest this year" [Pie stream @ 0:10](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=10) +- She gives a reason: "the judges were friends of mine so it felt wrong" [Pie stream @ 0:15](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=15) +- She will not discuss the lease: "my lawyer told me not to talk about the lease" [Pie stream @ 0:40](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=40) diff --git a/common/testing/draft/sweeps/inexact.md b/common/testing/draft/sweeps/inexact.md @@ -0,0 +1,10 @@ +# Inexact quotes + +Three quotes: one reversed (fuzzy recall passes it, the strict check does not), one two hundred seconds from its link, +and one exact. + +## Findings + +- Reversed: "I would sell the bakery to a chain" [Bread day @ 0:15](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15) +- Far from its link: "we opened the second shop in the spring" [Questions and answers @ 0:05](https://synth.example/?v=synth-kitchen%2Fqa-long-03&t=5) +- Exact: "I have never met the other finalist" [Pie stream @ 0:30](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=30) diff --git a/common/testing/draft/sweeps/multi-quote.md b/common/testing/draft/sweeps/multi-quote.md @@ -0,0 +1,10 @@ +# Several quotes per link + +## The contest + +- On the contest: "a lot of you asked about the contest" and "I did not enter the contest this year" [Pie stream @ 0:05](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=5) +- She will not discuss the lease, twice: "my lawyer told me not to talk about the lease" [Pie stream @ 0:40](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=40) and then "so I will not talk about the lease" [Pie stream @ 0:45](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=45) + +## The oven + +- She says the oven was fine: "we never said that about the old oven" … "the oven was fine it just ran hot" [Bread day @ 0:25](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25) diff --git a/common/testing/draft/sweeps/paragraphs.md b/common/testing/draft/sweeps/paragraphs.md @@ -0,0 +1,23 @@ +# Paragraphs between findings + +Scope: channels `synth-kitchen` and `synth-other`. The question was the second shop. + +Headlines: +- **The second shop (spring 2026):** she says it opened in the spring. +- **The recipe:** the other kitchen tried it. + +## The second shop + +She talks about it near the end of a long episode. + +- She says it opened in the spring: "we opened the second shop in the spring" [Questions and answers @ 3:25](https://synth.example/?v=synth-kitchen%2Fqa-long-03&t=205) + +### A sub-heading inside a section + +The other kitchen mentions the recipe, not the shop. + +- The other kitchen tried the recipe: "we tried the sourdough recipe from last week" [The flat loaf @ 0:05](https://synth.example/?v=synth-other%2Fflat-loaf-01&t=5) + +## Coverage + +N = 4 recordings read across 2 channels. Not read: none. diff --git a/common/testing/draft/sweeps/posts-only.md b/common/testing/draft/sweeps/posts-only.md @@ -0,0 +1,8 @@ +# Posts only + +What the account posted about the contest and the shop. + +## Posts + +- The account says it did not enter: "No, I did not enter the pie contest." [post by synthbaker, 2026-02-11](https://synth.example/?v=synth-social%2F1700000000000000001&vm=post) +- On the second shop: "The second shop opens in the spring." [post by synthbaker, 2026-03-02](https://synth.example/?v=synth-social%2F1700000000000000002&vm=post) diff --git a/common/testing/draft/sweeps/quotes-in-claims.md b/common/testing/draft/sweeps/quotes-in-claims.md @@ -0,0 +1,9 @@ +# Quotes in claims + +A generated sweep that breaks the rule: its claims carry quoted words before the quote. + +## Findings + +- She "would never" sell the bakery, she says: "I would never sell the bakery to a chain" [Bread day @ 0:15](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15) +- The "old oven" story is denied: "we never said that about the old oven" [Bread day @ 0:25](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25) +- She says “nobody sponsored” her: “nobody sponsored this kitchen” [Bread day @ 0:50](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=50) diff --git a/common/testing/fakes.test.ts b/common/testing/fakes.test.ts @@ -0,0 +1,219 @@ +// 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, +} from "./llm/fakeAnthropic.mjs"; +import { faultReply, jsonReply, startFakeOllama, toolCallsReply } from "./llm/fakeOllama.mjs"; +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<string, string> = {}) { + 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(); + } +}); + +// ─── 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 }); + } +}); diff --git a/common/testing/llm/fakeAnthropic.d.mts b/common/testing/llm/fakeAnthropic.d.mts @@ -0,0 +1,35 @@ +export type FakeBlock = Record<string, unknown> & { type: string }; +export type FakeTurn = { content: FakeBlock[]; stop_reason: string; usage?: Record<string, unknown> }; +export type FakeError = { __error: { status: number; type: string; message: string; headers: Record<string, string> } }; +export type FakeScripted = + | FakeTurn + | FakeError + | ((body: any, ctx: { requests: any[] }) => FakeTurn | FakeError | Promise<FakeTurn | FakeError>); + +export const FAKE_KEY: string; +export const DEFAULT_STRICT_MODELS: string[]; +export function textBlock(text: string): FakeBlock; +export function toolUseBlock(name: string, input: unknown, id?: string): FakeBlock; +export function thinkingBlock(thinking: string): FakeBlock; +export function webSearchBlocks( + query: string, + results: { url: string; title: string; text?: string; page_age?: string | null }[], +): FakeBlock[]; +export function turn(content: FakeBlock | FakeBlock[], opts?: { stop_reason?: string; usage?: Record<string, unknown> }): FakeTurn; +export function textTurn(text: string, opts?: { stop_reason?: string; usage?: Record<string, unknown> }): FakeTurn; +export function toolTurn(name: string, input: unknown, opts?: { stop_reason?: string; usage?: Record<string, unknown> }): FakeTurn; +export function pauseTurn(content: FakeBlock[]): FakeTurn; +export function errorTurn(status: number, type: string, message: string, headers?: Record<string, string>): FakeError; +export function strictModelProblem(body: any, strictModels?: string[]): string | null; +export function signatureProblem(body: any): string | null; + +export type FakeAnthropic = { + url: string; + key: string; + requests: any[]; + requestHeaders: Record<string, string | string[] | undefined>[]; + push(...turns: FakeScripted[]): void; + remaining(): number; + close(): Promise<void>; +}; +export function startFakeAnthropic(opts?: { key?: string; strictModels?: string[]; turns?: FakeScripted[] }): Promise<FakeAnthropic>; diff --git a/common/testing/llm/fakeAnthropic.mjs b/common/testing/llm/fakeAnthropic.mjs @@ -0,0 +1,227 @@ +// A fake Anthropic Messages API for the generation tests (release 27). No test +// ever calls the real API; the live smoke is the only place a real key is used. +// +// const api = await startFakeAnthropic({ turns: [textTurn("hi")] }); +// … point the client at api.url (the base, like ANTHROPIC_BASE_URL) with api.key … +// api.requests every request body, in order (headers in api.requestHeaders) +// api.push(…) more scripted turns +// await api.close() +// +// What it enforces, because the real API does (each is a 400 invalid_request_error): +// - a STRICT model (Sonnet 5.5 by default) refuses a non-default `temperature`, +// a forced `tool_choice` ({type:"tool"} or {type:"any"}) and `thinking: {type:"disabled"}`; +// - a thinking block is signed over the conversation before it: an assistant +// turn carrying thinking whose history was edited (or whose block was) is refused, +// so a client must keep history append-only once a thinking block appears; +// - `max_tokens` is required, and `model`, and a non-empty `messages`. +// A missing or wrong `x-api-key` is a 401 authentication_error. +// +// A scripted turn is a response (helpers below), an error (`errorTurn`), or a +// function (body, ctx) → either, for a turn that depends on the request. When +// the script runs out, the server answers 500 "fake: script exhausted" so the +// test fails where it should. +// +// Usage: a turn's `usage` is used as given; otherwise it is estimated (4 chars a +// token). A request carrying `cache_control` (top level or on a block) caches its +// prefix: the first time a prefix is seen it is a cache write, after that a read. + +import http from "node:http"; +import { createHash } from "node:crypto"; + +export const FAKE_KEY = "sk-ant-fake-0000-TESTKEY-never-real"; +export const DEFAULT_STRICT_MODELS = ["claude-sonnet-5-5"]; + +const tok = (v) => Math.max(1, Math.ceil(JSON.stringify(v ?? "").length / 4)); +let idSeq = 0; +const nextId = (p) => `${p}_fake${String(++idSeq).padStart(6, "0")}`; + +// ─── Turn builders ─── + +export const textBlock = (text) => ({ type: "text", text }); + +export const toolUseBlock = (name, input, id = nextId("toolu")) => ({ type: "tool_use", id, name, input }); + +// A thinking block; the server signs it over the request it answers. +export const thinkingBlock = (thinking) => ({ type: "thinking", thinking }); + +// The server-side web search (`web_search_20250305`-style): a server_tool_use +// block and its result block, both in the assistant's content. +export function webSearchBlocks(query, results) { + const id = nextId("srvtoolu"); + return [ + { type: "server_tool_use", id, name: "web_search", input: { query } }, + { + type: "web_search_tool_result", + tool_use_id: id, + content: results.map((r) => ({ + type: "web_search_result", + url: r.url, + title: r.title, + encrypted_content: Buffer.from(r.text ?? r.title).toString("base64"), + page_age: r.page_age ?? null, + })), + }, + ]; +} + +// A whole response. `stop_reason` defaults from the content: tool_use when it +// asks for a client tool, else end_turn. +export function turn(content, opts = {}) { + const blocks = Array.isArray(content) ? content : [content]; + return { + content: blocks, + stop_reason: opts.stop_reason ?? (blocks.some((b) => b.type === "tool_use") ? "tool_use" : "end_turn"), + ...(opts.usage ? { usage: opts.usage } : {}), + }; +} + +export const textTurn = (text, opts) => turn([textBlock(text)], opts); +export const toolTurn = (name, input, opts) => turn([toolUseBlock(name, input)], opts); + +// A long server-tool turn the API pauses: the client sends the conversation back +// as is (the paused assistant content appended) and the API continues it. +export const pauseTurn = (content) => turn(content, { stop_reason: "pause_turn" }); + +export const errorTurn = (status, type, message, headers = {}) => ({ __error: { status, type, message, headers } }); + +// ─── The rules the real API enforces ─── + +export function strictModelProblem(body, strictModels = DEFAULT_STRICT_MODELS) { + const model = String(body.model ?? ""); + if (!strictModels.some((m) => model.startsWith(m))) return null; + if (body.temperature !== undefined && body.temperature !== 1) + return `temperature: ${model} does not support a non-default temperature`; + const tc = body.tool_choice; + if (tc && (tc.type === "tool" || tc.type === "any")) + return `tool_choice: ${model} does not support forced tool use; use a strict tool with tool_choice auto`; + if (body.thinking && body.thinking.type === "disabled") + return `thinking: ${model} does not support thinking.type "disabled"; use "between_tools"`; + return null; +} + +const sign = (history, thinking) => + createHash("sha256").update(JSON.stringify(history)).update("\u0000").update(thinking).digest("base64url"); + +// Every assistant turn's thinking blocks must carry the signature they were +// issued with over the messages before them, unedited. +export function signatureProblem(body) { + const msgs = Array.isArray(body.messages) ? body.messages : []; + for (let i = 0; i < msgs.length; i++) { + const m = msgs[i]; + if (m.role !== "assistant" || !Array.isArray(m.content)) continue; + for (const b of m.content) { + if (b.type !== "thinking") continue; + if (!b.signature || b.signature !== sign(msgs.slice(0, i), b.thinking ?? "")) + return `messages.${i}.content: thinking block signature is invalid (the history before it was edited)`; + } + } + return null; +} + +function requestProblem(body) { + if (!body || typeof body !== "object") return "body: not JSON"; + if (!body.model) return "model: required"; + if (typeof body.max_tokens !== "number") return "max_tokens: required"; + if (!Array.isArray(body.messages) || body.messages.length === 0) return "messages: required"; + return null; +} + +const hasCacheControl = (body) => + !!body.cache_control || JSON.stringify([body.system, body.tools, body.messages]).includes('"cache_control"'); + +// ─── The server ─── + +export async function startFakeAnthropic(opts = {}) { + const key = opts.key ?? FAKE_KEY; + const strictModels = opts.strictModels ?? DEFAULT_STRICT_MODELS; + const script = [...(opts.turns ?? [])]; + const requests = []; + const requestHeaders = []; + const seenPrefixes = new Set(); + + const send = (res, status, payload, headers = {}) => { + res.writeHead(status, { "content-type": "application/json", ...headers }); + res.end(JSON.stringify(payload)); + }; + const apiError = (res, status, type, message, headers) => + send(res, status, { type: "error", error: { type, message } }, headers); + + const server = http.createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", async () => { + if (req.method !== "POST" || req.url !== "/v1/messages") + return apiError(res, 404, "not_found_error", `fake: no route ${req.method} ${req.url}`); + let body; + try { + body = JSON.parse(raw); + } catch { + return apiError(res, 400, "invalid_request_error", "body: not JSON"); + } + requests.push(body); + requestHeaders.push({ ...req.headers }); + if (req.headers["x-api-key"] !== key) return apiError(res, 401, "authentication_error", "invalid x-api-key"); + if (!req.headers["anthropic-version"]) + return apiError(res, 400, "invalid_request_error", "anthropic-version: header required"); + const problem = requestProblem(body) ?? strictModelProblem(body, strictModels) ?? signatureProblem(body); + if (problem) return apiError(res, 400, "invalid_request_error", problem); + + let next = script.shift(); + if (next === undefined) return apiError(res, 500, "api_error", "fake: script exhausted"); + if (typeof next === "function") next = await next(body, { requests }); + if (next.__error) { + const e = next.__error; + return apiError(res, e.status, e.type, e.message, e.headers); + } + + // Sign each thinking block over the conversation it answers. + const content = next.content.map((b) => + b.type === "thinking" ? { ...b, signature: sign(body.messages, b.thinking ?? "") } : b, + ); + let usage = next.usage; + if (!usage) { + // A cached request reads the longest conversation cached before it + // (same system and tools, its messages a prefix of these) and writes the + // rest up to its last message. + const head = JSON.stringify([body.system ?? null, body.tools ?? null]); + const total = tok([body.system ?? null, body.tools ?? null, body.messages]); + const last = tok(body.messages[body.messages.length - 1]); + const cached = hasCacheControl(body); + let read = 0; + if (cached) { + for (let k = body.messages.length; k >= 1 && !read; k--) + if (seenPrefixes.has(head + JSON.stringify(body.messages.slice(0, k)))) + read = tok([body.system ?? null, body.tools ?? null, body.messages.slice(0, k)]); + seenPrefixes.add(head + JSON.stringify(body.messages)); + } + usage = { + input_tokens: cached ? last : total, + cache_creation_input_tokens: cached ? Math.max(0, total - read - last) : 0, + cache_read_input_tokens: read, + output_tokens: tok(content), + }; + } + send(res, 200, { + id: nextId("msg"), + type: "message", + role: "assistant", + model: body.model, + content, + stop_reason: next.stop_reason, + stop_sequence: null, + usage, + }); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const { port } = server.address(); + return { + url: `http://127.0.0.1:${port}`, + key, + requests, + requestHeaders, + push: (...turns) => script.push(...turns), + remaining: () => script.length, + close: () => new Promise((r) => server.close(() => r())), + }; +} diff --git a/common/testing/llm/fakeOllama.d.mts b/common/testing/llm/fakeOllama.d.mts @@ -0,0 +1,34 @@ +export type OllamaReply = { + message: { role: string; content: string; tool_calls?: { function: { name: string; arguments: unknown } }[] }; + done: boolean; + [k: string]: unknown; +}; +export type OllamaError = { __error: { status: number; error: string } }; +export type OllamaScripted = + | OllamaReply + | OllamaError + | ((body: any, ctx: { requests: any[] }) => OllamaReply | OllamaError | Promise<OllamaReply | OllamaError>); + +export const PROMPT_CAP_TOKENS: number; +export const NUM_CTX_CAP: number; +export function reply(content: string, extra?: Record<string, unknown>): OllamaReply; +export function jsonReply(value: unknown): OllamaReply; +export function toolCallsReply(calls: { name: string; arguments?: unknown }[], content?: string): OllamaReply; +export function faultReply(): OllamaReply; +export function errorReply(status: number, error: string): OllamaError; + +export type FakeOllama = { + url: string; + requests: any[]; + unloads: string[]; + loaded(): string[]; + push(...turns: OllamaScripted[]): void; + remaining(): number; + close(): Promise<void>; +}; +export function startFakeOllama(opts?: { + models?: string[]; + promptCapTokens?: number; + numCtxCap?: number; + turns?: OllamaScripted[]; +}): Promise<FakeOllama>; diff --git a/common/testing/llm/fakeOllama.mjs b/common/testing/llm/fakeOllama.mjs @@ -0,0 +1,124 @@ +// A fake ollama for the generation tests (release 27): `/api/chat` with tools +// or a `format` schema, `/api/tags`, `/api/ps`, and the unload call +// (`keep_alive: 0`). No test talks to a real ollama or touches the GPU. +// +// const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] })] }); +// … point the client at ol.url … +// ol.requests every /api/chat body, in order +// ol.unloads the models unloaded with keep_alive 0 +// await ol.close() +// +// What it enforces, because the GPU does (Q0, 2026-10-11): a request over the +// prompt cap (8k tokens, estimated at 4 chars a token) or with `options.num_ctx` +// over 12k is refused with a 400 "fake: …", so a client that would hang the +// card fails its test instead. `stream: true` is refused: the clients here read +// one JSON answer. A scripted `faultReply()` answers `done: false` — what a GPU +// fault looks like — which a client must read as a failure, not an answer. +// +// A scripted turn is a reply (helpers below) or a function (body, ctx) → reply. +// When the script runs out the server answers 500 "fake: script exhausted". + +import http from "node:http"; + +export const PROMPT_CAP_TOKENS = 8192; +export const NUM_CTX_CAP = 12288; + +const tok = (v) => Math.ceil(JSON.stringify(v ?? "").length / 4); + +export const reply = (content, extra = {}) => ({ message: { role: "assistant", content }, done: true, ...extra }); + +// A `format`-schema answer: the content is the JSON text. +export const jsonReply = (value) => reply(JSON.stringify(value)); + +// Tool calls, as ollama returns them (arguments an object, not a string). +export const toolCallsReply = (calls, content = "") => ({ + message: { + role: "assistant", + content, + tool_calls: calls.map((c) => ({ function: { name: c.name, arguments: c.arguments ?? {} } })), + }, + done: true, +}); + +export const faultReply = () => ({ message: { role: "assistant", content: "" }, done: false }); + +export const errorReply = (status, error) => ({ __error: { status, error } }); + +export async function startFakeOllama(opts = {}) { + const models = opts.models ?? ["qwen3:8b", "qwen2.5:7b"]; + const promptCap = opts.promptCapTokens ?? PROMPT_CAP_TOKENS; + const numCtxCap = opts.numCtxCap ?? NUM_CTX_CAP; + const script = [...(opts.turns ?? [])]; + const requests = []; + const unloads = []; + const loaded = new Set(); + + const send = (res, status, payload) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(payload)); + }; + + const server = http.createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", async () => { + if (req.method === "GET" && req.url === "/api/tags") + return send(res, 200, { models: models.map((name) => ({ name, model: name })) }); + if (req.method === "GET" && req.url === "/api/ps") + return send(res, 200, { models: [...loaded].map((name) => ({ name, model: name })) }); + if (req.method !== "POST" || (req.url !== "/api/chat" && req.url !== "/api/generate")) + return send(res, 404, { error: `fake: no route ${req.method} ${req.url}` }); + let body; + try { + body = JSON.parse(raw); + } catch { + return send(res, 400, { error: "fake: body is not JSON" }); + } + if (!models.includes(body.model)) return send(res, 404, { error: `model "${body.model}" not found` }); + + // The unload: keep_alive 0 with nothing to answer. + const empty = + req.url === "/api/generate" ? !body.prompt : !Array.isArray(body.messages) || body.messages.length === 0; + if ((body.keep_alive === 0 || body.keep_alive === "0") && empty) { + unloads.push(body.model); + loaded.delete(body.model); + return send(res, 200, { model: body.model, done: true, done_reason: "unload" }); + } + if (req.url === "/api/generate") return send(res, 400, { error: "fake: only the unload call on /api/generate" }); + + requests.push(body); + if (body.stream !== false) return send(res, 400, { error: "fake: stream must be false" }); + const numCtx = body.options?.num_ctx; + if (typeof numCtx === "number" && numCtx > numCtxCap) + return send(res, 400, { error: `fake: num_ctx ${numCtx} is over the ${numCtxCap} cap` }); + const promptTokens = tok([body.messages, body.tools ?? null, body.format ?? null]); + if (promptTokens > promptCap) + return send(res, 400, { error: `fake: prompt ~${promptTokens} tokens is over the ${promptCap} cap` }); + + let next = script.shift(); + if (next === undefined) return send(res, 500, { error: "fake: script exhausted" }); + if (typeof next === "function") next = await next(body, { requests }); + if (next.__error) return send(res, next.__error.status, { error: next.__error.error }); + loaded.add(body.model); + send(res, 200, { + model: body.model, + created_at: "2026-10-13T00:00:00Z", + prompt_eval_count: promptTokens, + eval_count: tok(next.message), + done_reason: next.done ? "stop" : undefined, + ...next, + }); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const { port } = server.address(); + return { + url: `http://127.0.0.1:${port}`, + requests, + unloads, + loaded: () => [...loaded], + push: (...turns) => script.push(...turns), + remaining: () => script.length, + close: () => new Promise((r) => server.close(() => r())), + }; +}