dsh-eval 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +214 -13
  2. package/README.zh.md +99 -10
  3. package/lib/agreement.js +46 -0
  4. package/lib/argv.js +66 -0
  5. package/lib/atomic-write.js +38 -0
  6. package/lib/benchmark.js +116 -19
  7. package/lib/calibration.js +90 -0
  8. package/lib/command.js +202 -10
  9. package/lib/compare.js +310 -31
  10. package/lib/dashboard.js +260 -0
  11. package/lib/digest.js +118 -0
  12. package/lib/export.js +50 -0
  13. package/lib/gate.js +293 -0
  14. package/lib/import.js +17 -6
  15. package/lib/index.js +174 -12
  16. package/lib/judge.js +30 -7
  17. package/lib/leaderboard.js +222 -0
  18. package/lib/precision.js +50 -0
  19. package/lib/rejudge.js +107 -0
  20. package/lib/reliability.js +107 -0
  21. package/lib/report.js +285 -11
  22. package/lib/runner.js +189 -33
  23. package/lib/safe-regex.js +74 -0
  24. package/lib/segments.js +15 -0
  25. package/lib/stats.js +63 -0
  26. package/lib/trace.js +19 -2
  27. package/lib/types/agreement.d.ts +33 -0
  28. package/lib/types/argv.d.ts +19 -0
  29. package/lib/types/atomic-write.d.ts +15 -0
  30. package/lib/types/benchmark.d.ts +9 -2
  31. package/lib/types/calibration.d.ts +45 -0
  32. package/lib/types/command.d.ts +58 -0
  33. package/lib/types/compare.d.ts +82 -2
  34. package/lib/types/dashboard.d.ts +24 -0
  35. package/lib/types/digest.d.ts +38 -0
  36. package/lib/types/export.d.ts +17 -0
  37. package/lib/types/gate.d.ts +87 -0
  38. package/lib/types/index.d.ts +8 -4
  39. package/lib/types/judge.d.ts +4 -1
  40. package/lib/types/leaderboard.d.ts +70 -0
  41. package/lib/types/precision.d.ts +44 -0
  42. package/lib/types/rejudge.d.ts +22 -0
  43. package/lib/types/reliability.d.ts +85 -0
  44. package/lib/types/report.d.ts +18 -5
  45. package/lib/types/runner.d.ts +8 -1
  46. package/lib/types/safe-regex.d.ts +24 -0
  47. package/lib/types/segments.d.ts +12 -0
  48. package/lib/types/stats.d.ts +56 -0
  49. package/lib/types/trace.d.ts +7 -0
  50. package/lib/types/types.d.ts +55 -6
  51. package/lib/types/validate.d.ts +57 -0
  52. package/lib/validate.js +155 -0
  53. package/package.json +2 -2
  54. package/src/agreement.ts +60 -0
  55. package/src/argv.ts +63 -0
  56. package/src/atomic-write.ts +38 -0
  57. package/src/benchmark.ts +139 -13
  58. package/src/calibration.ts +113 -0
  59. package/src/command.ts +297 -10
  60. package/src/compare.ts +392 -37
  61. package/src/dashboard.ts +287 -0
  62. package/src/digest.ts +144 -0
  63. package/src/export.ts +57 -0
  64. package/src/gate.ts +383 -0
  65. package/src/import.ts +18 -6
  66. package/src/index.ts +192 -12
  67. package/src/judge.ts +30 -6
  68. package/src/leaderboard.ts +272 -0
  69. package/src/precision.ts +85 -0
  70. package/src/rejudge.ts +112 -0
  71. package/src/reliability.ts +166 -0
  72. package/src/report.ts +303 -11
  73. package/src/runner.ts +182 -35
  74. package/src/safe-regex.ts +79 -0
  75. package/src/segments.ts +16 -0
  76. package/src/stats.ts +104 -0
  77. package/src/trace.ts +19 -2
  78. package/src/types.ts +56 -6
  79. package/src/validate.ts +177 -0
package/lib/compare.js CHANGED
@@ -4,7 +4,8 @@
4
4
  *
5
5
  * @module dsh-eval/compare
6
6
  */
7
- import { pairedDelta, signTest } from "./stats.js";
7
+ import { computeCoverage, computeReliability } from "./reliability.js";
8
+ import { bonferroni, pairedDelta, signTest, signTestPower, } from "./stats.js";
8
9
  /** Render a nullable number with a dash placeholder. */
9
10
  function formatNumber(value, digits = 1) {
10
11
  return value === null ? '–' : value.toFixed(digits);
@@ -13,6 +14,22 @@ function formatNumber(value, digits = 1) {
13
14
  function formatRate(value) {
14
15
  return value === null ? '–' : `${(value * 100).toFixed(1)}%`;
15
16
  }
17
+ /** Render USD at micro-dollar precision — one decimal rounds every real cost to zero. */
18
+ function formatUsd(value) {
19
+ return value === null ? '–' : `$${value.toFixed(6)}`;
20
+ }
21
+ /** Render a signed USD delta at micro-dollar precision. */
22
+ function formatUsdDelta(a, b) {
23
+ if (a === null || b === null)
24
+ return '–';
25
+ const delta = b - a;
26
+ return `${delta >= 0 ? '+' : '-'}$${Math.abs(delta).toFixed(6)}`;
27
+ }
28
+ /** Render a signed delta between two counts without decimal noise. */
29
+ function formatCountDelta(a, b) {
30
+ const delta = b - a;
31
+ return `${delta >= 0 ? '+' : ''}${delta}`;
32
+ }
16
33
  /** Render a signed delta between two nullable numbers. */
17
34
  function formatDelta(a, b, unit = '') {
18
35
  if (a === null || b === null)
@@ -20,16 +37,19 @@ function formatDelta(a, b, unit = '') {
20
37
  const delta = unit === 'pp' ? (b - a) * 100 : b - a;
21
38
  return `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}${unit}`;
22
39
  }
23
- /** Render a paired delta with its bootstrap interval when the sample allows one. */
24
- function formatPairedDelta(delta) {
40
+ /** Render a paired delta with its bootstrap interval at the given confidence. */
41
+ function formatPairedDelta(delta, intervalConfidence) {
25
42
  const mean = formatDelta(0, delta.mean);
26
43
  return delta.lower === null || delta.upper === null
27
44
  ? mean
28
- : `${mean} [95% CI ${formatDelta(0, delta.lower)}, ${formatDelta(0, delta.upper)}]`;
45
+ : `${mean} [${(intervalConfidence * 100).toFixed(1)}% CI ${formatDelta(0, delta.lower)}, ${formatDelta(0, delta.upper)}]`;
29
46
  }
30
47
  /** Render an exact p-value, collapsing anything below the print precision. */
31
- function formatPValue(pValue) {
32
- return pValue < 0.001 ? '<0.001' : pValue.toFixed(3);
48
+ export function formatPValue(pValue) {
49
+ if (pValue < 0.001)
50
+ return '<0.001';
51
+ // Four decimals near alpha keep a significant 0.0496 from printing 0.050.
52
+ return pValue < 0.06 ? pValue.toFixed(4) : pValue.toFixed(3);
33
53
  }
34
54
  /** Read one trial's primary-metric outcome, or null when the trial lacks it. */
35
55
  function metricOutcome(result, metric) {
@@ -46,7 +66,9 @@ function pickMetric(pairs) {
46
66
  return metric;
47
67
  }
48
68
  }
49
- return 'final answer score';
69
+ // Counting absent outcomes as ties would manufacture a fake "no change"
70
+ // result. pairedCases and pairedSigns skip them; do the same here.
71
+ return null;
50
72
  }
51
73
  /** Classify one pair: 1 for a B win, -1 for an A win, 0 for a tie. */
52
74
  function pairSign(aValue, bValue) {
@@ -60,14 +82,30 @@ function pairSign(aValue, bValue) {
60
82
  return bValue > aValue ? 1 : (bValue < aValue ? -1 : 0);
61
83
  }
62
84
  /**
63
- * Pair both runs' trials by case id and trial index and compute win/lose/tie
64
- * plus mean deltas. Trials are paired as-is; the runs' `seed` is recorded
65
- * provenance for the pairing, not a guarantee of identical model output.
85
+ * Count paired wins/losses/ties for one metric, ignoring pairs missing it.
66
86
  * @param a - the baseline run.
67
87
  * @param b - the candidate run.
68
- * @returns paired statistics, or null when no trial is completed in both runs.
88
+ * @param metric - the metric to classify.
89
+ * @returns paired sign counts for that metric alone.
69
90
  */
70
- export function pairedCompare(a, b) {
91
+ export function pairedSigns(a, b, metric) {
92
+ const counts = { pairs: 0, wins: 0, losses: 0, ties: 0 };
93
+ for (const pair of pairedTrials(a, b)) {
94
+ const sign = pairSign(metricOutcome(pair.a, metric), metricOutcome(pair.b, metric));
95
+ if (metricOutcome(pair.a, metric) === null || metricOutcome(pair.b, metric) === null)
96
+ continue;
97
+ counts.pairs += 1;
98
+ if (sign > 0)
99
+ counts.wins += 1;
100
+ else if (sign < 0)
101
+ counts.losses += 1;
102
+ else
103
+ counts.ties += 1;
104
+ }
105
+ return counts;
106
+ }
107
+ /** Pair completed trials from both runs by case id and trial index. */
108
+ function pairedTrials(a, b) {
71
109
  const byKey = new Map();
72
110
  for (const result of b.cases) {
73
111
  if (result.status === 'completed')
@@ -81,9 +119,23 @@ export function pairedCompare(a, b) {
81
119
  if (match !== undefined)
82
120
  pairs.push({ a: result, b: match });
83
121
  }
122
+ return pairs;
123
+ }
124
+ /**
125
+ * Pair both runs' trials by case id and trial index and compute win/lose/tie
126
+ * plus mean deltas. Trials are paired as-is; the runs' `seed` is recorded
127
+ * provenance for the pairing, not a guarantee of identical model output.
128
+ * @param a - the baseline run.
129
+ * @param b - the candidate run.
130
+ * @returns paired statistics, or null when no trial is completed in both runs.
131
+ */
132
+ export function pairedCompare(a, b) {
133
+ const pairs = pairedTrials(a, b);
84
134
  if (pairs.length === 0)
85
135
  return null;
86
136
  const primaryMetric = pickMetric(pairs);
137
+ if (primaryMetric === null)
138
+ return null;
87
139
  let wins = 0;
88
140
  let losses = 0;
89
141
  let ties = 0;
@@ -110,18 +162,166 @@ export function pairedCompare(a, b) {
110
162
  scoreDeltas.push(bScore - aScore);
111
163
  }
112
164
  }
165
+ const test = signTest(wins, losses);
166
+ // The printed p-value and each non-null interval are tested as one family.
167
+ const comparisons = 1 + [stepDeltas, tokenDeltas, scoreDeltas].filter(deltas => deltas.length > 0).length;
168
+ const correction = bonferroni(test.pValue, comparisons);
113
169
  return {
114
170
  pairs: pairs.length,
115
171
  wins,
116
172
  losses,
117
173
  ties,
118
174
  primaryMetric,
119
- test: signTest(wins, losses),
120
- stepsDelta: pairedDelta(stepDeltas),
121
- tokensDelta: pairedDelta(tokenDeltas),
122
- scoreDelta: pairedDelta(scoreDeltas),
175
+ test,
176
+ correction,
177
+ power: signTestPower(test.discordant, comparisons, correction.alpha),
178
+ stepsDelta: pairedDelta(stepDeltas, { confidence: correction.intervalConfidence }),
179
+ tokensDelta: pairedDelta(tokenDeltas, { confidence: correction.intervalConfidence }),
180
+ scoreDelta: pairedDelta(scoreDeltas, { confidence: correction.intervalConfidence }),
123
181
  };
124
182
  }
183
+ /**
184
+ * Classify every paired case x trial, using the same metric selection as
185
+ * {@link pairedCompare} so the case list explains its win/lose/tie counts.
186
+ * @param a - the baseline run.
187
+ * @param b - the candidate run.
188
+ * @returns one row per completed pair with a measured value, or null when
189
+ * there are no comparable pairs. Ungraded pairs must not inflate the per-case
190
+ * Bonferroni family.
191
+ */
192
+ export function pairedCases(a, b, metricOverride) {
193
+ const pairs = pairedTrials(a, b);
194
+ if (pairs.length === 0)
195
+ return null;
196
+ const metric = metricOverride ?? pickMetric(pairs);
197
+ if (metric === null)
198
+ return null;
199
+ const measured = pairs.filter(pair => metricOutcome(pair.a, metric) !== null && metricOutcome(pair.b, metric) !== null);
200
+ if (measured.length === 0)
201
+ return null;
202
+ return measured.map(pair => {
203
+ const aValue = metricOutcome(pair.a, metric);
204
+ const bValue = metricOutcome(pair.b, metric);
205
+ const sign = pairSign(aValue, bValue);
206
+ return {
207
+ caseId: pair.a.caseId,
208
+ trial: pair.a.trial,
209
+ a: aValue,
210
+ b: bValue,
211
+ outcome: sign > 0 ? 'B better' : sign < 0 ? 'A better' : 'tie',
212
+ };
213
+ });
214
+ }
215
+ /**
216
+ * Per-case exact sign tests with Bonferroni correction across the cases.
217
+ * This is a separate inference family from the pooled paired metrics.
218
+ */
219
+ export function pairedCaseSignificance(a, b, metricOverride) {
220
+ const cases = pairedCases(a, b, metricOverride);
221
+ if (cases === null)
222
+ return null;
223
+ const grouped = new Map();
224
+ for (const item of cases) {
225
+ const row = grouped.get(item.caseId) ?? { pairs: 0, wins: 0, losses: 0, ties: 0 };
226
+ row.pairs += 1;
227
+ if (item.outcome === 'B better')
228
+ row.wins += 1;
229
+ else if (item.outcome === 'A better')
230
+ row.losses += 1;
231
+ else
232
+ row.ties += 1;
233
+ grouped.set(item.caseId, row);
234
+ }
235
+ const family = Math.max(1, grouped.size);
236
+ const alpha = bonferroni(1, family).alpha;
237
+ return [...grouped.entries()]
238
+ .map(([caseId, counts]) => {
239
+ const test = signTest(counts.wins, counts.losses);
240
+ const adjustedP = Math.min(1, test.pValue * family);
241
+ const power = signTestPower(counts.wins + counts.losses, family, alpha);
242
+ const detectable = power.detectable;
243
+ const better = counts.wins > counts.losses;
244
+ const worse = counts.losses > counts.wins;
245
+ return {
246
+ caseId,
247
+ ...counts,
248
+ adjustedP,
249
+ detectable,
250
+ requiredPairs: power.minimumDiscordant,
251
+ verdict: !detectable ? 'underpowered'
252
+ : better && adjustedP <= alpha ? 'significantly-better'
253
+ : worse && adjustedP <= alpha ? 'significantly-worse'
254
+ : 'not-significant',
255
+ };
256
+ })
257
+ .sort((left, right) => left.adjustedP - right.adjustedP
258
+ /* v8 ignore next -- case-id tie direction depends on engine sort order. */
259
+ || (left.caseId < right.caseId ? -1 : 1));
260
+ }
261
+ /** Render per-case paired significance as a markdown block. */
262
+ export function renderCaseSignificance(rows) {
263
+ if (rows.length === 0) {
264
+ return '## Per-case paired significance\n\n- no paired case evidence\n';
265
+ }
266
+ const confirmed = rows.filter(row => row.verdict === 'significantly-better' || row.verdict === 'significantly-worse');
267
+ const shown = confirmed.slice(0, 20);
268
+ const lines = [
269
+ '## Per-case paired significance',
270
+ '',
271
+ `- ${rows.length} cases · Bonferroni family = ${rows.length} · ${confirmed.length} confirmed changes`,
272
+ ];
273
+ if (shown.length < confirmed.length) {
274
+ lines.push(`- showing ${shown.length} of ${confirmed.length} confirmed changes`);
275
+ }
276
+ const underpowered = rows.filter(row => row.verdict === 'underpowered');
277
+ if (underpowered.length > 0) {
278
+ lines.push(`- ${underpowered.length} underpowered cases need at least ${Math.max(...underpowered.map(row => row.requiredPairs))} discordant pairs for this family`);
279
+ }
280
+ if (shown.length > 0) {
281
+ lines.push('', '| case | pairs | B wins | A wins | adjusted p | result |', '|---|---|---|---|---|---|');
282
+ for (const row of shown) {
283
+ const caseId = row.caseId.replace(/[\r\n|]/gu, ' ');
284
+ lines.push(`| ${caseId} | ${row.pairs} | ${row.wins} | ${row.losses} | ${formatPValue(row.adjustedP)} | ${row.verdict} |`);
285
+ }
286
+ }
287
+ return `${lines.join('\n')}\n`;
288
+ }
289
+ /** Format a paired case value for reports and dashboards. */
290
+ export function formatCaseValue(value) {
291
+ if (value === null)
292
+ return '–';
293
+ if (typeof value === 'boolean')
294
+ return value ? 'pass' : 'fail';
295
+ return String(value);
296
+ }
297
+ /**
298
+ * Render the most actionable paired case outcomes: candidate wins first, then
299
+ * candidate losses, capped at 20 rows so a large benchmark still fits a screen.
300
+ * @param cases - rows from {@link pairedCases}.
301
+ * @returns a markdown block ending in a newline.
302
+ */
303
+ export function renderPairedCases(cases) {
304
+ const wins = cases.filter(item => item.outcome === 'B better');
305
+ const losses = cases.filter(item => item.outcome === 'A better');
306
+ const ties = cases.length - wins.length - losses.length;
307
+ const shown = [...wins, ...losses].slice(0, 20);
308
+ const lines = [
309
+ '## Paired case outcomes',
310
+ '',
311
+ `- ${wins.length} candidate wins · ${losses.length} candidate losses · ${ties} ties`,
312
+ ];
313
+ if (shown.length < wins.length + losses.length) {
314
+ lines.push(`- showing ${shown.length} of ${wins.length + losses.length} discordant pairs`);
315
+ }
316
+ if (shown.length > 0) {
317
+ lines.push('', '| case | trial | A | B | result |', '|---|---|---|---|---|');
318
+ for (const item of shown) {
319
+ const caseId = item.caseId.replace(/[\r\n|]/gu, ' ');
320
+ lines.push(`| ${caseId} | ${item.trial} | ${formatCaseValue(item.a)} | ${formatCaseValue(item.b)} | ${item.outcome} |`);
321
+ }
322
+ }
323
+ return `${lines.join('\n')}\n`;
324
+ }
125
325
  /**
126
326
  * Build the comparison rows between two runs.
127
327
  * @param a - the baseline run.
@@ -141,39 +341,51 @@ export function compareRuns(a, b) {
141
341
  };
142
342
  };
143
343
  const numeric = (selector, label) => rates(selector, label, '');
344
+ const counts = (count, label) => ({
345
+ metric: label,
346
+ a: String(count(a)),
347
+ b: String(count(b)),
348
+ delta: formatCountDelta(count(a), count(b)),
349
+ });
350
+ const usd = (selector, label) => {
351
+ const aValue = selector(a);
352
+ const bValue = selector(b);
353
+ return { metric: label, a: formatUsd(aValue), b: formatUsd(bValue), delta: formatUsdDelta(aValue, bValue) };
354
+ };
144
355
  const rows = [
145
356
  { metric: 'benchmark', a: a.benchmark, b: b.benchmark, delta: '–' },
146
357
  { metric: 'model', a: a.model, b: b.model, delta: '–' },
147
- numeric(run => completed(run), 'completed trials'),
358
+ counts(completed, 'completed trials'),
148
359
  numeric(run => run.aggregate?.steps ?? null, 'steps/trial'),
149
360
  rates(run => run.aggregate?.toolSuccessRate ?? null, 'tool success', 'pp'),
150
361
  rates(run => run.grading?.taskSuccessRate ?? null, 'task success', 'pp'),
151
362
  rates(run => run.grading?.toolSelectionAccuracyRate ?? null, 'tool selection accuracy', 'pp'),
363
+ numeric(run => run.grading?.judgeFailures ?? null, 'judge failures'),
152
364
  numeric(run => run.aggregate?.invalidToolCalls ?? null, 'invalid tool calls/trial'),
153
365
  numeric(run => run.aggregate?.retries ?? null, 'retries/trial'),
154
366
  numeric(run => run.aggregate?.totalTokens ?? null, 'tokens/trial'),
155
- numeric(run => run.aggregate?.costUsd ?? null, 'cost/trial (USD)'),
367
+ usd(run => run.aggregate?.costUsd ?? null, 'cost/trial (USD)'),
156
368
  numeric(run => run.aggregate?.latencyMs ?? null, 'latency/trial (ms)'),
157
369
  ];
370
+ // Reliability is derived from the trials rather than stored, so older run
371
+ // reports gain these rows on the next `compare` without being rewritten.
372
+ rows.push(counts(run => computeCoverage(run).unscored, 'unscored trials'), rates(run => computeReliability(run, 'task')?.strictPassAt1 ?? null, 'strict pass@1 (task)', 'pp'), rates(run => computeReliability(run, 'task')?.passAtK ?? null, 'pass@k (task)', 'pp'), rates(run => computeReliability(run, 'task')?.passAllK ?? null, 'pass^k (task)', 'pp'), rates(run => computeReliability(run, 'tool-selection')?.passAtK ?? null, 'pass@k (tool-selection)', 'pp'), rates(run => computeReliability(run, 'tool-selection')?.passAllK ?? null, 'pass^k (tool-selection)', 'pp'));
158
373
  const paired = pairedCompare(a, b);
159
374
  if (paired !== null) {
375
+ // A p-value or a confidence interval is evidence about the pairing, not a
376
+ // signed difference between two run-level numbers. Keep it out of the
377
+ // `delta (B - A)` column so that column only ever contains real differences.
378
+ const inference = (metric, value) => ({
379
+ metric, a: '–', b: '–', delta: '–', inference: value,
380
+ });
160
381
  rows.push({ metric: 'paired trials', a: String(paired.pairs), b: String(paired.pairs), delta: '–' }, {
161
382
  metric: `paired ${paired.primaryMetric} (B/A/ties)`,
162
383
  a: `${paired.wins}/${paired.losses}/${paired.ties}`,
163
384
  b: '–',
164
385
  delta: '–',
165
- }, {
166
- metric: `paired ${paired.primaryMetric} p (sign test)`,
167
- a: '–',
168
- b: '–',
169
- delta: `${formatPValue(paired.test.pValue)} (n=${paired.test.discordant})`,
170
- }, ...(paired.stepsDelta === null ? [] : [{
171
- metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.stepsDelta),
172
- }]), ...(paired.tokensDelta === null ? [] : [{
173
- metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.tokensDelta),
174
- }]), ...(paired.scoreDelta === null ? [] : [{
175
- metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.scoreDelta),
176
- }]));
386
+ }, inference(`paired ${paired.primaryMetric} p (sign test, Bonferroni ×${paired.correction.comparisons})`, `${formatPValue(paired.correction.adjustedPValue)} (n=${paired.test.discordant})`), inference(`paired sign-test power (α=${paired.power.alpha})`, paired.power.detectable
387
+ ? `best p ${formatPValue(paired.power.bestAdjustedP)}; needs ${paired.power.minimumWins}/${paired.power.discordant} wins`
388
+ : `unreachable: best p ${formatPValue(paired.power.bestAdjustedP)}; need ≥${paired.power.minimumDiscordant} discordant pairs`), ...(paired.stepsDelta === null ? [] : [inference('paired steps delta (B-A)', formatPairedDelta(paired.stepsDelta, paired.correction.intervalConfidence))]), ...(paired.tokensDelta === null ? [] : [inference('paired tokens delta (B-A)', formatPairedDelta(paired.tokensDelta, paired.correction.intervalConfidence))]), ...(paired.scoreDelta === null ? [] : [inference('paired final-answer delta (B-A)', formatPairedDelta(paired.scoreDelta, paired.correction.intervalConfidence))]));
177
389
  }
178
390
  return rows;
179
391
  }
@@ -183,12 +395,79 @@ export function compareRuns(a, b) {
183
395
  * @returns the markdown text.
184
396
  */
185
397
  export function renderCompareMarkdown(rows) {
398
+ const metrics = rows.filter(row => row.inference === undefined);
399
+ const inference = rows.filter(row => row.inference !== undefined);
186
400
  return [
187
401
  '# Compare',
188
402
  '',
189
403
  '| metric | run A | run B | delta (B - A) |',
190
404
  '|---|---|---|---|',
191
- ...rows.map(row => `| ${row.metric} | ${row.a} | ${row.b} | ${row.delta} |`),
405
+ ...metrics.map(row => `| ${row.metric} | ${row.a} | ${row.b} | ${row.delta} |`),
192
406
  '',
407
+ ...(inference.length === 0 ? [] : [
408
+ '## Paired inference',
409
+ '',
410
+ 'Values below describe the paired sample, not a run-level difference.',
411
+ '',
412
+ '| quantity | value |',
413
+ '|---|---|',
414
+ ...inference.map(row => `| ${row.metric} | ${row.inference} |`),
415
+ '',
416
+ ]),
193
417
  ].join('\n');
194
418
  }
419
+ /**
420
+ * Render a two-run comparison as machine-readable JSON.
421
+ * @param a - the baseline run.
422
+ * @param b - the candidate run.
423
+ * @returns a JSON string ending in a newline.
424
+ */
425
+ export function renderCompareJson(a, b) {
426
+ const completed = (run) => run.cases.filter(result => result.status === 'completed').length;
427
+ const cases = pairedCases(a, b);
428
+ return `${JSON.stringify({
429
+ baseline: { benchmark: a.benchmark, model: a.model },
430
+ candidate: { benchmark: b.benchmark, model: b.model },
431
+ // `rows` keeps the formatted table for parity with the CLI; `metrics`
432
+ // carries raw numbers so automation never parses a display string.
433
+ rows: compareRuns(a, b),
434
+ metrics: {
435
+ completedTrials: { a: completed(a), b: completed(b) },
436
+ unscoredTrials: {
437
+ a: computeCoverage(a).unscored,
438
+ b: computeCoverage(b).unscored,
439
+ },
440
+ aggregate: ['steps', 'toolSuccessRate', 'invalidToolCalls', 'retries',
441
+ 'totalTokens', 'costUsd', 'latencyMs'].reduce((out, key) => {
442
+ const field = key;
443
+ out[key] = {
444
+ a: a.aggregate?.[field] ?? null,
445
+ b: b.aggregate?.[field] ?? null,
446
+ };
447
+ return out;
448
+ }, {}),
449
+ grading: ['taskSuccessRate', 'toolSelectionAccuracyRate', 'judgeFailures'].reduce((out, key) => {
450
+ const field = key;
451
+ out[key] = {
452
+ a: a.grading?.[field] ?? null,
453
+ b: b.grading?.[field] ?? null,
454
+ };
455
+ return out;
456
+ }, {}),
457
+ reliability: {
458
+ taskStrictPassAt1: {
459
+ a: computeReliability(a, 'task')?.strictPassAt1 ?? null,
460
+ b: computeReliability(b, 'task')?.strictPassAt1 ?? null,
461
+ },
462
+ taskPassAtK: {
463
+ a: computeReliability(a, 'task')?.passAtK ?? null,
464
+ b: computeReliability(b, 'task')?.passAtK ?? null,
465
+ },
466
+ },
467
+ },
468
+ paired: pairedCompare(a, b),
469
+ caseOutcomesMeasured: cases !== null,
470
+ cases,
471
+ caseSignificance: pairedCaseSignificance(a, b),
472
+ })}\n`;
473
+ }