dsh-eval 0.3.0 → 0.4.0

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.
package/lib/report.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Run-report persistence and markdown rendering for dsh-eval.
3
+ *
4
+ * @module dsh-eval/report
5
+ */
6
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
7
+ import { dirname, resolve } from 'node:path';
8
+ /**
9
+ * Write a run report as indented JSON with a trailing newline.
10
+ * @param run - the run record to persist.
11
+ * @param path - output path; parent directories are created.
12
+ */
13
+ 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');
17
+ }
18
+ /**
19
+ * Load a persisted run report, rejecting anything without the required surface.
20
+ * @param path - path to the run JSON.
21
+ * @returns the loaded run record.
22
+ */
23
+ export async function loadRunReport(path) {
24
+ 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`);
28
+ }
29
+ return value;
30
+ }
31
+ /** Render a nullable percentage with a dash placeholder. */
32
+ function formatRate(value) {
33
+ return value === null ? '–' : `${(value * 100).toFixed(1)}%`;
34
+ }
35
+ /** Render a nullable USD cost with a dash placeholder. */
36
+ function formatUsd(value) {
37
+ return value === null ? '–' : `$${value.toFixed(6)}`;
38
+ }
39
+ /** Render a nullable grading boolean with a dash placeholder. */
40
+ function formatGrade(value) {
41
+ return value === null ? '–' : value ? 'yes' : 'no';
42
+ }
43
+ /** Render a nullable score as `value/max` with a dash placeholder. */
44
+ function formatScore(value, maxScore) {
45
+ return value === null ? '–' : `${value.toFixed(1)}/${maxScore}`;
46
+ }
47
+ /**
48
+ * Render a run report as a markdown table: one row per trial plus the
49
+ * aggregate row.
50
+ * @param run - the run record to render.
51
+ * @returns the markdown text.
52
+ */
53
+ export function renderMarkdownReport(run) {
54
+ const judge = run.judge;
55
+ const judged = judge !== undefined;
56
+ const header = judged
57
+ ? [
58
+ '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc | score | halluc |',
59
+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',
60
+ ]
61
+ : [
62
+ '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc |',
63
+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|',
64
+ ];
65
+ const rows = run.cases.map((result) => {
66
+ const metrics = result.metrics;
67
+ const base = metrics === undefined
68
+ ? ['–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
69
+ : [
70
+ String(metrics.steps),
71
+ String(metrics.toolCalls),
72
+ formatRate(metrics.toolSuccessRate),
73
+ String(metrics.invalidToolCalls),
74
+ String(metrics.retries),
75
+ String(metrics.totalTokens),
76
+ formatUsd(metrics.costUsd),
77
+ String(metrics.latencyMs),
78
+ formatGrade(result.grade?.taskSuccess ?? null),
79
+ formatGrade(result.grade?.toolSelectionAccuracy ?? null),
80
+ ];
81
+ const judgeCells = judged
82
+ ? [
83
+ formatScore(result.judge?.finalAnswerScore ?? null, judge.maxScore),
84
+ formatGrade(result.judge?.hallucination ?? null),
85
+ ]
86
+ : [];
87
+ return `| ${result.caseId} | ${result.trial} | ${result.status} | ${[...base, ...judgeCells].join(' | ')} |`;
88
+ });
89
+ const aggregate = run.aggregate;
90
+ const aggregateJudgeCells = judged
91
+ ? [
92
+ formatScore(run.grading?.finalAnswerScore ?? null, judge.maxScore),
93
+ formatRate(run.grading?.hallucinationRate ?? null),
94
+ ]
95
+ : [];
96
+ const aggregateCells = aggregate === null
97
+ ? ['no completed trials', '–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
98
+ : [
99
+ 'completed',
100
+ aggregate.steps.toFixed(1),
101
+ aggregate.toolCalls.toFixed(1),
102
+ formatRate(aggregate.toolSuccessRate),
103
+ aggregate.invalidToolCalls.toFixed(1),
104
+ aggregate.retries.toFixed(1),
105
+ aggregate.totalTokens.toFixed(1),
106
+ formatUsd(aggregate.costUsd),
107
+ aggregate.latencyMs.toFixed(1),
108
+ formatRate(run.grading?.taskSuccessRate ?? null),
109
+ formatRate(run.grading?.toolSelectionAccuracyRate ?? null),
110
+ ];
111
+ const aggregateRow = `| aggregate | – | ${[...aggregateCells, ...aggregateJudgeCells].join(' | ')} |`;
112
+ return [
113
+ `# Eval: ${run.benchmark}`,
114
+ '',
115
+ `- model: ${run.model}`,
116
+ ...(judged ? [`- judge: ${judge.model}`] : []),
117
+ `- trials per case: ${run.trials}`,
118
+ `- created: ${new Date(run.createdAt).toISOString()}`,
119
+ `- traces: ${run.tempRoot}`,
120
+ '',
121
+ ...header,
122
+ ...rows,
123
+ aggregateRow,
124
+ '',
125
+ ].join('\n');
126
+ }
package/lib/runner.js ADDED
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Benchmark runner for dsh-eval: one fresh subprocess per case x trial.
3
+ *
4
+ * Each trial owns a private temp directory with a copied workspace, an
5
+ * isolated DSH_HOME, and a patch overlay that forces plain-JSONL persistence
6
+ * and non-interactive workspace-scoped permissions. The spawned command is
7
+ * the same trusted dsh harness (credentials flow through deliberately: the
8
+ * child must reach the real model API, and the session log never stores
9
+ * them), so the defensive scrubbed-env rule's leak concern does not apply to
10
+ * this child. Timeout kills the direct child and reports timed-out orthogonally
11
+ * from its exit code; Windows descendants of a killed process may survive.
12
+ *
13
+ * @module dsh-eval/runner
14
+ */
15
+ import { spawn } from 'node:child_process';
16
+ import { cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { tryJudgeTrial } from "./judge.js";
20
+ import { aggregateMetrics, computeMetrics } from "./metrics.js";
21
+ import { findSessionLogs, loadTrace, mergeTraces } from "./trace.js";
22
+ /** Cap per-stream child output so a runaway trial cannot exhaust memory. */
23
+ const MAX_OUTPUT_BYTES = 512 * 1024;
24
+ /** The child's trailing diagnostic for failed harvests. */
25
+ function diagnostic(outcome) {
26
+ const tail = outcome.stderr.slice(-2000);
27
+ const status = outcome.timedOut ? 'timed out' : `exited with code ${String(outcome.exitCode)}`;
28
+ return tail === '' ? `no session log found; dsh ${status}` : `no session log found; dsh ${status}: ${tail}`;
29
+ }
30
+ /** Human-readable error text. */
31
+ function message(error) {
32
+ /* v8 ignore next 3 -- every call site passes a node:fs or spawn Error; a non-Error rejection is impossible through the public API. */
33
+ return error instanceof Error ? error.message : String(error);
34
+ }
35
+ /** Reduce a case id to one safe temp-directory segment. */
36
+ function sanitizeSegment(value) {
37
+ const safe = value.replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '');
38
+ return safe === '' ? 'case' : safe;
39
+ }
40
+ /**
41
+ * Build the per-trial overlay: plain-JSONL persistence, non-interactive
42
+ * permissions, and the keyless replay plugin when recorded logs exist.
43
+ * @param replay - the replay primary log and child logs, or undefined.
44
+ * @returns the overlay YAML text.
45
+ */
46
+ function evalOverlay(replay) {
47
+ const lines = [
48
+ '- id: session-persistence-jsonl',
49
+ ' config:',
50
+ " root: !!js dshHomePath('sessions')",
51
+ ' packChunks: false',
52
+ ' compression: none',
53
+ '- id: sandbox-policy',
54
+ ' config:',
55
+ ' mode: workspace-write',
56
+ ' workspaceRoot: !!js process.cwd()',
57
+ '- id: approval',
58
+ ' config:',
59
+ ' policy: never',
60
+ ];
61
+ if (replay !== undefined) {
62
+ lines.push('- id: llm-replay', " name: '@deepseek-ai/dsh-llm-replay'", ' config:', ` file: ${JSON.stringify(replay.file)}`, ...(replay.childFiles.length === 0 ? [] : [` childFiles: ${JSON.stringify(replay.childFiles)}`]));
63
+ }
64
+ return `${lines.join('\n')}\n`;
65
+ }
66
+ /** Split a single command string into argv on whitespace. */
67
+ function splitWords(value) {
68
+ return value.trim().split(/\s+/u).filter(part => part !== '');
69
+ }
70
+ /**
71
+ * Grade one trial against its expectations: the expected tool is matched
72
+ * against recorded tool-call names, and the check command runs in the trial
73
+ * workspace with the same timeout as the agent. A spawn failure or timeout
74
+ * reads as task failure, never as an aborted run.
75
+ * @param caseValue - the case being graded.
76
+ * @param trace - the harvested trace.
77
+ * @param workspace - the trial's workspace, where the check runs.
78
+ * @param timeoutMs - check timeout, matching the trial timeout.
79
+ * @returns the grading outcome; unconfigured fields stay null.
80
+ */
81
+ async function gradeTrial(caseValue, trace, workspace, timeoutMs) {
82
+ const expected = caseValue.expected;
83
+ if (expected === undefined)
84
+ return { taskSuccess: null, toolSelectionAccuracy: null };
85
+ const expectedTool = expected.tool;
86
+ const toolSelectionAccuracy = expectedTool === undefined
87
+ ? null
88
+ : trace.events.some(event => event.type === 'tool/call' && event.data.name.includes(expectedTool));
89
+ let taskSuccess = null;
90
+ if (expected.check !== undefined) {
91
+ try {
92
+ const outcome = await runCommand(splitWords(expected.check), [], workspace, { ...process.env }, timeoutMs);
93
+ taskSuccess = !outcome.timedOut && outcome.exitCode === 0;
94
+ }
95
+ catch {
96
+ taskSuccess = false;
97
+ }
98
+ }
99
+ return { taskSuccess, toolSelectionAccuracy };
100
+ }
101
+ /** Pool one nullable boolean across graded trials into a rate, or null. */
102
+ function pooledRate(items, select) {
103
+ const values = items
104
+ .map(result => select(result.grade))
105
+ .filter((value) => value !== null);
106
+ return values.length === 0 ? null : values.filter(value => value).length / values.length;
107
+ }
108
+ /** Reduce completed trials' grades into pooled run-level rates. */
109
+ function gradingOf(results) {
110
+ const taskSuccessRate = pooledRate(results, grade => grade?.taskSuccess ?? null);
111
+ const toolSelectionAccuracyRate = pooledRate(results, grade => grade?.toolSelectionAccuracy ?? null);
112
+ const finalScores = results
113
+ .map(result => result.judge?.finalAnswerScore ?? null)
114
+ .filter((value) => value !== null);
115
+ const finalAnswerScore = finalScores.length === 0
116
+ ? null
117
+ : finalScores.reduce((total, value) => total + value, 0) / finalScores.length;
118
+ const hallucinated = results
119
+ .map(result => result.judge?.hallucination ?? null)
120
+ .filter((value) => value !== null);
121
+ const hallucinationRate = hallucinated.length === 0
122
+ ? null
123
+ : hallucinated.filter(value => value).length / hallucinated.length;
124
+ return taskSuccessRate === null && toolSelectionAccuracyRate === null
125
+ && finalAnswerScore === null && hallucinationRate === null
126
+ ? null
127
+ : { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate };
128
+ }
129
+ /**
130
+ * Spawn one command and collect its output, enforcing the timeout with a
131
+ * direct kill. The four outcome facts (exit code, timeout, stdout, stderr)
132
+ * are reported independently so a trapped or killed child cannot read as a
133
+ * clean success.
134
+ * @param command - the executable and its fixed argv.
135
+ * @param args - invocation args appended after `command`.
136
+ * @param cwd - the child's working directory.
137
+ * @param env - the child's environment.
138
+ * @param timeoutMs - kill the child after this many milliseconds.
139
+ * @returns the orthogonal outcome facts.
140
+ */
141
+ function runCommand(command, args, cwd, env, timeoutMs) {
142
+ const executable = command[0];
143
+ if (executable === undefined) {
144
+ return Promise.reject(new Error('eval: dsh command must not be empty'));
145
+ }
146
+ return new Promise((resolveOutcome, reject) => {
147
+ const child = spawn(executable, [...command.slice(1), ...args], {
148
+ cwd,
149
+ env,
150
+ stdio: ['ignore', 'pipe', 'pipe'],
151
+ windowsHide: true,
152
+ });
153
+ let stdout = '';
154
+ let stderr = '';
155
+ let timedOut = false;
156
+ let settled = false;
157
+ const cap = (current, chunk) => (current.length >= MAX_OUTPUT_BYTES
158
+ ? current
159
+ : current + chunk.toString('utf8').slice(0, MAX_OUTPUT_BYTES - current.length));
160
+ child.stdout.on('data', (chunk) => { stdout = cap(stdout, chunk); });
161
+ child.stderr.on('data', (chunk) => { stderr = cap(stderr, chunk); });
162
+ const timer = setTimeout(() => {
163
+ /* v8 ignore next 3 -- close clears the timer; only a same-tick close/kill race reaches here. */
164
+ if (settled)
165
+ return;
166
+ timedOut = true;
167
+ child.kill();
168
+ }, timeoutMs);
169
+ child.on('error', (error) => {
170
+ clearTimeout(timer);
171
+ /* v8 ignore next 3 -- spawn emits one error before close; the guard covers only an impossible duplicate error event. */
172
+ if (settled)
173
+ return;
174
+ settled = true;
175
+ reject(error);
176
+ });
177
+ child.on('close', (code) => {
178
+ clearTimeout(timer);
179
+ if (settled)
180
+ return;
181
+ settled = true;
182
+ resolveOutcome({ exitCode: code, timedOut, stdout, stderr });
183
+ });
184
+ });
185
+ }
186
+ /**
187
+ * Run one case x trial in its private temp directory and harvest its trace.
188
+ * @param benchmark - the loaded benchmark.
189
+ * @param caseValue - the case to run.
190
+ * @param trial - 1-based trial index.
191
+ * @param root - this run's temp root.
192
+ * @returns the trial result; a failed subprocess with no log is an `error` trial.
193
+ */
194
+ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
195
+ const trialDir = join(root, `${sanitizeSegment(caseValue.id)}-${trial}`);
196
+ const workspace = join(trialDir, 'workspace');
197
+ const dshHome = join(trialDir, 'dsh-home');
198
+ await mkdir(workspace, { recursive: true });
199
+ await mkdir(dshHome, { recursive: true, mode: 0o700 });
200
+ if (caseValue.workspace !== undefined)
201
+ await cp(caseValue.workspace, workspace, { recursive: true });
202
+ const replayFixture = benchmark.replay === undefined
203
+ ? undefined
204
+ : join(benchmark.replay.dir, `${sanitizeSegment(caseValue.id)}-${trial}`);
205
+ let replay;
206
+ if (replayFixture !== undefined) {
207
+ const logs = await findSessionLogs(replayFixture);
208
+ if (logs.length === 0) {
209
+ return {
210
+ caseId: caseValue.id,
211
+ trial,
212
+ status: 'error',
213
+ error: `no replay fixture found at ${replayFixture}`,
214
+ exitCode: null,
215
+ timedOut: false,
216
+ };
217
+ }
218
+ const primary = logs[0];
219
+ replay = { file: primary, childFiles: logs.slice(1) };
220
+ }
221
+ const overlayPath = join(trialDir, 'eval.cordis.yml');
222
+ await writeFile(overlayPath, evalOverlay(replay), 'utf8');
223
+ let outcome;
224
+ try {
225
+ outcome = await runCommand(benchmark.command, ['--profile', benchmark.profile, '--patch', overlayPath, caseValue.prompt], workspace, { ...process.env, DSH_HOME: dshHome }, benchmark.timeoutMs);
226
+ }
227
+ catch (error) {
228
+ return {
229
+ caseId: caseValue.id,
230
+ trial,
231
+ status: 'error',
232
+ error: `failed to spawn dsh: ${message(error)}`,
233
+ exitCode: null,
234
+ timedOut: false,
235
+ };
236
+ }
237
+ const tracePaths = await findSessionLogs(dshHome);
238
+ if (tracePaths.length === 0) {
239
+ return {
240
+ caseId: caseValue.id,
241
+ trial,
242
+ status: 'error',
243
+ error: diagnostic(outcome),
244
+ exitCode: outcome.exitCode,
245
+ timedOut: outcome.timedOut,
246
+ };
247
+ }
248
+ try {
249
+ const loaded = [];
250
+ for (const path of tracePaths)
251
+ loaded.push({ path, trace: await loadTrace(path) });
252
+ loaded.sort((a, b) => a.trace.createdAt - b.trace.createdAt);
253
+ // tracePaths.length > 0 above guarantees a non-empty loaded list.
254
+ const primaryPath = loaded[0].path;
255
+ const trace = mergeTraces(loaded.map(entry => entry.trace));
256
+ const pricing = benchmark.pricing?.[benchmark.model];
257
+ const metrics = computeMetrics(trace.events, pricing);
258
+ const grade = await gradeTrial(caseValue, trace, workspace, benchmark.timeoutMs);
259
+ const judge = benchmark.judge === undefined || judgeChat === undefined
260
+ ? undefined
261
+ : await tryJudgeTrial(caseValue, trace, benchmark.judge, judgeChat);
262
+ return {
263
+ caseId: caseValue.id,
264
+ trial,
265
+ status: 'completed',
266
+ tracePath: primaryPath,
267
+ tracePaths: loaded.map(entry => entry.path),
268
+ exitCode: outcome.exitCode,
269
+ timedOut: outcome.timedOut,
270
+ metrics,
271
+ ...(grade.taskSuccess !== null || grade.toolSelectionAccuracy !== null ? { grade } : {}),
272
+ ...(judge !== undefined ? { judge } : {}),
273
+ };
274
+ }
275
+ catch (error) {
276
+ return {
277
+ caseId: caseValue.id,
278
+ trial,
279
+ status: 'error',
280
+ error: `failed to read trace: ${message(error)}`,
281
+ exitCode: outcome.exitCode,
282
+ timedOut: outcome.timedOut,
283
+ };
284
+ }
285
+ }
286
+ /**
287
+ * Run every case x trial through a bounded worker pool and aggregate the
288
+ * completed trials.
289
+ *
290
+ * Trials are independent by construction — each owns a private temp directory,
291
+ * workspace copy, and DSH_HOME — so the only thing serial execution buys is
292
+ * determinism. The pool keeps that anyway: results land at their task index, so
293
+ * the run record stays in case-then-trial order no matter how the workers
294
+ * interleave. The first failure to escape `runCaseTrial` stops the remaining
295
+ * workers and rejects the run, which is the same contract as the serial loop.
296
+ *
297
+ * @param benchmark - the loaded benchmark.
298
+ * @param options - runtime overrides and test seams.
299
+ * @returns the completed run record, written by the caller.
300
+ */
301
+ export async function runBenchmark(benchmark, options = {}) {
302
+ if (benchmark.judge !== undefined && options.judgeChat === undefined) {
303
+ throw new Error('eval: benchmark configures a judge but no LLM chat seam is available');
304
+ }
305
+ if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
306
+ throw new Error('eval: judge and replay cannot be combined in one run');
307
+ }
308
+ const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'));
309
+ const trials = options.trials ?? benchmark.trials;
310
+ const effective = {
311
+ ...benchmark,
312
+ ...(options.profile !== undefined ? { profile: options.profile } : {}),
313
+ ...(options.command !== undefined ? { command: options.command } : {}),
314
+ ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),
315
+ };
316
+ const tasks = [];
317
+ for (const caseValue of effective.cases) {
318
+ for (let trial = 1; trial <= trials; trial++)
319
+ tasks.push({ caseValue, trial });
320
+ }
321
+ const results = Array.from({ length: tasks.length });
322
+ let failure;
323
+ let cursor = 0;
324
+ const worker = async () => {
325
+ while (failure === undefined) {
326
+ const index = cursor++;
327
+ const task = tasks[index];
328
+ if (task === undefined)
329
+ return;
330
+ try {
331
+ results[index] = await runCaseTrial(effective, task.caseValue, task.trial, root, options.judgeChat);
332
+ }
333
+ catch (error) {
334
+ failure = { error };
335
+ }
336
+ }
337
+ };
338
+ await Promise.all(Array.from({ length: Math.min(effective.concurrency, tasks.length) }, worker));
339
+ if (failure !== undefined)
340
+ throw failure.error;
341
+ const completed = results.filter((result) => result.status === 'completed' && result.metrics !== undefined);
342
+ return {
343
+ benchmark: benchmark.name,
344
+ model: benchmark.model,
345
+ createdAt: Date.now(),
346
+ trials,
347
+ seed: benchmark.seed,
348
+ pricing: benchmark.pricing?.[benchmark.model] ?? null,
349
+ ...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
350
+ tempRoot: root,
351
+ cases: results,
352
+ aggregate: aggregateMetrics(completed.map(result => result.metrics)),
353
+ grading: gradingOf(completed),
354
+ };
355
+ }
package/lib/stats.js ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Paired-comparison statistics for cross-run reports: an exact two-sided sign
3
+ * test over paired outcomes, and a seeded bootstrap confidence interval for a
4
+ * paired mean delta.
5
+ *
6
+ * Both are distribution-free on purpose. A benchmark run yields few paired
7
+ * trials (single digits to low tens), the per-trial deltas are integers with
8
+ * long tails, and the question is "on the same case, did B beat A" — which a
9
+ * paired sign test answers exactly, without a normality or symmetry assumption
10
+ * the data cannot support. Ties carry no sign and drop out of the test, as the
11
+ * sign test requires.
12
+ *
13
+ * The bootstrap resamples the observed deltas with replacement, so its interval
14
+ * needs no shape assumption either, and it is seeded so that re-running
15
+ * `compare` on the same reports prints a byte-identical table.
16
+ *
17
+ * @module dsh-eval/stats
18
+ */
19
+ /**
20
+ * Log of the binomial coefficient, accumulated rather than factorized so large
21
+ * pair counts stay finite.
22
+ * @param n - trials.
23
+ * @param k - successes, at most n.
24
+ * @returns `ln C(n, k)`.
25
+ */
26
+ function logChoose(n, k) {
27
+ let value = 0;
28
+ for (let index = 0; index < k; index++) {
29
+ value += Math.log(n - index) - Math.log(index + 1);
30
+ }
31
+ return value;
32
+ }
33
+ /**
34
+ * Exact two-sided sign test. Under the null hypothesis a discordant pair is a
35
+ * win or a loss with equal probability, so the win count is Binomial(n, 1/2)
36
+ * and the p-value doubles the smaller tail.
37
+ * @param wins - pairs where B beat A.
38
+ * @param losses - pairs where A beat B.
39
+ * @returns the discordant count and the exact p-value in `[0, 1]`.
40
+ */
41
+ export function signTest(wins, losses) {
42
+ const discordant = wins + losses;
43
+ if (discordant === 0)
44
+ return { discordant, pValue: 1 };
45
+ const tail = Math.min(wins, losses);
46
+ const halfPow = discordant * Math.log(2);
47
+ let cumulative = 0;
48
+ for (let index = 0; index <= tail; index++) {
49
+ cumulative += Math.exp(logChoose(discordant, index) - halfPow);
50
+ }
51
+ return { discordant, pValue: Math.min(1, 2 * cumulative) };
52
+ }
53
+ /**
54
+ * Small deterministic PRNG (mulberry32): identical seeds must produce identical
55
+ * intervals, otherwise `compare` output would drift between runs.
56
+ * @param seed - any integer.
57
+ * @returns a generator of floats in `[0, 1)`.
58
+ */
59
+ function prng(seed) {
60
+ let state = seed >>> 0;
61
+ return () => {
62
+ state = (state + 0x6d2b79f5) >>> 0;
63
+ let value = state;
64
+ value = Math.imul(value ^ (value >>> 15), value | 1);
65
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
66
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
67
+ };
68
+ }
69
+ /**
70
+ * Percentile of a sorted sample, linearly interpolated between neighbours.
71
+ * @param sorted - ascending values, non-empty.
72
+ * @param q - quantile in `[0, 1]`.
73
+ * @returns the interpolated value.
74
+ */
75
+ function quantile(sorted, q) {
76
+ const position = (sorted.length - 1) * q;
77
+ const low = Math.floor(position);
78
+ const weight = position - low;
79
+ return sorted[low] * (1 - weight) + sorted[Math.ceil(position)] * weight;
80
+ }
81
+ /**
82
+ * Mean paired delta with a percentile bootstrap interval.
83
+ * @param deltas - per-pair differences (`b - a`).
84
+ * @param options - confidence, resample count, and PRNG seed.
85
+ * @returns the mean and interval, or null when `deltas` is empty.
86
+ */
87
+ export function pairedDelta(deltas, options = {}) {
88
+ if (deltas.length === 0)
89
+ return null;
90
+ const mean = deltas.reduce((total, value) => total + value, 0) / deltas.length;
91
+ if (deltas.length === 1)
92
+ return { mean, lower: null, upper: null, pairs: 1 };
93
+ const confidence = options.confidence ?? 0.95;
94
+ const resamples = options.resamples ?? 2000;
95
+ const random = prng(options.seed ?? 0);
96
+ const means = [];
97
+ for (let resample = 0; resample < resamples; resample++) {
98
+ let total = 0;
99
+ for (let draw = 0; draw < deltas.length; draw++) {
100
+ total += deltas[Math.floor(random() * deltas.length)];
101
+ }
102
+ means.push(total / deltas.length);
103
+ }
104
+ means.sort((a, b) => a - b);
105
+ const alpha = (1 - confidence) / 2;
106
+ return {
107
+ mean,
108
+ lower: quantile(means, alpha),
109
+ upper: quantile(means, 1 - alpha),
110
+ pairs: deltas.length,
111
+ };
112
+ }