# @pleach/eval (/docs/eval)



How the garden grew this season — fixed seeds, measured shoots,
comparable rows. `@pleach/eval` is the evaluation harness for
`@pleach/core` agent runtimes. The package ships an `EvalSuite` class
that accepts cases as a discriminated union, four built-in scorers,
three report formatters (JSON, Markdown, JUnit XML), and an
`EvalRuntime` factory with live bodies for batch execution, report
rendering, structural `diffReports`, and statistical `compareScored`
(bootstrap + Welch's t-test). Coupling to `@pleach/replay` is opt-in
via dependency injection — the two SKUs install and adopt
independently.

This page is the SKU reference. For the DIY workflow using
`@pleach/core` primitives directly today (without this SKU), see
[Eval and replay](/docs/eval-and-replay).

**Package:** `@pleach/eval` ([not on npm yet](</docs/install#not-on-npm-yet>)) · **Source:** [github.com/pleachhq/eval](<https://www.getpleach.com/docs/eval>)

## Install [#install]

```bash
npm install @pleach/eval @pleach/core
```

```bash
pnpm add @pleach/eval @pleach/core
```

```bash
bun add @pleach/eval @pleach/core
```

`@pleach/core` is a peer dependency.

```typescript
import { EvalSuite } from "@pleach/eval";
import { tokenF1 } from "@pleach/eval/scorers";
import { formatMarkdown } from "@pleach/eval/report";
import { NoopReplayClient } from "@pleach/eval/replay";
```

The import names above are illustrative. The authoritative export
shape lives in the package README (not on npm yet) — check it when
pinning a version.

## The `EvalSuite` class [#the-evalsuite-class]

`EvalSuite` is the entry point. Construct it with a `suiteId` (the
identifier that surfaces in reports), register cases, then call
`run()` to produce an `EvalReport`.

```typescript
import { EvalSuite } from "@pleach/eval";

const suite = new EvalSuite({ suiteId: "my-eval" });

suite.register({
  kind: "expected",
  id: "greeting",
  input: "hello",
  expected: "hello",
});

const report = await suite.run();
console.log(report.summary);
// { total: 1, passed: 1, failed: 0, errored: 0 }
```

Cases run in registration order. The report carries a stable
`runId`, the start and completion timestamps, every case result, and
a summary count.

The constructor takes a `runtime` (any `EvalSessionRuntimeLike` — a
real `SessionRuntime` from `@pleach/core` satisfies the shape). The
`runtime` is optional so the surface unit-tests against a
mock; in production callers always provide a real runtime.

`EvalSuiteOptions` also declares `cacheBackend` and `cacheReadPolicy`,
but `EvalSuite` reads neither — they are accepted and inert in Phase
A. Configure caching on the runtime instead; see
[Cache configuration](#cache-configuration).

## Case shapes [#case-shapes]

`EvalCase` is a discriminated union with three shapes. There is no
global registry — scorers ride inline with the case.

### `expected` — pass/fail equality [#expected--passfail-equality]

A string or RegExp equality check.

```typescript
suite.register({
  kind: "expected",
  id: "section-cite",
  input: "the model output",
  expected: /section 4\.\d+/,
});
```

### `scored` — numeric score from a scorer [#scored--numeric-score-from-a-scorer]

A scorer returns a score in `[0, 1]`. Reference a built-in by id or
ship a custom function inline.

```typescript
suite.register({
  kind: "scored",
  id: "f1-against-golden",
  input: { expected: "the quick brown fox" },
  scorer: { kind: "builtin", id: "tokenF1" },
});

suite.register({
  kind: "scored",
  id: "length-bound",
  input: "...",
  scorer: {
    kind: "custom",
    fn: async (actual) => ({
      score: actual.length > 100 ? 1 : 0,
      explanation: `length=${actual.length}`,
    }),
  },
});
```

A `scored` case passes when its score is `>= 1`. Anything lower is a
fail, but the numeric score still rolls into the report's mean.

### `judged` — LLM-as-judge ensemble [#judged--llm-as-judge-ensemble]

A list of judge models that score the actual output. Each judge
carries a model id, a rubric prompt, and a score schema (`"binary"`,
`"likert-5"`, or `"numeric"`).

```typescript
suite.register({
  kind: "judged",
  id: "summary-accuracy",
  input: "summarize this paper: ...",
  judges: [
    {
      model: "anthropic/claude-opus-4-7",
      rubric: "Rate the summary's factual accuracy on a 1-5 Likert scale.",
      scoreSchema: "likert-5",
    },
  ],
});
```

Judge dispatch is live: judges are invoked in parallel through the
runtime's provider seam (routing through `@pleach/gateway` when
present), each response is normalized per its `scoreSchema`, and the
ensemble is averaged. Without a wired provider, judged cases return an
honest stub (`score: 0`) with an explanation noting no provider was
configured.

### The judge provider seam [#the-judge-provider-seam]

`@pleach/eval` stays free of a hard `@pleach/core` import: judge
dispatch runs through a structural seam the host wires on
`runtime.providers`. The public shapes:

| Export                 | Kind          | Role                                                                                                                                              |
| ---------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `EvalJudgeProvider`    | interface     | The seam — `invoke(request): Promise<EvalJudgeResponse>`. A thin adapter around your model client, or `@pleach/gateway` for multi-tenant routing. |
| `EvalJudgeInvocation`  | interface     | One invocation — the resolved `model` id plus the fully-built `prompt` (rubric + output + score-format instruction).                              |
| `EvalJudgeResponse`    | interface     | The judge's assistant `text`; the score is parsed from it.                                                                                        |
| `JUDGE_PASS_THRESHOLD` | const (`0.5`) | The averaged-score pass line. Every `scoreSchema` normalizes to `[0, 1]` first; a case passes at or above this.                                   |

The runtime's `providers` value is narrowed to `EvalJudgeProvider` at
dispatch time — any value lacking a callable `invoke` preserves the
honest stub, so a suite still runs offline.

## The four built-in scorers [#the-four-built-in-scorers]

Exported from `@pleach/eval/scorers`. All four implement the
`EvalScorerFn` contract — `(actual, ctx) => EvalScore` — so they
work as both inline values and `EvalScorerRef` references.

| Scorer              | Input expectation                          | Score                                         |
| ------------------- | ------------------------------------------ | --------------------------------------------- |
| `exactMatch`        | `expected` string in case input            | 1 iff `actual === expected`                   |
| `substringContains` | `expected` string in case input            | 1 iff `actual.includes(expected)`             |
| `regexMatch`        | `pattern` + optional `flags` in case input | 1 iff the regex tests true                    |
| `tokenF1`           | `expected` string in case input            | Token-level F1 (whitespace-split, lowercased) |

`exactMatch`, `substringContains`, and `tokenF1` read the expected
value from either a bare string input or an `{ expected }` field on a
record input. `regexMatch` reads `{ pattern, flags? }` (or treats a
bare string input as the pattern with no flags). When the expected
value is missing, the scorer returns score 0 with an explanation
naming the missing field — no thrown exceptions for misconfigured
cases.

`tokenF1` returns the F1 over the token multiset: `2PR / (P + R)`,
where P is overlap divided by `actual` token count and R is overlap
divided by `expected` token count. Both sides empty score 1 by
convention; one side empty scores 0.

## The three report formats [#the-three-report-formats]

Exported from `@pleach/eval/report`. The same `EvalReport` feeds all
three formatters — pick one (or several) depending on where the
report lands.

```typescript
import { formatJSON, formatMarkdown, formatJUnitXML } from "@pleach/eval/report";

const report = await suite.run();

console.log(formatJSON(report));        // pretty-printed JSON
console.log(formatMarkdown(report));    // human-readable summary
console.log(formatJUnitXML(report));    // CI consumer
```

`formatJSON` sorts case results by `caseId` and emits stable key
ordering — two runs against identical input produce byte-identical
JSON output, which makes the formatter usable as a golden-file
target. Two-space indent matches `jq` defaults.

`formatMarkdown` emits a summary block plus a per-case table with
status, score, and explanation. Pipe character escaping is handled.

`formatJUnitXML` produces a single `<testsuite>` element with one
`<testcase>` per eval case. Errored cases include `<error>`, failed
cases include `<failure>`. The shape matches the `junit-xml`
convention used by `mocha-junit-reporter` and `jest-junit`, so the
output plugs into GitHub Actions, GitLab CI, and Jenkins without a
custom reporter.

## Bundled benchmarks [#bundled-benchmarks]

Four loaders turn a public benchmark into `EvalCase[]` you feed
straight to an `EvalSuite`. Each ships on its own subpath under
`@pleach/eval/benchmarks`.

| Loader                    | Subpath                                | Returns                                          |
| ------------------------- | -------------------------------------- | ------------------------------------------------ |
| `loadMmluSubset(opts?)`   | `@pleach/eval/benchmarks/mmlu`         | MMLU cases; filter with `opts.subjects`          |
| `loadHumanEval(opts?)`    | `@pleach/eval/benchmarks/humaneval`    | HumanEval coding cases                           |
| `loadSweBenchLite(opts?)` | `@pleach/eval/benchmarks/swe-bench`    | SWE-bench Lite starter cases                     |
| `loadCustomDomain(opts)`  | `@pleach/eval/benchmarks/customDomain` | Your own `opts.cases`, capped by `opts.maxCases` |

Each accepts `maxCases` to bound the run. The three public benchmarks
are async (they load bundled or fetched rows); `loadCustomDomain` is
synchronous.

```ts
import { EvalSuite } from "@pleach/eval"
import { loadMmluSubset } from "@pleach/eval/benchmarks/mmlu"

const suite = new EvalSuite({ suiteId: "mmlu-cs" })
for (const c of await loadMmluSubset({ subjects: ["college_computer_science"], maxCases: 50 })) {
  suite.register(c)
}
const report = await suite.run()
```

## Cost estimation — `@pleach/eval/cost` [#cost-estimation--pleachevalcost]

Two pure functions on the `@pleach/eval/cost` subpath — no I/O, no
bundled pricing. Consumers supply a `PriceTable` (USD per million
tokens, keyed by model id) at call time, because prices drift and
bundling stale data is worse than failing fast.

| Export                                                                                                            | Kind     | Role                                                                                                                                                                                   |
| ----------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `estimateCost(runs, pricing)`                                                                                     | function | Returns a frozen `CostBreakdown` — `total`, per-run `usd`, `perModel` aggregates, and `unpricedRuns` (run IDs whose model was absent from `pricing`; those contribute `0` to `total`). |
| `compareCostWithCache(uncached, cached)`                                                                          | function | Diffs two `CostBreakdown`s into a `SavingsReport` — `savedUsd`, `savedPct` (0 when the baseline total is 0), and per-model savings.                                                    |
| `PriceTable`, `CostBreakdown`, `SavingsReport`, `EvalRun`, `ModelPricing`, `RunCost`, `ModelCost`, `ModelSavings` | types    | The input + report shapes.                                                                                                                                                             |

```ts
import { estimateCost, compareCostWithCache } from "@pleach/eval/cost";

const pricing = { "x": { inputPerMillion: 3, outputPerMillion: 15 } };
const breakdown = estimateCost(
  [{ id: "r1", model: "x", inputTokens: 1000, outputTokens: 500 }],
  pricing,
);
// breakdown.total === 0.0105

const savings = compareCostWithCache(uncached, cached);
console.log(`Saved $${savings.savedUsd.toFixed(2)} (${savings.savedPct.toFixed(1)}%)`);
```

For a router-side pricing lookup (rather than this provider-agnostic
estimator), see [`@pleach/gateway`](/docs/gateway).

## Replay coupling via constructor DI [#replay-coupling-via-constructor-di]

`@pleach/eval` does not import `@pleach/replay`. The two SKUs adopt
independently and couple through a structural contract —
`EvalReplayClient` — that consumers (or `@pleach/replay` itself)
implement.

```typescript
import { EvalSuite, type EvalReplayClient } from "@pleach/eval";
import { createReplayRuntime } from "@pleach/replay";

const suite = new EvalSuite({ suiteId: "replay-eval", runtime });

// @pleach/replay's turn-granular runtime, adapted to eval's structural
// `EvalReplayClient` contract (`replay(chatId) => { output }`).
const tenantId = "tenant_xyz";
const replayRuntime = createReplayRuntime({ tenantId, sessionRuntime: runtime });
const replayClient: EvalReplayClient = {
  async replay(chatId) {
    const { state } = await replayRuntime.replayTurn({ chatId, tenantId });
    return { output: String(state ?? "") };
  },
};
suite.setReplayClient(replayClient);

const report = await suite.replay("chat_01HKXJ...");
```

`replay(chatId)` reconstructs the turn's final output via the
injected client and runs every registered case against it. Without a
client, `replay()` throws with a message that names the missing DI.

`@pleach/eval/replay` ships two test stubs:

* `NoopReplayClient` — returns empty output for any chat id. Useful
  when unit-testing the `replay()` wiring without dragging in the
  real replay package.
* `StaticReplayClient` — returns a canned output for any chat id.
  Useful when unit-testing scorer dispatch against a known output.

```typescript
import { NoopReplayClient, StaticReplayClient } from "@pleach/eval/replay";

suite.setReplayClient(new StaticReplayClient("the canned output"));
```

The stubs ship in the same subpath as the contract, so consumers
that only need the structural type — not the real replay client —
don't pick up a transitive dependency.

## Cache configuration [#cache-configuration]

Cache behavior is configured on the `SessionRuntime` you hand the
suite, not on `EvalSuite`. `EvalSuiteOptions` declares `cacheBackend`
and `cacheReadPolicy`, but the class never reads them — passing them
to the constructor type-checks and does nothing.

Pass them to the runtime:

```typescript
import { SessionRuntime } from "@pleach/core";
import { createMemoryCacheBackend } from "@pleach/core/cache";

const runtime = new SessionRuntime({
  storage,
  checkpointer,
  tenantId:     "acme",
  cacheBackend: createMemoryCacheBackend({ maxEntries: 10_000 }),
  runtimeMode:  "deterministic",
});

const suite = new EvalSuite({ suiteId: "shared-cache-eval", runtime });
```

`SessionRuntimeConfig.cacheBackend` defaults to a fresh in-memory
backend per runtime, so two runtimes in one process can't poison each
other's cache. `runtimeMode` is the read-policy knob:
`"interactive"` (the default) reads and writes the interactive cache
partition; `"deterministic"` — the eval, replay, and batch setting —
reads across from interactive entries and writes strictly to the
deterministic partition. Deterministic mode fails closed without an
explicit `tenantId`, so pass one. See [Cache](/docs/cache) for the
policy contract.

## What you provide [#what-you-provide]

Judges run in parallel through `runtime.providers` (routing through
`@pleach/gateway` when configured). Each response is normalized per
its `scoreSchema` and the ensemble is averaged. With no provider
wired, judges return `score: 0`, so wire one.

You also provide the actual-output resolver. The default echoes the
case input back as the actual output, which keeps the surface
unit-testable. Call `setActualResolver(resolver)` to drive a real
runtime turn. The report shape doesn't change when you swap it.

## `createEvalRuntime` [#createevalruntime]

The `EvalRuntime` factory (`createEvalRuntime`) exposes the batch / report /
comparison surface used for cross-config and cross-run analysis.
At the current cut:

| `EvalRuntime` method                | Status                                                                                                                          |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `runScenario(input)`                | Live — validates input + emits a stub `EvalScenarioOutput` (real LLM invocation routes through `harnessRuntime` in a follow-up) |
| `runBatch(input)`                   | Live — iterates `configs × rows`, dispatches each cell via `runScenario`, aggregates per-config + global cost rolls             |
| `produceEvalReport(input)`          | Live — renders a versioned report in JSON / Markdown / CSV format                                                               |
| `recordOutcome(input)`              | Live — appends to an in-memory outcomes ledger (persistent storage via `@pleach/replay` cache is a follow-up)                   |
| `diffReports(prior, next)`          | Live — pure-function deterministic structural diff over two `EvalReportOutput` instances                                        |
| `compareScored(prior, next, opts?)` | Live — bootstrap resampling + Welch's t-test over two scored runs                                                               |
| `runStreaming(input, callbacks)`    | Live — streaming variant of `runBatch` with per-cell callbacks                                                                  |

### `diffReports(prior, next)` [#diffreportsprior-next]

Pure-function structural diff between two `EvalReportOutput`
instances. Both inputs must carry the same `version` and
`format: "json"` (the canonical JSON format is parsed and walked
cell-by-cell). The returned `EvalReportDiff` carries per-cell
status (`added`, `removed`, `changed`, `unchanged`) and a summary
roll-up. Use it to verify two pinned report snapshots match, or
to surface what changed between a pre- and post-refactor batch.

### `compareScored(prior, next, opts?)` [#comparescoredprior-next-opts]

Statistical comparison of two scored eval runs. Pairs cells by
`(config, row)` identity, then runs bootstrap resampling and
Welch's t-test on the paired score deltas — paired-sample
comparison with unequal variances (Welch's t-test is the
unequal-variance generalization of Student's t-test; bootstrap
resampling gives a non-parametric confidence interval that holds
without distributional assumptions on the score). The returned
`EvalComparisonResult` carries the bootstrap CI, the t-test
statistic + p-value, and per-row pairing diagnostics so a caller
can reject "the new config is statistically better" claims that
fail the significance bar.

Pair this with [`@pleach/replay`](/docs/replay) when the eval
batches you're comparing are themselves derived from chat
replays — `@pleach/eval` consumes `EvalReportOutput`s, and
`@pleach/replay` is the substrate that produces deterministic
outputs to score.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Eval and replay" href="/docs/eval-and-replay" description="The DIY workflow against `@pleach/core` primitives — fingerprint, audit ledger, checkpoints, runtimeMode. The path you can adopt today without this SKU." />

  <Card title="@pleach/replay" href="/docs/replay" description="The sibling SKU — event-granular ReplayClient + ReplayHandle that `EvalSuite.replay()` couples to via DI." />

  <Card title="Cache" href="/docs/cache" description="The `CacheBackend` contract `EvalSuite` reads through, and the read-policy modes that govern cross-mode cache visibility." />

  <Card title="Fingerprint" href="/docs/fingerprint" description="The cache key that anchors deterministic replay and makes regression eval a yes/no question." />
</Cards>
