@tangle-network/agent-eval 1.0.34 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/analyst/index.d.ts +3 -3
  4. package/dist/app-grade/index.d.ts +2 -2
  5. package/dist/benchmarks/index.d.ts +90 -8
  6. package/dist/benchmarks/index.d.ts.map +1 -1
  7. package/dist/benchmarks/index.js +590 -50
  8. package/dist/benchmarks/index.js.map +1 -1
  9. package/dist/campaign/index.d.ts +4 -4
  10. package/dist/contract/index.d.ts +7 -7
  11. package/dist/{default-registry-2Ziw-0sL.d.ts → default-registry-CfZCJdJT.d.ts} +2 -2
  12. package/dist/{default-registry-2Ziw-0sL.d.ts.map → default-registry-CfZCJdJT.d.ts.map} +1 -1
  13. package/dist/{define-agent-eval-DmCV1TZo.d.ts → define-agent-eval-QdTTdbyE.d.ts} +5 -5
  14. package/dist/{define-agent-eval-DmCV1TZo.d.ts.map → define-agent-eval-QdTTdbyE.d.ts.map} +1 -1
  15. package/dist/{evaluation-BQQ2ga5W.d.ts → evaluation-imW3I7tD.d.ts} +2 -2
  16. package/dist/{evaluation-BQQ2ga5W.d.ts.map → evaluation-imW3I7tD.d.ts.map} +1 -1
  17. package/dist/evaluation.d.ts +1 -1
  18. package/dist/experiment/index.d.ts +1 -1
  19. package/dist/{index-BwJtNdaj.d.ts → index-CeEW0CHk.d.ts} +11 -11
  20. package/dist/{index-BwJtNdaj.d.ts.map → index-CeEW0CHk.d.ts.map} +1 -1
  21. package/dist/{index-BFpDeCuS.d.ts → index-CeTno9aO.d.ts} +2 -2
  22. package/dist/{index-BFpDeCuS.d.ts.map → index-CeTno9aO.d.ts.map} +1 -1
  23. package/dist/{index-8hbrQwdR.d.ts → index-DshgWP9U.d.ts} +4 -4
  24. package/dist/{index-8hbrQwdR.d.ts.map → index-DshgWP9U.d.ts.map} +1 -1
  25. package/dist/{index-BfxYoHGF.d.ts → index-_Gwk9sZl.d.ts} +2 -2
  26. package/dist/{index-BfxYoHGF.d.ts.map → index-_Gwk9sZl.d.ts.map} +1 -1
  27. package/dist/{index-BnqugnsM.d.ts → index-sOdbeWGO.d.ts} +6 -6
  28. package/dist/{index-BnqugnsM.d.ts.map → index-sOdbeWGO.d.ts.map} +1 -1
  29. package/dist/index.d.ts +11 -11
  30. package/dist/index.js +1 -153
  31. package/dist/index.js.map +1 -1
  32. package/dist/llm-judge-DOgWUOml.js.map +1 -1
  33. package/dist/{matrix-D0fEU0fq.d.ts → matrix-Bk8Iz49C.d.ts} +2 -2
  34. package/dist/{matrix-D0fEU0fq.d.ts.map → matrix-Bk8Iz49C.d.ts.map} +1 -1
  35. package/dist/multishot/golden/index.d.ts +1 -1
  36. package/dist/multishot/index.d.ts +2 -2
  37. package/dist/openapi.json +1 -1
  38. package/dist/rl.d.ts +1 -1
  39. package/dist/rollout/index.d.ts +2 -2
  40. package/dist/search/index.d.ts +2 -2
  41. package/dist/{search-kernel-IpyhPDQd.d.ts → search-kernel-BigyOZX3.d.ts} +2 -2
  42. package/dist/{search-kernel-IpyhPDQd.d.ts.map → search-kernel-BigyOZX3.d.ts.map} +1 -1
  43. package/dist/{statistical-heldout-AvgLVFp6.d.ts → statistical-heldout-Bd6PVnQD.d.ts} +2 -2
  44. package/dist/{statistical-heldout-AvgLVFp6.d.ts.map → statistical-heldout-Bd6PVnQD.d.ts.map} +1 -1
  45. package/dist/{systemone-DPVj7a1g.d.ts → systemone-Dpp7I3uV.d.ts} +3 -3
  46. package/dist/{systemone-DPVj7a1g.d.ts.map → systemone-Dpp7I3uV.d.ts.map} +1 -1
  47. package/dist/systemone.d.ts +2 -2
  48. package/dist/{types-qJwFZTqa.d.ts → types-BeJIREX-.d.ts} +6 -1
  49. package/dist/types-BeJIREX-.d.ts.map +1 -0
  50. package/dist/{types-rf0yhJmW.d.ts → types-ff0YYJnj.d.ts} +69 -3
  51. package/dist/types-ff0YYJnj.d.ts.map +1 -0
  52. package/dist/verification-strategy-CYhDX1rE.js +156 -0
  53. package/dist/verification-strategy-CYhDX1rE.js.map +1 -0
  54. package/dist/wire/index.d.ts +5 -5
  55. package/package.json +1 -1
  56. package/dist/types-qJwFZTqa.d.ts.map +0 -1
  57. package/dist/types-rf0yhJmW.d.ts.map +0 -1
@@ -1,13 +1,19 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-BJohB4LM.js";
2
+ import { a as hashCanonical } from "../canonical-BANK6NOj.js";
2
3
  import { pt as mean, ut as summarizeNumberSeries } from "../statistics-CHs0jlsY.js";
3
4
  import { $ as runCampaign } from "../llm-judge-DOgWUOml.js";
5
+ import { t as deepFreezeCanonicalJson } from "../deep-freeze-CK8-2W7p.js";
4
6
  import { M as fsCampaignStorage } from "../external-optimizer-subprocess-BUCI-uFn.js";
7
+ import { c as redactText, o as redact } from "../redact-zp_ILC4l.js";
8
+ import { t as certificationEvidenceDigest } from "../verdict-CKo1iZkI.js";
9
+ import { r as VERIFICATION_STRATEGY_SOURCES } from "../verification-strategy-CYhDX1rE.js";
5
10
  import "../campaign-BOoc6hc3.js";
6
- import { createHash, randomUUID } from "node:crypto";
7
- import { dirname, join, resolve } from "node:path";
8
- import { tmpdir } from "node:os";
11
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
12
+ import { z } from "zod";
13
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
14
+ import { hostname, tmpdir } from "node:os";
9
15
  import { execFile } from "node:child_process";
10
- import { cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
16
+ import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";
11
17
  import { promisify, stripVTControlCharacters } from "node:util";
12
18
  import { parse, stringify } from "smol-toml";
13
19
  import { setTimeout } from "node:timers/promises";
@@ -42,6 +48,55 @@ function clamp01$1(value) {
42
48
  if (value > 1) return 1;
43
49
  return value;
44
50
  }
51
+ // src/benchmarks/definition.ts
52
+ const text$1 = z.string().min(1).refine((value) => value.trim().length > 0, "must not be blank");
53
+ const source = z.object({
54
+ name: text$1.optional(),
55
+ url: text$1.optional(),
56
+ version: text$1.optional(),
57
+ revision: text$1,
58
+ license: text$1.optional(),
59
+ citation: text$1.optional(),
60
+ rules: text$1.optional(),
61
+ contamination: z.enum([
62
+ "unknown",
63
+ "none-known",
64
+ "suspected",
65
+ "confirmed"
66
+ ]).optional()
67
+ }).strict();
68
+ const schema$1 = z.object({
69
+ schemaVersion: z.literal(1),
70
+ id: text$1,
71
+ source,
72
+ taskIds: z.array(text$1).min(1).refine((ids) => new Set(ids).size === ids.length, "duplicate task ids"),
73
+ metric: z.object({
74
+ name: text$1,
75
+ unit: text$1,
76
+ direction: z.enum(["higher", "lower"]),
77
+ aggregation: text$1,
78
+ range: z.tuple([z.number().finite(), z.number().finite()]).refine(([low, high]) => low < high, "range must have lower < upper").optional(),
79
+ normalization: text$1
80
+ }).strict(),
81
+ verification: z.object({
82
+ strategy: z.enum(VERIFICATION_STRATEGY_SOURCES),
83
+ checker: z.object({
84
+ name: text$1,
85
+ version: text$1,
86
+ pins: z.record(text$1, text$1).optional()
87
+ }).strict(),
88
+ assumptions: z.array(text$1)
89
+ }).strict()
90
+ }).strict();
91
+ /** Synchronous validation for JSON play/manifests; reject lossy or unrecognized identity fields. */
92
+ function defineBenchmark(input) {
93
+ hashCanonical(input);
94
+ return deepFreezeCanonicalJson(schema$1.parse(input));
95
+ }
96
+ /** Uses the stack's canonical JSON owner; changing metric, roster or checker changes identity. */
97
+ function benchmarkDefinitionDigest(input) {
98
+ return hashCanonical(defineBenchmark(input));
99
+ }
45
100
  // src/benchmarks/harbor-environment.ts
46
101
  /**
47
102
  * The docker host lifecycle of a Harbor case: its environment image is built once, before its first
@@ -52,8 +107,17 @@ function clamp01$1(value) {
52
107
  * floor, since that space belongs to the host. `gradeHarborPatch` then names the prepared image
53
108
  * as the task's `docker_image`, so Harbor builds nothing per trial. A `host` is an ssh target:
54
109
  * builds and `docker run` reach it through `DOCKER_HOST`, and Harbor runs there.
110
+ *
111
+ * Each prepared case owns its tag: `harbor-case/<task dir>:<environment digest>-<owner>`, the owner
112
+ * being this machine, this process id and a nonce. Two processes grading the same case on one
113
+ * docker host (two improve passes at once) share the image and its build cache but never a tag, so
114
+ * one pass's release untags only its own name and the other's grades keep their image. Before its
115
+ * space check a preparation removes the case's tags left by dead processes of this machine (a
116
+ * crash or kill leaves them) and shares a live owner's image of the same environment under its own
117
+ * tag; a release removes such dead tags too. Tags of other machines' processes stay, since their
118
+ * liveness is not known here.
55
119
  */
56
- const execute$1 = promisify(execFile);
120
+ const execute$2 = promisify(execFile);
57
121
  /** The environment for docker commands on `host`. */
58
122
  const dockerHostEnv = (host) => host ? {
59
123
  ...process.env,
@@ -64,15 +128,50 @@ const waiters = [];
64
128
  const wake = () => {
65
129
  for (const resume of waiters.splice(0)) resume();
66
130
  };
67
- /** `harbor-case/<task dir>:<digest of every file under environment/>`. */
68
- async function imageTag(item) {
131
+ const MACHINE = createHash("sha256").update(hostname()).digest("hex").slice(0, 6);
132
+ const OWNED = new RegExp(`^[0-9a-f]{16}-${MACHINE}-(\\d+)-[0-9a-f]{4}$`, "u");
133
+ const alive = (pid) => {
134
+ try {
135
+ process.kill(pid, 0);
136
+ return true;
137
+ } catch (error) {
138
+ return error.code === "EPERM";
139
+ }
140
+ };
141
+ /** `harbor-case/<task dir>` and the digest of every file under `environment/`. */
142
+ async function caseImage(item) {
69
143
  const dir = join(item.payload.taskDir, "environment");
70
144
  const digest = createHash("sha256");
71
145
  for (const file of (await readdir(dir, {
72
146
  recursive: true,
73
147
  withFileTypes: true
74
148
  })).filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name)).sort()) digest.update(`${file.slice(dir.length)}\0`).update(await readFile(file));
75
- return `harbor-case/${item.payload.dir.toLowerCase()}:${digest.digest("hex").slice(0, 16)}`;
149
+ return {
150
+ repository: `harbor-case/${item.payload.dir.toLowerCase()}`,
151
+ digest: digest.digest("hex").slice(0, 16)
152
+ };
153
+ }
154
+ /**
155
+ * Remove the case's tags whose owner is a dead process of this machine, and return the tags left.
156
+ * Tags of other machines' processes stay, since their liveness is not known here.
157
+ */
158
+ async function reclaimDead(repository, env) {
159
+ const tags = (await execute$2("docker", [
160
+ "images",
161
+ repository,
162
+ "--format",
163
+ "{{.Tag}}"
164
+ ], { env })).stdout.split("\n").filter(Boolean);
165
+ const dead = (tag) => {
166
+ const pid = Number(OWNED.exec(tag)?.[1] ?? process.pid);
167
+ return pid !== process.pid && !alive(pid);
168
+ };
169
+ for (const tag of tags.filter(dead)) await execute$2("docker", [
170
+ "image",
171
+ "rm",
172
+ `${repository}:${tag}`
173
+ ], { env }).catch(() => void 0);
174
+ return tags.filter((tag) => !dead(tag));
76
175
  }
77
176
  /** The image `gradeHarborPatch` names for a case prepared in this process. */
78
177
  const preparedImage = (item) => live.get(item.payload.taskDir);
@@ -81,23 +180,24 @@ async function freeBytes(host) {
81
180
  "df",
82
181
  "-B1",
83
182
  "--output=avail",
84
- (await execute$1("docker", [
183
+ (await execute$2("docker", [
85
184
  "info",
86
185
  "-f",
87
186
  "{{.DockerRootDir}}"
88
187
  ], { env: dockerHostEnv(host) })).stdout.trim()
89
188
  ];
90
- const { stdout } = await (host ? execute$1("ssh", [host, ...df]) : execute$1("df", df.slice(1)));
189
+ const { stdout } = await (host ? execute$2("ssh", [host, ...df]) : execute$2("df", df.slice(1)));
91
190
  return Number(stdout.trim().split("\n").pop());
92
191
  }
93
192
  async function build(item, options) {
94
193
  const { host, freeFloorBytes = 25 * 2 ** 30, recheckMs = 6e4, signal } = options;
95
194
  const log = options.log ?? ((line) => console.error(line));
96
195
  const env = dockerHostEnv(host);
97
- const image = await imageTag(item);
98
- if (await execute$1("docker", [
99
- "image",
100
- "inspect",
196
+ const { repository, digest } = await caseImage(item);
197
+ const image = `${repository}:${digest}-${`${MACHINE}-${process.pid}-${randomBytes(2).toString("hex")}`}`;
198
+ for (const tag of (await reclaimDead(repository, env)).filter((t) => t.startsWith(`${digest}-`))) if (await execute$2("docker", [
199
+ "tag",
200
+ `${repository}:${tag}`,
101
201
  image
102
202
  ], { env }).then(() => true, () => false)) return image;
103
203
  for (let free = await freeBytes(host); free < freeFloorBytes; free = await freeBytes(host)) {
@@ -106,7 +206,7 @@ async function build(item, options) {
106
206
  await setTimeout(recheckMs, void 0, { signal });
107
207
  }
108
208
  const context = join(item.payload.taskDir, "environment");
109
- await execute$1("docker", [
209
+ await execute$2("docker", [
110
210
  "build",
111
211
  "-q",
112
212
  "-t",
@@ -143,23 +243,26 @@ async function prepareCaseEnvironment(item, options = {}) {
143
243
  return entry.image;
144
244
  }
145
245
  /**
146
- * Remove the case's image and its build cache: the records whose step is the Dockerfile's first
147
- * `RUN` line, and every record built on them. Frees the case's live slot.
246
+ * Remove the case's tag and its build cache: the records whose step is the Dockerfile's first
247
+ * `RUN` line, and every record built on them. Frees the case's live slot. Another owner's tag of
248
+ * the same image keeps that image, and pruning build cache never removes an image.
148
249
  */
149
250
  async function releaseCaseEnvironment(item, options = {}) {
150
- const host = live.get(item.payload.taskDir)?.host ?? options.host;
251
+ const entry = live.get(item.payload.taskDir);
151
252
  live.delete(item.payload.taskDir);
152
253
  wake();
153
- const env = dockerHostEnv(host);
154
- await execute$1("docker", [
254
+ const env = dockerHostEnv(entry?.host ?? options.host);
255
+ const image = await entry?.image.catch(() => void 0);
256
+ if (image) await execute$2("docker", [
155
257
  "image",
156
258
  "rm",
157
- await imageTag(item)
259
+ image
158
260
  ], { env }).catch(() => void 0);
261
+ await reclaimDead((await caseImage(item)).repository, env);
159
262
  const dockerfile = await readFile(join(item.payload.taskDir, "environment/Dockerfile"), "utf8");
160
263
  const marker = /^RUN\s+(.*?)\s*\\?$/mu.exec(dockerfile)?.[1];
161
264
  if (!marker) return;
162
- const { stdout } = await execute$1("docker", [
265
+ const { stdout } = await execute$2("docker", [
163
266
  "buildx",
164
267
  "du",
165
268
  "--format",
@@ -174,7 +277,7 @@ async function releaseCaseEnvironment(item, options = {}) {
174
277
  size = ids.size;
175
278
  for (const r of records) if (r.Parents?.some((id) => ids.has(id))) ids.add(r.ID);
176
279
  }
177
- if (ids.size) await execute$1("docker", [
280
+ if (ids.size) await execute$2("docker", [
178
281
  "buildx",
179
282
  "prune",
180
283
  "-f",
@@ -230,30 +333,35 @@ function deterministicSplit(itemId, seed = BENCHMARK_SPLIT_SEED, cuts = [.6, .8]
230
333
  * is that callback for a code patch: it spawns the Harbor CLI, which starts the containers; this
231
334
  * package starts none itself. A verifier that did not run is an error, never a score of zero.
232
335
  */
233
- const execute = promisify(execFile);
336
+ const execute$1 = promisify(execFile);
234
337
  const table = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
235
338
  const numberOrNull = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
236
339
  const textOrNull = (value) => typeof value === "string" && value.length > 0 ? value : null;
237
340
  /** Read one Harbor task directory. Throws when `task.toml` or `instruction.md` is missing or malformed. */
238
- async function readHarborTask(taskDir) {
341
+ async function readHarborTask(taskDir, relativePath) {
239
342
  const dir = resolve(taskDir);
240
- const config = parse(await readFile(join(dir, "task.toml"), "utf8"));
343
+ const configText = await readFile(join(dir, "task.toml"), "utf8");
344
+ const config = parse(configText);
241
345
  const instruction = await readFile(join(dir, "instruction.md"), "utf8");
242
346
  const task = table(config.task);
243
347
  const agent = table(config.agent);
244
348
  const verifier = table(config.verifier);
245
349
  const environment = table(config.environment);
246
350
  const metadata = table(config.metadata);
247
- const artifacts = (Array.isArray(config.artifacts) ? config.artifacts : []).map((entry, index) => {
351
+ const artifactMappings = (Array.isArray(config.artifacts) ? config.artifacts : []).map((entry, index) => {
248
352
  const source = typeof entry === "string" ? entry : table(entry).source;
249
353
  if (typeof source !== "string" || source.length === 0) throw new Error(`${dir}/task.toml: artifacts[${index}] names no source path`);
250
- return source;
354
+ return {
355
+ ...table(entry),
356
+ source
357
+ };
251
358
  });
252
359
  const environmentFiles = await readdir(join(dir, "environment")).catch(() => []);
253
360
  const name = dir.split("/").pop() ?? dir;
254
361
  return {
255
362
  name: textOrNull(task.name) ?? name,
256
363
  dir: name,
364
+ relativePath,
257
365
  taskDir: dir,
258
366
  instruction,
259
367
  agentTimeoutSec: numberOrNull(agent.timeout_sec),
@@ -265,28 +373,59 @@ async function readHarborTask(taskDir) {
265
373
  storageMb: numberOrNull(environment.storage_mb),
266
374
  gpus: numberOrNull(environment.gpus) ?? 0
267
375
  },
268
- artifacts,
376
+ artifacts: artifactMappings.map((entry) => entry.source),
377
+ artifactMappings,
378
+ config,
379
+ configDigest: `sha256:${createHash("sha256").update(configText).digest("hex")}`,
380
+ metadata,
269
381
  multiContainer: environmentFiles.some((file) => /compose\.ya?ml$/u.test(file)),
270
382
  category: textOrNull(metadata.category),
271
383
  expertTimeEstimateHours: numberOrNull(metadata.expert_time_estimate_hours)
272
384
  };
273
385
  }
386
+ /** Do not descend into a task's own assets or follow directory symlinks during discovery. */
387
+ async function discoverHarborTasks(tasksDir, prefix = "") {
388
+ const entries = await readdir(join(tasksDir, prefix), { withFileTypes: true });
389
+ if (entries.some((entry) => entry.name === "task.toml" && entry.isFile())) {
390
+ if (!prefix) throw new Error(`${tasksDir}: task.toml must be inside a task directory`);
391
+ return [prefix];
392
+ }
393
+ return (await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => discoverHarborTasks(tasksDir, prefix ? `${prefix}/${entry.name}` : entry.name)))).flat().sort();
394
+ }
395
+ async function resolveHarborTask(tasksDir, name) {
396
+ if (!name || isAbsolute(name) || name.includes("\\") || name.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Harbor task path must be a normalized relative path: ${JSON.stringify(name)}`);
397
+ const [root, task] = await Promise.all([realpath(tasksDir), realpath(join(tasksDir, name))]);
398
+ const local = relative(root, task);
399
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local)) throw new Error(`Harbor task path escapes the dataset: ${name}`);
400
+ return task;
401
+ }
274
402
  /** Import a Harbor dataset checkout as a `BenchmarkAdapter` whose scorer is the dataset's own verifier. */
275
403
  function createHarborBenchmarkAdapter(options) {
276
404
  const split = options.assignSplit ?? ((itemId) => deterministicSplit(`${options.id}::${itemId}`));
277
405
  const tasksDir = join(resolve(options.datasetDir), "tasks");
278
406
  async function loadAll() {
279
- const names = options.tasks ?? (await Promise.all((await readdir(tasksDir)).map(async (entry) => await stat(join(tasksDir, entry, "task.toml")).catch(() => null) === null ? null : entry))).filter((entry) => entry !== null).sort();
407
+ const names = options.tasks ?? await discoverHarborTasks(tasksDir);
408
+ if (new Set(names).size !== names.length) throw new Error("Harbor task selection contains duplicate paths");
409
+ if (names.length === 0) throw new Error(`${tasksDir}: no Harbor tasks found`);
280
410
  return Promise.all(names.map(async (dir) => {
281
- const payload = await readHarborTask(join(tasksDir, dir));
411
+ const payload = await readHarborTask(await resolveHarborTask(tasksDir, dir), dir);
412
+ const metadata = payload.metadata ?? {};
413
+ const tags = [
414
+ payload.category,
415
+ metadata.domain,
416
+ metadata.field,
417
+ metadata.subfield,
418
+ ...Array.isArray(metadata.tags) ? metadata.tags : []
419
+ ].filter((tag) => typeof tag === "string" && tag.length > 0);
282
420
  return {
283
421
  id: dir,
284
422
  payload,
285
423
  split: split(dir),
286
424
  family: options.source.name ?? "harbor",
287
425
  taskKind: "harbor-task",
288
- tags: payload.category === null ? [] : [payload.category],
289
- source: options.source
426
+ tags: [...new Set(tags)],
427
+ source: options.source,
428
+ metadata
290
429
  };
291
430
  }));
292
431
  }
@@ -304,12 +443,13 @@ function createHarborBenchmarkAdapter(options) {
304
443
  async evaluate(item, artifact) {
305
444
  const outcome = await options.grade(item, artifact);
306
445
  if (!outcome.succeeded) throw new Error(`${options.id} ${item.id}: the verifier did not score this artifact: ${outcome.error}`);
307
- const { reward, detail } = outcome.value;
446
+ const { reward, detail, raw } = outcome.value;
308
447
  if (!(Number.isFinite(reward) && reward >= 0 && reward <= 1)) throw new Error(`${options.id} ${item.id}: the verifier returned reward ${reward}, outside [0, 1]`);
309
448
  return {
310
449
  score: reward,
311
450
  passed: reward === 1,
312
451
  raw: {
452
+ ...raw,
313
453
  reward,
314
454
  ...detail === void 0 ? {} : { detail }
315
455
  },
@@ -339,8 +479,8 @@ async function remoteHarbor(host, args, run) {
339
479
  const q = (text) => `'${text.replaceAll("'", "'\\''")}'`;
340
480
  const at = (path) => `~/${q(`agent-eval-harbor${path}`)}`;
341
481
  const remote = args.map((arg) => arg === task || arg === jobsDir ? at(arg) : q(arg));
342
- await execute("ssh", [host, `mkdir -p ${at(task)} ${at(jobsDir)}`]);
343
- await execute("rsync", [
482
+ await execute$1("ssh", [host, `mkdir -p ${at(task)} ${at(jobsDir)}`]);
483
+ await execute$1("rsync", [
344
484
  "-a",
345
485
  "--delete",
346
486
  `${task}/`,
@@ -348,13 +488,13 @@ async function remoteHarbor(host, args, run) {
348
488
  ]);
349
489
  const harbor = `cd /tmp && env -u DOCKER_HOST PATH="$HOME/.local/bin:$PATH" harbor`;
350
490
  try {
351
- await execute("ssh", [host, `${harbor} ${remote.join(" ")}`], run);
491
+ await execute$1("ssh", [host, `${harbor} ${remote.join(" ")}`], run);
352
492
  } finally {
353
493
  await mkdir(jobsDir, { recursive: true });
354
494
  const back = [`${host}:agent-eval-harbor${jobsDir}/${job}/`, `${jobsDir}/${job}/`];
355
- await execute("rsync", ["-a", ...back]).catch(() => void 0);
495
+ await execute$1("rsync", ["-a", ...back]).catch(() => void 0);
356
496
  const clean = `rm -rf ${at(dirname(task))} ${at(`${jobsDir}/${job}`)}`;
357
- await execute("ssh", [host, clean]).catch(() => void 0);
497
+ await execute$1("ssh", [host, clean]).catch(() => void 0);
358
498
  }
359
499
  }
360
500
  /**
@@ -413,7 +553,7 @@ function gradeHarborPatch(options = {}) {
413
553
  ];
414
554
  for (let attempt = 1; attempt <= retries + 1; attempt += 1) {
415
555
  const job = `${item.payload.dir}-${randomUUID()}`;
416
- const failure = await (host ? remoteHarbor(host, [...args, job], run) : execute(harborBin, [...args, job], run)).then(() => null, (error) => detailTail(error.message, 500));
556
+ const failure = await (host ? remoteHarbor(host, [...args, job], run) : execute$1(harborBin, [...args, job], run)).then(() => null, (error) => detailTail(error.message, 500));
417
557
  const trial = (await readdir(join(jobsDir, job), { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory()).map((entry) => join(jobsDir, job, entry.name, "/"))[0];
418
558
  const read = (path) => readFile(`${trial}${path}`, "utf8").catch(() => "");
419
559
  const result = table(trial === void 0 ? {} : JSON.parse(await read("result.json") || "{}"));
@@ -447,6 +587,374 @@ function gradeHarborPatch(options = {}) {
447
587
  }
448
588
  };
449
589
  }
590
+ // src/benchmarks/harbor-regrade.ts
591
+ const execute = promisify(execFile);
592
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
593
+ const digest$1 = (text) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
594
+ /**
595
+ * Re-run Harbor's separate verifier on a genuine retained trial. Harbor owns artifact-manifest,
596
+ * coverage and separate-verifier checks. Original and current task identities remain distinct:
597
+ * regrading old outputs with a new verifier does not establish a new agent solve.
598
+ *
599
+ * Protocol source: harbor-framework/harbor@ec6aeab7fe0eb51df52b4e72c524daf5ea9cc5f4,
600
+ * src/harbor/cli/trials.py, trial/regrade.py and models/trial/result.py. No fallback oracle run.
601
+ */
602
+ function gradeHarborTrial(options) {
603
+ if (!options.trialsDir.trim() || !options.rewardKey.trim()) throw new Error("gradeHarborTrial requires a retained trialsDir and rewardKey");
604
+ const redaction = { knownSecrets: Object.values(options.env ?? {}) };
605
+ return async (item, artifact) => {
606
+ try {
607
+ const source = await realpath(artifact.trialDir);
608
+ const sourceText = await readFile(join(source, "result.json"), "utf8");
609
+ const sourceResult = object(JSON.parse(sourceText));
610
+ if (sourceResult.task_name !== item.payload.name || artifact.sourceTrialId !== void 0 && artifact.sourceTrialId !== sourceResult.id || artifact.sourceTaskChecksum !== void 0 && artifact.sourceTaskChecksum !== sourceResult.task_checksum || artifact.sourceResultDigest !== void 0 && artifact.sourceResultDigest !== digest$1(sourceText)) return {
611
+ succeeded: false,
612
+ error: "retained Harbor source trial identity mismatch"
613
+ };
614
+ const parent = await realpath(options.trialsDir);
615
+ const local = relative(source, parent);
616
+ if (local === "" || !local.startsWith(`..${sep}`) && local !== ".." && !isAbsolute(local)) return {
617
+ succeeded: false,
618
+ error: "Harbor regrade output must be outside the source trial"
619
+ };
620
+ const sourceConfig = await readFile(join(source, "config.json"), "utf8").catch((error) => {
621
+ if (error.code === "ENOENT") return null;
622
+ throw error;
623
+ });
624
+ const steps = Array.isArray(sourceResult.step_results) ? sourceResult.step_results : [];
625
+ const manifestPaths = steps.length ? steps.map((step) => {
626
+ const name = object(step).step_name;
627
+ if (typeof name !== "string" || !name || name.includes("/") || name.includes("\\") || name === "." || name === "..") throw new Error("Harbor source has an invalid step name");
628
+ return `steps/${name}/artifacts/manifest.json`;
629
+ }) : ["artifacts/manifest.json"];
630
+ const manifests = await Promise.all(manifestPaths.map(async (path) => {
631
+ const text = await readFile(join(source, path), "utf8");
632
+ return {
633
+ path,
634
+ digest: digest$1(text),
635
+ manifest: JSON.parse(text)
636
+ };
637
+ }));
638
+ const taskConfig = await readFile(join(item.payload.taskDir, "task.toml"), "utf8");
639
+ if (item.payload.configDigest !== void 0 && item.payload.configDigest !== digest$1(taskConfig)) return {
640
+ succeeded: false,
641
+ error: "Harbor verifier task configuration changed since import"
642
+ };
643
+ const original = {
644
+ result: sourceResult,
645
+ resultDigest: digest$1(sourceText),
646
+ config: sourceConfig === null ? null : JSON.parse(sourceConfig),
647
+ configDigest: sourceConfig === null ? null : digest$1(sourceConfig),
648
+ manifests
649
+ };
650
+ const verifierTask = {
651
+ id: item.id,
652
+ source: item.source ?? null,
653
+ taskDir: item.payload.taskDir,
654
+ taskConfigDigest: digest$1(taskConfig),
655
+ config: item.payload.config ?? null
656
+ };
657
+ const name = `regrade-${randomUUID()}`;
658
+ const output = join(parent, name);
659
+ const args = [
660
+ "trial",
661
+ "regrade",
662
+ source,
663
+ "-p",
664
+ item.payload.taskDir,
665
+ "-e",
666
+ options.environment ?? "docker",
667
+ "--trial-name",
668
+ name,
669
+ "--trials-dir",
670
+ parent
671
+ ];
672
+ const attemptPath = join(parent, `${name}.agent-eval-attempt.json`);
673
+ const attempt = {
674
+ command: [options.harborBin ?? "harbor", ...args],
675
+ sourceTrialDir: source,
676
+ trialDir: output,
677
+ original,
678
+ verifierTask,
679
+ rewardKey: options.rewardKey
680
+ };
681
+ const retain = async (extra) => {
682
+ const { value, report } = redact({
683
+ ...attempt,
684
+ ...extra
685
+ }, redaction);
686
+ await writeFile(attemptPath, `${JSON.stringify({
687
+ ...value,
688
+ redaction: report
689
+ }, null, 2)}\n`);
690
+ };
691
+ await retain({ status: "started" });
692
+ let failure;
693
+ try {
694
+ await execute(options.harborBin ?? "harbor", args, {
695
+ env: {
696
+ ...process.env,
697
+ ...options.env
698
+ },
699
+ timeout: options.timeoutMs,
700
+ maxBuffer: 1 << 26
701
+ });
702
+ } catch (error) {
703
+ failure = error instanceof Error ? error.message : String(error);
704
+ }
705
+ let result;
706
+ try {
707
+ result = object(JSON.parse(await readFile(join(output, "result.json"), "utf8")));
708
+ } catch (error) {
709
+ const detail = error instanceof Error ? error.message : String(error);
710
+ const reason = `${failure ? `${failure}; ` : ""}no readable regrade result: ${detail}`;
711
+ await retain({
712
+ status: "unmeasured",
713
+ commandError: failure ?? null,
714
+ error: reason
715
+ });
716
+ return {
717
+ succeeded: false,
718
+ error: redactText(reason, redaction)
719
+ };
720
+ }
721
+ const nativeSource = object(object(result.config).source_trial);
722
+ const bound = nativeSource.action === "regrade" && nativeSource.trial_id === sourceResult.id && typeof nativeSource.path === "string" && resolve(nativeSource.path) === source;
723
+ const { value: raw } = redact({
724
+ sourceTrialDir: source,
725
+ trialDir: output,
726
+ original,
727
+ verifierTask,
728
+ result,
729
+ attemptPath,
730
+ commandError: failure ?? null
731
+ }, redaction);
732
+ if (failure || !bound || result.task_name !== item.payload.name || result.reward_valid !== true) {
733
+ const reason = failure ?? "Harbor regrade has no valid reward or source-trial binding";
734
+ await retain({
735
+ status: "unmeasured",
736
+ result,
737
+ error: reason
738
+ });
739
+ return {
740
+ succeeded: false,
741
+ error: `${redactText(reason, redaction)}; evidence retained at ${attemptPath}`
742
+ };
743
+ }
744
+ const reward = object(object(result.verifier_result).rewards)[options.rewardKey];
745
+ if (typeof reward !== "number" || !Number.isFinite(reward) || reward < 0 || reward > 1) {
746
+ const reason = `Harbor reward ${options.rewardKey} is missing or outside [0, 1]`;
747
+ await retain({
748
+ status: "unmeasured",
749
+ result,
750
+ error: reason
751
+ });
752
+ return {
753
+ succeeded: false,
754
+ error: `${reason}; evidence retained at ${attemptPath}`
755
+ };
756
+ }
757
+ await retain({
758
+ status: "measured",
759
+ result,
760
+ reward
761
+ });
762
+ return {
763
+ succeeded: true,
764
+ value: {
765
+ reward,
766
+ raw,
767
+ detail: `Harbor regrade retained at ${output}`
768
+ }
769
+ };
770
+ } catch (error) {
771
+ return {
772
+ succeeded: false,
773
+ error: redactText(error instanceof Error ? error.message : String(error), redaction)
774
+ };
775
+ }
776
+ };
777
+ }
778
+ // src/benchmarks/result.ts
779
+ const text = z.string().min(1).refine((value) => value.trim().length > 0, "must not be blank");
780
+ const digest = z.string().regex(/^sha256:[0-9a-f]{64}$/);
781
+ const schema = z.object({
782
+ schemaVersion: z.literal(1),
783
+ definitionDigest: digest,
784
+ taskId: text,
785
+ artifactDigest: digest,
786
+ evaluation: z.object({
787
+ score: z.number().finite().min(0).max(1),
788
+ passed: z.boolean(),
789
+ dimensions: z.record(z.string(), z.number().finite()).optional(),
790
+ raw: z.record(z.string(), z.unknown()).refine((raw) => Object.keys(raw).length > 0, "raw evidence required"),
791
+ notes: z.string().optional(),
792
+ certification: z.object({
793
+ strategy: z.enum(VERIFICATION_STRATEGY_SOURCES),
794
+ checker: z.object({
795
+ name: text,
796
+ version: text,
797
+ pins: z.record(text, text).optional()
798
+ }).strict(),
799
+ assumptions: z.array(text),
800
+ evidenceDigest: text
801
+ }).strict().optional()
802
+ }).strict()
803
+ }).strict();
804
+ /**
805
+ * Validate retained JSON without executing a checker. With a definition, also bind the task,
806
+ * metric and claimed checker. Validation cannot authenticate an untrusted producer's attestation.
807
+ */
808
+ function defineBenchmarkResult(input, definition) {
809
+ hashCanonical(input);
810
+ const result = schema.parse(input);
811
+ if (definition) {
812
+ const expected = defineBenchmark(definition);
813
+ if (result.definitionDigest !== benchmarkDefinitionDigest(expected)) throw new Error("benchmark result definition digest mismatch");
814
+ if (!expected.taskIds.includes(result.taskId)) throw new Error("benchmark result task is outside the frozen roster");
815
+ const certification = result.evaluation.certification;
816
+ if (certification && (certification.strategy !== expected.verification.strategy || hashCanonical(certification.checker) !== hashCanonical(expected.verification.checker) || hashCanonical(certification.assumptions) !== hashCanonical(expected.verification.assumptions))) throw new Error("benchmark result certification checker mismatch");
817
+ }
818
+ if (result.evaluation.certification && result.evaluation.certification.evidenceDigest !== benchmarkResultEvidenceDigest(result)) throw new Error("benchmark result certification evidence digest mismatch");
819
+ return result;
820
+ }
821
+ /** Bind identities and the complete measurement, excluding the certificate's own digest. */
822
+ function benchmarkResultEvidenceDigest(result) {
823
+ const { certification: _certification, ...evaluation } = result.evaluation;
824
+ return certificationEvidenceDigest({
825
+ definitionDigest: result.definitionDigest,
826
+ taskId: result.taskId,
827
+ artifactDigest: result.artifactDigest,
828
+ evaluation
829
+ });
830
+ }
831
+ /** Wrap an already executed evaluation; never invent a certification from a planned definition. */
832
+ function benchmarkResult(input) {
833
+ return defineBenchmarkResult({
834
+ schemaVersion: 1,
835
+ definitionDigest: benchmarkDefinitionDigest(input.definition),
836
+ taskId: input.taskId,
837
+ artifactDigest: input.artifactDigest,
838
+ evaluation: input.evaluation
839
+ }, input.definition);
840
+ }
841
+ // src/benchmarks/native.ts
842
+ /**
843
+ * Bind an existing native grader without replacing its protocol. The checker explicitly projects
844
+ * native scores into [0, 1], returns pass/fail separately, and retains native measurements in raw.
845
+ * Execution, hidden-reference staging, model transport and spend remain the caller's responsibility.
846
+ */
847
+ function createNativeBenchmarkAdapter(options) {
848
+ const definition = defineBenchmark(options.definition);
849
+ const definitionDigest = benchmarkDefinitionDigest(definition);
850
+ if (!options.implementationRef.trim()) throw new Error("native benchmark requires an implementationRef");
851
+ const evaluationRef = hashCanonical({
852
+ definitionDigest,
853
+ implementationRef: options.implementationRef
854
+ });
855
+ const checker = options.checker;
856
+ const checkIdentity = () => {
857
+ if (checker.strategy !== definition.verification.strategy || hashCanonical(checker.identity) !== hashCanonical(definition.verification.checker)) throw new Error("native benchmark checker does not match its definition");
858
+ };
859
+ checkIdentity();
860
+ const load = options.load;
861
+ const splitPolicy = options.assignSplit;
862
+ const digestArtifact = options.artifactDigest ?? hashCanonical;
863
+ const roster = new Set(definition.taskIds);
864
+ const admitted = /* @__PURE__ */ new Map();
865
+ let snapshot;
866
+ const loadAll = async () => {
867
+ snapshot ??= (async () => {
868
+ const items = await load();
869
+ const ids = new Set(items.map((item) => item.id));
870
+ if (ids.size !== items.length || ids.size !== roster.size || [...ids].some((id) => !roster.has(id))) throw new Error(`native benchmark ${definition.id}: loaded task roster differs from its definition`);
871
+ return items.map((item) => {
872
+ if (item.source?.revision !== void 0 && item.source.revision !== definition.source.revision) throw new Error(`native benchmark ${definition.id}: source revision mismatch for ${item.id}`);
873
+ const split = item.split ?? splitPolicy?.(item.id);
874
+ if (!split || ![
875
+ "search",
876
+ "dev",
877
+ "holdout"
878
+ ].includes(split)) throw new Error(`native benchmark ${definition.id}: no explicit valid split for ${item.id}`);
879
+ const value = {
880
+ ...item,
881
+ source: item.source ?? definition.source,
882
+ split
883
+ };
884
+ const digest = hashCanonical(value);
885
+ const frozen = deepFreezeCanonicalJson(structuredClone(value));
886
+ admitted.set(item.id, {
887
+ item: frozen,
888
+ digest
889
+ });
890
+ return frozen;
891
+ });
892
+ })();
893
+ return [...await snapshot];
894
+ };
895
+ const evaluateResult = async (item, artifact) => {
896
+ await loadAll();
897
+ if (admitted.get(item.id)?.digest !== hashCanonical(item)) throw new Error(`native benchmark ${definition.id}: item differs from the admitted task snapshot: ${item.id}`);
898
+ checkIdentity();
899
+ const artifactDigest = await digestArtifact(artifact);
900
+ if (!/^sha256:[0-9a-f]{64}$/.test(artifactDigest)) throw new Error("native benchmark artifact digest must be sha256");
901
+ const outcome = await checker.check({
902
+ item: admitted.get(item.id).item,
903
+ artifact
904
+ });
905
+ if (!outcome.succeeded) throw new Error(`${definition.id} ${item.id}: native checker failed: ${outcome.error}`);
906
+ if (await digestArtifact(artifact) !== artifactDigest) throw new Error(`${definition.id} ${item.id}: artifact changed during verification`);
907
+ const result = outcome.value;
908
+ if (!result.raw || typeof result.raw !== "object" || Array.isArray(result.raw) || Object.keys(result.raw).length === 0) throw new Error(`${definition.id} ${item.id}: native checker must retain raw measurement evidence`);
909
+ const { certification, ...measurement } = result;
910
+ const receipt = benchmarkResult({
911
+ definition,
912
+ taskId: item.id,
913
+ artifactDigest,
914
+ evaluation: {
915
+ ...measurement,
916
+ raw: {
917
+ measurement: result.raw,
918
+ binding: {
919
+ definitionDigest,
920
+ taskId: item.id,
921
+ artifactDigest,
922
+ evaluationRef
923
+ }
924
+ }
925
+ }
926
+ });
927
+ receipt.evaluation.certification = certification ?? {
928
+ strategy: checker.strategy,
929
+ checker: structuredClone(checker.identity),
930
+ assumptions: [...definition.verification.assumptions],
931
+ evidenceDigest: benchmarkResultEvidenceDigest(receipt)
932
+ };
933
+ return deepFreezeCanonicalJson(defineBenchmarkResult(receipt, definition));
934
+ };
935
+ return {
936
+ id: definition.id,
937
+ definition,
938
+ evaluationRef,
939
+ source: definition.source,
940
+ family: options.family ?? "custom",
941
+ taskKind: options.taskKind ?? "custom",
942
+ defaultMetric: definition.metric.name,
943
+ loadAll,
944
+ assignSplit(id) {
945
+ const split = admitted.get(id)?.item.split;
946
+ if (!split) throw new Error(`native benchmark: load the task snapshot before assigning split for ${id}`);
947
+ return split;
948
+ },
949
+ async loadDataset(split) {
950
+ return (await loadAll()).filter((item) => item.split === split);
951
+ },
952
+ evaluateResult,
953
+ async evaluate(item, artifact) {
954
+ return (await evaluateResult(item, artifact)).evaluation;
955
+ }
956
+ };
957
+ }
450
958
  // src/benchmarks/routing/dataset.ts
451
959
  const ROUTING_DATASET = [
452
960
  {
@@ -639,9 +1147,12 @@ const assignSplit = adapter.assignSplit.bind(adapter);
639
1147
  // src/benchmarks/runner.ts
640
1148
  async function runBenchmarkAdapter(options) {
641
1149
  const storage = options.storage ?? fsCampaignStorage();
1150
+ if (options.dispatchRef !== void 0 && !options.dispatchRef.trim()) throw new Error("benchmark dispatchRef must not be blank");
1151
+ if (options.adapter.definition && options.resumable !== false && !options.dispatchRef) throw new Error("resumable defined benchmarks require an explicit responder dispatchRef");
642
1152
  const benchmarkId = benchmarkIdFor(options.adapter);
643
1153
  const scenarios = await benchmarkScenarios(options.adapter, options.splits);
644
1154
  const judge = benchmarkJudge(options.adapter);
1155
+ const definitionDigest = options.adapter.definition ? benchmarkDefinitionDigest(options.adapter.definition) : void 0;
645
1156
  const dispatch = async (scenario, context) => {
646
1157
  return options.respond({
647
1158
  scenario,
@@ -652,7 +1163,12 @@ async function runBenchmarkAdapter(options) {
652
1163
  const campaign = await runCampaign({
653
1164
  scenarios,
654
1165
  dispatch,
655
- dispatchRef: `benchmark:${benchmarkId}`,
1166
+ dispatchRef: [
1167
+ `benchmark:${benchmarkId}`,
1168
+ definitionDigest,
1169
+ options.adapter.evaluationRef,
1170
+ options.dispatchRef
1171
+ ].filter((part) => part !== void 0).join(":"),
656
1172
  judges: [judge],
657
1173
  seed: options.seed,
658
1174
  reps: options.reps,
@@ -720,6 +1236,7 @@ function benchmarkJudge(adapter) {
720
1236
  const benchmarkId = benchmarkIdFor(adapter);
721
1237
  return {
722
1238
  name: `${benchmarkId}:score`,
1239
+ ...adapter.evaluationRef ? { judgeVersion: adapter.evaluationRef } : {},
723
1240
  dimensions: [{
724
1241
  key: "score",
725
1242
  description: `Primary ${benchmarkId} benchmark score`
@@ -731,35 +1248,52 @@ function benchmarkJudge(adapter) {
731
1248
  return scenario.kind === "benchmark" && scenario.id.startsWith(`${benchmarkId}:`);
732
1249
  },
733
1250
  async score({ artifact, scenario }) {
734
- const evaluation = await adapter.evaluate(scenario.item, artifact);
1251
+ const receipt = adapter.evaluateResult ? defineBenchmarkResult(await adapter.evaluateResult(scenario.item, artifact), adapter.definition) : void 0;
1252
+ const evaluation = receipt?.evaluation ?? await adapter.evaluate(scenario.item, artifact);
1253
+ if (!Number.isFinite(evaluation.score) || evaluation.score < 0 || evaluation.score > 1) throw new Error(`${benchmarkId}: invalid normalized benchmark score ${evaluation.score}`);
1254
+ if (adapter.definition && typeof evaluation.passed !== "boolean") throw new Error(`${benchmarkId}: defined benchmarks require an explicit pass/fail projection`);
735
1255
  return {
736
1256
  dimensions: normalizeEvaluationDimensions(evaluation),
737
1257
  composite: clamp01(evaluation.score),
738
- notes: evaluation.notes ?? ""
1258
+ notes: evaluation.notes ?? "",
1259
+ evidence: {
1260
+ benchmarkId,
1261
+ ...adapter.evaluationRef ? { evaluationRef: adapter.evaluationRef } : {},
1262
+ ...receipt ? { benchmarkResult: receipt } : { evaluation }
1263
+ },
1264
+ ...evaluation.certification ? { certification: evaluation.certification } : {}
739
1265
  };
740
1266
  }
741
1267
  };
742
1268
  }
743
1269
  function summarizeBenchmarkCampaign(input) {
744
1270
  const scenarioById = new Map(input.scenarios.map((scenario) => [scenario.id, scenario]));
745
- const successful = input.campaign.cells.map((cell) => {
1271
+ const rows = input.campaign.cells.map((cell) => {
746
1272
  const scenario = scenarioById.get(cell.scenarioId);
747
1273
  const judge = firstJudgeScore(cell.judgeScores);
748
- const score = judge?.composite ?? 0;
1274
+ const measured = judge !== void 0 && !judge.failed && Number.isFinite(judge.composite);
1275
+ const score = measured ? judge.composite : NaN;
749
1276
  return {
750
1277
  cell,
751
1278
  scenario,
752
1279
  score,
1280
+ measured,
753
1281
  passed: (judge?.dimensions.passed ?? (score > 0 ? 1 : 0)) >= 1,
754
1282
  dimensions: judge?.dimensions ?? {}
755
1283
  };
756
- }).filter((row) => !row.cell.error);
1284
+ });
1285
+ const successful = rows.filter((row) => !row.cell.error && row.measured);
757
1286
  const scoreValues = successful.map((row) => row.score);
758
1287
  return {
759
1288
  benchmarkId: benchmarkIdFor(input.adapter),
760
1289
  family: input.adapter.family ?? "custom",
761
1290
  taskKind: input.adapter.taskKind ?? "custom",
762
1291
  ...input.adapter.source ? { source: input.adapter.source } : {},
1292
+ ...input.adapter.definition ? {
1293
+ definition: input.adapter.definition,
1294
+ definitionDigest: benchmarkDefinitionDigest(input.adapter.definition)
1295
+ } : {},
1296
+ ...input.adapter.evaluationRef ? { evaluationRef: input.adapter.evaluationRef } : {},
763
1297
  runDir: input.campaign.runDir,
764
1298
  manifestHash: input.campaign.manifestHash,
765
1299
  seed: input.campaign.seed,
@@ -767,7 +1301,11 @@ function summarizeBenchmarkCampaign(input) {
767
1301
  endedAt: input.campaign.endedAt,
768
1302
  durationMs: input.campaign.durationMs,
769
1303
  totalItems: input.scenarios.length,
1304
+ scoreAggregation: "mean-normalized-score",
1305
+ nativeAggregation: "not-computed",
770
1306
  totalCells: input.campaign.cells.length,
1307
+ cellsMeasured: successful.length,
1308
+ cellsUnmeasured: rows.length - successful.length,
771
1309
  cellsFailed: input.campaign.aggregates.cellsFailed,
772
1310
  cellsCached: input.campaign.aggregates.cellsCached,
773
1311
  totalCostUsd: input.campaign.aggregates.cost.totalCostUsd,
@@ -795,9 +1333,11 @@ function renderBenchmarkReportMarkdown(report) {
795
1333
  `- task kind: ${report.taskKind}`,
796
1334
  `- run dir: ${report.runDir}`,
797
1335
  `- manifest: ${report.manifestHash}`,
798
- `- cells: ${report.totalCells} total, ${report.cellsFailed} failed, ${report.cellsCached} cached`,
1336
+ `- cells: ${report.totalCells} total, ${report.cellsMeasured} measured, ${report.cellsUnmeasured} unmeasured, ${report.cellsFailed} failed, ${report.cellsCached} cached`,
1337
+ ...report.definitionDigest ? [`- definition: ${report.definitionDigest}`] : [],
1338
+ `- aggregation: ${report.scoreAggregation}; native aggregation: ${report.nativeAggregation}`,
799
1339
  `- cost: $${fmt(report.totalCostUsd)}`,
800
- `- score: mean ${fmt(report.score.mean)}, median ${fmt(report.score.median)}, p90 ${fmt(report.score.p90)}, n=${report.score.n}`,
1340
+ report.score.n === 0 ? "- score: unmeasured (n=0)" : `- normalized score: mean ${fmt(report.score.mean)}, median ${fmt(report.score.median)}, p90 ${fmt(report.score.p90)}, n=${report.score.n}`,
801
1341
  "",
802
1342
  "## Splits",
803
1343
  "",
@@ -818,7 +1358,7 @@ function benchmarkIdFor(adapter) {
818
1358
  }
819
1359
  function normalizeEvaluationDimensions(evaluation) {
820
1360
  const dimensions = { score: clamp01(evaluation.score) };
821
- for (const [key, value] of Object.entries(evaluation.dimensions ?? {})) if (Number.isFinite(value)) dimensions[key] = value;
1361
+ for (const [key, value] of Object.entries(evaluation.dimensions ?? {})) if (key !== "score" && key !== "passed" && Number.isFinite(value)) dimensions[key] = value;
822
1362
  dimensions.passed = evaluation.passed ?? evaluation.score > 0 ? 1 : 0;
823
1363
  return dimensions;
824
1364
  }
@@ -1099,6 +1639,6 @@ function discountedGain(relevance, zeroBasedRank) {
1099
1639
  if (relevance <= 0) return 0;
1100
1640
  return (2 ** relevance - 1) / Math.log2(zeroBasedRank + 2);
1101
1641
  }
1102
- export { BENCHMARK_SPLIT_SEED, benchmarkJudge, benchmarkScenarios, buildStandardRetrievalItems, calibrateBenchmarkMetric, createHarborBenchmarkAdapter, createRetrievalIdBenchmarkAdapter, deterministicSplit, dockerHostEnv, evaluateStandardRetrieval, gradeHarborPatch, parseBeirCorpusJsonl, parseBeirQueriesJsonl, parseQrels, prepareCaseEnvironment, releaseCaseEnvironment, routing_exports as routing, runBenchmarkAdapter };
1642
+ export { BENCHMARK_SPLIT_SEED, benchmarkDefinitionDigest, benchmarkJudge, benchmarkResult, benchmarkResultEvidenceDigest, benchmarkScenarios, buildStandardRetrievalItems, calibrateBenchmarkMetric, createHarborBenchmarkAdapter, createNativeBenchmarkAdapter, createRetrievalIdBenchmarkAdapter, defineBenchmark, defineBenchmarkResult, deterministicSplit, dockerHostEnv, evaluateStandardRetrieval, gradeHarborPatch, gradeHarborTrial, parseBeirCorpusJsonl, parseBeirQueriesJsonl, parseQrels, prepareCaseEnvironment, releaseCaseEnvironment, routing_exports as routing, runBenchmarkAdapter };
1103
1643
 
1104
1644
  //# sourceMappingURL=index.js.map