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