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/gate.js ADDED
@@ -0,0 +1,293 @@
1
+ /**
2
+ * CI quality gate for dsh-eval: compare a candidate run against a baseline and
3
+ * fail when a quality metric regresses beyond an allowed tolerance.
4
+ *
5
+ * All quality metrics are expressed on a 0..1 scale, so one `--max-drop`
6
+ * threshold applies uniformly to pass rates and judge scores. Judge scores are
7
+ * normalized by each run's configured `maxScore` before comparison.
8
+ *
9
+ * @module dsh-eval/gate
10
+ */
11
+ import { formatPValue, pairedCaseSignificance, pairedSigns } from "./compare.js";
12
+ import { computeCoverage, computeReliability } from "./reliability.js";
13
+ import { signTest, signTestPower } from "./stats.js";
14
+ /** Normalized judge score for a run, or null when ungraded. */
15
+ function scoreRate(run) {
16
+ const score = run.grading?.finalAnswerScore;
17
+ if (score === null || score === undefined)
18
+ return null;
19
+ const maxScore = run.judge?.maxScore;
20
+ return maxScore === undefined || maxScore <= 0 ? null : score / maxScore;
21
+ }
22
+ /** Normalized per-case judge score for one trial. */
23
+ function caseScore(run, result) {
24
+ const verdict = result.judge;
25
+ if (verdict === undefined)
26
+ return null;
27
+ const score = verdict.finalAnswerScore;
28
+ const maxScore = run.judge?.maxScore;
29
+ if (score === null || maxScore === undefined || maxScore <= 0)
30
+ return null;
31
+ return Math.max(0, Math.min(1, score / maxScore));
32
+ }
33
+ /** Find paired case x trials that regressed, for actionable CI output. */
34
+ function findRegressions(baseline, candidate, maxDrop) {
35
+ const byKey = new Map();
36
+ for (const result of baseline.cases)
37
+ byKey.set(`${result.caseId}\u0000${result.trial}`, result);
38
+ const regressions = [];
39
+ for (const result of candidate.cases) {
40
+ const before = byKey.get(`${result.caseId}\u0000${result.trial}`);
41
+ if (before === undefined)
42
+ continue;
43
+ for (const [metric, previous, current] of [
44
+ ['task success', before.grade?.taskSuccess, result.grade?.taskSuccess],
45
+ ['tool selection', before.grade?.toolSelectionAccuracy, result.grade?.toolSelectionAccuracy],
46
+ ]) {
47
+ if (previous === true && current === false) {
48
+ regressions.push({ caseId: result.caseId, trial: result.trial, metric, before: 1, after: 0 });
49
+ }
50
+ }
51
+ const previousScore = caseScore(baseline, before);
52
+ const currentScore = caseScore(candidate, result);
53
+ if (previousScore !== null && currentScore !== null && currentScore < previousScore - maxDrop) {
54
+ regressions.push({
55
+ caseId: result.caseId, trial: result.trial, metric: 'judge score',
56
+ before: previousScore, after: currentScore,
57
+ });
58
+ }
59
+ }
60
+ return regressions;
61
+ }
62
+ /** Compare two nullable rates, allowing a drop of at most `maxDrop`. */
63
+ function compareRate(metric, baseline, candidate, maxDrop, suppressDrop = false) {
64
+ if (baseline === null) {
65
+ return { metric, baseline, candidate, delta: null, passed: true, note: 'baseline ungraded' };
66
+ }
67
+ if (candidate === null) {
68
+ return { metric, baseline, candidate, delta: null, passed: false, note: 'candidate ungraded' };
69
+ }
70
+ const delta = candidate - baseline;
71
+ if (delta >= -maxDrop)
72
+ return { metric, baseline, candidate, delta, passed: true };
73
+ if (suppressDrop) {
74
+ return { metric, baseline, candidate, delta, passed: true, note: 'drop not statistically confirmed' };
75
+ }
76
+ return { metric, baseline, candidate, delta, passed: false };
77
+ }
78
+ /** Compare two resource figures against a relative increase budget. */
79
+ function compareBudget(metric, baseline, candidate, maxIncrease, unit) {
80
+ if (baseline === null) {
81
+ return { metric, baseline, candidate, delta: null, passed: true, unit, note: 'baseline metrics unavailable — check skipped' };
82
+ }
83
+ if (candidate === null) {
84
+ return { metric, baseline, candidate, delta: null, passed: false, unit, note: 'candidate unpriced' };
85
+ }
86
+ const delta = candidate - baseline;
87
+ // Floating-point noise at 1e-9 of the baseline must not fail an exact budget.
88
+ const limit = baseline * maxIncrease + Math.abs(baseline) * 1e-9;
89
+ return { metric, baseline, candidate, delta, passed: delta <= limit, unit };
90
+ }
91
+ /**
92
+ * Evaluate a candidate run against a baseline.
93
+ * @param baseline - the trusted reference run.
94
+ * @param candidate - the run under test.
95
+ * @param maxDrop - largest tolerated regression on the 0..1 scale.
96
+ * @param allowIncomplete - skip the trial-coverage checks when true.
97
+ * @param budgets - optional relative cost and latency increase limits.
98
+ * @param options - optional significance mode for quality regressions.
99
+ * @returns the per-metric checks and the overall decision.
100
+ */
101
+ export function evaluateGate(baseline, candidate, maxDrop, allowIncomplete = false, budgets = {}, options = {}) {
102
+ const baseCoverage = computeCoverage(baseline);
103
+ const candCoverage = computeCoverage(candidate);
104
+ const baseTask = computeReliability(baseline, 'task');
105
+ const candTask = computeReliability(candidate, 'task');
106
+ const checks = [];
107
+ if (!allowIncomplete) {
108
+ for (const [metric, value, limit, comparison] of [
109
+ ['completed trials', candCoverage.completed, baseCoverage.completed, 'at least'],
110
+ ['unscored trials', candCoverage.unscored, baseCoverage.unscored, 'at most'],
111
+ ]) {
112
+ const passed = comparison === 'at least' ? value >= limit : value <= limit;
113
+ checks.push({
114
+ metric, baseline: limit, candidate: value,
115
+ delta: value - limit, passed, unit: 'count',
116
+ ...(passed ? {} : { note: `expected ${comparison} ${limit}` }),
117
+ });
118
+ }
119
+ }
120
+ // Significance is assessed per quality metric: a clean task-success result
121
+ // must never hide a real tool-selection or judge-score regression.
122
+ const suppressByMetric = new Map();
123
+ if (options.requireSignificance === true) {
124
+ const qualityMetrics = [
125
+ { metric: 'task success', paired: 'task success', a: baseline.grading?.taskSuccessRate ?? null, b: candidate.grading?.taskSuccessRate ?? null },
126
+ { metric: 'tool selection', paired: 'tool selection accuracy', a: baseline.grading?.toolSelectionAccuracyRate ?? null, b: candidate.grading?.toolSelectionAccuracyRate ?? null },
127
+ { metric: 'strict pass@1 (task)', paired: 'task success', a: baseTask?.strictPassAt1 ?? null, b: candTask?.strictPassAt1 ?? null },
128
+ { metric: 'judge score', paired: 'final answer score', a: scoreRate(baseline), b: scoreRate(candidate) },
129
+ ];
130
+ let undecidable = false;
131
+ let bestFloor = 1;
132
+ let worstObserved = 0;
133
+ const assessed = qualityMetrics.filter(item => item.a !== null || item.b !== null);
134
+ // task success and strict pass@1 share one sign test, and ungraded metrics
135
+ // are not tested at all; correcting for all four rows would be too lax.
136
+ const pairedMetrics = [...new Set(assessed.map(item => item.paired))];
137
+ const family = pairedMetrics.length;
138
+ const verdicts = new Map();
139
+ for (const pairedMetric of pairedMetrics) {
140
+ const counts = pairedSigns(baseline, candidate, pairedMetric);
141
+ const discordant = counts.wins + counts.losses;
142
+ const power = signTestPower(discordant, family);
143
+ const observed = Math.min(1, signTest(counts.wins, counts.losses).pValue * family);
144
+ const worse = counts.losses > counts.wins;
145
+ const informative = discordant > 0 && power.detectable;
146
+ const confirmed = informative && worse && observed <= power.alpha;
147
+ const clear = informative && !confirmed && (observed > power.alpha || !worse);
148
+ verdicts.set(pairedMetric, clear);
149
+ if (!informative || (!confirmed && !clear))
150
+ undecidable = true;
151
+ bestFloor = Math.min(bestFloor, power.bestAdjustedP);
152
+ worstObserved = Math.max(worstObserved, observed);
153
+ }
154
+ for (const item of assessed) {
155
+ suppressByMetric.set(item.metric, verdicts.get(item.paired) === true);
156
+ }
157
+ // The strict pass@1 rate keeps errors and timeouts in its denominator, but
158
+ // pairedSigns only sees completed trials. A candidate with more unscored
159
+ // trials must not get its strict drop excused by survivor-only evidence.
160
+ if (computeCoverage(candidate).unscored > computeCoverage(baseline).unscored) {
161
+ suppressByMetric.set('strict pass@1 (task)', false);
162
+ }
163
+ checks.push({
164
+ metric: 'paired significance',
165
+ baseline: bestFloor,
166
+ candidate: worstObserved,
167
+ delta: worstObserved - bestFloor,
168
+ passed: !undecidable,
169
+ unit: 'p',
170
+ note: undecidable ? 'some quality metrics lack conclusive paired evidence'
171
+ : 'all quality metrics assessed independently',
172
+ });
173
+ }
174
+ checks.push(compareRate('task success', baseline.grading?.taskSuccessRate ?? null, candidate.grading?.taskSuccessRate ?? null, maxDrop, suppressByMetric.get('task success')), compareRate('tool selection', baseline.grading?.toolSelectionAccuracyRate ?? null, candidate.grading?.toolSelectionAccuracyRate ?? null, maxDrop, suppressByMetric.get('tool selection')), compareRate('strict pass@1 (task)', baseTask?.strictPassAt1 ?? null, candTask?.strictPassAt1 ?? null, maxDrop, suppressByMetric.get('strict pass@1 (task)')), compareRate('judge score', scoreRate(baseline), scoreRate(candidate), maxDrop, suppressByMetric.get('judge score')));
175
+ if (budgets.maxCostIncrease !== undefined && budgets.maxCostIncrease !== null) {
176
+ checks.push(compareBudget('cost/trial', baseline.aggregate?.costUsd ?? null, candidate.aggregate?.costUsd ?? null, budgets.maxCostIncrease, 'usd'));
177
+ }
178
+ if (budgets.maxLatencyIncrease !== undefined && budgets.maxLatencyIncrease !== null) {
179
+ checks.push(compareBudget('latency/trial', baseline.aggregate?.latencyMs ?? null, candidate.aggregate?.latencyMs ?? null, budgets.maxLatencyIncrease, 'ms'));
180
+ }
181
+ // Per-case evidence uses each quality metric's own paired trials; the
182
+ // default metric chosen by pickMetric() would miss tool/judge-only drops.
183
+ const confirmedCaseRegressions = ['task success', 'tool selection accuracy', 'final answer score']
184
+ .flatMap(metric => (pairedCaseSignificance(baseline, candidate, metric) ?? [])
185
+ .filter(row => row.verdict === 'significantly-worse')
186
+ .map(row => ({ caseId: row.caseId, metric, adjustedP: row.adjustedP })));
187
+ if (options.requireSignificance === true && confirmedCaseRegressions.length > 0) {
188
+ checks.push({
189
+ metric: 'confirmed case regressions',
190
+ baseline: 0, candidate: confirmedCaseRegressions.length,
191
+ delta: confirmedCaseRegressions.length, passed: false, unit: 'count',
192
+ note: 'family-corrected per-case regression',
193
+ });
194
+ }
195
+ return {
196
+ checks,
197
+ passed: checks.every(check => check.passed),
198
+ maxDrop,
199
+ ...(budgets.maxCostIncrease === undefined || budgets.maxCostIncrease === null
200
+ ? {} : { maxCostIncrease: budgets.maxCostIncrease }),
201
+ ...(budgets.maxLatencyIncrease === undefined || budgets.maxLatencyIncrease === null
202
+ ? {} : { maxLatencyIncrease: budgets.maxLatencyIncrease }),
203
+ regressions: findRegressions(baseline, candidate, maxDrop)
204
+ .filter(regression => suppressByMetric.get(regression.metric) !== true),
205
+ confirmedCaseRegressions,
206
+ };
207
+ }
208
+ /** Format a gate value as a percentage, a count, or a dash. */
209
+ function format(value, check) {
210
+ if (value === null)
211
+ return '–';
212
+ if (check.unit === 'count')
213
+ return String(value);
214
+ if (check.unit === 'usd')
215
+ return `$${value.toFixed(6)}`;
216
+ if (check.unit === 'ms')
217
+ return `${value.toFixed(1)} ms`;
218
+ if (check.unit === 'p')
219
+ return value.toFixed(4);
220
+ return `${(value * 100).toFixed(1)}%`;
221
+ }
222
+ /** Format a signed delta with the check's unit. */
223
+ function formatDelta(value, check) {
224
+ if (value === null)
225
+ return '–';
226
+ const sign = value >= 0 ? '+' : '';
227
+ if (check.unit === 'count')
228
+ return `${sign}${value}`;
229
+ if (check.unit === 'p')
230
+ return `${sign}${value.toFixed(4)}`;
231
+ if (check.unit === 'usd' || check.unit === 'ms') {
232
+ const relative = check.baseline === null || check.baseline === 0
233
+ ? null : (value / check.baseline) * 100;
234
+ return relative === null ? `${sign}${value.toFixed(2)}` : `${sign}${relative.toFixed(1)}%`;
235
+ }
236
+ return `${sign}${(value * 100).toFixed(1)}pp`;
237
+ }
238
+ /**
239
+ * Render a gate decision as machine-readable JSON for CI consumers.
240
+ * @param result - the evaluated gate.
241
+ * @returns a JSON string ending in a newline.
242
+ */
243
+ export function renderGateJson(result) {
244
+ return `${JSON.stringify({
245
+ passed: result.passed,
246
+ maxDrop: result.maxDrop,
247
+ ...(result.maxCostIncrease === undefined ? {} : { maxCostIncrease: result.maxCostIncrease }),
248
+ ...(result.maxLatencyIncrease === undefined ? {} : { maxLatencyIncrease: result.maxLatencyIncrease }),
249
+ checks: result.checks,
250
+ regressions: result.regressions ?? [],
251
+ confirmedCaseRegressions: result.confirmedCaseRegressions ?? [],
252
+ })}\n`;
253
+ }
254
+ /**
255
+ * Render a gate decision as markdown.
256
+ * @param result - the evaluated gate.
257
+ * @returns a compact table ending in a newline.
258
+ */
259
+ export function renderGate(result) {
260
+ const rows = result.checks.map(check => `| ${check.metric} | ${format(check.baseline, check)} | ${format(check.candidate, check)} | ${formatDelta(check.delta, check)} | ${check.passed ? 'PASS' : 'FAIL'}${check.note === undefined ? '' : ` (${check.note})`} |`);
261
+ const regressions = (result.regressions ?? []).slice(0, 5).map(item => {
262
+ // Case ids come from benchmark files; keep them from breaking markdown lines.
263
+ const caseId = item.caseId.replace(/[\r\n|]/gu, ' ');
264
+ const before = `${(item.before * 100).toFixed(1)}%`;
265
+ const after = `${(item.after * 100).toFixed(1)}%`;
266
+ return ` - ${caseId} #${item.trial}: ${item.metric} ${before} → ${after}`;
267
+ });
268
+ const confirmed = (result.confirmedCaseRegressions ?? []).slice(0, 5).map(item => {
269
+ const caseId = item.caseId.replace(/[\r\n|]/gu, ' ');
270
+ return ` - ${caseId}: ${item.metric}, adjusted p ${formatPValue(item.adjustedP)}`;
271
+ });
272
+ return [
273
+ `# Gate: ${result.passed ? 'PASS' : 'FAIL'}`,
274
+ '',
275
+ `- max tolerated drop: ${(result.maxDrop * 100).toFixed(1)} percentage points`,
276
+ ...(result.maxCostIncrease === undefined ? [] : [`- max tolerated cost increase: ${(result.maxCostIncrease * 100).toFixed(1)}%`]),
277
+ ...(result.maxLatencyIncrease === undefined ? [] : [`- max tolerated latency increase: ${(result.maxLatencyIncrease * 100).toFixed(1)}%`]),
278
+ '',
279
+ '| check | baseline | candidate | Δ | result |',
280
+ '|---|---|---|---|---|',
281
+ ...rows,
282
+ '',
283
+ ...(regressions.length === 0 ? [] : [
284
+ `- case regressions: ${result.regressions.length} paired trial(s) got worse (showing up to 5)`,
285
+ ...regressions,
286
+ ]),
287
+ ...(confirmed.length === 0 ? [] : [
288
+ `- confirmed case regressions: ${result.confirmedCaseRegressions.length} case(s) survived family correction (showing up to 5)`,
289
+ ...confirmed,
290
+ ]),
291
+ ...(regressions.length === 0 && confirmed.length === 0 ? [] : ['']),
292
+ ].join('\n');
293
+ }
package/lib/import.js CHANGED
@@ -20,7 +20,11 @@ const BASE_MS = 1_700_000_000_000;
20
20
  function eventTime(lineIndex) {
21
21
  return BASE_MS + lineIndex * STEP_MS;
22
22
  }
23
- /** Extract display text from a string, a text block, or a block array. */
23
+ /** Split external JSONL, tolerating a UTF-8 BOM before the first line. */
24
+ function splitLines(text) {
25
+ return text.replace(/^\uFEFF/u, '').split(/\r?\n/u);
26
+ }
27
+ /** Extract display text from a string, a single text block, or a block array. */
24
28
  function textOf(value) {
25
29
  if (typeof value === 'string')
26
30
  return value;
@@ -32,6 +36,10 @@ function textOf(value) {
32
36
  return typeof text === 'string' ? [text] : [];
33
37
  }).join('');
34
38
  }
39
+ if (typeof value === 'object') {
40
+ const text = value?.text;
41
+ return typeof text === 'string' ? text : '';
42
+ }
35
43
  return '';
36
44
  }
37
45
  /** Stable synthetic session id from the source filename. */
@@ -68,11 +76,12 @@ export function importCodexLog(text, source) {
68
76
  let step = 0;
69
77
  let open = false;
70
78
  let callCounter = 0;
79
+ let resultCounter = 0;
71
80
  let messageCounter = 0;
72
81
  const close = () => {
73
82
  open = closeTurn(events, turn, step, open);
74
83
  };
75
- for (const line of text.split(/\r?\n/u)) {
84
+ for (const line of splitLines(text)) {
76
85
  if (line.trim() === '')
77
86
  continue;
78
87
  let record;
@@ -130,8 +139,10 @@ export function importCodexLog(text, source) {
130
139
  events.push({ type: 'tool/call', data: { turn, step, callId, name, arguments: argumentsText } });
131
140
  }
132
141
  else if (payload.type === 'function_call_output') {
133
- callCounter += 1;
134
- const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${callCounter}`;
142
+ // Fallback ids pair by occurrence order: a call and its output each
143
+ // increment their own counter, so two missing call_id values both get N.
144
+ resultCounter += 1;
145
+ const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${resultCounter}`;
135
146
  const output = textOf(payload.output ?? payload.content);
136
147
  events.push({
137
148
  type: 'tool/result',
@@ -139,7 +150,7 @@ export function importCodexLog(text, source) {
139
150
  turn,
140
151
  step,
141
152
  message: {
142
- id: `tool-result-${callCounter}`,
153
+ id: `tool-result-${resultCounter}`,
143
154
  role: 'user',
144
155
  content: [{ type: 'tool-result', text: output, isError: payload.is_error === true }],
145
156
  source: { kind: 'tool', callId },
@@ -173,7 +184,7 @@ export function importClaudeLog(text, source) {
173
184
  const close = () => {
174
185
  open = closeTurn(events, turn, step, open);
175
186
  };
176
- for (const line of text.split(/\r?\n/u)) {
187
+ for (const line of splitLines(text)) {
177
188
  if (line.trim() === '')
178
189
  continue;
179
190
  let record;
package/lib/index.js CHANGED
@@ -6,17 +6,27 @@
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
  */
15
+ import { writeTextAtomic } from "./atomic-write.js";
14
16
  import { loadBenchmark } from "./benchmark.js";
17
+ import { hashBenchmarkOverrides } from "./digest.js";
15
18
  import { applyEval } from "./command.js";
16
- import { compareRuns, renderCompareMarkdown } from "./compare.js";
19
+ import { compareRuns, pairedCases, pairedCaseSignificance, renderCaseSignificance, renderCompareJson, renderCompareMarkdown, renderPairedCases, } from "./compare.js";
20
+ import { writeDashboard } from "./dashboard.js";
21
+ import { evaluateGate, renderGate, renderGateJson } from "./gate.js";
22
+ import { renderTrialsCsv } from "./export.js";
17
23
  import { importTraceFile } from "./import.js";
24
+ import { buildLeaderboard, renderLeaderboard, renderLeaderboardJson } from "./leaderboard.js";
18
25
  import { llmJudgeChat } from "./judge.js";
19
- import { renderMarkdownReport, writeRunReport, loadRunReport } from "./report.js";
26
+ import { computeCoverage, computeReliability } from "./reliability.js";
27
+ import { rejudgeRun } from "./rejudge.js";
28
+ import { renderBenchmarkJson, renderBenchmarkSummary } from "./validate.js";
29
+ import { renderBriefReport, renderMarkdownReport, renderReportJson, writeRunReport, loadRunReport } from "./report.js";
20
30
  import { runBenchmark } from "./runner.js";
21
31
  /** Stable Cordis plugin name. */
22
32
  export const name = 'eval';
@@ -37,6 +47,34 @@ export function resolveJudgeChat(ctx) {
37
47
  const llm = ctx.get('llm');
38
48
  return llm === undefined ? undefined : llmJudgeChat(llm.stream);
39
49
  }
50
+ /** Rough seconds remaining from observed throughput; null until meaningful. */
51
+ function estimateEta(finished, total, startedAtMs, nowMs) {
52
+ if (startedAtMs === undefined || finished <= 0 || finished >= total)
53
+ return null;
54
+ const elapsed = nowMs - startedAtMs;
55
+ if (!Number.isFinite(elapsed) || elapsed <= 0)
56
+ return null;
57
+ return Math.max(0, Math.round((elapsed / finished) * (total - finished) / 1000));
58
+ }
59
+ /** One bounded progress line; agent-controlled text must not inject newlines or terminal control codes. */
60
+ export function renderProgress(result, finished, total, startedAtMs, nowMs = Date.now()) {
61
+ const clean = (value) => value
62
+ // CSI / OSC sequences first, then every remaining C0/C1 control byte.
63
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, '')
64
+ .replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/gu, '')
65
+ .replace(/[\u0000-\u001f\u007f-\u009f]/gu, ' ')
66
+ .slice(0, 200);
67
+ const label = `${clean(result.caseId)} #${result.trial}`;
68
+ const eta = estimateEta(finished, total, startedAtMs, nowMs);
69
+ const suffix = eta === null ? '' : `, eta ${eta}s`;
70
+ if (result.status === 'error') {
71
+ return `[eval] ${finished}/${total} ${label} ERROR ${clean(result.error ?? 'unknown error')}${suffix}\n`;
72
+ }
73
+ const task = result.grade?.taskSuccess === undefined || result.grade.taskSuccess === null
74
+ ? 'n/a' : result.grade.taskSuccess ? 'pass' : 'fail';
75
+ const latency = result.metrics?.latencyMs === undefined ? '?' : result.metrics.latencyMs.toFixed(0);
76
+ return `[eval] ${finished}/${total} ${label} task ${task}, ${latency} ms${suffix}\n`;
77
+ }
40
78
  /** Aggregate-success sentence for the run summary line. */
41
79
  function summary(run) {
42
80
  const aggregate = run.aggregate;
@@ -51,15 +89,30 @@ function summary(run) {
51
89
  const score = judgeScore === null || judgeScore === undefined
52
90
  ? ''
53
91
  : `, judge score ${judgeScore.toFixed(1)}`;
54
- return `tool success ${rate}${task}${score}, ${aggregate.steps.toFixed(1)} steps/trial`;
92
+ const reliability = computeReliability(run, 'task');
93
+ const passes = reliability === null
94
+ ? ''
95
+ : `, pass@${reliability.k} ${(reliability.passAtK * 100).toFixed(1)}% / pass^${reliability.k} ${(reliability.passAllK * 100).toFixed(1)}%`;
96
+ const coverage = computeCoverage(run);
97
+ const unscored = coverage.unscored === 0 ? '' : `, ${coverage.unscored} unscored`;
98
+ return `tool success ${rate}${task}${score}${passes}${unscored}, ${aggregate.steps.toFixed(1)} steps/trial`;
99
+ }
100
+ /** Print derived text, or write it to a file and confirm the path. */
101
+ async function emitText(io, text, outPath, detail = '') {
102
+ if (outPath === undefined) {
103
+ io.stdout.write(text);
104
+ return;
105
+ }
106
+ await writeTextAtomic(outPath, text);
107
+ io.stdout.write(`Wrote ${outPath}${detail}\n`);
55
108
  }
56
109
  /**
57
110
  * Execute one eval invocation to completion.
58
111
  * @param values - the resolved command-line invocation.
59
112
  * @param io - output streams for the report and diagnostics.
60
113
  * @param services - injected runtime seams, e.g. the LLM-judge chat.
61
- * @returns the process exit code; nonzero for any failure or a run with no
62
- * completed trials.
114
+ * @returns the process exit code; nonzero when any trial failed or no trial
115
+ * completed, so a partially failing run cannot be mistaken for a green CI.
63
116
  */
64
117
  export async function executeEval(values, io, services = {}) {
65
118
  try {
@@ -71,26 +124,135 @@ export async function executeEval(values, io, services = {}) {
71
124
  }
72
125
  if (values.kind === 'report') {
73
126
  const run = await loadRunReport(values.runPath);
74
- io.stdout.write(renderMarkdownReport(run));
127
+ const report = values.json === true
128
+ ? renderReportJson(run)
129
+ : values.brief ? renderBriefReport(run) : renderMarkdownReport(run);
130
+ await emitText(io, report, values.outPath);
75
131
  return 0;
76
132
  }
77
133
  if (values.kind === 'compare') {
78
134
  const a = await loadRunReport(values.runPathA);
79
135
  const b = await loadRunReport(values.runPathB);
80
- io.stdout.write(renderCompareMarkdown(compareRuns(a, b)));
136
+ if (values.json === true) {
137
+ await emitText(io, renderCompareJson(a, b), values.outPath);
138
+ return 0;
139
+ }
140
+ const cases = pairedCases(a, b);
141
+ const significance = pairedCaseSignificance(a, b);
142
+ const text = renderCompareMarkdown(compareRuns(a, b))
143
+ + (cases === null ? '' : renderPairedCases(cases))
144
+ + (significance === null || significance.length === 0 ? '' : renderCaseSignificance(significance));
145
+ await emitText(io, text, values.outPath);
146
+ return 0;
147
+ }
148
+ if (values.kind === 'export') {
149
+ const run = await loadRunReport(values.runPath);
150
+ const csv = renderTrialsCsv(run);
151
+ await emitText(io, csv, values.outPath, ` (${run.cases.length} trials)`);
152
+ return 0;
153
+ }
154
+ if (values.kind === 'validate') {
155
+ const benchmark = await loadBenchmark(values.benchmarkPath, {
156
+ allowExternalPaths: values.allowExternalPaths === true,
157
+ });
158
+ await emitText(io, values.json === true
159
+ ? renderBenchmarkJson(benchmark)
160
+ : renderBenchmarkSummary(benchmark), values.outPath);
81
161
  return 0;
82
162
  }
83
- const benchmark = await loadBenchmark(values.benchmarkPath);
163
+ if (values.kind === 'provenance') {
164
+ const run = await loadRunReport(values.runPath);
165
+ const benchmark = await loadBenchmark(values.benchmarkPath, {
166
+ allowExternalPaths: values.allowExternalPaths === true,
167
+ excludeFromDigest: [values.runPath],
168
+ });
169
+ const runSha256 = run.benchmarkSha256 ?? null;
170
+ // loadBenchmark always computes this digest from the resolved inputs;
171
+ // CLI overrides are folded in exactly as runBenchmark did.
172
+ const benchmarkSha256 = run.benchmarkOverrides === undefined
173
+ ? benchmark.sourceSha256
174
+ : hashBenchmarkOverrides(benchmark.sourceSha256, run.benchmarkOverrides);
175
+ const status = runSha256 === null ? 'missing'
176
+ : runSha256 === benchmarkSha256 ? 'match' : 'mismatch';
177
+ const text = values.json === true
178
+ ? `${JSON.stringify({ status, runSha256, benchmarkSha256 })}\n`
179
+ : `Provenance: ${status}\nrun: ${runSha256 ?? 'n/a'}\nbenchmark: ${benchmarkSha256}\n`;
180
+ await emitText(io, text, values.outPath);
181
+ return status === 'match' ? 0 : 1;
182
+ }
183
+ if (values.kind === 'leaderboard') {
184
+ const runs = await Promise.all(values.runPaths.map(async (path) => loadRunReport(path)));
185
+ const entries = buildLeaderboard(runs.map(run => ({
186
+ label: `${run.benchmark} — ${run.model}`,
187
+ run,
188
+ })), values.metric);
189
+ await emitText(io, values.json === true
190
+ ? renderLeaderboardJson(entries, values.metric)
191
+ : renderLeaderboard(entries, values.metric), values.outPath);
192
+ return 0;
193
+ }
194
+ if (values.kind === 'gate') {
195
+ const [candidate, baseline] = await Promise.all([
196
+ loadRunReport(values.candidatePath),
197
+ loadRunReport(values.baselinePath),
198
+ ]);
199
+ const budgets = {
200
+ ...(values.maxCostIncrease === undefined ? {} : { maxCostIncrease: values.maxCostIncrease }),
201
+ ...(values.maxLatencyIncrease === undefined ? {} : { maxLatencyIncrease: values.maxLatencyIncrease }),
202
+ };
203
+ const result = evaluateGate(baseline, candidate, values.maxDrop, values.allowIncomplete, budgets, values.requireSignificance === true ? { requireSignificance: true } : {});
204
+ await emitText(io, values.json === true ? renderGateJson(result) : renderGate(result), values.outPath);
205
+ return result.passed ? 0 : 1;
206
+ }
207
+ if (values.kind === 'dashboard') {
208
+ const runs = await Promise.all(values.runPaths.map(async (path) => loadRunReport(path)));
209
+ await writeDashboard(runs, values.outPath, values.metric);
210
+ io.stdout.write(`Wrote ${values.outPath}\n`);
211
+ return 0;
212
+ }
213
+ if (values.kind === 'rejudge') {
214
+ if (services.judgeChat === undefined)
215
+ throw new Error('rejudge: no LLM chat seam is available');
216
+ const run = await loadRunReport(values.runPath);
217
+ const rejudged = await rejudgeRun(run, services.judgeChat, values.judge);
218
+ await writeRunReport(rejudged, values.outPath);
219
+ const judgedCount = rejudged.cases.filter(result => result.judge?.finalAnswerScore !== null && result.judge?.finalAnswerScore !== undefined).length;
220
+ io.stdout.write(`Wrote ${values.outPath} (${judgedCount}/${rejudged.cases.length} judged)\n`);
221
+ return 0;
222
+ }
223
+ const benchmark = await loadBenchmark(values.benchmarkPath, {
224
+ allowExternalPaths: values.allowExternalPaths === true,
225
+ excludeFromDigest: [values.outPath],
226
+ });
227
+ const startedAtMs = Date.now();
84
228
  const run = await runBenchmark(benchmark, {
85
229
  ...(values.trials !== undefined ? { trials: values.trials } : {}),
86
230
  ...(values.concurrency !== undefined ? { concurrency: values.concurrency } : {}),
231
+ ...(values.seed !== undefined ? { seed: values.seed } : {}),
87
232
  ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
88
233
  ...(values.profile !== undefined ? { profile: values.profile } : {}),
89
234
  ...(services.judgeChat !== undefined ? { judgeChat: services.judgeChat } : {}),
235
+ ...(values.quiet === true ? {} : {
236
+ onProgress: (result, finished, total) => {
237
+ io.stderr.write(renderProgress(result, finished, total, startedAtMs));
238
+ },
239
+ }),
90
240
  });
91
241
  await writeRunReport(run, values.outPath);
92
- io.stdout.write(`Wrote ${values.outPath} (${run.cases.length} trials, ${summary(run)})\n`);
93
- return run.aggregate === null ? 1 : 0;
242
+ const failed = run.cases.filter(result => result.status === 'error');
243
+ const completed = run.cases.length - failed.length;
244
+ io.stdout.write(`Wrote ${values.outPath} (${completed}/${run.cases.length} completed, ${summary(run)})\n`);
245
+ // A failed trial lives in the JSON report, but a CLI run must also say why
246
+ // on stderr — otherwise an empty stdout/stderr looks like a clean failure.
247
+ if (failed.length > 0) {
248
+ const sample = failed.slice(0, 3).map((result) => {
249
+ /* v8 ignore next 2 -- runner always sets `error` on error trials; the fallback guards hand-edited reports. */
250
+ const detail = result.error ?? 'unknown error';
251
+ return `${result.caseId}#${result.trial}: ${detail}`;
252
+ }).join('\n');
253
+ io.stderr.write(`dsh eval: ${failed.length} trial(s) failed:\n${sample}\n`);
254
+ }
255
+ return failed.length > 0 || run.aggregate === null ? 1 : 0;
94
256
  }
95
257
  catch (error) {
96
258
  io.stderr.write(`dsh eval: ${error instanceof Error ? error.message : String(error)}\n`);