@tangle-network/agent-eval 0.126.1 → 0.126.3

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.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  fsCampaignStorage,
3
3
  runCampaign
4
- } from "./chunk-UCLVDLCH.js";
4
+ } from "./chunk-ZVCHKKOP.js";
5
5
  import {
6
6
  __export
7
7
  } from "./chunk-PZ5AY32C.js";
@@ -763,4 +763,4 @@ export {
763
763
  retrievalMetricsAtCutoff,
764
764
  benchmarks_exports
765
765
  };
766
- //# sourceMappingURL=chunk-W4L6C2XT.js.map
766
+ //# sourceMappingURL=chunk-CGG5SLH3.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  summarizeBackendIntegrity
3
- } from "./chunk-UCLVDLCH.js";
3
+ } from "./chunk-ZVCHKKOP.js";
4
4
  import {
5
5
  paretoChart
6
6
  } from "./chunk-DPZAEKA6.js";
@@ -1006,4 +1006,4 @@ export {
1006
1006
  summarizeExecution,
1007
1007
  analyzeRuns
1008
1008
  };
1009
- //# sourceMappingURL=chunk-SDPM6554.js.map
1009
+ //# sourceMappingURL=chunk-K6IAZZ6L.js.map
@@ -7,7 +7,7 @@ import {
7
7
  pairHoldout,
8
8
  recoverTruncatedJson,
9
9
  surfaceContentHash
10
- } from "./chunk-VMUENW6F.js";
10
+ } from "./chunk-3I74FLK6.js";
11
11
  import {
12
12
  SearchLedgerConflictError,
13
13
  SearchLedgerError,
@@ -19,7 +19,7 @@ import {
19
19
  runCampaign,
20
20
  summarizeBackendIntegrity,
21
21
  withSearchLedgerFileLock
22
- } from "./chunk-UCLVDLCH.js";
22
+ } from "./chunk-ZVCHKKOP.js";
23
23
  import {
24
24
  Mutex
25
25
  } from "./chunk-WGXIEX7P.js";
@@ -4634,4 +4634,4 @@ export {
4634
4634
  verifyCodeSurface,
4635
4635
  resolveWorktreePath
4636
4636
  };
4637
- //# sourceMappingURL=chunk-NGUYT5CI.js.map
4637
+ //# sourceMappingURL=chunk-P6WN2KF5.js.map
@@ -815,6 +815,7 @@ async function runCampaign(opts) {
815
815
  let nextIdx = 0;
816
816
  const cellsRef = cells;
817
817
  let firstLaneError;
818
+ let firstCellFailure;
818
819
  for (let i = 0; i < maxConcurrency; i++) {
819
820
  lanes.push(
820
821
  (async () => {
@@ -837,7 +838,13 @@ async function runCampaign(opts) {
837
838
  dispatchShutdownTimeoutMs,
838
839
  costLedger,
839
840
  costPhase,
840
- runAttemptId
841
+ runAttemptId,
842
+ onFailure: opts.abortOnCellError ? (failure) => {
843
+ if (firstCellFailure === void 0) {
844
+ firstCellFailure = failure;
845
+ campaignAbort.abort(failure.cause);
846
+ }
847
+ } : void 0
841
848
  });
842
849
  cellsRef.push(result.cell);
843
850
  Object.assign(artifactsByPath, result.artifactsByPath);
@@ -854,6 +861,9 @@ async function runCampaign(opts) {
854
861
  );
855
862
  });
856
863
  }
864
+ if (opts.abortOnCellError && result.failure) {
865
+ return;
866
+ }
857
867
  }
858
868
  } catch (error) {
859
869
  if (firstLaneError === void 0) {
@@ -870,6 +880,7 @@ async function runCampaign(opts) {
870
880
  const failedLane = laneResults.find(
871
881
  (result) => result.status === "rejected"
872
882
  );
883
+ if (firstCellFailure) throw firstCellFailure.cause;
873
884
  if (failedLane) throw firstLaneError ?? failedLane.reason;
874
885
  const endedAt = now();
875
886
  cellsRef.sort((a, b) => a.cellId.localeCompare(b.cellId));
@@ -999,6 +1010,8 @@ async function executeCell(args) {
999
1010
  };
1000
1011
  let artifact;
1001
1012
  let errorMessage;
1013
+ let failure;
1014
+ let fatalCellError;
1002
1015
  let dispatched;
1003
1016
  const timeoutMs = args.dispatchTimeoutMs;
1004
1017
  let timeoutTimer;
@@ -1038,6 +1051,7 @@ async function executeCell(args) {
1038
1051
  }
1039
1052
  } catch (err) {
1040
1053
  errorMessage = err instanceof Error ? err.message : String(err);
1054
+ failure = { stage: "dispatch", cause: err };
1041
1055
  } finally {
1042
1056
  if (timeoutTimer) clearTimeout(timeoutTimer);
1043
1057
  removeAbortListener();
@@ -1106,16 +1120,22 @@ async function executeCell(args) {
1106
1120
  });
1107
1121
  judgeScores[judge.name] = score;
1108
1122
  } catch (err) {
1109
- if (err instanceof CostAccountingIncompleteError) {
1110
- await trace.flush();
1111
- throw err;
1112
- }
1113
1123
  errorMessage = `judge '${judge.name}' failed: ${err instanceof Error ? err.message : String(err)}`;
1124
+ failure = { stage: "judge", judge: judge.name, cause: err };
1125
+ if (err instanceof CostAccountingIncompleteError) fatalCellError = err;
1114
1126
  break;
1115
1127
  }
1116
1128
  }
1117
1129
  }
1118
- await trace.flush();
1130
+ if (failure) {
1131
+ await waitForFailedCellCostSettlement({
1132
+ costLedger: args.costLedger,
1133
+ costPhase: args.costPhase,
1134
+ costTags,
1135
+ cellId: args.slot.cellId,
1136
+ timeoutMs: args.dispatchShutdownTimeoutMs
1137
+ });
1138
+ }
1119
1139
  const costCallIds = args.costLedger.list({ tags: costTags }).map((receipt) => receipt.callId).sort();
1120
1140
  const cell = {
1121
1141
  manifestHash: args.manifestHash,
@@ -1136,10 +1156,58 @@ async function executeCell(args) {
1136
1156
  cached: false,
1137
1157
  error: errorMessage
1138
1158
  };
1159
+ if (failure) {
1160
+ const failurePath = join3(cellDir, "failure-receipt.json");
1161
+ const receipt = {
1162
+ schemaVersion: 1,
1163
+ runAttemptId: args.runAttemptId,
1164
+ recordedAt: args.now().toISOString(),
1165
+ failure: {
1166
+ stage: failure.stage,
1167
+ ...failure.judge ? { judge: failure.judge } : {},
1168
+ error: serializeCellError(failure.cause)
1169
+ },
1170
+ cell,
1171
+ cost: args.costLedger.summary({ phase: args.costPhase, tags: costTags })
1172
+ };
1173
+ storage.write(failurePath, JSON.stringify(receipt, null, 2));
1174
+ artifactsByPath[`${args.slot.cellId}/failure-receipt.json`] = failurePath;
1175
+ args.onFailure?.(failure);
1176
+ }
1177
+ await trace.flush();
1139
1178
  if (!errorMessage && args.resumable) {
1140
1179
  storage.write(cachePath, JSON.stringify(cell));
1141
1180
  }
1142
- return { cell, artifactsByPath };
1181
+ if (fatalCellError !== void 0) throw fatalCellError;
1182
+ return { cell, artifactsByPath, ...failure ? { failure } : {} };
1183
+ }
1184
+ async function waitForFailedCellCostSettlement(input) {
1185
+ const filter = { phase: input.costPhase, tags: input.costTags };
1186
+ if (input.costLedger.summary(filter).pendingCalls === 0) return;
1187
+ if (typeof input.costLedger.waitForIdle !== "function") {
1188
+ throw new CostAccountingIncompleteError(
1189
+ `cost ledger for failed cell '${input.cellId}' cannot prove that paid calls stopped`
1190
+ );
1191
+ }
1192
+ const settled = await input.costLedger.waitForIdle({
1193
+ timeoutMs: input.timeoutMs,
1194
+ filter
1195
+ });
1196
+ if (!settled || input.costLedger.summary(filter).pendingCalls > 0) {
1197
+ throw new CostAccountingIncompleteError(
1198
+ `paid calls for failed cell '${input.cellId}' did not settle within ${input.timeoutMs}ms; no complete failure receipt was produced`
1199
+ );
1200
+ }
1201
+ }
1202
+ function serializeCellError(error) {
1203
+ if (error instanceof Error) {
1204
+ return {
1205
+ name: error.name,
1206
+ message: error.message,
1207
+ ...error.stack ? { stack: error.stack } : {}
1208
+ };
1209
+ }
1210
+ return { name: "NonErrorThrown", message: String(error) };
1143
1211
  }
1144
1212
  function settlesWithin(promise, timeoutMs) {
1145
1213
  return new Promise((resolve) => {
@@ -1464,4 +1532,4 @@ export {
1464
1532
  runCampaign,
1465
1533
  planCampaignRun
1466
1534
  };
1467
- //# sourceMappingURL=chunk-UCLVDLCH.js.map
1535
+ //# sourceMappingURL=chunk-ZVCHKKOP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/campaign/run-campaign.ts","../src/integrity/backend-integrity.ts","../src/verdict-cache.ts","../src/campaign/coverage.ts","../src/campaign/run-dir.ts","../src/campaign/storage.ts","../src/campaign/search-ledger-file.ts","../src/campaign/atomic-file-lock.ts","../src/campaign/search-ledger-errors.ts"],"sourcesContent":["/**\n * `runCampaign` — Pass A substrate primitive. ONE function that orchestrates\n * scenarios → dispatch → artifacts → judges → aggregates, with full\n * reproducibility (seed + manifest hash), cell-level resumability, bootstrap\n * CIs, and the `LabeledScenarioStore` capture flywheel.\n *\n * Improvement loops (optimizer / gate / autoOnPromote) ride on top of this\n * primitive but live in `presets/run-improvement-loop.ts`. This file keeps\n * the core orchestrator minimal — Phase 1 of the Pass A track.\n */\n\nimport { join } from 'node:path'\nimport {\n CostAccountingIncompleteError,\n type CostLedgerHandle,\n type CostLedgerSummary,\n} from '../cost-ledger'\nimport { BackendIntegrityError, type BackendIntegrityReport } from '../integrity/backend-integrity'\nimport { confidenceInterval } from '../statistics'\nimport { contentHash } from '../verdict-cache'\nimport { assertCampaignDesign, campaignScenarioIdentity, campaignSplitDigest } from './coverage'\nimport { resolveRunDir } from './run-dir'\nimport { type CampaignStorage, createRunCostLedger, fsCampaignStorage } from './storage'\nimport type {\n CampaignAggregates,\n CampaignArtifactWriter,\n CampaignCellResult,\n CampaignCostMeter,\n CampaignResult,\n CampaignTokenUsage,\n CampaignTraceWriter,\n DispatchContext,\n DispatchFn,\n JudgeAggregate,\n JudgeConfig,\n JudgeScore,\n LabeledScenarioStore,\n Scenario,\n ScenarioAggregate,\n TraceSpan,\n} from './types'\n\nexport interface RunCampaignOptions<TScenario extends Scenario, TArtifact> {\n scenarios: TScenario[]\n dispatch: DispatchFn<TScenario, TArtifact>\n /** Abort active dispatches when the owning operation is cancelled. */\n signal?: AbortSignal\n /**\n * Stable identity for the dispatch behavior, included in the manifest/cache\n * key. Set this when the same function name can run different models,\n * prompts, tools, or external config.\n */\n dispatchRef?: string\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Required for reproducibility. Default 42. */\n seed?: number\n /** Per-scenario replicates for CI bands. Default 1; raise to 5+ for\n * bootstrap-tight intervals on critical eval. */\n reps?: number\n /** When true (default), completed cells are cached by\n * (manifestHash, scenarioId, rep, generation). Re-runs skip cached cells. */\n resumable?: boolean\n /** Optional store — when present, every artifact + judge score is captured\n * with the configured `captureSource`. Capture is default ON; pass `'off'`\n * to disable. */\n labeledStore?: LabeledScenarioStore | 'off'\n captureSource?: 'production-trace' | 'eval-run' | 'manual' | 'red-team' | 'synthetic'\n captureSourceVersionHash?: string\n /** Hard spend cap. Each paid call reserves its enforced maximum before dispatch. */\n costCeiling?: number\n /** Shared spend account. Improvement loops pass one ledger through every\n * campaign so the ceiling and returned total are run-wide. */\n costLedger?: CostLedgerHandle\n /** Attribution label for receipts recorded by this campaign. */\n costPhase?: string\n /** Additional immutable receipt tags supplied by an owning workflow. */\n costTags?: Readonly<Record<string, string>>\n /** Max concurrent cells. Default 2. */\n maxConcurrency?: number\n /**\n * Stop after the first dispatch or judge error. The failed cell is persisted\n * before active sibling cells are aborted and drained, then the campaign\n * rejects with the exact error thrown by that dispatch or judge.\n * Default false preserves the normal behavior of returning failed cells and\n * continuing the remaining schedule.\n */\n abortOnCellError?: boolean\n /**\n * Per-cell dispatch deadline in ms. A `dispatch` that neither resolves nor\n * rejects within this window is a hang (a stalled model request, an\n * exhausted runtime resource, a backend that never closes its stream). When\n * set, the cell's `ctx.signal` is aborted. A dispatch that stops is recorded\n * as an error (`dispatch exceeded <N>ms`). A dispatch that ignores\n * cancellation rejects the campaign without publishing incomplete cost data.\n * `undefined`/`0` means unbounded.\n */\n dispatchTimeoutMs?: number\n /**\n * Time allowed for an aborted dispatch and its paid calls to stop before the\n * campaign rejects without producing a result. Default 5 seconds.\n */\n dispatchShutdownTimeoutMs?: number\n /** Required: where artifacts + traces land. A bare name (not an absolute path)\n * resolves to the shared `~/.tangle/traces/<repo>/runs/<name>` root so run\n * bundles never pollute a repo working tree. Pass an absolute path to override. */\n runDir: string\n /** Subject repo for the shared run-dir root (defaults to the CWD basename).\n * Only consulted when `runDir` is a bare name. */\n repo?: string\n /** Tracing posture. Default is the substrate's `FileSystemTraceStore` rooted\n * at `<runDir>/traces/`. `'off'` disables capture entirely — substrate\n * refuses this when the caller wires `autoOnPromote !== 'none'`. */\n tracing?: 'on' | 'off'\n /**\n * Per-cell usage expectation — the early, fine-grained sibling of the\n * batch `assertRealBackend` guard. A cell that produced an artifact (no\n * error) but reported `costUsd === 0` AND zero tokens is a stub: the\n * dispatch never reported LLM activity via `ctx.cost`. Modes:\n * - `'warn'` (default) — log the offending cell loudly, keep going.\n * - `'assert'` — throw `BackendIntegrityError` on the first such cell\n * (fail-fast; recommended for CI campaigns expecting real LLM calls).\n * - `'off'` — no check (replay / deterministic-only / offline analysis).\n */\n expectUsage?: 'assert' | 'warn' | 'off'\n /** Test seam — override the wall clock for deterministic tests. */\n now?: () => Date\n /** Test seam — override per-cell trace writer factory. */\n buildTraceWriter?: (cellId: string, dir: string) => CampaignTraceWriter\n /** Storage backend for run/cell dirs, the resumability cache, artifacts,\n * and trace spans. Default: the Node filesystem (`fsCampaignStorage`).\n * Pass `inMemoryCampaignStorage()` to run in a filesystem-less runtime\n * (Cloudflare Workers, Deno, edge) — the `CampaignResult` is still\n * produced; artifacts/traces just aren't persisted to disk. */\n storage?: CampaignStorage\n /**\n * Optional per-cell placement strategy. Returns an opaque string the\n * substrate forwards as `ctx.placement` to the Dispatch — placement-aware\n * Dispatches (e.g. `httpDispatch` from `/adapters/http`) use it to route\n * each cell to the right worker, region, or sandbox. When unset, every\n * cell receives `ctx.placement = undefined` and behaves identically to\n * the in-process case.\n *\n * @example\n * cellPlacement: ({ scenario }) => scenario.tags?.includes('eu') ? 'eu-west' : 'us-east'\n */\n cellPlacement?: (input: {\n scenario: TScenario\n rep: number\n generation?: number\n }) => string | undefined\n}\n\n/** Durable `<cell>/failure-receipt.json` written before a failed cell can\n * trigger campaign-wide cancellation. The cell keeps its dispatch-only usage\n * fields for compatibility; `cost` covers every settled agent and judge call\n * attributed to this exact run attempt. */\nexport interface CampaignCellFailureReceipt<TArtifact = unknown> {\n schemaVersion: 1\n runAttemptId: string\n recordedAt: string\n failure: {\n stage: 'dispatch' | 'judge'\n judge?: string\n error: {\n name: string\n message: string\n stack?: string\n }\n }\n cell: CampaignCellResult<TArtifact>\n cost: CostLedgerSummary\n}\n\n/**\n * Core campaign orchestrator: fan scenarios through dispatch, score with judges, aggregate bootstrap CIs, and persist reproducible `CampaignResult` records.\n */\nexport async function runCampaign<TScenario extends Scenario, TArtifact>(\n opts: RunCampaignOptions<TScenario, TArtifact>,\n): Promise<CampaignResult<TArtifact, TScenario>> {\n const seed = opts.seed ?? 42\n const reps = opts.reps ?? 1\n const resumable = opts.resumable ?? true\n const now = opts.now ?? (() => new Date())\n const judges = opts.judges ?? []\n const storage = opts.storage ?? fsCampaignStorage()\n const costPhase = opts.costPhase ?? 'campaign'\n const dispatchShutdownTimeoutMs = opts.dispatchShutdownTimeoutMs ?? 5_000\n\n assertCampaignDesign(opts.scenarios, reps)\n if (!Number.isSafeInteger(dispatchShutdownTimeoutMs) || dispatchShutdownTimeoutMs <= 0) {\n throw new Error('runCampaign: dispatchShutdownTimeoutMs must be a positive safe integer')\n }\n\n if (typeof opts.runDir !== 'string' || opts.runDir.trim().length === 0) {\n throw new Error('runCampaign: runDir is required and must be a non-empty string')\n }\n opts.runDir = resolveRunDir(opts.runDir, opts.repo)\n storage.ensureDir(opts.runDir)\n const costLedger =\n opts.costLedger ??\n createRunCostLedger({\n storage,\n runDir: opts.runDir,\n costCeilingUsd: opts.costCeiling,\n })\n if (opts.costCeiling !== undefined && costLedger.costCeilingUsd !== opts.costCeiling) {\n throw new Error('runCampaign: costCeiling must match the shared CostLedger ceiling')\n }\n const maxConcurrency = opts.maxConcurrency ?? 2\n\n const manifestHash = computeManifestHash({\n scenarios: opts.scenarios,\n judges: judges as unknown as JudgeConfig<unknown>[],\n dispatchRef: dispatchRefFor(opts.dispatch, opts.dispatchRef),\n seed,\n reps,\n })\n const splitDigest = campaignSplitDigest(opts.scenarios, reps)\n\n const startedAt = now()\n const runAttemptId = globalThis.crypto.randomUUID()\n const cells: CampaignCellResult<TArtifact>[] = []\n const artifactsByPath: Record<string, string> = {}\n\n // Build the cell schedule (scenario × rep).\n const schedule = buildCellSchedule(opts.scenarios, seed, reps)\n\n // Concurrency-limited execution.\n const campaignAbort = new AbortController()\n const onOwnerAbort = (): void => campaignAbort.abort(opts.signal?.reason)\n if (opts.signal?.aborted) campaignAbort.abort(opts.signal.reason)\n else opts.signal?.addEventListener('abort', onOwnerAbort, { once: true })\n const campaignSignal = campaignAbort.signal\n // Concurrency lanes that drain the cell schedule. Named \"lanes\" — not\n // \"workers\" — to avoid clashing with the taxonomy's worker (= the agent\n // harness in a sandbox, invoked behind `dispatch`). See loop-taxonomy.md.\n const lanes: Promise<void>[] = []\n let nextIdx = 0\n const cellsRef = cells\n let firstLaneError: unknown\n let firstCellFailure: CellFailure | undefined\n\n for (let i = 0; i < maxConcurrency; i++) {\n lanes.push(\n (async () => {\n try {\n while (true) {\n if (campaignSignal.aborted) return\n const myIdx = nextIdx++\n if (myIdx >= schedule.length) return\n const slot = schedule[myIdx]!\n const result = await executeCell({\n slot,\n opts,\n manifestHash,\n resumable,\n now,\n storage,\n buildTraceWriter: opts.buildTraceWriter ?? defaultBuildTraceWriter(storage),\n signal: campaignSignal,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n dispatchShutdownTimeoutMs,\n costLedger,\n costPhase,\n runAttemptId,\n onFailure: opts.abortOnCellError\n ? (failure) => {\n if (firstCellFailure === undefined) {\n firstCellFailure = failure\n campaignAbort.abort(failure.cause)\n }\n }\n : undefined,\n })\n cellsRef.push(result.cell)\n Object.assign(artifactsByPath, result.artifactsByPath)\n // Capture into LabeledScenarioStore unless explicitly disabled.\n if (opts.labeledStore && opts.labeledStore !== 'off' && !result.cell.error) {\n await captureToStore({\n store: opts.labeledStore,\n cell: result.cell,\n scenario: slot.scenario,\n opts,\n now,\n }).catch((err) => {\n // Capture failures are non-fatal — log but don't crash the campaign.\n // (Trace would normally land here.)\n console.warn(\n `[runCampaign] capture failed for ${result.cell.cellId}: ${err instanceof Error ? err.message : String(err)}`,\n )\n })\n }\n if (opts.abortOnCellError && result.failure) {\n return\n }\n }\n } catch (error) {\n if (firstLaneError === undefined) {\n firstLaneError = error\n campaignAbort.abort(error)\n }\n throw error\n }\n })(),\n )\n }\n const laneResults = await Promise.allSettled(lanes)\n opts.signal?.removeEventListener('abort', onOwnerAbort)\n const failedLane = laneResults.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (firstCellFailure) throw firstCellFailure.cause\n if (failedLane) throw firstLaneError ?? failedLane.reason\n\n const endedAt = now()\n cellsRef.sort((a, b) => a.cellId.localeCompare(b.cellId))\n\n const campaignCost = costLedger.summary({ tags: { runDir: opts.runDir } })\n const aggregates = computeAggregates(\n cellsRef,\n judges as unknown as JudgeConfig<TArtifact>[],\n seed,\n campaignCost,\n )\n\n return {\n manifestHash,\n splitDigest,\n seed,\n reps,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: endedAt.getTime() - startedAt.getTime(),\n cells: cellsRef,\n aggregates,\n runDir: opts.runDir,\n artifactsByPath,\n scenarios: opts.scenarios.map(campaignScenarioIdentity),\n }\n}\n\n// ── Internals ─────────────────────────────────────────────────────────\n\ninterface ExecuteCellArgs<TScenario extends Scenario, TArtifact> {\n slot: { scenario: TScenario; rep: number; cellId: string; cellSeed: number }\n opts: RunCampaignOptions<TScenario, TArtifact>\n manifestHash: string\n resumable: boolean\n now: () => Date\n storage: CampaignStorage\n buildTraceWriter: (cellId: string, dir: string) => CampaignTraceWriter\n signal: AbortSignal\n dispatchTimeoutMs?: number\n dispatchShutdownTimeoutMs: number\n costLedger: CostLedgerHandle\n costPhase: string\n runAttemptId: string\n onFailure?: (failure: CellFailure) => void\n}\n\ninterface CellFailure {\n stage: 'dispatch' | 'judge'\n judge?: string\n cause: unknown\n}\n\ninterface ExecuteCellResult<TArtifact> {\n cell: CampaignCellResult<TArtifact>\n artifactsByPath: Record<string, string>\n failure?: CellFailure\n}\n\nasync function executeCell<TScenario extends Scenario, TArtifact>(\n args: ExecuteCellArgs<TScenario, TArtifact>,\n): Promise<ExecuteCellResult<TArtifact>> {\n const storage = args.storage\n const cellDir = join(args.opts.runDir, args.slot.cellId.replace(/[^a-zA-Z0-9_-]/g, '_'))\n storage.ensureDir(cellDir)\n const stableCostTags = {\n ...(args.opts.costTags ?? {}),\n runDir: args.opts.runDir,\n cellId: args.slot.cellId,\n scenarioId: args.slot.scenario.id,\n rep: String(args.slot.rep),\n }\n const costTags = { ...stableCostTags, runAttemptId: args.runAttemptId }\n\n // Resumability: cache key = (manifestHash, scenarioId, rep)\n const cachePath = join(cellDir, 'cached-result.json')\n if (args.resumable) {\n const cached = readCachedCell<TArtifact>({\n storage,\n cachePath,\n cellId: args.slot.cellId,\n manifestHash: args.manifestHash,\n })\n if (cached.status === 'hit') {\n enforceDispatchUsage(cached.cell, args.opts.expectUsage ?? 'warn')\n const cachedHasUsage =\n cached.cell.costUsd > 0 ||\n cached.cell.tokenUsage.input > 0 ||\n cached.cell.tokenUsage.output > 0\n if (cached.cell.costCallIds === undefined) {\n if (cachedHasUsage || Object.keys(cached.cell.judgeScores).length > 0) {\n throw new CostAccountingIncompleteError(\n `runCampaign: cached cell '${args.slot.cellId}' does not identify its ledger receipts`,\n )\n }\n } else if (\n !Array.isArray(cached.cell.costCallIds) ||\n cached.cell.costCallIds.some(\n (callId) => typeof callId !== 'string' || callId.trim().length === 0,\n ) ||\n new Set(cached.cell.costCallIds).size !== cached.cell.costCallIds.length\n ) {\n throw new CostAccountingIncompleteError(\n `runCampaign: cached cell '${args.slot.cellId}' has invalid ledger receipt IDs`,\n )\n } else {\n const restoredCallIds = new Set(\n args.costLedger.list({ tags: stableCostTags }).map((receipt) => receipt.callId),\n )\n const missingCallIds = cached.cell.costCallIds.filter(\n (callId) => !restoredCallIds.has(callId),\n )\n if (missingCallIds.length > 0) {\n throw new CostAccountingIncompleteError(\n `runCampaign: cached cell '${args.slot.cellId}' is missing ledger receipt(s): ${missingCallIds.join(', ')}`,\n )\n }\n }\n return { cell: { ...cached.cell, cached: true }, artifactsByPath: {} }\n }\n }\n\n const startMs = Date.now()\n const trace = args.buildTraceWriter(args.slot.cellId, cellDir)\n const artifactsByPath: Record<string, string> = {}\n let paidCallStarted = false\n const artifacts: CampaignArtifactWriter = {\n async write(path, content) {\n const fullPath = join(cellDir, path)\n storage.ensureDir(join(fullPath, '..'))\n storage.write(fullPath, content)\n artifactsByPath[`${args.slot.cellId}/${path}`] = fullPath\n return fullPath\n },\n async writeJson(path, value) {\n return artifacts.write(path, JSON.stringify(value, null, 2))\n },\n }\n const cost: CampaignCostMeter = {\n async runPaidCall(input) {\n paidCallStarted = true\n const result = await args.costLedger.runPaidCall({\n ...input,\n channel: input.channel ?? 'agent',\n phase: args.costPhase,\n actor: input.actor,\n tags: costTags,\n signal: cellAbort.signal,\n })\n if (result.receipt) {\n trace.span(`cost.${result.receipt.actor}`, { amountUsd: result.receipt.costUsd }).end()\n }\n return result\n },\n }\n\n const placement = args.opts.cellPlacement?.({\n scenario: args.slot.scenario,\n rep: args.slot.rep,\n })\n\n // Per-cell abort signal, chained to the campaign signal. The dispatch sees\n // THIS signal so a timeout (below) can abort just this cell's in-flight work\n // without tearing down sibling cells — and a signal-honoring dispatch\n // releases its open request instead of leaking it past the deadline.\n const cellAbort = new AbortController()\n const onCampaignAbort = () => cellAbort.abort((args.signal as { reason?: unknown }).reason)\n if (args.signal.aborted) cellAbort.abort((args.signal as { reason?: unknown }).reason)\n else args.signal.addEventListener('abort', onCampaignAbort, { once: true })\n\n const ctx: DispatchContext = {\n cellId: args.slot.cellId,\n rep: args.slot.rep,\n seed: args.slot.cellSeed,\n signal: cellAbort.signal,\n trace,\n artifacts,\n cost,\n placement,\n }\n\n let artifact: TArtifact | undefined\n let errorMessage: string | undefined\n let failure: CellFailure | undefined\n let fatalCellError: unknown\n let dispatched: Promise<TArtifact> | undefined\n const timeoutMs = args.dispatchTimeoutMs\n let timeoutTimer: ReturnType<typeof setTimeout> | undefined\n let removeAbortListener: () => void = () => undefined\n try {\n dispatched = Promise.resolve(args.opts.dispatch(args.slot.scenario, ctx))\n const aborted = new Promise<never>((_resolve, reject) => {\n const rejectAbort = () => {\n const reason = cellAbort.signal.reason\n reject(reason instanceof Error ? reason : new Error(String(reason ?? 'dispatch aborted')))\n }\n if (cellAbort.signal.aborted) {\n rejectAbort()\n return\n }\n cellAbort.signal.addEventListener('abort', rejectAbort, { once: true })\n removeAbortListener = () => cellAbort.signal.removeEventListener('abort', rejectAbort)\n })\n if (timeoutMs !== undefined && timeoutMs > 0) {\n // A dispatch that never settles (stalled model request, exhausted runtime\n // resource, a stream that never closes) must NOT hang the cell — and with\n // it the lane, the campaign, the loop, the CI job — forever. Race it\n // against the deadline; on timeout, abort the cell and fail it LOUD.\n artifact = await Promise.race([\n dispatched,\n aborted,\n new Promise<never>((_, reject) => {\n timeoutTimer = setTimeout(() => {\n const timeoutError = new Error(\n `dispatch exceeded ${timeoutMs}ms for cell '${args.slot.cellId}' — aborted and failed loud (no silent hang)`,\n )\n reject(timeoutError)\n cellAbort.abort(timeoutError)\n }, timeoutMs)\n if (typeof (timeoutTimer as { unref?: () => void }).unref === 'function')\n (timeoutTimer as { unref: () => void }).unref()\n }),\n ])\n } else {\n artifact = await Promise.race([dispatched, aborted])\n }\n } catch (err) {\n errorMessage = err instanceof Error ? err.message : String(err)\n failure = { stage: 'dispatch', cause: err }\n } finally {\n if (timeoutTimer) clearTimeout(timeoutTimer)\n removeAbortListener()\n args.signal.removeEventListener('abort', onCampaignAbort)\n }\n\n if (dispatched) {\n const dispatchSettled = await settlesWithin(dispatched, args.dispatchShutdownTimeoutMs)\n if (!dispatchSettled) {\n await trace.flush()\n throw new CostAccountingIncompleteError(\n `dispatch for cell '${args.slot.cellId}' ignored cancellation and did not stop within ${args.dispatchShutdownTimeoutMs}ms; no campaign result was produced`,\n )\n }\n }\n if (paidCallStarted) {\n if (typeof args.costLedger.waitForIdle !== 'function') {\n await trace.flush()\n throw new CostAccountingIncompleteError(\n `cost ledger for cell '${args.slot.cellId}' cannot prove that paid calls stopped`,\n )\n }\n const paidCallsSettled = await args.costLedger.waitForIdle({\n timeoutMs: args.dispatchShutdownTimeoutMs,\n filter: { channel: 'agent', phase: args.costPhase, tags: costTags },\n })\n if (!paidCallsSettled) {\n await trace.flush()\n throw new CostAccountingIncompleteError(\n `paid calls for cell '${args.slot.cellId}' did not settle within ${args.dispatchShutdownTimeoutMs}ms; no campaign result was produced`,\n )\n }\n }\n\n const agentReceipts = args.costLedger.list({ channel: 'agent', tags: costTags })\n const agentCost = args.costLedger.summary({ channel: 'agent', tags: costTags })\n const tokenUsage: CampaignTokenUsage = {\n input: agentCost.inputTokens,\n output: agentCost.outputTokens,\n ...(agentCost.cachedTokens > 0 ? { cached: agentCost.cachedTokens } : {}),\n }\n const resolvedModel = agentReceipts.at(-1)?.model\n const dispatchResult = {\n cellId: args.slot.cellId,\n artifact,\n error: errorMessage,\n costUsd: agentCost.totalCostUsd,\n tokenUsage,\n }\n try {\n enforceDispatchUsage(dispatchResult, args.opts.expectUsage ?? 'warn')\n } catch (error) {\n await trace.flush()\n throw error\n }\n\n // Run judges (only if we have an artifact). A judge that throws invalidates\n // the cell — recorded as `error`, NOT folded into a fake composite:0 (a fake\n // zero is indistinguishable from a real zero and poisons every aggregate).\n const judgeScores: Record<string, JudgeScore> = {}\n if (artifact !== undefined) {\n for (const judge of args.opts.judges ?? []) {\n if (judge.appliesTo && !judge.appliesTo(args.slot.scenario)) continue\n try {\n const score = await runJudgeCell(judge, {\n artifact,\n scenario: args.slot.scenario,\n signal: args.signal,\n costLedger: args.costLedger,\n costPhase: args.costPhase,\n costTags,\n })\n judgeScores[judge.name] = score\n } catch (err) {\n errorMessage = `judge '${judge.name}' failed: ${err instanceof Error ? err.message : String(err)}`\n failure = { stage: 'judge', judge: judge.name, cause: err }\n if (err instanceof CostAccountingIncompleteError) fatalCellError = err\n break\n }\n }\n }\n\n if (failure) {\n await waitForFailedCellCostSettlement({\n costLedger: args.costLedger,\n costPhase: args.costPhase,\n costTags,\n cellId: args.slot.cellId,\n timeoutMs: args.dispatchShutdownTimeoutMs,\n })\n }\n const costCallIds = args.costLedger\n .list({ tags: costTags })\n .map((receipt) => receipt.callId)\n .sort()\n\n const cell: CampaignCellResult<TArtifact> = {\n manifestHash: args.manifestHash,\n cellId: args.slot.cellId,\n scenarioId: args.slot.scenario.id,\n rep: args.slot.rep,\n artifact: (artifact ?? null) as TArtifact,\n judgeScores,\n costUsd: agentCost.totalCostUsd,\n costEstimated: agentReceipts.some(\n (receipt) => receipt.actualCostUsd === undefined && !receipt.costUnknown,\n ),\n costCallIds,\n tokenUsage,\n ...(resolvedModel ? { resolvedModel } : {}),\n durationMs: Date.now() - startMs,\n seed: args.slot.cellSeed,\n cached: false,\n error: errorMessage,\n }\n\n if (failure) {\n const failurePath = join(cellDir, 'failure-receipt.json')\n const receipt: CampaignCellFailureReceipt<TArtifact> = {\n schemaVersion: 1,\n runAttemptId: args.runAttemptId,\n recordedAt: args.now().toISOString(),\n failure: {\n stage: failure.stage,\n ...(failure.judge ? { judge: failure.judge } : {}),\n error: serializeCellError(failure.cause),\n },\n cell,\n cost: args.costLedger.summary({ phase: args.costPhase, tags: costTags }),\n }\n storage.write(failurePath, JSON.stringify(receipt, null, 2))\n artifactsByPath[`${args.slot.cellId}/failure-receipt.json`] = failurePath\n args.onFailure?.(failure)\n }\n\n await trace.flush()\n\n if (!errorMessage && args.resumable) {\n storage.write(cachePath, JSON.stringify(cell))\n }\n\n if (fatalCellError !== undefined) throw fatalCellError\n return { cell, artifactsByPath, ...(failure ? { failure } : {}) }\n}\n\nasync function waitForFailedCellCostSettlement(input: {\n costLedger: CostLedgerHandle\n costPhase: string\n costTags: Record<string, string>\n cellId: string\n timeoutMs: number\n}): Promise<void> {\n const filter = { phase: input.costPhase, tags: input.costTags }\n if (input.costLedger.summary(filter).pendingCalls === 0) return\n if (typeof input.costLedger.waitForIdle !== 'function') {\n throw new CostAccountingIncompleteError(\n `cost ledger for failed cell '${input.cellId}' cannot prove that paid calls stopped`,\n )\n }\n const settled = await input.costLedger.waitForIdle({\n timeoutMs: input.timeoutMs,\n filter,\n })\n if (!settled || input.costLedger.summary(filter).pendingCalls > 0) {\n throw new CostAccountingIncompleteError(\n `paid calls for failed cell '${input.cellId}' did not settle within ${input.timeoutMs}ms; no complete failure receipt was produced`,\n )\n }\n}\n\nfunction serializeCellError(error: unknown): {\n name: string\n message: string\n stack?: string\n} {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack ? { stack: error.stack } : {}),\n }\n }\n return { name: 'NonErrorThrown', message: String(error) }\n}\n\nfunction settlesWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n let completed = false\n let timer: ReturnType<typeof setTimeout> | undefined\n const finish = (value: boolean): void => {\n if (completed) return\n completed = true\n if (timer) clearTimeout(timer)\n resolve(value)\n }\n timer = setTimeout(() => finish(false), timeoutMs)\n promise.then(\n () => finish(true),\n () => finish(true),\n )\n })\n}\n\nexport interface CampaignRunPlanCell {\n cellId: string\n scenarioId: string\n rep: number\n seed: number\n cachePath: string\n status: 'cached' | 'run'\n reason?: 'missing' | 'manifest-mismatch' | 'cell-mismatch' | 'corrupt' | 'resumable-off'\n}\n\nexport interface CampaignRunPlan {\n manifestHash: string\n splitDigest: `sha256:${string}`\n totalCells: number\n cellsCached: number\n cellsToRun: number\n cells: CampaignRunPlanCell[]\n}\n\nexport interface PlanCampaignRunOptions<TScenario extends Scenario, TArtifact> {\n scenarios: TScenario[]\n dispatch?: DispatchFn<TScenario, TArtifact>\n dispatchRef?: string\n judges?: JudgeConfig<TArtifact, TScenario>[]\n seed?: number\n reps?: number\n resumable?: boolean\n runDir: string\n /** Subject repo for the shared run-dir root (see RunCampaignOptions.repo). */\n repo?: string\n storage?: CampaignStorage\n}\n\n/**\n * Plan a campaign WITHOUT dispatching: computes the manifest hash and the per-cell\n * run-vs-cached schedule so callers can preview cost and resumability before spending.\n */\nexport function planCampaignRun<TScenario extends Scenario, TArtifact>(\n opts: PlanCampaignRunOptions<TScenario, TArtifact>,\n): CampaignRunPlan {\n const seed = opts.seed ?? 42\n const reps = opts.reps ?? 1\n const resumable = opts.resumable ?? true\n const storage = opts.storage ?? fsCampaignStorage()\n\n assertCampaignDesign(opts.scenarios, reps)\n\n if (typeof opts.runDir !== 'string' || opts.runDir.trim().length === 0) {\n throw new Error('planCampaignRun: runDir is required and must be a non-empty string')\n }\n opts.runDir = resolveRunDir(opts.runDir, opts.repo)\n\n const manifestHash = computeManifestHash({\n scenarios: opts.scenarios,\n judges: (opts.judges ?? []) as unknown as JudgeConfig<unknown>[],\n dispatchRef: dispatchRefFor(opts.dispatch, opts.dispatchRef),\n seed,\n reps,\n })\n const splitDigest = campaignSplitDigest(opts.scenarios, reps)\n\n const cells = buildCellSchedule(opts.scenarios, seed, reps).map((slot): CampaignRunPlanCell => {\n const cachePath = join(\n opts.runDir,\n slot.cellId.replace(/[^a-zA-Z0-9_-]/g, '_'),\n 'cached-result.json',\n )\n if (!resumable) {\n return {\n cellId: slot.cellId,\n scenarioId: slot.scenario.id,\n rep: slot.rep,\n seed: slot.cellSeed,\n cachePath,\n status: 'run',\n reason: 'resumable-off',\n }\n }\n\n const cached = readCachedCell<unknown>({\n storage,\n cachePath,\n cellId: slot.cellId,\n manifestHash,\n })\n if (cached.status === 'hit') {\n return {\n cellId: slot.cellId,\n scenarioId: slot.scenario.id,\n rep: slot.rep,\n seed: slot.cellSeed,\n cachePath,\n status: 'cached',\n }\n }\n\n return {\n cellId: slot.cellId,\n scenarioId: slot.scenario.id,\n rep: slot.rep,\n seed: slot.cellSeed,\n cachePath,\n status: 'run',\n reason: cached.reason,\n }\n })\n\n const cellsCached = cells.filter((cell) => cell.status === 'cached').length\n return {\n manifestHash,\n splitDigest,\n totalCells: cells.length,\n cellsCached,\n cellsToRun: cells.length - cellsCached,\n cells,\n }\n}\n\n/**\n * Per-dispatch stub guard. An artifact produced with `costUsd === 0` AND zero\n * tokens means the dispatch never called `ctx.cost` —\n * i.e. it ran against a stub or silently dropped its usage. `'warn'` logs it,\n * `'assert'` throws (fail-fast), and `'off'` skips the check.\n */\nfunction enforceDispatchUsage(\n cell: Pick<\n CampaignCellResult<unknown>,\n 'cellId' | 'artifact' | 'error' | 'costUsd' | 'tokenUsage'\n >,\n mode: 'assert' | 'warn' | 'off',\n): void {\n if (mode === 'off') return\n if (cell.artifact === null || cell.artifact === undefined) return\n const zeroTokens = cell.tokenUsage.input === 0 && cell.tokenUsage.output === 0\n if (cell.costUsd !== 0 || !zeroTokens) return\n const msg = `cell '${cell.cellId}' produced an artifact but reported zero cost and zero tokens — the dispatch made no paid call through ctx.cost.runPaidCall (a stub cell)`\n if (mode === 'assert') {\n const report: BackendIntegrityReport = {\n totalRecords: 1,\n stubRecords: 1,\n realRecords: 0,\n uncostedRecords: 0,\n totalInputTokens: 0,\n totalOutputTokens: 0,\n totalCostUsd: 0,\n verdict: 'stub',\n diagnosis: msg,\n }\n throw new BackendIntegrityError(`expectUsage: ${msg}`, report)\n }\n // eslint-disable-next-line no-console\n console.warn(`[runCampaign] expectUsage: ${msg}`)\n}\n\nasync function runJudgeCell<TArtifact, TScenario extends Scenario>(\n judge: JudgeConfig<TArtifact, TScenario>,\n input: Parameters<JudgeConfig<TArtifact, TScenario>['score']>[0],\n): Promise<JudgeScore> {\n const previousJudgeCalls = new Set(\n input.costLedger\n ?.list({ channel: 'judge', tags: input.costTags })\n .map((receipt) => receipt.callId) ?? [],\n )\n try {\n const score = await judge.score(input)\n assertReportedJudgeCallRecorded(judge.name, score, input, previousJudgeCalls)\n return score\n } catch (error) {\n assertReportedJudgeCallRecorded(judge.name, error, input, previousJudgeCalls, error)\n throw error\n }\n}\n\nfunction assertReportedJudgeCallRecorded(\n judgeName: string,\n value: unknown,\n input: Parameters<JudgeConfig<unknown>['score']>[0],\n previousCallIds: ReadonlySet<string>,\n cause?: unknown,\n): void {\n if (!hasLlmCall(value)) return\n const recorded = input.costLedger\n ?.list({ channel: 'judge', tags: input.costTags })\n .some((receipt) => !previousCallIds.has(receipt.callId))\n if (recorded) return\n throw new CostAccountingIncompleteError(\n `runCampaign: judge '${judgeName}' reported a paid LLM call without a CostLedger receipt`,\n cause === undefined ? undefined : { cause },\n )\n}\n\nfunction hasLlmCall(value: unknown): value is { llmCall: unknown } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'llmCall' in value &&\n (value as { llmCall?: unknown }).llmCall !== undefined\n )\n}\n\nfunction defaultBuildTraceWriter(\n storage: CampaignStorage,\n): (cellId: string, dir: string) => CampaignTraceWriter {\n return (cellId, dir) => {\n const spans: Array<Record<string, unknown>> = []\n return {\n span(name, attributes) {\n const startMs = Date.now()\n const record: Record<string, unknown> = { name, cellId, startMs, ...(attributes ?? {}) }\n const finish: TraceSpan = {\n end(endAttrs) {\n record.durationMs = Date.now() - startMs\n if (endAttrs) Object.assign(record, endAttrs)\n spans.push(record)\n },\n setAttribute(key, value) {\n record[key] = value\n },\n }\n return finish\n },\n async flush() {\n storage.write(join(dir, 'spans.jsonl'), spans.map((s) => JSON.stringify(s)).join('\\n'))\n },\n }\n }\n}\n\nfunction buildCellSchedule<TScenario extends Scenario>(\n scenarios: TScenario[],\n seed: number,\n reps: number,\n): Array<{ scenario: TScenario; rep: number; cellId: string; cellSeed: number }> {\n const schedule: Array<{ scenario: TScenario; rep: number; cellId: string; cellSeed: number }> = []\n const groupIndexes = new Map<string, number>()\n let nextGroupIndex = 0\n for (const scenario of scenarios) {\n let groupIndex: number\n if (scenario.seedGroup === undefined) {\n groupIndex = nextGroupIndex\n nextGroupIndex += 1\n } else {\n const existing = groupIndexes.get(scenario.seedGroup)\n if (existing !== undefined) {\n groupIndex = existing\n } else {\n groupIndex = nextGroupIndex\n nextGroupIndex += 1\n groupIndexes.set(scenario.seedGroup, groupIndex)\n }\n }\n for (let rep = 0; rep < reps; rep++) {\n const cellId = `${scenario.id}:${rep}`\n const cellSeed = seed + groupIndex * reps + rep\n schedule.push({ scenario, rep, cellId, cellSeed })\n }\n }\n return schedule\n}\n\nfunction dispatchRefFor<TScenario extends Scenario, TArtifact>(\n dispatch: DispatchFn<TScenario, TArtifact> | undefined,\n override: string | undefined,\n): string {\n const ref = override ?? dispatch?.name ?? 'anonymous'\n if (typeof ref !== 'string' || ref.trim().length === 0) {\n throw new Error('runCampaign: dispatchRef must be a non-empty string when provided')\n }\n return ref\n}\n\ntype CacheRead<TArtifact> =\n | { status: 'hit'; cell: CampaignCellResult<TArtifact> }\n | { status: 'miss'; reason: 'missing' | 'manifest-mismatch' | 'cell-mismatch' | 'corrupt' }\n\nfunction readCachedCell<TArtifact>(args: {\n storage: CampaignStorage\n cachePath: string\n cellId: string\n manifestHash: string\n}): CacheRead<TArtifact> {\n const raw = args.storage.read(args.cachePath)\n if (raw === undefined) return { status: 'miss', reason: 'missing' }\n\n try {\n const cached = JSON.parse(raw) as CampaignCellResult<TArtifact>\n if (cached.cellId !== args.cellId) return { status: 'miss', reason: 'cell-mismatch' }\n if (cached.manifestHash !== args.manifestHash) {\n return { status: 'miss', reason: 'manifest-mismatch' }\n }\n return { status: 'hit', cell: cached }\n } catch {\n return { status: 'miss', reason: 'corrupt' }\n }\n}\n\ninterface CaptureArgs<TScenario extends Scenario, TArtifact> {\n store: LabeledScenarioStore\n cell: CampaignCellResult<TArtifact>\n scenario: TScenario\n opts: RunCampaignOptions<TScenario, TArtifact>\n now: () => Date\n}\n\nasync function captureToStore<TScenario extends Scenario, TArtifact>(\n args: CaptureArgs<TScenario, TArtifact>,\n): Promise<void> {\n await args.store.observe({\n scenario: args.scenario,\n artifact: args.cell.artifact,\n judgeScores: args.cell.judgeScores,\n source: args.opts.captureSource ?? 'eval-run',\n sourceVersionHash: args.opts.captureSourceVersionHash ?? 'unknown',\n capturedAt: args.now().toISOString(),\n redactionStatus: 'raw',\n })\n}\n\n// ── Aggregates + manifest hash ────────────────────────────────────────\n\nfunction computeManifestHash(input: {\n scenarios: Scenario[]\n judges: JudgeConfig<unknown>[]\n dispatchRef: string\n seed: number\n reps: number\n}): string {\n return contentHash({\n scenarios: input.scenarios,\n judges: input.judges.map((judge) => ({\n name: judge.name,\n dims: judge.dimensions,\n version: judgeVersionFor(judge),\n })),\n dispatch: input.dispatchRef,\n seed: input.seed,\n reps: input.reps,\n })\n}\n\nfunction judgeVersionFor(judge: JudgeConfig<unknown>): string {\n if (judge.judgeVersion !== undefined) {\n const version = judge.judgeVersion.trim()\n if (version.length === 0) {\n throw new Error(`runCampaign: judge '${judge.name}' has an empty judgeVersion`)\n }\n return version\n }\n return contentHash({\n score: judge.score.toString(),\n appliesTo: judge.appliesTo?.toString() ?? null,\n })\n}\n\nfunction computeAggregates<TArtifact>(\n cells: CampaignCellResult<TArtifact>[],\n judges: JudgeConfig<TArtifact>[],\n seed: number,\n cost: CostLedgerSummary,\n): CampaignAggregates {\n const byJudge: Record<string, JudgeAggregate> = {}\n for (const judge of judges) {\n const scores: number[] = []\n for (const cell of cells) {\n const s = cell.judgeScores[judge.name]\n if (s !== undefined) scores.push(s.composite)\n }\n byJudge[judge.name] = aggregate(scores, seed)\n }\n const byScenario: Record<string, ScenarioAggregate> = {}\n const scenarioGroups = new Map<string, number[]>()\n for (const cell of cells) {\n const composites = Object.values(cell.judgeScores).map((s) => s.composite)\n if (composites.length === 0) continue\n const mean = composites.reduce((a, b) => a + b, 0) / composites.length\n const arr = scenarioGroups.get(cell.scenarioId) ?? []\n arr.push(mean)\n scenarioGroups.set(cell.scenarioId, arr)\n }\n for (const [scenarioId, samples] of scenarioGroups) {\n const ag = aggregate(samples, seed)\n byScenario[scenarioId] = { meanComposite: ag.mean, ci95: ag.ci95, n: ag.n }\n }\n return {\n byJudge,\n byScenario,\n cost,\n totalCostUsd: cost.totalCostUsd,\n cellsExecuted: cells.filter((c) => !c.error).length,\n cellsSkipped: cells.filter((c) => c.error?.startsWith('skipped:')).length,\n cellsCached: cells.filter((c) => c.cached).length,\n cellsFailed: cells.filter((c) => c.error && !c.error.startsWith('skipped:')).length,\n }\n}\n\n// Percentile bootstrap CI95 via seeded resampling. Deterministic for a given\n// seed — same campaign re-run produces identical CI bands. Falls back to\n// degenerate intervals at n<=1 (the bootstrap is undefined there).\nfunction aggregate(samples: number[], seed: number): JudgeAggregate {\n const n = samples.length\n if (n === 0) return { mean: 0, stdev: 0, ci95: [0, 0], n: 0 }\n const mean = samples.reduce((a, b) => a + b, 0) / n\n const variance = samples.reduce((a, b) => a + (b - mean) ** 2, 0) / Math.max(1, n - 1)\n const stdev = Math.sqrt(variance)\n const ci = confidenceInterval(samples, 0.95, { seed, resamples: 1000 })\n return { mean, stdev, ci95: [ci.lower, ci.upper], n }\n}\n","/**\n * Backend-integrity guard: distinguish \"agent failed\" from \"eval ran against\n * a stub / unconfigured backend.\" Without this guard a canonical eval can\n * silently report `0/N passed` and look like an agent-quality problem when\n * the LLM was never actually called — the failure mode we just hit running\n * the 4-vertical parallel eval (legal-sandbox-stub returned hard-coded 33-104\n * char strings; gtm/creative defaulted to a cli-bridge that wasn't running).\n *\n * The shape:\n *\n * const report = summarizeBackendIntegrity(records)\n * assertRealBackend(records) // throws BackendIntegrityError if 100% stub\n *\n * A record is \"stub-mode\" if its `tokenUsage.input === 0 && tokenUsage.output === 0`.\n * (`costUsd` alone is unreliable — some backends successfully call LLMs but\n * don't propagate pricing, producing real tokens with $0 cost.)\n *\n * Verdicts:\n * - `real` — at least one record has nonzero token usage\n * - `stub` — every record is stub-mode (eval ran blind)\n * - `mixed` — some records real, some stub (partial backend failure;\n * often the 429-cascade or auth-half-failed case)\n */\n\nimport type { CostReceipt } from '../cost-ledger'\nimport { AgentEvalError } from '../errors'\nimport type { RunRecord } from '../run-record'\n\nexport interface BackendIntegrityReport {\n /** Total records inspected. */\n totalRecords: number\n /** Records with input=0 AND output=0 (a stub fingerprint). */\n stubRecords: number\n /** Records with nonzero token usage (real LLM activity). */\n realRecords: number\n /** Records where output>0 but costUsd=0 (real LLM, broken cost ledger). */\n uncostedRecords: number\n /** Sum of input tokens across all records. */\n totalInputTokens: number\n /** Sum of output tokens across all records. */\n totalOutputTokens: number\n /** Sum of costUsd across all records. */\n totalCostUsd: number\n /** Worst-case integrity verdict. */\n verdict: 'real' | 'mixed' | 'stub'\n /** Human-readable diagnosis suitable for terminal output. */\n diagnosis: string\n}\n\n/**\n * Error thrown when an integrity assertion fails. Caller can pattern-match\n * by `code === 'AGENT_EVAL_BACKEND_STUB'` to differentiate from other\n * errors.\n */\nexport class BackendIntegrityError extends AgentEvalError {\n constructor(\n message: string,\n public readonly report: BackendIntegrityReport,\n ) {\n super('backend_integrity', message)\n }\n}\n\n/**\n * Inspect a batch of RunRecords and return an integrity report. Pure\n * function — no I/O, no logging. The caller decides what to do with the\n * verdict (print warning, throw, gate CI, etc.).\n */\nexport function summarizeBackendIntegrity(\n records: ReadonlyArray<RunRecord>,\n): BackendIntegrityReport {\n return summarizeBackendUsage(\n records.map((record) => ({\n inputTokens: record.tokenUsage.input,\n outputTokens: record.tokenUsage.output,\n costUsd: record.costUsd,\n })),\n )\n}\n\n/** Inspect settled agent calls from the canonical cost ledger. */\nexport function summarizeAgentReceiptIntegrity(\n receipts: ReadonlyArray<CostReceipt>,\n): BackendIntegrityReport {\n return summarizeBackendUsage(\n receipts\n .filter((receipt) => receipt.channel === 'agent')\n .map((receipt) => ({\n inputTokens: receipt.inputTokens,\n outputTokens: receipt.outputTokens,\n costUsd: receipt.costUsd,\n })),\n )\n}\n\ninterface BackendUsage {\n inputTokens: number\n outputTokens: number\n costUsd: number\n}\n\nfunction summarizeBackendUsage(records: readonly BackendUsage[]): BackendIntegrityReport {\n const totalRecords = records.length\n let stubRecords = 0\n let realRecords = 0\n let uncostedRecords = 0\n let totalInputTokens = 0\n let totalOutputTokens = 0\n let totalCostUsd = 0\n for (const rec of records) {\n totalInputTokens += rec.inputTokens\n totalOutputTokens += rec.outputTokens\n totalCostUsd += rec.costUsd\n if (rec.inputTokens === 0 && rec.outputTokens === 0) stubRecords++\n else realRecords++\n if (rec.outputTokens > 0 && rec.costUsd === 0) uncostedRecords++\n }\n const verdict: BackendIntegrityReport['verdict'] =\n totalRecords === 0\n ? 'stub'\n : stubRecords === totalRecords\n ? 'stub'\n : stubRecords === 0\n ? 'real'\n : 'mixed'\n const diagnosis = buildDiagnosis({\n totalRecords,\n stubRecords,\n realRecords,\n uncostedRecords,\n totalInputTokens,\n totalOutputTokens,\n totalCostUsd,\n verdict,\n })\n return {\n totalRecords,\n stubRecords,\n realRecords,\n uncostedRecords,\n totalInputTokens,\n totalOutputTokens,\n totalCostUsd,\n verdict,\n diagnosis,\n }\n}\n\nfunction buildDiagnosis(r: Omit<BackendIntegrityReport, 'diagnosis'>): string {\n if (r.totalRecords === 0) {\n return 'no records — eval produced zero runs; backend likely failed before first turn'\n }\n if (r.verdict === 'stub') {\n return [\n `all ${r.totalRecords} records have zero token usage — the LLM backend was never called.`,\n 'common causes: --backend sandbox without a sandbox bridge running; stub model returning hard-coded strings;',\n 'auth misconfigured so requests were silently dropped before the LLM. Re-run with --backend tcloud and TANGLE_API_KEY set,',\n 'or boot the cli-bridge / sandbox before invoking the eval.',\n ].join(' ')\n }\n if (r.verdict === 'mixed') {\n const pct = ((r.stubRecords / r.totalRecords) * 100).toFixed(0)\n return [\n `${r.stubRecords}/${r.totalRecords} records (${pct}%) have zero token usage — the backend partially failed.`,\n 'common causes: rate-limit cascade (429s after the first N personas);',\n 'transient auth expiry mid-run; provider outage. Treat the affected records as missing data, not agent failures.',\n ].join(' ')\n }\n // verdict === 'real'\n if (r.uncostedRecords > 0) {\n const pct = ((r.uncostedRecords / r.totalRecords) * 100).toFixed(0)\n return [\n `${r.totalRecords} records with real LLM activity (in=${r.totalInputTokens}, out=${r.totalOutputTokens} tokens).`,\n `${r.uncostedRecords} (${pct}%) have output tokens but costUsd=0. Two distinct roots:`,\n '(a) cost ledger mis-wired — no usage propagation from the runtime stream into RunRecord; or',\n '(b) the model is unpriced at the source (sandbox/router returned $0 despite real tokens).',\n 'For (b), price the measured tokens against the substrate table (estimateCost) instead of leaving $0.',\n ].join(' ')\n }\n return `${r.totalRecords} records with real LLM activity (in=${r.totalInputTokens}, out=${r.totalOutputTokens} tokens, $${r.totalCostUsd.toFixed(4)}).`\n}\n\n/**\n * Throw BackendIntegrityError if the verdict is 'stub' — i.e. every record\n * shows zero LLM activity. Non-strict callers can pass `{ allowMixed: false }`\n * to also reject mixed verdicts (recommended for CI gates).\n *\n * Real backends pass through silently.\n */\nexport function assertRealBackend(\n records: ReadonlyArray<RunRecord>,\n opts: { allowMixed?: boolean } = {},\n): BackendIntegrityReport {\n const report = summarizeBackendIntegrity(records)\n return assertBackendReport(report, opts)\n}\n\n/** Reject a cost ledger with no real agent call or a partial stub run. */\nexport function assertRealAgentReceipts(\n receipts: ReadonlyArray<CostReceipt>,\n opts: { allowMixed?: boolean } = {},\n): BackendIntegrityReport {\n const report = summarizeAgentReceiptIntegrity(receipts)\n return assertBackendReport(report, opts)\n}\n\nfunction assertBackendReport(\n report: BackendIntegrityReport,\n opts: { allowMixed?: boolean },\n): BackendIntegrityReport {\n const allowMixed = opts.allowMixed ?? true\n if (report.verdict === 'stub') {\n throw new BackendIntegrityError(\n `backend-integrity: ran against a stub or unconfigured backend — ${report.diagnosis}`,\n report,\n )\n }\n if (!allowMixed && report.verdict === 'mixed') {\n throw new BackendIntegrityError(\n `backend-integrity: partial backend failure rejected — ${report.diagnosis}`,\n report,\n )\n }\n return report\n}\n","/**\n * Content-addressed judge-verdict caching.\n *\n * LAW: cache JUDGE VERDICTS only — judging the same artifact with the same\n * judge+rubric is pure. NEVER cache agent rollouts. (A router that cached\n * identical fanout prompts silently destroyed best-of-N diversity; rollout\n * caching reintroduces that failure class. Judging has no diversity to\n * destroy — same artifact + same rubric ⇒ same verdict is the desired\n * property, not a bug.)\n *\n * The cache key is a sha-256 over the canonical JSON of everything that can\n * change a verdict: the artifact content, the scenario id, the judge name,\n * the full dimension list (key + description — the description IS the rubric\n * text shown to the judge), and a caller-supplied `judgeVersion`.\n * `judgeVersion` is REQUIRED: a judge whose prompt/model/ensemble changes\n * without a version bump would otherwise silently serve stale verdicts.\n *\n * Strict canonicalization (`canonicalJson`) throws on undefined / function /\n * symbol / non-finite numbers — an artifact that cannot be unambiguously\n * serialized cannot be content-addressed, and coercing it would let two\n * different artifacts collide on one key.\n */\n\nimport { createHash } from 'node:crypto'\nimport { appendFileSync, existsSync, readFileSync } from 'node:fs'\nimport type { JudgeConfig, JudgeScore, Scenario } from './campaign/types'\n\n// ── canonical JSON + content hash ─────────────────────────────────────────\n\nfunction canonicalizeAt(value: unknown, path: string): string {\n if (value === null) return 'null'\n switch (typeof value) {\n case 'boolean':\n return value ? 'true' : 'false'\n case 'number':\n if (!Number.isFinite(value)) {\n throw new Error(\n `canonicalJson: non-finite number (${value}) at ${path} — ambiguity is an error, not a coercion`,\n )\n }\n return JSON.stringify(value)\n case 'string':\n return JSON.stringify(value)\n case 'undefined':\n case 'function':\n case 'symbol':\n throw new Error(\n `canonicalJson: ${typeof value} at ${path} — ambiguity is an error, not a coercion`,\n )\n case 'bigint':\n throw new Error(`canonicalJson: bigint at ${path} — not representable in JSON`)\n case 'object':\n break\n }\n const obj = value as Record<string, unknown>\n // Honor toJSON (Date → ISO string) before structural checks — without it a\n // Date would canonicalize to '{}' and every timestamp would collide.\n if (typeof obj.toJSON === 'function') {\n return canonicalizeAt((obj as { toJSON(): unknown }).toJSON(), path)\n }\n if (Array.isArray(obj)) {\n return `[${obj.map((item, i) => canonicalizeAt(item, `${path}[${i}]`)).join(',')}]`\n }\n if (obj instanceof Map || obj instanceof Set) {\n throw new Error(\n `canonicalJson: ${obj instanceof Map ? 'Map' : 'Set'} at ${path} — would serialize as '{}'; convert to a plain object/array first`,\n )\n }\n const keys = Object.keys(obj).sort()\n const parts = keys.map((k) => `${JSON.stringify(k)}:${canonicalizeAt(obj[k], `${path}.${k}`)}`)\n return `{${parts.join(',')}}`\n}\n\n/**\n * Stable JSON stringify: object keys sorted recursively, so two semantically\n * equal values produce byte-identical output regardless of key insertion\n * order. Throws on undefined / function / symbol / NaN / ±Infinity / bigint /\n * Map / Set — anything JSON.stringify would coerce or drop silently.\n *\n * Distinct from `pre-registration.ts`'s `canonicalize`/`hashJson`, which are\n * permissive (coercion allowed) and async (web-crypto). Use THIS pair when a\n * hash collision or silent coercion would corrupt a cache key or attestation.\n */\nexport function canonicalJson(value: unknown): string {\n return canonicalizeAt(value, '$')\n}\n\n/** Hex sha-256 over `canonicalJson(value)`. The content address used by the\n * verdict cache and report attestation. */\nexport function contentHash(value: unknown): string {\n return createHash('sha256').update(canonicalJson(value)).digest('hex')\n}\n\n// ── store contract ─────────────────────────────────────────────────────────\n\n/** Pluggable verdict store. Sync or async on both legs — `cachedJudge`\n * awaits the results either way. */\nexport interface VerdictCacheStore {\n get(key: string): Promise<JudgeScore | undefined> | JudgeScore | undefined\n set(key: string, score: JudgeScore): Promise<void> | void\n}\n\n/** Process-local Map-backed store. */\nexport function inMemoryVerdictCache(): VerdictCacheStore {\n const entries = new Map<string, JudgeScore>()\n return {\n get: (key) => entries.get(key),\n set: (key, score) => {\n entries.set(key, score)\n },\n }\n}\n\ninterface VerdictCacheLine {\n key: string\n score: JudgeScore\n}\n\nfunction parseCacheLine(line: string, path: string, lineNo: number): VerdictCacheLine {\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new Error(\n `fileVerdictCache: corrupt JSONL at ${path}:${lineNo} — ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const rec = parsed as Partial<VerdictCacheLine>\n if (\n typeof rec !== 'object' ||\n rec === null ||\n typeof rec.key !== 'string' ||\n typeof rec.score !== 'object' ||\n rec.score === null ||\n typeof rec.score.composite !== 'number' ||\n typeof rec.score.dimensions !== 'object'\n ) {\n throw new Error(\n `fileVerdictCache: invalid record shape at ${path}:${lineNo} — expected {key, score:{dimensions, composite, notes}}`,\n )\n }\n return rec as VerdictCacheLine\n}\n\n/**\n * JSONL-file-backed store: the full file is loaded into an in-memory index at\n * construction; every `set` appends one line synchronously (durable before\n * the verdict is returned). A corrupt or malformed line throws at load with\n * file:line — a skipped line would silently re-judge (cost) or, worse, mask\n * a half-written file that needs operator attention.\n */\nexport function fileVerdictCache(path: string): VerdictCacheStore {\n const entries = new Map<string, JudgeScore>()\n if (existsSync(path)) {\n const lines = readFileSync(path, 'utf8').split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined || line.trim() === '') continue\n const rec = parseCacheLine(line, path, i + 1)\n entries.set(rec.key, rec.score)\n }\n }\n return {\n get: (key) => entries.get(key),\n set: (key, score) => {\n appendFileSync(path, `${JSON.stringify({ key, score })}\\n`, 'utf8')\n entries.set(key, score)\n },\n }\n}\n\n// ── cached judge wrapper ───────────────────────────────────────────────────\n\nexport interface VerdictCacheStats {\n hits: number\n misses: number\n}\n\nexport interface CachedJudgeOptions {\n /** REQUIRED — part of the cache key. Bump on any change to the judge's\n * prompt, model, ensemble, or scoring logic; silent judge upgrades must\n * never serve stale verdicts. */\n judgeVersion: string\n}\n\n/** The wrapped judge: same `JudgeConfig` seam, plus hit/miss observability. */\nexport type CachedJudge<TArtifact, TScenario extends Scenario = Scenario> = JudgeConfig<\n TArtifact,\n TScenario\n> & {\n stats(): VerdictCacheStats\n}\n\n/**\n * Wrap a `JudgeConfig` so repeat judgments of the same artifact are served\n * from the store instead of re-invoking `score()`. The wrapper is generic\n * over the judge's own type parameters and preserves `appliesTo` — it is a\n * drop-in replacement anywhere a `JudgeConfig` is accepted.\n *\n * A judge that throws is NOT cached: the error propagates and the next\n * attempt re-judges (caching a failure would pin a transient outage forever).\n */\nexport function cachedJudge<TArtifact, TScenario extends Scenario = Scenario>(\n judge: JudgeConfig<TArtifact, TScenario>,\n store: VerdictCacheStore,\n options: CachedJudgeOptions,\n): CachedJudge<TArtifact, TScenario> {\n if (typeof options.judgeVersion !== 'string' || options.judgeVersion.trim() === '') {\n throw new Error('cachedJudge: judgeVersion is required and must be a non-empty string')\n }\n const stats: VerdictCacheStats = { hits: 0, misses: 0 }\n const wrapped: CachedJudge<TArtifact, TScenario> = {\n name: judge.name,\n dimensions: judge.dimensions,\n judgeVersion: options.judgeVersion,\n async score(input) {\n const key = contentHash({\n artifact: canonicalJson(input.artifact),\n scenarioId: input.scenario.id,\n judgeName: judge.name,\n dimensions: judge.dimensions,\n judgeVersion: options.judgeVersion,\n })\n const cached = await store.get(key)\n if (cached !== undefined) {\n stats.hits += 1\n return cached\n }\n const score = await judge.score(input)\n await store.set(key, score)\n stats.misses += 1\n return score\n },\n stats: () => ({ ...stats }),\n }\n if (judge.appliesTo) wrapped.appliesTo = judge.appliesTo\n return wrapped\n}\n","import { contentHash } from '../verdict-cache'\nimport type { CampaignCellResult, CampaignScenarioIdentity, Scenario } from './types'\n\nexport interface CampaignCoverage {\n complete: boolean\n expectedCellIds: string[]\n scorableCellIds: string[]\n unscorableCells: Array<{ cellId: string; reason: string }>\n}\n\n/** Reject campaign designs whose denominator cannot be identified exactly. */\nexport function assertCampaignDesign<TScenario extends Scenario>(\n scenarios: readonly TScenario[],\n reps: number,\n): void {\n if (!Number.isSafeInteger(reps) || reps < 1) {\n throw new Error('campaign design requires reps to be a positive safe integer')\n }\n const scenarioIds = new Set<string>()\n for (const scenario of scenarios) {\n if (typeof scenario.id !== 'string' || scenario.id.trim().length === 0) {\n throw new Error('campaign design requires every scenario to have a non-empty id')\n }\n if (scenarioIds.has(scenario.id)) {\n throw new Error(`campaign design contains duplicate scenario id '${scenario.id}'`)\n }\n if (typeof scenario.kind !== 'string' || scenario.kind.trim().length === 0) {\n throw new Error('campaign design requires every scenario to have a non-empty kind')\n }\n if (\n scenario.seedGroup !== undefined &&\n (typeof scenario.seedGroup !== 'string' || scenario.seedGroup.trim().length === 0)\n ) {\n throw new Error('campaign design requires seedGroup to be a non-empty string when set')\n }\n scenarioIds.add(scenario.id)\n }\n}\n\n/** Redacted but independently verifiable identity of one complete scenario. */\nexport function campaignScenarioIdentity<TScenario extends Scenario>(\n scenario: TScenario,\n): CampaignScenarioIdentity & Pick<TScenario, 'id' | 'kind'> {\n assertCampaignDesign([scenario], 1)\n return {\n id: scenario.id,\n kind: scenario.kind,\n scenarioDigest: `sha256:${contentHash(scenario)}`,\n }\n}\n\n/** Canonical split identity reconstructed from redacted scenario identities. */\nexport function campaignSplitDigestFromIdentities(\n scenarios: readonly CampaignScenarioIdentity[],\n reps: number,\n): `sha256:${string}` {\n assertCampaignDesign(scenarios, reps)\n for (const scenario of scenarios) {\n if (!/^sha256:[a-f0-9]{64}$/.test(scenario.scenarioDigest)) {\n throw new Error(`campaign scenario '${scenario.id}' has an invalid digest`)\n }\n }\n return `sha256:${contentHash({\n schema: 'tangle.campaign-split',\n scenarios: scenarios.map(({ id, kind, scenarioDigest }) => ({ id, kind, scenarioDigest })),\n reps,\n })}`\n}\n\n/** Canonical identity of the exact scenario payloads and replicate count. */\nexport function campaignSplitDigest<TScenario extends Scenario>(\n scenarios: readonly TScenario[],\n reps: number,\n): `sha256:${string}` {\n assertCampaignDesign(scenarios, reps)\n return campaignSplitDigestFromIdentities(scenarios.map(campaignScenarioIdentity), reps)\n}\n\n/** Refuse a campaign whose retained task identities contradict its split digest. */\nexport function assertCampaignSplitIdentity(\n scenarios: readonly CampaignScenarioIdentity[],\n reps: number,\n splitDigest: string,\n): void {\n if (campaignSplitDigestFromIdentities(scenarios, reps) !== splitDigest) {\n throw new Error('campaign split digest does not match its retained scenario identities')\n }\n}\n\n/** Exact designed-denominator receipt for one campaign. */\nexport function campaignCoverage<TArtifact, TScenario extends Scenario>(\n cells: readonly CampaignCellResult<TArtifact>[],\n scenarios: readonly TScenario[],\n reps: number,\n requireJudgeScore: boolean,\n): CampaignCoverage {\n assertCampaignDesign(scenarios, reps)\n const expectedCellIds = designedCellIds(scenarios, reps)\n const cellsById = new Map<string, CampaignCellResult<TArtifact>[]>()\n for (const cell of cells) {\n const matches = cellsById.get(cell.cellId) ?? []\n matches.push(cell)\n cellsById.set(cell.cellId, matches)\n }\n\n const scorableCellIds: string[] = []\n const unscorableCells: Array<{ cellId: string; reason: string }> = []\n for (const cellId of expectedCellIds) {\n const matches = cellsById.get(cellId) ?? []\n if (matches.length === 0) {\n unscorableCells.push({ cellId, reason: 'missing campaign cell' })\n continue\n }\n if (matches.length > 1) {\n unscorableCells.push({ cellId, reason: `duplicate campaign cell (${matches.length})` })\n continue\n }\n\n const cell = matches[0]!\n const scoreEntries = Object.entries(cell.judgeScores)\n const successfulScores = scoreEntries\n .map(([, score]) => score)\n .filter((score) => score.failed !== true && Number.isFinite(score.composite))\n const nonFiniteScores = scoreEntries.filter(\n ([, score]) =>\n score.failed !== true &&\n (!Number.isFinite(score.composite) ||\n Object.values(score.dimensions).some((value) => !Number.isFinite(value))),\n )\n const reasons: string[] = []\n if (cell.error) reasons.push(cell.error)\n if (cell.artifact === null || cell.artifact === undefined) reasons.push('missing artifact')\n if (!cell.error && requireJudgeScore && successfulScores.length === 0) {\n reasons.push('no successful finite judge score')\n }\n if (scoreEntries.some(([, score]) => score.failed === true)) {\n reasons.push('judge score marked failed')\n }\n if (nonFiniteScores.length > 0) {\n reasons.push(\n `non-finite judge score: ${nonFiniteScores\n .map(([name]) => name)\n .sort()\n .join(', ')}`,\n )\n }\n\n if (reasons.length > 0) {\n unscorableCells.push({ cellId, reason: reasons.join('; ') })\n } else {\n scorableCellIds.push(cellId)\n }\n }\n\n const expected = new Set(expectedCellIds)\n for (const cell of cells) {\n if (cell.cellId !== `${cell.scenarioId}:${cell.rep}`) {\n unscorableCells.push({\n cellId: cell.cellId,\n reason: 'campaign cell id does not match scenario id and rep',\n })\n continue\n }\n if (!expected.has(cell.cellId)) {\n unscorableCells.push({ cellId: cell.cellId, reason: 'unexpected campaign cell' })\n }\n }\n\n return {\n complete: unscorableCells.length === 0 && scorableCellIds.length === expectedCellIds.length,\n expectedCellIds,\n scorableCellIds,\n unscorableCells,\n }\n}\n\nexport function formatCoverageFailures(coverage: CampaignCoverage): string {\n const shown = coverage.unscorableCells\n .slice(0, 3)\n .map((cell) => `${cell.cellId}: ${cell.reason}`)\n .join('; ')\n const remainder = coverage.unscorableCells.length - Math.min(3, coverage.unscorableCells.length)\n return remainder > 0 ? `${shown}; +${remainder} more` : shown || 'unknown coverage failure'\n}\n\nfunction designedCellIds<TScenario extends Scenario>(\n scenarios: readonly TScenario[],\n reps: number,\n): string[] {\n const ids: string[] = []\n for (const scenario of scenarios) {\n for (let rep = 0; rep < reps; rep++) ids.push(`${scenario.id}:${rep}`)\n }\n return ids\n}\n","import { homedir } from 'node:os'\nimport { basename, isAbsolute, join } from 'node:path'\n\n/** The shared, out-of-repo root for campaign/benchmark run bundles. Keeping run\n * outputs here means they never land in a repo working tree (no per-repo\n * gitignore, no clutter, no accidental commits). Layout:\n * ~/.tangle/traces/<repo>/runs/<runName>/\n * where <repo> disambiguates runs across repos in one place. */\nexport function tangleTracesRoot(): string {\n return join(homedir(), '.tangle', 'traces')\n}\n\n/** Resolve a campaign `runDir`. An absolute path is honored as-is (the caller\n * chose an explicit location). A bare name is placed under the shared home root\n * so bundles never pollute a repo working tree — the default the harness should\n * compute so callers pass a *name*, not a path. */\nexport function resolveRunDir(runDir: string, repo?: string): string {\n if (isAbsolute(runDir) || runDir.startsWith('mem://')) return runDir\n const r = repo && repo.trim().length > 0 ? repo : basename(process.cwd())\n return join(tangleTracesRoot(), r, 'runs', runDir)\n}\n","import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { CostLedger } from '../cost-ledger'\nimport { appendSearchLedgerLine, tryWithSearchLedgerFileLock } from './search-ledger-file'\n\n/**\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n /** Append only when the current UTF-8 byte length matches `expectedBytes`.\n * Returns the new length, or undefined when another writer won. */\n append?(path: string, content: string, expectedBytes: number): number | undefined\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n append(path, content, expectedBytes) {\n const result = tryWithSearchLedgerFileLock(path, () => {\n let actualBytes = 0\n try {\n actualBytes = statSync(path).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (actualBytes !== expectedBytes) return undefined\n appendSearchLedgerLine(path, content)\n return expectedBytes + Buffer.byteLength(content)\n })\n return result.acquired ? result.value : undefined\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n append(path, content, expectedBytes) {\n const current = files.get(path)\n const currentText =\n current === undefined\n ? ''\n : typeof current === 'string'\n ? current\n : new TextDecoder().decode(current)\n const currentBytes = new TextEncoder().encode(currentText).byteLength\n if (currentBytes !== expectedBytes) return undefined\n files.set(path, `${currentText}${content}`)\n return currentBytes + new TextEncoder().encode(content).byteLength\n },\n }\n}\n\n/** Open the durable spend account stored beside a logical run. */\nexport function createRunCostLedger(input: {\n storage: CampaignStorage\n runDir: string\n costCeilingUsd?: number\n}): CostLedger {\n const path = join(input.runDir, 'cost-ledger.jsonl')\n input.storage.ensureDir(input.runDir)\n return new CostLedger({\n costCeilingUsd: input.costCeilingUsd,\n persistence: {\n read: () => {\n const stored = input.storage.read(path)\n if (stored === undefined && input.storage.exists(path)) {\n throw new Error(`CostLedger: cannot read existing event log '${path}'`)\n }\n const events = stored ?? ''\n return {\n revision: String(new TextEncoder().encode(events).byteLength),\n events,\n }\n },\n append: (expectedRevision, event) => {\n const expectedBytes = Number(expectedRevision)\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {\n throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`)\n }\n if (!input.storage.append) {\n throw new Error('CostLedger: CampaignStorage.append is required for paid calls')\n }\n const next = input.storage.append(path, event, expectedBytes)\n return next === undefined ? undefined : String(next)\n },\n },\n })\n}\n","/** Filesystem durability and cross-process exclusion for the search ledger. */\n\nimport { closeSync, constants, fsyncSync, mkdirSync, openSync, writeSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\nimport { SearchLedgerIntegrityError } from './search-ledger-errors'\n\nexport function appendSearchLedgerLine(path: string, line: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'))\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\nexport function withSearchLedgerFileLock<T>(ledgerPath: string, run: () => T): T {\n const result = tryWithSearchLedgerFileLock(ledgerPath, run)\n if (!result.acquired) {\n throw new SearchLedgerIntegrityError(`search ledger lock is held (${ledgerPath})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithSearchLedgerFileLock<T>(\n ledgerPath: string,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(ledgerPath), { recursive: true })\n const lockPath = `${ledgerPath}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw new SearchLedgerIntegrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw new SearchLedgerIntegrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n readonly acceptLegacyPid?: boolean\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath, options.acceptLegacyPid ?? false)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { pid, host: hostname(), nonce: randomUUID() }\n const acceptLegacyPid = options.acceptLegacyPid ?? false\n\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n return { acquired: false, reason: 'recovery' }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath, acceptLegacyPid)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const reclaimPath = recoveryPath(options.lockPath)\n if (!tryLinkOwner(reclaimPath, owner, `reclaim.${attempt}`)) {\n return { acquired: false, reason: 'recovery' }\n }\n try {\n const current = ownerState(options.lockPath, acceptLegacyPid)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${options.lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(options.lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `recovered.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n } finally {\n releaseOwnedPath(reclaimPath, owner)\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n writeFileSync(descriptor, `${canonicalOwner(owner)}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\nfunction ownerState(lockPath: string, acceptLegacyPid: boolean): OwnerState {\n const owner = readOwner(lockPath, acceptLegacyPid)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string, acceptLegacyPid: boolean): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n if (acceptLegacyPid && /^[1-9]\\d*$/.test(contents)) {\n const pid = Number(contents)\n if (Number.isSafeInteger(pid)) return { pid, host: hostname(), nonce: 'legacy-pid' }\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath, true)\n if (!current) return\n if (canonicalOwner(current) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","import { ValidationError } from '../errors'\n\nexport class SearchLedgerError extends ValidationError {}\n\nexport class SearchLedgerIntegrityError extends SearchLedgerError {}\n\nexport class SearchLedgerConflictError extends SearchLedgerError {}\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAS,QAAAA,aAAY;;;AC2Cd,IAAM,wBAAN,cAAoC,eAAe;AAAA,EACxD,YACE,SACgB,QAChB;AACA,UAAM,qBAAqB,OAAO;AAFlB;AAAA,EAGlB;AAAA,EAHkB;AAIpB;AAOO,SAAS,0BACd,SACwB;AACxB,SAAO;AAAA,IACL,QAAQ,IAAI,CAAC,YAAY;AAAA,MACvB,aAAa,OAAO,WAAW;AAAA,MAC/B,cAAc,OAAO,WAAW;AAAA,MAChC,SAAS,OAAO;AAAA,IAClB,EAAE;AAAA,EACJ;AACF;AAGO,SAAS,+BACd,UACwB;AACxB,SAAO;AAAA,IACL,SACG,OAAO,CAAC,YAAY,QAAQ,YAAY,OAAO,EAC/C,IAAI,CAAC,aAAa;AAAA,MACjB,aAAa,QAAQ;AAAA,MACrB,cAAc,QAAQ;AAAA,MACtB,SAAS,QAAQ;AAAA,IACnB,EAAE;AAAA,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,QAAQ;AAChC,QAAM,KAAK,mBAAmB,SAAS,MAAM,EAAE,MAAM,WAAW,IAAK,CAAC;AACtE,SAAO,EAAE,MAAM,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,EAAE;AACtD;","names":["join","join","closeSync","constants","fsyncSync","openSync","existsSync","readFileSync","openSync","constants","fsyncSync","closeSync","existsSync","mkdirSync","readFileSync","writeFileSync","join","join"]}
@@ -1271,6 +1271,14 @@ interface RunCampaignOptions<TScenario extends Scenario$1, TArtifact> {
1271
1271
  costTags?: Readonly<Record<string, string>>;
1272
1272
  /** Max concurrent cells. Default 2. */
1273
1273
  maxConcurrency?: number;
1274
+ /**
1275
+ * Stop after the first dispatch or judge error. The failed cell is persisted
1276
+ * before active sibling cells are aborted and drained, then the campaign
1277
+ * rejects with the exact error thrown by that dispatch or judge.
1278
+ * Default false preserves the normal behavior of returning failed cells and
1279
+ * continuing the remaining schedule.
1280
+ */
1281
+ abortOnCellError?: boolean;
1274
1282
  /**
1275
1283
  * Per-cell dispatch deadline in ms. A `dispatch` that neither resolves nor
1276
1284
  * rejects within this window is a hang (a stalled model request, an
@@ -1335,6 +1343,26 @@ interface RunCampaignOptions<TScenario extends Scenario$1, TArtifact> {
1335
1343
  generation?: number;
1336
1344
  }) => string | undefined;
1337
1345
  }
1346
+ /** Durable `<cell>/failure-receipt.json` written before a failed cell can
1347
+ * trigger campaign-wide cancellation. The cell keeps its dispatch-only usage
1348
+ * fields for compatibility; `cost` covers every settled agent and judge call
1349
+ * attributed to this exact run attempt. */
1350
+ interface CampaignCellFailureReceipt<TArtifact = unknown> {
1351
+ schemaVersion: 1;
1352
+ runAttemptId: string;
1353
+ recordedAt: string;
1354
+ failure: {
1355
+ stage: 'dispatch' | 'judge';
1356
+ judge?: string;
1357
+ error: {
1358
+ name: string;
1359
+ message: string;
1360
+ stack?: string;
1361
+ };
1362
+ };
1363
+ cell: CampaignCellResult<TArtifact>;
1364
+ cost: CostLedgerSummary;
1365
+ }
1338
1366
  /**
1339
1367
  * Core campaign orchestrator: fan scenarios through dispatch, score with judges, aggregate bootstrap CIs, and persist reproducible `CampaignResult` records.
1340
1368
  */
@@ -1477,6 +1505,24 @@ interface RunOptimizationBaseOptions<TScenario extends Scenario$1, TArtifact> ex
1477
1505
  costLedger?: CostLedgerHandle;
1478
1506
  costPhase?: string;
1479
1507
  }) => Promise<unknown[]>;
1508
+ /**
1509
+ * Optional override for how the WINNER is selected among coverage-complete
1510
+ * candidates (and how the incumbent bar is set). Returns a lexicographic rank
1511
+ * key — each element higher-is-better; candidates are ranked by descending key
1512
+ * (`compareRankKeys`) and the top must STRICTLY beat the incumbent's key to
1513
+ * promote. Defaults to `[campaignMeanComposite(campaign)]`, i.e. the historical
1514
+ * scalar-mean ranking (single-element key ⇒ identical behavior).
1515
+ *
1516
+ * A binary-with-replicates consumer (e.g. swe-arena, whose ship-gate counts an
1517
+ * instance resolved only when EVERY replicate resolved) passes a fail-closed
1518
+ * key built from the SAME reduction its gate uses, so winner-selection and the
1519
+ * ship-gate rank on the identical metric and can never invert — the selector
1520
+ * cannot promote a flaky per-cell-mean candidate the gate would reject over a
1521
+ * fail-closed candidate the gate would accept. Only the winner CHOICE changes;
1522
+ * the descriptive `composite` (mean) on every record and the Pareto objective
1523
+ * vectors are untouched, so proposer diversity and reporting are unaffected.
1524
+ */
1525
+ selectionRankKey?: (campaign: CampaignResult<TArtifact, TScenario>) => number[];
1480
1526
  }
1481
1527
  type RunOptimizationOptions<TScenario extends Scenario$1, TArtifact> = RunOptimizationBaseOptions<TScenario, TArtifact>;
1482
1528
  interface RunOptimizationResult<TArtifact, TScenario extends Scenario$1> {
@@ -3726,6 +3772,13 @@ interface SelfImproveOptions<TScenario extends Scenario$1, TArtifact> {
3726
3772
  /** Static findings forwarded to the proposer's `propose()` as `ctx.findings`
3727
3773
  * (a findings-grounded proposer consumes them). Default: none. */
3728
3774
  findings?: unknown[];
3775
+ /** Override how the WINNER is selected among coverage-complete candidates.
3776
+ * Defaults to the scalar mean composite (historical behavior). A binary-with-
3777
+ * replicates consumer whose ship-gate counts an instance resolved only when
3778
+ * every replicate resolved passes a fail-closed lexicographic key here so that
3779
+ * winner-selection and the ship-gate rank on the identical metric and cannot
3780
+ * invert. See `RunOptimizationOptions.selectionRankKey`. */
3781
+ selectionRankKey?: RunOptimizationOptions<TScenario, TArtifact>['selectionRankKey'];
3729
3782
  }
3730
3783
  interface SelfImproveResult<TScenario extends Scenario$1, TArtifact> {
3731
3784
  /** Composite mean across all scenarios, baseline run. When
@@ -5410,4 +5463,4 @@ interface FromOtelSpansOptions {
5410
5463
  }
5411
5464
  declare function fromOtelSpans(opts: FromOtelSpansOptions): RunRecord[];
5412
5465
 
5413
- export { type AgentEvalAgent, type AgentEvalEvaluateOptions, type AgentEvalImproveOptions, type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AnalystFinding, type AnalyzeRunsOptions, type AuthoringProvenance, type AxisEvidence, type AxisVerdict, type BuildEvidenceVectorOptions, type CampaignAggregates, type CampaignArtifactWriter, type CampaignCellResult, type CampaignCostMeter, type CampaignResult, type CampaignStorage, type CampaignTraceWriter, type CandidateExperimentExecutionInput, type ChatClient, type CodeAgentSessionAction, type CodeAgentSessionActionKind, type CodeAgentSessionActionStatus, type CodeAgentSessionActionSurface, type CodeAgentSessionDiagnostic, type CodeAgentSessionExecutionReceipt, type CodeAgentSessionIntakeOptions, type CodeAgentSessionIntakeResult, type CodeAgentSessionMetrics, type CodeAgentSessionObservation, type CodeAgentSessionSource, type CodeAgentSessionTerminalStatus, type CodeSurface, type CompareCandidateExperimentOptions, type CompareOptimizationMethodsOptions, type ComparisonCost, type CostLedgerHandle, type CostProvenanceSummary, type CreateChatClientOpts, type DefaultAnalystRegistryOptions, type DefaultProductionGateOptions, type DefineAgentEvalOptions, type DefinedAgentEval, type DeploymentOutcome, type DispatchFn as Dispatch, type DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalReportingSuiteInput, type EvalReportingSuiteOptions, type EvalReportingSuiteResult, type EvalRunDiff, type EvidenceVector, type ExecutionInsight, type ExecutionReport, type ExternalOptimizationExample, type ExternalTextEvaluationResponse, type ExternalTextOptimizationMethodConfig, type ExternalTextOptimizerContext, type ExternalTextOptimizerResult, type FailureClusterInsight, type FeedbackTableMeta, type FeedbackTableRow, FileSystemOutcomeStore, type FileSystemOutcomeStoreOptions, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, type FromRunRecordDirOptions, type FromRunRecordDirResult, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaAdaptiveEngineRun, type GepaEngineOptions, type GepaEngineRun, type GepaOptimizationMethodConfig, type GepaOptimizationRecipe, type GepaRunnerCommand, type HeldOutGateOptions, type HostedTenant, InMemoryOutcomeStore, type InsightReport, type InterRaterInsight, type JudgeConfig, type JudgeDimension, type JudgeInsight, type JudgeScore, type LiftInsight, type LlmJudgeDimension, type LlmJudgeOptions, type MutableSurface, type ObjectiveSource, type OpenAICompatibleOptimizerModel, type OptimizationMethod, type OptimizationMethodComparison, type OptimizationMethodInput, type OptimizationMethodProvenance, type OptimizationMethodResult, type OptimizationPackageSource, type OptimizationProposer, type OptimizationTokenUsage, type OptimizerConfig, type OptimizerModelBudget, type OutcomeCorrelationInsight, type OutcomeStore, type ParetoSignificanceGateOptions, type ParsedCodeAgentJsonl, type PartitionByAuthoringModelResult, type PromotionObjective, type PromotionPolicy, REFERENCE_EQUIVALENCE_INPUT_LIMITS, REFERENCE_EQUIVALENCE_JUDGE_VERSION, type Recommendation, type ReferenceEquivalenceJudgeInput, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceJudgeResult, type ReferenceEquivalenceScenario, type ReleaseSummary, type RunCampaignOptions, type RunCandidateExperimentOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunRecordRejection, type ScalarDistribution, type Scenario$1 as Scenario, type SealCandidateBenchmarkSuiteOptions, type SelfImproveBudget, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, SelfImproveRunError, type SessionScript, type SkillOptOptimizationMethodConfig, type SkillOptRunnerCommand, type SkillOptTrainerConfig, type SummarizeExecutionOptions, type SurfaceProposer, type TokenUsageInsight, analyzeRuns, buildDefaultAnalystRegistry, buildEvidenceVector, campaignSplitDigest, compareOptimizationMethods, composeGate, createChatClient, createReferenceEquivalenceJudge, defaultProductionGate, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, externalTextOptimizationMethod, fromClaudeCodeSession, fromCodexSession, fromFeedbackTable, fromKimiCodeSession, fromOpenCodeSession, fromOtelSpans, fromPiSession, fromPigraphSession, fromRunRecordDir, fsCampaignStorage, gepaOptimizationMethod, heldOutGate, inMemoryCampaignStorage, llmJudge, measuredComparisonFromCandidateExperiment, observeCodeAgentSession, paretoPolicy, paretoSignificanceGate, parseAgentTrace, parseCodeAgentJsonl, partitionRunsByAuthoringModel, runCampaign, runCandidateExperiment, runEval, runImprovementLoop, runReferenceEquivalenceJudge, sealCandidateBenchmarkSuite, sealCandidateBenchmarkTask, sealCandidateExperiment, selfImprove, skillOptOptimizationMethod, summarizeExecution, verifyCandidateBenchmarkSuite, verifyCandidateBenchmarkSuiteInputs, verifyCandidateBenchmarkTask, verifyCandidateExperiment, verifyCandidateExperimentComparison };
5466
+ export { type AgentEvalAgent, type AgentEvalEvaluateOptions, type AgentEvalImproveOptions, type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AnalystFinding, type AnalyzeRunsOptions, type AuthoringProvenance, type AxisEvidence, type AxisVerdict, type BuildEvidenceVectorOptions, type CampaignAggregates, type CampaignArtifactWriter, type CampaignCellFailureReceipt, type CampaignCellResult, type CampaignCostMeter, type CampaignResult, type CampaignStorage, type CampaignTraceWriter, type CandidateExperimentExecutionInput, type ChatClient, type CodeAgentSessionAction, type CodeAgentSessionActionKind, type CodeAgentSessionActionStatus, type CodeAgentSessionActionSurface, type CodeAgentSessionDiagnostic, type CodeAgentSessionExecutionReceipt, type CodeAgentSessionIntakeOptions, type CodeAgentSessionIntakeResult, type CodeAgentSessionMetrics, type CodeAgentSessionObservation, type CodeAgentSessionSource, type CodeAgentSessionTerminalStatus, type CodeSurface, type CompareCandidateExperimentOptions, type CompareOptimizationMethodsOptions, type ComparisonCost, type CostLedgerHandle, type CostProvenanceSummary, type CreateChatClientOpts, type DefaultAnalystRegistryOptions, type DefaultProductionGateOptions, type DefineAgentEvalOptions, type DefinedAgentEval, type DeploymentOutcome, type DispatchFn as Dispatch, type DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalReportingSuiteInput, type EvalReportingSuiteOptions, type EvalReportingSuiteResult, type EvalRunDiff, type EvidenceVector, type ExecutionInsight, type ExecutionReport, type ExternalOptimizationExample, type ExternalTextEvaluationResponse, type ExternalTextOptimizationMethodConfig, type ExternalTextOptimizerContext, type ExternalTextOptimizerResult, type FailureClusterInsight, type FeedbackTableMeta, type FeedbackTableRow, FileSystemOutcomeStore, type FileSystemOutcomeStoreOptions, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, type FromRunRecordDirOptions, type FromRunRecordDirResult, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaAdaptiveEngineRun, type GepaEngineOptions, type GepaEngineRun, type GepaOptimizationMethodConfig, type GepaOptimizationRecipe, type GepaRunnerCommand, type HeldOutGateOptions, type HostedTenant, InMemoryOutcomeStore, type InsightReport, type InterRaterInsight, type JudgeConfig, type JudgeDimension, type JudgeInsight, type JudgeScore, type LiftInsight, type LlmJudgeDimension, type LlmJudgeOptions, type MutableSurface, type ObjectiveSource, type OpenAICompatibleOptimizerModel, type OptimizationMethod, type OptimizationMethodComparison, type OptimizationMethodInput, type OptimizationMethodProvenance, type OptimizationMethodResult, type OptimizationPackageSource, type OptimizationProposer, type OptimizationTokenUsage, type OptimizerConfig, type OptimizerModelBudget, type OutcomeCorrelationInsight, type OutcomeStore, type ParetoSignificanceGateOptions, type ParsedCodeAgentJsonl, type PartitionByAuthoringModelResult, type PromotionObjective, type PromotionPolicy, REFERENCE_EQUIVALENCE_INPUT_LIMITS, REFERENCE_EQUIVALENCE_JUDGE_VERSION, type Recommendation, type ReferenceEquivalenceJudgeInput, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceJudgeResult, type ReferenceEquivalenceScenario, type ReleaseSummary, type RunCampaignOptions, type RunCandidateExperimentOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunRecordRejection, type ScalarDistribution, type Scenario$1 as Scenario, type SealCandidateBenchmarkSuiteOptions, type SelfImproveBudget, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, SelfImproveRunError, type SessionScript, type SkillOptOptimizationMethodConfig, type SkillOptRunnerCommand, type SkillOptTrainerConfig, type SummarizeExecutionOptions, type SurfaceProposer, type TokenUsageInsight, analyzeRuns, buildDefaultAnalystRegistry, buildEvidenceVector, campaignSplitDigest, compareOptimizationMethods, composeGate, createChatClient, createReferenceEquivalenceJudge, defaultProductionGate, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, externalTextOptimizationMethod, fromClaudeCodeSession, fromCodexSession, fromFeedbackTable, fromKimiCodeSession, fromOpenCodeSession, fromOtelSpans, fromPiSession, fromPigraphSession, fromRunRecordDir, fsCampaignStorage, gepaOptimizationMethod, heldOutGate, inMemoryCampaignStorage, llmJudge, measuredComparisonFromCandidateExperiment, observeCodeAgentSession, paretoPolicy, paretoSignificanceGate, parseAgentTrace, parseCodeAgentJsonl, partitionRunsByAuthoringModel, runCampaign, runCandidateExperiment, runEval, runImprovementLoop, runReferenceEquivalenceJudge, sealCandidateBenchmarkSuite, sealCandidateBenchmarkTask, sealCandidateExperiment, selfImprove, skillOptOptimizationMethod, summarizeExecution, verifyCandidateBenchmarkSuite, verifyCandidateBenchmarkSuiteInputs, verifyCandidateBenchmarkTask, verifyCandidateExperiment, verifyCandidateExperimentComparison };