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/gate.ts ADDED
@@ -0,0 +1,383 @@
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
+
12
+ import { formatPValue, pairedCaseSignificance, pairedSigns, type PairedMetric } from './compare.ts'
13
+ import { computeCoverage, computeReliability } from './reliability.ts'
14
+ import { signTest, signTestPower } from './stats.ts'
15
+ import type { EvalRun } from './types.ts'
16
+
17
+ /** One gate criterion. */
18
+ export interface GateCheck {
19
+ metric: string
20
+ baseline: number | null
21
+ candidate: number | null
22
+ delta: number | null
23
+ passed: boolean
24
+ /** Count checks print integers; rates print percentages; budgets print money/time. */
25
+ unit?: 'count' | 'usd' | 'ms' | 'p'
26
+ note?: string
27
+ }
28
+
29
+ /** A single case x trial that got worse between the two runs. */
30
+ export interface CaseRegression {
31
+ caseId: string
32
+ trial: number
33
+ metric: 'task success' | 'tool selection' | 'judge score'
34
+ before: number
35
+ after: number
36
+ }
37
+
38
+ /** Aggregated gate decision. */
39
+ export interface GateResult {
40
+ checks: readonly GateCheck[]
41
+ passed: boolean
42
+ maxDrop: number
43
+ /** Optional for callers that only need the aggregate verdict. */
44
+ regressions?: readonly CaseRegression[]
45
+ /** Enabled relative cost budget, if any. */
46
+ maxCostIncrease?: number
47
+ /** Enabled relative latency budget, if any. */
48
+ maxLatencyIncrease?: number
49
+ /** Cases with a family-corrected, statistically confirmed paired regression. */
50
+ confirmedCaseRegressions?: readonly ConfirmedCaseRegression[]
51
+ }
52
+
53
+ /** A regression that survives per-case multiple-comparison correction. */
54
+ export interface ConfirmedCaseRegression {
55
+ caseId: string
56
+ metric: PairedMetric
57
+ adjustedP: number
58
+ }
59
+
60
+ /** Optional resource budgets for a gate run. */
61
+ export interface GateBudgets {
62
+ maxCostIncrease?: number | null
63
+ maxLatencyIncrease?: number | null
64
+ }
65
+
66
+ /** Optional significance mode for a gate run. */
67
+ export interface GateOptions {
68
+ /**
69
+ * Only treat quality drops as failures when the paired sign test confirms a
70
+ * regression. Insufficient or underpowered evidence fails closed.
71
+ */
72
+ requireSignificance?: boolean
73
+ }
74
+
75
+ /** Normalized judge score for a run, or null when ungraded. */
76
+ function scoreRate(run: EvalRun): number | null {
77
+ const score = run.grading?.finalAnswerScore
78
+ if (score === null || score === undefined) return null
79
+ const maxScore = run.judge?.maxScore
80
+ return maxScore === undefined || maxScore <= 0 ? null : score / maxScore
81
+ }
82
+
83
+ /** Normalized per-case judge score for one trial. */
84
+ function caseScore(run: EvalRun, result: EvalRun['cases'][number]): number | null {
85
+ const verdict = result.judge
86
+ if (verdict === undefined) return null
87
+ const score = verdict.finalAnswerScore
88
+ const maxScore = run.judge?.maxScore
89
+ if (score === null || maxScore === undefined || maxScore <= 0) return null
90
+ return Math.max(0, Math.min(1, score / maxScore))
91
+ }
92
+
93
+ /** Find paired case x trials that regressed, for actionable CI output. */
94
+ function findRegressions(
95
+ baseline: EvalRun,
96
+ candidate: EvalRun,
97
+ maxDrop: number,
98
+ ): CaseRegression[] {
99
+ const byKey = new Map<string, EvalRun['cases'][number]>()
100
+ for (const result of baseline.cases) byKey.set(`${result.caseId}\u0000${result.trial}`, result)
101
+ const regressions: CaseRegression[] = []
102
+ for (const result of candidate.cases) {
103
+ const before = byKey.get(`${result.caseId}\u0000${result.trial}`)
104
+ if (before === undefined) continue
105
+ for (const [metric, previous, current] of [
106
+ ['task success', before.grade?.taskSuccess, result.grade?.taskSuccess],
107
+ ['tool selection', before.grade?.toolSelectionAccuracy, result.grade?.toolSelectionAccuracy],
108
+ ] as const) {
109
+ if (previous === true && current === false) {
110
+ regressions.push({ caseId: result.caseId, trial: result.trial, metric, before: 1, after: 0 })
111
+ }
112
+ }
113
+ const previousScore = caseScore(baseline, before)
114
+ const currentScore = caseScore(candidate, result)
115
+ if (previousScore !== null && currentScore !== null && currentScore < previousScore - maxDrop) {
116
+ regressions.push({
117
+ caseId: result.caseId, trial: result.trial, metric: 'judge score',
118
+ before: previousScore, after: currentScore,
119
+ })
120
+ }
121
+ }
122
+ return regressions
123
+ }
124
+
125
+ /** Compare two nullable rates, allowing a drop of at most `maxDrop`. */
126
+ function compareRate(
127
+ metric: string,
128
+ baseline: number | null,
129
+ candidate: number | null,
130
+ maxDrop: number,
131
+ suppressDrop = false,
132
+ ): GateCheck {
133
+ if (baseline === null) {
134
+ return { metric, baseline, candidate, delta: null, passed: true, note: 'baseline ungraded' }
135
+ }
136
+ if (candidate === null) {
137
+ return { metric, baseline, candidate, delta: null, passed: false, note: 'candidate ungraded' }
138
+ }
139
+ const delta = candidate - baseline
140
+ if (delta >= -maxDrop) return { metric, baseline, candidate, delta, passed: true }
141
+ if (suppressDrop) {
142
+ return { metric, baseline, candidate, delta, passed: true, note: 'drop not statistically confirmed' }
143
+ }
144
+ return { metric, baseline, candidate, delta, passed: false }
145
+ }
146
+
147
+ /** Compare two resource figures against a relative increase budget. */
148
+ function compareBudget(
149
+ metric: string,
150
+ baseline: number | null,
151
+ candidate: number | null,
152
+ maxIncrease: number,
153
+ unit: 'usd' | 'ms',
154
+ ): GateCheck {
155
+ if (baseline === null) {
156
+ return { metric, baseline, candidate, delta: null, passed: true, unit, note: 'baseline metrics unavailable — check skipped' }
157
+ }
158
+ if (candidate === null) {
159
+ return { metric, baseline, candidate, delta: null, passed: false, unit, note: 'candidate unpriced' }
160
+ }
161
+ const delta = candidate - baseline
162
+ // Floating-point noise at 1e-9 of the baseline must not fail an exact budget.
163
+ const limit = baseline * maxIncrease + Math.abs(baseline) * 1e-9
164
+ return { metric, baseline, candidate, delta, passed: delta <= limit, unit }
165
+ }
166
+
167
+ /**
168
+ * Evaluate a candidate run against a baseline.
169
+ * @param baseline - the trusted reference run.
170
+ * @param candidate - the run under test.
171
+ * @param maxDrop - largest tolerated regression on the 0..1 scale.
172
+ * @param allowIncomplete - skip the trial-coverage checks when true.
173
+ * @param budgets - optional relative cost and latency increase limits.
174
+ * @param options - optional significance mode for quality regressions.
175
+ * @returns the per-metric checks and the overall decision.
176
+ */
177
+ export function evaluateGate(
178
+ baseline: EvalRun,
179
+ candidate: EvalRun,
180
+ maxDrop: number,
181
+ allowIncomplete = false,
182
+ budgets: GateBudgets = {},
183
+ options: GateOptions = {},
184
+ ): GateResult {
185
+ const baseCoverage = computeCoverage(baseline)
186
+ const candCoverage = computeCoverage(candidate)
187
+ const baseTask = computeReliability(baseline, 'task')
188
+ const candTask = computeReliability(candidate, 'task')
189
+ const checks: GateCheck[] = []
190
+ if (!allowIncomplete) {
191
+ for (const [metric, value, limit, comparison] of [
192
+ ['completed trials', candCoverage.completed, baseCoverage.completed, 'at least'],
193
+ ['unscored trials', candCoverage.unscored, baseCoverage.unscored, 'at most'],
194
+ ] as const) {
195
+ const passed = comparison === 'at least' ? value >= limit : value <= limit
196
+ checks.push({
197
+ metric, baseline: limit, candidate: value,
198
+ delta: value - limit, passed, unit: 'count',
199
+ ...(passed ? {} : { note: `expected ${comparison} ${limit}` }),
200
+ })
201
+ }
202
+ }
203
+ // Significance is assessed per quality metric: a clean task-success result
204
+ // must never hide a real tool-selection or judge-score regression.
205
+ const suppressByMetric = new Map<string, boolean>()
206
+ if (options.requireSignificance === true) {
207
+ const qualityMetrics = [
208
+ { metric: 'task success', paired: 'task success', a: baseline.grading?.taskSuccessRate ?? null, b: candidate.grading?.taskSuccessRate ?? null },
209
+ { metric: 'tool selection', paired: 'tool selection accuracy', a: baseline.grading?.toolSelectionAccuracyRate ?? null, b: candidate.grading?.toolSelectionAccuracyRate ?? null },
210
+ { metric: 'strict pass@1 (task)', paired: 'task success', a: baseTask?.strictPassAt1 ?? null, b: candTask?.strictPassAt1 ?? null },
211
+ { metric: 'judge score', paired: 'final answer score', a: scoreRate(baseline), b: scoreRate(candidate) },
212
+ ] as const satisfies readonly { metric: string; paired: PairedMetric; a: number | null; b: number | null }[]
213
+ let undecidable = false
214
+ let bestFloor = 1
215
+ let worstObserved = 0
216
+ const assessed = qualityMetrics.filter(item => item.a !== null || item.b !== null)
217
+ // task success and strict pass@1 share one sign test, and ungraded metrics
218
+ // are not tested at all; correcting for all four rows would be too lax.
219
+ const pairedMetrics = [...new Set(assessed.map(item => item.paired))]
220
+ const family = pairedMetrics.length
221
+ const verdicts = new Map<PairedMetric, boolean>()
222
+ for (const pairedMetric of pairedMetrics) {
223
+ const counts = pairedSigns(baseline, candidate, pairedMetric)
224
+ const discordant = counts.wins + counts.losses
225
+ const power = signTestPower(discordant, family)
226
+ const observed = Math.min(1, signTest(counts.wins, counts.losses).pValue * family)
227
+ const worse = counts.losses > counts.wins
228
+ const informative = discordant > 0 && power.detectable
229
+ const confirmed = informative && worse && observed <= power.alpha
230
+ const clear = informative && !confirmed && (observed > power.alpha || !worse)
231
+ verdicts.set(pairedMetric, clear)
232
+ if (!informative || (!confirmed && !clear)) undecidable = true
233
+ bestFloor = Math.min(bestFloor, power.bestAdjustedP)
234
+ worstObserved = Math.max(worstObserved, observed)
235
+ }
236
+ for (const item of assessed) {
237
+ suppressByMetric.set(item.metric, verdicts.get(item.paired) === true)
238
+ }
239
+ // The strict pass@1 rate keeps errors and timeouts in its denominator, but
240
+ // pairedSigns only sees completed trials. A candidate with more unscored
241
+ // trials must not get its strict drop excused by survivor-only evidence.
242
+ if (computeCoverage(candidate).unscored > computeCoverage(baseline).unscored) {
243
+ suppressByMetric.set('strict pass@1 (task)', false)
244
+ }
245
+ checks.push({
246
+ metric: 'paired significance',
247
+ baseline: bestFloor,
248
+ candidate: worstObserved,
249
+ delta: worstObserved - bestFloor,
250
+ passed: !undecidable,
251
+ unit: 'p',
252
+ note: undecidable ? 'some quality metrics lack conclusive paired evidence'
253
+ : 'all quality metrics assessed independently',
254
+ })
255
+ }
256
+ checks.push(
257
+ compareRate('task success', baseline.grading?.taskSuccessRate ?? null,
258
+ candidate.grading?.taskSuccessRate ?? null, maxDrop, suppressByMetric.get('task success')),
259
+ compareRate('tool selection', baseline.grading?.toolSelectionAccuracyRate ?? null,
260
+ candidate.grading?.toolSelectionAccuracyRate ?? null, maxDrop,
261
+ suppressByMetric.get('tool selection')),
262
+ compareRate('strict pass@1 (task)', baseTask?.strictPassAt1 ?? null,
263
+ candTask?.strictPassAt1 ?? null, maxDrop, suppressByMetric.get('strict pass@1 (task)')),
264
+ compareRate('judge score', scoreRate(baseline), scoreRate(candidate), maxDrop,
265
+ suppressByMetric.get('judge score')),
266
+ )
267
+ if (budgets.maxCostIncrease !== undefined && budgets.maxCostIncrease !== null) {
268
+ checks.push(compareBudget('cost/trial', baseline.aggregate?.costUsd ?? null,
269
+ candidate.aggregate?.costUsd ?? null, budgets.maxCostIncrease, 'usd'))
270
+ }
271
+ if (budgets.maxLatencyIncrease !== undefined && budgets.maxLatencyIncrease !== null) {
272
+ checks.push(compareBudget('latency/trial', baseline.aggregate?.latencyMs ?? null,
273
+ candidate.aggregate?.latencyMs ?? null, budgets.maxLatencyIncrease, 'ms'))
274
+ }
275
+ // Per-case evidence uses each quality metric's own paired trials; the
276
+ // default metric chosen by pickMetric() would miss tool/judge-only drops.
277
+ const confirmedCaseRegressions = (['task success', 'tool selection accuracy', 'final answer score'] as const)
278
+ .flatMap(metric => (pairedCaseSignificance(baseline, candidate, metric) ?? [])
279
+ .filter(row => row.verdict === 'significantly-worse')
280
+ .map(row => ({ caseId: row.caseId, metric, adjustedP: row.adjustedP })))
281
+ if (options.requireSignificance === true && confirmedCaseRegressions.length > 0) {
282
+ checks.push({
283
+ metric: 'confirmed case regressions',
284
+ baseline: 0, candidate: confirmedCaseRegressions.length,
285
+ delta: confirmedCaseRegressions.length, passed: false, unit: 'count',
286
+ note: 'family-corrected per-case regression',
287
+ })
288
+ }
289
+ return {
290
+ checks,
291
+ passed: checks.every(check => check.passed),
292
+ maxDrop,
293
+ ...(budgets.maxCostIncrease === undefined || budgets.maxCostIncrease === null
294
+ ? {} : { maxCostIncrease: budgets.maxCostIncrease }),
295
+ ...(budgets.maxLatencyIncrease === undefined || budgets.maxLatencyIncrease === null
296
+ ? {} : { maxLatencyIncrease: budgets.maxLatencyIncrease }),
297
+ regressions: findRegressions(baseline, candidate, maxDrop)
298
+ .filter(regression => suppressByMetric.get(regression.metric) !== true),
299
+ confirmedCaseRegressions,
300
+ }
301
+ }
302
+
303
+ /** Format a gate value as a percentage, a count, or a dash. */
304
+ function format(value: number | null, check: GateCheck): string {
305
+ if (value === null) return '–'
306
+ if (check.unit === 'count') return String(value)
307
+ if (check.unit === 'usd') return `$${value.toFixed(6)}`
308
+ if (check.unit === 'ms') return `${value.toFixed(1)} ms`
309
+ if (check.unit === 'p') return value.toFixed(4)
310
+ return `${(value * 100).toFixed(1)}%`
311
+ }
312
+
313
+ /** Format a signed delta with the check's unit. */
314
+ function formatDelta(value: number | null, check: GateCheck): string {
315
+ if (value === null) return '–'
316
+ const sign = value >= 0 ? '+' : ''
317
+ if (check.unit === 'count') return `${sign}${value}`
318
+ if (check.unit === 'p') return `${sign}${value.toFixed(4)}`
319
+ if (check.unit === 'usd' || check.unit === 'ms') {
320
+ const relative = check.baseline === null || check.baseline === 0
321
+ ? null : (value / check.baseline) * 100
322
+ return relative === null ? `${sign}${value.toFixed(2)}` : `${sign}${relative.toFixed(1)}%`
323
+ }
324
+ return `${sign}${(value * 100).toFixed(1)}pp`
325
+ }
326
+
327
+ /**
328
+ * Render a gate decision as machine-readable JSON for CI consumers.
329
+ * @param result - the evaluated gate.
330
+ * @returns a JSON string ending in a newline.
331
+ */
332
+ export function renderGateJson(result: GateResult): string {
333
+ return `${JSON.stringify({
334
+ passed: result.passed,
335
+ maxDrop: result.maxDrop,
336
+ ...(result.maxCostIncrease === undefined ? {} : { maxCostIncrease: result.maxCostIncrease }),
337
+ ...(result.maxLatencyIncrease === undefined ? {} : { maxLatencyIncrease: result.maxLatencyIncrease }),
338
+ checks: result.checks,
339
+ regressions: result.regressions ?? [],
340
+ confirmedCaseRegressions: result.confirmedCaseRegressions ?? [],
341
+ })}\n`
342
+ }
343
+
344
+ /**
345
+ * Render a gate decision as markdown.
346
+ * @param result - the evaluated gate.
347
+ * @returns a compact table ending in a newline.
348
+ */
349
+ export function renderGate(result: GateResult): string {
350
+ 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})`} |`)
351
+ const regressions = (result.regressions ?? []).slice(0, 5).map(item => {
352
+ // Case ids come from benchmark files; keep them from breaking markdown lines.
353
+ const caseId = item.caseId.replace(/[\r\n|]/gu, ' ')
354
+ const before = `${(item.before * 100).toFixed(1)}%`
355
+ const after = `${(item.after * 100).toFixed(1)}%`
356
+ return ` - ${caseId} #${item.trial}: ${item.metric} ${before} → ${after}`
357
+ })
358
+ const confirmed = (result.confirmedCaseRegressions ?? []).slice(0, 5).map(item => {
359
+ const caseId = item.caseId.replace(/[\r\n|]/gu, ' ')
360
+ return ` - ${caseId}: ${item.metric}, adjusted p ${formatPValue(item.adjustedP)}`
361
+ })
362
+ return [
363
+ `# Gate: ${result.passed ? 'PASS' : 'FAIL'}`,
364
+ '',
365
+ `- max tolerated drop: ${(result.maxDrop * 100).toFixed(1)} percentage points`,
366
+ ...(result.maxCostIncrease === undefined ? [] : [`- max tolerated cost increase: ${(result.maxCostIncrease * 100).toFixed(1)}%`]),
367
+ ...(result.maxLatencyIncrease === undefined ? [] : [`- max tolerated latency increase: ${(result.maxLatencyIncrease * 100).toFixed(1)}%`]),
368
+ '',
369
+ '| check | baseline | candidate | Δ | result |',
370
+ '|---|---|---|---|---|',
371
+ ...rows,
372
+ '',
373
+ ...(regressions.length === 0 ? [] : [
374
+ `- case regressions: ${result.regressions!.length} paired trial(s) got worse (showing up to 5)`,
375
+ ...regressions,
376
+ ]),
377
+ ...(confirmed.length === 0 ? [] : [
378
+ `- confirmed case regressions: ${result.confirmedCaseRegressions!.length} case(s) survived family correction (showing up to 5)`,
379
+ ...confirmed,
380
+ ]),
381
+ ...(regressions.length === 0 && confirmed.length === 0 ? [] : ['']),
382
+ ].join('\n')
383
+ }
package/src/import.ts CHANGED
@@ -31,7 +31,12 @@ function eventTime(lineIndex: number): number {
31
31
  return BASE_MS + lineIndex * STEP_MS
32
32
  }
33
33
 
34
- /** Extract display text from a string, a text block, or a block array. */
34
+ /** Split external JSONL, tolerating a UTF-8 BOM before the first line. */
35
+ function splitLines(text: string): string[] {
36
+ return text.replace(/^\uFEFF/u, '').split(/\r?\n/u)
37
+ }
38
+
39
+ /** Extract display text from a string, a single text block, or a block array. */
35
40
  function textOf(value: unknown): string {
36
41
  if (typeof value === 'string') return value
37
42
  if (Array.isArray(value)) {
@@ -41,6 +46,10 @@ function textOf(value: unknown): string {
41
46
  return typeof text === 'string' ? [text] : []
42
47
  }).join('')
43
48
  }
49
+ if (typeof value === 'object') {
50
+ const text = (value as Record<string, unknown> | null)?.text
51
+ return typeof text === 'string' ? text : ''
52
+ }
44
53
  return ''
45
54
  }
46
55
 
@@ -85,11 +94,12 @@ export function importCodexLog(text: string, source: string): EvalTrace {
85
94
  let step = 0
86
95
  let open = false
87
96
  let callCounter = 0
97
+ let resultCounter = 0
88
98
  let messageCounter = 0
89
99
  const close = (): void => {
90
100
  open = closeTurn(events, turn, step, open)
91
101
  }
92
- for (const line of text.split(/\r?\n/u)) {
102
+ for (const line of splitLines(text)) {
93
103
  if (line.trim() === '') continue
94
104
  let record: unknown
95
105
  try {
@@ -140,8 +150,10 @@ export function importCodexLog(text: string, source: string): EvalTrace {
140
150
  const argumentsText = typeof payload.arguments === 'string' ? payload.arguments : '{}'
141
151
  events.push({ type: 'tool/call', data: { turn, step, callId, name, arguments: argumentsText } })
142
152
  } else if (payload.type === 'function_call_output') {
143
- callCounter += 1
144
- const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${callCounter}`
153
+ // Fallback ids pair by occurrence order: a call and its output each
154
+ // increment their own counter, so two missing call_id values both get N.
155
+ resultCounter += 1
156
+ const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${resultCounter}`
145
157
  const output = textOf(payload.output ?? payload.content)
146
158
  events.push({
147
159
  type: 'tool/result',
@@ -149,7 +161,7 @@ export function importCodexLog(text: string, source: string): EvalTrace {
149
161
  turn,
150
162
  step,
151
163
  message: {
152
- id: `tool-result-${callCounter}`,
164
+ id: `tool-result-${resultCounter}`,
153
165
  role: 'user',
154
166
  content: [{ type: 'tool-result', text: output, isError: payload.is_error === true }],
155
167
  source: { kind: 'tool', callId },
@@ -185,7 +197,7 @@ export function importClaudeLog(text: string, source: string): EvalTrace {
185
197
  const close = (): void => {
186
198
  open = closeTurn(events, turn, step, open)
187
199
  }
188
- for (const line of text.split(/\r?\n/u)) {
200
+ for (const line of splitLines(text)) {
189
201
  if (line.trim() === '') continue
190
202
  let record: unknown
191
203
  try {