dsh-eval 0.3.0 → 0.3.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.
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,326 @@
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 sequentially and aggregate the completed trials.
288
+ * @param benchmark - the loaded benchmark.
289
+ * @param options - runtime overrides and test seams.
290
+ * @returns the completed run record, written by the caller.
291
+ */
292
+ export async function runBenchmark(benchmark, options = {}) {
293
+ if (benchmark.judge !== undefined && options.judgeChat === undefined) {
294
+ throw new Error('eval: benchmark configures a judge but no LLM chat seam is available');
295
+ }
296
+ if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
297
+ throw new Error('eval: judge and replay cannot be combined in one run');
298
+ }
299
+ const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'));
300
+ const trials = options.trials ?? benchmark.trials;
301
+ const effective = {
302
+ ...benchmark,
303
+ ...(options.profile !== undefined ? { profile: options.profile } : {}),
304
+ ...(options.command !== undefined ? { command: options.command } : {}),
305
+ };
306
+ const results = [];
307
+ for (const caseValue of effective.cases) {
308
+ for (let trial = 1; trial <= trials; trial++) {
309
+ results.push(await runCaseTrial(effective, caseValue, trial, root, options.judgeChat));
310
+ }
311
+ }
312
+ const completed = results.filter((result) => result.status === 'completed' && result.metrics !== undefined);
313
+ return {
314
+ benchmark: benchmark.name,
315
+ model: benchmark.model,
316
+ createdAt: Date.now(),
317
+ trials,
318
+ seed: benchmark.seed,
319
+ pricing: benchmark.pricing?.[benchmark.model] ?? null,
320
+ ...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
321
+ tempRoot: root,
322
+ cases: results,
323
+ aggregate: aggregateMetrics(completed.map(result => result.metrics)),
324
+ grading: gradingOf(completed),
325
+ };
326
+ }
package/lib/trace.js ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Session-log harvesting and parsing for dsh-eval. A trial's headless dsh
3
+ * writes a plain-JSONL session log under its DSH_HOME; the importer reads the
4
+ * header line, decodes every event row (packed chunk rows included) through
5
+ * the session package's storage decoder, and enforces seq continuity.
6
+ *
7
+ * @module dsh-eval/trace
8
+ */
9
+ import { readFile, readdir, stat } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { decodeStorageRecord, SessionId } from '@deepseek-ai/dsh-session';
12
+ import { z } from 'zod';
13
+ const headerSchema = z.object({
14
+ type: z.literal('session'),
15
+ id: z.string().min(1),
16
+ createdAt: z.number().nonnegative(),
17
+ }).loose();
18
+ /**
19
+ * Parse a plain-JSONL session log into a trace.
20
+ * @param text - the log file's UTF-8 text, header line first.
21
+ * @returns the parsed trace.
22
+ * @throws when the header is missing or malformed, a row is not valid JSON,
23
+ * or event seqs are not contiguous.
24
+ */
25
+ export function parseSessionLog(text) {
26
+ const lines = text.split(/\r?\n/u).filter(line => line.trim() !== '');
27
+ if (lines.length === 0)
28
+ throw new Error('empty session log');
29
+ const header = headerSchema.parse(JSON.parse(lines[0]));
30
+ const events = [];
31
+ for (let index = 1; index < lines.length; index++) {
32
+ const line = lines[index];
33
+ let record;
34
+ try {
35
+ record = JSON.parse(line);
36
+ }
37
+ catch {
38
+ throw new Error(`corrupt session log: invalid JSON at line ${index + 1}`);
39
+ }
40
+ for (const event of decodeStorageRecord(record)) {
41
+ if (event.seq !== events.length) {
42
+ throw new Error(`corrupt session log: seq gap at line ${index + 1} (expected ${events.length}, got ${event.seq})`);
43
+ }
44
+ events.push(event);
45
+ }
46
+ }
47
+ return {
48
+ sessionId: SessionId(header.id),
49
+ createdAt: header.createdAt,
50
+ events,
51
+ };
52
+ }
53
+ /**
54
+ * Load and parse the primary session log at a path.
55
+ * @param path - absolute path to a `session.jsonl` file.
56
+ * @returns the parsed trace.
57
+ */
58
+ export async function loadTrace(path) {
59
+ return parseSessionLog(await readFile(path, 'utf8'));
60
+ }
61
+ /**
62
+ * Find the newest primary `session.jsonl` under a DSH_HOME tree, descending
63
+ * into directories without following symlinks.
64
+ * @param root - the DSH_HOME directory to scan.
65
+ * @returns the newest primary log's absolute path, or null when none exists.
66
+ */
67
+ export async function findPrimarySessionLog(root) {
68
+ let entries;
69
+ try {
70
+ entries = await readdir(root, { withFileTypes: true });
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ let best = null;
76
+ for (const entry of entries) {
77
+ if (entry.isDirectory()) {
78
+ const found = await findPrimarySessionLog(join(root, entry.name));
79
+ if (found !== null) {
80
+ const mtime = (await stat(found)).mtimeMs;
81
+ if (best === null || mtime > best.mtime)
82
+ best = { path: found, mtime };
83
+ }
84
+ }
85
+ else if (entry.isFile() && entry.name === 'session.jsonl') {
86
+ const mtime = (await stat(join(root, entry.name))).mtimeMs;
87
+ if (best === null || mtime > best.mtime)
88
+ best = { path: join(root, entry.name), mtime };
89
+ }
90
+ }
91
+ return best?.path ?? null;
92
+ }
93
+ /**
94
+ * Find every `session.jsonl` under a DSH_HOME tree, sorted by modification
95
+ * time ascending so the parent session (started first) comes first.
96
+ * @param root - the DSH_HOME directory to scan.
97
+ * @returns absolute log paths in ascending mtime order.
98
+ */
99
+ export async function findSessionLogs(root) {
100
+ let entries;
101
+ try {
102
+ entries = await readdir(root, { withFileTypes: true });
103
+ }
104
+ catch {
105
+ return [];
106
+ }
107
+ const found = [];
108
+ for (const entry of entries) {
109
+ if (entry.isDirectory()) {
110
+ for (const nested of await findSessionLogs(join(root, entry.name))) {
111
+ found.push({ path: nested, mtime: (await stat(nested)).mtimeMs });
112
+ }
113
+ }
114
+ else if (entry.isFile() && entry.name === 'session.jsonl') {
115
+ found.push({ path: join(root, entry.name), mtime: (await stat(join(root, entry.name))).mtimeMs });
116
+ }
117
+ }
118
+ return found.sort((a, b) => a.mtime - b.mtime).map(entry => entry.path);
119
+ }
120
+ /**
121
+ * Merge traces into one timeline: events from every trace sorted by event
122
+ * time, ties broken by source order. The primary trace's header (session id
123
+ * and creation time) labels the merged trace.
124
+ * @param traces - harvested traces, primary first.
125
+ * @returns the merged trace.
126
+ */
127
+ export function mergeTraces(traces) {
128
+ const primary = traces[0];
129
+ if (primary === undefined)
130
+ throw new Error('mergeTraces requires at least one trace');
131
+ const events = traces
132
+ .flatMap((trace, source) => trace.events.map(event => ({ event, source })))
133
+ .sort((a, b) => a.event.time - b.event.time || a.source - b.source)
134
+ .map(entry => entry.event);
135
+ return { sessionId: primary.sessionId, createdAt: primary.createdAt, events };
136
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh-eval 鈥?agent evaluation over headless dsh profiles.
2
+ * dsh-eval — agent evaluation over headless dsh profiles.
3
3
  *
4
4
  * The eval bundle mounts this command-line plugin over dsh-base. It parses
5
5
  * `dsh --profile eval run <benchmark.yaml>` / `report <run.json>`, spawns one
package/lib/types.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Pure types of the dsh-eval domain: benchmark configuration, harvested
3
+ * traces, per-trial metrics, and the persisted run record. This file contains
4
+ * no runtime code.
5
+ *
6
+ * @module dsh-eval/types
7
+ */
8
+ export {};