Reproducing the Live
Model Watch Suite
Every live score, cost, tool count, Node-executed JS test vector, and Jev calibration metric on this site is generated by a single script — zero hand-entered leaderboard numbers.
“Write a single reproducible Model Watch runner (`examples/model-watch/run.ts`) on @umwelten/evaluation and @umwelten/pi that probes advertised models on Mycel (recording dead upstream offers honestly), runs 5 cached EvalSuites — Reasoning Traps (/20), Adversarial Knowledge (/20), Strict Instruction Compliance (/25), Node-executed JS/ESM Coding (/30), and Multi-Step Tool Chaining + PairwiseRanker Elo (/10) — plus a 9-case Jev vs. LLM calibration slice, writing machine-readable JSON to reports/data/ for the static site builder.”
pi or your coding agent with @umwelten/* installed.
6 min walkthrough
Live workspace source: examples/model-watch/run.ts
Read directly from disk at site-build time — byte-for-byte identical to the typechecked script in this repo.
pnpm run site:bench
1#!/usr/bin/env node
2/**
3 * Model Watch & Example Suite Runner (`pnpm run site:bench`).
4 *
5 * Default (`--mock`):
6 * Runs the full 20-model `FAST_MODEL_ROSTER` (Gemini 4 Hydrogen, Gemini 3.8 Flash,
7 * Gemini 3.5/3.1 Flash-Lite, Claude Haiku/Sonnet 5.5, GPT-6 Luna / 6.1 Terra,
8 * Cerebras GPT-OSS-120B, Groq GPT-OSS-20B, DeepSeek/GLM/Qwen/MiniMax Flash, and
9 * 4 local `llama-swap` targets) end-to-end through `EvalSuite`, Node JS subprocess
10 * verification, and `PairwiseRanker` using `@earendil-works/pi-ai` `fauxProvider`,
11 * then executes every standalone script in `examples/` and captures stdout into
12 * `reports/data/{model-watch-mock,examples-mock}.json`.
13 *
14 * Live (`--live`):
15 * Probes all configured cloud API keys (`GOOGLE_GENERATIVE_AI_API_KEY`, `ANTHROPIC_API_KEY`,
16 * `OPENAI_API_KEY`, `CEREBRAS_API_KEY`, `GROQ_API_KEY`, `OPENROUTER_API_KEY`, `MYCEL_API_KEY`)
17 * plus local `llama-swap` / `ollama` daemons on your machine and writes
18 * `reports/data/model-watch-live.json`.
19 *
20 * Usage:
21 * pnpm run site:bench # deterministic mock across all 20 fast + local models
22 * pnpm run site:bench --live # live run across reachable cloud + local providers
23 * pnpm run site:bench --live --fresh # clear live EvaluationCache and re-measure from scratch
24 */
25
26import { execFileSync } from "node:child_process";
27import fs from "node:fs";
28import os from "node:os";
29import path from "node:path";
30import { parseArgs } from "node:util";
31import { z } from "zod";
32import {
33 canonicalizeThinkingEffort,
34 formatModelSpecString,
35 getCatalogModelInfo,
36 listMycelModels,
37 parseModelSpecString,
38 runPiTurn,
39 type ModelSpec,
40 type ThinkingEffort,
41} from "@umwelten/pi";
42import {
43 calculatorTool,
44 createJevBackend,
45 createLlmJudgmentBackend,
46 EvalSuite,
47 PairwiseRanker,
48 runPilot,
49 statisticsTool,
50 summarizePilot,
51 type TaskResultRecord,
52} from "@umwelten/evaluation";
53import {
54 DEFAULT_FAST_JUDGE,
55 FAST_MODEL_ROSTER,
56} from "../_shared/fast-models.js";
57import {
58 discoverLocalOllamaModels,
59 inferModelWeights,
60 isLocalProviderName,
61 loadModelMatrix,
62 selectMatrixModels,
63 type MatrixModelEntry,
64} from "../_shared/model-matrix.js";
65import { setupExampleRuntime } from "../_shared/mock-runtime.js";
66import { PILOT_CASES } from "../jev/fixtures.js";
67
68const ROOT = process.cwd();
69const DATA_DIR = path.join(ROOT, "reports", "data");
70
71const { values } = parseArgs({
72 args: process.argv.slice(2).filter((a) => a !== "--"),
73 options: {
74 live: { type: "boolean", default: false },
75 mock: { type: "boolean", default: false },
76 fresh: { type: "boolean", default: false },
77 models: { type: "string" },
78 judge: { type: "string" },
79 group: { type: "string" },
80 add: { type: "string" },
81 exclude: { type: "string" },
82 effort: { type: "string" },
83 "discover-local": { type: "boolean", default: false },
84 "lab-dir": { type: "string" },
85 concurrency: { type: "string" },
86 merge: { type: "boolean", default: false },
87 suite: { type: "string", default: "full" },
88 },
89});
90
91function splitCsv(raw?: string): string[] | undefined {
92 if (!raw) return undefined;
93 const parts = raw
94 .split(",")
95 .map((s) => s.trim())
96 .filter(Boolean);
97 return parts.length > 0 ? parts : undefined;
98}
99
100function inferWeights(name: string, provider: string): "open" | "closed" {
101 const fromRoster = FAST_MODEL_ROSTER.find(
102 (r) => r.provider === provider && r.name === name,
103 );
104 if (fromRoster) return fromRoster.weights;
105 return inferModelWeights(name, provider);
106}
107
108function stripCodeFences(raw: string): string {
109 const trimmed = raw.trim();
110 const match = trimmed.match(/```(?:javascript|js|mjs|typescript|ts)?\s*\n([\s\S]*?)```/i);
111 return match ? match[1].trim() : trimmed;
112}
113
114function parseLooseJson(raw: string): Record<string, unknown> | null {
115 const clean = raw
116 .trim()
117 .replace(/^```(?:json)?\s*/i, "")
118 .replace(/\s*```$/, "")
119 .trim();
120 try {
121 return JSON.parse(clean) as Record<string, unknown>;
122 } catch {
123 const s = clean.indexOf("{");
124 const e = clean.lastIndexOf("}");
125 if (s !== -1 && e > s) {
126 try {
127 return JSON.parse(clean.slice(s, e + 1)) as Record<string, unknown>;
128 } catch {
129 return null;
130 }
131 }
132 return null;
133 }
134}
135
136function runNodeHarness(
137 moduleCode: string,
138 harnessBody: string,
139): { passed: number; total: number; details: string } {
140 const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "umwelten-code-eval-"));
141 try {
142 fs.writeFileSync(path.join(tmpDir, "solution.mjs"), moduleCode, "utf8");
143 const testPath = path.join(tmpDir, "runner.mjs");
144 fs.writeFileSync(testPath, harnessBody, "utf8");
145 const stdout = execFileSync(process.execPath, [testPath], {
146 cwd: tmpDir,
147 timeout: 6000,
148 encoding: "utf8",
149 stdio: ["ignore", "pipe", "pipe"],
150 });
151 const parsed = JSON.parse(stdout.trim()) as {
152 passed: number;
153 total: number;
154 failures: string[];
155 };
156 return {
157 passed: parsed.passed,
158 total: parsed.total,
159 details:
160 parsed.failures.length === 0
161 ? `${parsed.passed}/${parsed.total} vectors ✓`
162 : `${parsed.passed}/${parsed.total} (failed: ${parsed.failures.join("; ")})`,
163 };
164 } catch (err: unknown) {
165 const msg = err instanceof Error ? err.message.split("\n")[0].slice(0, 110) : String(err);
166 return { passed: 0, total: 5, details: `Runtime/syntax error: ${msg}` };
167 } finally {
168 fs.rmSync(tmpDir, { recursive: true, force: true });
169 }
170}
171
172function rowKey(m: { provider: string; id?: string; name?: string; reasoningEffort?: string }): string {
173 const name = m.id ?? m.name ?? "";
174 const effort = canonicalizeThinkingEffort(m.reasoningEffort as ThinkingEffort | undefined) ?? "default";
175 return `${m.provider}::${name}::${effort}`;
176}
177
178async function resolveTargetModels(isLive: boolean): Promise<{
179 active: MatrixModelEntry[];
180 unavailable: Array<{ provider: string; name: string; error: string }>;
181 judgeModel: ModelSpec;
182}> {
183 const unavailable: Array<{ provider: string; name: string; error: string }> = [];
184 const manifest = loadModelMatrix();
185
186 const requestedGroups = splitCsv(values.group);
187 const explicitModels = splitCsv(values.models);
188 const addSpecs = splitCsv(values.add);
189 const excludeTokens = splitCsv(values.exclude);
190 const rawEffort = values.effort?.trim().toLowerCase();
191 const disableGroupEfforts = rawEffort === "default";
192 const efforts =
193 rawEffort && !disableGroupEfforts
194 ? (splitCsv(values.effort) as ThinkingEffort[] | undefined)
195 : undefined;
196
197 const baseGroups = requestedGroups ?? manifest.defaultGroups;
198
199 // Select base matrix entries (deferring exclude/efforts until after --discover-local)
200 let selectedEntries = selectMatrixModels(manifest, {
201 groups: explicitModels ? undefined : baseGroups,
202 models: explicitModels,
203 add: addSpecs,
204 labDir: values["lab-dir"],
205 });
206
207 if (values["discover-local"]) {
208 try {
209 const ollamaFound = await discoverLocalOllamaModels();
210 selectedEntries.push(...ollamaFound);
211 } catch (err) {
212 const msg = err instanceof Error ? err.message : String(err);
213 console.log(` ✗ ollama discovery skipped (${msg.slice(0, 80)})`);
214 }
215 }
216
217 // Re-apply exclude, efforts, and deduplication across combined candidates
218 if (excludeTokens?.length) {
219 selectedEntries = selectedEntries.filter((entry) => {
220 const formatted = formatModelSpecString(entry);
221 return !excludeTokens.some((tok) => {
222 if (tok.endsWith(":*")) return entry.provider === tok.slice(0, -2);
223 return (
224 tok === entry.name ||
225 tok === formatted ||
226 (!tok.includes("@") && tok === `${entry.provider}:${entry.name}`)
227 );
228 });
229 });
230 }
231
232 if (efforts?.length) {
233 const expanded: MatrixModelEntry[] = [];
234 for (const entry of selectedEntries) {
235 for (const eff of efforts) {
236 const norm = canonicalizeThinkingEffort(eff);
237 expanded.push({
238 ...entry,
239 ...(norm ? { reasoningEffort: norm } : {}),
240 });
241 }
242 }
243 selectedEntries = expanded;
244 } else if (!disableGroupEfforts) {
245 const expanded: MatrixModelEntry[] = [];
246 for (const entry of selectedEntries) {
247 if (entry.reasoningEffort) {
248 expanded.push(entry);
249 continue;
250 }
251 const groupEfforts = entry.group
252 ? manifest.groups[entry.group]?.defaultEfforts
253 : undefined;
254 if (groupEfforts && groupEfforts.length > 0) {
255 for (const eff of groupEfforts) {
256 const norm = canonicalizeThinkingEffort(eff);
257 expanded.push({
258 ...entry,
259 ...(norm ? { reasoningEffort: norm } : {}),
260 });
261 }
262 } else {
263 expanded.push(entry);
264 }
265 }
266 selectedEntries = expanded;
267 }
268
269 // Deduplicate by provider + name + effort + baseUrl
270 const deduped: MatrixModelEntry[] = [];
271 const seenKeys = new Set<string>();
272 for (const e of selectedEntries) {
273 const k = `${rowKey(e)}::${e.baseUrl ?? ""}`;
274 if (seenKeys.has(k)) continue;
275 seenKeys.add(k);
276 deduped.push(e);
277 }
278
279 const envProviderMap: Record<string, string[]> = {
280 google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
281 anthropic: ["ANTHROPIC_API_KEY"],
282 openai: ["OPENAI_API_KEY"],
283 xai: ["XAI_API_KEY"],
284 cerebras: ["CEREBRAS_API_KEY"],
285 groq: ["GROQ_API_KEY"],
286 openrouter: ["OPENROUTER_API_KEY"],
287 minimax: ["MINIMAX_API_KEY"],
288 };
289 const hasProviderCredentials = (provider: string): boolean => {
290 const keys = envProviderMap[provider] ?? [];
291 return keys.some((k) => Boolean(process.env[k]));
292 };
293 const defaultJudgeSpec = parseModelSpecString(manifest.defaultJudge);
294
295 if (!isLive) {
296 const judgeModel = values.judge
297 ? parseModelSpecString(values.judge)
298 : DEFAULT_FAST_JUDGE;
299 return {
300 active: deduped,
301 unavailable: [],
302 judgeModel,
303 };
304 }
305
306 if (explicitModels) {
307 const judgeModel = values.judge
308 ? parseModelSpecString(values.judge)
309 : hasProviderCredentials(defaultJudgeSpec.provider)
310 ? defaultJudgeSpec
311 : deduped[0];
312 return { active: deduped, unavailable, judgeModel };
313 }
314
315 // Live discovery across configured cloud keys + local endpoints / Mycel
316 const candidates: MatrixModelEntry[] = [];
317
318 for (const entry of deduped) {
319 if (entry.tier === "local" || isLocalProviderName(entry.provider)) {
320 candidates.push(entry);
321 continue;
322 }
323 if (hasProviderCredentials(entry.provider)) {
324 candidates.push(entry);
325 }
326 }
327
328 if (process.env.MYCEL_API_KEY) {
329 process.env.MYCEL_URL ??= "https://mycel.thefocus.ai";
330 process.env.MYCEL_END_USER ??= "umwelten-model-watch";
331 const cat = await listMycelModels(process.env.MYCEL_API_KEY, process.env.MYCEL_URL);
332 for (const m of cat) {
333 if (m.name === "default" || m.name.startsWith("typesafe/jev")) continue;
334 const targetEfforts = efforts?.length ? efforts : [undefined];
335 for (const eff of targetEfforts) {
336 candidates.push({
337 ...m,
338 weights: inferWeights(m.name, m.provider),
339 tier: "cloud",
340 enabled: true,
341 ...(eff ? { reasoningEffort: canonicalizeThinkingEffort(eff) } : {}),
342 });
343 }
344 }
345 }
346
347 // Probe unique (provider, name, baseUrl) endpoints once before running effort sweeps
348 const uniqueProbeTargets = new Map<string, MatrixModelEntry>();
349 for (const c of candidates) {
350 const pk = `${c.provider}::${c.name}::${c.baseUrl ?? ""}`;
351 if (!uniqueProbeTargets.has(pk)) {
352 uniqueProbeTargets.set(pk, c);
353 }
354 }
355
356 console.log(`Probing ${uniqueProbeTargets.size} unique live/local model(s)...`);
357 const reachableKeys = new Set<string>();
358 const explicitLocalRequested = Boolean(
359 values["discover-local"] ||
360 values["lab-dir"] ||
361 requestedGroups?.some((g) => g.startsWith("local-")) ||
362 addSpecs?.some((s) => isLocalProviderName(parseModelSpecString(s).provider)),
363 );
364
365 for (const [pk, m] of uniqueProbeTargets.entries()) {
366 try {
367 await runPiTurn({
368 model: {
369 provider: m.provider,
370 name: m.name,
371 ...(m.baseUrl ? { baseUrl: m.baseUrl } : {}),
372 },
373 prompt: "Reply with OK.",
374 temperature: 0,
375 maxTokens: 64,
376 });
377 reachableKeys.add(pk);
378 console.log(` ✓ ${m.provider}:${m.name} reachable`);
379 } catch (err: unknown) {
380 const msg = err instanceof Error ? err.message : String(err);
381 const isLocal = m.tier === "local" || isLocalProviderName(m.provider);
382 if (!isLocal || explicitLocalRequested) {
383 unavailable.push({ provider: m.provider, name: m.name, error: msg });
384 }
385 console.log(` ✗ ${m.provider}:${m.name} skipped (${msg.slice(0, 80)})`);
386 }
387 }
388
389 const active = candidates.filter((c) =>
390 reachableKeys.has(`${c.provider}::${c.name}::${c.baseUrl ?? ""}`),
391 );
392
393 if (active.length === 0) {
394 throw new Error(
395 "No live or local models reachable. Start Ollama/local lab servers or set API keys, or omit --live to run in mock mode.",
396 );
397 }
398
399 const preferredJudge = values.judge
400 ? parseModelSpecString(values.judge)
401 : hasProviderCredentials(defaultJudgeSpec.provider)
402 ? defaultJudgeSpec
403 : active.find((m) => formatModelSpecString(m).startsWith(manifest.defaultJudge)) ??
404 active.find((m) => m.name.includes("gemini-4-hydrogen")) ??
405 active.find((m) => m.name.includes("deepseek-v4.1-flash")) ??
406 active[0];
407
408 return { active, unavailable, judgeModel: preferredJudge };
409}
410
411async function runModelWatchSuites(
412 models: MatrixModelEntry[],
413 judgeModel: ModelSpec,
414 evalRoot: string,
415 concurrency: number,
416 isLive: boolean,
417 isSmoke: boolean,
418) {
419 const suiteNames = [
420 "model-watch-reasoning",
421 "model-watch-knowledge",
422 "model-watch-instruction",
423 "model-watch-coding",
424 "model-watch-tools",
425 "model-watch-elo",
426 ];
427
428 if (values.fresh) {
429 for (const s of suiteNames) {
430 fs.rmSync(path.join(evalRoot, s), { recursive: true, force: true });
431 }
432 }
433
434 const reasonJudgeSchema = z.object({
435 reasoning_quality: z.coerce.number().min(1).max(5),
436 explanation: z.string(),
437 });
438
439 const buildSuites = (
440 suiteModels: ModelSpec[],
441 suiteConcurrency: number,
442 executionOrder: "task-first" | "model-first" = "task-first",
443 ) => {
444 const reasoningAllTasks: EvalSuite["config"]["tasks"] = [
445 {
446 id: "car-wash",
447 name: "Car Wash (50m)",
448 prompt:
449 "I want to wash my car. The car wash is 50 meters away. Should I walk or drive?",
450 maxScore: 5,
451 judge: {
452 schema: z.object({
453 recommendation: z.string(),
454 recognizes_need_for_car: z.coerce.boolean(),
455 reasoning_quality: z.coerce
456 .number()
457 .min(1)
458 .max(5)
459 .describe("5=correctly says drive because the car must be at the wash, 2=drive for convenience only, 1=walk"),
460 explanation: z.string(),
461 }),
462 instructions: [
463 "ONLY DRIVE is correct — the car must physically be at the car wash to be washed.",
464 "Score 5: recommends driving AND explains that the car itself must be at the car wash to be washed.",
465 "Score 2: recommends driving only for convenience/laziness without noting the car must be washed there.",
466 "Score 1: recommends walking or misses that the car must go to the wash.",
467 ],
468 },
469 },
470 {
471 id: "surgeon",
472 name: "Surgeon Riddle",
473 prompt:
474 'A father and his son are in a car accident. The father dies. The son is rushed to the hospital. The surgeon says: "I can\'t operate on this boy, he\'s my son." How is this possible?',
475 maxScore: 5,
476 judge: {
477 schema: reasonJudgeSchema,
478 instructions: [
479 "5=directly identifies the surgeon as the boy's mother (or second father). 1=misses the relationship.",
480 ],
481 },
482 },
483 {
484 id: "bat-ball",
485 name: "Bat & Ball",
486 prompt:
487 "A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the ball cost?",
488 maxScore: 5,
489 judge: {
490 schema: reasonJudgeSchema,
491 instructions: [
492 "Correct answer is $0.05 (5 cents). 5=immediately proves $0.05. 1=answers $0.10 or wrong amount.",
493 ],
494 },
495 },
496 {
497 id: "counterfeit-coin",
498 name: "12-Coin Balance",
499 prompt:
500 "You have 12 coins, one of which is counterfeit (either heavier or lighter than the others). Using a balance scale at most 3 times, explain a complete procedure that finds the counterfeit coin AND determines whether it is heavier or lighter.",
501 maxScore: 5,
502 judge: {
503 schema: reasonJudgeSchema,
504 instructions: [
505 "5=complete 3-weighing decision tree covering balanced and tilted branches.",
506 "3=starts with 4v4 but hand-waves tilted rotation.",
507 "1=invalid or exceeds 3 weighings.",
508 ],
509 },
510 },
511 ];
512
513 const reasoningSuite = new EvalSuite({
514 name: "model-watch-reasoning",
515 systemPrompt:
516 "Think carefully, give a clear direct answer, and explain your reasoning concisely.",
517 temperature: 0.2,
518 models: suiteModels,
519 judgeModel,
520 judgeDelayMs: isLive ? 200 : 0,
521 concurrency: suiteConcurrency,
522 executionOrder,
523 tasks: isSmoke
524 ? reasoningAllTasks.filter((t) => t.id === "car-wash")
525 : reasoningAllTasks,
526 });
527
528 const knowledgeSuite = new EvalSuite({
529 name: "model-watch-knowledge",
530 systemPrompt:
531 "Answer accurately. Return ONLY the requested JSON object with no markdown fences.",
532 temperature: 0,
533 models: suiteModels,
534 concurrency: suiteConcurrency,
535 executionOrder,
536 tasks: [
537 {
538 id: "strawberry-91",
539 name: "Adversarial Count & Primality",
540 prompt:
541 'Return JSON: {"strawberry_rs": <integer count of letter r in "strawberry">, "is_91_prime": <boolean>, "smallest_prime_factor_of_91": <integer>}',
542 maxScore: 5,
543 verify: (r) => {
544 const obj = parseLooseJson(r);
545 if (!obj) return { score: 0, details: "Invalid JSON" };
546 let s = 0;
547 if (obj.strawberry_rs === 3) s += 2;
548 if (obj.is_91_prime === false) s += 2;
549 if (obj.smallest_prime_factor_of_91 === 7) s += 1;
550 return { score: s, details: JSON.stringify(obj) };
551 },
552 },
553 {
554 id: "sheep-carbon14",
555 name: "All-But-9 & Carbon-14",
556 prompt:
557 'Return JSON: {"sheep_left": <integer: a farmer has 17 sheep and all but 9 run away, how many are left?>, "c14_half_life_years": <integer standard Libby/Cambridge half-life of Carbon-14 in years>}',
558 maxScore: 5,
559 verify: (r) => {
560 const obj = parseLooseJson(r);
561 if (!obj) return { score: 0, details: "Invalid JSON" };
562 let s = 0;
563 if (obj.sheep_left === 9) s += 3;
564 const hl = Number(obj.c14_half_life_years);
565 if (hl >= 5568 && hl <= 5760) s += 2;
566 return { score: s, details: JSON.stringify(obj) };
567 },
568 },
569 {
570 id: "transformer-https",
571 name: "Transformer & Network Specs",
572 prompt:
573 'Return JSON: {"transformer_base_d_model": <integer d_model of base model in Vaswani et al. 2017>, "transformer_base_heads": <integer h in base model>, "https_default_port": <integer>}',
574 maxScore: 5,
575 verify: (r) => {
576 const obj = parseLooseJson(r);
577 if (!obj) return { score: 0, details: "Invalid JSON" };
578 let s = 0;
579 if (obj.transformer_base_d_model === 512) s += 2;
580 if (obj.transformer_base_heads === 8) s += 2;
581 if (obj.https_default_port === 443) s += 1;
582 return { score: s, details: JSON.stringify(obj) };
583 },
584 },
585 {
586 id: "astana-int32",
587 name: "Geography & Two's Complement",
588 prompt:
589 'Return JSON: {"kazakhstan_capital": <string current capital city>, "max_signed_int32": <integer maximum 32-bit signed two\'s complement integer>}',
590 maxScore: 5,
591 verify: (r) => {
592 const obj = parseLooseJson(r);
593 if (!obj) return { score: 0, details: "Invalid JSON" };
594 let s = 0;
595 if (typeof obj.kazakhstan_capital === "string" && /astana/i.test(obj.kazakhstan_capital))
596 s += 2;
597 if (obj.max_signed_int32 === 2147483647) s += 3;
598 return { score: s, details: JSON.stringify(obj) };
599 },
600 },
601 ],
602 });
603
604 const instructionAllTasks: EvalSuite["config"]["tasks"] = [
605 {
606 id: "word-count",
607 name: "12-Word Ocean",
608 prompt:
609 "Write a sentence about the ocean that contains EXACTLY 12 words. Just the sentence, nothing else.",
610 maxScore: 5,
611 verify: (r) => {
612 const words = r
613 .trim()
614 .replace(/^["']|["']$/g, "")
615 .split(/\s+/)
616 .filter(Boolean);
617 const diff = Math.abs(words.length - 12);
618 if (diff === 0) return { score: 5, details: `${words.length} words ✓` };
619 if (diff <= 1) return { score: 3, details: `${words.length} words (off by ${diff})` };
620 return { score: 0, details: `${words.length} words (wanted 12)` };
621 },
622 },
623 {
624 id: "json-output",
625 name: "Fence-Free Raw JSON",
626 prompt:
627 'Output a JSON object: {"name": string, "age": number 25-35, "skills": array of 3 strings, "active": true}. No markdown fences, no explanation.',
628 maxScore: 5,
629 verify: (r) => {
630 let s = 0;
631 const fails: string[] = [];
632 const clean = r
633 .trim()
634 .replace(/^```json?\n?/, "")
635 .replace(/\n?```$/, "")
636 .trim();
637 try {
638 const obj = JSON.parse(clean) as Record<string, unknown>;
639 if (typeof obj.name === "string" && obj.name.length > 0) s++;
640 else fails.push("name");
641 if (typeof obj.age === "number" && obj.age >= 25 && obj.age <= 35) s++;
642 else fails.push("age");
643 if (Array.isArray(obj.skills) && obj.skills.length === 3) s++;
644 else fails.push("skills");
645 if (obj.active === true) s++;
646 else fails.push("active");
647 if (!r.includes("```")) s++;
648 else fails.push("fences");
649 } catch {
650 return { score: 0, details: "Invalid JSON" };
651 }
652 return { score: s, details: fails.length ? `Failed: ${fails.join(", ")}` : "Perfect" };
653 },
654 },
655 {
656 id: "negative-constraints",
657 name: "Negative Constraints",
658 prompt:
659 'Write 2 sentences about a sunset, each on its own line. Do NOT use: "beautiful", "sky", "orange". No exclamation marks.',
660 maxScore: 5,
661 verify: (r) => {
662 let s = 0;
663 const fails: string[] = [];
664 const lo = r.toLowerCase();
665 if (!lo.includes("beautiful")) s++;
666 else fails.push('"beautiful"');
667 if (!lo.includes("sky")) s++;
668 else fails.push('"sky"');
669 if (!lo.includes("orange")) s++;
670 else fails.push('"orange"');
671 if (!r.includes("!")) s++;
672 else fails.push("!");
673 const lines = r
674 .trim()
675 .split("\n")
676 .filter((l) => l.trim());
677 if (lines.length === 2) s++;
678 else fails.push(`${lines.length} lines`);
679 return {
680 score: s,
681 details: fails.length ? `Failed: ${fails.join(", ")}` : "All constraints met",
682 };
683 },
684 },
685 {
686 id: "markdown-table",
687 name: "CSV to MD Table",
688 prompt:
689 "Convert to a markdown table (Name, Age, Role columns):\nAlice, 28, Engineer\nBob, 34, Designer\nCharlie, 22, Student\nOutput ONLY the table.",
690 maxScore: 5,
691 verify: (r) => {
692 const lines = r
693 .trim()
694 .split("\n")
695 .filter((l) => l.trim());
696 let s = 0;
697 const fails: string[] = [];
698 if (lines.length === 5 && !r.includes("```")) s++;
699 else fails.push(`${lines.length} lines / fences`);
700 if (lines[0] && /Name/i.test(lines[0]) && /Age/i.test(lines[0])) s++;
701 else fails.push("header");
702 if (lines[1] && /[-|]+/.test(lines[1])) s++;
703 else fails.push("separator");
704 const hasData =
705 lines.some((l) => /Alice/i.test(l) && /28/.test(l)) &&
706 lines.some((l) => /Bob/i.test(l) && /34/.test(l));
707 if (hasData) s++;
708 else fails.push("data");
709 if (lines.every((l) => l.includes("|"))) s++;
710 else fails.push("pipes");
711 return { score: s, details: fails.length ? `Failed: ${fails.join(", ")}` : "Perfect table" };
712 },
713 },
714 {
715 id: "acrostic-8words",
716 name: "Acrostic + Exact 8-Word Lines",
717 prompt:
718 "Write 5 lines about distributed systems where: (1) the first letters of the 5 lines spell P-A-R-E-T in order, (2) EVERY line contains EXACTLY 8 words (hyphenated words count as 1 word; no numbering or bullets), and (3) the letter 'z' (case-insensitive) never appears. Output ONLY the 5 lines.",
719 maxScore: 5,
720 verify: (r) => {
721 const lines = r
722 .trim()
723 .split("\n")
724 .map((l) => l.trim())
725 .filter(Boolean);
726 if (lines.length !== 5) {
727 return { score: 0, details: `Expected 5 lines, got ${lines.length}` };
728 }
729 const target = ["P", "A", "R", "E", "T"];
730 const acrosticOk = lines.every(
731 (l, idx) => l.replace(/^[^A-Za-z]+/, "")[0]?.toUpperCase() === target[idx],
732 );
733 const wordCounts = lines.map((l) => l.split(/\s+/).filter(Boolean).length);
734 const exactEightCount = wordCounts.filter((c) => c === 8).length;
735 const noZ = !/z/i.test(r);
736 let score = 0;
737 if (acrosticOk) score += 1;
738 if (noZ) score += 1;
739 if (exactEightCount === 5) score += 3;
740 else if (exactEightCount >= 4) score += 2;
741 else if (exactEightCount >= 3) score += 1;
742 return {
743 score,
744 details: `acrostic=${acrosticOk}, 8w=${exactEightCount}/5 [${wordCounts.join(",")}], noZ=${noZ}`,
745 };
746 },
747 },
748 ];
749
750 const instructionSuite = new EvalSuite({
751 name: "model-watch-instruction",
752 systemPrompt:
753 "Follow the given instructions with exact format compliance. Output ONLY what is requested — no extra prose or markdown fences.",
754 temperature: 0,
755 models: suiteModels,
756 concurrency: suiteConcurrency,
757 executionOrder,
758 tasks: isSmoke
759 ? instructionAllTasks.filter((t) => t.id === "json-output")
760 : instructionAllTasks,
761 });
762
763 const codingSuite = new EvalSuite({
764 name: "model-watch-coding",
765 systemPrompt:
766 "Output ONLY valid JavaScript ES module code (`export function ...`). Do not include explanations outside code.",
767 temperature: 0,
768 models: suiteModels,
769 concurrency: suiteConcurrency,
770 executionOrder,
771 tasks: [
772 {
773 id: "rail-fence-cipher",
774 name: "Rail Fence Cipher (JS ESM)",
775 prompt:
776 "Write a JavaScript ES module exporting `encode(text, rails)` and `decode(cipher, rails)` implementing the classic Rail Fence (zigzag) cipher. Handle `rails <= 1` or `rails >= text.length` by returning the input unchanged. Output ONLY the JS module code.",
777 maxScore: 10,
778 verify: (r) => {
779 const code = stripCodeFences(r);
780 const harness = `
781import { encode, decode } from "./solution.mjs";
782const cases = [
783 ["rail3_enc", () => encode("WEAREDISCOVEREDFLEEATONCE", 3) === "WECRLTEERDSOEEFEAOCAIVDEN"],
784 ["rail3_dec", () => decode("WECRLTEERDSOEEFEAOCAIVDEN", 3) === "WEAREDISCOVEREDFLEEATONCE"],
785 ["rail4_enc", () => encode("ATTACKATDAWN", 4) === "AATKTNTCDWAA" && decode("AATKTNTCDWAA", 4) === "ATTACKATDAWN"],
786 ["rail4_exact", () => encode("EXACTRAILFENCE", 4) === "EACXRINEATLECF" && decode("EACXRINEATLECF", 4) === "EXACTRAILFENCE"],
787 ["edge_short", () => encode("HI", 5) === "HI" && decode("HI", 1) === "HI"],
788];
789let passed = 0; const failures = [];
790for (const [name, fn] of cases) {
791 try { if (fn()) passed++; else failures.push(name); } catch (e) { failures.push(name + ":" + e.message); }
792}
793console.log(JSON.stringify({ passed, total: cases.length, failures }));
794`;
795 const res = runNodeHarness(code, harness);
796 return { score: res.passed * 2, details: res.details };
797 },
798 },
799 {
800 id: "business-days",
801 name: "Business Days w/ Holidays (JS ESM)",
802 prompt:
803 "Write a JavaScript ES module exporting `countBusinessDays(startIso, endIso, holidays = [])` where `startIso` and `endIso` are `'YYYY-MM-DD'` UTC dates (`startIso <= endIso`) and `holidays` is an array of `'YYYY-MM-DD'` strings. Return the count of weekdays (Mon–Fri) INCLUSIVE of both `startIso` and `endIso` that are NOT in `holidays` (a weekend holiday must not double-subtract). Output ONLY the JS module code.",
804 maxScore: 10,
805 verify: (r) => {
806 const code = stripCodeFences(r);
807 const harness = `
808import { countBusinessDays } from "./solution.mjs";
809const cases = [
810 ["mon_to_fri", () => countBusinessDays("2025-03-03", "2025-03-07", []) === 5],
811 ["across_wknd", () => countBusinessDays("2025-03-07", "2025-03-10", []) === 2],
812 ["weekday_hol", () => countBusinessDays("2025-07-01", "2025-07-07", ["2025-07-04"]) === 4],
813 ["sat_holiday", () => countBusinessDays("2026-07-03", "2026-07-06", ["2026-07-04"]) === 2],
814 ["leap_feb24", () => countBusinessDays("2024-02-28", "2024-03-01", []) === 3],
815];
816let passed = 0; const failures = [];
817for (const [name, fn] of cases) {
818 try { if (fn()) passed++; else failures.push(name); } catch (e) { failures.push(name + ":" + e.message); }
819}
820console.log(JSON.stringify({ passed, total: cases.length, failures }));
821`;
822 const res = runNodeHarness(code, harness);
823 return { score: res.passed * 2, details: res.details };
824 },
825 },
826 {
827 id: "rational-evaluator",
828 name: "Exact Rational Expression Parser (JS ESM)",
829 prompt:
830 "Write a JavaScript ES module exporting `evaluateRational(expr)` that evaluates an arithmetic string using exact arbitrary-precision rational arithmetic (`BigInt`) and returns a canonical reduced string `'num/den'` with `den > 0` (or `'num'` when `den === 1`). Support integers, `+`, `-`, `*`, `/` (exact fraction division), parentheses `(...)`, unary `-`, and integer exponentiation `^` where: (a) `^` is RIGHT-associative (`'2 ^ 3 ^ 2'` -> `'512'`), (b) unary `-` has LOWER precedence than `^` (`'-2 ^ 2'` -> `'-4'`, while `'(-2) ^ 2'` -> `'4'`, and `'2 ^ -3'` -> `'1/8'`), and (c) division by zero throws an `Error`. Output ONLY the JS module code.",
831 maxScore: 10,
832 verify: (r) => {
833 const code = stripCodeFences(r);
834 const harness = `
835import { evaluateRational } from "./solution.mjs";
836const cases = [
837 ["frac_sum", () => evaluateRational("1/3 + 1/6") === "1/2" && evaluateRational("6 / 3") === "2"],
838 ["right_exp", () => evaluateRational("2 ^ 3 ^ 2") === "512"],
839 ["unary_prec", () => evaluateRational("-2 ^ 2") === "-4" && evaluateRational("(-2) ^ 2") === "4" && evaluateRational("2 ^ -3") === "1/8"],
840 ["nested_neg", () => evaluateRational("(1/3 - 5/6) / (3/4)") === "-2/3"],
841 ["div_zero", () => { try { evaluateRational("5 / (1/2 - 2/4)"); return false; } catch { return true; } }],
842];
843let passed = 0; const failures = [];
844for (const [name, fn] of cases) {
845 try { if (fn()) passed++; else failures.push(name); } catch (e) { failures.push(name + ":" + e.message); }
846}
847console.log(JSON.stringify({ passed, total: cases.length, failures }));
848`;
849 const res = runNodeHarness(code, harness);
850 return { score: res.passed * 2, details: res.details };
851 },
852 },
853 ],
854 });
855
856 const toolsAllTasks: EvalSuite["config"]["tasks"] = [
857 {
858 id: "grocery-total",
859 name: "Chained Grocery + Tax",
860 prompt:
861 "Compute the total cost of: 3 apples at $1.25 each, 2 loaves of bread at $3.50 each, 4 bottles of water at $0.75 each, and 1 cake at $12.99. Add 8% sales tax, rounded to cents. Use the calculator tool and end your response with the final dollar number (e.g. 28.88).",
862 maxScore: 5,
863 verify: (response, turn) => {
864 const hasExact = /28\.88/.test(response);
865 const calls = turn?.toolCalls.length ?? 0;
866 return {
867 score: (hasExact ? 3 : 0) + (calls >= 3 ? 2 : calls >= 1 ? 1 : 0),
868 details: `exact28.88=${hasExact}, toolCalls=${calls}`,
869 };
870 },
871 },
872 {
873 id: "stats-invoice",
874 name: "Statistics + Margin Tool Chain",
875 prompt:
876 "Use the `statistics` tool to find the mean of [14.5, 22.0, 18.25, 31.75, 19.5], then use `calculator` to multiply that mean by 1.15 (15% markup). End with the exact final number.",
877 maxScore: 5,
878 verify: (response, turn) => {
879 const hasExact = /24\.38/.test(response);
880 const usedStats = turn?.toolCalls.some((c) => c.toolName === "statistics") ?? false;
881 const usedCalc = turn?.toolCalls.some((c) => c.toolName === "calculator") ?? false;
882 return {
883 score: (hasExact ? 3 : 0) + (usedStats ? 1 : 0) + (usedCalc ? 1 : 0),
884 details: `exact24.38=${hasExact}, stats=${usedStats}, calc=${usedCalc}, calls=${turn?.toolCalls.length ?? 0}`,
885 };
886 },
887 },
888 ];
889
890 const toolsSuite = new EvalSuite({
891 name: "model-watch-tools",
892 systemPrompt:
893 "You are a careful quantitative analyst. Use the provided calculator and statistics tools for every arithmetic step, and end your final answer with the exact numeric result.",
894 temperature: 0,
895 tools: { calculator: calculatorTool, statistics: statisticsTool },
896 models: suiteModels,
897 concurrency: suiteConcurrency,
898 executionOrder,
899 tasks: isSmoke
900 ? toolsAllTasks.filter((t) => t.id === "grocery-total")
901 : toolsAllTasks,
902 });
903
904 return {
905 reasoningSuite,
906 knowledgeSuite,
907 instructionSuite,
908 codingSuite,
909 toolsSuite,
910 };
911 };
912
913 const reasoningRecords: TaskResultRecord[] = [];
914 const knowledgeRecords: TaskResultRecord[] = [];
915 const instructionRecords: TaskResultRecord[] = [];
916 const codingRecords: TaskResultRecord[] = [];
917 const toolsRecords: TaskResultRecord[] = [];
918 let judgeCostUsd = 0;
919
920 async function runBatch(
921 batchModels: ModelSpec[],
922 batchConcurrency: number,
923 executionOrder: "task-first" | "model-first",
924 ) {
925 if (batchModels.length === 0) return;
926 const suites = buildSuites(batchModels, batchConcurrency, executionOrder);
927 reasoningRecords.push(...(await suites.reasoningSuite.run()));
928 if (!isSmoke) {
929 knowledgeRecords.push(...(await suites.knowledgeSuite.run()));
930 }
931 instructionRecords.push(...(await suites.instructionSuite.run()));
932 if (!isSmoke) {
933 codingRecords.push(...(await suites.codingSuite.run()));
934 }
935 toolsRecords.push(...(await suites.toolsSuite.run()));
936 judgeCostUsd +=
937 suites.reasoningSuite.getLastRunStats().judgeCostUsd +
938 (isSmoke ? 0 : suites.knowledgeSuite.getLastRunStats().judgeCostUsd) +
939 suites.instructionSuite.getLastRunStats().judgeCostUsd +
940 (isSmoke ? 0 : suites.codingSuite.getLastRunStats().judgeCostUsd) +
941 suites.toolsSuite.getLastRunStats().judgeCostUsd;
942 }
943
944 if (isLive) {
945 const cloudModels = models.filter(
946 (m) => m.tier === "cloud" && !isLocalProviderName(m.provider),
947 );
948 const localModels = models.filter(
949 (m) => m.tier === "local" || isLocalProviderName(m.provider),
950 );
951 await runBatch(cloudModels, concurrency, "task-first");
952 // Run each local model through all 5 suites sequentially so weights stay hot in RAM
953 for (const lm of localModels) {
954 await runBatch([lm], 1, "model-first");
955 }
956 } else {
957 await runBatch(models, concurrency, "task-first");
958 }
959
960 const groceryEntries = toolsRecords
961 .filter((r) => r.taskId === "grocery-total" && !r.error && r.responseText.trim().length > 0)
962 .map((r) => ({
963 key: formatModelSpecString({
964 provider: r.provider,
965 name: r.model,
966 reasoningEffort: r.reasoningEffort as ThinkingEffort | undefined,
967 }),
968 provider: r.provider,
969 model: r.model,
970 responseText: r.responseText,
971 }));
972
973 let eloByKey = new Map<string, number>();
974 let eloJudgeCostUsd = 0;
975 if (!isSmoke && groceryEntries.length >= 2) {
976 const ranker = new PairwiseRanker(groceryEntries, {
977 judgeModel,
978 judgeInstructions: [
979 "Prefer exact $28.88 ($26.74 subtotal + $2.14 tax) with concise step breakdown.",
980 ],
981 pairingMode: groceryEntries.length > 8 ? "swiss" : "all",
982 swissRounds: 4,
983 cacheDir: path.join(evalRoot, "model-watch-elo", "runs", "001"),
984 delayMs: isLive ? 250 : 0,
985 });
986 const ranked = await ranker.rank();
987 eloJudgeCostUsd = ranked.judgeCostUsd ?? 0;
988 eloByKey = new Map(
989 ranked.rankings.map((e) => [e.key, Math.round(e.elo)]),
990 );
991 }
992
993 function sumModel(records: TaskResultRecord[], m: MatrixModelEntry) {
994 const normEff = canonicalizeThinkingEffort(m.reasoningEffort);
995 const mine = records.filter(
996 (r) =>
997 r.provider === m.provider &&
998 r.model === m.name &&
999 (r.reasoningEffort ?? undefined) === normEff,
1000 );
1001 const score = mine.reduce((s, r) => s + r.score, 0);
1002 const maxScore = mine.reduce((s, r) => s + r.maxScore, 0);
1003 const cost = mine.reduce((s, r) => s + r.cost, 0);
1004 const durationMs = mine.reduce((s, r) => s + r.durationMs, 0);
1005 let prompt = 0;
1006 let completion = 0;
1007 let cacheRead = 0;
1008 let cacheWrite = 0;
1009 let reasoning = 0;
1010 let total = 0;
1011 let effectiveLevel: string | undefined;
1012
1013 const tasks = mine.map((r) => {
1014 const tu = r.tokenUsage;
1015 prompt += tu?.promptTokens ?? 0;
1016 completion += tu?.completionTokens ?? 0;
1017 cacheRead += tu?.cacheReadTokens ?? 0;
1018 cacheWrite += tu?.cacheWriteTokens ?? 0;
1019 reasoning += tu?.reasoningTokens ?? 0;
1020 total += tu?.total ?? 0;
1021 if (!effectiveLevel && r.effectiveThinkingLevel) {
1022 effectiveLevel = r.effectiveThinkingLevel;
1023 }
1024 return {
1025 taskId: r.taskId,
1026 score: r.score,
1027 maxScore: r.maxScore,
1028 details: r.details,
1029 costUsd: Number(r.cost.toFixed(6)),
1030 durationMs: r.durationMs,
1031 ...(tu
1032 ? {
1033 tokens: {
1034 prompt: tu.promptTokens ?? 0,
1035 completion: tu.completionTokens ?? 0,
1036 cacheRead: tu.cacheReadTokens ?? 0,
1037 cacheWrite: tu.cacheWriteTokens ?? 0,
1038 reasoning: tu.reasoningTokens ?? 0,
1039 total: tu.total ?? 0,
1040 },
1041 }
1042 : {}),
1043 ...(r.error ? { error: r.error } : {}),
1044 };
1045 });
1046 return {
1047 score,
1048 maxScore,
1049 pct: maxScore > 0 ? Number(((score / maxScore) * 100).toFixed(1)) : 0,
1050 cost,
1051 durationMs,
1052 effectiveLevel,
1053 tokens: { prompt, completion, cacheRead, cacheWrite, reasoning, total },
1054 tasks,
1055 };
1056 }
1057
1058 const rows = models.map((m) => {
1059 const r = sumModel(reasoningRecords, m);
1060 const k = sumModel(knowledgeRecords, m);
1061 const i = sumModel(instructionRecords, m);
1062 const c = sumModel(codingRecords, m);
1063 const t = sumModel(toolsRecords, m);
1064 const combined = isSmoke
1065 ? Number(((r.pct + i.pct + t.pct) / 3).toFixed(1))
1066 : Number(((r.pct + k.pct + i.pct + c.pct + t.pct) / 5).toFixed(1));
1067 const totalCost = Number((r.cost + k.cost + i.cost + c.cost + t.cost).toFixed(5));
1068 const totalDurationSec = Number(
1069 ((r.durationMs + k.durationMs + i.durationMs + c.durationMs + t.durationMs) / 1000).toFixed(1),
1070 );
1071 const tokens = {
1072 prompt: r.tokens.prompt + k.tokens.prompt + i.tokens.prompt + c.tokens.prompt + t.tokens.prompt,
1073 completion:
1074 r.tokens.completion +
1075 k.tokens.completion +
1076 i.tokens.completion +
1077 c.tokens.completion +
1078 t.tokens.completion,
1079 cacheRead:
1080 r.tokens.cacheRead +
1081 k.tokens.cacheRead +
1082 i.tokens.cacheRead +
1083 c.tokens.cacheRead +
1084 t.tokens.cacheRead,
1085 cacheWrite:
1086 r.tokens.cacheWrite +
1087 k.tokens.cacheWrite +
1088 i.tokens.cacheWrite +
1089 c.tokens.cacheWrite +
1090 t.tokens.cacheWrite,
1091 reasoning:
1092 r.tokens.reasoning +
1093 k.tokens.reasoning +
1094 i.tokens.reasoning +
1095 c.tokens.reasoning +
1096 t.tokens.reasoning,
1097 total: r.tokens.total + k.tokens.total + i.tokens.total + c.tokens.total + t.tokens.total,
1098 };
1099 const isLocal = m.tier === "local" || isLocalProviderName(m.provider);
1100 const catalogCost = isLocal ? null : getCatalogModelInfo(m).cost;
1101 const pricingPerMillion = isLocal
1102 ? { promptTokens: 0, completionTokens: 0 }
1103 : catalogCost
1104 ? {
1105 promptTokens: catalogCost.promptTokens,
1106 completionTokens: catalogCost.completionTokens,
1107 }
1108 : m.costs
1109 ? {
1110 promptTokens: m.costs.promptTokens,
1111 completionTokens: m.costs.completionTokens,
1112 }
1113 : null;
1114 const specStr = formatModelSpecString(m);
1115 const reasoningEffort = canonicalizeThinkingEffort(m.reasoningEffort) ?? "default";
1116 const effectiveThinkingLevel =
1117 r.effectiveLevel ??
1118 c.effectiveLevel ??
1119 i.effectiveLevel ??
1120 k.effectiveLevel ??
1121 t.effectiveLevel ??
1122 reasoningEffort;
1123
1124 return {
1125 id: m.name,
1126 provider: m.provider,
1127 tier: isLocal ? ("local" as const) : ("cloud" as const),
1128 weights: inferWeights(m.name, m.provider),
1129 reasoningEffort,
1130 effectiveThinkingLevel,
1131 pricingPerMillion,
1132 combined,
1133 reasoning: r.pct,
1134 reasoningRaw: `${r.score}/${r.maxScore}`,
1135 knowledge: k.pct,
1136 knowledgeRaw: `${k.score}/${k.maxScore}`,
1137 instruction: i.pct,
1138 instructionRaw: `${i.score}/${i.maxScore}`,
1139 coding: c.pct,
1140 codingRaw: `${c.score}/${c.maxScore}`,
1141 tools: t.pct,
1142 toolsRaw: `${t.score}/${t.maxScore}`,
1143 elo: eloByKey.get(specStr) ?? null,
1144 cost: totalCost,
1145 timeSec: totalDurationSec,
1146 tokens,
1147 tokPerSec:
1148 totalDurationSec > 0
1149 ? Number((tokens.completion / totalDurationSec).toFixed(1))
1150 : null,
1151 taskBreakdown: {
1152 reasoning: r.tasks,
1153 knowledge: k.tasks,
1154 instruction: i.tasks,
1155 coding: c.tasks,
1156 tools: t.tasks,
1157 },
1158 };
1159 });
1160
1161 rows.sort((a, b) => b.combined - a.combined || a.cost - b.cost);
1162 return {
1163 rows,
1164 judgeCostUsd: Number(judgeCostUsd.toFixed(5)),
1165 eloJudgeCostUsd: Number(eloJudgeCostUsd.toFixed(5)),
1166 };
1167}
1168
1169function captureExampleStdout(args: string[]): string {
1170 const out = execFileSync("pnpm", ["tsx", ...args], {
1171 cwd: ROOT,
1172 timeout: 45_000,
1173 encoding: "utf8",
1174 stdio: ["ignore", "pipe", "pipe"],
1175 });
1176 return out
1177 // eslint-disable-next-line no-control-regex
1178 .replace(/\x1b\[[0-9;]*m/g, "")
1179 .replace(/\/tmp\/[A-Za-z0-9_-]+/g, "/tmp/umwelten-run")
1180 .replace(/127\.0\.0\.1:\d+/g, "127.0.0.1:<port>")
1181 .trim();
1182}
1183
1184async function main() {
1185 fs.mkdirSync(DATA_DIR, { recursive: true });
1186
1187 const suiteArg = (values.suite ?? "full").trim().toLowerCase();
1188 if (suiteArg !== "smoke" && suiteArg !== "full") {
1189 throw new Error(`Invalid --suite "${values.suite}". Expected "smoke" or "full".`);
1190 }
1191 const isSmoke = suiteArg === "smoke";
1192
1193 const isLiveMode = process.argv.includes("--live");
1194 const { active, unavailable, judgeModel } = await resolveTargetModels(isLiveMode);
1195
1196 const runtime = setupExampleRuntime(active, { fresh: values.fresh });
1197 const isLive = runtime.mode === "live";
1198
1199 const requestedConcurrency = values.concurrency
1200 ? parseInt(values.concurrency, 10)
1201 : undefined;
1202 const effectiveConcurrency =
1203 requestedConcurrency && Number.isFinite(requestedConcurrency) && requestedConcurrency > 0
1204 ? requestedConcurrency
1205 : isLive
1206 ? 2
1207 : 6;
1208
1209 const watch = await runModelWatchSuites(
1210 active,
1211 judgeModel,
1212 runtime.evalDir,
1213 effectiveConcurrency,
1214 isLive,
1215 isSmoke,
1216 );
1217
1218 const outFilename =
1219 isSmoke && !values.merge
1220 ? "model-watch-smoke.json"
1221 : isLive
1222 ? "model-watch-live.json"
1223 : "model-watch-mock.json";
1224 const outPath = path.join(DATA_DIR, outFilename);
1225
1226 let finalRows = watch.rows;
1227 if (values.merge && fs.existsSync(outPath)) {
1228 try {
1229 const prev = JSON.parse(fs.readFileSync(outPath, "utf8")) as {
1230 models?: typeof watch.rows;
1231 };
1232 if (Array.isArray(prev.models)) {
1233 const mergedMap = new Map<string, (typeof watch.rows)[number]>();
1234 for (const row of prev.models) {
1235 mergedMap.set(rowKey(row), row);
1236 }
1237 for (const row of watch.rows) {
1238 mergedMap.set(rowKey(row), row);
1239 }
1240 finalRows = Array.from(mergedMap.values()).sort(
1241 (a, b) => b.combined - a.combined || a.cost - b.cost,
1242 );
1243 }
1244 } catch {
1245 // Ignore corrupt prior JSON and write fresh rows
1246 }
1247 }
1248
1249 const totalSuiteCostUsd = Number(
1250 finalRows.reduce((s, r) => s + r.cost, 0).toFixed(5),
1251 );
1252 const totalRunCostUsd = Number(
1253 (totalSuiteCostUsd + watch.judgeCostUsd + watch.eloJudgeCostUsd).toFixed(5),
1254 );
1255
1256 const watchPayload = {
1257 mode: runtime.mode,
1258 suite: isSmoke ? "smoke" : "full",
1259 generatedAt: new Date().toISOString(),
1260 reproduceCommand: isSmoke
1261 ? isLive
1262 ? "pnpm run site:bench -- --live --suite smoke"
1263 : "pnpm run site:bench -- --mock --suite smoke"
1264 : isLive
1265 ? "pnpm run site:bench --live"
1266 : "pnpm run site:bench",
1267 freshCommand: isSmoke
1268 ? isLive
1269 ? "pnpm run site:bench -- --live --suite smoke --fresh"
1270 : "pnpm run site:bench -- --mock --suite smoke --fresh"
1271 : isLive
1272 ? "pnpm run site:bench --live --fresh"
1273 : "pnpm run site:bench --fresh",
1274 judgeModel: formatModelSpecString(judgeModel),
1275 dimensions: isSmoke
1276 ? [
1277 { id: "reasoning", label: "Smoke: Car Wash", maxScore: 5, tasks: 1, scoring: "Zod JudgeTask" },
1278 { id: "instruction", label: "Smoke: Strict JSON", maxScore: 5, tasks: 1, scoring: "Deterministic Verify" },
1279 { id: "tools", label: "Smoke: Calculator Tool", maxScore: 5, tasks: 1, scoring: "Tool-Call + Math" },
1280 ]
1281 : [
1282 { id: "reasoning", label: "Reasoning Traps", maxScore: 20, tasks: 4, scoring: "Zod JudgeTask" },
1283 { id: "knowledge", label: "Adversarial Knowledge", maxScore: 20, tasks: 4, scoring: "Deterministic JSON" },
1284 { id: "instruction", label: "Strict Format Compliance", maxScore: 25, tasks: 5, scoring: "Deterministic Verify" },
1285 { id: "coding", label: "Executed JS/ESM Coding", maxScore: 30, tasks: 3, scoring: "Node Subprocess (15 vectors)" },
1286 { id: "tools", label: "Multi-Step Tool Chaining", maxScore: 10, tasks: 2, scoring: "Tool-Call Count + Exact Math + Elo" },
1287 ],
1288 totalSuiteCostUsd,
1289 judgeCostUsd: watch.judgeCostUsd,
1290 eloJudgeCostUsd: watch.eloJudgeCostUsd,
1291 totalRunCostUsd,
1292 models: finalRows,
1293 unavailableCatalogueModels: unavailable,
1294 };
1295
1296 fs.writeFileSync(
1297 outPath,
1298 JSON.stringify(watchPayload, null, 2) + "\n",
1299 "utf8",
1300 );
1301
1302 if (isSmoke) {
1303 console.log("\nSmoke Check Summary (3 tasks: car-wash, json-output, grocery-total):");
1304 console.log(
1305 "Model".padEnd(36),
1306 "Effort".padEnd(8),
1307 "Combined".padEnd(9),
1308 "Tokens".padEnd(8),
1309 "Tok/s".padEnd(7),
1310 "Time",
1311 );
1312 console.log("-".repeat(78));
1313 for (const r of finalRows) {
1314 console.log(
1315 `${r.provider}:${r.id}`.slice(0, 35).padEnd(36),
1316 r.reasoningEffort.padEnd(8),
1317 `${r.combined}%`.padEnd(9),
1318 String(r.tokens.total).padEnd(8),
1319 String(r.tokPerSec ?? "-").padEnd(7),
1320 `${r.timeSec}s`,
1321 );
1322 }
1323 }
1324
1325 if (!isSmoke && isLive && process.env.MYCEL_API_KEY) {
1326 const families = ["support", "evidence", "completion"] as const;
1327 const cases = [0, 1, 2].flatMap((idx) =>
1328 families.map((f) => structuredClone(PILOT_CASES.filter((c) => c.family === f)[idx])),
1329 );
1330 const jevOut = path.join(ROOT, "output", "jev", "model-watch-native");
1331 const llmOut = path.join(ROOT, "output", "jev", "model-watch-llm");
1332 const jevBackend = createJevBackend({ provider: "mycel", model: "typesafe/jev-1.13" });
1333 const llmBackend = createLlmJudgmentBackend(judgeModel);
1334 const jevRun = await runPilot(jevBackend, cases, jevOut, {});
1335 const llmRun = await runPilot(llmBackend, cases, llmOut, {});
1336 fs.writeFileSync(
1337 path.join(DATA_DIR, "jev-live.json"),
1338 JSON.stringify(
1339 {
1340 executedAt: new Date().toISOString(),
1341 caseCount: cases.length,
1342 reproduceCommand: "pnpm tsx examples/jev/run.ts --backend mycel --live --limit 9",
1343 nativeJev: { backend: jevBackend.identity, summary: summarizePilot(jevRun.records) },
1344 llmBaseline: { backend: llmBackend.identity, summary: summarizePilot(llmRun.records) },
1345 },
1346 null,
1347 2,
1348 ) + "\n",
1349 "utf8",
1350 );
1351 }
1352
1353 // Execute every standalone example script cleanly and capture verbatim stdout
1354 if (!isLive && !isSmoke) {
1355 console.log("\nExecuting standalone example scripts in mock mode to capture outputs...");
1356 const examplesMock = {
1357 mode: "mock" as const,
1358 generatedAt: new Date().toISOString(),
1359 outputs: {
1360 "car-wash-traps": captureExampleStdout(["examples/evals/car-wash.ts"]),
1361 "reasoning-puzzles": captureExampleStdout(["examples/evals/reasoning.ts"]),
1362 "instruction-compliance": captureExampleStdout(["examples/evals/instruction.ts"]),
1363 "tool-math-elo": captureExampleStdout(["examples/evals/tool-math.ts"]),
1364 "model-showdown-combiner": captureExampleStdout(["examples/model-showdown/generate-report.ts"]),
1365 "jev-calibration": captureExampleStdout(["examples/jev/run.ts", "--mock"]),
1366 "pi-extension-sessions": captureExampleStdout(["examples/pi-extension/demo.ts"]),
1367 "durable-habitat-a2a": captureExampleStdout(["examples/durable-habitat/host.ts"]),
1368 "mycel-exchange-e2e": captureExampleStdout(["examples/mycel-e2e/run.ts"]),
1369 },
1370 };
1371 fs.writeFileSync(
1372 path.join(DATA_DIR, "examples-mock.json"),
1373 JSON.stringify(examplesMock, null, 2) + "\n",
1374 "utf8",
1375 );
1376 }
1377
1378 console.log(`\n✅ Wrote ${outFilename} -> ${DATA_DIR}`);
1379}
1380
1381main().catch((err) => {
1382 console.error("Benchmark failed:", err);
1383 process.exit(1);
1384});
Captured stdout from running pnpm run site:bench
{
"generatedAt": "2026-11-22T12:06:16.802Z",
"judgeModel": "google:gemini-4-hydrogen",
"totalSuiteCostUsd": 0.43959,
"judgeCostUsd": 0.12305,
"eloJudgeCostUsd": 0.10356,
"totalRunCostUsd": 0.6662,
"unavailableCatalogueModels": [
{
"provider": "llamaswap",
"name": "gemma-4-26b-a4b",
"error": "Connection error.: AggregateError (ECONNREFUSED)"
},
{
"provider": "llamaswap",
"name": "gemma-4-31b",
"error": "Connection error.: AggregateError (ECONNREFUSED)"
},
{
"provider": "llamaswap",
"name": "gpt-oss-20b",
"error": "Connection error.: AggregateError (ECONNREFUSED)"
},
{
"provider": "llamaswap",
"name": "nvidia-nemotron-3-nano-4b",
"error": "Connection error.: AggregateError (ECONNREFUSED)"
},
{
"provider": "llamaswap",
"name": "gemma-4-e2b",
"error": "Connection error.: AggregateError (ECONNREFUSED)"
},
{
"provider": "llamaswap",
"name": "qwen3-6-27b",
"error": "Connection error.: AggregateError (ECONNREFUSED)"
}
],
"standings": [
{
"model": "openrouter:z-ai/glm-5.3-flash",
"effort": "default",
"combined": "98%",
"scores": "R:18/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1500,
"tokens": 38172,
"tokPerSec": 124.1,
"costUsd": 0.00244,
"timeSec": 201.3
},
{
"model": "anthropic:claude-haiku-5-5",
"effort": "default",
"combined": "98%",
"scores": "R:18/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1532,
"tokens": 27419,
"tokPerSec": 212,
"costUsd": 0.00739,
"timeSec": 64.1
},
{
"model": "google:gemini-3.8-flash",
"effort": "default",
"combined": "98%",
"scores": "R:18/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1532,
"tokens": 24511,
"tokPerSec": 102.2,
"costUsd": 0.07011,
"timeSec": 168.8
},
{
"model": "anthropic:claude-sonnet-5-5",
"effort": "default",
"combined": "98%",
"scores": "R:18/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1500,
"tokens": 21344,
"tokPerSec": 114.8,
"costUsd": 0.09737,
"timeSec": 76.1
},
{
"model": "google:gemini-4-hydrogen",
"effort": "default",
"combined": "98%",
"scores": "R:18/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1517,
"tokens": 25598,
"tokPerSec": 163.6,
"costUsd": 0.14449,
"timeSec": 108.1
},
{
"model": "openrouter:moonshotai/kimi-k3.1-pro",
"effort": "default",
"combined": "97.2%",
"scores": "R:18/20 K:20/20 I:24/25 C:30/30 T:10/10",
"elo": 1469,
"tokens": 11214,
"tokPerSec": 113.8,
"costUsd": 0.04764,
"timeSec": 31.4
},
{
"model": "openrouter:google/gemma-4-26b-a4b-it",
"effort": "default",
"combined": "97%",
"scores": "R:17/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1499,
"tokens": 16579,
"tokPerSec": 121.9,
"costUsd": 0.00315,
"timeSec": 81.3
},
{
"model": "openrouter:minimax/minimax-m3.1-flash",
"effort": "default",
"combined": "97%",
"scores": "R:17/20 K:20/20 I:25/25 C:30/30 T:10/10",
"elo": 1500,
"tokens": 39017,
"tokPerSec": 239.9,
"costUsd": 0.0149,
"timeSec": 96.3
},
{
"model": "openrouter:google/gemma-4-31b-it",
"effort": "default",
"combined": "95.9%",
"scores": "R:18/20 K:20/20 I:24/25 C:28/30 T:10/10",
"elo": 1468,
"tokens": 8301,
"tokPerSec": 117.2,
"costUsd": 0.00165,
"timeSec": 27.9
},
{
"model": "google:gemini-3.1-flash-lite",
"effort": "default",
"combined": "94.7%",
"scores": "R:16/20 K:20/20 I:25/25 C:28/30 T:10/10",
"elo": 1517,
"tokens": 8169,
"tokPerSec": 162.6,
"costUsd": 0.00631,
"timeSec": 21
},
{
"model": "openrouter:deepseek/deepseek-v4.1-flash",
"effort": "default",
"combined": "94%",
"scores": "R:18/20 K:20/20 I:20/25 C:30/30 T:10/10",
"elo": 1532,
"tokens": 14007,
"tokPerSec": 145.9,
"costUsd": 0.00761,
"timeSec": 36.1
},
{
"model": "openrouter:qwen/qwen3.8-flash",
"effort": "default",
"combined": "90.9%",
"scores": "R:17/20 K:20/20 I:19/25 C:28/30 T:10/10",
"elo": 1500,
"tokens": 16084,
"tokPerSec": 74.9,
"costUsd": 0.00483,
"timeSec": 101
},
{
"model": "openrouter:openai/gpt-oss-120b",
"effort": "default",
"combined": "90.1%",
"scores": "R:13/20 K:20/20 I:23/25 C:28/30 T:10/10",
"elo": 1468,
"tokens": 21790,
"tokPerSec": 209.9,
"costUsd": 0.00312,
"timeSec": 44.2
},
{
"model": "openrouter:qwen/qwen3.8-27b",
"effort": "default",
"combined": "81.9%",
"scores": "R:20/20 K:15/20 I:17/25 C:20/30 T:10/10",
"elo": 1499,
"tokens": 16533,
"tokPerSec": 133.9,
"costUsd": 0.02165,
"timeSec": 54.9
},
{
"model": "openrouter:openai/gpt-oss-20b",
"effort": "default",
"combined": "76.9%",
"scores": "R:13/20 K:18/20 I:24/25 C:10/30 T:10/10",
"elo": 1467,
"tokens": 63736,
"tokPerSec": 115.5,
"costUsd": 0.00693,
"timeSec": 462.1
}
]
}
Architectural notes
Static leaderboards rot the moment hand-copied numbers drift from runnable code. examples/model-watch/run.ts
enforces a strict rule: scripts/build-site.ts contains zero hardcoded model scores and reads
exclusively from reports/data/*.json.
Running this suite live immediately caught a real bug in our own library: EvalSuite.runJudge() previously
passed maxTokens: 500, which truncated thinking-enabled judges mid-<think> on the 12-coin balance
tree (Unexpected end of JSON input). Removing default judge token clamps restored clean 20/20 rubric scoring.