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/src/index.ts CHANGED
@@ -6,20 +6,34 @@
6
6
  * headless dsh subprocess per case x trial, harvests each persisted session
7
7
  * log as a trace, folds automatic metrics, scripted grading (task success,
8
8
  * tool-selection accuracy), and cross-run comparison, and writes a JSON run
9
- * report. LLM-judge metrics (final-answer score, hallucination) and paired
10
- * same-seed trials are deferred to later milestones.
9
+ * report. LLM-judge metrics (final-answer score, hallucination), offline
10
+ * rejudging, paired same-seed inference, calibration and statistical gates
11
+ * are implemented and available from the same CLI.
11
12
  *
12
13
  * @module dsh-eval
13
14
  */
14
15
 
16
+ import { writeTextAtomic } from './atomic-write.ts'
15
17
  import type { Context } from '@deepseek-ai/cordis'
16
18
  import { loadBenchmark } from './benchmark.ts'
19
+ import { hashBenchmarkOverrides } from './digest.ts'
17
20
  import { applyEval, type EvalStartupValues } from './command.ts'
18
- import { compareRuns, renderCompareMarkdown } from './compare.ts'
21
+ import {
22
+ compareRuns, pairedCases, pairedCaseSignificance, renderCaseSignificance,
23
+ renderCompareJson, renderCompareMarkdown, renderPairedCases,
24
+ } from './compare.ts'
25
+ import { writeDashboard } from './dashboard.ts'
26
+ import { evaluateGate, renderGate, renderGateJson } from './gate.ts'
27
+ import { renderTrialsCsv } from './export.ts'
19
28
  import { importTraceFile } from './import.ts'
29
+ import { buildLeaderboard, renderLeaderboard, renderLeaderboardJson } from './leaderboard.ts'
20
30
  import { llmJudgeChat, type JudgeChat } from './judge.ts'
21
- import { renderMarkdownReport, writeRunReport, loadRunReport } from './report.ts'
31
+ import { computeCoverage, computeReliability } from './reliability.ts'
32
+ import { rejudgeRun } from './rejudge.ts'
33
+ import { renderBenchmarkJson, renderBenchmarkSummary } from './validate.ts'
34
+ import { renderBriefReport, renderMarkdownReport, renderReportJson, writeRunReport, loadRunReport } from './report.ts'
22
35
  import { runBenchmark } from './runner.ts'
36
+ import type { EvalTrialResult } from './types.ts'
23
37
 
24
38
  /** Stable Cordis plugin name. */
25
39
  export const name = 'eval'
@@ -49,6 +63,45 @@ export function resolveJudgeChat(ctx: Context): JudgeChat | undefined {
49
63
  return llm === undefined ? undefined : llmJudgeChat(llm.stream)
50
64
  }
51
65
 
66
+ /** Rough seconds remaining from observed throughput; null until meaningful. */
67
+ function estimateEta(
68
+ finished: number,
69
+ total: number,
70
+ startedAtMs: number | undefined,
71
+ nowMs: number,
72
+ ): number | null {
73
+ if (startedAtMs === undefined || finished <= 0 || finished >= total) return null
74
+ const elapsed = nowMs - startedAtMs
75
+ if (!Number.isFinite(elapsed) || elapsed <= 0) return null
76
+ return Math.max(0, Math.round((elapsed / finished) * (total - finished) / 1000))
77
+ }
78
+
79
+ /** One bounded progress line; agent-controlled text must not inject newlines or terminal control codes. */
80
+ export function renderProgress(
81
+ result: EvalTrialResult,
82
+ finished: number,
83
+ total: number,
84
+ startedAtMs?: number,
85
+ nowMs: number = Date.now(),
86
+ ): string {
87
+ const clean = (value: string): string => value
88
+ // CSI / OSC sequences first, then every remaining C0/C1 control byte.
89
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, '')
90
+ .replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/gu, '')
91
+ .replace(/[\u0000-\u001f\u007f-\u009f]/gu, ' ')
92
+ .slice(0, 200)
93
+ const label = `${clean(result.caseId)} #${result.trial}`
94
+ const eta = estimateEta(finished, total, startedAtMs, nowMs)
95
+ const suffix = eta === null ? '' : `, eta ${eta}s`
96
+ if (result.status === 'error') {
97
+ return `[eval] ${finished}/${total} ${label} ERROR ${clean(result.error ?? 'unknown error')}${suffix}\n`
98
+ }
99
+ const task = result.grade?.taskSuccess === undefined || result.grade.taskSuccess === null
100
+ ? 'n/a' : result.grade.taskSuccess ? 'pass' : 'fail'
101
+ const latency = result.metrics?.latencyMs === undefined ? '?' : result.metrics.latencyMs.toFixed(0)
102
+ return `[eval] ${finished}/${total} ${label} task ${task}, ${latency} ms${suffix}\n`
103
+ }
104
+
52
105
  /** Aggregate-success sentence for the run summary line. */
53
106
  function summary(run: Awaited<ReturnType<typeof runBenchmark>>): string {
54
107
  const aggregate = run.aggregate
@@ -62,7 +115,23 @@ function summary(run: Awaited<ReturnType<typeof runBenchmark>>): string {
62
115
  const score = judgeScore === null || judgeScore === undefined
63
116
  ? ''
64
117
  : `, judge score ${judgeScore.toFixed(1)}`
65
- return `tool success ${rate}${task}${score}, ${aggregate.steps.toFixed(1)} steps/trial`
118
+ const reliability = computeReliability(run, 'task')
119
+ const passes = reliability === null
120
+ ? ''
121
+ : `, pass@${reliability.k} ${(reliability.passAtK * 100).toFixed(1)}% / pass^${reliability.k} ${(reliability.passAllK * 100).toFixed(1)}%`
122
+ const coverage = computeCoverage(run)
123
+ const unscored = coverage.unscored === 0 ? '' : `, ${coverage.unscored} unscored`
124
+ return `tool success ${rate}${task}${score}${passes}${unscored}, ${aggregate.steps.toFixed(1)} steps/trial`
125
+ }
126
+
127
+ /** Print derived text, or write it to a file and confirm the path. */
128
+ async function emitText(io: EvalIo, text: string, outPath?: string, detail = ''): Promise<void> {
129
+ if (outPath === undefined) {
130
+ io.stdout.write(text)
131
+ return
132
+ }
133
+ await writeTextAtomic(outPath, text)
134
+ io.stdout.write(`Wrote ${outPath}${detail}\n`)
66
135
  }
67
136
 
68
137
  /**
@@ -70,8 +139,8 @@ function summary(run: Awaited<ReturnType<typeof runBenchmark>>): string {
70
139
  * @param values - the resolved command-line invocation.
71
140
  * @param io - output streams for the report and diagnostics.
72
141
  * @param services - injected runtime seams, e.g. the LLM-judge chat.
73
- * @returns the process exit code; nonzero for any failure or a run with no
74
- * completed trials.
142
+ * @returns the process exit code; nonzero when any trial failed or no trial
143
+ * completed, so a partially failing run cannot be mistaken for a green CI.
75
144
  */
76
145
  export async function executeEval(
77
146
  values: EvalStartupValues,
@@ -87,26 +156,137 @@ export async function executeEval(
87
156
  }
88
157
  if (values.kind === 'report') {
89
158
  const run = await loadRunReport(values.runPath)
90
- io.stdout.write(renderMarkdownReport(run))
159
+ const report = values.json === true
160
+ ? renderReportJson(run)
161
+ : values.brief ? renderBriefReport(run) : renderMarkdownReport(run)
162
+ await emitText(io, report, values.outPath)
91
163
  return 0
92
164
  }
93
165
  if (values.kind === 'compare') {
94
166
  const a = await loadRunReport(values.runPathA)
95
167
  const b = await loadRunReport(values.runPathB)
96
- io.stdout.write(renderCompareMarkdown(compareRuns(a, b)))
168
+ if (values.json === true) {
169
+ await emitText(io, renderCompareJson(a, b), values.outPath)
170
+ return 0
171
+ }
172
+ const cases = pairedCases(a, b)
173
+ const significance = pairedCaseSignificance(a, b)
174
+ const text = renderCompareMarkdown(compareRuns(a, b))
175
+ + (cases === null ? '' : renderPairedCases(cases))
176
+ + (significance === null || significance.length === 0 ? '' : renderCaseSignificance(significance))
177
+ await emitText(io, text, values.outPath)
178
+ return 0
179
+ }
180
+ if (values.kind === 'export') {
181
+ const run = await loadRunReport(values.runPath)
182
+ const csv = renderTrialsCsv(run)
183
+ await emitText(io, csv, values.outPath, ` (${run.cases.length} trials)`)
184
+ return 0
185
+ }
186
+ if (values.kind === 'validate') {
187
+ const benchmark = await loadBenchmark(values.benchmarkPath, {
188
+ allowExternalPaths: values.allowExternalPaths === true,
189
+ })
190
+ await emitText(io, values.json === true
191
+ ? renderBenchmarkJson(benchmark)
192
+ : renderBenchmarkSummary(benchmark), values.outPath)
97
193
  return 0
98
194
  }
99
- const benchmark = await loadBenchmark(values.benchmarkPath)
195
+ if (values.kind === 'provenance') {
196
+ const run = await loadRunReport(values.runPath)
197
+ const benchmark = await loadBenchmark(values.benchmarkPath, {
198
+ allowExternalPaths: values.allowExternalPaths === true,
199
+ excludeFromDigest: [values.runPath],
200
+ })
201
+ const runSha256 = run.benchmarkSha256 ?? null
202
+ // loadBenchmark always computes this digest from the resolved inputs;
203
+ // CLI overrides are folded in exactly as runBenchmark did.
204
+ const benchmarkSha256 = run.benchmarkOverrides === undefined
205
+ ? benchmark.sourceSha256!
206
+ : hashBenchmarkOverrides(benchmark.sourceSha256!, run.benchmarkOverrides)
207
+ const status = runSha256 === null ? 'missing'
208
+ : runSha256 === benchmarkSha256 ? 'match' : 'mismatch'
209
+ const text = values.json === true
210
+ ? `${JSON.stringify({ status, runSha256, benchmarkSha256 })}\n`
211
+ : `Provenance: ${status}\nrun: ${runSha256 ?? 'n/a'}\nbenchmark: ${benchmarkSha256}\n`
212
+ await emitText(io, text, values.outPath)
213
+ return status === 'match' ? 0 : 1
214
+ }
215
+ if (values.kind === 'leaderboard') {
216
+ const runs = await Promise.all(values.runPaths.map(async path => loadRunReport(path)))
217
+ const entries = buildLeaderboard(runs.map(run => ({
218
+ label: `${run.benchmark} — ${run.model}`,
219
+ run,
220
+ })), values.metric)
221
+ await emitText(io, values.json === true
222
+ ? renderLeaderboardJson(entries, values.metric)
223
+ : renderLeaderboard(entries, values.metric), values.outPath)
224
+ return 0
225
+ }
226
+ if (values.kind === 'gate') {
227
+ const [candidate, baseline] = await Promise.all([
228
+ loadRunReport(values.candidatePath),
229
+ loadRunReport(values.baselinePath),
230
+ ])
231
+ const budgets = {
232
+ ...(values.maxCostIncrease === undefined ? {} : { maxCostIncrease: values.maxCostIncrease }),
233
+ ...(values.maxLatencyIncrease === undefined ? {} : { maxLatencyIncrease: values.maxLatencyIncrease }),
234
+ }
235
+ const result = evaluateGate(baseline, candidate, values.maxDrop, values.allowIncomplete, budgets,
236
+ values.requireSignificance === true ? { requireSignificance: true } : {})
237
+ await emitText(io, values.json === true ? renderGateJson(result) : renderGate(result), values.outPath)
238
+ return result.passed ? 0 : 1
239
+ }
240
+ if (values.kind === 'dashboard') {
241
+ const runs = await Promise.all(values.runPaths.map(async path => loadRunReport(path)))
242
+ await writeDashboard(runs, values.outPath, values.metric)
243
+ io.stdout.write(`Wrote ${values.outPath}\n`)
244
+ return 0
245
+ }
246
+ if (values.kind === 'rejudge') {
247
+ if (services.judgeChat === undefined) throw new Error('rejudge: no LLM chat seam is available')
248
+ const run = await loadRunReport(values.runPath)
249
+ const rejudged = await rejudgeRun(run, services.judgeChat, values.judge)
250
+ await writeRunReport(rejudged, values.outPath)
251
+ const judgedCount = rejudged.cases.filter(result =>
252
+ result.judge?.finalAnswerScore !== null && result.judge?.finalAnswerScore !== undefined,
253
+ ).length
254
+ io.stdout.write(`Wrote ${values.outPath} (${judgedCount}/${rejudged.cases.length} judged)\n`)
255
+ return 0
256
+ }
257
+ const benchmark = await loadBenchmark(values.benchmarkPath, {
258
+ allowExternalPaths: values.allowExternalPaths === true,
259
+ excludeFromDigest: [values.outPath],
260
+ })
261
+ const startedAtMs = Date.now()
100
262
  const run = await runBenchmark(benchmark, {
101
263
  ...(values.trials !== undefined ? { trials: values.trials } : {}),
102
264
  ...(values.concurrency !== undefined ? { concurrency: values.concurrency } : {}),
265
+ ...(values.seed !== undefined ? { seed: values.seed } : {}),
103
266
  ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
104
267
  ...(values.profile !== undefined ? { profile: values.profile } : {}),
105
268
  ...(services.judgeChat !== undefined ? { judgeChat: services.judgeChat } : {}),
269
+ ...(values.quiet === true ? {} : {
270
+ onProgress: (result: EvalTrialResult, finished: number, total: number) => {
271
+ io.stderr.write(renderProgress(result, finished, total, startedAtMs))
272
+ },
273
+ }),
106
274
  })
107
275
  await writeRunReport(run, values.outPath)
108
- io.stdout.write(`Wrote ${values.outPath} (${run.cases.length} trials, ${summary(run)})\n`)
109
- return run.aggregate === null ? 1 : 0
276
+ const failed = run.cases.filter(result => result.status === 'error')
277
+ const completed = run.cases.length - failed.length
278
+ io.stdout.write(`Wrote ${values.outPath} (${completed}/${run.cases.length} completed, ${summary(run)})\n`)
279
+ // A failed trial lives in the JSON report, but a CLI run must also say why
280
+ // on stderr — otherwise an empty stdout/stderr looks like a clean failure.
281
+ if (failed.length > 0) {
282
+ const sample = failed.slice(0, 3).map((result) => {
283
+ /* v8 ignore next 2 -- runner always sets `error` on error trials; the fallback guards hand-edited reports. */
284
+ const detail = result.error ?? 'unknown error'
285
+ return `${result.caseId}#${result.trial}: ${detail}`
286
+ }).join('\n')
287
+ io.stderr.write(`dsh eval: ${failed.length} trial(s) failed:\n${sample}\n`)
288
+ }
289
+ return failed.length > 0 || run.aggregate === null ? 1 : 0
110
290
  } catch (error) {
111
291
  io.stderr.write(`dsh eval: ${error instanceof Error ? error.message : String(error)}\n`)
112
292
  return 1
package/src/judge.ts CHANGED
@@ -32,6 +32,15 @@ function blockText(blocks: readonly ContentBlock[]): string {
32
32
  return blocks.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
33
33
  }
34
34
 
35
+ /** The last assistant text message in a trace, used as the final answer. */
36
+ export function finalAnswerOf(trace: EvalTrace): string {
37
+ let finalAnswer = ''
38
+ for (const event of trace.events) {
39
+ if (event.type === 'assistant/message') finalAnswer = blockText(event.data.message.content)
40
+ }
41
+ return finalAnswer
42
+ }
43
+
35
44
  /**
36
45
  * Summarize a trace for the judge: final assistant answer, the distinct tool
37
46
  * names called, and the failure counters a hallucination call needs.
@@ -39,12 +48,11 @@ function blockText(blocks: readonly ContentBlock[]): string {
39
48
  * @returns a compact human-readable summary.
40
49
  */
41
50
  export function summarizeTrace(trace: EvalTrace): string {
42
- let finalAnswer = ''
51
+ const finalAnswer = finalAnswerOf(trace)
43
52
  const toolNames: string[] = []
44
53
  let invalidToolCalls = 0
45
54
  let retries = 0
46
55
  for (const event of trace.events) {
47
- if (event.type === 'assistant/message') finalAnswer = blockText(event.data.message.content)
48
56
  if (event.type === 'tool/call') {
49
57
  if (!toolNames.includes(event.data.name)) toolNames.push(event.data.name)
50
58
  }
@@ -71,11 +79,15 @@ export function buildJudgePrompt(
71
79
  trace: EvalTrace,
72
80
  judge: BenchmarkJudge,
73
81
  ): { system: string; prompt: string } {
82
+ const hasReference = caseValue.expected?.answer !== undefined
74
83
  const system = [
75
84
  'You are an impartial evaluation judge for agent task completion.',
76
85
  `Score the agent's final answer from 0 to ${judge.maxScore} against the task,`,
77
86
  'and set "hallucination" to true only when the final answer asserts facts',
78
87
  'not supported by the task or the trace.',
88
+ ...(hasReference
89
+ ? ['A reference answer is supplied: score factual agreement with it, not mere fluency.']
90
+ : []),
79
91
  'Return STRICT JSON with exactly these fields:',
80
92
  `{"finalAnswerScore": <integer 0..${judge.maxScore}>, "hallucination": <true|false>, "rationale": "<one short sentence>"}`,
81
93
  ...(judge.rubric !== undefined ? ['Rubric:', judge.rubric] : []),
@@ -83,6 +95,7 @@ export function buildJudgePrompt(
83
95
  const prompt = [
84
96
  `Task id: ${caseValue.id}`,
85
97
  `Task: ${caseValue.prompt}`,
98
+ ...(hasReference ? [`Reference answer: ${caseValue.expected?.answer}`] : []),
86
99
  'Trace summary:',
87
100
  summarizeTrace(trace),
88
101
  ].join('\n')
@@ -154,7 +167,8 @@ export async function judgeTrial(
154
167
  * @param trace - the merged trial trace.
155
168
  * @param judge - the judge configuration.
156
169
  * @param chat - the injected chat seam.
157
- * @returns the parsed verdict, or all-null when the chat call threw.
170
+ * @returns the parsed verdict, or all-null plus `judgeError` when the call
171
+ * failed or the reply could not be parsed.
158
172
  */
159
173
  export async function tryJudgeTrial(
160
174
  caseValue: BenchmarkCase,
@@ -163,9 +177,19 @@ export async function tryJudgeTrial(
163
177
  chat: JudgeChat,
164
178
  ): Promise<EvalJudgeVerdict> {
165
179
  try {
166
- return await judgeTrial(caseValue, trace, judge, chat)
167
- } catch {
168
- return { finalAnswerScore: null, hallucination: null }
180
+ const verdict = await judgeTrial(caseValue, trace, judge, chat)
181
+ // A syntactically valid but field-less reply is just as unusable as an
182
+ // outage; without this marker its score silently drops out of the mean.
183
+ if (verdict.finalAnswerScore === null && verdict.hallucination === null) {
184
+ return { ...verdict, judgeError: 'unparsable judge reply' }
185
+ }
186
+ return verdict
187
+ } catch (error) {
188
+ return {
189
+ finalAnswerScore: null,
190
+ hallucination: null,
191
+ judgeError: error instanceof Error ? error.message : String(error),
192
+ }
169
193
  }
170
194
  }
171
195
 
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Multi-run leaderboard for dsh-eval.
3
+ *
4
+ * `compare` answers a two-run question with paired inference; a leaderboard
5
+ * answers the wider "which of these runs is currently best" question. Ranks
6
+ * use pooled task success with deterministic tie-breakers, and every row shows
7
+ * how far it trails the leader. This is a screening view, not a significance
8
+ * test, but each non-leader row carries a Bonferroni-corrected paired verdict
9
+ * against the leader so a one-point lead is not mistaken for a real gap.
10
+ *
11
+ * @module dsh-eval/leaderboard
12
+ */
13
+
14
+ import { formatPValue, pairedCompare } from './compare.ts'
15
+ import { computeCoverage, computeReliability } from './reliability.ts'
16
+ import { signTest, signTestPower } from './stats.ts'
17
+ import type { EvalRun } from './types.ts'
18
+
19
+ /** Primary ranking metric for a leaderboard. */
20
+ export type LeaderboardMetric = 'taskSuccess' | 'strictPassAt1'
21
+
22
+ /** Paired evidence that a row really trails the current leader. */
23
+ export interface LeaderboardSignificance {
24
+ /** p-value adjusted for the leaderboard comparison family. */
25
+ adjustedP: number
26
+ /** Whether the smallest attainable p-value can reach alpha at this sample size. */
27
+ detectable: boolean
28
+ /** Whether the paired primary metric moved against the row. */
29
+ worse: boolean
30
+ /** The paired metric the verdict is based on. */
31
+ primaryMetric: string | null
32
+ /** Machine-readable interpretation of the comparison. */
33
+ verdict: 'significantly-behind' | 'behind-not-significant' | 'ahead-or-tied'
34
+ | 'underpowered' | 'unpaired'
35
+ }
36
+
37
+ /** One ranked run. */
38
+ export interface LeaderboardEntry {
39
+ label: string
40
+ benchmark: string
41
+ model: string
42
+ rank: number
43
+ completed: number
44
+ total: number
45
+ taskSuccess: number | null
46
+ strictPassAt1: number | null
47
+ toolSelection: number | null
48
+ judgeScore: number | null
49
+ costUsd: number | null
50
+ latencyMs: number | null
51
+ gapFromBest: number | null
52
+ /** Paired verdict against the leader; null for the leader itself. */
53
+ significance: LeaderboardSignificance | null
54
+ }
55
+
56
+ /** Normalize a pooled judge score using the run's configured scale. */
57
+ function judgeRate(run: EvalRun): number | null {
58
+ const score = run.grading?.finalAnswerScore
59
+ const maxScore = run.judge?.maxScore
60
+ if (score === null || score === undefined || maxScore === undefined || maxScore <= 0) return null
61
+ return Math.max(0, Math.min(1, score / maxScore))
62
+ }
63
+
64
+ /** Prefer higher values, pushing missing metrics to the bottom. */
65
+ function descending(a: number | null, b: number | null): number {
66
+ if (a === null) return b === null ? 0 : 1
67
+ if (b === null) return -1
68
+ return b - a
69
+ }
70
+
71
+ /** Value used for ranking, gaps and ties. */
72
+ function metricValue(entry: LeaderboardEntry, metric: LeaderboardMetric): number | null {
73
+ return metric === 'strictPassAt1' ? entry.strictPassAt1 : entry.taskSuccess
74
+ }
75
+
76
+ /** Strict pass@1 outcome for one trial: errors and timeouts count as failures. */
77
+ function strictOutcome(result: EvalRun['cases'][number]): boolean {
78
+ return result.status === 'completed' && result.grade?.taskSuccess === true
79
+ }
80
+
81
+ function trialKey(result: EvalRun['cases'][number]): string {
82
+ return `${result.caseId}\u0000${result.trial}`
83
+ }
84
+
85
+ /**
86
+ * Discordant strict-pass counts across every trial key in either run.
87
+ * Unlike pairedCompare(), incomplete trials stay in the denominator.
88
+ */
89
+ function strictPairCounts(leader: EvalRun, row: EvalRun): { wins: number; losses: number; ties: number } {
90
+ const leaderTrials = new Map(leader.cases.map(result => [trialKey(result), result]))
91
+ const rowTrials = new Map(row.cases.map(result => [trialKey(result), result]))
92
+ let wins = 0
93
+ let losses = 0
94
+ let ties = 0
95
+ for (const key of new Set([...leaderTrials.keys(), ...rowTrials.keys()])) {
96
+ const a = leaderTrials.get(key)
97
+ const b = rowTrials.get(key)
98
+ const aPass = a === undefined ? false : strictOutcome(a)
99
+ const bPass = b === undefined ? false : strictOutcome(b)
100
+ if (bPass && !aPass) wins += 1
101
+ else if (aPass && !bPass) losses += 1
102
+ else ties += 1
103
+ }
104
+ return { wins, losses, ties }
105
+ }
106
+
107
+ /**
108
+ * Rank persisted runs by task success or strict pass@1.
109
+ * @param runs - labelled run records; labels are usually `benchmark — model`.
110
+ * @param metric - primary ranking metric; default is pooled task success.
111
+ * @returns ranked rows with ties sharing a rank.
112
+ */
113
+ export function buildLeaderboard(
114
+ runs: readonly { label: string; run: EvalRun }[],
115
+ metric: LeaderboardMetric = 'taskSuccess',
116
+ ): LeaderboardEntry[] {
117
+ const runByEntry = new Map<LeaderboardEntry, EvalRun>()
118
+ const rows: LeaderboardEntry[] = runs.map(({ label, run }) => {
119
+ const coverage = computeCoverage(run)
120
+ const reliability = computeReliability(run, 'task')
121
+ const entry: LeaderboardEntry = {
122
+ label,
123
+ benchmark: run.benchmark,
124
+ model: run.model,
125
+ completed: coverage.completed,
126
+ total: coverage.total,
127
+ taskSuccess: run.grading?.taskSuccessRate ?? null,
128
+ strictPassAt1: reliability?.strictPassAt1 ?? null,
129
+ toolSelection: run.grading?.toolSelectionAccuracyRate ?? null,
130
+ judgeScore: judgeRate(run),
131
+ costUsd: run.aggregate?.costUsd ?? null,
132
+ latencyMs: run.aggregate?.latencyMs ?? null,
133
+ gapFromBest: null,
134
+ significance: null,
135
+ rank: 0,
136
+ }
137
+ runByEntry.set(entry, run)
138
+ return entry
139
+ })
140
+ rows.sort((a, b) => descending(metricValue(a, metric), metricValue(b, metric))
141
+ || descending(a.strictPassAt1, b.strictPassAt1)
142
+ || descending(a.taskSuccess, b.taskSuccess)
143
+ || descending(a.toolSelection, b.toolSelection)
144
+ || descending(a.judgeScore, b.judgeScore)
145
+ || a.label.localeCompare(b.label))
146
+ const best = rows.length === 0 ? null : metricValue(rows[0]!, metric)
147
+ let lastRate: number | null = null
148
+ let lastRank = 0
149
+ let first = true
150
+ rows.forEach((row, index) => {
151
+ const value = metricValue(row, metric)
152
+ if (value === null || first || value !== lastRate) {
153
+ lastRank = index + 1
154
+ lastRate = value
155
+ first = false
156
+ }
157
+ row.rank = lastRank
158
+ row.gapFromBest = best === null || value === null ? null : best - value
159
+ })
160
+ const leader = rows.find(row => row.rank === 1)
161
+ const leaderRun = leader === undefined ? undefined : runByEntry.get(leader)
162
+ const family = Math.max(1, rows.length - 1)
163
+ if (leaderRun !== undefined) {
164
+ for (const row of rows) {
165
+ if (row === leader) continue
166
+ const rowRun = runByEntry.get(row)!
167
+ if (metric === 'strictPassAt1') {
168
+ // Strict ranking counts errors and timeouts, so the verdict must use
169
+ // the same denominator rather than survivor-only paired task success.
170
+ const counts = strictPairCounts(leaderRun, rowRun)
171
+ const test = signTest(counts.wins, counts.losses)
172
+ const adjustedP = Math.min(1, test.pValue * family)
173
+ const detectable = signTestPower(counts.wins + counts.losses, family).detectable
174
+ row.significance = {
175
+ adjustedP,
176
+ detectable,
177
+ worse: counts.losses > counts.wins,
178
+ primaryMetric: 'strict pass@1 (task)',
179
+ // Unequal trial counts can tie on rate while the extra trials are
180
+ // wins, so direction must be checked explicitly.
181
+ verdict: !detectable ? 'underpowered'
182
+ : counts.losses > counts.wins && adjustedP <= 0.05 ? 'significantly-behind'
183
+ : counts.losses > counts.wins ? 'behind-not-significant' : 'ahead-or-tied',
184
+ }
185
+ continue
186
+ }
187
+ const paired = pairedCompare(leaderRun, rowRun)
188
+ if (paired === null) {
189
+ row.significance = {
190
+ adjustedP: 1, detectable: false, worse: false, primaryMetric: null,
191
+ verdict: 'unpaired',
192
+ }
193
+ continue
194
+ }
195
+ const worse = paired.losses > paired.wins
196
+ // The verdict concerns the one primary metric only, so the board's
197
+ // comparison family is the only correction that applies here. Comparing
198
+ // every metric (as `paired.correction` does) would double-count.
199
+ const adjustedP = Math.min(1, paired.test.pValue * family)
200
+ const detectable = signTestPower(paired.losses + paired.wins,
201
+ family, paired.correction.alpha).detectable
202
+ row.significance = {
203
+ adjustedP,
204
+ detectable,
205
+ worse,
206
+ primaryMetric: paired.primaryMetric,
207
+ verdict: !detectable ? 'underpowered'
208
+ : worse && adjustedP <= paired.correction.alpha ? 'significantly-behind'
209
+ : worse ? 'behind-not-significant' : 'ahead-or-tied',
210
+ }
211
+ }
212
+ }
213
+ return rows
214
+ }
215
+
216
+ /**
217
+ * Render leaderboard rows as machine-readable JSON.
218
+ * @param rows - rows from {@link buildLeaderboard}.
219
+ * @returns a JSON string ending in a newline.
220
+ */
221
+ export function renderLeaderboardJson(
222
+ rows: readonly LeaderboardEntry[],
223
+ metric: LeaderboardMetric = 'taskSuccess',
224
+ ): string {
225
+ return `${JSON.stringify({ rankedBy: metric, rows })}\n`
226
+ }
227
+
228
+ /** Format a rate or a dash for markdown. */
229
+ function rate(value: number | null): string {
230
+ return value === null ? '–' : `${(value * 100).toFixed(1)}%`
231
+ }
232
+
233
+ /** Format a signed percentage-point gap from the leader. */
234
+ function gap(value: number | null, rank: number): string {
235
+ if (value === null) return '–'
236
+ if (rank === 1) return 'leader'
237
+ return `-${(value * 100).toFixed(1)}pp`
238
+ }
239
+
240
+ /** Format the paired verdict against the leader. */
241
+ export function formatLeaderboardSignificance(value: LeaderboardSignificance | null): string {
242
+ if (value === null) return 'leader'
243
+ if (value.verdict === 'unpaired') return 'unpaired'
244
+ return `${value.verdict} (p=${formatPValue(value.adjustedP)}, ${value.primaryMetric})`
245
+ }
246
+
247
+ /**
248
+ * Render a leaderboard as markdown.
249
+ * @param rows - rows from {@link buildLeaderboard}.
250
+ * @returns markdown ending in a newline.
251
+ */
252
+ export function renderLeaderboard(
253
+ rows: readonly LeaderboardEntry[],
254
+ metric: LeaderboardMetric = 'taskSuccess',
255
+ ): string {
256
+ const lines = [
257
+ '# Leaderboard',
258
+ '',
259
+ metric === 'strictPassAt1'
260
+ ? '- ranked by strict pass@1 (errors and timeouts stay in the denominator); ties share a rank'
261
+ : '- ranked by pooled task success; ties share a rank',
262
+ '- ranks are a screening view; `vs leader` applies a Bonferroni-corrected paired sign test',
263
+ '',
264
+ '| rank | run | completed | task | strict pass@1 | tool | judge | cost/trial | latency/trial | Δ best | vs leader |',
265
+ '|---|---|---|---|---|---|---|---|---|---|---|',
266
+ ]
267
+ for (const row of rows) {
268
+ const label = row.label.replace(/[\r\n|]/gu, ' ')
269
+ lines.push(`| ${row.rank} | ${label} | ${row.completed}/${row.total} | ${rate(row.taskSuccess)} | ${rate(row.strictPassAt1)} | ${rate(row.toolSelection)} | ${rate(row.judgeScore)} | ${row.costUsd === null ? '–' : `$${row.costUsd.toFixed(6)}`} | ${row.latencyMs === null ? '–' : `${row.latencyMs.toFixed(1)} ms`} | ${gap(row.gapFromBest, row.rank)} | ${formatLeaderboardSignificance(row.significance)} |`)
270
+ }
271
+ return `${lines.join('\n')}\n`
272
+ }