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/report.ts CHANGED
@@ -4,33 +4,147 @@
4
4
  * @module dsh-eval/report
5
5
  */
6
6
 
7
- import { mkdir, readFile, writeFile } from 'node:fs/promises'
8
- import { dirname, resolve } from 'node:path'
7
+ import { readFile } from 'node:fs/promises'
8
+ import { resolve } from 'node:path'
9
+ import { z } from 'zod'
10
+ import { writeTextAtomic } from './atomic-write.ts'
11
+ import { computeAgreement, type AgreementSummary } from './agreement.ts'
12
+ import { computeCalibration, type CalibrationSummary } from './calibration.ts'
13
+ import { computePrecision, type RateInterval, type RunPrecision } from './precision.ts'
14
+ import { computeCoverage, computeReliability, type ReliabilitySummary } from './reliability.ts'
9
15
  import type { EvalRun } from './types.ts'
10
16
 
11
17
  /**
12
18
  * Write a run report as indented JSON with a trailing newline.
19
+ *
20
+ * The JSON is staged in a sibling temporary file and renamed into place, so a
21
+ * crash or a full disk cannot leave a half-written report that looks valid.
13
22
  * @param run - the run record to persist.
14
23
  * @param path - output path; parent directories are created.
15
24
  */
16
25
  export async function writeRunReport(run: EvalRun, path: string): Promise<void> {
17
- const absolute = resolve(path)
18
- await mkdir(dirname(absolute), { recursive: true })
19
- await writeFile(absolute, `${JSON.stringify(run, null, 2)}\n`, 'utf8')
26
+ await writeTextAtomic(path, `${JSON.stringify(run, null, 2)}\n`)
20
27
  }
21
28
 
29
+ const pricingSchema = z.object({
30
+ inputUsdPerMTokens: z.number(),
31
+ cacheReadUsdPerMTokens: z.number(),
32
+ cacheWriteUsdPerMTokens: z.number(),
33
+ outputUsdPerMTokens: z.number(),
34
+ })
35
+
36
+ const tokenUsageSchema = z.object({
37
+ inputTokens: z.number(),
38
+ cacheReadTokens: z.number(),
39
+ cacheWriteTokens: z.number(),
40
+ outputTokens: z.number(),
41
+ })
42
+
43
+ const metricsSchema = z.object({
44
+ turns: z.number(),
45
+ steps: z.number(),
46
+ toolCalls: z.number(),
47
+ toolResults: z.number(),
48
+ toolSuccess: z.number(),
49
+ toolSuccessRate: z.number().nullable(),
50
+ invalidToolCalls: z.number(),
51
+ retries: z.number(),
52
+ tokens: tokenUsageSchema,
53
+ totalTokens: z.number(),
54
+ contextTokens: z.number(),
55
+ llmMs: z.number(),
56
+ toolMs: z.number(),
57
+ ttftMs: z.number(),
58
+ latencyMs: z.number(),
59
+ costUsd: z.number().nullable(),
60
+ })
61
+
62
+ const gradeSchema = z.object({
63
+ taskSuccess: z.boolean().nullable(),
64
+ toolSelectionAccuracy: z.boolean().nullable(),
65
+ })
66
+
67
+ const judgeVerdictSchema = z.object({
68
+ finalAnswerScore: z.number().nullable(),
69
+ hallucination: z.boolean().nullable(),
70
+ rationale: z.string().optional(),
71
+ judgeError: z.string().optional(),
72
+ })
73
+
74
+ const trialSchema = z.object({
75
+ caseId: z.string(),
76
+ trial: z.number(),
77
+ status: z.enum(['completed', 'error']),
78
+ error: z.string().optional(),
79
+ tracePath: z.string().optional(),
80
+ tracePaths: z.array(z.string()).optional(),
81
+ traceSha256: z.string().regex(/^[0-9a-f]{64}$/u).optional(),
82
+ exitCode: z.number().nullable(),
83
+ timedOut: z.boolean(),
84
+ metrics: metricsSchema.optional(),
85
+ grade: gradeSchema.optional(),
86
+ judge: judgeVerdictSchema.optional(),
87
+ })
88
+
89
+ const gradingSchema = z.object({
90
+ taskSuccessRate: z.number().nullable(),
91
+ toolSelectionAccuracyRate: z.number().nullable(),
92
+ finalAnswerScore: z.number().nullable(),
93
+ hallucinationRate: z.number().nullable(),
94
+ judgeFailures: z.number().optional(),
95
+ })
96
+
97
+ const judgeConfigSchema = z.object({
98
+ provider: z.string(),
99
+ model: z.string(),
100
+ rubric: z.string().optional(),
101
+ maxScore: z.number(),
102
+ })
103
+
104
+ /** Keep in step with `EvalRun`: deep validation turns malformed input into a field-path diagnostic instead of a TypeError in the renderer. */
105
+ const runReportSchema = z.object({
106
+ benchmark: z.string(),
107
+ model: z.string(),
108
+ benchmarkSha256: z.string().regex(/^[0-9a-f]{64}$/u).optional(),
109
+ benchmarkOverrides: z.object({
110
+ trials: z.number().int().positive().optional(),
111
+ concurrency: z.number().int().positive().optional(),
112
+ seed: z.number().int().optional(),
113
+ profile: z.string().min(1).optional(),
114
+ dshCommand: z.array(z.string().min(1)).optional(),
115
+ }).strict().optional(),
116
+ createdAt: z.number(),
117
+ trials: z.number(),
118
+ seed: z.number(),
119
+ pricing: pricingSchema.nullable(),
120
+ judge: judgeConfigSchema.optional(),
121
+ tempRoot: z.string(),
122
+ cases: z.array(trialSchema),
123
+ caseInputs: z.array(z.object({
124
+ caseId: z.string(),
125
+ prompt: z.string(),
126
+ answer: z.string().optional(),
127
+ })).optional(),
128
+ aggregate: metricsSchema.nullable(),
129
+ grading: gradingSchema.nullable(),
130
+ })
131
+
22
132
  /**
23
- * Load a persisted run report, rejecting anything without the required surface.
133
+ * Load a persisted run report, validating its full shape before use.
24
134
  * @param path - path to the run JSON.
25
135
  * @returns the loaded run record.
136
+ * @throws with the offending field path when the document is malformed.
26
137
  */
27
138
  export async function loadRunReport(path: string): Promise<EvalRun> {
28
139
  const value: unknown = JSON.parse(await readFile(resolve(path), 'utf8'))
29
- if (typeof value !== 'object' || value === null
30
- || !Array.isArray((value as { cases?: unknown }).cases)) {
31
- throw new Error(`${path} is not a dsh-eval run report`)
140
+ const parsed = runReportSchema.safeParse(value)
141
+ if (!parsed.success) {
142
+ const detail = parsed.error.issues
143
+ .map(issue => `${issue.path.join('.') || '(root)'}: ${issue.message}`)
144
+ .join('; ')
145
+ throw new Error(`${path} is not a dsh-eval run report: ${detail}`)
32
146
  }
33
- return value as EvalRun
147
+ return parsed.data as EvalRun
34
148
  }
35
149
 
36
150
  /** Render a nullable percentage with a dash placeholder. */
@@ -53,12 +167,169 @@ function formatScore(value: number | null, maxScore: number): string {
53
167
  return value === null ? '–' : `${value.toFixed(1)}/${maxScore}`
54
168
  }
55
169
 
170
+ /** Render one reliability block; callers pass only a non-null summary. */
171
+ function renderReliability(summary: ReliabilitySummary, graded: number): string[] {
172
+ const label = summary.dimension === 'task' ? 'task success' : 'tool selection accuracy'
173
+ const lines = [
174
+ `## Reliability: ${label}`,
175
+ '',
176
+ `- cases: ${summary.cases} · trials/case: ${summary.k}`,
177
+ `- pass@1: ${(summary.passAt1 * 100).toFixed(1)}% · pass@k (${graded} graded): ${(summary.passAtK * 100).toFixed(1)}% · pass^k: ${(summary.passAllK * 100).toFixed(1)}%`,
178
+ ...(summary.unscored === 0 ? [] : [
179
+ `- strict pass@1: ${(summary.strictPassAt1 * 100).toFixed(1)}% over all ${summary.total} trials (${summary.unscored} unscored)`,
180
+ ]),
181
+ `- hardest cases: ${summary.hardest.map(item => `\`${item.caseId}\` ${item.passes}/${item.trials}`).join(' · ')}`,
182
+ ]
183
+ if (summary.flaky.length > 0) {
184
+ lines.push(`- flaky cases (${summary.flaky.length}): ${summary.flaky.map(item => `\`${item.caseId}\` ${item.passes}/${item.trials}`).join(' · ')}`)
185
+ }
186
+ return [...lines, '']
187
+ }
188
+
189
+ /** Render the single-run precision block; callers pass only a populated summary. */
190
+ function renderPrecision(summary: RunPrecision): string[] {
191
+ const rateLine = (label: string, interval: RateInterval | null): string[] => {
192
+ if (interval === null) return []
193
+ const uncertainty = interval.lower === null || interval.upper === null
194
+ ? ''
195
+ : ` [95% CI ${(interval.lower * 100).toFixed(1)}%, ${(interval.upper * 100).toFixed(1)}%]`
196
+ return [`- ${label}: ${(interval.rate * 100).toFixed(1)}%${uncertainty} (n=${interval.trials})`]
197
+ }
198
+ return [
199
+ '## Precision',
200
+ '',
201
+ ...rateLine('task success', summary.task),
202
+ ...rateLine('strict pass@1 (all trials)', summary.strictPassAt1),
203
+ ...rateLine('tool selection accuracy', summary.toolSelection),
204
+ ...(summary.latencyP50 === null || summary.latencyP95 === null
205
+ ? []
206
+ : [`- latency p50/p95: ${summary.latencyP50.toFixed(0)} / ${summary.latencyP95.toFixed(0)} ms`]),
207
+ '',
208
+ ]
209
+ }
210
+
211
+ /** Render the judge/script agreement block; callers pass only a populated summary. */
212
+ function renderAgreement(summary: AgreementSummary): string[] {
213
+ const judgeRate = summary.judgePassed / summary.pairs
214
+ const scriptRate = summary.scriptPassed / summary.pairs
215
+ return [
216
+ '## Judge / script agreement',
217
+ '',
218
+ `- pairs: ${summary.pairs} trial(s) with both a scripted task result and a judge verdict`,
219
+ `- observed agreement: ${(summary.rate * 100).toFixed(1)}% (${summary.agreements}/${summary.pairs})`,
220
+ `- Cohen's kappa: ${summary.kappa.toFixed(2)}`,
221
+ `- pass rates: judge no-hallucination ${(judgeRate * 100).toFixed(1)}% · script task success ${(scriptRate * 100).toFixed(1)}%`,
222
+ '',
223
+ ]
224
+ }
225
+
226
+ /**
227
+ * Render a compact terminal summary of a run. Unlike the markdown report this
228
+ * omits the per-trial table, so a hundred-trial run still fits on one screen.
229
+ * @param run - the run record to summarize.
230
+ * @returns a short markdown fragment ending in a newline.
231
+ */
232
+ export function renderBriefReport(run: EvalRun): string {
233
+ const coverage = computeCoverage(run)
234
+ const aggregate = run.aggregate
235
+ const reliability = computeReliability(run, 'task')
236
+ const interval = computePrecision(run).task
237
+ const agreement = computeAgreement(run)
238
+ const lines = [
239
+ `# ${run.benchmark} — ${run.model}`,
240
+ ...(run.benchmarkSha256 === undefined ? [] :
241
+ [`- source: ${run.benchmarkSha256.slice(0, 12)}`]),
242
+ `- trials: ${coverage.completed}/${coverage.total} completed${coverage.unscored === 0
243
+ ? ''
244
+ : ` · ${coverage.unscored} unscored (${coverage.timeouts} timeouts, ${coverage.errors} errors)`}`,
245
+ ]
246
+ if (aggregate !== null) {
247
+ lines.push(
248
+ `- tool success: ${formatRate(aggregate.toolSuccessRate)}`,
249
+ `- steps / tokens / cost per trial: ${aggregate.steps.toFixed(1)} / ${aggregate.totalTokens.toFixed(0)} / ${aggregate.costUsd === null ? '–' : `$${aggregate.costUsd.toFixed(6)}`}`,
250
+ )
251
+ }
252
+ if (reliability !== null) {
253
+ const graded = run.cases.filter(result => typeof result.grade?.taskSuccess === 'boolean').length
254
+ lines.push(`- task success: ${(reliability.passAt1 * 100).toFixed(1)}% · pass@k (${graded} graded): ${(reliability.passAtK * 100).toFixed(1)}% · pass^k: ${(reliability.passAllK * 100).toFixed(1)}%`)
255
+ lines.push(`- strict pass@1 (all ${coverage.total} trials): ${(reliability.strictPassAt1 * 100).toFixed(1)}%`)
256
+ }
257
+ if (interval !== null && interval.lower !== null && interval.upper !== null) {
258
+ lines.push(`- task precision: ${(interval.rate * 100).toFixed(1)}% [95% CI ${(interval.lower * 100).toFixed(1)}%, ${(interval.upper * 100).toFixed(1)}%]`)
259
+ }
260
+ if (agreement !== null) {
261
+ lines.push(`- judge/script agreement: ${(agreement.rate * 100).toFixed(1)}% (n=${agreement.pairs}) · kappa ${agreement.kappa.toFixed(2)}`)
262
+ }
263
+ const calibration = computeCalibration(run)
264
+ if (calibration !== null && calibration.separation !== null) {
265
+ // Non-null separation implies scores on both sides, so ranking and Brier are present too.
266
+ lines.push(`- judge separation: ${calibration.separation >= 0 ? '+' : ''}${(calibration.separation * 100).toFixed(1)}pp · ranking ${(calibration.rankingAccuracy! * 100).toFixed(1)}% · Brier ${calibration.brier!.toFixed(3)}`)
267
+ } else if (calibration !== null && calibration.brier !== null) {
268
+ // One-sided scores have no separation but still have a meaningful error.
269
+ lines.push(`- judge Brier: ${calibration.brier.toFixed(3)}`)
270
+ }
271
+ if (run.grading?.judgeFailures) lines.push(`- judge failures: ${run.grading.judgeFailures}`)
272
+ return `${lines.join('\n')}\n`
273
+ }
274
+
56
275
  /**
57
276
  * Render a run report as a markdown table: one row per trial plus the
58
- * aggregate row.
277
+ * aggregate row, followed by reliability and precision summaries.
59
278
  * @param run - the run record to render.
60
279
  * @returns the markdown text.
61
280
  */
281
+ /** Render the judge calibration block; callers pass only a populated summary. */
282
+ function renderCalibration(summary: CalibrationSummary): string[] {
283
+ const lines = [
284
+ '## Judge calibration',
285
+ '',
286
+ `- pairs: ${summary.pairs} trial(s) with a scripted task result and a usable judge verdict`,
287
+ `- mean normalized score: passed ${summary.passedMean === null ? 'n/a' : `${(summary.passedMean * 100).toFixed(1)}%`} · failed ${summary.failedMean === null ? 'n/a' : `${(summary.failedMean * 100).toFixed(1)}%`}`,
288
+ `- separation (passed − failed): ${summary.separation === null ? 'n/a' : `${summary.separation >= 0 ? '+' : ''}${(summary.separation * 100).toFixed(1)}pp`}`,
289
+ `- ranking accuracy: ${summary.rankingAccuracy === null ? 'n/a' : `${(summary.rankingAccuracy * 100).toFixed(1)}% (ties count as half)`}`,
290
+ `- Brier score: ${summary.brier === null ? 'n/a' : summary.brier.toFixed(3)} (lower is better)`,
291
+ ]
292
+ if (summary.disagreements.length > 0) {
293
+ lines.push('- disagreements to review:',
294
+ ...summary.disagreements.map(item => ` - ${item.caseId} trial ${item.trial}: script ${item.scriptPassed ? 'pass' : 'fail'} · judge score ${item.score ?? 'n/a'}${item.hallucination === true ? ' · hallucination' : ''}`))
295
+ }
296
+ lines.push('')
297
+ return lines
298
+ }
299
+
300
+ /**
301
+ * Render a run as machine-readable JSON, including every derived block shown
302
+ * in the markdown report. Raw trial results are kept so consumers can drill
303
+ * into a single case without parsing another file.
304
+ * @param run - the run record.
305
+ * @returns a JSON string ending in a newline.
306
+ */
307
+ export function renderReportJson(run: EvalRun): string {
308
+ return `${JSON.stringify({
309
+ benchmark: run.benchmark,
310
+ model: run.model,
311
+ benchmarkSha256: run.benchmarkSha256 ?? null,
312
+ createdAt: run.createdAt,
313
+ trials: run.trials,
314
+ seed: run.seed,
315
+ tempRoot: run.tempRoot,
316
+ judge: run.judge ?? null,
317
+ pricing: run.pricing ?? null,
318
+ grading: run.grading ?? null,
319
+ aggregate: run.aggregate ?? null,
320
+ caseInputs: run.caseInputs ?? [],
321
+ coverage: computeCoverage(run),
322
+ reliability: {
323
+ task: computeReliability(run, 'task'),
324
+ toolSelection: computeReliability(run, 'tool-selection'),
325
+ },
326
+ precision: computePrecision(run),
327
+ agreement: computeAgreement(run),
328
+ calibration: computeCalibration(run),
329
+ cases: run.cases,
330
+ })}\n`
331
+ }
332
+
62
333
  export function renderMarkdownReport(run: EvalRun): string {
63
334
  const judge = run.judge
64
335
  const judged = judge !== undefined
@@ -118,18 +389,39 @@ export function renderMarkdownReport(run: EvalRun): string {
118
389
  formatRate(run.grading?.toolSelectionAccuracyRate ?? null),
119
390
  ]
120
391
  const aggregateRow = `| aggregate | – | ${[...aggregateCells, ...aggregateJudgeCells].join(' | ')} |`
392
+ const taskReliability = computeReliability(run, 'task')
393
+ const toolReliability = computeReliability(run, 'tool-selection')
394
+ const coverage = computeCoverage(run)
395
+ const precision = computePrecision(run)
396
+ const agreement = computeAgreement(run)
397
+ const calibration = computeCalibration(run)
398
+ const hasPrecision = precision.task !== null || precision.toolSelection !== null
399
+ || precision.strictPassAt1 !== null || precision.latencyP50 !== null
400
+ const coverageLine = coverage.unscored === 0
401
+ ? `- trials: ${coverage.completed}/${coverage.total} completed`
402
+ : `- trials: ${coverage.completed}/${coverage.total} completed · ${coverage.unscored} unscored (${coverage.timeouts} timeouts, ${coverage.errors} errors)`
121
403
  return [
122
404
  `# Eval: ${run.benchmark}`,
123
405
  '',
124
406
  `- model: ${run.model}`,
407
+ ...(run.benchmarkSha256 === undefined ? [] : [`- benchmark sha256: ${run.benchmarkSha256}`]),
125
408
  ...(judged ? [`- judge: ${judge.model}`] : []),
409
+ ...(run.grading?.judgeFailures ? [`- judge failures: ${run.grading.judgeFailures}`] : []),
126
410
  `- trials per case: ${run.trials}`,
127
411
  `- created: ${new Date(run.createdAt).toISOString()}`,
128
412
  `- traces: ${run.tempRoot}`,
413
+ coverageLine,
129
414
  '',
130
415
  ...header,
131
416
  ...rows,
132
417
  aggregateRow,
133
418
  '',
419
+ ...(taskReliability === null ? [] : renderReliability(taskReliability,
420
+ run.cases.filter(result => typeof result.grade?.taskSuccess === 'boolean').length)),
421
+ ...(toolReliability === null ? [] : renderReliability(toolReliability,
422
+ run.cases.filter(result => typeof result.grade?.toolSelectionAccuracy === 'boolean').length)),
423
+ ...(hasPrecision ? renderPrecision(precision) : []),
424
+ ...(agreement === null ? [] : renderAgreement(agreement)),
425
+ ...(calibration === null ? [] : renderCalibration(calibration)),
134
426
  ].join('\n')
135
427
  }