dsh-eval 0.1.0-rc.6 → 0.2.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/README.md CHANGED
@@ -55,21 +55,52 @@ pricing:
55
55
  | `cases[].expected` | absent | Scripted grading: `tool` is a substring matched against recorded tool-call names; `check` is a command run in the trial workspace after the agent exits (exit 0 = task success). At least one is required when present. |
56
56
  | `pricing` | absent | Per-million-token USD prices keyed by model id; absent models report `costUsd: null`. |
57
57
 
58
+ ### Judge
59
+
60
+ `judge` enables LLM-judge scoring of final answers and hallucination:
61
+
62
+ ```yaml
63
+ judge:
64
+ provider: deepseek
65
+ model: deepseek-v4
66
+ rubric: Prefer correct, concise fixes.
67
+ maxScore: 10
68
+ ```
69
+
70
+ | Field | Default | Meaning |
71
+ |---|---|---|
72
+ | `provider` | `deepseek` | LLM provider route for the judge call. |
73
+ | `model` | benchmark `model` | Judge model id. |
74
+ | `rubric` | absent | Task rubric appended to the judging prompt. |
75
+ | `maxScore` | `10` | Maximum final-answer score. |
76
+
77
+ The judge builds a strict-JSON prompt from the case and the merged trace. A
78
+ trial carries its verdict (`finalAnswerScore`, `hallucination`, `rationale`)
79
+ when the reply parses; unusable output or a chat failure reads as null verdict
80
+ fields, never as a failed trial. A run with a configured judge fails before
81
+ starting when the host exposes no LLM chat seam.
82
+
58
83
  ## Metrics
59
84
 
60
85
  The metric fold computes the automatic metrics directly from the session log: `turns`, `steps`, `toolCalls`, `toolResults`, `toolSuccess` plus `toolSuccessRate`, `invalidToolCalls` (results carrying an internal failure identity), `retries` (`llm/retry`), disjoint token buckets and totals, billed context tokens, `llmMs`/`toolMs`/`ttftMs`/`latencyMs`, and `costUsd` when pricing is configured. Scripted grading adds per-trial `taskSuccess` (check-command exit 0) and `toolSelectionAccuracy` (expected-tool match) and pools them into run-level rates. LLM-judge metrics (final-answer score, hallucination) are deferred.
61
86
 
87
+ Child session logs under the trial's DSH_HOME are merged into the trial trace
88
+ before the fold, so delegated subagent work counts toward steps, tokens, tool
89
+ calls, retries, and latency. LLM-judge verdicts add per-trial
90
+ `finalAnswerScore` and `hallucination` and pool into run-level mean score and
91
+ hallucination rate.
92
+
62
93
  ## Run report
63
94
 
64
95
  `dsh eval run --out run.json` writes one JSON document per run: benchmark and model identity, per-trial outcomes with absolute trace paths, aggregate metrics (means for counts and wall times, pooled success rate), and pooled grading rates. `dsh eval report run.json` renders the run as markdown. Trial workspaces and traces stay under the run's `tempRoot` (a private temp directory) and are not deleted; remove them when the run is no longer needed.
65
96
 
66
97
  ## Comparison
67
98
 
68
- `dsh eval compare run-v1.json run-v2.json` renders both runs as a markdown table: benchmark/model identity, completed trials, steps, tool/task/tool-selection rates, invalid calls, retries, tokens, cost, and latency, with signed `B - A` deltas. Comparison is read-only over persisted runs; paired same-seed trials remain deferred.
99
+ `dsh eval compare run-v1.json run-v2.json` renders both runs as a markdown table: benchmark/model identity, completed trials, steps, tool/task/tool-selection rates, invalid calls, retries, tokens, cost, and latency, with signed `B - A` deltas. When both runs complete the same case x trial keys, the table appends paired statistics: trial count, win/lose/tie on the first available metric (task success, tool selection accuracy, or final-answer score), and mean `B - A` deltas for steps, tokens, and judge score. The runs' `seed` is recorded provenance for the pairing, not a guarantee of identical model output.
69
100
 
70
101
  ## Extension points
71
102
 
72
- The runner is the only consumer today: `runBenchmark` takes a loaded benchmark and returns the run record, and the report module persists and renders it. Grader and comparison seams are deliberately deferred until a second consumer exists.
103
+ The runner is the only consumer today: `runBenchmark` takes a loaded benchmark and returns the run record, and the report module persists and renders it. The judge chat seam is injected by the host (a dsh-llm stream) and stubbed in tests, keeping the suite keyless.
73
104
 
74
105
  ## Model Experience
75
106
 
@@ -81,9 +112,8 @@ None; this package neither assembles nor sends a provider request, so no request
81
112
 
82
113
  ## Known Limitations and Deferred Work
83
114
 
84
- - **LLM-judge metrics are deferred** — final-answer score and hallucination need an LLM judge provider; scripted task success and tool-selection accuracy are implemented.
85
- - **Paired comparison is deferred** — `dsh eval compare` compares persisted runs as-is; `seed` is validated but not yet used for deterministic paired trials, and per-arm leaderboards are not rendered.
86
- - **Primary session only** — child subagent logs under `session.<n>.jsonl` are not harvested; aggregate numbers omit delegated work.
115
+ - **Judge output is best-effort** — a judge chat failure or unparsable reply yields null verdict fields, and judge calls consume model quota outside the trial's measured cost.
116
+ - **Paired comparison pairs as-is** — trials pair by case id and trial index; `seed` is recorded provenance, not a deterministic guarantee of identical model output, and per-arm leaderboards are not rendered.
87
117
  - **Replay mode is deferred** — real runs need the model credentials the spawned harness resolves; llm-replay wiring for keyless CI is a later step.
88
118
  - **Direct-child timeout only** — a timed-out trial kills the direct dsh process; on Windows its descendants may survive.
89
119
  - **Windows launcher commands** — the spawned command runs without a shell, so `.cmd`/`.bat` shims need a direct executable or `node <path>` override (`--dsh "node C:/.../apps/cli/lib/bin.js"`).
package/lib/index.js CHANGED
@@ -14,6 +14,7 @@
14
14
  import { loadBenchmark } from "./benchmark.js";
15
15
  import { applyEval } from "./command.js";
16
16
  import { compareRuns, renderCompareMarkdown } from "./compare.js";
17
+ import { llmJudgeChat } from "./judge.js";
17
18
  import { renderMarkdownReport, writeRunReport, loadRunReport } from "./report.js";
18
19
  import { runBenchmark } from "./runner.js";
19
20
  /** Stable Cordis plugin name. */
@@ -25,6 +26,16 @@ export const internals = {
25
26
  stdout: process.stdout,
26
27
  stderr: process.stderr,
27
28
  };
29
+ /**
30
+ * Resolve the production judge chat seam from the mounted llm service, or
31
+ * undefined when the composition carries no llm service.
32
+ * @param ctx - the plugin context.
33
+ * @returns a chat seam over the llm stream, or undefined without llm.
34
+ */
35
+ export function resolveJudgeChat(ctx) {
36
+ const llm = ctx.get('llm');
37
+ return llm === undefined ? undefined : llmJudgeChat(llm.stream);
38
+ }
28
39
  /** Aggregate-success sentence for the run summary line. */
29
40
  function summary(run) {
30
41
  const aggregate = run.aggregate;
@@ -35,16 +46,21 @@ function summary(run) {
35
46
  const task = taskRate === null || taskRate === undefined
36
47
  ? ''
37
48
  : `, task success ${(taskRate * 100).toFixed(1)}%`;
38
- return `tool success ${rate}${task}, ${aggregate.steps.toFixed(1)} steps/trial`;
49
+ const judgeScore = run.grading?.finalAnswerScore;
50
+ const score = judgeScore === null || judgeScore === undefined
51
+ ? ''
52
+ : `, judge score ${judgeScore.toFixed(1)}`;
53
+ return `tool success ${rate}${task}${score}, ${aggregate.steps.toFixed(1)} steps/trial`;
39
54
  }
40
55
  /**
41
56
  * Execute one eval invocation to completion.
42
57
  * @param values - the resolved command-line invocation.
43
58
  * @param io - output streams for the report and diagnostics.
59
+ * @param services - injected runtime seams, e.g. the LLM-judge chat.
44
60
  * @returns the process exit code; nonzero for any failure or a run with no
45
61
  * completed trials.
46
62
  */
47
- export async function executeEval(values, io) {
63
+ export async function executeEval(values, io, services = {}) {
48
64
  try {
49
65
  if (values.kind === 'report') {
50
66
  const run = await loadRunReport(values.runPath);
@@ -62,6 +78,7 @@ export async function executeEval(values, io) {
62
78
  ...(values.trials !== undefined ? { trials: values.trials } : {}),
63
79
  ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
64
80
  ...(values.profile !== undefined ? { profile: values.profile } : {}),
81
+ ...(services.judgeChat !== undefined ? { judgeChat: services.judgeChat } : {}),
65
82
  });
66
83
  await writeRunReport(run, values.outPath);
67
84
  io.stdout.write(`Wrote ${values.outPath} (${run.cases.length} trials, ${summary(run)})\n`);
@@ -81,8 +98,9 @@ export function apply(ctx) {
81
98
  const exit = ctx.get('appExit');
82
99
  if (exit === undefined)
83
100
  throw new Error('eval: the launcher must provide ctx.appExit before the tree mounts');
101
+ const judgeChat = resolveJudgeChat(ctx);
84
102
  const values = applyEval(ctx);
85
103
  if (values === undefined)
86
104
  return;
87
- void executeEval(values, internals).then((code) => { exit(code); });
105
+ void executeEval(values, internals, { judgeChat }).then((code) => { exit(code); });
88
106
  }
@@ -16,6 +16,34 @@ export interface CompareRow {
16
16
  /** Signed delta (`b - a`) for numeric rows, or a dash for text rows. */
17
17
  delta: string;
18
18
  }
19
+ /** Paired same-case statistics over two runs. */
20
+ export interface PairedStats {
21
+ /** Number of case x trial pairs completed in both runs. */
22
+ pairs: number;
23
+ /** Pairs where run B beat run A on the primary metric. */
24
+ wins: number;
25
+ /** Pairs where run A beat run B on the primary metric. */
26
+ losses: number;
27
+ /** Pairs with equal primary-metric outcomes. */
28
+ ties: number;
29
+ /** The metric used for win/lose/tie classification. */
30
+ primaryMetric: 'task success' | 'tool selection accuracy' | 'final answer score';
31
+ /** Mean per-pair step delta (`b - a`), or null when no pair is numeric. */
32
+ meanStepsDelta: number | null;
33
+ /** Mean per-pair token delta (`b - a`), or null when no pair is numeric. */
34
+ meanTokensDelta: number | null;
35
+ /** Mean per-pair judge score delta (`b - a`), or null without judge verdicts. */
36
+ meanScoreDelta: number | null;
37
+ }
38
+ /**
39
+ * Pair both runs' trials by case id and trial index and compute win/lose/tie
40
+ * plus mean deltas. Trials are paired as-is; the runs' `seed` is recorded
41
+ * provenance for the pairing, not a guarantee of identical model output.
42
+ * @param a - the baseline run.
43
+ * @param b - the candidate run.
44
+ * @returns paired statistics, or null when no trial is completed in both runs.
45
+ */
46
+ export declare function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null;
19
47
  /**
20
48
  * Build the comparison rows between two runs.
21
49
  * @param a - the baseline run.
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import type { Context } from '@deepseek-ai/cordis';
15
15
  import { type EvalStartupValues } from './command.ts';
16
+ import { type JudgeChat } from './judge.ts';
16
17
  /** Stable Cordis plugin name. */
17
18
  export declare const name = "eval";
18
19
  /** The launcher-provided command line is the only required service. */
@@ -28,14 +29,24 @@ export interface EvalIo {
28
29
  }
29
30
  /** The process streams the eval app writes to; tests substitute captures. */
30
31
  export declare const internals: EvalIo;
32
+ /**
33
+ * Resolve the production judge chat seam from the mounted llm service, or
34
+ * undefined when the composition carries no llm service.
35
+ * @param ctx - the plugin context.
36
+ * @returns a chat seam over the llm stream, or undefined without llm.
37
+ */
38
+ export declare function resolveJudgeChat(ctx: Context): JudgeChat | undefined;
31
39
  /**
32
40
  * Execute one eval invocation to completion.
33
41
  * @param values - the resolved command-line invocation.
34
42
  * @param io - output streams for the report and diagnostics.
43
+ * @param services - injected runtime seams, e.g. the LLM-judge chat.
35
44
  * @returns the process exit code; nonzero for any failure or a run with no
36
45
  * completed trials.
37
46
  */
38
- export declare function executeEval(values: EvalStartupValues, io: EvalIo): Promise<number>;
47
+ export declare function executeEval(values: EvalStartupValues, io: EvalIo, services?: {
48
+ judgeChat?: JudgeChat | undefined;
49
+ }): Promise<number>;
39
50
  /**
40
51
  * Mount the eval command-line app: parse the invocation, run it asynchronously,
41
52
  * and request launcher exit with the result code.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * LLM-judge scoring for dsh-eval: builds a judging prompt from the case and
3
+ * its trace, calls an injected chat seam, and parses the model's strict-JSON
4
+ * verdict into a final-answer score and hallucination flag. The production
5
+ * seam wraps the dsh-llm stream API; tests inject a fake so the suite stays
6
+ * keyless.
7
+ *
8
+ * @module dsh-eval/judge
9
+ */
10
+ import { type LlmRuntime } from '@deepseek-ai/dsh-llm';
11
+ import type { BenchmarkCase, BenchmarkJudge, EvalJudgeVerdict, EvalTrace } from './types.ts';
12
+ /** One judge chat call: system instructions plus the single task prompt. */
13
+ export interface JudgeChatRequest {
14
+ /** Provider route, e.g. `deepseek`. */
15
+ provider: string;
16
+ /** Judge model id. */
17
+ model: string;
18
+ /** System instructions demanding strict JSON output. */
19
+ system: string;
20
+ /** The task and trace summary to judge. */
21
+ prompt: string;
22
+ }
23
+ /** The injected chat seam; returns the model's raw text reply. */
24
+ export type JudgeChat = (request: JudgeChatRequest) => Promise<string>;
25
+ /**
26
+ * Summarize a trace for the judge: final assistant answer, the distinct tool
27
+ * names called, and the failure counters a hallucination call needs.
28
+ * @param trace - the merged trial trace.
29
+ * @returns a compact human-readable summary.
30
+ */
31
+ export declare function summarizeTrace(trace: EvalTrace): string;
32
+ /**
33
+ * Build the judge's system instructions and task prompt.
34
+ * @param caseValue - the benchmark case being judged.
35
+ * @param trace - the merged trial trace.
36
+ * @param judge - the judge configuration.
37
+ * @returns the system and prompt texts.
38
+ */
39
+ export declare function buildJudgePrompt(caseValue: BenchmarkCase, trace: EvalTrace, judge: BenchmarkJudge): {
40
+ system: string;
41
+ prompt: string;
42
+ };
43
+ /**
44
+ * Parse the judge model's strict-JSON reply into a verdict. Unusable output
45
+ * yields null fields, never a fabricated verdict.
46
+ * @param text - the raw model reply.
47
+ * @param maxScore - the configured maximum score.
48
+ * @returns the parsed verdict.
49
+ */
50
+ export declare function parseJudgeVerdict(text: string, maxScore: number): EvalJudgeVerdict;
51
+ /**
52
+ * Judge one trial through the chat seam.
53
+ * @param caseValue - the benchmark case being judged.
54
+ * @param trace - the merged trial trace.
55
+ * @param judge - the judge configuration.
56
+ * @param chat - the injected chat seam.
57
+ * @returns the parsed verdict; a chat failure rejects.
58
+ */
59
+ export declare function judgeTrial(caseValue: BenchmarkCase, trace: EvalTrace, judge: BenchmarkJudge, chat: JudgeChat): Promise<EvalJudgeVerdict>;
60
+ /**
61
+ * Judge one trial, converting a chat failure into an all-null verdict so a
62
+ * judge outage reads as unjudged rather than a failed trial.
63
+ * @param caseValue - the benchmark case being judged.
64
+ * @param trace - the merged trial trace.
65
+ * @param judge - the judge configuration.
66
+ * @param chat - the injected chat seam.
67
+ * @returns the parsed verdict, or all-null when the chat call threw.
68
+ */
69
+ export declare function tryJudgeTrial(caseValue: BenchmarkCase, trace: EvalTrace, judge: BenchmarkJudge, chat: JudgeChat): Promise<EvalJudgeVerdict>;
70
+ /**
71
+ * Build the production chat seam over a dsh-llm stream: one user turn, zero
72
+ * temperature, and text-block assembly of the reply.
73
+ * @param stream - the llm service's stream method.
74
+ * @returns a chat seam reading only text blocks from the stream.
75
+ */
76
+ export declare function llmJudgeChat(stream: LlmRuntime['stream']): JudgeChat;
@@ -13,6 +13,7 @@
13
13
  * @module dsh-eval/runner
14
14
  */
15
15
  import type { Benchmark, EvalRun } from './types.ts';
16
+ import { type JudgeChat } from './judge.ts';
16
17
  /** Runtime overrides applied to a loaded benchmark. */
17
18
  export interface RunOptions {
18
19
  /** Override the benchmark's dsh command argv. */
@@ -23,6 +24,8 @@ export interface RunOptions {
23
24
  trials?: number;
24
25
  /** Root for trial directories; defaults to the platform temp dir. */
25
26
  tempRoot?: string;
27
+ /** LLM-judge chat seam; required when the benchmark configures a judge. */
28
+ judgeChat?: JudgeChat;
26
29
  }
27
30
  /**
28
31
  * Run every case x trial sequentially and aggregate the completed trials.
@@ -28,3 +28,18 @@ export declare function loadTrace(path: string): Promise<EvalTrace>;
28
28
  * @returns the newest primary log's absolute path, or null when none exists.
29
29
  */
30
30
  export declare function findPrimarySessionLog(root: string): Promise<string | null>;
31
+ /**
32
+ * Find every `session.jsonl` under a DSH_HOME tree, sorted by modification
33
+ * time ascending so the parent session (started first) comes first.
34
+ * @param root - the DSH_HOME directory to scan.
35
+ * @returns absolute log paths in ascending mtime order.
36
+ */
37
+ export declare function findSessionLogs(root: string): Promise<string[]>;
38
+ /**
39
+ * Merge traces into one timeline: events from every trace sorted by event
40
+ * time, ties broken by source order. The primary trace's header (session id
41
+ * and creation time) labels the merged trace.
42
+ * @param traces - harvested traces, primary first.
43
+ * @returns the merged trace.
44
+ */
45
+ export declare function mergeTraces(traces: readonly EvalTrace[]): EvalTrace;
@@ -35,6 +35,17 @@ export interface BenchmarkExpectation {
35
35
  /** Command run in the trial workspace after the agent exits; exit 0 means task success. */
36
36
  check?: string;
37
37
  }
38
+ /** LLM-judge configuration: scores final answers and flags hallucinations. */
39
+ export interface BenchmarkJudge {
40
+ /** Provider route for the judge call, e.g. `deepseek`. */
41
+ provider: string;
42
+ /** Judge model id; defaults to the benchmark model when unset. */
43
+ model: string;
44
+ /** Optional task rubric appended to the default judging instructions. */
45
+ rubric?: string;
46
+ /** Maximum final-answer score; defaults to 10. */
47
+ maxScore: number;
48
+ }
38
49
  /** A validated benchmark document. */
39
50
  export interface Benchmark {
40
51
  /** Benchmark name; also the run record's `benchmark` field. */
@@ -55,6 +66,8 @@ export interface Benchmark {
55
66
  cases: readonly BenchmarkCase[];
56
67
  /** Pricing keyed by model id; an absent model reports `costUsd: null`. */
57
68
  pricing?: Readonly<Record<string, BenchmarkPricing>>;
69
+ /** LLM-judge configuration, when final-answer scoring is enabled. */
70
+ judge?: BenchmarkJudge;
58
71
  /** Directory the benchmark document was loaded from; relative paths resolve against it. */
59
72
  baseDir: string;
60
73
  }
@@ -129,6 +142,8 @@ export interface EvalTrialResult {
129
142
  error?: string;
130
143
  /** Absolute path of the harvested primary session log. */
131
144
  tracePath?: string;
145
+ /** Absolute paths of every harvested session log, primary first. */
146
+ tracePaths?: readonly string[];
132
147
  /** The child process's exit code, or null when it was killed. */
133
148
  exitCode: number | null;
134
149
  /** Whether the trial hit its timeout and killed the child. */
@@ -137,6 +152,8 @@ export interface EvalTrialResult {
137
152
  metrics?: EvalCaseMetrics;
138
153
  /** Scripted grading outcome for `completed` trials with expectations. */
139
154
  grade?: EvalGrade;
155
+ /** LLM-judge verdict for `completed` trials with a configured judge. */
156
+ judge?: EvalJudgeVerdict;
140
157
  }
141
158
  /** Scripted grading outcome for one trial. */
142
159
  export interface EvalGrade {
@@ -145,12 +162,25 @@ export interface EvalGrade {
145
162
  /** Whether an expected tool was called, or null when no tool is configured. */
146
163
  toolSelectionAccuracy: boolean | null;
147
164
  }
165
+ /** LLM-judge verdict for one trial. */
166
+ export interface EvalJudgeVerdict {
167
+ /** Final-answer score within the benchmark's `maxScore`, or null when the judge output was unusable. */
168
+ finalAnswerScore: number | null;
169
+ /** Whether the judge flagged hallucinated content, or null when the judge output was unusable. */
170
+ hallucination: boolean | null;
171
+ /** Judge rationale, when the model returned one. */
172
+ rationale?: string;
173
+ }
148
174
  /** Pooled grading rates over completed trials. */
149
175
  export interface EvalRunGrading {
150
176
  /** Pooled task-success rate, or null when no trial carried a check. */
151
177
  taskSuccessRate: number | null;
152
178
  /** Pooled tool-selection-accuracy rate, or null when no trial carried an expected tool. */
153
179
  toolSelectionAccuracyRate: number | null;
180
+ /** Mean final-answer score over judged trials, or null when nothing was judged. */
181
+ finalAnswerScore: number | null;
182
+ /** Pooled hallucination rate over judged trials, or null when nothing was judged. */
183
+ hallucinationRate: number | null;
154
184
  }
155
185
  /** A persisted eval run. */
156
186
  export interface EvalRun {
@@ -166,6 +196,8 @@ export interface EvalRun {
166
196
  seed: number;
167
197
  /** Resolved pricing for the benchmark model, or null without one. */
168
198
  pricing: BenchmarkPricing | null;
199
+ /** The judge configuration the run used, when one was configured. */
200
+ judge?: BenchmarkJudge;
169
201
  /** Root holding every trial's workspace, overlay, and harvested trace. */
170
202
  tempRoot: string;
171
203
  /** Per-trial outcomes in execution order. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-eval",
3
3
  "description": "Agent evaluation platform: benchmark YAML, headless run orchestration, trace-based metrics, and run reports",
4
- "version": "0.1.0-rc.6",
4
+ "version": "0.2.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -71,12 +71,12 @@
71
71
  "typescript": "^6.0.3",
72
72
  "vitest": "^4.1.8",
73
73
  "@deepseek-ai/cordis": "^4.0.1",
74
- "@deepseek-ai/cordis-plugin-include": "^1.0.6",
75
- "@deepseek-ai/cordis-plugin-loader": "^1.0.2",
76
74
  "@deepseek-ai/dsh-cmdline": "^0.1.0-rc.5",
77
- "@deepseek-ai/dsh-invariants": "^0.1.0-rc.5",
75
+ "@deepseek-ai/cordis-plugin-include": "^1.0.6",
78
76
  "@deepseek-ai/dsh-llm": "^0.1.0-rc.5",
79
77
  "@deepseek-ai/dsh-llm-retry": "^0.1.0-rc.5",
78
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.5",
79
+ "@deepseek-ai/cordis-plugin-loader": "^1.0.2",
80
80
  "@deepseek-ai/dsh-session": "^0.1.0-rc.5"
81
81
  },
82
82
  "scripts": {
package/src/benchmark.ts CHANGED
@@ -12,6 +12,13 @@ import { load } from 'js-yaml'
12
12
  import { z } from 'zod'
13
13
  import type { Benchmark, BenchmarkCase } from './types.ts'
14
14
 
15
+ const judgeSchema = z.object({
16
+ provider: z.string().min(1).default('deepseek'),
17
+ model: z.string().min(1).optional(),
18
+ rubric: z.string().min(1).optional(),
19
+ maxScore: z.number().int().positive().default(10),
20
+ }).strict()
21
+
15
22
  const pricingSchema = z.object({
16
23
  inputUsdPerMTokens: z.number().nonnegative(),
17
24
  cacheReadUsdPerMTokens: z.number().nonnegative(),
@@ -46,6 +53,7 @@ const benchmarkSchema = z.object({
46
53
  seed: z.number().int().default(0),
47
54
  cases: z.array(benchmarkCaseSchema).min(1),
48
55
  pricing: z.record(z.string().min(1), pricingSchema).optional(),
56
+ judge: judgeSchema.optional(),
49
57
  }).strict()
50
58
 
51
59
  /**
@@ -96,6 +104,7 @@ export async function parseBenchmark(text: string, baseDir: string): Promise<Ben
96
104
  cases.push(await resolveCase(caseValue, baseDir))
97
105
  }
98
106
  const pricing = parsed.pricing
107
+ const judge = parsed.judge
99
108
  return {
100
109
  name: parsed.name,
101
110
  model: parsed.model,
@@ -106,6 +115,9 @@ export async function parseBenchmark(text: string, baseDir: string): Promise<Ben
106
115
  seed: parsed.seed,
107
116
  cases,
108
117
  ...(pricing !== undefined ? { pricing } : {}),
118
+ ...(judge !== undefined
119
+ ? { judge: { provider: judge.provider, model: judge.model ?? parsed.model, ...(judge.rubric !== undefined ? { rubric: judge.rubric } : {}), maxScore: judge.maxScore } }
120
+ : {}),
109
121
  baseDir,
110
122
  }
111
123
  }
package/src/compare.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * @module dsh-eval/compare
6
6
  */
7
7
 
8
- import type { EvalRun } from './types.ts'
8
+ import type { EvalRun, EvalTrialResult } from './types.ts'
9
9
 
10
10
  /** One compared metric row. */
11
11
  export interface CompareRow {
@@ -19,6 +19,26 @@ export interface CompareRow {
19
19
  delta: string
20
20
  }
21
21
 
22
+ /** Paired same-case statistics over two runs. */
23
+ export interface PairedStats {
24
+ /** Number of case x trial pairs completed in both runs. */
25
+ pairs: number
26
+ /** Pairs where run B beat run A on the primary metric. */
27
+ wins: number
28
+ /** Pairs where run A beat run B on the primary metric. */
29
+ losses: number
30
+ /** Pairs with equal primary-metric outcomes. */
31
+ ties: number
32
+ /** The metric used for win/lose/tie classification. */
33
+ primaryMetric: 'task success' | 'tool selection accuracy' | 'final answer score'
34
+ /** Mean per-pair step delta (`b - a`), or null when no pair is numeric. */
35
+ meanStepsDelta: number | null
36
+ /** Mean per-pair token delta (`b - a`), or null when no pair is numeric. */
37
+ meanTokensDelta: number | null
38
+ /** Mean per-pair judge score delta (`b - a`), or null without judge verdicts. */
39
+ meanScoreDelta: number | null
40
+ }
41
+
22
42
  /** Render a nullable number with a dash placeholder. */
23
43
  function formatNumber(value: number | null, digits = 1): string {
24
44
  return value === null ? '–' : value.toFixed(digits)
@@ -36,6 +56,97 @@ function formatDelta(a: number | null, b: number | null, unit: 'pp' | '' = ''):
36
56
  return `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}${unit}`
37
57
  }
38
58
 
59
+ /** A metric that can classify a paired winner. */
60
+ type PairedMetric = 'task success' | 'tool selection accuracy' | 'final answer score'
61
+
62
+ /** Read one trial's primary-metric outcome, or null when the trial lacks it. */
63
+ function metricOutcome(result: EvalTrialResult, metric: PairedMetric): boolean | number | null {
64
+ if (metric === 'task success') return result.grade?.taskSuccess ?? null
65
+ if (metric === 'tool selection accuracy') return result.grade?.toolSelectionAccuracy ?? null
66
+ return result.judge?.finalAnswerScore ?? null
67
+ }
68
+
69
+ /** Pick the first metric with data in every paired trial of a run. */
70
+ function pickMetric(
71
+ pairs: readonly { a: EvalTrialResult; b: EvalTrialResult }[],
72
+ ): PairedMetric {
73
+ for (const metric of ['task success', 'tool selection accuracy', 'final answer score'] as const) {
74
+ if (pairs.every(pair => metricOutcome(pair.a, metric) !== null && metricOutcome(pair.b, metric) !== null)) {
75
+ return metric
76
+ }
77
+ }
78
+ return 'final answer score'
79
+ }
80
+
81
+ /** Classify one pair: 1 for a B win, -1 for an A win, 0 for a tie. */
82
+ function pairSign(aValue: boolean | number | null, bValue: boolean | number | null): number {
83
+ if (aValue === null || bValue === null) return 0
84
+ if (typeof aValue === 'boolean' || typeof bValue === 'boolean') {
85
+ const aBool = aValue === true
86
+ const bBool = bValue === true
87
+ return bBool === aBool ? 0 : (bBool ? 1 : -1)
88
+ }
89
+ return bValue > aValue ? 1 : (bValue < aValue ? -1 : 0)
90
+ }
91
+
92
+ /**
93
+ * Pair both runs' trials by case id and trial index and compute win/lose/tie
94
+ * plus mean deltas. Trials are paired as-is; the runs' `seed` is recorded
95
+ * provenance for the pairing, not a guarantee of identical model output.
96
+ * @param a - the baseline run.
97
+ * @param b - the candidate run.
98
+ * @returns paired statistics, or null when no trial is completed in both runs.
99
+ */
100
+ export function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null {
101
+ const byKey = new Map<string, EvalTrialResult>()
102
+ for (const result of b.cases) {
103
+ if (result.status === 'completed') byKey.set(`${result.caseId}\u0000${result.trial}`, result)
104
+ }
105
+ const pairs: { a: EvalTrialResult; b: EvalTrialResult }[] = []
106
+ for (const result of a.cases) {
107
+ if (result.status !== 'completed') continue
108
+ const match = byKey.get(`${result.caseId}\u0000${result.trial}`)
109
+ if (match !== undefined) pairs.push({ a: result, b: match })
110
+ }
111
+ if (pairs.length === 0) return null
112
+ const primaryMetric = pickMetric(pairs)
113
+ let wins = 0
114
+ let losses = 0
115
+ let ties = 0
116
+ const stepDeltas: number[] = []
117
+ const tokenDeltas: number[] = []
118
+ const scoreDeltas: number[] = []
119
+ for (const pair of pairs) {
120
+ const sign = pairSign(metricOutcome(pair.a, primaryMetric), metricOutcome(pair.b, primaryMetric))
121
+ if (sign > 0) wins += 1
122
+ else if (sign < 0) losses += 1
123
+ else ties += 1
124
+ const aMetrics = pair.a.metrics
125
+ const bMetrics = pair.b.metrics
126
+ if (aMetrics !== undefined && bMetrics !== undefined) {
127
+ stepDeltas.push(bMetrics.steps - aMetrics.steps)
128
+ tokenDeltas.push(bMetrics.totalTokens - aMetrics.totalTokens)
129
+ }
130
+ const aScore = pair.a.judge?.finalAnswerScore
131
+ const bScore = pair.b.judge?.finalAnswerScore
132
+ if (aScore !== null && aScore !== undefined && bScore !== null && bScore !== undefined) {
133
+ scoreDeltas.push(bScore - aScore)
134
+ }
135
+ }
136
+ const mean = (values: readonly number[]): number | null =>
137
+ values.length === 0 ? null : values.reduce((total, value) => total + value, 0) / values.length
138
+ return {
139
+ pairs: pairs.length,
140
+ wins,
141
+ losses,
142
+ ties,
143
+ primaryMetric,
144
+ meanStepsDelta: mean(stepDeltas),
145
+ meanTokensDelta: mean(tokenDeltas),
146
+ meanScoreDelta: mean(scoreDeltas),
147
+ }
148
+ }
149
+
39
150
  /** Pull one nullable numeric value from a run for comparison. */
40
151
  type RunSelector = (run: EvalRun) => number | null
41
152
 
@@ -58,7 +169,7 @@ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
58
169
  }
59
170
  }
60
171
  const numeric = (selector: RunSelector, label: string): CompareRow => rates(selector, label, '')
61
- return [
172
+ const rows: CompareRow[] = [
62
173
  { metric: 'benchmark', a: a.benchmark, b: b.benchmark, delta: '–' },
63
174
  { metric: 'model', a: a.model, b: b.model, delta: '–' },
64
175
  numeric(run => completed(run), 'completed trials'),
@@ -72,6 +183,28 @@ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
72
183
  numeric(run => run.aggregate?.costUsd ?? null, 'cost/trial (USD)'),
73
184
  numeric(run => run.aggregate?.latencyMs ?? null, 'latency/trial (ms)'),
74
185
  ]
186
+ const paired = pairedCompare(a, b)
187
+ if (paired !== null) {
188
+ rows.push(
189
+ { metric: 'paired trials', a: String(paired.pairs), b: String(paired.pairs), delta: '–' },
190
+ {
191
+ metric: `paired ${paired.primaryMetric} (B/A/ties)`,
192
+ a: `${paired.wins}/${paired.losses}/${paired.ties}`,
193
+ b: '–',
194
+ delta: '–',
195
+ },
196
+ ...(paired.meanStepsDelta === null ? [] : [{
197
+ metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanStepsDelta),
198
+ }]),
199
+ ...(paired.meanTokensDelta === null ? [] : [{
200
+ metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanTokensDelta),
201
+ }]),
202
+ ...(paired.meanScoreDelta === null ? [] : [{
203
+ metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanScoreDelta),
204
+ }]),
205
+ )
206
+ }
207
+ return rows
75
208
  }
76
209
 
77
210
  /**
package/src/index.ts CHANGED
@@ -16,6 +16,7 @@ import type { Context } from '@deepseek-ai/cordis'
16
16
  import { loadBenchmark } from './benchmark.ts'
17
17
  import { applyEval, type EvalStartupValues } from './command.ts'
18
18
  import { compareRuns, renderCompareMarkdown } from './compare.ts'
19
+ import { llmJudgeChat, type JudgeChat } from './judge.ts'
19
20
  import { renderMarkdownReport, writeRunReport, loadRunReport } from './report.ts'
20
21
  import { runBenchmark } from './runner.ts'
21
22
 
@@ -36,6 +37,17 @@ export const internals: EvalIo = {
36
37
  stderr: process.stderr,
37
38
  }
38
39
 
40
+ /**
41
+ * Resolve the production judge chat seam from the mounted llm service, or
42
+ * undefined when the composition carries no llm service.
43
+ * @param ctx - the plugin context.
44
+ * @returns a chat seam over the llm stream, or undefined without llm.
45
+ */
46
+ export function resolveJudgeChat(ctx: Context): JudgeChat | undefined {
47
+ const llm = ctx.get('llm')
48
+ return llm === undefined ? undefined : llmJudgeChat(llm.stream)
49
+ }
50
+
39
51
  /** Aggregate-success sentence for the run summary line. */
40
52
  function summary(run: Awaited<ReturnType<typeof runBenchmark>>): string {
41
53
  const aggregate = run.aggregate
@@ -45,17 +57,26 @@ function summary(run: Awaited<ReturnType<typeof runBenchmark>>): string {
45
57
  const task = taskRate === null || taskRate === undefined
46
58
  ? ''
47
59
  : `, task success ${(taskRate * 100).toFixed(1)}%`
48
- return `tool success ${rate}${task}, ${aggregate.steps.toFixed(1)} steps/trial`
60
+ const judgeScore = run.grading?.finalAnswerScore
61
+ const score = judgeScore === null || judgeScore === undefined
62
+ ? ''
63
+ : `, judge score ${judgeScore.toFixed(1)}`
64
+ return `tool success ${rate}${task}${score}, ${aggregate.steps.toFixed(1)} steps/trial`
49
65
  }
50
66
 
51
67
  /**
52
68
  * Execute one eval invocation to completion.
53
69
  * @param values - the resolved command-line invocation.
54
70
  * @param io - output streams for the report and diagnostics.
71
+ * @param services - injected runtime seams, e.g. the LLM-judge chat.
55
72
  * @returns the process exit code; nonzero for any failure or a run with no
56
73
  * completed trials.
57
74
  */
58
- export async function executeEval(values: EvalStartupValues, io: EvalIo): Promise<number> {
75
+ export async function executeEval(
76
+ values: EvalStartupValues,
77
+ io: EvalIo,
78
+ services: { judgeChat?: JudgeChat | undefined } = {},
79
+ ): Promise<number> {
59
80
  try {
60
81
  if (values.kind === 'report') {
61
82
  const run = await loadRunReport(values.runPath)
@@ -73,6 +94,7 @@ export async function executeEval(values: EvalStartupValues, io: EvalIo): Promis
73
94
  ...(values.trials !== undefined ? { trials: values.trials } : {}),
74
95
  ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
75
96
  ...(values.profile !== undefined ? { profile: values.profile } : {}),
97
+ ...(services.judgeChat !== undefined ? { judgeChat: services.judgeChat } : {}),
76
98
  })
77
99
  await writeRunReport(run, values.outPath)
78
100
  io.stdout.write(`Wrote ${values.outPath} (${run.cases.length} trials, ${summary(run)})\n`)
@@ -91,7 +113,8 @@ export async function executeEval(values: EvalStartupValues, io: EvalIo): Promis
91
113
  export function apply(ctx: Context): void {
92
114
  const exit = ctx.get('appExit')
93
115
  if (exit === undefined) throw new Error('eval: the launcher must provide ctx.appExit before the tree mounts')
116
+ const judgeChat = resolveJudgeChat(ctx)
94
117
  const values = applyEval(ctx)
95
118
  if (values === undefined) return
96
- void executeEval(values, internals).then((code) => { exit(code) })
119
+ void executeEval(values, internals, { judgeChat }).then((code) => { exit(code) })
97
120
  }
package/src/judge.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * LLM-judge scoring for dsh-eval: builds a judging prompt from the case and
3
+ * its trace, calls an injected chat seam, and parses the model's strict-JSON
4
+ * verdict into a final-answer score and hallucination flag. The production
5
+ * seam wraps the dsh-llm stream API; tests inject a fake so the suite stays
6
+ * keyless.
7
+ *
8
+ * @module dsh-eval/judge
9
+ */
10
+
11
+ import { BlockAssembler, createMessage, type LlmRuntime } from '@deepseek-ai/dsh-llm'
12
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
13
+ import type { BenchmarkCase, BenchmarkJudge, EvalJudgeVerdict, EvalTrace } from './types.ts'
14
+
15
+ /** One judge chat call: system instructions plus the single task prompt. */
16
+ export interface JudgeChatRequest {
17
+ /** Provider route, e.g. `deepseek`. */
18
+ provider: string
19
+ /** Judge model id. */
20
+ model: string
21
+ /** System instructions demanding strict JSON output. */
22
+ system: string
23
+ /** The task and trace summary to judge. */
24
+ prompt: string
25
+ }
26
+
27
+ /** The injected chat seam; returns the model's raw text reply. */
28
+ export type JudgeChat = (request: JudgeChatRequest) => Promise<string>
29
+
30
+ /** Concatenate one message's text blocks. */
31
+ function blockText(blocks: readonly ContentBlock[]): string {
32
+ return blocks.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
33
+ }
34
+
35
+ /**
36
+ * Summarize a trace for the judge: final assistant answer, the distinct tool
37
+ * names called, and the failure counters a hallucination call needs.
38
+ * @param trace - the merged trial trace.
39
+ * @returns a compact human-readable summary.
40
+ */
41
+ export function summarizeTrace(trace: EvalTrace): string {
42
+ let finalAnswer = ''
43
+ const toolNames: string[] = []
44
+ let invalidToolCalls = 0
45
+ let retries = 0
46
+ for (const event of trace.events) {
47
+ if (event.type === 'assistant/message') finalAnswer = blockText(event.data.message.content)
48
+ if (event.type === 'tool/call') {
49
+ if (!toolNames.includes(event.data.name)) toolNames.push(event.data.name)
50
+ }
51
+ if (event.type === 'tool/result' && event.data.error !== undefined) invalidToolCalls += 1
52
+ if (event.type === 'llm/retry') retries += 1
53
+ }
54
+ return [
55
+ `final answer: ${finalAnswer === '' ? '(none)' : finalAnswer}`,
56
+ `tools called: ${toolNames.length === 0 ? '(none)' : toolNames.join(', ')}`,
57
+ `invalid tool calls: ${invalidToolCalls}`,
58
+ `llm retries: ${retries}`,
59
+ ].join('\n')
60
+ }
61
+
62
+ /**
63
+ * Build the judge's system instructions and task prompt.
64
+ * @param caseValue - the benchmark case being judged.
65
+ * @param trace - the merged trial trace.
66
+ * @param judge - the judge configuration.
67
+ * @returns the system and prompt texts.
68
+ */
69
+ export function buildJudgePrompt(
70
+ caseValue: BenchmarkCase,
71
+ trace: EvalTrace,
72
+ judge: BenchmarkJudge,
73
+ ): { system: string; prompt: string } {
74
+ const system = [
75
+ 'You are an impartial evaluation judge for agent task completion.',
76
+ `Score the agent's final answer from 0 to ${judge.maxScore} against the task,`,
77
+ 'and set "hallucination" to true only when the final answer asserts facts',
78
+ 'not supported by the task or the trace.',
79
+ 'Return STRICT JSON with exactly these fields:',
80
+ `{"finalAnswerScore": <integer 0..${judge.maxScore}>, "hallucination": <true|false>, "rationale": "<one short sentence>"}`,
81
+ ...(judge.rubric !== undefined ? ['Rubric:', judge.rubric] : []),
82
+ ].join('\n')
83
+ const prompt = [
84
+ `Task id: ${caseValue.id}`,
85
+ `Task: ${caseValue.prompt}`,
86
+ 'Trace summary:',
87
+ summarizeTrace(trace),
88
+ ].join('\n')
89
+ return { system, prompt }
90
+ }
91
+
92
+ /** Extract the JSON object from a model reply, accepting fenced output. */
93
+ function parseJsonObject(text: string): Record<string, unknown> | null {
94
+ const cleaned = text.trim()
95
+ const fenced = cleaned.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/u)
96
+ const candidate = fenced?.[1] ?? cleaned
97
+ try {
98
+ const value: unknown = JSON.parse(candidate)
99
+ return typeof value === 'object' && value !== null
100
+ ? value as Record<string, unknown>
101
+ : null
102
+ } catch {
103
+ return null
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Parse the judge model's strict-JSON reply into a verdict. Unusable output
109
+ * yields null fields, never a fabricated verdict.
110
+ * @param text - the raw model reply.
111
+ * @param maxScore - the configured maximum score.
112
+ * @returns the parsed verdict.
113
+ */
114
+ export function parseJudgeVerdict(text: string, maxScore: number): EvalJudgeVerdict {
115
+ const value = parseJsonObject(text)
116
+ if (value === null) return { finalAnswerScore: null, hallucination: null }
117
+ const score = value.finalAnswerScore
118
+ const hallucination = value.hallucination
119
+ const rationale = value.rationale
120
+ const finalAnswerScore = typeof score === 'number' && Number.isFinite(score) && score >= 0 && score <= maxScore
121
+ ? score
122
+ : null
123
+ const parsedHallucination = typeof hallucination === 'boolean' ? hallucination : null
124
+ const parsedRationale = typeof rationale === 'string' && rationale.trim() !== '' ? rationale : undefined
125
+ return {
126
+ finalAnswerScore,
127
+ hallucination: parsedHallucination,
128
+ ...(parsedRationale !== undefined ? { rationale: parsedRationale } : {}),
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Judge one trial through the chat seam.
134
+ * @param caseValue - the benchmark case being judged.
135
+ * @param trace - the merged trial trace.
136
+ * @param judge - the judge configuration.
137
+ * @param chat - the injected chat seam.
138
+ * @returns the parsed verdict; a chat failure rejects.
139
+ */
140
+ export async function judgeTrial(
141
+ caseValue: BenchmarkCase,
142
+ trace: EvalTrace,
143
+ judge: BenchmarkJudge,
144
+ chat: JudgeChat,
145
+ ): Promise<EvalJudgeVerdict> {
146
+ const { system, prompt } = buildJudgePrompt(caseValue, trace, judge)
147
+ return parseJudgeVerdict(await chat({ provider: judge.provider, model: judge.model, system, prompt }), judge.maxScore)
148
+ }
149
+
150
+ /**
151
+ * Judge one trial, converting a chat failure into an all-null verdict so a
152
+ * judge outage reads as unjudged rather than a failed trial.
153
+ * @param caseValue - the benchmark case being judged.
154
+ * @param trace - the merged trial trace.
155
+ * @param judge - the judge configuration.
156
+ * @param chat - the injected chat seam.
157
+ * @returns the parsed verdict, or all-null when the chat call threw.
158
+ */
159
+ export async function tryJudgeTrial(
160
+ caseValue: BenchmarkCase,
161
+ trace: EvalTrace,
162
+ judge: BenchmarkJudge,
163
+ chat: JudgeChat,
164
+ ): Promise<EvalJudgeVerdict> {
165
+ try {
166
+ return await judgeTrial(caseValue, trace, judge, chat)
167
+ } catch {
168
+ return { finalAnswerScore: null, hallucination: null }
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Build the production chat seam over a dsh-llm stream: one user turn, zero
174
+ * temperature, and text-block assembly of the reply.
175
+ * @param stream - the llm service's stream method.
176
+ * @returns a chat seam reading only text blocks from the stream.
177
+ */
178
+ export function llmJudgeChat(stream: LlmRuntime['stream']): JudgeChat {
179
+ return async (request) => {
180
+ const assembler = new BlockAssembler()
181
+ for await (const chunk of stream({
182
+ provider: request.provider,
183
+ model: request.model,
184
+ system: request.system,
185
+ messages: [createMessage({
186
+ role: 'user',
187
+ content: [{ type: 'text', text: request.prompt }],
188
+ source: { kind: 'user' },
189
+ })],
190
+ temperature: 0,
191
+ })) {
192
+ assembler.push(chunk)
193
+ }
194
+ return assembler.message().content
195
+ .flatMap(block => block.type === 'text' ? [block.text] : [])
196
+ .join('')
197
+ }
198
+ }
package/src/report.ts CHANGED
@@ -48,6 +48,11 @@ function formatGrade(value: boolean | null): string {
48
48
  return value === null ? '–' : value ? 'yes' : 'no'
49
49
  }
50
50
 
51
+ /** Render a nullable score as `value/max` with a dash placeholder. */
52
+ function formatScore(value: number | null, maxScore: number): string {
53
+ return value === null ? '–' : `${value.toFixed(1)}/${maxScore}`
54
+ }
55
+
51
56
  /**
52
57
  * Render a run report as a markdown table: one row per trial plus the
53
58
  * aggregate row.
@@ -55,13 +60,20 @@ function formatGrade(value: boolean | null): string {
55
60
  * @returns the markdown text.
56
61
  */
57
62
  export function renderMarkdownReport(run: EvalRun): string {
58
- const header = [
59
- '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc |',
60
- '|---|---|---|---|---|---|---|---|---|---|---|---|---|',
61
- ]
63
+ const judge = run.judge
64
+ const judged = judge !== undefined
65
+ const header = judged
66
+ ? [
67
+ '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc | score | halluc |',
68
+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',
69
+ ]
70
+ : [
71
+ '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc |',
72
+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|',
73
+ ]
62
74
  const rows = run.cases.map((result) => {
63
75
  const metrics = result.metrics
64
- const values = metrics === undefined
76
+ const base = metrics === undefined
65
77
  ? ['–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
66
78
  : [
67
79
  String(metrics.steps),
@@ -75,20 +87,42 @@ export function renderMarkdownReport(run: EvalRun): string {
75
87
  formatGrade(result.grade?.taskSuccess ?? null),
76
88
  formatGrade(result.grade?.toolSelectionAccuracy ?? null),
77
89
  ]
78
- return `| ${result.caseId} | ${result.trial} | ${result.status} | ${values.join(' | ')} |`
90
+ const judgeCells = judged
91
+ ? [
92
+ formatScore(result.judge?.finalAnswerScore ?? null, judge.maxScore),
93
+ formatGrade(result.judge?.hallucination ?? null),
94
+ ]
95
+ : []
96
+ return `| ${result.caseId} | ${result.trial} | ${result.status} | ${[...base, ...judgeCells].join(' | ')} |`
79
97
  })
80
98
  const aggregate = run.aggregate
81
- const aggregateRow = aggregate === null
82
- ? '| aggregate | – | no completed trials | – | – | – | – | – | – | – | – | – | – |'
83
- : `| aggregate | – | completed | ${aggregate.steps.toFixed(1)} | ${aggregate.toolCalls.toFixed(1)} | `
84
- + `${formatRate(aggregate.toolSuccessRate)} | ${aggregate.invalidToolCalls.toFixed(1)} | `
85
- + `${aggregate.retries.toFixed(1)} | ${aggregate.totalTokens.toFixed(1)} | `
86
- + `${formatUsd(aggregate.costUsd)} | ${aggregate.latencyMs.toFixed(1)} | `
87
- + `${formatRate(run.grading?.taskSuccessRate ?? null)} | ${formatRate(run.grading?.toolSelectionAccuracyRate ?? null)} |`
99
+ const aggregateJudgeCells = judged
100
+ ? [
101
+ formatScore(run.grading?.finalAnswerScore ?? null, judge.maxScore),
102
+ formatRate(run.grading?.hallucinationRate ?? null),
103
+ ]
104
+ : []
105
+ const aggregateCells = aggregate === null
106
+ ? ['no completed trials', '–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
107
+ : [
108
+ 'completed',
109
+ aggregate.steps.toFixed(1),
110
+ aggregate.toolCalls.toFixed(1),
111
+ formatRate(aggregate.toolSuccessRate),
112
+ aggregate.invalidToolCalls.toFixed(1),
113
+ aggregate.retries.toFixed(1),
114
+ aggregate.totalTokens.toFixed(1),
115
+ formatUsd(aggregate.costUsd),
116
+ aggregate.latencyMs.toFixed(1),
117
+ formatRate(run.grading?.taskSuccessRate ?? null),
118
+ formatRate(run.grading?.toolSelectionAccuracyRate ?? null),
119
+ ]
120
+ const aggregateRow = `| aggregate | – | ${[...aggregateCells, ...aggregateJudgeCells].join(' | ')} |`
88
121
  return [
89
122
  `# Eval: ${run.benchmark}`,
90
123
  '',
91
124
  `- model: ${run.model}`,
125
+ ...(judged ? [`- judge: ${judge.model}`] : []),
92
126
  `- trials per case: ${run.trials}`,
93
127
  `- created: ${new Date(run.createdAt).toISOString()}`,
94
128
  `- traces: ${run.tempRoot}`,
package/src/runner.ts CHANGED
@@ -19,8 +19,9 @@ import { tmpdir } from 'node:os'
19
19
  import { join } from 'node:path'
20
20
  import type { Benchmark, EvalRun, EvalTrialResult } from './types.ts'
21
21
  import type { EvalGrade, EvalRunGrading } from './types.ts'
22
+ import { tryJudgeTrial, type JudgeChat } from './judge.ts'
22
23
  import { aggregateMetrics, computeMetrics } from './metrics.ts'
23
- import { findPrimarySessionLog, loadTrace } from './trace.ts'
24
+ import { findSessionLogs, loadTrace, mergeTraces } from './trace.ts'
24
25
 
25
26
  /** Overlay forcing the harvested log to plain JSONL and the run to be non-interactive. */
26
27
  const EVAL_OVERLAY = `- id: session-persistence-jsonl
@@ -50,6 +51,8 @@ export interface RunOptions {
50
51
  trials?: number
51
52
  /** Root for trial directories; defaults to the platform temp dir. */
52
53
  tempRoot?: string
54
+ /** LLM-judge chat seam; required when the benchmark configures a judge. */
55
+ judgeChat?: JudgeChat
53
56
  }
54
57
 
55
58
  /** One child process's orthogonal outcome facts. */
@@ -131,9 +134,22 @@ function pooledRate(items: readonly EvalTrialResult[], select: (grade: EvalGrade
131
134
  function gradingOf(results: readonly EvalTrialResult[]): EvalRunGrading | null {
132
135
  const taskSuccessRate = pooledRate(results, grade => grade?.taskSuccess ?? null)
133
136
  const toolSelectionAccuracyRate = pooledRate(results, grade => grade?.toolSelectionAccuracy ?? null)
137
+ const finalScores = results
138
+ .map(result => result.judge?.finalAnswerScore ?? null)
139
+ .filter((value): value is number => value !== null)
140
+ const finalAnswerScore = finalScores.length === 0
141
+ ? null
142
+ : finalScores.reduce((total, value) => total + value, 0) / finalScores.length
143
+ const hallucinated = results
144
+ .map(result => result.judge?.hallucination ?? null)
145
+ .filter((value): value is boolean => value !== null)
146
+ const hallucinationRate = hallucinated.length === 0
147
+ ? null
148
+ : hallucinated.filter(value => value).length / hallucinated.length
134
149
  return taskSuccessRate === null && toolSelectionAccuracyRate === null
150
+ && finalAnswerScore === null && hallucinationRate === null
135
151
  ? null
136
- : { taskSuccessRate, toolSelectionAccuracyRate }
152
+ : { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate }
137
153
  }
138
154
 
139
155
  /**
@@ -212,6 +228,7 @@ async function runCaseTrial(
212
228
  caseValue: Benchmark['cases'][number],
213
229
  trial: number,
214
230
  root: string,
231
+ judgeChat: JudgeChat | undefined,
215
232
  ): Promise<EvalTrialResult> {
216
233
  const trialDir = join(root, `${sanitizeSegment(caseValue.id)}-${trial}`)
217
234
  const workspace = join(trialDir, 'workspace')
@@ -240,8 +257,8 @@ async function runCaseTrial(
240
257
  timedOut: false,
241
258
  }
242
259
  }
243
- const tracePath = await findPrimarySessionLog(dshHome)
244
- if (tracePath === null) {
260
+ const tracePaths = await findSessionLogs(dshHome)
261
+ if (tracePaths.length === 0) {
245
262
  return {
246
263
  caseId: caseValue.id,
247
264
  trial,
@@ -252,26 +269,36 @@ async function runCaseTrial(
252
269
  }
253
270
  }
254
271
  try {
255
- const trace = await loadTrace(tracePath)
272
+ const loaded: { path: string; trace: Awaited<ReturnType<typeof loadTrace>> }[] = []
273
+ for (const path of tracePaths) loaded.push({ path, trace: await loadTrace(path) })
274
+ loaded.sort((a, b) => a.trace.createdAt - b.trace.createdAt)
275
+ // tracePaths.length > 0 above guarantees a non-empty loaded list.
276
+ const primaryPath = loaded[0]!.path
277
+ const trace = mergeTraces(loaded.map(entry => entry.trace))
256
278
  const pricing = benchmark.pricing?.[benchmark.model]
257
279
  const metrics = computeMetrics(trace.events, pricing)
258
280
  const grade = await gradeTrial(caseValue, trace, workspace, benchmark.timeoutMs)
281
+ const judge = benchmark.judge === undefined || judgeChat === undefined
282
+ ? undefined
283
+ : await tryJudgeTrial(caseValue, trace, benchmark.judge, judgeChat)
259
284
  return {
260
285
  caseId: caseValue.id,
261
286
  trial,
262
287
  status: 'completed',
263
- tracePath,
288
+ tracePath: primaryPath,
289
+ tracePaths: loaded.map(entry => entry.path),
264
290
  exitCode: outcome.exitCode,
265
291
  timedOut: outcome.timedOut,
266
292
  metrics,
267
293
  ...(grade.taskSuccess !== null || grade.toolSelectionAccuracy !== null ? { grade } : {}),
294
+ ...(judge !== undefined ? { judge } : {}),
268
295
  }
269
296
  } catch (error) {
270
297
  return {
271
298
  caseId: caseValue.id,
272
299
  trial,
273
300
  status: 'error',
274
- error: `failed to read trace ${tracePath}: ${message(error)}`,
301
+ error: `failed to read trace: ${message(error)}`,
275
302
  exitCode: outcome.exitCode,
276
303
  timedOut: outcome.timedOut,
277
304
  }
@@ -285,6 +312,9 @@ async function runCaseTrial(
285
312
  * @returns the completed run record, written by the caller.
286
313
  */
287
314
  export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {}): Promise<EvalRun> {
315
+ if (benchmark.judge !== undefined && options.judgeChat === undefined) {
316
+ throw new Error('eval: benchmark configures a judge but no LLM chat seam is available')
317
+ }
288
318
  const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'))
289
319
  const trials = options.trials ?? benchmark.trials
290
320
  const effective: Benchmark = {
@@ -295,7 +325,7 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
295
325
  const results: EvalTrialResult[] = []
296
326
  for (const caseValue of effective.cases) {
297
327
  for (let trial = 1; trial <= trials; trial++) {
298
- results.push(await runCaseTrial(effective, caseValue, trial, root))
328
+ results.push(await runCaseTrial(effective, caseValue, trial, root, options.judgeChat))
299
329
  }
300
330
  }
301
331
  const completed = results.filter(
@@ -309,6 +339,7 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
309
339
  trials,
310
340
  seed: benchmark.seed,
311
341
  pricing: benchmark.pricing?.[benchmark.model] ?? null,
342
+ ...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
312
343
  tempRoot: root,
313
344
  cases: results,
314
345
  aggregate: aggregateMetrics(completed.map(result => result.metrics)),
package/src/trace.ts CHANGED
@@ -92,3 +92,46 @@ export async function findPrimarySessionLog(root: string): Promise<string | null
92
92
  }
93
93
  return best?.path ?? null
94
94
  }
95
+
96
+ /**
97
+ * Find every `session.jsonl` under a DSH_HOME tree, sorted by modification
98
+ * time ascending so the parent session (started first) comes first.
99
+ * @param root - the DSH_HOME directory to scan.
100
+ * @returns absolute log paths in ascending mtime order.
101
+ */
102
+ export async function findSessionLogs(root: string): Promise<string[]> {
103
+ let entries
104
+ try {
105
+ entries = await readdir(root, { withFileTypes: true })
106
+ } catch {
107
+ return []
108
+ }
109
+ const found: { path: string; mtime: number }[] = []
110
+ for (const entry of entries) {
111
+ if (entry.isDirectory()) {
112
+ for (const nested of await findSessionLogs(join(root, entry.name))) {
113
+ found.push({ path: nested, mtime: (await stat(nested)).mtimeMs })
114
+ }
115
+ } else if (entry.isFile() && entry.name === 'session.jsonl') {
116
+ found.push({ path: join(root, entry.name), mtime: (await stat(join(root, entry.name))).mtimeMs })
117
+ }
118
+ }
119
+ return found.sort((a, b) => a.mtime - b.mtime).map(entry => entry.path)
120
+ }
121
+
122
+ /**
123
+ * Merge traces into one timeline: events from every trace sorted by event
124
+ * time, ties broken by source order. The primary trace's header (session id
125
+ * and creation time) labels the merged trace.
126
+ * @param traces - harvested traces, primary first.
127
+ * @returns the merged trace.
128
+ */
129
+ export function mergeTraces(traces: readonly EvalTrace[]): EvalTrace {
130
+ const primary = traces[0]
131
+ if (primary === undefined) throw new Error('mergeTraces requires at least one trace')
132
+ const events = traces
133
+ .flatMap((trace, source) => trace.events.map(event => ({ event, source })))
134
+ .sort((a, b) => a.event.time - b.event.time || a.source - b.source)
135
+ .map(entry => entry.event)
136
+ return { sessionId: primary.sessionId, createdAt: primary.createdAt, events }
137
+ }
package/src/types.ts CHANGED
@@ -40,6 +40,18 @@ export interface BenchmarkExpectation {
40
40
  check?: string
41
41
  }
42
42
 
43
+ /** LLM-judge configuration: scores final answers and flags hallucinations. */
44
+ export interface BenchmarkJudge {
45
+ /** Provider route for the judge call, e.g. `deepseek`. */
46
+ provider: string
47
+ /** Judge model id; defaults to the benchmark model when unset. */
48
+ model: string
49
+ /** Optional task rubric appended to the default judging instructions. */
50
+ rubric?: string
51
+ /** Maximum final-answer score; defaults to 10. */
52
+ maxScore: number
53
+ }
54
+
43
55
  /** A validated benchmark document. */
44
56
  export interface Benchmark {
45
57
  /** Benchmark name; also the run record's `benchmark` field. */
@@ -60,6 +72,8 @@ export interface Benchmark {
60
72
  cases: readonly BenchmarkCase[]
61
73
  /** Pricing keyed by model id; an absent model reports `costUsd: null`. */
62
74
  pricing?: Readonly<Record<string, BenchmarkPricing>>
75
+ /** LLM-judge configuration, when final-answer scoring is enabled. */
76
+ judge?: BenchmarkJudge
63
77
  /** Directory the benchmark document was loaded from; relative paths resolve against it. */
64
78
  baseDir: string
65
79
  }
@@ -138,6 +152,8 @@ export interface EvalTrialResult {
138
152
  error?: string
139
153
  /** Absolute path of the harvested primary session log. */
140
154
  tracePath?: string
155
+ /** Absolute paths of every harvested session log, primary first. */
156
+ tracePaths?: readonly string[]
141
157
  /** The child process's exit code, or null when it was killed. */
142
158
  exitCode: number | null
143
159
  /** Whether the trial hit its timeout and killed the child. */
@@ -146,6 +162,8 @@ export interface EvalTrialResult {
146
162
  metrics?: EvalCaseMetrics
147
163
  /** Scripted grading outcome for `completed` trials with expectations. */
148
164
  grade?: EvalGrade
165
+ /** LLM-judge verdict for `completed` trials with a configured judge. */
166
+ judge?: EvalJudgeVerdict
149
167
  }
150
168
 
151
169
  /** Scripted grading outcome for one trial. */
@@ -156,12 +174,26 @@ export interface EvalGrade {
156
174
  toolSelectionAccuracy: boolean | null
157
175
  }
158
176
 
177
+ /** LLM-judge verdict for one trial. */
178
+ export interface EvalJudgeVerdict {
179
+ /** Final-answer score within the benchmark's `maxScore`, or null when the judge output was unusable. */
180
+ finalAnswerScore: number | null
181
+ /** Whether the judge flagged hallucinated content, or null when the judge output was unusable. */
182
+ hallucination: boolean | null
183
+ /** Judge rationale, when the model returned one. */
184
+ rationale?: string
185
+ }
186
+
159
187
  /** Pooled grading rates over completed trials. */
160
188
  export interface EvalRunGrading {
161
189
  /** Pooled task-success rate, or null when no trial carried a check. */
162
190
  taskSuccessRate: number | null
163
191
  /** Pooled tool-selection-accuracy rate, or null when no trial carried an expected tool. */
164
192
  toolSelectionAccuracyRate: number | null
193
+ /** Mean final-answer score over judged trials, or null when nothing was judged. */
194
+ finalAnswerScore: number | null
195
+ /** Pooled hallucination rate over judged trials, or null when nothing was judged. */
196
+ hallucinationRate: number | null
165
197
  }
166
198
 
167
199
  /** A persisted eval run. */
@@ -178,6 +210,8 @@ export interface EvalRun {
178
210
  seed: number
179
211
  /** Resolved pricing for the benchmark model, or null without one. */
180
212
  pricing: BenchmarkPricing | null
213
+ /** The judge configuration the run used, when one was configured. */
214
+ judge?: BenchmarkJudge
181
215
  /** Root holding every trial's workspace, overlay, and harvested trace. */
182
216
  tempRoot: string
183
217
  /** Per-trial outcomes in execution order. */