@tangle-network/agent-eval 2.0.10 → 2.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-_JzxgLDM.d.ts → agent-profile-C0FBdYa6.d.ts} +3 -3
- package/dist/{agent-profile-_JzxgLDM.d.ts.map → agent-profile-C0FBdYa6.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +292 -74
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +11 -161
- package/dist/analyst/index.js.map +1 -1
- package/dist/app-grade/index.d.ts +2 -2
- package/dist/app-grade/index.js +3 -3
- package/dist/{benchmark-command-CGQXNFj7.js → benchmark-command-Be5O6A2v.js} +797 -13
- package/dist/benchmark-command-Be5O6A2v.js.map +1 -0
- package/dist/benchmarks/index.d.ts +5 -5
- package/dist/benchmarks/index.d.ts.map +1 -1
- package/dist/benchmarks/index.js +19 -10
- package/dist/benchmarks/index.js.map +1 -1
- package/dist/campaign/index.d.ts +5 -5
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-eus7YRs2.js → campaign-CE08mvQO.js} +11 -11
- package/dist/{campaign-eus7YRs2.js.map → campaign-CE08mvQO.js.map} +1 -1
- package/dist/{campaign-evidence-KM5GTsHG.js → campaign-evidence-71uzJMVY.js} +2 -2
- package/dist/{campaign-evidence-KM5GTsHG.js.map → campaign-evidence-71uzJMVY.js.map} +1 -1
- package/dist/{campaign-evidence-BOcX4w0r.d.ts → campaign-evidence-DRvr7lZU.d.ts} +2 -2
- package/dist/{campaign-evidence-BOcX4w0r.d.ts.map → campaign-evidence-DRvr7lZU.d.ts.map} +1 -1
- package/dist/{chat-client-Oyot5tyo.js → chat-client-TkNgQDLj.js} +2 -2
- package/dist/{chat-client-Oyot5tyo.js.map → chat-client-TkNgQDLj.js.map} +1 -1
- package/dist/{chat-json-call-DTmv2uNY.js → chat-json-call-gu3deRID.js} +2 -2
- package/dist/{chat-json-call-DTmv2uNY.js.map → chat-json-call-gu3deRID.js.map} +1 -1
- package/dist/cli.js +778 -10
- package/dist/cli.js.map +1 -1
- package/dist/code-agent-jsonl-aPWZG3vr.js +104 -0
- package/dist/code-agent-jsonl-aPWZG3vr.js.map +1 -0
- package/dist/{completion-verifier-CCPG2Yc0.js → completion-verifier-BvPqg9Gp.js} +4 -4
- package/dist/{completion-verifier-CCPG2Yc0.js.map → completion-verifier-BvPqg9Gp.js.map} +1 -1
- package/dist/contract/index.d.ts +8 -8
- package/dist/contract/index.js +16 -112
- package/dist/contract/index.js.map +1 -1
- package/dist/{cost-ledger-C5CCidPm.js → cost-ledger-ni6f77QJ.js} +106 -50
- package/dist/cost-ledger-ni6f77QJ.js.map +1 -0
- package/dist/{decision-point-CfqtnGop.js → decision-point-CjC56Enj.js} +2 -2
- package/dist/{decision-point-CfqtnGop.js.map → decision-point-CjC56Enj.js.map} +1 -1
- package/dist/{default-registry-Rs5uzlfJ.js → default-registry-C5iSuS8e.js} +5 -5
- package/dist/{default-registry-Rs5uzlfJ.js.map → default-registry-C5iSuS8e.js.map} +1 -1
- package/dist/{default-registry-X8McMoUV.d.ts → default-registry-DFRlBniE.d.ts} +2 -2
- package/dist/{default-registry-X8McMoUV.d.ts.map → default-registry-DFRlBniE.d.ts.map} +1 -1
- package/dist/{define-agent-eval-D8ntOXqV.js → define-agent-eval-BHn6t-DC.js} +4 -4
- package/dist/{define-agent-eval-D8ntOXqV.js.map → define-agent-eval-BHn6t-DC.js.map} +1 -1
- package/dist/{define-agent-eval-DH5-xi-F.d.ts → define-agent-eval-n63vmQMR.d.ts} +4 -4
- package/dist/{define-agent-eval-DH5-xi-F.d.ts.map → define-agent-eval-n63vmQMR.d.ts.map} +1 -1
- package/dist/{dspy-rlm-engine-ChE1PUM5.js → dspy-rlm-engine-CR5MSL2k.js} +6 -5
- package/dist/{dspy-rlm-engine-ChE1PUM5.js.map → dspy-rlm-engine-CR5MSL2k.js.map} +1 -1
- package/dist/{evaluation-BAisv8ZR.js → evaluation-DqfNMaKr.js} +2 -2
- package/dist/{evaluation-BAisv8ZR.js.map → evaluation-DqfNMaKr.js.map} +1 -1
- package/dist/{evaluation-CjZH6gW0.d.ts → evaluation-VbjqORBn.d.ts} +2 -2
- package/dist/{evaluation-CjZH6gW0.d.ts.map → evaluation-VbjqORBn.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/evaluation.js +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.js +1 -1
- package/dist/{external-optimizer-contracts-BFV8lnhl.js → external-optimizer-contracts-vrye9kti.js} +2 -2
- package/dist/{external-optimizer-contracts-BFV8lnhl.js.map → external-optimizer-contracts-vrye9kti.js.map} +1 -1
- package/dist/{external-optimizer-process-B6emPodQ.js → external-optimizer-process-DkOMkeHW.js} +3 -3
- package/dist/{external-optimizer-process-B6emPodQ.js.map → external-optimizer-process-DkOMkeHW.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-_O06eDVA.js → external-optimizer-subprocess-CFIiwHSE.js} +3 -3
- package/dist/{external-optimizer-subprocess-_O06eDVA.js.map → external-optimizer-subprocess-CFIiwHSE.js.map} +1 -1
- package/dist/{finding-scope-B_As3F_v.js → finding-scope-BVQVcjz7.js} +2 -2
- package/dist/{finding-scope-B_As3F_v.js.map → finding-scope-BVQVcjz7.js.map} +1 -1
- package/dist/{findings-store-CvYUzQBR.js → findings-store-Drnjid7m.js} +5 -5
- package/dist/{findings-store-CvYUzQBR.js.map → findings-store-Drnjid7m.js.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-BmWw8zN6.d.ts → index-BEXEYURJ.d.ts} +7 -7
- package/dist/{index-BmWw8zN6.d.ts.map → index-BEXEYURJ.d.ts.map} +1 -1
- package/dist/{index-ZffK_5sD.d.ts → index-CbzPtg7O.d.ts} +205 -29
- package/dist/index-CbzPtg7O.d.ts.map +1 -0
- package/dist/{index-CCOaNmh2.d.ts → index-Dt3zWlRa.d.ts} +3 -3
- package/dist/{index-CCOaNmh2.d.ts.map → index-Dt3zWlRa.d.ts.map} +1 -1
- package/dist/{index-aRalB_Ma.d.ts → index-rrPT3Pw0.d.ts} +2 -2
- package/dist/{index-aRalB_Ma.d.ts.map → index-rrPT3Pw0.d.ts.map} +1 -1
- package/dist/index.d.ts +13 -13
- package/dist/index.js +471 -22
- package/dist/index.js.map +1 -1
- package/dist/{judge-gate-CpD3wmcf.js → judge-gate-WgYqQ9LA.js} +2 -2
- package/dist/{judge-gate-CpD3wmcf.js.map → judge-gate-WgYqQ9LA.js.map} +1 -1
- package/dist/{kind-factory-B-xCxG7p.js → kind-factory-C8MJpMTV.js} +2 -2
- package/dist/{kind-factory-B-xCxG7p.js.map → kind-factory-C8MJpMTV.js.map} +1 -1
- package/dist/{llm-client-Dk8lBnMh.js → llm-client-D4B1qR_1.js} +2 -2
- package/dist/{llm-client-Dk8lBnMh.js.map → llm-client-D4B1qR_1.js.map} +1 -1
- package/dist/{llm-judge-DYmEdo3M.js → llm-judge-CgF3ZM3R.js} +4 -4
- package/dist/{llm-judge-DYmEdo3M.js.map → llm-judge-CgF3ZM3R.js.map} +1 -1
- package/dist/{matrix-BDl7hoBr.d.ts → matrix-B95YsrV7.d.ts} +2 -2
- package/dist/{matrix-BDl7hoBr.d.ts.map → matrix-B95YsrV7.d.ts.map} +1 -1
- package/dist/meta-eval/index.js +2 -2
- package/dist/metrics-C6pXdupw.js +9 -0
- package/dist/metrics-C6pXdupw.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +6 -6
- package/dist/multishot/index.js +8 -7
- package/dist/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{optimization-method-4JlbMxd2.js → optimization-method-1xzXK-B6.js} +9 -9
- package/dist/{optimization-method-4JlbMxd2.js.map → optimization-method-1xzXK-B6.js.map} +1 -1
- package/dist/{proposal-findings-CfRFCFXS.js → proposal-findings-BCd4KjLy.js} +2 -2
- package/dist/{proposal-findings-CfRFCFXS.js.map → proposal-findings-BCd4KjLy.js.map} +1 -1
- package/dist/rl.d.ts +1 -1
- package/dist/rollout/index.d.ts +2 -2
- package/dist/rollout/index.js +1 -1
- package/dist/{rollout--rSr43Pd.js → rollout-CbHMVoDr.js} +2 -2
- package/dist/{rollout--rSr43Pd.js.map → rollout-CbHMVoDr.js.map} +1 -1
- package/dist/{run-improvement-loop-BeHu5D9Z.d.ts → run-improvement-loop-BPhkYKV2.d.ts} +5 -5
- package/dist/{run-improvement-loop-BeHu5D9Z.d.ts.map → run-improvement-loop-BPhkYKV2.d.ts.map} +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-mZc79S6N.js → search-kernel-BkkDo75N.js} +2 -2
- package/dist/{search-kernel-mZc79S6N.js.map → search-kernel-BkkDo75N.js.map} +1 -1
- package/dist/{search-kernel-CJZ-ZSV1.d.ts → search-kernel-CDSEWa2X.d.ts} +2 -2
- package/dist/{search-kernel-CJZ-ZSV1.d.ts.map → search-kernel-CDSEWa2X.d.ts.map} +1 -1
- package/dist/{search-ledger-C7t68cmy.js → search-ledger-sormHFLS.js} +17 -1
- package/dist/search-ledger-sormHFLS.js.map +1 -0
- package/dist/{search-shipper-CmDW9dU6.js → search-shipper-BJ2Bkx2q.js} +2 -2
- package/dist/{search-shipper-CmDW9dU6.js.map → search-shipper-BJ2Bkx2q.js.map} +1 -1
- package/dist/{search-summary-CCgP2qXz.js → search-summary-DMckFUNY.js} +2 -2
- package/dist/{search-summary-CCgP2qXz.js.map → search-summary-DMckFUNY.js.map} +1 -1
- package/dist/{self-improve-C_Bcdmv8.js → self-improve-CMrPmjYE.js} +5 -5
- package/dist/{self-improve-C_Bcdmv8.js.map → self-improve-CMrPmjYE.js.map} +1 -1
- package/dist/{self-improve-B1fsNejr.d.ts → self-improve-D0TtJz4e.d.ts} +5 -5
- package/dist/{self-improve-B1fsNejr.d.ts.map → self-improve-D0TtJz4e.d.ts.map} +1 -1
- package/dist/{server-aZFmRucn.js → server-B-7vXS9T.js} +4 -4
- package/dist/{server-aZFmRucn.js.map → server-B-7vXS9T.js.map} +1 -1
- package/dist/{skillopt-optimization-method-DHk1K757.js → skillopt-optimization-method-D-BPMi8J.js} +9 -9
- package/dist/{skillopt-optimization-method-DHk1K757.js.map → skillopt-optimization-method-D-BPMi8J.js.map} +1 -1
- package/dist/{store-otlp-CdeW7NWq.js → store-otlp-DL30pdXE.js} +2 -2
- package/dist/{store-otlp-CdeW7NWq.js.map → store-otlp-DL30pdXE.js.map} +1 -1
- package/dist/{store-tool-spans-CVX-jfkk.js → store-tool-spans-DRdpbrnb.js} +3 -3
- package/dist/{store-tool-spans-CVX-jfkk.js.map → store-tool-spans-DRdpbrnb.js.map} +1 -1
- package/dist/{systemone-4PadCE4C.d.ts → systemone-C26IFS-a.d.ts} +3 -3
- package/dist/{systemone-4PadCE4C.d.ts.map → systemone-C26IFS-a.d.ts.map} +1 -1
- package/dist/systemone.d.ts +2 -2
- package/dist/systemone.js +2 -2
- package/dist/traces.js +3 -3
- package/dist/{tree-CiIe-f3f.js → tree-BX9ykHi3.js} +3 -3
- package/dist/{tree-CiIe-f3f.js.map → tree-BX9ykHi3.js.map} +1 -1
- package/dist/{types-D5XtEH9Q.d.ts → types-CBT-XcX5.d.ts} +14 -1
- package/dist/types-CBT-XcX5.d.ts.map +1 -0
- package/dist/{types-an-CUndX.d.ts → types-CYPV2dlR.d.ts} +52 -5
- package/dist/types-CYPV2dlR.d.ts.map +1 -0
- package/dist/wire/index.js +1 -1
- package/docs/feature-guide.md +2 -0
- package/docs/public-api.md +23 -16
- package/docs/skill-eval.md +103 -0
- package/package.json +4 -2
- package/dist/benchmark-command-CGQXNFj7.js.map +0 -1
- package/dist/cost-ledger-C5CCidPm.js.map +0 -1
- package/dist/index-ZffK_5sD.d.ts.map +0 -1
- package/dist/search-ledger-C7t68cmy.js.map +0 -1
- package/dist/types-D5XtEH9Q.d.ts.map +0 -1
- package/dist/types-an-CUndX.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"campaign-eus7YRs2.js","names":["validateAndIndex","rowFor","componentSetKey","rowsFor","canonicalComponents","difficulty","calibration","scoreOf","esc","fsConstants"],"sources":["../src/campaign/cost-breakdown.ts","../src/campaign/cross-surface-context.ts","../src/campaign/cross-surface-evidence.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/neutralize.ts","../src/campaign/optimization-method-composition.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/profile-matrix-stability.ts","../src/campaign/presets/profile-matrix-analysis.ts","../src/campaign/presets/profile-matrix-report.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/segmented-profile-matrix.ts","../src/campaign/presets/race-profile-matrix.ts","../src/campaign/repeat-reliability.ts","../src/campaign/retained-dispatch.ts","../src/campaign/scenario-selection.ts","../src/campaign/worktree/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { CostBreakdown, CostUsage } from '../cost-ledger'\n\n/** Read the source rates for this execution, never a copied model price table.\n * inputTokens includes cachedTokens. Seat credits are standard model credits;\n * discounts and MCP charges require provider observations, not token guesses.\n * The existing USD receipt remains the Router charge. Sandbox is additional.\n */\nexport async function measureCampaignCost(input: {\n routerUsd?: number\n sandbox?: { seconds: number; cpu: number; memoryGB: number; diskGB: number; pool?: string }\n seat?: { model: string; usage: CostUsage & { usageUnknown?: boolean } }\n signal?: AbortSignal\n}): Promise<CostBreakdown> {\n const sources: CostBreakdown['sources'] = []\n const unknown = { kind: 'uncaptured', usd: null } as const\n if (input.routerUsd !== undefined) finite(input.routerUsd, 'routerUsd')\n const result: CostBreakdown = {\n router: input.routerUsd === undefined ? unknown : { kind: 'observed', usd: input.routerUsd },\n sandbox: unknown,\n seatCredits: { kind: 'uncaptured', credits: null, reason: 'No seat usage supplied' },\n sources,\n }\n const read = async (url: string) => {\n const response = await fetch(url, {\n signal: input.signal\n ? AbortSignal.any([input.signal, AbortSignal.timeout(15_000)])\n : AbortSignal.timeout(15_000),\n })\n if (!response.ok) throw new Error(`Rate source HTTP ${response.status}`)\n // Refuse a changed/unbounded document rather than importing arbitrary data.\n if (Number(response.headers.get('content-length')) > 1_000_000)\n throw new Error('Rate source too large')\n const chunks: Uint8Array[] = []\n let bytes = 0\n for await (const chunk of response.body ?? []) {\n bytes += chunk.byteLength\n if (bytes > 1_000_000) throw new Error('Rate source too large')\n chunks.push(chunk)\n }\n const text = Buffer.concat(chunks).toString('utf8')\n return {\n text,\n snapshot: {\n url,\n readAt: new Date().toISOString(),\n sha256: createHash('sha256').update(text).digest('hex'),\n },\n }\n }\n if (input.sandbox) {\n for (const [key, value] of Object.entries(input.sandbox))\n if (key !== 'pool') finite(value, `sandbox.${key}`)\n try {\n const { text, snapshot } = await read('https://sandbox.tangle.tools/v1/pricing/sandboxes')\n const card = JSON.parse(text).pools?.[input.sandbox.pool ?? 'general']\n const rates: Record<string, number> = {}\n for (const key of [\n 'cpuCoreHourUsd',\n 'memoryGBHourUsd',\n 'diskGBHourUsd',\n 'minChargeHourUsd',\n ]) {\n finite(card?.[key], key)\n rates[key] = card[key]\n }\n const s = input.sandbox\n const hourly = Math.max(\n rates.minChargeHourUsd!,\n s.cpu * rates.cpuCoreHourUsd! +\n s.memoryGB * rates.memoryGBHourUsd! +\n s.diskGB * rates.diskGBHourUsd!,\n )\n const usd = (hourly * s.seconds) / 3600\n finite(usd, 'sandbox USD estimate')\n result.sandbox = { kind: 'estimated', usd }\n sources.push({ ...snapshot, rates })\n } catch {\n // A missing rate leaves the estimate unknown while preserving Router observations.\n }\n }\n if (input.seat) {\n const { usage, model } = input.seat\n if (usage.usageUnknown || usage.cachedTokens === undefined) {\n result.seatCredits = {\n kind: 'uncaptured',\n credits: null,\n reason: 'Seat token or cached-input usage is unknown',\n }\n return result\n }\n for (const key of ['inputTokens', 'cachedTokens', 'outputTokens'] as const) {\n const value = usage[key]\n if (!Number.isSafeInteger(value) || value! < 0)\n throw new Error(`seat.${key} must be a known nonnegative token count`)\n }\n if (usage.cachedTokens! > usage.inputTokens) throw new Error('cachedTokens exceeds inputTokens')\n try {\n const { text, snapshot } = await read('https://docs.z.ai/devpack/overview.md')\n const modelName = model.split('/').at(-1)!.toLowerCase()\n const section = text\n .split('#### Credit Calculation')[1]\n ?.split('#### Estimated Token Allowance')[0]\n if (!section) throw new Error('Credit calculation section unavailable')\n const rows = [...section.matchAll(/<tr>\\s*([\\s\\S]*?)<\\/tr>/gu)]\n const matching = rows.filter((row) => {\n const cells = [...row[1]!.matchAll(/<td\\b[^>]*>([\\s\\S]*?)<\\/td>/gu)].map((cell) =>\n cell[1]!.trim(),\n )\n return cells.some(\n (cell) =>\n cell\n .split(/\\\\|\\n|</u)[0]!\n .trim()\n .toLowerCase() === modelName,\n )\n })\n if (matching.length !== 1) throw new Error(`No unique live credit row for '${model}'`)\n const cells = [...matching[0]![1]!.matchAll(/<td\\b[^>]*>([\\s\\S]*?)<\\/td>/gu)].map((cell) =>\n cell[1]!.trim(),\n )\n const rateCells = cells.slice(-3)\n if (rateCells.length !== 3 || rateCells.some((cell) => !/^(?:\\d+)(?:\\.\\d+)?$/u.test(cell)))\n throw new Error('Invalid live credit multipliers')\n const multipliers = rateCells.map(Number)\n for (const rate of multipliers) finite(rate, 'credit multiplier')\n const divisor = Number(\n section.match(/Model credit usage[^\\n]*\\/\\s*([\\d,]+)/u)?.[1]?.replaceAll(',', ''),\n )\n if (!Number.isFinite(divisor) || divisor <= 0) throw new Error('No live credit divisor')\n const [fresh, cached, output] = multipliers as [number, number, number]\n const credits =\n ((usage.inputTokens - usage.cachedTokens!) * fresh +\n usage.cachedTokens! * cached +\n usage.outputTokens * output) /\n divisor\n finite(credits, 'standard seat credits')\n result.seatCredits = { kind: 'estimated', credits }\n sources.push({\n ...snapshot,\n rates: {\n inputMultiplier: fresh,\n cachedInputMultiplier: cached,\n outputMultiplier: output,\n divisor,\n },\n })\n } catch (error) {\n result.seatCredits = {\n kind: 'uncaptured',\n credits: null,\n reason: error instanceof Error ? error.message : 'Credit source unavailable',\n }\n }\n }\n return result\n}\n\nfunction finite(value: unknown, label: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)\n throw new Error(`${label} must be finite and nonnegative`)\n}\n","import { ValidationError } from '../errors'\nimport type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceCandidate,\n CrossSurfaceComponent,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\n/** Validated indexes shared by analysis and deterministic selection. */\nexport interface CrossSurfaceAnalysisContext<TRow extends CrossSurfaceTaskRow> {\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>\n components: CrossSurfaceComponent[]\n candidates: CrossSurfaceCandidate[]\n componentById: Map<string, CrossSurfaceComponent>\n candidateById: Map<string, CrossSurfaceCandidate>\n candidateByComponents: Map<string, CrossSurfaceCandidate>\n singleByComponent: Map<string, CrossSurfaceCandidate>\n rowsByCandidate: Map<string, Map<string, TRow>>\n componentIndex: Map<string, number>\n candidateIndex: Map<string, number>\n}\n\nexport function validateCrossSurfaceInput<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): CrossSurfaceAnalysisContext<TRow> {\n assertNonEmptyUnique(input.taskOrder, 'taskOrder')\n assertNonEmptyUnique(input.componentOrder, 'componentOrder')\n if (input.componentOrder.length < 2) {\n throw new ValidationError(\n 'analyzeCrossSurfaceInteractions: componentOrder must contain at least two surfaces',\n )\n }\n assertNonEmptyUnique(input.candidateOrder, 'candidateOrder')\n assertNonEmptyUnique(input.costMetricOrder, 'costMetricOrder')\n if (input.costMetricOrder.includes('score')) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: costMetricOrder cannot contain reserved metric 'score'`,\n )\n }\n validateBootstrap(input)\n validateSelection(input)\n\n const componentById = indexUnique(\n input.components,\n (component) => component.componentId,\n 'component',\n )\n assertExactSet(input.componentOrder, componentById.keys(), 'componentOrder', 'components')\n const surfaces = new Set<string>()\n for (const component of componentById.values()) {\n assertNonEmpty(component.componentId, 'componentId')\n assertNonEmpty(component.surfaceId, `surfaceId for component '${component.componentId}'`)\n if (surfaces.has(component.surfaceId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: surfaceId '${component.surfaceId}' has more than one component; ` +\n 'the interaction stage requires one independently selected finalist per surface',\n )\n }\n surfaces.add(component.surfaceId)\n if (typeof component.bestSingleEligible !== 'boolean') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: component '${component.componentId}' must declare bestSingleEligible`,\n )\n }\n }\n\n const componentIndex = new Map(input.componentOrder.map((id, index) => [id, index]))\n const candidateById = indexUnique(\n input.candidates,\n (candidate) => candidate.candidateId,\n 'candidate',\n )\n assertExactSet(input.candidateOrder, candidateById.keys(), 'candidateOrder', 'candidates')\n if (!candidateById.has(input.baselineCandidateId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: unknown baselineCandidateId '${input.baselineCandidateId}'`,\n )\n }\n\n const candidateByComponents = new Map<string, CrossSurfaceCandidate>()\n const singleByComponent = new Map<string, CrossSurfaceCandidate>()\n for (const candidate of candidateById.values()) {\n validateCandidate(candidate, componentById, componentIndex, input.baselineCandidateId)\n const key = crossSurfaceComponentSetKey(candidate.componentIds)\n const duplicate = candidateByComponents.get(key)\n if (duplicate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidates '${duplicate.candidateId}' and ` +\n `'${candidate.candidateId}' materialize the same component set`,\n )\n }\n candidateByComponents.set(key, candidate)\n if (candidate.componentIds.length === 1) {\n singleByComponent.set(candidate.componentIds[0]!, candidate)\n }\n }\n const baseline = candidateById.get(input.baselineCandidateId)!\n if (baseline.componentIds.length !== 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: baseline '${baseline.candidateId}' must have zero components`,\n )\n }\n for (const componentId of input.componentOrder) {\n if (!singleByComponent.has(componentId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: no single-surface candidate for component '${componentId}'`,\n )\n }\n }\n for (let left = 0; left < input.componentOrder.length; left++) {\n for (let right = left + 1; right < input.componentOrder.length; right++) {\n const ids = [input.componentOrder[left]!, input.componentOrder[right]!]\n if (!candidateByComponents.has(crossSurfaceComponentSetKey(ids))) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: missing pair candidate for components [${ids.join(', ')}]`,\n )\n }\n }\n }\n\n const rowsByCandidate = new Map<string, Map<string, TRow>>()\n const taskIds = new Set(input.taskOrder)\n for (const row of input.rows) {\n const candidate = candidateById.get(row.candidateId)\n if (!candidate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row for task '${row.taskId}' names unknown candidate '${row.candidateId}'`,\n )\n }\n if (!taskIds.has(row.taskId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row for candidate '${row.candidateId}' names task '${row.taskId}' ` +\n 'outside the declared taskOrder',\n )\n }\n validateRow(input, row, candidate)\n const byTask = rowsByCandidate.get(row.candidateId) ?? new Map<string, TRow>()\n if (byTask.has(row.taskId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: duplicate row for candidate '${row.candidateId}' and task '${row.taskId}'`,\n )\n }\n byTask.set(row.taskId, row)\n rowsByCandidate.set(row.candidateId, byTask)\n }\n for (const candidateId of input.candidateOrder) {\n const byTask = rowsByCandidate.get(candidateId)\n const missing = input.taskOrder.filter((taskId) => !byTask?.has(taskId))\n if (missing.length > 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidateId}' is missing declared task row(s) ` +\n `[${missing.join(', ')}]; encode failed attempts explicitly instead of changing the task axis`,\n )\n }\n }\n const expectedRows = input.candidateOrder.length * input.taskOrder.length\n if (input.rows.length !== expectedRows) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: expected exactly ${expectedRows} candidate × task rows, got ${input.rows.length}`,\n )\n }\n\n return {\n input,\n components: input.componentOrder.map((id) => componentById.get(id)!),\n candidates: input.candidateOrder.map((id) => candidateById.get(id)!),\n componentById,\n candidateById,\n candidateByComponents,\n singleByComponent,\n rowsByCandidate,\n componentIndex,\n candidateIndex: new Map(input.candidateOrder.map((id, index) => [id, index])),\n }\n}\n\nexport function crossSurfaceRowsFor<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n candidateId: string,\n): TRow[] {\n return context.input.taskOrder.map((taskId) => crossSurfaceRowFor(context, candidateId, taskId))\n}\n\nexport function crossSurfaceRowFor<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n candidateId: string,\n taskId: string,\n): TRow {\n return context.rowsByCandidate.get(candidateId)!.get(taskId)!\n}\n\nexport function canonicalCrossSurfaceComponents<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n componentIds: string[],\n): string[] {\n return [...componentIds].sort(\n (left, right) => context.componentIndex.get(left)! - context.componentIndex.get(right)!,\n )\n}\n\nexport function crossSurfaceComponentSetKey(componentIds: readonly string[]): string {\n return JSON.stringify(componentIds)\n}\n\nfunction validateBootstrap<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): void {\n const { seed, resamples, confidence } = input.bootstrap\n if (!Number.isInteger(seed)) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: bootstrap.seed must be an integer`)\n }\n if (!Number.isInteger(resamples) || resamples <= 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: bootstrap.resamples must be a positive integer`,\n )\n }\n if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: bootstrap.confidence must be in (0,1)`,\n )\n }\n}\n\nfunction validateSelection<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): void {\n const policy = input.selection\n for (const [name, value] of [\n ['minimumFiringTasks', policy.minimumFiringTasks],\n ['minimumEffectTasks', policy.minimumEffectTasks],\n ] as const) {\n if (!Number.isInteger(value) || value < 0 || value > input.taskOrder.length) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: selection.${name} must be an integer in [0,${input.taskOrder.length}]`,\n )\n }\n }\n if (\n !Number.isInteger(policy.minimumBundleComponents) ||\n policy.minimumBundleComponents < 2 ||\n policy.minimumBundleComponents > input.componentOrder.length\n ) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: selection.minimumBundleComponents must be an integer in ` +\n `[2,${input.componentOrder.length}]`,\n )\n }\n for (const [metric, limit] of Object.entries(policy.maximumMedianCostRatioToBaseline)) {\n if (!input.costMetricOrder.includes(metric)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: cost limit names undeclared metric '${metric}'`,\n )\n }\n if (!Number.isFinite(limit) || limit <= 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: cost ratio limit for '${metric}' must be positive and finite`,\n )\n }\n }\n}\n\nfunction validateCandidate(\n candidate: CrossSurfaceCandidate,\n componentById: Map<string, CrossSurfaceComponent>,\n componentIndex: Map<string, number>,\n baselineCandidateId: string,\n): void {\n assertNonEmpty(candidate.candidateId, 'candidateId')\n assertNonEmpty(candidate.contentHash, `contentHash for candidate '${candidate.candidateId}'`)\n if (!Number.isInteger(candidate.artifactBytes) || candidate.artifactBytes < 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: artifactBytes for candidate '${candidate.candidateId}' must be a non-negative integer`,\n )\n }\n assertUnique(candidate.componentIds, `componentIds for candidate '${candidate.candidateId}'`)\n for (const componentId of candidate.componentIds) {\n if (!componentById.has(componentId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidate.candidateId}' names unknown component '${componentId}'`,\n )\n }\n }\n const canonical = [...candidate.componentIds].sort(\n (left, right) => componentIndex.get(left)! - componentIndex.get(right)!,\n )\n if (!arraysEqual(candidate.componentIds, canonical)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidate.candidateId}' components must follow componentOrder`,\n )\n }\n if (candidate.candidateId !== baselineCandidateId && candidate.componentIds.length === 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: only baseline '${baselineCandidateId}' may have zero components`,\n )\n }\n}\n\nfunction validateRow<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n row: TRow,\n candidate: CrossSurfaceCandidate,\n): void {\n if (!arraysEqual(row.componentIds, candidate.componentIds)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row '${row.candidateId}/${row.taskId}' componentIds do not match its candidate`,\n )\n }\n if (!['complete', 'missing', 'invalid'].includes(row.completeness)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row '${row.candidateId}/${row.taskId}' has unknown completeness '${String(row.completeness)}'`,\n )\n }\n if (row.completeness === 'complete') {\n if (typeof row.pass !== 'boolean' || !Number.isFinite(row.score)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: complete row '${row.candidateId}/${row.taskId}' requires boolean pass and finite score`,\n )\n }\n if (row.rejectReason !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: complete row '${row.candidateId}/${row.taskId}' cannot carry rejectReason`,\n )\n }\n } else {\n if (row.pass !== null || row.score !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${row.completeness} row '${row.candidateId}/${row.taskId}' must use null pass and score`,\n )\n }\n if (typeof row.rejectReason !== 'string' || row.rejectReason.trim() === '') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${row.completeness} row '${row.candidateId}/${row.taskId}' requires rejectReason`,\n )\n }\n }\n assertExactSet(\n input.costMetricOrder,\n Object.keys(row.cost),\n `cost keys for row '${row.candidateId}/${row.taskId}'`,\n 'costMetricOrder',\n )\n for (const metric of input.costMetricOrder) {\n const value = row.cost[metric]\n if (value === null || value === undefined || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: unknown or invalid cost '${metric}' on row ` +\n `'${row.candidateId}/${row.taskId}'; every attempt must report a non-negative finite value`,\n )\n }\n }\n const evidenceByComponent = indexUnique(\n row.componentEvidence,\n (evidence) => evidence.componentId,\n `componentEvidence on row '${row.candidateId}/${row.taskId}'`,\n )\n assertExactSet(\n candidate.componentIds,\n evidenceByComponent.keys(),\n `componentEvidence on row '${row.candidateId}/${row.taskId}'`,\n 'candidate components',\n )\n for (const evidence of evidenceByComponent.values()) {\n assertTriState(evidence.fired, 'fired', row)\n assertTriState(evidence.effectObserved, 'effectObserved', row)\n if (evidence.effectObserved === true && evidence.fired !== true) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: effectObserved=true requires fired=true for component ` +\n `'${evidence.componentId}' on row '${row.candidateId}/${row.taskId}'`,\n )\n }\n }\n}\n\nfunction assertTriState<TRow extends CrossSurfaceTaskRow>(\n value: boolean | null,\n field: string,\n row: TRow,\n): void {\n if (value !== true && value !== false && value !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${field} on row '${row.candidateId}/${row.taskId}' must be boolean or null`,\n )\n }\n}\n\nfunction indexUnique<T>(\n items: readonly T[],\n id: (item: T) => string,\n label: string,\n): Map<string, T> {\n const result = new Map<string, T>()\n for (const item of items) {\n const key = id(item)\n assertNonEmpty(key, `${label} id`)\n if (result.has(key)) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: duplicate ${label} id '${key}'`)\n }\n result.set(key, item)\n }\n return result\n}\n\nfunction assertNonEmptyUnique(values: readonly string[], label: string): void {\n if (values.length === 0) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: ${label} is empty`)\n }\n assertUnique(values, label)\n for (const value of values) assertNonEmpty(value, label)\n}\n\nfunction assertUnique(values: readonly string[], label: string): void {\n if (new Set(values).size !== values.length) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: ${label} contains duplicates`)\n }\n}\n\nfunction assertNonEmpty(value: string, label: string): void {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${label} must be a non-empty string`,\n )\n }\n}\n\nfunction assertExactSet(\n expected: readonly string[],\n actualIterable: Iterable<string>,\n actualLabel: string,\n expectedLabel: string,\n): void {\n const actual = [...actualIterable]\n const expectedSet = new Set(expected)\n const actualSet = new Set(actual)\n const missing = expected.filter((value) => !actualSet.has(value))\n const extra = actual.filter((value) => !expectedSet.has(value))\n if (missing.length > 0 || extra.length > 0 || actual.length !== expected.length) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${actualLabel} does not match ${expectedLabel}; ` +\n `missing=[${missing.join(', ')}], extra=[${extra.join(', ')}]`,\n )\n }\n}\n\nfunction arraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n","import type {\n CrossSurfaceCandidateEvidence,\n CrossSurfaceEvidenceBreakdown,\n CrossSurfacePairEvidence,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\nexport function summarizeCandidateEvidence<TRow extends CrossSurfaceTaskRow>(\n rows: TRow[],\n componentIds: string[],\n field: 'fired' | 'effectObserved',\n): CrossSurfaceCandidateEvidence {\n if (componentIds.length === 0) {\n return {\n byComponent: [],\n allObservedTaskIds: [],\n someObservedTaskIds: [],\n noneObservedTaskIds: [],\n unobservedTaskIds: [],\n }\n }\n const byComponent: CrossSurfaceEvidenceBreakdown[] = componentIds.map((componentId) => {\n const observedTaskIds: string[] = []\n const notObservedTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const value = evidenceValue(row, componentId, field)\n if (value === true) observedTaskIds.push(row.taskId)\n else if (value === false) notObservedTaskIds.push(row.taskId)\n else unobservedTaskIds.push(row.taskId)\n }\n return { componentId, observedTaskIds, notObservedTaskIds, unobservedTaskIds }\n })\n const allObservedTaskIds: string[] = []\n const someObservedTaskIds: string[] = []\n const noneObservedTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const values = componentIds.map((componentId) => evidenceValue(row, componentId, field))\n if (values.some((value) => value === null)) unobservedTaskIds.push(row.taskId)\n else if (values.every(Boolean)) allObservedTaskIds.push(row.taskId)\n else if (values.some(Boolean)) someObservedTaskIds.push(row.taskId)\n else noneObservedTaskIds.push(row.taskId)\n }\n return {\n byComponent,\n allObservedTaskIds,\n someObservedTaskIds,\n noneObservedTaskIds,\n unobservedTaskIds,\n }\n}\n\nexport function summarizePairEvidence<TRow extends CrossSurfaceTaskRow>(\n rows: TRow[],\n leftComponentId: string,\n rightComponentId: string,\n field: 'fired' | 'effectObserved',\n): CrossSurfacePairEvidence {\n const bothTaskIds: string[] = []\n const leftOnlyTaskIds: string[] = []\n const rightOnlyTaskIds: string[] = []\n const neitherTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const left = evidenceValue(row, leftComponentId, field)\n const right = evidenceValue(row, rightComponentId, field)\n if (left === null || right === null) unobservedTaskIds.push(row.taskId)\n else if (left && right) bothTaskIds.push(row.taskId)\n else if (left) leftOnlyTaskIds.push(row.taskId)\n else if (right) rightOnlyTaskIds.push(row.taskId)\n else neitherTaskIds.push(row.taskId)\n }\n return {\n bothTaskIds,\n leftOnlyTaskIds,\n rightOnlyTaskIds,\n neitherTaskIds,\n unobservedTaskIds,\n }\n}\n\nfunction evidenceValue(\n row: CrossSurfaceTaskRow,\n componentId: string,\n field: 'fired' | 'effectObserved',\n): boolean | null {\n return row.componentEvidence.find((evidence) => evidence.componentId === componentId)![field]\n}\n\nexport function appendEvidenceReasons<TReason extends string>(\n reasons: TReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: TReason,\n unobservedReason: TReason,\n): void {\n if (evidence.byComponent.some((component) => component.observedTaskIds.length < minimum)) {\n reasons.push(belowReason)\n }\n if (\n requireObserved &&\n evidence.byComponent.some((component) => component.unobservedTaskIds.length > 0)\n ) {\n reasons.push(unobservedReason)\n }\n}\n","/**\n * Task-paired comparison and deterministic selection for independently\n * proposed agent surfaces. Unlike factorial cell-mean attribution, every\n * benefit, regression, and interaction remains attached to its task row.\n */\n\nimport { ValidationError } from '../errors'\nimport { comparePairedArms, type PairedArmRow, type PairedArmsComparison } from '../paired-arms'\nimport { pairedBootstrap } from '../statistics'\nimport { meanOrNull } from '../statistics/mean'\nimport {\n type CrossSurfaceAnalysisContext as AnalysisContext,\n canonicalCrossSurfaceComponents as canonicalComponents,\n crossSurfaceComponentSetKey as componentSetKey,\n crossSurfaceRowFor as rowFor,\n crossSurfaceRowsFor as rowsFor,\n validateCrossSurfaceInput as validateAndIndex,\n} from './cross-surface-context'\nimport {\n appendEvidenceReasons as appendBundleEvidenceReasons,\n appendEvidenceReasons as appendEvidenceEligibilityReasons,\n summarizeCandidateEvidence,\n summarizePairEvidence,\n} from './cross-surface-evidence'\nimport type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceAdditionDecision,\n CrossSurfaceAdditionRejectionReason,\n CrossSurfaceCandidate,\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateOutcome,\n CrossSurfaceCandidateSummary,\n CrossSurfaceCompositionStep,\n CrossSurfaceDistribution,\n CrossSurfaceEligibility,\n CrossSurfaceIneligibilityReason,\n CrossSurfaceInteractionAwareSelection,\n CrossSurfaceInteractionEffect,\n CrossSurfaceInteractionPath,\n CrossSurfaceInteractionReport,\n CrossSurfaceNaiveStackSelection,\n CrossSurfacePairCompatibility,\n CrossSurfacePairEvidence,\n CrossSurfacePairIncompatibilityReason,\n CrossSurfacePairwiseEntry,\n CrossSurfaceRankedSingle,\n CrossSurfaceRelativeCost,\n CrossSurfaceSelections,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\n/**\n * Build the complete cross-surface evidence matrix and derive all three frozen\n * candidates. The task/candidate/component orders are part of the input so\n * neither insertion order nor an after-the-fact tie-break can change a result.\n */\nexport function analyzeCrossSurfaceInteractions<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): CrossSurfaceInteractionReport<TRow> {\n const context = validateAndIndex(input)\n const baseline = context.candidateById.get(input.baselineCandidateId)!\n\n const preliminary = context.candidates.map((candidate) =>\n summarizeCandidate(context, candidate, baseline),\n )\n const baselineSummary = preliminary.find(\n (summary) => summary.candidate.candidateId === input.baselineCandidateId,\n )!\n const summaries = preliminary.map((summary) =>\n summary.candidate.candidateId === input.baselineCandidateId\n ? summary\n : {\n ...summary,\n eligibility: candidateEligibility(context, summary, baselineSummary),\n },\n )\n const summaryById = new Map(summaries.map((summary) => [summary.candidate.candidateId, summary]))\n const eligibleSingles = rankedEligibleSingles(context, summaryById)\n const interactionReadySingles = rankedInteractionReadySingles(context, summaryById)\n const pairwise = buildPairwise(context, summaryById, interactionReadySingles, baselineSummary)\n const selections = selectCandidates(\n context,\n summaryById,\n eligibleSingles,\n interactionReadySingles,\n pairwise,\n )\n const rows = context.candidates.flatMap((candidate) =>\n input.taskOrder.map(\n (taskId) => context.rowsByCandidate.get(candidate.candidateId)!.get(taskId)!,\n ),\n )\n\n return {\n taskIds: [...input.taskOrder],\n componentIds: [...input.componentOrder],\n candidateIds: [...input.candidateOrder],\n costMetrics: [...input.costMetricOrder],\n rows,\n missingAttempts: rows.filter((row) => row.completeness === 'missing'),\n invalidAttempts: rows.filter((row) => row.completeness === 'invalid'),\n candidates: summaries,\n pairwise,\n selections,\n }\n}\n\nfunction compareCandidates<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n comparatorCandidateId: string,\n treatmentCandidateId: string,\n): CrossSurfaceCandidateComparison {\n const winsTaskIds: string[] = []\n const regressionTaskIds: string[] = []\n const missingTaskIds: string[] = []\n for (const taskId of context.input.taskOrder) {\n const comparator = rowFor(context, comparatorCandidateId, taskId)\n const treatment = rowFor(context, treatmentCandidateId, taskId)\n if (comparator.completeness !== 'complete' || treatment.completeness !== 'complete') {\n missingTaskIds.push(taskId)\n } else if (treatment.pass && !comparator.pass) winsTaskIds.push(taskId)\n else if (!treatment.pass && comparator.pass) regressionTaskIds.push(taskId)\n }\n return {\n comparatorCandidateId,\n treatmentCandidateId,\n winsTaskIds,\n regressionTaskIds,\n missingTaskIds,\n paired: pairedComparison(context, comparatorCandidateId, treatmentCandidateId),\n relativeCost: relativeCosts(\n context,\n summaryById.get(treatmentCandidateId)!,\n summaryById.get(comparatorCandidateId)!,\n ),\n }\n}\n\nfunction pairedComparison<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n comparatorCandidateId: string,\n treatmentCandidateId: string,\n): PairedArmsComparison {\n const rows: PairedArmRow[] = []\n for (const taskId of context.input.taskOrder) {\n rows.push(toPairedArmRow(context, rowFor(context, comparatorCandidateId, taskId)))\n rows.push(toPairedArmRow(context, rowFor(context, treatmentCandidateId, taskId)))\n }\n return comparePairedArms(rows, {\n baselineArm: comparatorCandidateId,\n treatmentArm: treatmentCandidateId,\n metricNames: ['score', ...context.input.costMetricOrder],\n bootstrap: { ...context.input.bootstrap, statistic: 'mean' },\n })\n}\n\nfunction toPairedArmRow<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n row: TRow,\n): PairedArmRow {\n const metrics: Record<string, number> = Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [metric, row.cost[metric] as number]),\n )\n if (row.completeness === 'complete') metrics.score = row.score as number\n return {\n pairKey: row.taskId,\n arm: row.candidateId,\n ...(row.completeness === 'complete' ? { pass: row.pass as boolean } : {}),\n metrics,\n }\n}\n\nfunction relativeCosts<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n treatment: CrossSurfaceCandidateSummary,\n comparator: CrossSurfaceCandidateSummary,\n): Record<string, CrossSurfaceRelativeCost> {\n return Object.fromEntries(\n context.input.costMetricOrder.map((metric) => {\n const treatmentMedian = treatment.costs[metric]!.median\n const comparatorMedian = comparator.costs[metric]!.median\n return [\n metric,\n {\n treatmentMedian,\n comparatorMedian,\n medianDelta: treatmentMedian - comparatorMedian,\n medianRatio:\n comparatorMedian === 0\n ? treatmentMedian === 0\n ? 1\n : null\n : treatmentMedian / comparatorMedian,\n },\n ]\n }),\n )\n}\n\nfunction withinCostLimits<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n treatment: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n): boolean {\n const relative = relativeCosts(context, treatment, baseline)\n return Object.entries(context.input.selection.maximumMedianCostRatioToBaseline).every(\n ([metric, limit]) => {\n const ratio = relative[metric]!.medianRatio\n return ratio !== null && ratio <= limit\n },\n )\n}\n\nfunction distribution(values: number[]): CrossSurfaceDistribution {\n const sorted = [...values].sort((left, right) => left - right)\n const total = sorted.reduce((sum, value) => sum + value, 0)\n const middle = Math.floor(sorted.length / 2)\n const median =\n sorted.length % 2 === 1 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2\n return {\n n: sorted.length,\n min: sorted[0]!,\n median,\n mean: total / sorted.length,\n max: sorted[sorted.length - 1]!,\n total,\n }\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n\nfunction buildPairwise<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n baseline: CrossSurfaceCandidateSummary,\n): CrossSurfacePairwiseEntry[] {\n const interactionReadyIds = new Set(\n interactionReadySingles.map((summary) => summary.candidate.candidateId),\n )\n const entries: CrossSurfacePairwiseEntry[] = []\n for (let leftIndex = 0; leftIndex < context.components.length; leftIndex++) {\n for (let rightIndex = leftIndex + 1; rightIndex < context.components.length; rightIndex++) {\n const leftComponent = context.components[leftIndex]!\n const rightComponent = context.components[rightIndex]!\n const leftSingle = context.singleByComponent.get(leftComponent.componentId)!\n const rightSingle = context.singleByComponent.get(rightComponent.componentId)!\n const pair = context.candidateByComponents.get(\n componentSetKey([leftComponent.componentId, rightComponent.componentId]),\n )!\n const pairSummary = summaryById.get(pair.candidateId)!\n const leftSummary = summaryById.get(leftSingle.candidateId)!\n const rightSummary = summaryById.get(rightSingle.candidateId)!\n const synergyTaskIds: string[] = []\n const interferenceTaskIds: string[] = []\n for (const taskId of context.input.taskOrder) {\n const pairRow = rowFor(context, pair.candidateId, taskId)\n const leftRow = rowFor(context, leftSingle.candidateId, taskId)\n const rightRow = rowFor(context, rightSingle.candidateId, taskId)\n if (![pairRow, leftRow, rightRow].every((row) => row.completeness === 'complete')) continue\n if (pairRow.pass && !leftRow.pass && !rightRow.pass) synergyTaskIds.push(taskId)\n if (!pairRow.pass && (leftRow.pass || rightRow.pass)) interferenceTaskIds.push(taskId)\n }\n const incrementalVsConstituents: [\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateComparison,\n ] = [\n compareCandidates(context, summaryById, leftSingle.candidateId, pair.candidateId),\n compareCandidates(context, summaryById, rightSingle.candidateId, pair.candidateId),\n ]\n const betterSingle =\n compareSingleSummaries(context, leftSummary, rightSummary) <= 0 ? leftSummary : rightSummary\n const firing = summarizePairEvidence(\n rowsFor(context, pair.candidateId),\n leftComponent.componentId,\n rightComponent.componentId,\n 'fired',\n )\n const effect = summarizePairEvidence(\n rowsFor(context, pair.candidateId),\n leftComponent.componentId,\n rightComponent.componentId,\n 'effectObserved',\n )\n const compatibility = pairCompatibility(\n context,\n pairSummary,\n baseline,\n betterSingle,\n incrementalVsConstituents,\n interactionReadyIds.has(leftSingle.candidateId) &&\n interactionReadyIds.has(rightSingle.candidateId),\n interferenceTaskIds,\n firing,\n effect,\n )\n entries.push({\n componentIds: [leftComponent.componentId, rightComponent.componentId],\n singleCandidateIds: [leftSingle.candidateId, rightSingle.candidateId],\n compositionCandidateId: pair.candidateId,\n benefitTaskIds: [...pairSummary.outcome.benefitTaskIds],\n regressionTaskIds: [...pairSummary.outcome.regressionTaskIds],\n synergyTaskIds,\n interferenceTaskIds,\n incrementalVsConstituents,\n relativeCostToBaseline: relativeCosts(context, pairSummary, baseline),\n firing,\n effect,\n interaction: interactionEffect(\n context,\n baseline.candidate,\n [leftSingle, rightSingle],\n pair,\n ),\n compatibility,\n })\n }\n }\n return entries\n}\n\nfunction pairCompatibility<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n pair: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n betterSingle: CrossSurfaceCandidateSummary,\n comparisons: [CrossSurfaceCandidateComparison, CrossSurfaceCandidateComparison],\n constituentsReady: boolean,\n interferenceTaskIds: string[],\n firing: CrossSurfacePairEvidence,\n effect: CrossSurfacePairEvidence,\n): CrossSurfacePairCompatibility {\n const reasons: CrossSurfacePairIncompatibilityReason[] = []\n if (!constituentsReady) reasons.push('constituent_not_ready')\n if (\n pair.outcome.missingTaskIds.length > 0 ||\n pair.outcome.invalidTaskIds.length > 0 ||\n pair.outcome.comparisonMissingTaskIds.length > 0\n ) {\n reasons.push('pair_incomplete')\n }\n if (pair.outcome.regressionTaskIds.length > 0) reasons.push('baseline_regression')\n if (interferenceTaskIds.length > 0) reasons.push('interference')\n const betterComparison = comparisons.find(\n (comparison) => comparison.comparatorCandidateId === betterSingle.candidate.candidateId,\n )!\n if (betterComparison.winsTaskIds.length === 0) reasons.push('no_incremental_resolution')\n appendPairEvidenceReasons(\n reasons,\n firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendPairEvidenceReasons(\n reasons,\n effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, pair, baseline)) reasons.push('cost_limit_exceeded')\n return {\n compatible: reasons.length === 0,\n reasons: unique(reasons),\n betterSingleCandidateId: betterSingle.candidate.candidateId,\n }\n}\n\nfunction appendPairEvidenceReasons(\n reasons: CrossSurfacePairIncompatibilityReason[],\n evidence: CrossSurfacePairEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfacePairIncompatibilityReason,\n unobservedReason: CrossSurfacePairIncompatibilityReason,\n): void {\n const leftObserved = evidence.bothTaskIds.length + evidence.leftOnlyTaskIds.length\n const rightObserved = evidence.bothTaskIds.length + evidence.rightOnlyTaskIds.length\n if (leftObserved < minimum || rightObserved < minimum) reasons.push(belowReason)\n if (requireObserved && evidence.unobservedTaskIds.length > 0) reasons.push(unobservedReason)\n}\n\nfunction interactionEffect<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n baseline: CrossSurfaceCandidate,\n singles: CrossSurfaceCandidate[],\n composition: CrossSurfaceCandidate,\n): CrossSurfaceInteractionEffect {\n const perTask = context.input.taskOrder.map((taskId) => {\n const baselineRow = rowFor(context, baseline.candidateId, taskId)\n const singleRows = singles.map((single) => rowFor(context, single.candidateId, taskId))\n const compositionRow = rowFor(context, composition.candidateId, taskId)\n const rows = [baselineRow, ...singleRows, compositionRow]\n if (!rows.every((row) => row.completeness === 'complete')) {\n return { taskId, passInteraction: null, scoreInteraction: null }\n }\n const additivePass =\n singleRows.reduce((sum, row) => sum + Number(row.pass), 0) -\n (singles.length - 1) * Number(baselineRow.pass)\n const additiveScore =\n singleRows.reduce((sum, row) => sum + (row.score as number), 0) -\n (singles.length - 1) * (baselineRow.score as number)\n return {\n taskId,\n passInteraction: Number(compositionRow.pass) - additivePass,\n scoreInteraction: (compositionRow.score as number) - additiveScore,\n }\n })\n const complete = perTask.filter(\n (row): row is { taskId: string; passInteraction: number; scoreInteraction: number } =>\n row.passInteraction !== null && row.scoreInteraction !== null,\n )\n const passInteractions = complete.map((row) => row.passInteraction)\n const scoreInteractions = complete.map((row) => row.scoreInteraction)\n return {\n perTask,\n n: complete.length,\n nMissing: perTask.length - complete.length,\n meanPassInteraction: meanOrNull(passInteractions),\n meanScoreInteraction: meanOrNull(scoreInteractions),\n passBootstrap: bootstrapInteraction(passInteractions, context),\n scoreBootstrap: bootstrapInteraction(scoreInteractions, context),\n }\n}\n\nfunction bootstrapInteraction<TRow extends CrossSurfaceTaskRow>(\n interactions: number[],\n context: AnalysisContext<TRow>,\n) {\n if (interactions.length === 0) return null\n return pairedBootstrap(new Array(interactions.length).fill(0), interactions, {\n ...context.input.bootstrap,\n statistic: 'mean',\n })\n}\n\nfunction selectCandidates<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n eligibleSingles: CrossSurfaceCandidateSummary[],\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairwise: CrossSurfacePairwiseEntry[],\n): CrossSurfaceSelections {\n const bestSingleRanking = eligibleSingles.filter((summary) => {\n const componentId = summary.candidate.componentIds[0]!\n return context.componentById.get(componentId)!.bestSingleEligible\n })\n const ranking: CrossSurfaceRankedSingle[] = bestSingleRanking.map((summary, index) => ({\n rank: index + 1,\n candidateId: summary.candidate.candidateId,\n componentId: summary.candidate.componentIds[0]!,\n }))\n const best = bestSingleRanking[0]\n const bestSingle = best\n ? {\n candidateId: best.candidate.candidateId,\n componentId: best.candidate.componentIds[0]!,\n ranking,\n }\n : null\n const naiveStack = selectNaiveStack(context, eligibleSingles)\n const interactionAware = selectInteractionAware(\n context,\n summaryById,\n interactionReadySingles,\n pairwise,\n )\n return { bestSingle, naiveStack, interactionAware }\n}\n\nfunction selectNaiveStack<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n eligibleSingles: CrossSurfaceCandidateSummary[],\n): CrossSurfaceNaiveStackSelection | null {\n if (eligibleSingles.length === 0) return null\n const componentIds = eligibleSingles\n .map((summary) => summary.candidate.componentIds[0]!)\n .sort((left, right) => context.componentIndex.get(left)! - context.componentIndex.get(right)!)\n const candidate = context.candidateByComponents.get(componentSetKey(componentIds))\n if (!candidate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: naive stack [${componentIds.join(', ')}] was not evaluated`,\n )\n }\n return { candidateId: candidate.candidateId, componentIds }\n}\n\nfunction selectInteractionAware<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairwise: CrossSurfacePairwiseEntry[],\n): CrossSurfaceInteractionAwareSelection | null {\n const baseline = summaryById.get(context.input.baselineCandidateId)!\n const pairByComponents = new Map(\n pairwise.map((entry) => [componentSetKey(entry.componentIds), entry]),\n )\n const paths = pairwise\n .filter((entry) => entry.compatibility.compatible)\n .map((entry) =>\n growInteractionPath(\n context,\n summaryById,\n interactionReadySingles,\n pairByComponents,\n baseline,\n summaryById.get(entry.compositionCandidateId)!,\n ),\n )\n if (paths.length === 0) return null\n\n const qualified = paths\n .filter((path) => path.qualified)\n .sort((left, right) => compareInteractionPaths(context, summaryById, left, right))\n const winning =\n qualified[0] ??\n [...paths].sort((left, right) => compareInteractionPaths(context, summaryById, left, right))[0]!\n return {\n seedCandidateId: winning.seedCandidateId,\n terminalCandidateId: winning.terminalCandidateId,\n terminalComponentIds: [...winning.terminalComponentIds],\n selectedCandidateId: qualified.length > 0 ? winning.terminalCandidateId : null,\n qualified: qualified.length > 0,\n evaluatedPaths: paths,\n steps: winning.steps,\n }\n}\n\nfunction growInteractionPath<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairByComponents: Map<string, CrossSurfacePairwiseEntry>,\n baseline: CrossSurfaceCandidateSummary,\n seed: CrossSurfaceCandidateSummary,\n): CrossSurfaceInteractionPath {\n let current = seed\n let retained = [...seed.candidate.componentIds]\n let remaining = interactionReadySingles.filter(\n (summary) => !retained.includes(summary.candidate.componentIds[0]!),\n )\n const steps: CrossSurfaceCompositionStep[] = []\n\n while (remaining.length > 0) {\n const decisions = remaining.map((addition) =>\n evaluateAddition(\n context,\n summaryById,\n pairByComponents,\n baseline,\n current,\n retained,\n addition,\n ),\n )\n const eligible = decisions\n .filter((decision) => decision.eligible)\n .sort((left, right) => compareAdditionDecisions(context, summaryById, left, right))\n const selected = eligible[0]\n if (selected) selected.selected = true\n steps.push({\n fromCandidateId: current.candidate.candidateId,\n retainedComponentIds: [...retained],\n considered: decisions.sort(\n (left, right) =>\n context.candidateIndex.get(left.additionCandidateId)! -\n context.candidateIndex.get(right.additionCandidateId)!,\n ),\n selectedCandidateId: selected?.bundleCandidateId ?? null,\n })\n if (!selected?.bundleCandidateId) break\n current = summaryById.get(selected.bundleCandidateId)!\n retained = [...current.candidate.componentIds]\n remaining = remaining.filter(\n (summary) => summary.candidate.candidateId !== selected.additionCandidateId,\n )\n }\n\n const qualified = retained.length >= context.input.selection.minimumBundleComponents\n return {\n seedCandidateId: seed.candidate.candidateId,\n terminalCandidateId: current.candidate.candidateId,\n terminalComponentIds: retained,\n qualified,\n steps,\n }\n}\n\nfunction compareInteractionPaths<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n left: CrossSurfaceInteractionPath,\n right: CrossSurfaceInteractionPath,\n): number {\n const leftSummary = summaryById.get(left.terminalCandidateId)!\n const rightSummary = summaryById.get(right.terminalCandidateId)!\n const byNetBenefit = rightSummary.outcome.netBenefit - leftSummary.outcome.netBenefit\n if (byNetBenefit !== 0) return byNetBenefit\n const byBenefit =\n rightSummary.outcome.benefitTaskIds.length - leftSummary.outcome.benefitTaskIds.length\n if (byBenefit !== 0) return byBenefit\n const byRegression =\n leftSummary.outcome.regressionTaskIds.length - rightSummary.outcome.regressionTaskIds.length\n if (byRegression !== 0) return byRegression\n for (const metric of context.input.costMetricOrder) {\n const byCost = leftSummary.costs[metric]!.median - rightSummary.costs[metric]!.median\n if (byCost !== 0) return byCost\n }\n const byBytes = leftSummary.candidate.artifactBytes - rightSummary.candidate.artifactBytes\n if (byBytes !== 0) return byBytes\n const byCandidateOrder =\n context.candidateIndex.get(left.terminalCandidateId)! -\n context.candidateIndex.get(right.terminalCandidateId)!\n if (byCandidateOrder !== 0) return byCandidateOrder\n return (\n context.candidateIndex.get(left.seedCandidateId)! -\n context.candidateIndex.get(right.seedCandidateId)!\n )\n}\n\nfunction evaluateAddition<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n pairByComponents: Map<string, CrossSurfacePairwiseEntry>,\n baseline: CrossSurfaceCandidateSummary,\n current: CrossSurfaceCandidateSummary,\n retained: string[],\n addition: CrossSurfaceCandidateSummary,\n): CrossSurfaceAdditionDecision {\n const additionComponentId = addition.candidate.componentIds[0]!\n const reasons: CrossSurfaceAdditionRejectionReason[] = []\n for (const retainedComponentId of retained) {\n const pair = pairByComponents.get(\n componentSetKey(canonicalComponents(context, [retainedComponentId, additionComponentId])),\n )\n if (!pair?.compatibility.compatible) reasons.push('pair_incompatible')\n }\n const bundleComponents = canonicalComponents(context, [...retained, additionComponentId])\n const bundle = context.candidateByComponents.get(componentSetKey(bundleComponents))\n if (!bundle) {\n reasons.push('full_bundle_not_evaluated')\n return emptyAdditionDecision(addition, additionComponentId, reasons)\n }\n const bundleSummary = summaryById.get(bundle.candidateId)!\n if (\n bundleSummary.outcome.missingTaskIds.length > 0 ||\n bundleSummary.outcome.invalidTaskIds.length > 0 ||\n bundleSummary.outcome.comparisonMissingTaskIds.length > 0\n ) {\n reasons.push('bundle_incomplete')\n }\n if (bundleSummary.outcome.regressionTaskIds.length > 0) reasons.push('baseline_regression')\n const comparison = compareCandidates(\n context,\n summaryById,\n current.candidate.candidateId,\n bundle.candidateId,\n )\n if (comparison.winsTaskIds.length === 0) reasons.push('no_incremental_resolution')\n if (comparison.regressionTaskIds.length > 0) reasons.push('incremental_regression')\n appendBundleEvidenceReasons(\n reasons,\n bundleSummary.firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendBundleEvidenceReasons(\n reasons,\n bundleSummary.effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, bundleSummary, baseline)) reasons.push('cost_limit_exceeded')\n return {\n additionCandidateId: addition.candidate.candidateId,\n additionComponentId,\n bundleCandidateId: bundle.candidateId,\n incrementalResolutionTaskIds: comparison.winsTaskIds,\n incrementalRegressionTaskIds: comparison.regressionTaskIds,\n incrementalMedianCost: Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [\n metric,\n bundleSummary.costs[metric]!.median - current.costs[metric]!.median,\n ]),\n ),\n eligible: reasons.length === 0,\n selected: false,\n reasons: unique(reasons),\n }\n}\n\nfunction emptyAdditionDecision(\n addition: CrossSurfaceCandidateSummary,\n additionComponentId: string,\n reasons: CrossSurfaceAdditionRejectionReason[],\n): CrossSurfaceAdditionDecision {\n return {\n additionCandidateId: addition.candidate.candidateId,\n additionComponentId,\n bundleCandidateId: null,\n incrementalResolutionTaskIds: [],\n incrementalRegressionTaskIds: [],\n incrementalMedianCost: null,\n eligible: false,\n selected: false,\n reasons: unique(reasons),\n }\n}\n\nfunction compareAdditionDecisions<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n left: CrossSurfaceAdditionDecision,\n right: CrossSurfaceAdditionDecision,\n): number {\n const byWins =\n right.incrementalResolutionTaskIds.length - left.incrementalResolutionTaskIds.length\n if (byWins !== 0) return byWins\n for (const metric of context.input.costMetricOrder) {\n const byCost = left.incrementalMedianCost![metric]! - right.incrementalMedianCost![metric]!\n if (byCost !== 0) return byCost\n }\n const leftBytes = summaryById.get(left.additionCandidateId)!.candidate.artifactBytes\n const rightBytes = summaryById.get(right.additionCandidateId)!.candidate.artifactBytes\n const byBytes = leftBytes - rightBytes\n if (byBytes !== 0) return byBytes\n return (\n context.candidateIndex.get(left.additionCandidateId)! -\n context.candidateIndex.get(right.additionCandidateId)!\n )\n}\n\nfunction summarizeCandidate<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n candidate: CrossSurfaceCandidate,\n baseline: CrossSurfaceCandidate,\n): CrossSurfaceCandidateSummary {\n const rows = rowsFor(context, candidate.candidateId)\n const baselineRows = rowsFor(context, baseline.candidateId)\n const outcome = summarizeOutcome(\n context,\n rows,\n baselineRows,\n candidate.candidateId === baseline.candidateId,\n )\n const completeScores = rows\n .filter((row) => row.completeness === 'complete')\n .map((row) => row.score as number)\n const costs = Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [\n metric,\n distribution(rows.map((row) => row.cost[metric] as number)),\n ]),\n )\n return {\n candidate,\n outcome,\n score: completeScores.length === 0 ? null : distribution(completeScores),\n costs,\n firing: summarizeCandidateEvidence(rows, candidate.componentIds, 'fired'),\n effect: summarizeCandidateEvidence(rows, candidate.componentIds, 'effectObserved'),\n comparisonToBaseline:\n candidate.candidateId === baseline.candidateId\n ? null\n : pairedComparison(context, baseline.candidateId, candidate.candidateId),\n eligibility: null,\n }\n}\n\nfunction summarizeOutcome<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n rows: TRow[],\n baselineRows: TRow[],\n isBaseline: boolean,\n): CrossSurfaceCandidateOutcome {\n const resolvedTaskIds: string[] = []\n const failedTaskIds: string[] = []\n const missingTaskIds: string[] = []\n const invalidTaskIds: string[] = []\n const benefitTaskIds: string[] = []\n const regressionTaskIds: string[] = []\n const comparisonMissingTaskIds: string[] = []\n for (let index = 0; index < context.input.taskOrder.length; index++) {\n const row = rows[index]!\n const baseline = baselineRows[index]!\n if (row.completeness === 'missing') missingTaskIds.push(row.taskId)\n else if (row.completeness === 'invalid') invalidTaskIds.push(row.taskId)\n else if (row.pass) resolvedTaskIds.push(row.taskId)\n else failedTaskIds.push(row.taskId)\n\n if (isBaseline) continue\n if (row.completeness !== 'complete' || baseline.completeness !== 'complete') {\n comparisonMissingTaskIds.push(row.taskId)\n } else if (row.pass && !baseline.pass) benefitTaskIds.push(row.taskId)\n else if (!row.pass && baseline.pass) regressionTaskIds.push(row.taskId)\n }\n return {\n resolvedTaskIds,\n failedTaskIds,\n missingTaskIds,\n invalidTaskIds,\n benefitTaskIds,\n regressionTaskIds,\n comparisonMissingTaskIds,\n netBenefit: benefitTaskIds.length - regressionTaskIds.length,\n }\n}\n\nfunction candidateEligibility<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summary: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n): CrossSurfaceEligibility {\n const reasons: CrossSurfaceIneligibilityReason[] = []\n if (summary.outcome.missingTaskIds.length > 0) reasons.push('missing_attempt')\n if (summary.outcome.invalidTaskIds.length > 0) reasons.push('invalid_attempt')\n if (summary.outcome.comparisonMissingTaskIds.length > 0) reasons.push('baseline_outcome_missing')\n if (summary.outcome.benefitTaskIds.length <= summary.outcome.regressionTaskIds.length) {\n reasons.push('benefit_not_greater_than_regression')\n }\n appendEvidenceEligibilityReasons(\n reasons,\n summary.firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendEvidenceEligibilityReasons(\n reasons,\n summary.effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, summary, baseline)) reasons.push('cost_limit_exceeded')\n return { eligible: reasons.length === 0, reasons: unique(reasons) }\n}\n\nfunction rankedEligibleSingles<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n): CrossSurfaceCandidateSummary[] {\n return [...context.singleByComponent.values()]\n .map((candidate) => summaryById.get(candidate.candidateId)!)\n .filter((summary) => summary.eligibility?.eligible)\n .sort((left, right) => compareSingleSummaries(context, left, right))\n}\n\n/**\n * A neutral constituent may seed a composition when it has complete, bounded,\n * observed evidence and causes no baseline regression. Individual benefit is\n * deliberately left to the best-single arm rather than used as a pair gate.\n */\nfunction rankedInteractionReadySingles<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n): CrossSurfaceCandidateSummary[] {\n return [...context.singleByComponent.values()]\n .map((candidate) => summaryById.get(candidate.candidateId)!)\n .filter(\n (summary) =>\n summary.outcome.regressionTaskIds.length === 0 &&\n summary.eligibility?.reasons.every(\n (reason) => reason === 'benefit_not_greater_than_regression',\n ),\n )\n .sort((left, right) => compareSingleSummaries(context, left, right))\n}\n\nfunction compareSingleSummaries<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n left: CrossSurfaceCandidateSummary,\n right: CrossSurfaceCandidateSummary,\n): number {\n const byNetBenefit = right.outcome.netBenefit - left.outcome.netBenefit\n if (byNetBenefit !== 0) return byNetBenefit\n const byBenefit = right.outcome.benefitTaskIds.length - left.outcome.benefitTaskIds.length\n if (byBenefit !== 0) return byBenefit\n const byRegression =\n left.outcome.regressionTaskIds.length - right.outcome.regressionTaskIds.length\n if (byRegression !== 0) return byRegression\n for (const metric of context.input.costMetricOrder) {\n const byCost = left.costs[metric]!.median - right.costs[metric]!.median\n if (byCost !== 0) return byCost\n }\n const byBytes = left.candidate.artifactBytes - right.candidate.artifactBytes\n if (byBytes !== 0) return byBytes\n return (\n context.candidateIndex.get(left.candidate.candidateId)! -\n context.candidateIndex.get(right.candidate.candidateId)!\n )\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve } from 'node:path'\nimport { contentHash } from '../verdict-cache'\nimport { type CampaignRunPlan, type PlanCampaignRunOptions, planCampaignRun } from './run-campaign'\nimport type { CampaignStorage } from './storage'\nimport type { JudgeConfig, Scenario } from './types'\n\nexport type EvalFixtureValidationMode = 'vitest' | 'none'\n\nexport interface EvalFixtureFile {\n path: string\n sha256: string\n bytes: number\n}\n\nexport interface EvalFixture {\n name: string\n path: string\n promptPath: string\n evalPath?: string\n packageJsonPath?: string\n prompt: string\n files: EvalFixtureFile[]\n fingerprint: string\n}\n\nexport interface EvalFixtureScenario extends Scenario {\n kind: 'eval-fixture'\n fixtureName: string\n fixturePath: string\n promptPath: string\n evalPath?: string\n packageJsonPath?: string\n prompt: string\n fingerprint: string\n}\n\nexport interface EvalFixtureLoadOptions {\n /** `vitest` requires EVAL.ts/EVAL.tsx and package.json type=module. `none` only requires PROMPT.md. */\n validation?: EvalFixtureValidationMode\n /** Extra caller-owned knobs that affect fixture behavior, folded into the fingerprint. */\n fingerprintConfig?: unknown\n}\n\nexport interface LoadEvalFixtureScenariosOptions extends EvalFixtureLoadOptions {\n names?: string[]\n}\n\nexport interface PlanEvalFixtureRunOptions<TArtifact = unknown>\n extends Pick<\n PlanCampaignRunOptions<EvalFixtureScenario, TArtifact>,\n 'dispatchRef' | 'judges' | 'seed' | 'reps' | 'resumable' | 'runDir'\n > {\n evalsDir: string\n validation?: EvalFixtureValidationMode\n fingerprintConfig?: unknown\n names?: string[]\n storage?: CampaignStorage\n}\n\nexport type EvalFixtureRunPlan = CampaignRunPlan & {\n fixtures: Array<Pick<EvalFixtureScenario, 'fixtureName' | 'fixturePath' | 'fingerprint'>>\n}\n\n/** Walk `evalsDir` and return the relative name of every fixture directory (one containing an exact-case `PROMPT.md`). */\nexport function discoverEvalFixtures(evalsDir: string): string[] {\n const root = resolve(evalsDir)\n if (!existsSync(root)) throw new Error(`discoverEvalFixtures: evalsDir not found: ${root}`)\n\n const fixtures: string[] = []\n const walk = (dir: string, base = '') => {\n for (const entry of readdirSync(dir).sort()) {\n if (entry.startsWith('.') || entry === 'node_modules') continue\n const fullPath = join(dir, entry)\n if (!statSync(fullPath).isDirectory()) continue\n\n const name = base ? `${base}/${entry}` : entry\n if (existsWithExactCase(fullPath, 'PROMPT.md')) {\n fixtures.push(name)\n } else {\n walk(fullPath, name)\n }\n }\n }\n\n walk(root)\n return fixtures\n}\n\n/**\n * Load ONE fixture by name: reads `PROMPT.md` (plus `EVAL.ts`/`EVAL.tsx` and `package.json` under\n * `vitest` validation) and content-fingerprints the full file set for cache identity.\n */\nexport function loadEvalFixture(\n evalsDir: string,\n name: string,\n options: EvalFixtureLoadOptions = {},\n): EvalFixture {\n const validation = options.validation ?? 'vitest'\n const root = resolve(evalsDir)\n const fixturePath = resolve(root, name)\n assertInside(root, fixturePath, name)\n\n if (!existsSync(fixturePath) || !statSync(fixturePath).isDirectory()) {\n throw new Error(`loadEvalFixture: fixture not found: ${name}`)\n }\n if (!existsWithExactCase(fixturePath, 'PROMPT.md')) {\n throw new Error(`loadEvalFixture: ${name} is missing exact-case PROMPT.md`)\n }\n\n const promptPath = join(fixturePath, 'PROMPT.md')\n const evalPath = resolveEvalPath(fixturePath)\n const packageJsonPath = existsWithExactCase(fixturePath, 'package.json')\n ? join(fixturePath, 'package.json')\n : undefined\n\n if (validation !== 'none') {\n if (!evalPath)\n throw new Error(`loadEvalFixture: ${name} is missing exact-case EVAL.ts or EVAL.tsx`)\n if (!packageJsonPath)\n throw new Error(`loadEvalFixture: ${name} is missing exact-case package.json`)\n assertModulePackage(packageJsonPath, name)\n }\n\n const files = collectFixtureFiles(fixturePath)\n return {\n name,\n path: fixturePath,\n promptPath,\n evalPath,\n packageJsonPath,\n prompt: readFileSync(promptPath, 'utf8'),\n files,\n fingerprint: contentHash({\n files,\n config: options.fingerprintConfig ?? null,\n }),\n }\n}\n\n/** Load fixtures (all discovered, or just `names`) as campaign `Scenario`s tagged `eval-fixture`. */\nexport function loadEvalFixtureScenarios(\n evalsDir: string,\n options: LoadEvalFixtureScenariosOptions = {},\n): EvalFixtureScenario[] {\n const names = options.names ?? discoverEvalFixtures(evalsDir)\n return names.map((name) => {\n const fixture = loadEvalFixture(evalsDir, name, options)\n return {\n id: fixture.name,\n kind: 'eval-fixture',\n tags: ['eval-fixture'],\n fixtureName: fixture.name,\n fixturePath: fixture.path,\n promptPath: fixture.promptPath,\n evalPath: fixture.evalPath,\n packageJsonPath: fixture.packageJsonPath,\n prompt: fixture.prompt,\n fingerprint: fixture.fingerprint,\n }\n })\n}\n\n/**\n * Dry-run planner for a fixture campaign: loads the scenarios, delegates to `planCampaignRun`,\n * and returns the plan plus each fixture's name/path/fingerprint.\n */\nexport function planEvalFixtureRun<TArtifact = unknown>(\n options: PlanEvalFixtureRunOptions<TArtifact>,\n): EvalFixtureRunPlan {\n const scenarios = loadEvalFixtureScenarios(options.evalsDir, {\n names: options.names,\n validation: options.validation,\n fingerprintConfig: options.fingerprintConfig,\n })\n const plan = planCampaignRun<EvalFixtureScenario, TArtifact>({\n scenarios,\n dispatchRef: options.dispatchRef ?? 'eval-fixture-dispatch',\n judges: options.judges as JudgeConfig<TArtifact, EvalFixtureScenario>[] | undefined,\n seed: options.seed,\n reps: options.reps,\n resumable: options.resumable,\n runDir: options.runDir,\n storage: options.storage,\n })\n\n return {\n ...plan,\n fixtures: scenarios.map((scenario) => ({\n fixtureName: scenario.fixtureName,\n fixturePath: scenario.fixturePath,\n fingerprint: scenario.fingerprint,\n })),\n }\n}\n\nfunction existsWithExactCase(dirPath: string, fileName: string): boolean {\n try {\n return readdirSync(dirPath).includes(fileName)\n } catch {\n return false\n }\n}\n\nfunction resolveEvalPath(fixturePath: string): string | undefined {\n if (existsWithExactCase(fixturePath, 'EVAL.ts')) return join(fixturePath, 'EVAL.ts')\n if (existsWithExactCase(fixturePath, 'EVAL.tsx')) return join(fixturePath, 'EVAL.tsx')\n return undefined\n}\n\nfunction assertModulePackage(packageJsonPath: string, name: string): void {\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(packageJsonPath, 'utf8'))\n } catch (err) {\n throw new Error(\n `loadEvalFixture: ${name} package.json is invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n (parsed as { type?: unknown }).type !== 'module'\n ) {\n throw new Error(`loadEvalFixture: ${name} package.json must set \"type\": \"module\"`)\n }\n}\n\nfunction collectFixtureFiles(fixturePath: string, base = ''): EvalFixtureFile[] {\n const files: EvalFixtureFile[] = []\n for (const entry of readdirSync(join(fixturePath, base)).sort()) {\n if (entry === 'node_modules' || entry === '.git') continue\n const relativePath = base ? `${base}/${entry}` : entry\n const fullPath = join(fixturePath, relativePath)\n const stat = statSync(fullPath)\n if (stat.isDirectory()) {\n files.push(...collectFixtureFiles(fixturePath, relativePath))\n continue\n }\n const bytes = readFileSync(fullPath)\n files.push({\n path: relativePath,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n bytes: bytes.byteLength,\n })\n }\n return files\n}\n\nfunction assertInside(root: string, target: string, label: string): void {\n const rel = relative(root, target)\n if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) return\n throw new Error(`loadEvalFixture: fixture path escapes evalsDir: ${label}`)\n}\n","/**\n * @module\n * Composable placebo / neutralization promotion gate.\n *\n * A held-out gate proves a candidate beat baseline. It CANNOT prove the lift came\n * from the candidate's CONTENT rather than from the prompt/mount FOOTPRINT the\n * content happened to add (more bytes, a longer prompt). This gate closes that\n * hole: it compares the candidate's held-out lift against the lift of a\n * FOOTPRINT-MATCHED neutralized variant (same layout + length, zero content, via\n * `neutralizeText`). If the neutralized variant reproduces more than\n * `maxDecorativeFraction` of the candidate's lift, the lift is decorative — it\n * survives blanking the content — and the candidate is HELD regardless of how\n * large or significant its raw lift is.\n *\n * Compose it AFTER the significance gate — significance says the lift is real,\n * this says the lift is CAUSED BY THE CONTENT:\n * composeGate(heldOutGate({ ... }), neutralizationGate({ ... }))\n *\n * Requires `ctx.neutralizedJudgeScores`, populated by `runImprovementLoop` when it\n * is given a `neutralize` function. A gate composed without that wiring fails\n * loud rather than silently passing an unproven candidate.\n */\n\nimport { mean } from '../../statistics/mean'\nimport type { Gate, GateContext, GateResult, Scenario } from '../types'\nimport { pairHoldout } from './statistical-heldout'\n\nexport interface NeutralizationGateOptions<TScenario extends Scenario = Scenario> {\n scenarios: TScenario[]\n /** Reject when the neutralized (content-blanked, footprint-matched) variant\n * reproduces at least this fraction of the candidate's held-out lift. Default\n * 0.5 — if blanking the content keeps half the lift, the content is decorative.\n * Equality rejects: a neutralized lift == threshold·candidateLift is decorative. */\n maxDecorativeFraction?: number\n}\n\n/** Paired mean held-out lift of `arm` over baseline, on the in-scope cells. */\nfunction pairedLift(\n arm: Map<string, Record<string, { composite: number }>>,\n baseline: Map<string, Record<string, { composite: number }>>,\n scenarioIds: Set<string>,\n): { lift: number; n: number } {\n const paired = pairHoldout(arm as never, baseline as never, scenarioIds, (s) => s.composite)\n const deltas = paired.after.map((a, i) => a - (paired.before[i] ?? 0))\n return { lift: deltas.length ? mean(deltas) : 0, n: deltas.length }\n}\n\n/**\n * Composable placebo gate: ships only when the candidate's held-out lift is NOT\n * mostly reproduced by a footprint-matched neutralized variant.\n */\nexport function neutralizationGate<TArtifact, TScenario extends Scenario>(\n options: NeutralizationGateOptions<TScenario>,\n): Gate<TArtifact, TScenario> {\n const maxDecorativeFraction = options.maxDecorativeFraction ?? 0.5\n return {\n name: 'neutralizationGate',\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n 'neutralizationGate: ctx.baselineJudgeScores is required — the placebo control measures lift OVER baseline.',\n )\n }\n if (!ctx.neutralizedJudgeScores) {\n throw new Error(\n 'neutralizationGate: ctx.neutralizedJudgeScores is required. It is populated by runImprovementLoop only when a `neutralize` function is supplied — composing this gate without that wiring would pass an unproven candidate.',\n )\n }\n const scenarioIds = new Set(options.scenarios.map((s) => s.id))\n const cand = pairedLift(\n ctx.judgeScores as never,\n ctx.baselineJudgeScores as never,\n scenarioIds,\n )\n const neut = pairedLift(\n ctx.neutralizedJudgeScores as never,\n ctx.baselineJudgeScores as never,\n scenarioIds,\n )\n\n // No positive candidate lift → nothing to attribute. Fail closed: the\n // placebo control has no basis to clear the candidate (the significance\n // gate is what judges lift magnitude; this one only judges its CAUSE).\n if (cand.lift <= 0) {\n return {\n decision: 'hold',\n reasons: [\n `neutralization: candidate held-out lift ${cand.lift.toFixed(3)} ≤ 0 — no positive lift to attribute to content`,\n ],\n contributingGates: [\n {\n name: 'neutralizationGate',\n status: 'fail',\n detail: { candidateLift: cand.lift, neutralizedLift: neut.lift, n: cand.n },\n },\n ],\n delta: cand.lift,\n }\n }\n\n const decorativeFraction = neut.lift / cand.lift\n const passed = decorativeFraction < maxDecorativeFraction\n const pct = (decorativeFraction * 100).toFixed(0)\n return {\n decision: passed ? 'ship' : 'hold',\n reasons: passed\n ? [\n `neutralization: content is causal — blanked variant reproduces ${pct}% of the lift (< ${(maxDecorativeFraction * 100).toFixed(0)}%); candidate Δ ${cand.lift.toFixed(3)}, neutralized Δ ${neut.lift.toFixed(3)}`,\n ]\n : [\n `neutralization: lift is DECORATIVE — blanking the content (footprint-matched) reproduces ${pct}% of the lift (≥ ${(maxDecorativeFraction * 100).toFixed(0)}%); candidate Δ ${cand.lift.toFixed(3)}, neutralized Δ ${neut.lift.toFixed(3)}`,\n ],\n contributingGates: [\n {\n name: 'neutralizationGate',\n status: passed ? 'pass' : 'fail',\n detail: {\n candidateLift: cand.lift,\n neutralizedLift: neut.lift,\n decorativeFraction,\n maxDecorativeFraction,\n n: cand.n,\n },\n },\n ],\n delta: cand.lift,\n }\n },\n }\n}\n","/**\n * @module\n * Footprint-matched neutralization — the placebo control for content-vs-footprint\n * attribution in a promotion gate.\n *\n * A promoted surface can raise a held-out score two different ways:\n * 1. its CONTENT is informative (the thing we want to promote), or\n * 2. it merely added prompt/mount FOOTPRINT — more bytes, more lines, a longer\n * more authoritative-looking prompt — that the model spends attention on\n * regardless of what the bytes say.\n *\n * A held-out gate proves the candidate beat baseline; it cannot separate (1) from\n * (2). `neutralizeText` produces a variant that keeps the input's layout and\n * length while carrying ZERO information, so scoring it isolates the footprint\n * contribution (2). Feed the neutralized variant's scores to `neutralizationGate`:\n * any lift it still holds over baseline is decorative, and a candidate whose lift\n * survives neutralization is rejected however large its raw lift.\n */\n\n/** Filler for blanked content. A single ASCII byte, so a run of it preserves an\n * ASCII source's exact byte length; for multibyte sources it preserves CHARACTER\n * count and layout (what the tokenizer footprint tracks), not raw byte count. */\nconst FILLER = '#'\n\n/**\n * Blank every non-whitespace character to a 1-byte filler while preserving all\n * whitespace. Line count, indentation, and word/line lengths are unchanged — so\n * the neutralized variant has the same layout and (for ASCII) the same byte\n * footprint as the input, but no readable content. Whitespace is preserved\n * deliberately: collapsing it would change the token structure and stop the\n * variant from being a true footprint match.\n */\nexport function neutralizeText(content: string): string {\n return content.replace(/\\S/g, FILLER)\n}\n","import { join } from 'node:path'\nimport { combineComparisonCosts } from './optimization-cost'\nimport type { OptimizationMethod, OptimizationMethodComposition } from './optimization-method'\nimport { executeOptimizationMethod } from './optimization-method'\nimport { fsCampaignStorage } from './storage'\nimport { surfaceContentHash } from './surface-identity'\nimport type { MutableSurface, Scenario } from './types'\n\n/** A composition owns artifact description when a method it composes does, so the\n * entry points refuse a caller's `describeArtifact` before the first stage spends. */\nfunction ownedArtifactDescription(\n methods: readonly Pick<OptimizationMethod, 'ownsArtifactDescription'>[],\n): { ownsArtifactDescription?: true } {\n return methods.some((method) => method.ownsArtifactDescription === true)\n ? { ownsArtifactDescription: true }\n : {}\n}\n\n/** Optimize a projection while evaluating every proposal in the complete candidate. */\nexport function scopedOptimizationMethod<S extends Scenario, A>(options: {\n name: string\n method: OptimizationMethod<S, A>\n project: (surface: MutableSurface) => MutableSurface\n merge: (baseline: MutableSurface, selected: MutableSurface) => MutableSurface\n}): OptimizationMethod<S, A> {\n return {\n name: options.name,\n ...ownedArtifactDescription([options.method]),\n async optimize(input) {\n const baseline = structuredClone(input.baselineSurface)\n const projected = options.project(structuredClone(baseline))\n const merge = (surface: MutableSurface) =>\n options.merge(structuredClone(baseline), structuredClone(surface))\n const baselineSurfaceHash = surfaceContentHash(baseline)\n if (surfaceContentHash(merge(projected)) !== baselineSurfaceHash)\n throw new Error('scoped optimization project/merge must preserve the baseline')\n const { selected, cost } = await executeOptimizationMethod({\n method: options.method,\n input: {\n ...input,\n baselineSurface: projected,\n surfaceToRoot: (surface) => {\n const merged = merge(surface)\n return input.surfaceToRoot ? input.surfaceToRoot(merged) : merged\n },\n runDir: join(input.runDir, `scope-${baselineSurfaceHash.slice('sha256:'.length)}`),\n runOptions: {\n ...input.runOptions,\n dispatchRef: JSON.stringify([\n input.runOptions.dispatchRef ?? null,\n options.name,\n baselineSurfaceHash,\n ]),\n },\n dispatchWithSurface: (surface, scenario, ctx) =>\n input.dispatchWithSurface(merge(surface), scenario, ctx),\n },\n storage: input.runOptions.storage ?? fsCampaignStorage(),\n })\n return {\n winnerSurface: merge(selected.winnerSurface),\n cost,\n ...(selected.durationMs === undefined ? {} : { durationMs: selected.durationMs }),\n composition: {\n kind: 'scoped',\n baselineSurfaceHash,\n stages: [\n {\n name: options.method.name,\n baselineSurfaceHash: surfaceContentHash(projected),\n result: { ...selected, cost },\n },\n ],\n },\n }\n },\n }\n}\n\n/** Each stage starts from the previous selected candidate, without an intervening release gate. */\nexport function sequentialOptimizationMethod<S extends Scenario, A>(options: {\n name: string\n methods: readonly OptimizationMethod<S, A>[]\n}): OptimizationMethod<S, A> {\n if (!options.methods.length)\n throw new Error('sequential optimization requires at least one method')\n const methods = [...options.methods]\n return {\n name: options.name,\n ...ownedArtifactDescription(methods),\n async optimize(input) {\n const started = Date.now()\n const stages: OptimizationMethodComposition['stages'] = []\n let winnerSurface = structuredClone(input.baselineSurface)\n for (const [index, method] of methods.entries()) {\n input.runOptions.signal?.throwIfAborted()\n const baselineSurfaceHash = surfaceContentHash(winnerSurface)\n const { selected, cost } = await executeOptimizationMethod({\n method,\n input: {\n ...input,\n baselineSurface: winnerSurface,\n runDir: join(input.runDir, `stage-${index}`),\n },\n storage: input.runOptions.storage ?? fsCampaignStorage(),\n })\n stages.push({ name: method.name, baselineSurfaceHash, result: { ...selected, cost } })\n winnerSurface = structuredClone(selected.winnerSurface)\n }\n return {\n winnerSurface,\n cost: combineComparisonCosts(\n stages.map((stage) => ({ label: stage.name, cost: stage.result.cost })),\n ),\n durationMs: Date.now() - started,\n composition: {\n kind: 'sequential',\n baselineSurfaceHash: surfaceContentHash(input.baselineSurface),\n stages,\n },\n }\n },\n }\n}\n","/**\n * Product-flow playback — drive the REAL product through a user story and\n * score the produced state per requirement (the launch \"Jira tick-off\").\n *\n * This is the substrate adapter + contract only. It plugs a `PlaybackDriver`\n * into the existing `runProfileMatrix` dispatch seam: a driver drives the real\n * product (a Playwright UI session or a sandbox workspace) and returns the\n * runtime event stream; `extractProducedState` + `verifyCompletion` then score\n * each requirement PASS/FAIL. The concrete drivers live in consumers — they\n * depend on browser / runtime infra the substrate must not import — so\n * agent-eval owns the seam, the `UserStory` contract, and the scoreboard.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n type CompletionRequirement,\n type CompletionVerdict,\n type CorrectnessChecker,\n type ProducedState,\n verifyCompletion,\n} from '../../completion-verifier'\nimport type { RuntimeEventLike } from '../../produced-state'\nimport type { DispatchContext, Scenario } from '../types'\n\n/** One step of a user story — what the user does. The driver interprets\n * `payload` (a Playwright selector + action, or a sandbox chat turn). */\nexport interface PlaybackStep {\n /** Human-readable action, captured verbatim in the UX narrative. */\n action: string\n /** Driver-specific payload (e.g. `{ selector, fill }` or `{ turn }`). */\n payload?: Record<string, unknown>\n}\n\n/**\n * A user story = a runnable product journey plus the requirements that define\n * \"this story works\". Each requirement is one Jira ticket line. Extends\n * `Scenario` so a catalog drops straight into `runProfileMatrix({ scenarios })`.\n */\nexport interface UserStory extends Scenario {\n /** Human-readable story title (the ticket headline). */\n title: string\n /** Ordered steps the driver executes. */\n steps: PlaybackStep[]\n /** What must hold in the produced state for the story to pass. */\n requirements: CompletionRequirement[]\n}\n\n/** Dispatch context plus the profile under test (which cheap model, etc.). */\nexport interface PlaybackContext extends DispatchContext {\n profile: AgentProfile\n}\n\n/**\n * Drives the real product through a story and returns the runtime event stream\n * `extractProducedState` consumes. Implemented by CONSUMERS —\n * `SandboxPlaybackDriver` (real API / sandbox workspace) and\n * `PlaywrightPlaybackDriver` (real UI) — because they depend on runtime /\n * browser infra the substrate must not import. The driver MUST report LLM\n * usage through `ctx.cost.runPaidCall` so the backend-integrity check sees real\n * tokens (a run that never reports tokens reads as a stub).\n */\nexport interface PlaybackDriver<TStory extends UserStory = UserStory> {\n run(story: TStory, ctx: PlaybackContext): Promise<readonly RuntimeEventLike[]>\n}\n\n/** A scored user story — the completion verdict plus its human title. */\nexport interface UserStoryVerdict extends CompletionVerdict {\n title: string\n}\n\n/**\n * Score one story's produced state against its requirements. Thin wrapper over\n * `verifyCompletion` that builds the gold from the story and returns a\n * per-requirement PASS/FAIL verdict. `checkCorrectness` is injected — a\n * deterministic stub in tests, `createLlmCorrectnessChecker` in production.\n */\nexport async function scoreUserStory(\n story: UserStory,\n state: ProducedState,\n checkCorrectness: CorrectnessChecker,\n): Promise<UserStoryVerdict> {\n const verdict = await verifyCompletion(\n { taskId: story.id, requirements: story.requirements },\n state,\n checkCorrectness,\n )\n return { ...verdict, title: story.title }\n}\n\n/** One row of the launch scoreboard — story × requirement → PASS/FAIL. */\nexport interface ScoreboardRow {\n storyId: string\n storyTitle: string\n reqId: string\n reqTitle: string\n status: 'PASS' | 'FAIL'\n evidence: string[]\n}\n\n/**\n * Flatten story verdicts into the per-requirement scoreboard — the literal\n * Jira tick-off: one row per (story, requirement) with PASS/FAIL and the\n * evidence behind the verdict.\n */\nexport function userStoryScoreboard(verdicts: readonly UserStoryVerdict[]): ScoreboardRow[] {\n const rows: ScoreboardRow[] = []\n for (const v of verdicts) {\n for (const r of v.requirements) {\n rows.push({\n storyId: v.taskId,\n storyTitle: v.title,\n reqId: r.reqId,\n reqTitle: r.title,\n status: r.satisfied ? 'PASS' : 'FAIL',\n evidence: r.evidence,\n })\n }\n }\n return rows\n}\n\n/** Launch-readiness headline counts rolled up from the per-requirement rows. */\nexport interface ScoreboardSummary {\n /** Distinct user stories on the board. */\n stories: number\n /** Stories whose every requirement passed. */\n storiesFullyComplete: number\n /** Total (story, requirement) rows. */\n requirements: number\n /** Rows with status PASS. */\n passed: number\n /** Rows with status FAIL. */\n failed: number\n /** passed / requirements; 0 when there are no rows. */\n passRate: number\n}\n\n/** Roll the per-requirement rows up into the launch headline counts. */\nexport function scoreboardSummary(rows: readonly ScoreboardRow[]): ScoreboardSummary {\n const byStory = new Map<string, { total: number; passed: number }>()\n let passed = 0\n for (const r of rows) {\n const s = byStory.get(r.storyId) ?? { total: 0, passed: 0 }\n s.total++\n if (r.status === 'PASS') {\n s.passed++\n passed++\n }\n byStory.set(r.storyId, s)\n }\n let storiesFullyComplete = 0\n for (const s of byStory.values()) if (s.total > 0 && s.passed === s.total) storiesFullyComplete++\n return {\n stories: byStory.size,\n storiesFullyComplete,\n requirements: rows.length,\n passed,\n failed: rows.length - passed,\n passRate: rows.length === 0 ? 0 : passed / rows.length,\n }\n}\n\nexport interface ScoreboardRenderOptions {\n /** Document H1. Defaults to a generic playback title. */\n title?: string\n /** Key/value run metadata rendered under the headline (runId, backend, model, date). */\n meta?: Record<string, string>\n /** Max chars of joined evidence shown per row. Default 160. */\n maxEvidenceChars?: number\n}\n\nfunction escapeCell(s: string): string {\n return s.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}…`\n}\n\n/**\n * Render the scoreboard as a launch-readiness Markdown document — the literal\n * \"tick off every user story\" artifact: a headline roll-up, the open tickets\n * (FAIL rows) up top as the launch blockers, then a per-story table of\n * requirement → PASS/FAIL with the evidence behind each verdict. Pure: same\n * rows in, same bytes out (no clock/random), so it is safe to snapshot.\n */\nexport function renderScoreboardMarkdown(\n rows: readonly ScoreboardRow[],\n opts: ScoreboardRenderOptions = {},\n): string {\n const maxEv = opts.maxEvidenceChars ?? 160\n const sum = scoreboardSummary(rows)\n const pct = (n: number) => `${Math.round(n * 100)}%`\n const ev = (e: string[]) => escapeCell(truncate(e.join('; '), maxEv)) || '—'\n const out: string[] = [`# ${opts.title ?? 'Product-flow playback scoreboard'}`, '']\n if (opts.meta) {\n for (const [k, v] of Object.entries(opts.meta)) out.push(`- **${k}:** ${v}`)\n out.push('')\n }\n out.push(\n `**${sum.storiesFullyComplete}/${sum.stories}** user stories fully shipped · ` +\n `**${sum.passed}/${sum.requirements}** requirements passing (${pct(sum.passRate)}) · ` +\n `**${sum.failed}** open`,\n '',\n )\n const fails = rows.filter((r) => r.status === 'FAIL')\n if (fails.length > 0) {\n out.push('## Open tickets', '', '| Story | Requirement | Evidence |', '| --- | --- | --- |')\n for (const r of fails) {\n out.push(`| ${escapeCell(r.storyTitle)} | ${escapeCell(r.reqTitle)} | ${ev(r.evidence)} |`)\n }\n out.push('')\n } else {\n out.push('_All requirements passing — no open tickets._', '')\n }\n out.push('## Per-story tick-off', '')\n for (const storyId of [...new Set(rows.map((r) => r.storyId))]) {\n const storyRows = rows.filter((r) => r.storyId === storyId)\n const passed = storyRows.filter((r) => r.status === 'PASS').length\n const mark = passed === storyRows.length ? '✅' : '⚠️'\n out.push(\n `### ${escapeCell(storyRows[0]!.storyTitle)} — ${passed}/${storyRows.length} ${mark}`,\n '',\n '| Requirement | Status | Evidence |',\n '| --- | --- | --- |',\n )\n for (const r of storyRows) {\n out.push(\n `| ${escapeCell(r.reqTitle)} | ${r.status === 'PASS' ? '✅ PASS' : '❌ FAIL'} | ${ev(r.evidence)} |`,\n )\n }\n out.push('')\n }\n return out.join('\\n')\n}\n","/**\n * How far a profile-matrix verdict can be trusted: the familywise adjustment that turns each\n * profile's paired difference from the baseline into a verdict, and the run-to-run noise of a\n * profile run more than once. `analyzeProfileMatrix` calls both and re-exports these types.\n */\n\nimport { type RunRecord, runTaskScore } from '../../run-record'\nimport { holm } from '../../statistics'\nimport { zQuantile } from '../../statistics/internal'\nimport { mean } from '../../statistics/mean'\nimport type { ProfileMatrixProfileStats } from './profile-matrix-analysis'\n\n/**\n * A profile against the baseline after the family adjustment. `better` and `worse`: the nominal\n * interval excludes zero and the Holm-adjusted p over the page's family is at most 1 - level.\n * `candidate`: the nominal interval excludes zero but the adjusted p does not pass.\n * `unresolved`: the nominal interval includes zero, or there is no paired case.\n */\nexport type ProfileMatrixVerdict = 'better' | 'worse' | 'candidate' | 'unresolved'\n\n/** The family of profile-against-baseline comparisons the verdicts control the error over. */\nexport interface ProfileMatrixFamily {\n method: 'holm'\n /** Familywise error rate the verdicts control: 1 - level. */\n alpha: number\n /** Comparisons with a p-value, one per profile other than the baseline. */\n comparisons: number\n}\n\n/** A share measured on each pair of runs: its mean over the pairs, and the lowest and highest. */\nexport interface ProfileMatrixPairwiseShare {\n mean: number\n min: number\n max: number\n}\n\n/** How much one profile's runs differ with nothing changed between them. */\nexport interface ProfileMatrixRunStability {\n profileId: string\n runs: number\n /** Cases every run of this profile scored; every number below is on them. */\n n: number\n /** Each run's mean score, in run order; null when `n` is 0. */\n runQuality: { run: number; quality: number | null }[]\n /** Highest run quality minus the lowest; null when `n` is 0. */\n spread: number | null\n /** Share of cases one run got right and the other did not, over run pairs; null when `n` is 0. */\n correctnessDisagreement: ProfileMatrixPairwiseShare | null\n /** Share of the cases both runs answered where the answers differ; null without such a case. */\n answerDisagreement: ProfileMatrixPairwiseShare | null\n /**\n * Half-width of the range, at the analysis level, within which two runs of this profile land\n * on the panel's common cases with nothing changed: z·√(m / n), where m is the mean squared\n * per-case score difference between two runs (for right/wrong scores, the correctness\n * disagreement) and each case's change is taken as independent. Null without common cases.\n */\n rerunMargin: number | null\n}\n\n/** Whether an interval lies wholly above zero, wholly below it, or includes it. */\nexport function intervalSide(i: {\n low: number | null\n high: number | null\n}): 'up' | 'down' | 'flat' {\n if (i.low !== null && i.low > 0) return 'up'\n if (i.high !== null && i.high < 0) return 'down'\n return 'flat'\n}\n\n/** The run a record belongs to: the campaign's `outcome.raw.rep`, or run 0 when absent. */\nexport function runOf(record: RunRecord): number {\n const rep = record.outcome.raw.rep\n return Number.isFinite(rep) ? rep! : 0\n}\n\n/**\n * Holm over every profile-against-baseline p-value on the page, so the better and worse verdicts\n * together keep the familywise error at `alpha`. A comparison without a p-value cannot pass, so\n * it stays out of the family instead of raising everyone else's bar.\n */\nexport function withVerdicts(\n stats: readonly ProfileMatrixProfileStats[],\n baseline: string,\n alpha: number,\n): { profiles: ProfileMatrixProfileStats[]; family: ProfileMatrixFamily } {\n const tested = stats.filter((p) => typeof p.vsBaseline?.pValue === 'number')\n const { adjusted } = holm(\n tested.map((p) => p.vsBaseline!.pValue!),\n alpha,\n )\n const adjustedOf = new Map(tested.map((p, index) => [p.profileId, adjusted[index]!]))\n const profiles = stats.map((p) => {\n if (p.profileId === baseline) return p\n const adjustedPValue = adjustedOf.get(p.profileId) ?? null\n const side = p.vsBaseline ? intervalSide(p.vsBaseline) : 'flat'\n const verdict: ProfileMatrixVerdict =\n side === 'flat'\n ? 'unresolved'\n : adjustedPValue !== null && adjustedPValue <= alpha\n ? side === 'up'\n ? 'better'\n : 'worse'\n : 'candidate'\n return { ...p, adjustedPValue, verdict }\n })\n return { profiles, family: { method: 'holm', alpha, comparisons: tested.length } }\n}\n\n/**\n * Each profile with two or more runs, on the cases every one of its runs scored. A run's score\n * on a case is the mean of its records there, and its answer the last one `answerOf` returned.\n */\nexport function runStability(input: {\n profileIds: readonly string[]\n recordsByProfile: ReadonlyMap<string, readonly RunRecord[]>\n answerOf: ((record: RunRecord) => string | undefined) | undefined\n level: number\n passScore: number\n /** Common cases of the panel: the n the rerun margin is stated at. */\n commonCases: number\n}): ProfileMatrixRunStability[] {\n const z = zQuantile(1 - (1 - input.level) / 2)\n const panelN = input.commonCases\n const right = (score: number) => score >= input.passScore\n const share = (values: number[]): ProfileMatrixPairwiseShare | null =>\n values.length\n ? { mean: mean(values), min: Math.min(...values), max: Math.max(...values) }\n : null\n return input.profileIds.flatMap((profileId) => {\n const scores = new Map<number, Map<string, number[]>>()\n const answers = new Map<number, Map<string, string>>()\n for (const record of input.recordsByProfile.get(profileId)!) {\n const run = runOf(record)\n const own = scores.get(run) ?? new Map<string, number[]>()\n scores.set(run, own)\n const score = runTaskScore(record)\n if (score === undefined) continue\n own.set(record.scenarioId, [...(own.get(record.scenarioId) ?? []), score])\n const answer = input.answerOf?.(record)\n if (answer === undefined) continue\n const given = answers.get(run) ?? new Map<string, string>()\n given.set(record.scenarioId, answer)\n answers.set(run, given)\n }\n if (scores.size < 2) return []\n const runs = [...scores.keys()].sort((a, b) => a - b)\n const scoreIn = (run: number, caseId: string) => mean(scores.get(run)!.get(caseId)!)\n const cases = [...scores.get(runs[0]!)!.keys()]\n .filter((caseId) => runs.every((run) => scores.get(run)!.has(caseId)))\n .sort()\n const n = cases.length\n const pairs = runs.flatMap((a, index) => runs.slice(index + 1).map((b) => [a, b] as const))\n const runQuality = runs.map((run) => ({\n run,\n quality: n ? mean(cases.map((caseId) => scoreIn(run, caseId))) : null,\n }))\n const qualities = runQuality.flatMap((r) => (r.quality === null ? [] : [r.quality]))\n const correctness = n\n ? pairs.map(\n ([a, b]) => cases.filter((c) => right(scoreIn(a, c)) !== right(scoreIn(b, c))).length / n,\n )\n : []\n const answered = pairs.flatMap(([a, b]) => {\n const both = cases.filter((c) => answers.get(a)?.has(c) && answers.get(b)?.has(c))\n const differ = both.filter((c) => answers.get(a)!.get(c) !== answers.get(b)!.get(c))\n return both.length ? [differ.length / both.length] : []\n })\n const squared = n\n ? mean(pairs.map(([a, b]) => mean(cases.map((c) => (scoreIn(a, c) - scoreIn(b, c)) ** 2))))\n : null\n return [\n {\n profileId,\n runs: runs.length,\n n,\n runQuality,\n spread: qualities.length ? Math.max(...qualities) - Math.min(...qualities) : null,\n correctnessDisagreement: share(correctness),\n answerDisagreement: share(answered),\n rerunMargin: squared !== null && panelN > 0 ? z * Math.sqrt(squared / panelN) : null,\n },\n ]\n })\n}\n","/**\n * The numbers behind a profile-matrix decision page, computed once from the\n * matrix's RunRecords so the page and any caller read the same analysis.\n *\n * Cells often run on different numbers of cases, so the analysis keeps two\n * case sets apart. Every paired difference (from the baseline, inside a factor\n * effect, in a race) is measured on the cases both profiles scored, so each\n * comparison uses all the evidence it has and carries its own n. The panels\n * that need one case set for every profile (the frontiers, error overlap, item\n * difficulty, slices and power) use the common set of the panel profiles: the\n * profiles that scored at least `minCoverage` of the baseline's scored cases. A\n * profile under that line is reported in its own partial-coverage rows instead\n * of shrinking the common set for everyone.\n *\n * A case a profile failed has no score, so it leaves that profile's cases\n * instead of counting as wrong, and the failure shows as its failure rate.\n * Cases drawn from one source (a docket, a repository, a user) are not\n * independent, so intervals resample whole clusters when the caller names them.\n */\n\nimport { ValidationError } from '../../errors'\nimport { clusteredPower } from '../../experiment/power'\nimport { brierScore, type CalibrationBin, calibrationFromPairs } from '../../meta-eval/calibration'\nimport { paretoFrontier } from '../../pareto'\nimport { type RunRecord, runTaskScore } from '../../run-record'\nimport {\n clusteredPairedContrast,\n clusterJackknife,\n mcnemarRequiredN,\n percentileNearestRank,\n requiredPairedSampleSize,\n wilson,\n} from '../../statistics'\nimport { mean } from '../../statistics/mean'\nimport {\n type ProfileMatrixFamily,\n type ProfileMatrixRunStability,\n type ProfileMatrixVerdict,\n runOf,\n runStability,\n withVerdicts,\n} from './profile-matrix-stability'\nimport type { ProfileMatrixRaceResult } from './race-profile-matrix'\n\n/** A cost drawn against quality. `seconds` is the latency axis. */\nexport type ProfileMatrixCostAxis = 'usd' | 'tokens' | 'seconds'\n\nexport const PROFILE_MATRIX_COST_AXES: readonly ProfileMatrixCostAxis[] = [\n 'usd',\n 'tokens',\n 'seconds',\n]\n\nexport interface ProfileMatrixReportOptions {\n /** A `runProfileMatrix` or `raceProfileMatrix` result, or the RunRecords alone. */\n source: { readonly records: readonly RunRecord[] } | readonly RunRecord[]\n /** Profile id (`candidateId`) every paired difference is measured against. */\n baseline: string\n /** Profiles to compare, in display order. Default: every profile in the records, baseline first. */\n profiles?: readonly string[]\n /**\n * Share of the baseline's scored cases a profile must also have scored to join the\n * common-set panels, in (0, 1]. Default 0.9. When the source is a race result, its\n * survivors form the panel instead.\n */\n minCoverage?: number\n /** Independent unit per case id. Every scored case needs one; default one unit per case. */\n clusters?: Readonly<Record<string, string>>\n /** Slice per case id for the slice heatmap. */\n slices?: Readonly<Record<string, string>>\n /** Factor levels per profile id, such as model, harness, effort or instructions. */\n factors?: Readonly<Record<string, Readonly<Record<string, string>>>>\n /** Costs to draw against quality. Default all three; an axis without measurements is reported, not drawn. */\n costAxes?: readonly ProfileMatrixCostAxis[]\n /** A case counts as correct at or above this score. Default 0.5, which pass/fail scores do not notice. */\n passScore?: number\n /** The profile's own forecast, in [0, 1], that its answer is correct, when it returned one. */\n probabilityOf?: (record: RunRecord) => number | undefined\n /**\n * The answer a record gave, such as its label, so the run-to-run panel can count answers that\n * change between runs; without it the panel counts only changes of correctness.\n */\n answerOf?: (record: RunRecord) => string | undefined\n /** A race over these profiles: the page prints its elimination log and its selection-bias note. */\n race?: ProfileMatrixRaceResult\n /** Interval level. Default 0.95. */\n level?: number\n title?: string\n}\n\nexport interface ProfileMatrixInterval {\n estimate: number\n /** Null when the interval is undefined, as with fewer than two clusters. */\n low: number | null\n high: number | null\n}\n\n/** One profile against another on the cases both scored. */\nexport interface ProfileMatrixPairedDifference extends ProfileMatrixInterval {\n /** Cases both profiles scored. */\n n: number\n /** Independent clusters among those cases. */\n clusters: number\n /** Exact cluster sign-flip p-value for a zero difference. */\n pValue: number | null\n /** Share of the paired cases where exactly one of the two profiles was correct. */\n discordance: number\n /** Paired cases a two-sided test needs for 80% power at the observed difference; null at a zero difference. Ignores clustering. */\n casesToResolve: number | null\n}\n\nexport {\n intervalSide,\n type ProfileMatrixFamily,\n type ProfileMatrixPairwiseShare,\n type ProfileMatrixRunStability,\n type ProfileMatrixVerdict,\n} from './profile-matrix-stability'\n\nexport interface ProfileMatrixProfileStats {\n profileId: string\n factors: Readonly<Record<string, string>>\n /** Distinct runs among this profile's records by `outcome.raw.rep`; a record without one is run 0. */\n runs: number\n casesAttempted: number\n casesScored: number\n /** Share of this profile's records without a score: a dispatch or judge failure. */\n failureRate: number\n /** Share of the baseline's scored cases this profile also scored. */\n coverage: number\n /** In the common-set panels: the frontiers, error overlap, difficulty, slices and power. */\n panel: boolean\n /** Cases this profile and the baseline both scored, the n of `vsBaseline`; on the baseline, its own scored cases. */\n pairedN: number\n /** The race batch whose standings dropped this profile. */\n droppedAtBatch?: number\n /** Mean score on this profile's own scored cases. */\n ownQuality: ProfileMatrixInterval | null\n /** Mean score on the common set; null outside the panel. */\n quality: ProfileMatrixInterval | null\n /** Paired difference from the baseline on the cases both scored; absent on the baseline. */\n vsBaseline?: ProfileMatrixPairedDifference\n /** Holm-adjusted `vsBaseline.pValue` over the family; null without a p-value. */\n adjustedPValue?: number | null\n /** Standing against the baseline after the family adjustment; absent on the baseline. */\n verdict?: ProfileMatrixVerdict\n /** Mean per common case; null outside the panel or when a record in it did not measure that cost. */\n costPerCase: Record<ProfileMatrixCostAxis, number | null>\n /** Common-set total divided by the common cases answered correctly; null outside the panel or with none correct. */\n costPerCorrect: Record<ProfileMatrixCostAxis, number | null>\n /** Seconds per common case; null outside the panel. */\n latency: { p50: number; p90: number } | null\n}\n\nexport interface ProfileMatrixAxisSummary {\n axis: ProfileMatrixCostAxis\n drawn: boolean\n /** What the axis measures, or why it is not drawn. */\n note: string\n /** Panel profiles on the quality-versus-this-axis Pareto set, cheapest first. */\n frontier: string[]\n}\n\nexport interface ProfileMatrixFactorEffect {\n factor: string\n level: string\n /** The baseline's level of this factor, or its most common level. */\n reference: string\n /** Profile pairs that differ only in this factor; zero means the effect is confounded. */\n matchedPairs: number\n /** Cases at least one matched pair scored on both sides. */\n n: number\n /** Fewest and most cases one matched pair shares; null without a matched pair. */\n pairCases: { min: number; max: number } | null\n /** Mean over those cases of the matched pairs' mean difference on each case. */\n effect: ProfileMatrixInterval | null\n pValue: number | null\n}\n\nexport interface ProfileMatrixSliceCell {\n profileId: string\n slice: string\n /** Common cases in the slice. */\n n: number\n quality: number | null\n}\n\nexport interface ProfileMatrixErrorOverlap {\n a: string\n b: string\n /** Share of common cases both got wrong. */\n bothWrong: number\n /** Share of common cases exactly one got right. */\n disagree: number\n}\n\nexport interface ProfileMatrixCaseDifficulty {\n caseId: string\n slice?: string\n /** Panel profiles that got the case right. */\n solved: number\n /** Panel profiles that scored the case. */\n scored: number\n share: number\n}\n\nexport interface ProfileMatrixCalibration {\n profileId: string\n n: number\n ece: number\n brier: number\n bins: CalibrationBin[]\n}\n\nexport interface ProfileMatrixPower {\n n: number\n clusters: number\n /** Median share of common cases on which a panel profile and the baseline disagree on correctness. */\n discordance: number\n /** Smallest paired difference detected with 80% power; null when not even a difference of 1 is. */\n detectable: number | null\n /** False when this many clusters cannot reach the level by an exact sign-flip test at any effect. */\n certifiable: boolean\n minClusters: number\n}\n\nexport interface ProfileMatrixAnalysis {\n title: string\n baseline: string\n level: number\n passScore: number\n /** True when every per-case score is 0 or 1. */\n passFail: boolean\n minCoverage: number\n /** `coverage`: profiles at `minCoverage` or above; `race-survivors`: the source race's survivors. */\n panelRule: 'coverage' | 'race-survivors'\n /** Profiles in the common-set panels, baseline first. */\n panelProfiles: string[]\n /** Cases every panel profile scored: the set the frontiers, overlap, difficulty, slices and power use. */\n commonCases: string[]\n commonClusters: number\n axes: ProfileMatrixAxisSummary[]\n /** Every profile, baseline first; `panel` marks the panel profiles. */\n profiles: ProfileMatrixProfileStats[]\n /** The comparisons each profile's `verdict` is adjusted over. */\n family: ProfileMatrixFamily\n /** Every profile with two or more runs, in profile order. */\n stability: ProfileMatrixRunStability[]\n factorEffects: ProfileMatrixFactorEffect[]\n /** Slice names, the slice with the most common cases first. */\n slices: string[]\n sliceCells: ProfileMatrixSliceCell[]\n errorOverlap: ProfileMatrixErrorOverlap[]\n /** Share of common cases at least one panel profile got right. */\n oracle: number | null\n difficulty: ProfileMatrixCaseDifficulty[]\n calibration: ProfileMatrixCalibration[]\n power: ProfileMatrixPower | null\n}\n\n/** How two profiles are paired: clusters, level, and what counts as correct. */\nexport interface ProfilePairingRule {\n clusterOf: (caseId: string) => string\n level: number\n passScore: number\n /** Every score is 0 or 1, so the required n follows McNemar. */\n passFail: boolean\n}\n\nconst TARGET_POWER = 0.8\nconst UNLABELLED_SLICE = 'unlabelled'\n\n/** One profile's records on one case, reps averaged. */\ninterface CaseCost {\n usd: number | null\n tokens: number | null\n seconds: number\n}\n\ninterface Context {\n options: ProfileMatrixReportOptions\n rule: ProfilePairingRule\n minCoverage: number\n race: ProfileMatrixRaceResult | undefined\n panelRule: ProfileMatrixAnalysis['panelRule']\n profileIds: string[]\n panel: string[]\n scores: Map<string, Map<string, number>>\n costs: Map<string, Map<string, CaseCost>>\n recordsByProfile: Map<string, RunRecord[]>\n baselineCases: string[]\n common: string[]\n}\n\n/**\n * Compare profile-matrix cells against one baseline: quality with clustered\n * intervals, paired differences, the cost and latency frontiers, factor main\n * effects, slices, error overlap, item difficulty, calibration and power.\n *\n * A profile run more than once (its records carry `outcome.raw.rep`, as campaign\n * records do) scores each case at its mean over the runs, and `stability` measures\n * how far its runs differ with nothing changed. Each verdict against the baseline\n * is Holm-adjusted over every profile-against-baseline comparison, so with dozens\n * of profiles one lucky interval reads as a candidate, not a win.\n */\nexport function analyzeProfileMatrix(options: ProfileMatrixReportOptions): ProfileMatrixAnalysis {\n const ctx = buildContext(options)\n const { profiles, family } = withVerdicts(\n ctx.profileIds.map((profileId) => profileStats(ctx, profileId)),\n options.baseline,\n 1 - ctx.rule.level,\n )\n const panel = profiles.filter((stats) => stats.panel)\n const slices = sliceNames(ctx)\n return {\n title: options.title ?? 'Profile matrix',\n baseline: options.baseline,\n level: ctx.rule.level,\n passScore: ctx.rule.passScore,\n passFail: ctx.rule.passFail,\n minCoverage: ctx.minCoverage,\n panelRule: ctx.panelRule,\n panelProfiles: ctx.panel,\n commonCases: ctx.common,\n commonClusters: new Set(ctx.common.map((caseId) => ctx.rule.clusterOf(caseId))).size,\n axes: axisSummaries(ctx, panel),\n profiles,\n family,\n stability: runStability({\n profileIds: ctx.profileIds,\n recordsByProfile: ctx.recordsByProfile,\n answerOf: options.answerOf,\n level: ctx.rule.level,\n passScore: ctx.rule.passScore,\n commonCases: ctx.common.length,\n }),\n factorEffects: factorEffects(ctx),\n slices,\n sliceCells: sliceCells(ctx, slices),\n ...errorOverlap(ctx),\n difficulty: difficulty(ctx),\n calibration: calibration(ctx),\n power: power(ctx, panel),\n }\n}\n\n/** Mean score per profile and case over its scored reps; a case without a scored rep is absent. */\nexport function scoresByProfile(records: readonly RunRecord[]): Map<string, Map<string, number>> {\n const scored = new Map<string, Map<string, number[]>>()\n for (const record of records) {\n const score = runTaskScore(record)\n if (score === undefined) continue\n const cases = scored.get(record.candidateId) ?? new Map<string, number[]>()\n cases.set(record.scenarioId, [...(cases.get(record.scenarioId) ?? []), score])\n scored.set(record.candidateId, cases)\n }\n return new Map(\n [...scored].map(([id, cases]) => [id, new Map([...cases].map(([c, xs]) => [c, mean(xs)]))]),\n )\n}\n\n/**\n * Profile `a` against profile `b` on the cases both scored, restricted to `cases` when\n * given. Every paired number on the page and in the race comes from here.\n */\nexport function pairProfiles(\n a: ReadonlyMap<string, number>,\n b: ReadonlyMap<string, number>,\n rule: ProfilePairingRule,\n cases?: readonly string[],\n): ProfileMatrixPairedDifference | undefined {\n const both = (cases ?? [...a.keys()]).filter((c) => a.has(c) && b.has(c)).sort()\n if (both.length === 0) return undefined\n const deltas = both.map((caseId) => ({ caseId, delta: a.get(caseId)! - b.get(caseId)! }))\n const right = (score: number) => score >= rule.passScore\n const wins = both.filter((c) => right(a.get(c)!) && !right(b.get(c)!)).length\n const losses = both.filter((c) => !right(a.get(c)!) && right(b.get(c)!)).length\n return {\n ...clusteredDifference(deltas, rule.clusterOf, rule.level),\n discordance: (wins + losses) / both.length,\n casesToResolve: casesToResolve(\n rule,\n deltas.map((d) => d.delta),\n wins / both.length,\n losses / both.length,\n ),\n }\n}\n\n/** True when every score is 0 or 1. */\nexport function allPassFail(scores: ReadonlyMap<string, ReadonlyMap<string, number>>): boolean {\n return [...scores.values()].every((cases) =>\n [...cases.values()].every((score) => score === 0 || score === 1),\n )\n}\n\n/**\n * Each case's independent unit, one per case when no clusters are given. A case missing from\n * a given cluster map is refused rather than counted as its own unit. Shared with the race.\n */\nexport function clusterResolver(\n clusters: Readonly<Record<string, string>> | undefined,\n owner: string,\n): (caseId: string) => string {\n return (caseId) => {\n if (!clusters) return caseId\n const cluster = clusters[caseId]\n if (typeof cluster !== 'string' || cluster.length === 0) {\n throw new ValidationError(`${owner}: case '${caseId}' has no cluster`)\n }\n return cluster\n }\n}\n\n/** Mean of per-case differences with its cluster-jackknife interval and exact sign-flip p. */\nfunction clusteredDifference(\n deltas: readonly { caseId: string; delta: number }[],\n clusterOf: (caseId: string) => string,\n level: number,\n): ProfileMatrixInterval & { n: number; clusters: number; pValue: number | null } {\n const units = deltas.map(({ caseId, delta }) => ({ cluster: clusterOf(caseId), delta }))\n const result = clusteredPairedContrast(units, { level, seed: 1 })\n return {\n estimate: mean(deltas.map((d) => d.delta)),\n low: result.low,\n high: result.high,\n pValue: result.pValue,\n n: deltas.length,\n clusters: new Set(units.map((unit) => unit.cluster)).size,\n }\n}\n\nfunction casesToResolve(\n rule: ProfilePairingRule,\n deltas: number[],\n p10: number,\n p01: number,\n): number | null {\n const alpha = 1 - rule.level\n if (rule.passFail) {\n const needed = mcnemarRequiredN({ p10, p01, alpha, power: TARGET_POWER })\n return Number.isFinite(needed) ? needed : null\n }\n if (deltas.length < 2) return null\n const average = mean(deltas)\n const sd = Math.sqrt(deltas.reduce((sum, d) => sum + (d - average) ** 2, 0) / (deltas.length - 1))\n if (sd === 0 || average === 0) return null\n const needed = requiredPairedSampleSize({\n effect: Math.abs(average) / sd,\n alpha,\n power: TARGET_POWER,\n })\n return Number.isFinite(needed) ? needed : null\n}\n\n/** True when the source is a `raceProfileMatrix` result. */\nexport function isRaceResult(\n source: ProfileMatrixReportOptions['source'],\n): source is ProfileMatrixRaceResult {\n return 'survivors' in source && 'log' in source\n}\n\nfunction buildContext(options: ProfileMatrixReportOptions): Context {\n const level = options.level ?? 0.95\n if (!(level > 0 && level < 1))\n throw new ValidationError('profile matrix: level must be in (0, 1)')\n const passScore = options.passScore ?? 0.5\n if (!Number.isFinite(passScore))\n throw new ValidationError('profile matrix: passScore must be finite')\n const minCoverage = options.minCoverage ?? 0.9\n if (!(minCoverage > 0 && minCoverage <= 1))\n throw new ValidationError('profile matrix: minCoverage must be in (0, 1]')\n const raceSource = isRaceResult(options.source) ? options.source : undefined\n const records = 'records' in options.source ? options.source.records : options.source\n const recordsByProfile = new Map<string, RunRecord[]>()\n for (const record of records) {\n const list = recordsByProfile.get(record.candidateId) ?? []\n list.push(record)\n recordsByProfile.set(record.candidateId, list)\n }\n const listed = options.profiles ? [...options.profiles] : [...recordsByProfile.keys()]\n if (new Set(listed).size !== listed.length) {\n throw new ValidationError('profile matrix: profiles must be distinct')\n }\n const baseline = options.baseline\n const profileIds = [baseline, ...listed.filter((id) => id !== baseline)]\n for (const profileId of profileIds) {\n if (!recordsByProfile.has(profileId)) {\n throw new ValidationError(`profile matrix: profile '${profileId}' has no records`)\n }\n }\n const scored = scoresByProfile(records)\n const scores = new Map(profileIds.map((id) => [id, scored.get(id) ?? new Map<string, number>()]))\n const baselineCases = [...scores.get(baseline)!.keys()].sort()\n if (baselineCases.length === 0) {\n throw new ValidationError(`profile matrix: baseline '${baseline}' scored no case`)\n }\n const clusterOf = clusterResolver(options.clusters, 'profile matrix')\n for (const cases of scores.values()) for (const caseId of cases.keys()) clusterOf(caseId)\n const covers = (id: string) => coverageOf(scores, baselineCases, id) >= minCoverage\n const panel = raceSource\n ? profileIds.filter((id) => id === baseline || raceSource.survivors.includes(id))\n : profileIds.filter((id) => id === baseline || covers(id))\n return {\n options,\n rule: { clusterOf, level, passScore, passFail: allPassFail(scores) },\n minCoverage,\n race: options.race ?? raceSource,\n panelRule: raceSource ? 'race-survivors' : 'coverage',\n profileIds,\n panel,\n scores,\n costs: new Map(profileIds.map((id) => [id, caseCosts(recordsByProfile.get(id)!)])),\n recordsByProfile,\n baselineCases,\n common: baselineCases.filter((caseId) => panel.every((id) => scores.get(id)!.has(caseId))),\n }\n}\n\nfunction coverageOf(\n scores: Map<string, Map<string, number>>,\n baselineCases: readonly string[],\n profileId: string,\n): number {\n const own = scores.get(profileId)!\n return baselineCases.filter((caseId) => own.has(caseId)).length / baselineCases.length\n}\n\nfunction caseCosts(records: readonly RunRecord[]): Map<string, CaseCost> {\n const grouped = new Map<string, RunRecord[]>()\n for (const record of records) {\n const list = grouped.get(record.scenarioId) ?? []\n list.push(record)\n grouped.set(record.scenarioId, list)\n }\n const costs = new Map<string, CaseCost>()\n for (const [caseId, reps] of grouped) {\n costs.set(caseId, {\n usd: reps.every((r) => r.costUsd !== null) ? mean(reps.map((r) => r.costUsd!)) : null,\n tokens: reps.every((r) => r.tokenUsage.tokensKnown !== false)\n ? mean(reps.map(tokenTotal))\n : null,\n seconds: mean(reps.map(latencySeconds)),\n })\n }\n return costs\n}\n\n/** Every prompt token (fresh, cached and cache-write) plus output; reasoning is counted inside output. */\nfunction tokenTotal(record: RunRecord): number {\n const usage = record.tokenUsage\n return usage.input + (usage.cached ?? 0) + (usage.cacheWrite ?? 0) + usage.output\n}\n\n/** Dispatch time when the cell recorded it, so judging does not count as latency; else the wall clock. */\nfunction latencySeconds(record: RunRecord): number {\n const dispatchMs = record.outcome.raw.dispatch_ms\n return (Number.isFinite(dispatchMs) ? dispatchMs! : record.wallMs) / 1000\n}\n\nfunction scoreOf(ctx: Context, profileId: string, caseId: string): number {\n return ctx.scores.get(profileId)!.get(caseId)!\n}\n\nfunction correct(ctx: Context, profileId: string, caseId: string): boolean {\n return scoreOf(ctx, profileId, caseId) >= ctx.rule.passScore\n}\n\nconst NO_COST: Record<ProfileMatrixCostAxis, null> = { usd: null, tokens: null, seconds: null }\n\nfunction profileStats(ctx: Context, profileId: string): ProfileMatrixProfileStats {\n const own = [...ctx.scores.get(profileId)!.keys()]\n const records = ctx.recordsByProfile.get(profileId)!\n const isBaseline = profileId === ctx.options.baseline\n const vsBaseline = isBaseline\n ? undefined\n : pairProfiles(ctx.scores.get(profileId)!, ctx.scores.get(ctx.options.baseline)!, ctx.rule)\n const droppedAtBatch = ctx.race?.log.find((batch) =>\n batch.standings.some((s) => s.profileId === profileId && s.dropped),\n )?.batch\n const base = {\n profileId,\n factors: ctx.options.factors?.[profileId] ?? {},\n runs: new Set(records.map(runOf)).size,\n casesAttempted: ctx.costs.get(profileId)!.size,\n casesScored: own.length,\n failureRate: records.filter((r) => runTaskScore(r) === undefined).length / records.length,\n coverage: coverageOf(ctx.scores, ctx.baselineCases, profileId),\n panel: ctx.panel.includes(profileId),\n pairedN: isBaseline ? own.length : (vsBaseline?.n ?? 0),\n ...(droppedAtBatch === undefined ? {} : { droppedAtBatch }),\n ownQuality: qualityOn(ctx, profileId, own),\n ...(vsBaseline ? { vsBaseline } : {}),\n }\n if (!base.panel) {\n return { ...base, quality: null, costPerCase: NO_COST, costPerCorrect: NO_COST, latency: null }\n }\n const costs = ctx.common.map((caseId) => ctx.costs.get(profileId)!.get(caseId)!)\n const correctCount = ctx.common.filter((caseId) => correct(ctx, profileId, caseId)).length\n const costPerCase = {} as Record<ProfileMatrixCostAxis, number | null>\n const costPerCorrect = {} as Record<ProfileMatrixCostAxis, number | null>\n for (const axis of PROFILE_MATRIX_COST_AXES) {\n const values = costs.map((cost) => cost[axis])\n const known = values.length > 0 && values.every((value) => value !== null)\n costPerCase[axis] = known ? mean(values as number[]) : null\n costPerCorrect[axis] =\n known && correctCount > 0\n ? (values as number[]).reduce((a, b) => a + b, 0) / correctCount\n : null\n }\n const seconds = costs.map((cost) => cost.seconds)\n return {\n ...base,\n quality: qualityOn(ctx, profileId, ctx.common),\n costPerCase,\n costPerCorrect,\n latency:\n seconds.length > 0\n ? { p50: percentileNearestRank(seconds, 50), p90: percentileNearestRank(seconds, 90) }\n : null,\n }\n}\n\n/** Mean score on `cases`: Wilson for unclustered pass/fail scores, the cluster jackknife otherwise. */\nfunction qualityOn(\n ctx: Context,\n profileId: string,\n cases: readonly string[],\n): ProfileMatrixInterval | null {\n const items = cases.map((caseId) => ({ caseId, score: scoreOf(ctx, profileId, caseId) }))\n if (items.length === 0) return null\n const estimate = mean(items.map((item) => item.score))\n if (ctx.rule.passFail && !ctx.options.clusters) {\n const successes = items.filter((item) => item.score === 1).length\n const interval = wilson(successes, items.length, ctx.rule.level)\n return { estimate, low: interval.lower, high: interval.upper }\n }\n const interval = clusterJackknife(\n items,\n (item) => ctx.rule.clusterOf(item.caseId),\n (sample) => mean(sample.map((item) => item.score)),\n { level: ctx.rule.level },\n )\n return { estimate, low: interval.low, high: interval.high }\n}\n\nfunction axisSummaries(\n ctx: Context,\n panel: readonly ProfileMatrixProfileStats[],\n): ProfileMatrixAxisSummary[] {\n const requested = ctx.options.costAxes ?? PROFILE_MATRIX_COST_AXES\n return requested.map((axis) => {\n const x = (stats: ProfileMatrixProfileStats) =>\n axis === 'seconds' ? (stats.latency?.p50 ?? null) : stats.costPerCase[axis]\n const unmeasured = panel.filter((stats) => x(stats) === null)\n const reason =\n ctx.common.length === 0\n ? 'no case was scored by every panel profile'\n : unmeasured.length > 0\n ? `${unmeasured.length} of ${panel.length} panel profiles did not measure it on every common case`\n : axis === 'usd' && panel.every((stats) => x(stats) === 0)\n ? 'every profile costs $0 at the margin, as on flat-rate seats'\n : null\n if (reason !== null) return { axis, drawn: false, note: reason, frontier: [] }\n const { frontier } = paretoFrontier(\n [...panel],\n [\n { name: 'quality', direction: 'maximize', value: (stats) => stats.quality!.estimate },\n { name: axis, direction: 'minimize', value: (stats) => x(stats)! },\n ],\n )\n return {\n axis,\n drawn: true,\n note: AXIS_NOTES[axis],\n frontier: frontier.sort((a, b) => x(a)! - x(b)!).map((stats) => stats.profileId),\n }\n })\n}\n\nconst AXIS_NOTES: Record<ProfileMatrixCostAxis, string> = {\n usd: 'mean dollars per common case',\n tokens:\n 'mean tokens per common case: every prompt token, cached included, plus output with reasoning counted once',\n seconds:\n 'median seconds per common case: dispatch time, or the cell wall clock where dispatch time was not recorded',\n}\n\n/**\n * Each level against the reference over matched pairs: profiles that differ only in this\n * factor. Each pair is compared on the cases it shares; a case's delta is the mean over the\n * pairs that share it, so a case counts once and the clusters stay independent.\n */\nfunction factorEffects(ctx: Context): ProfileMatrixFactorEffect[] {\n const factors = ctx.options.factors\n if (!factors) return []\n const levelOf = (profileId: string, factor: string) => factors[profileId]?.[factor]\n const names = [...new Set(ctx.profileIds.flatMap((id) => Object.keys(factors[id] ?? {})))].sort()\n const effects: ProfileMatrixFactorEffect[] = []\n for (const factor of names) {\n const defined = ctx.profileIds.filter((id) => levelOf(id, factor) !== undefined)\n const counts = new Map<string, number>()\n for (const id of defined)\n counts.set(levelOf(id, factor)!, (counts.get(levelOf(id, factor)!) ?? 0) + 1)\n const reference =\n levelOf(ctx.options.baseline, factor) ??\n [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]![0]\n for (const level of [...counts.keys()].filter((l) => l !== reference).sort()) {\n const matched = defined.flatMap((p) =>\n levelOf(p, factor) !== level\n ? []\n : defined\n .filter(\n (q) => levelOf(q, factor) === reference && differOnlyIn(factors, p, q, factor),\n )\n .map((q) => [p, q] as const),\n )\n const perCase = new Map<string, number[]>()\n const pairSizes = matched.map(([p, q]) => {\n const [a, b] = [ctx.scores.get(p)!, ctx.scores.get(q)!]\n const both = [...a.keys()].filter((caseId) => b.has(caseId))\n for (const caseId of both) {\n perCase.set(caseId, [...(perCase.get(caseId) ?? []), a.get(caseId)! - b.get(caseId)!])\n }\n return both.length\n })\n const base = {\n factor,\n level,\n reference,\n matchedPairs: matched.length,\n n: perCase.size,\n pairCases: matched.length\n ? { min: Math.min(...pairSizes), max: Math.max(...pairSizes) }\n : null,\n }\n if (perCase.size === 0) {\n effects.push({ ...base, effect: null, pValue: null })\n continue\n }\n const deltas = [...perCase]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([caseId, values]) => ({ caseId, delta: mean(values) }))\n const { pValue, estimate, low, high } = clusteredDifference(\n deltas,\n ctx.rule.clusterOf,\n ctx.rule.level,\n )\n effects.push({ ...base, effect: { estimate, low, high }, pValue })\n }\n }\n return effects\n}\n\nfunction differOnlyIn(\n factors: Readonly<Record<string, Readonly<Record<string, string>>>>,\n p: string,\n q: string,\n factor: string,\n): boolean {\n const keys = new Set([...Object.keys(factors[p] ?? {}), ...Object.keys(factors[q] ?? {})])\n return [...keys].every((key) => key === factor || factors[p]?.[key] === factors[q]?.[key])\n}\n\nfunction sliceOf(ctx: Context, caseId: string): string | undefined {\n const slices = ctx.options.slices\n return slices ? (slices[caseId] ?? UNLABELLED_SLICE) : undefined\n}\n\n/** Slices with the most common cases first, so the columns that carry evidence lead. */\nfunction sliceNames(ctx: Context): string[] {\n if (!ctx.options.slices) return []\n const counts = new Map<string, number>()\n for (const caseId of ctx.common) {\n const slice = sliceOf(ctx, caseId)!\n counts.set(slice, (counts.get(slice) ?? 0) + 1)\n }\n return [...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([slice]) => slice)\n}\n\nfunction sliceCells(ctx: Context, slices: readonly string[]): ProfileMatrixSliceCell[] {\n return ctx.panel.flatMap((profileId) =>\n slices.map((slice) => {\n const cases = ctx.common.filter((caseId) => sliceOf(ctx, caseId) === slice)\n const scores = cases.map((caseId) => scoreOf(ctx, profileId, caseId))\n return { profileId, slice, n: scores.length, quality: scores.length ? mean(scores) : null }\n }),\n )\n}\n\nfunction errorOverlap(ctx: Context): Pick<ProfileMatrixAnalysis, 'errorOverlap' | 'oracle'> {\n const n = ctx.common.length\n const pairs: ProfileMatrixErrorOverlap[] = []\n ctx.panel.forEach((a, index) => {\n for (const b of ctx.panel.slice(index + 1)) {\n const right = ctx.common.map((c) => [correct(ctx, a, c), correct(ctx, b, c)] as const)\n pairs.push({\n a,\n b,\n bothWrong: n ? right.filter(([x, y]) => !x && !y).length / n : 0,\n disagree: n ? right.filter(([x, y]) => x !== y).length / n : 0,\n })\n }\n })\n const solved = ctx.common.filter((c) => ctx.panel.some((p) => correct(ctx, p, c))).length\n return { errorOverlap: pairs, oracle: n ? solved / n : null }\n}\n\nfunction difficulty(ctx: Context): ProfileMatrixCaseDifficulty[] {\n return ctx.common\n .map((caseId) => {\n const solved = ctx.panel.filter((p) => correct(ctx, p, caseId)).length\n const slice = sliceOf(ctx, caseId)\n return {\n caseId,\n ...(slice === undefined ? {} : { slice }),\n solved,\n scored: ctx.panel.length,\n share: solved / ctx.panel.length,\n }\n })\n .sort((a, b) => a.share - b.share || a.caseId.localeCompare(b.caseId))\n}\n\nfunction calibration(ctx: Context): ProfileMatrixCalibration[] {\n const probabilityOf = ctx.options.probabilityOf\n if (!probabilityOf) return []\n return ctx.profileIds.flatMap((profileId) => {\n const pairs = ctx.recordsByProfile.get(profileId)!.flatMap((record) => {\n const score = runTaskScore(record)\n const probability = probabilityOf(record)\n if (score === undefined || probability === undefined) return []\n if (!(probability >= 0 && probability <= 1)) {\n throw new ValidationError(\n `profile matrix: profile '${profileId}' returned probability ${probability} outside [0, 1]`,\n )\n }\n return [{ evalScore: probability, outcome: score >= ctx.rule.passScore ? 1 : 0 }]\n })\n const report = calibrationFromPairs(pairs, 'probability', 'correct', {\n bins: 10,\n range: { lo: 0, hi: 1 },\n })\n if (report === null) return []\n return [\n { profileId, n: report.n, ece: report.ece, brier: brierScore(pairs), bins: report.bins },\n ]\n })\n}\n\nfunction power(\n ctx: Context,\n panel: readonly ProfileMatrixProfileStats[],\n): ProfileMatrixPower | null {\n const baselineScores = ctx.scores.get(ctx.options.baseline)!\n const discordances = panel\n .filter((stats) => stats.profileId !== ctx.options.baseline)\n .map(\n (stats) =>\n pairProfiles(ctx.scores.get(stats.profileId)!, baselineScores, ctx.rule, ctx.common)\n ?.discordance,\n )\n .filter((value) => value !== undefined)\n .sort((a, b) => a - b)\n if (ctx.common.length < 2 || discordances.length === 0) return null\n const discordance = discordances[Math.floor((discordances.length - 1) / 2)]!\n const sizes = new Map<string, number>()\n for (const caseId of ctx.common) {\n const cluster = ctx.rule.clusterOf(caseId)\n sizes.set(cluster, (sizes.get(cluster) ?? 0) + 1)\n }\n const clusterSizes = [...sizes.values()]\n // The observed discordance is the noise floor: half of it wins and half of\n // it loses under no effect, and an effect adds wins on top of it.\n const powerAt = (effect: number) =>\n clusteredPower({\n clusterSizes,\n effects: [effect],\n minimumEffect: effect,\n seed: 1,\n trials: 400,\n resamples: 800,\n confidence: ctx.rule.level,\n alpha: 1 - ctx.rule.level,\n targetPower: TARGET_POWER,\n baseWinRate: discordance / 2,\n baseLossRate: discordance / 2,\n })\n const largest = powerAt(1)\n let detectable: number | null = null\n if (largest.powerAtMinimumEffect >= TARGET_POWER) {\n let [low, high] = [0, 1]\n for (let step = 0; step < 7; step++) {\n const middle = (low + high) / 2\n if (powerAt(middle).powerAtMinimumEffect >= TARGET_POWER) high = middle\n else low = middle\n }\n detectable = high\n }\n return {\n n: ctx.common.length,\n clusters: clusterSizes.length,\n discordance,\n detectable,\n certifiable: largest.signFlipFloor.certifiableAtAlpha,\n minClusters: largest.signFlipFloor.minClustersForAlpha,\n }\n}\n","/**\n * The profile-matrix decision page: one self-contained HTML string (inline\n * SVG and CSS, no network, light and dark) rendered from\n * `analyzeProfileMatrix`, so the page shows exactly the numbers a caller reads.\n */\n\nimport { escapeHtml as esc } from '../../reporting-html'\nimport {\n analyzeProfileMatrix,\n intervalSide,\n isRaceResult,\n type ProfileMatrixAnalysis,\n type ProfileMatrixAxisSummary,\n type ProfileMatrixCostAxis,\n type ProfileMatrixFactorEffect,\n type ProfileMatrixInterval,\n type ProfileMatrixPairedDifference,\n type ProfileMatrixPairwiseShare,\n type ProfileMatrixProfileStats,\n type ProfileMatrixReportOptions,\n type ProfileMatrixVerdict,\n} from './profile-matrix-analysis'\nimport type { ProfileMatrixRaceResult } from './race-profile-matrix'\n\n/** Render the decision page for a profile matrix or a race over one. */\nexport function renderProfileMatrixReport(options: ProfileMatrixReportOptions): string {\n const a = analyzeProfileMatrix(options)\n const race = options.race ?? (isRaceResult(options.source) ? options.source : undefined)\n const sections = [\n section('Frontier', frontier(a)),\n section('Profiles', profileTable(a)),\n ...(a.profiles.some((p) => !p.panel) ? [section('Partial coverage', partialTable(a))] : []),\n section('Run-to-run stability', stability(a)),\n section('Factor main effects', factorTable(a)),\n section('Slices', sliceHeatmap(a)),\n section('Error overlap', overlap(a)),\n section('Item difficulty', difficulty(a)),\n section('Calibration', calibration(a)),\n section('Power', `<p>${powerSentence(a)}</p>`),\n ...(race ? [section('Race', raceSection(race))] : []),\n ]\n return [\n '<!doctype html>',\n '<html lang=\"en\">',\n '<head>',\n '<meta charset=\"utf-8\">',\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">',\n `<title>${esc(a.title)}</title>`,\n `<meta name=\"description\" content=\"${esc(description(a))}\">`,\n `<style>${STYLE}</style>`,\n '</head>',\n '<body><main>',\n `<h1>${esc(a.title)}</h1>`,\n `<div class=\"decision\">${decision(a, race)}</div>`,\n ...sections,\n '</main></body></html>',\n ].join('\\n')\n}\n\nconst STYLE = `\n:root{color-scheme:light;--surface:#fcfcfb;--panel:#ffffff;--border:#e4e3de;--grid:#ecebe7;\n--text:#0b0b0b;--text-2:#52514e;--text-3:#7a7974;--accent:#2a78d6;--base:#eb6834;--better:#2a78d6;\n--worse:#e34948;--flat:#9b9a95;--seq:#1c5cab;--seq-2:#eb6834;--on-seq:#ffffff;--thin:#efeeea}\n@media (prefers-color-scheme:dark){:root:not([data-theme=\"light\"]){color-scheme:dark;--surface:#1a1a19;\n--panel:#222221;--border:#383835;--grid:#2c2c2a;--text:#f0efec;--text-2:#c3c2b7;--text-3:#8f8e86;\n--accent:#3987e5;--base:#d95926;--better:#3987e5;--worse:#e66767;--flat:#77766f;--seq:#6da7ec;\n--seq-2:#d95926;--on-seq:#0b0b0b;--thin:#2a2a28}}\n:root[data-theme=\"dark\"]{color-scheme:dark;--surface:#1a1a19;--panel:#222221;--border:#383835;\n--grid:#2c2c2a;--text:#f0efec;--text-2:#c3c2b7;--text-3:#8f8e86;--accent:#3987e5;--base:#d95926;\n--better:#3987e5;--worse:#e66767;--flat:#77766f;--seq:#6da7ec;--seq-2:#d95926;--on-seq:#0b0b0b;--thin:#2a2a28}\n*{box-sizing:border-box}\nbody{margin:0;background:var(--surface);color:var(--text);\nfont:15px/1.5 ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",sans-serif}\nmain{max-width:1120px;margin:0 auto;padding:32px 16px 64px}\nh1{font-size:28px;line-height:1.2;margin:0 0 16px}\nh2{font-size:19px;margin:40px 0 8px;padding-top:20px;border-top:1px solid var(--border)}\np{margin:8px 0}.muted{color:var(--text-3)}.note{color:var(--text-2);font-size:13px}\n.decision{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:12px 16px}\n.decision p{margin:6px 0}\n.scroll{overflow-x:auto;margin:12px 0}\ntable{border-collapse:collapse;font-size:13px;font-variant-numeric:tabular-nums}\nth,td{padding:6px 8px;border-bottom:1px solid var(--border);text-align:right;white-space:nowrap}\nth{color:var(--text-2);font-weight:600}th:first-child,td:first-child{text-align:left}\ntd .sub{display:block;color:var(--text-3);font-size:11px}\ntd.cell{text-align:center;min-width:64px}td.cell .sub{color:inherit;opacity:.75}\ntd.tight{min-width:40px;padding:6px 3px}td.thin{background:var(--thin);color:var(--text-3)}\ntd.diag{color:var(--text-3)}\n.charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,460px),1fr));gap:16px}\nfigure{margin:12px 0;background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:8px}\nfigcaption{font-size:12px;color:var(--text-2);padding:4px 6px}\nsvg{display:block;width:100%;height:auto}svg text{fill:var(--text-2);font-size:11px}\nsvg .title{fill:var(--text);font-size:12px;font-weight:600}\n.grid{stroke:var(--grid);stroke-width:1}.zero{stroke:var(--text-3);stroke-width:1}\n.whisker{stroke:var(--flat);stroke-width:1.5;stroke-opacity:.45}\n.leader{stroke:var(--text-2);stroke-width:.75;stroke-opacity:.6}.step{fill:none;stroke:var(--accent);stroke-width:2;stroke-dasharray:4 3}\n.pt{fill:var(--flat);stroke:var(--panel);stroke-width:2}.pt.front{fill:var(--accent)}\n.ring{fill:none;stroke:var(--base);stroke-width:2}.pt:hover{stroke:var(--text)}\n.forest{width:120px;height:16px;display:inline-block;vertical-align:middle}\n.ci{stroke-width:2}.ci.up,.up{stroke:var(--better);fill:var(--better)}\n.ci.down,.down{stroke:var(--worse);fill:var(--worse)}.ci.flat,.flat{stroke:var(--flat);fill:var(--flat)}\n.ci.cand{stroke-dasharray:3 2}circle.cand{fill:var(--panel);stroke-width:1.5}\n.bar{fill:var(--accent)}.bar:hover{fill:var(--text-2)}.diagonal{stroke:var(--text-3);stroke-dasharray:3 3}\n.cal{fill:none;stroke:var(--accent);stroke-width:2}.calpt{fill:var(--accent);stroke:var(--panel);stroke-width:2}\n.callout{border-left:3px solid var(--base);padding:6px 12px;background:var(--panel)}\n.small-multiples{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}\n`\n\nfunction section(title: string, body: string): string {\n return `<section><h2>${esc(title)}</h2>\\n${body}\\n</section>`\n}\n\nfunction num(value: number | null | undefined, digits = 3): string {\n return value === null || value === undefined || !Number.isFinite(value)\n ? '—'\n : value.toFixed(digits)\n}\n\nfunction signed(value: number | null | undefined, digits = 3): string {\n if (value === null || value === undefined || !Number.isFinite(value)) return '—'\n return `${value > 0 ? '+' : value < 0 ? '-' : '±'}${Math.abs(value).toFixed(digits)}`\n}\n\nfunction pct(value: number | null | undefined): string {\n return value === null || value === undefined ? '—' : `${Math.round(value * 100)}%`\n}\n\n/** An interval as text; a zero-width one says so, since it means no spread to measure, not certainty. */\nfunction bounds(i: { low: number | null; high: number | null }, f = signed): string {\n if (i.low === null || i.high === null) return 'no interval'\n return i.low === i.high ? 'no spread across clusters' : `[${f(i.low)}, ${f(i.high)}]`\n}\n\nfunction grouped(value: number): string {\n return Math.round(value)\n .toString()\n .replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n}\n\nfunction cost(axis: ProfileMatrixCostAxis, value: number | null): string {\n if (value === null) return '—'\n if (axis === 'usd') return `$${value < 0.1 ? value.toFixed(4) : value.toFixed(2)}`\n if (axis === 'tokens') return grouped(value)\n return `${value < 10 ? value.toFixed(1) : grouped(value)} s`\n}\n\nfunction pct1(value: number): string {\n return `${(value * 100).toFixed(1)}%`\n}\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`\n}\n\n/** One value, or the lowest to the highest of several. */\nfunction lowToHigh(values: readonly number[], f: (value: number) => string): string {\n const [low, high] = [Math.min(...values), Math.max(...values)]\n return f(low) === f(high) ? f(low) : `${f(low)} to ${f(high)}`\n}\n\nconst DIRECTION_WORD = { up: 'better', down: 'worse', flat: 'unresolved' } as const\n\nconst P_NOTE =\n 'Better and worse follow the interval. p is the exact sign-flip test over clusters, which ' +\n 'stays high when few clusters disagree even if the interval excludes zero: read both.'\n\nfunction common(a: ProfileMatrixAnalysis): string {\n return `${a.commonCases.length} common case${a.commonCases.length === 1 ? '' : 's'}`\n}\n\nfunction panelOf(a: ProfileMatrixAnalysis): ProfileMatrixProfileStats[] {\n return a.profiles.filter((p) => p.panel)\n}\n\nfunction withVerdict(a: ProfileMatrixAnalysis, verdict: ProfileMatrixVerdict) {\n return a.profiles.filter((p) => p.verdict === verdict)\n}\n\n/** The family the verdicts are adjusted over, as the page names it everywhere. */\nfunction familyName(a: ProfileMatrixAnalysis): string {\n const { alpha, comparisons } = a.family\n return `familywise ${pct(alpha)} (Holm) over ${plural(comparisons, 'comparison')}`\n}\n\nfunction description(a: ProfileMatrixAnalysis): string {\n const count = (verdict: ProfileMatrixVerdict) => withVerdict(a, verdict).length\n return (\n `${a.profiles.length} profiles against ${a.baseline}, each paired on the cases it shares with it: ` +\n `${count('better')} better and ${count('worse')} worse at ${familyName(a)}, ` +\n `${plural(count('candidate'), 'candidate')} whose nominal ${pct(a.level)} interval excludes zero, ` +\n `${count('unresolved')} unresolved; ${a.panelProfiles.length} panel profiles on ${common(a)}; ` +\n `${plural(a.stability.length, 'profile')} run more than once.`\n )\n}\n\n/**\n * A paired difference as two cells: its own n with clusters, then the estimate with a word, the\n * interval and p. The word is the nominal interval's side unless a standing replaces it.\n */\nfunction pairedCells(\n vs: ProfileMatrixPairedDifference | null | undefined,\n standing?: { word: string; sub: string },\n): [string, string] {\n if (!vs) return ['—', '—']\n return [\n `${vs.n}<span class=\"sub\">${vs.clusters} cluster${vs.clusters === 1 ? '' : 's'}</span>`,\n `${signed(vs.estimate)} ${standing?.word ?? DIRECTION_WORD[intervalSide(vs)]}` +\n `<span class=\"sub\">${bounds(vs)}, p ${num(vs.pValue)}${standing?.sub ?? ''}</span>`,\n ]\n}\n\n/** A profile's paired difference from the baseline with its family-adjusted verdict. */\nfunction verdictCells(p: ProfileMatrixProfileStats): [string, string] {\n const oneRun = p.verdict !== 'unresolved' && p.runs === 1\n return pairedCells(p.vsBaseline, {\n word: `${p.verdict}${oneRun ? ' <span class=\"muted\">1 run</span>' : ''}`,\n sub: `, Holm p ${num(p.adjustedPValue)}`,\n })\n}\n\nfunction verdictNote(a: ProfileMatrixAnalysis): string {\n return (\n `Better and worse are at ${familyName(a)}: the nominal ${pct(a.level)} interval excludes zero ` +\n `and the Holm-adjusted p (Holm p) is at most ${num(a.family.alpha, 2)}. A candidate’s interval ` +\n 'excludes zero but its Holm p does not pass, drawn hollow; a verdict other than unresolved that ' +\n 'rests on one run of the profile is marked 1 run. p is the sign-flip test over clusters, which ' +\n 'stays high when few clusters disagree even if the interval excludes zero.'\n )\n}\n\nfunction scoredCell(p: ProfileMatrixProfileStats): string {\n return `${p.casesScored} / ${p.casesAttempted}<span class=\"sub\">${pct(p.failureRate)} failed</span>`\n}\n\nfunction profileCell(a: ProfileMatrixAnalysis, p: ProfileMatrixProfileStats): string {\n const levels = Object.values(p.factors).join(' · ')\n const named = Object.entries(p.factors)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')\n return (\n `${esc(p.profileId)}${p.profileId === a.baseline ? ' <span class=\"muted\">(baseline)</span>' : ''}` +\n (levels ? `<span class=\"sub\" title=\"${esc(named)}\">${esc(levels)}</span>` : '')\n )\n}\n\nfunction panelRuleText(a: ProfileMatrixAnalysis): string {\n return a.panelRule === 'race-survivors'\n ? 'the race survivors'\n : `the profiles that scored at least ${pct(a.minCoverage)} of the baseline’s ${a.profiles[0]!.casesScored} cases`\n}\n\nfunction decision(a: ProfileMatrixAnalysis, race: ProfileMatrixRaceResult | undefined): string {\n const base = a.profiles[0]!\n const partial = a.profiles.length - a.panelProfiles.length\n const lines = [\n `Every profile is paired with the baseline <strong>${esc(a.baseline)}</strong> on the cases the two ` +\n `both scored. The panel (${a.panelProfiles.length} of ${a.profiles.length} profiles: ${panelRuleText(a)}) ` +\n `shares ${common(a)} in ${a.commonClusters} independent cluster${a.commonClusters === 1 ? '' : 's'}, ` +\n `where the baseline scores ${num(base.quality?.estimate)} ${base.quality ? bounds(base.quality, num) : ''}` +\n `${partial ? `; ${partial} partial-coverage profile${partial === 1 ? '' : 's'} sit outside the frontier` : ''}.`,\n ]\n if (a.panelProfiles.length === 1 && partial > 0) {\n lines.push(\n a.panelRule === 'race-survivors'\n ? 'The race left the baseline alone, so the frontier, overlap and power have nothing to compare.'\n : `No other profile scored ${pct(a.minCoverage)} of the baseline’s cases, so the frontier, overlap ` +\n 'and power have nothing to compare; a lower <code>minCoverage</code> widens the panel.',\n )\n }\n const list = (verdict: ProfileMatrixVerdict) => {\n const named = withVerdict(a, verdict).map((p) => {\n const vs = p.vsBaseline!\n return `${esc(p.profileId)} (${signed(vs.estimate)}, n ${vs.n}, ${plural(p.runs, 'run')})`\n })\n return named.length ? named.join(', ') : 'none'\n }\n lines.push(\n `Better than the baseline at ${familyName(a)}: ${list('better')}. Worse: ${list('worse')}. ` +\n `Candidates, whose nominal ${pct(a.level)} interval excludes zero but which do not pass the ` +\n `adjustment: ${list('candidate')}. Unresolved: ${withVerdict(a, 'unresolved').length}.`,\n familySentence(a),\n )\n for (const axis of a.axes.filter((x) => x.drawn)) {\n lines.push(`Pareto set on ${AXIS_NAME[axis.axis]}: ${axis.frontier.map(esc).join(', ')}.`)\n }\n const top = Math.max(...panelOf(a).map((p) => p.quality?.estimate ?? 0))\n const leaders = panelOf(a).filter((p) => p.quality?.estimate === top)\n if (a.oracle !== null && leaders.length > 0) {\n const named =\n leaders.length === 1\n ? esc(leaders[0]!.profileId)\n : `${esc(leaders[0]!.profileId)} and ${leaders.length - 1} tied`\n lines.push(\n `On the common cases, choosing the right panel profile per case would score ${num(a.oracle)}; the best single one ` +\n `(${named}) scores ${num(top)}.`,\n )\n }\n if (typeof a.power?.detectable === 'number') {\n lines.push(\n `Differences below about ${num(a.power.detectable, 2)} are beyond what this n resolves.`,\n )\n }\n if (race) {\n lines.push(\n `Raced: ${race.cellsRun} of ${race.plannedCells} planned cells run; leader ` +\n `<strong>${esc(race.leader)}</strong>. ${esc(race.selectionBias)}`,\n )\n }\n return lines.map((line) => `<p>${line}</p>`).join('\\n')\n}\n\n/** How many comparisons the family holds and what a candidate needs to pass it. */\nfunction familySentence(a: ProfileMatrixAnalysis): string {\n const { alpha, comparisons } = a.family\n if (comparisons === 0) {\n return 'No profile has a p-value against the baseline, so none can read as better or worse.'\n }\n return (\n `The family holds ${plural(comparisons, 'comparison')}, one per profile compared with the baseline, ` +\n `so Holm passes the smallest p only at ${num(alpha / comparisons, 4)} (${pct(alpha)} ÷ ${comparisons}) ` +\n 'or below; a candidate needs more cases or repeated runs before it reads as better or worse.'\n )\n}\n\nconst AXIS_NAME: Record<ProfileMatrixCostAxis, string> = {\n usd: 'dollars',\n tokens: 'tokens',\n seconds: 'latency',\n}\n\nconst AXIS_TITLE: Record<ProfileMatrixCostAxis, string> = {\n usd: 'Dollars per case',\n tokens: 'Tokens per case',\n seconds: 'Median seconds per case',\n}\n\nfunction ticks(min: number, max: number, count = 5): number[] {\n const span = max - min\n const raw = span / count\n const power = 10 ** Math.floor(Math.log10(raw))\n const step = [1, 2, 2.5, 5, 10].map((m) => m * power).find((s) => span / s <= count)!\n const out: number[] = []\n for (let v = Math.ceil(min / step) * step; v <= max + step * 1e-9; v += step) {\n out.push(Number(v.toFixed(10)))\n }\n return out\n}\n\nfunction extent(values: readonly number[], clamp?: readonly [number, number]): [number, number] {\n let low = Math.min(...values)\n let high = Math.max(...values)\n if (low === high) {\n low -= Math.abs(low) * 0.1 || 0.5\n high += Math.abs(high) * 0.1 || 0.5\n }\n const pad = (high - low) * 0.08\n low -= pad\n high += pad\n return clamp ? [Math.max(clamp[0], low), Math.min(clamp[1], high)] : [low, high]\n}\n\nfunction tickLabel(axis: ProfileMatrixCostAxis | 'quality', value: number): string {\n const short = (v: number) => Number(v.toPrecision(3)).toString()\n if (axis === 'tokens' && Math.abs(value) >= 1000) return `${short(value / 1000)}k`\n if (axis === 'usd') return `$${short(value)}`\n return short(value)\n}\n\nfunction frontier(a: ProfileMatrixAnalysis): string {\n const drawn = a.axes.filter((axis) => axis.drawn)\n const skipped = a.axes\n .filter((axis) => !axis.drawn)\n .map(\n (axis) => `<p class=\"note\">${esc(AXIS_TITLE[axis.axis])} not drawn: ${esc(axis.note)}.</p>`,\n )\n return [\n `<p class=\"note\">Panel profiles’ quality on the ${common(a)} against each cost; whiskers are ${pct(a.level)} intervals. ` +\n 'Filled blue points form the Pareto set (no other profile is both better and cheaper), joined ' +\n 'by the dashed staircase; the orange ring marks the baseline.</p>',\n `<div class=\"charts\">${drawn.map((axis) => scatter(a, axis)).join('')}</div>`,\n ...skipped,\n ].join('\\n')\n}\n\nfunction scatter(a: ProfileMatrixAnalysis, axis: ProfileMatrixAxisSummary): string {\n const [W, H, L, R, T, B] = [560, 330, 52, 16, 14, 46]\n const xOf = (p: ProfileMatrixProfileStats) =>\n axis.axis === 'seconds' ? p.latency!.p50 : p.costPerCase[axis.axis]!\n const points = panelOf(a).map((p) => ({ p, x: xOf(p), q: p.quality! }))\n const ys = points.flatMap(({ q }) => [q.estimate, q.low ?? q.estimate, q.high ?? q.estimate])\n const [x0, x1] = extent(points.map((pt) => pt.x))\n const [y0, y1] = extent(ys, ys.every((y) => y >= 0 && y <= 1) ? [0, 1] : undefined)\n const sx = (v: number) => L + ((v - x0) / (x1 - x0)) * (W - L - R)\n const sy = (v: number) => H - B - ((v - y0) / (y1 - y0)) * (H - T - B)\n const parts: string[] = []\n for (const t of ticks(y0, y1)) {\n parts.push(`<line class=\"grid\" x1=\"${L}\" x2=\"${W - R}\" y1=\"${sy(t)}\" y2=\"${sy(t)}\"/>`)\n parts.push(\n `<text x=\"${L - 6}\" y=\"${sy(t) + 4}\" text-anchor=\"end\">${tickLabel('quality', t)}</text>`,\n )\n }\n for (const t of ticks(x0, x1)) {\n parts.push(\n `<text x=\"${sx(t)}\" y=\"${H - B + 16}\" text-anchor=\"middle\">${tickLabel(axis.axis, t)}</text>`,\n )\n }\n const front = axis.frontier.map((id) => points.find((pt) => pt.p.profileId === id)!)\n if (front.length > 1) {\n const path = front\n .map((pt, i) =>\n i === 0 ? `M${sx(pt.x)} ${sy(pt.q.estimate)}` : `H${sx(pt.x)} V${sy(pt.q.estimate)}`,\n )\n .join(' ')\n parts.push(`<path class=\"step\" d=\"${path}\"/>`)\n }\n for (const { x, q } of points) {\n if (q.low === null || q.high === null) continue\n const cx = sx(x)\n parts.push(`<line class=\"whisker\" x1=\"${cx}\" x2=\"${cx}\" y1=\"${sy(q.low)}\" y2=\"${sy(q.high)}\"/>`)\n }\n // Every point is an obstacle, so a label never covers a mark.\n const placed: LabelBox[] = points.map(({ x, q }) => {\n const [cx, cy] = [sx(x), sy(q.estimate)]\n return [cx - 6, cx + 6, cy - 6, cy + 6]\n })\n for (const { p, x, q } of points) {\n const onFront = axis.frontier.includes(p.profileId)\n const [cx, cy] = [sx(x), sy(q.estimate)]\n const tip = `${p.profileId}: quality ${num(q.estimate)} ${bounds(q, num)}, ${cost(axis.axis, x)}`\n parts.push(\n `<circle class=\"pt${onFront ? ' front' : ''}\" cx=\"${cx}\" cy=\"${cy}\" r=\"5.5\">` +\n `<title>${esc(tip)}</title></circle>`,\n )\n if (p.profileId === a.baseline) parts.push(`<circle class=\"ring\" cx=\"${cx}\" cy=\"${cy}\" r=\"9\"/>`)\n if (onFront || p.profileId === a.baseline) {\n const at = placeLabel(cx, cy, p.profileId, placed, [L, W - R, T, H - B])\n if (Math.abs(at.y - cy) > 16) {\n const edge = at.anchor === 'start' ? at.x - 2 : at.x + 2\n parts.push(`<line class=\"leader\" x1=\"${cx}\" y1=\"${cy}\" x2=\"${edge}\" y2=\"${at.y - 4}\"/>`)\n }\n parts.push(\n `<text x=\"${at.x}\" y=\"${at.y}\" text-anchor=\"${at.anchor}\">${esc(p.profileId)}</text>`,\n )\n }\n }\n parts.push(\n `<text class=\"title\" x=\"${(L + W - R) / 2}\" y=\"${H - 8}\" text-anchor=\"middle\">${AXIS_TITLE[axis.axis]}</text>`,\n )\n parts.push(\n `<text class=\"title\" transform=\"translate(14 ${(T + H - B) / 2}) rotate(-90)\" text-anchor=\"middle\">Quality</text>`,\n )\n const label = `Quality against ${AXIS_NAME[axis.axis]} for ${points.length} profiles`\n return (\n `<figure><svg viewBox=\"0 0 ${W} ${H}\" role=\"img\" aria-label=\"${esc(label)}\">${parts.join('')}</svg>` +\n `<figcaption>${esc(AXIS_TITLE[axis.axis])}: ${esc(axis.note)}.</figcaption></figure>`\n )\n}\n\ntype LabelBox = readonly [x0: number, x1: number, y0: number, y1: number]\n\n/**\n * Place a point label beside its point where it overlaps no label or point already placed and\n * stays inside the plot, trying right then left at widening vertical offsets across the plot's\n * height; a label set far from its point gets a leader line. Width is estimated from the 11px\n * label font.\n */\nfunction placeLabel(\n cx: number,\n cy: number,\n text: string,\n placed: LabelBox[],\n [left, right, top, bottom]: readonly [number, number, number, number],\n): { x: number; y: number; anchor: 'start' | 'end' } {\n const width = text.length * 6.2\n const offsets = Array.from({ length: 2 * Math.ceil((bottom - top) / 7) }, (_, k) =>\n k % 2 ? 8 + 7 * k : -(8 + 7 * k),\n )\n const candidates = offsets.flatMap((dy) =>\n (['start', 'end'] as const).map((anchor) => {\n const x = anchor === 'start' ? cx + 11 : cx - 11\n const box: LabelBox = [\n anchor === 'start' ? x : x - width,\n anchor === 'start' ? x + width : x,\n cy + dy - 10,\n cy + dy + 2,\n ]\n return { x, y: cy + dy, anchor, box }\n }),\n )\n const inside = ({ box }: (typeof candidates)[number]) =>\n box[0] >= left && box[1] <= right && box[2] >= top && box[3] <= bottom\n const free = ({ box }: (typeof candidates)[number]) =>\n placed.every((o) => box[1] <= o[0] || box[0] >= o[1] || box[3] <= o[2] || box[2] >= o[3])\n const at =\n candidates.find((c) => inside(c) && free(c)) ?? candidates.find(inside) ?? candidates[0]!\n placed.push(at.box)\n return at\n}\n\n/** An interval against zero; a candidate is drawn dashed and hollow. */\nfunction forest(\n i: ProfileMatrixInterval | null | undefined,\n span: number,\n candidate = false,\n): string {\n if (!i) return ''\n const W = 120\n const sx = (v: number) => Math.max(1, Math.min(W - 1, ((v + span) / (2 * span)) * W))\n const d = `${intervalSide(i)}${candidate ? ' cand' : ''}`\n const ci =\n i.low !== null && i.high !== null\n ? `<line class=\"ci ${d}\" x1=\"${sx(i.low)}\" x2=\"${sx(i.high)}\" y1=\"8\" y2=\"8\"/>`\n : ''\n return (\n `<svg class=\"forest\" viewBox=\"0 0 ${W} 16\" aria-hidden=\"true\">` +\n `<line class=\"zero\" x1=\"${W / 2}\" x2=\"${W / 2}\" y1=\"1\" y2=\"15\"/>${ci}` +\n `<circle class=\"${d}\" cx=\"${sx(i.estimate)}\" cy=\"8\" r=\"4\"/></svg>`\n )\n}\n\nfunction forestSpan(intervals: readonly (ProfileMatrixInterval | null | undefined)[]): number {\n const values = intervals.flatMap((i) => (i ? [i.estimate, i.low ?? 0, i.high ?? 0] : []))\n return Math.max(0.05, ...values.map(Math.abs)) * 1.05\n}\n\nfunction profileTable(a: ProfileMatrixAnalysis): string {\n const usd = a.axes.some((axis) => axis.axis === 'usd' && axis.drawn)\n const panel = panelOf(a)\n const span = forestSpan(a.profiles.map((p) => p.vsBaseline))\n const head = [\n 'Profile',\n 'Scored',\n 'Runs',\n `Quality [${pct(a.level)}]`,\n 'Paired n',\n 'Δ vs baseline',\n '',\n 'To resolve',\n 'Tokens / correct',\n ...(usd ? ['$ / correct'] : []),\n 'Seconds p50 · p90',\n ]\n const rows = panel.map((p) => {\n const cells = [\n profileCell(a, p),\n scoredCell(p),\n `${p.runs}`,\n p.quality\n ? `${num(p.quality.estimate)} <span class=\"sub\">${bounds(p.quality, num)}</span>`\n : '—',\n ...verdictCells(p),\n forest(p.vsBaseline, span, p.verdict === 'candidate'),\n resolveCell(p.vsBaseline),\n cost('tokens', p.costPerCorrect.tokens),\n ...(usd ? [cost('usd', p.costPerCorrect.usd)] : []),\n `${num(p.latency?.p50, 1)} · ${num(p.latency?.p90, 1)}`,\n ]\n return `<tr>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`\n })\n return [\n `<p class=\"note\">The panel: ${panelRuleText(a)}. Scored is each profile’s own cases with a score out of ` +\n 'those it attempted, with the share of attempts that failed beneath. Runs is how many times the profile ' +\n 'ran the cases; with several, a case scores its mean over them. ' +\n `Quality, tokens and seconds are on the ${common(a)}, so ` +\n `the panel compares like with like. Δ is paired with the baseline on every case the two both scored, ` +\n `so each row carries its own paired n and clusters. A case counts as correct at a score of ${a.passScore} or more. ` +\n 'To resolve is the number of paired cases a two-sided test needs for 80% power at the observed ' +\n 'difference and discordance (unclustered). Seconds are dispatch time where the cell recorded ' +\n `it. ${verdictNote(a)}</p>`,\n table(head, rows),\n ].join('\\n')\n}\n\nfunction resolveCell(vs: ProfileMatrixPairedDifference | undefined): string {\n return vs?.casesToResolve == null ? '—' : grouped(vs.casesToResolve)\n}\n\nfunction partialTable(a: ProfileMatrixAnalysis): string {\n const partial = a.profiles.filter((p) => !p.panel)\n const raced = partial.some((p) => p.droppedAtBatch !== undefined)\n const span = forestSpan(a.profiles.map((p) => p.vsBaseline))\n const head = [\n 'Profile',\n 'Scored',\n 'Runs',\n 'Coverage',\n `Own accuracy [${pct(a.level)}]`,\n 'Paired n',\n 'Δ vs baseline',\n '',\n 'To resolve',\n ...(raced ? ['Dropped after batch'] : []),\n ]\n const rows = partial.map((p) => {\n const cells = [\n profileCell(a, p),\n scoredCell(p),\n `${p.runs}`,\n pct(p.coverage),\n p.ownQuality\n ? `${num(p.ownQuality.estimate)} <span class=\"sub\">${bounds(p.ownQuality, num)}</span>`\n : '—',\n ...verdictCells(p),\n forest(p.vsBaseline, span, p.verdict === 'candidate'),\n resolveCell(p.vsBaseline),\n ...(raced ? [p.droppedAtBatch === undefined ? '—' : `${p.droppedAtBatch}`] : []),\n ]\n return `<tr>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`\n })\n const why =\n (a.panelRule === 'race-survivors'\n ? 'The race dropped these profiles, so they stopped running cases'\n : `These profiles scored fewer than ${pct(a.minCoverage)} of the baseline’s cases`) +\n '; in the frontier they would cut every common-set panel down to the cases they ran.'\n return [\n `<p class=\"note\">${why} Each is paired with the baseline on the cases the two both scored instead. ` +\n 'Coverage is the share of the baseline’s scored cases this profile also scored; own accuracy is on ' +\n 'its own cases, which can be easier or harder than the panel’s, so read Δ, not own accuracy, ' +\n 'against the panel. Runs and the verdict read as in the profiles table, in the same family.</p>',\n table(head, rows),\n ].join('\\n')\n}\n\nfunction shareCell(share: ProfileMatrixPairwiseShare | null): string {\n if (!share) return '—'\n const pairs =\n share.min === share.max\n ? ''\n : `<span class=\"sub\">pairs ${lowToHigh([share.min, share.max], pct1)}</span>`\n return `${pct1(share.mean)}${pairs}`\n}\n\n/** Each profile run more than once, and the reading rule its rerun noise gives at the panel's n. */\nfunction stability(a: ProfileMatrixAnalysis): string {\n if (a.stability.length === 0) {\n return (\n '<p class=\"note\">No profile was run more than once, so this page cannot measure rerun noise: ' +\n 'every difference above rests on one run of each profile and carries noise the page does not show.</p>'\n )\n }\n const answers = a.stability.some((s) => s.answerDisagreement !== null)\n const n = a.commonCases.length\n const head = [\n 'Profile',\n 'Runs',\n 'Cases',\n 'Quality per run',\n 'Spread',\n 'Correctness differs',\n ...(answers ? ['Answers differ'] : []),\n `Rerun margin at n ${n}`,\n ]\n const rows = a.stability.map((s) => {\n const cells = [\n profileCell(a, a.profiles.find((p) => p.profileId === s.profileId)!),\n `${s.runs}`,\n `${s.n}`,\n s.runQuality.map((r) => num(r.quality)).join(' · '),\n num(s.spread),\n shareCell(s.correctnessDisagreement),\n ...(answers ? [shareCell(s.answerDisagreement)] : []),\n s.rerunMargin === null ? '—' : `±${num(s.rerunMargin)}`,\n ]\n return `<tr>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`\n })\n const margins = a.stability.flatMap((s) => (s.rerunMargin === null ? [] : [s.rerunMargin]))\n const differ = a.stability.flatMap((s) =>\n s.correctnessDisagreement ? [s.correctnessDisagreement.mean] : [],\n )\n const rule =\n margins.length && differ.length\n ? `<p><strong>Reading rule:</strong> two runs of one profile disagree on correctness on ` +\n `${lowToHigh(differ, pct1)} of cases, so on the panel’s ${common(a)} two runs with nothing ` +\n `changed differ in quality by up to about ${lowToHigh(margins, (m) => num(m))} in ` +\n `${pct(a.level)} of reruns; a single-run difference from the baseline smaller than that can be ` +\n 'rerun noise alone.</p>'\n : '<p>The panel has no common case, so the page cannot turn this noise into a margin.</p>'\n return [\n '<p class=\"note\">Every profile run more than once, on the cases every one of its runs scored. ' +\n 'Quality per run is each run’s mean score there, in run order, and spread is the highest minus the ' +\n 'lowest. Correctness differs is the share of those cases one run got right and the other did not' +\n (answers ? '; answers differ, the share where the two runs gave different answers' : '') +\n '; each is the mean over pairs of runs, with the range over pairs beneath. ' +\n (answers ? '' : 'Answers are not compared: pass <code>answerOf</code> to read them. ') +\n `Rerun margin is z·√(m/n) at the panel’s ${common(a)}, where m is the mean squared per-case score ` +\n 'difference between two runs (for right/wrong scores, the correctness disagreement) and each ' +\n 'case’s change is taken as independent.</p>',\n table(head, rows),\n rule,\n ].join('\\n')\n}\n\nfunction table(head: readonly string[], rows: readonly string[]): string {\n return (\n `<div class=\"scroll\"><table><thead><tr>${head.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead>` +\n `<tbody>${rows.join('\\n')}</tbody></table></div>`\n )\n}\n\nfunction pairCases({ pairCases: range }: ProfileMatrixFactorEffect): string {\n if (!range) return '—'\n return range.min === range.max ? `${range.min}` : `${range.min}–${range.max}`\n}\n\nfunction factorTable(a: ProfileMatrixAnalysis): string {\n if (a.factorEffects.length === 0) return '<p class=\"note\">No factor levels were given.</p>'\n const span = forestSpan(a.factorEffects.map((e) => e.effect))\n const rows = a.factorEffects.map((e) =>\n [\n `<tr><td>${esc(e.factor)}</td>`,\n `<td>${esc(e.level)} <span class=\"muted\">vs ${esc(e.reference)}</span></td>`,\n `<td>${e.matchedPairs}</td>`,\n `<td>${pairCases(e)}</td>`,\n e.effect\n ? `<td>${signed(e.effect.estimate)} ${DIRECTION_WORD[intervalSide(e.effect)]}` +\n `<span class=\"sub\">${bounds(e.effect)}, p ${num(e.pValue)}, n ${e.n}</span></td>`\n : `<td class=\"muted\">${e.matchedPairs ? 'no case scored by both sides of a pair' : 'confounded: no profile pair differs only here'}</td>`,\n `<td>${forest(e.effect, span)}</td></tr>`,\n ].join(''),\n )\n return [\n '<p class=\"note\">The effect of moving one factor from the reference level, all else equal. Each ' +\n 'matched pair (two profiles that differ only in that factor) is compared on the cases it shares; ' +\n 'the effect is the mean, over the cases any pair shares, of the pairs’ difference on that case, ' +\n `with a clustered ${pct(a.level)} interval. Pair cases is the fewest and most cases one pair shares. ${P_NOTE}</p>`,\n table(['Factor', 'Level', 'Matched pairs', 'Pair cases', 'Effect', ''], rows),\n ].join('\\n')\n}\n\nfunction shade(value: number | null, variable: '--seq' | '--seq-2'): string {\n if (value === null) return ''\n const share = Math.round(Math.max(0, Math.min(1, value)) * 85)\n const ink = share > 50 ? 'color:var(--on-seq);' : ''\n return ` style=\"${ink}background:color-mix(in oklab,var(${variable}) ${share}%,var(--panel))\"`\n}\n\nfunction sliceHeatmap(a: ProfileMatrixAnalysis): string {\n if (a.slices.length === 0) return '<p class=\"note\">No slices were given.</p>'\n const rows = panelOf(a).map((p) => {\n const cells = a.slices.map((slice) => {\n const cell = a.sliceCells.find((c) => c.profileId === p.profileId && c.slice === slice)!\n const tip = `${p.profileId} on ${slice}: ${num(cell.quality)} over ${cell.n} cases`\n if (cell.n === 0) return `<td class=\"cell thin\" title=\"${esc(tip)}\"></td>`\n if (cell.n < 5) {\n return `<td class=\"cell thin\" title=\"${esc(tip)}\">${num(cell.quality, 2)}<span class=\"sub\">n ${cell.n}</span></td>`\n }\n return `<td class=\"cell\"${shade(cell.quality, '--seq')} title=\"${esc(tip)}\">${num(cell.quality, 2)}<span class=\"sub\">n ${cell.n}</span></td>`\n })\n return `<tr><td>${esc(p.profileId)}</td>${cells.join('')}</tr>`\n })\n return [\n `<p class=\"note\">Each panel profile’s mean score on the ${common(a)} in each slice, the largest slice ` +\n 'first. Cells with fewer than five cases are greyed: too few to read.</p>',\n table(['Profile', ...a.slices], rows),\n ].join('\\n')\n}\n\nfunction overlap(a: ProfileMatrixAnalysis): string {\n if (a.commonCases.length === 0)\n return '<p class=\"note\">No case was scored by every panel profile.</p>'\n const ids = a.panelProfiles\n const pair = (x: string, y: string) =>\n a.errorOverlap.find((o) => (o.a === x && o.b === y) || (o.a === y && o.b === x))!\n const rows = ids.map((row, i) => {\n const cells = ids.map((col, j) => {\n if (i === j) {\n const wrong = 1 - (a.profiles.find((p) => p.profileId === row)!.quality?.estimate ?? 0)\n return `<td class=\"cell tight diag\" title=\"${esc(row)} error rate\">${pct(wrong)}</td>`\n }\n const o = pair(row, col)\n const [value, variable, what] =\n j > i\n ? [o.bothWrong, '--seq-2' as const, 'both wrong']\n : [o.disagree, '--seq' as const, 'disagree']\n return `<td class=\"cell tight\"${shade(value, variable)} title=\"${esc(`${row} and ${col}: ${what} ${pct(value)}`)}\">${pct(value)}</td>`\n })\n return `<tr><td>${i + 1}. ${esc(row)}</td>${cells.join('')}</tr>`\n })\n const best = Math.max(...panelOf(a).map((p) => p.quality?.estimate ?? 0))\n return [\n `<p class=\"note\">Panel profiles on the ${common(a)}, numbered as in the rows. Above the diagonal (orange): share both profiles got wrong. ` +\n 'Below it (blue): share exactly one got right. The diagonal is each profile’s error rate. Profiles ' +\n 'that disagree often and rarely fail together are candidates to route between.</p>',\n table(['', ...ids.map((_, i) => `${i + 1}`)], rows),\n `<p>Oracle ceiling: ${num(a.oracle)} (a case counts when any panel profile got it right), against ${num(best)} for the best single one.</p>`,\n ].join('\\n')\n}\n\nfunction difficulty(a: ProfileMatrixAnalysis): string {\n const items = a.difficulty\n if (items.length === 0) return '<p class=\"note\">No case was scored.</p>'\n const [H, L, T, B] = [160, 36, 8, 22]\n const barW = Math.max(2, Math.min(14, Math.floor(860 / items.length)))\n const W = L + items.length * barW + 8\n const sy = (v: number) => H - B - v * (H - T - B)\n const parts = [0, 0.5, 1].map(\n (t) =>\n `<line class=\"grid\" x1=\"${L}\" x2=\"${W - 8}\" y1=\"${sy(t)}\" y2=\"${sy(t)}\"/>` +\n `<text x=\"${L - 6}\" y=\"${sy(t) + 4}\" text-anchor=\"end\">${t}</text>`,\n )\n items.forEach((item, i) => {\n const tip = `${item.caseId}${item.slice ? ` (${item.slice})` : ''}: ${item.solved} of ${item.scored} profiles right`\n const h = Math.max(1, item.share * (H - T - B))\n const y = sy(item.share) - (item.share === 0 ? 1 : 0)\n parts.push(\n `<rect class=\"bar\" x=\"${L + i * barW + 1}\" y=\"${y}\" width=\"${barW - 2}\" height=\"${h}\" rx=\"1\">` +\n `<title>${esc(tip)}</title></rect>`,\n )\n })\n parts.push(\n `<text x=\"${L}\" y=\"${H - 6}\">hardest</text><text x=\"${W - 8}\" y=\"${H - 6}\" text-anchor=\"end\">easiest</text>`,\n )\n const none = items.filter((item) => item.solved === 0)\n const all = items.filter((item) => item.solved === item.scored)\n const listed = none.slice(0, 24).map((item) => esc(item.caseId))\n const more = none.length > listed.length ? ` and ${none.length - listed.length} more` : ''\n return [\n `<p class=\"note\">Each bar is one of the ${common(a)}: the share of the ${a.panelProfiles.length} panel ` +\n 'profiles that got it right, hardest first.</p>',\n `<figure><svg viewBox=\"0 0 ${W} ${H}\" role=\"img\" aria-label=\"Share of panel profiles right per case\">${parts.join('')}</svg></figure>`,\n `<p>Of the ${common(a)}, ${none.length} were missed by every panel profile` +\n `${none.length ? ` (${listed.join(', ')}${more})` : ''} and ${all.length} were solved by every one. ` +\n 'Cases nobody solves are worth reading for label errors before they are read as hard.</p>',\n ].join('\\n')\n}\n\nfunction calibration(a: ProfileMatrixAnalysis): string {\n if (a.calibration.length === 0) {\n return '<p class=\"note\">No profile returned a probability (pass <code>probabilityOf</code> to read one).</p>'\n }\n const S = 200\n const pad = 26\n const sc = (v: number) => pad + v * (S - 2 * pad)\n const plots = a.calibration.map((c) => {\n const maxN = Math.max(...c.bins.map((b) => b.n))\n const pts = c.bins.map((b) => ({ x: sc(b.evalMean), y: S - sc(b.outcomeMean), b }))\n const line = pts.map((p, i) => `${i ? 'L' : 'M'}${p.x} ${p.y}`).join(' ')\n const dots = pts\n .map(\n (p) =>\n `<circle class=\"calpt\" cx=\"${p.x}\" cy=\"${p.y}\" r=\"${3 + 4 * Math.sqrt(p.b.n / maxN)}\">` +\n `<title>${esc(`forecast ${num(p.b.evalMean, 2)}, right ${num(p.b.outcomeMean, 2)}, n ${p.b.n}`)}</title></circle>`,\n )\n .join('')\n return (\n `<figure><svg viewBox=\"0 0 ${S} ${S}\" role=\"img\" aria-label=\"${esc(`Calibration of ${c.profileId}`)}\">` +\n `<line class=\"grid\" x1=\"${pad}\" x2=\"${S - pad}\" y1=\"${S - pad}\" y2=\"${S - pad}\"/>` +\n `<line class=\"diagonal\" x1=\"${sc(0)}\" y1=\"${S - sc(0)}\" x2=\"${sc(1)}\" y2=\"${S - sc(1)}\"/>` +\n `<path class=\"cal\" d=\"${line}\"/>${dots}` +\n `<text x=\"${pad}\" y=\"${S - 8}\">forecast</text><text x=\"4\" y=\"${pad - 8}\">right</text></svg>` +\n `<figcaption>${esc(c.profileId)}: n ${c.n}, ECE ${num(c.ece)}, Brier ${num(c.brier)}</figcaption></figure>`\n )\n })\n return [\n '<p class=\"note\">Forecast probability of being right against the share actually right, in ten bins; ' +\n 'the dashed diagonal is perfect calibration and dot area follows the bin count.</p>',\n `<div class=\"small-multiples\">${plots.join('')}</div>`,\n ].join('\\n')\n}\n\nfunction powerSentence(a: ProfileMatrixAnalysis): string {\n const p = a.power\n if (!p)\n return 'Power is not computed: it needs at least two common cases and one panel profile besides the baseline.'\n const base =\n `With ${p.n} common cases in ${p.clusters} independent cluster${p.clusters === 1 ? '' : 's'} and a ` +\n `median discordance of ${pct(p.discordance)} against the baseline, `\n const finding =\n p.detectable === null\n ? 'no paired difference up to 1.0 reaches 80% power at this n.'\n : `the smallest paired difference this design detects with 80% power is about ${num(p.detectable, 2)} ` +\n `(whole-cluster bootstrap, ${pct(a.level)} interval); a smaller difference in the table is not resolvable here.`\n const floor = p.certifiable\n ? ''\n : ` With ${p.clusters} clusters an exact sign-flip test cannot reach the ${pct(1 - a.level)} level at any effect; it needs at least ${p.minClusters}.`\n return base + finding + floor\n}\n\nfunction raceSection(race: ProfileMatrixRaceResult): string {\n const reason = {\n 'one-left': 'one profile was left',\n 'cell-budget': 'the next batch would have passed the cell budget',\n 'batches-ended': 'the batch list ended',\n }[race.stoppedBecause]\n const saved = race.plannedCells ? 1 - race.cellsRun / race.plannedCells : 0\n const log = race.log.flatMap((batch) =>\n batch.standings.map(\n (s) =>\n `<tr><td>${batch.batch}</td><td>${batch.casesSeen}</td><td>${esc(batch.leader)}</td>` +\n `<td>${esc(s.profileId)}</td><td>${s.n}</td><td>${signed(s.difference)}</td>` +\n `<td>${bounds(s)}<span class=\"sub\">p ${num(s.pValue)}, ${s.clusters} clusters</span></td><td>${s.dropped ? '<strong>dropped</strong>' : 'kept'}` +\n `${s.reason ? `<span class=\"sub\">${esc(s.reason)}</span>` : ''}</td></tr>`,\n ),\n )\n const final = race.final.rows.map(\n (row) =>\n `<tr><td>${esc(row.profileId)}${row.profileId === race.leader ? ' <span class=\"muted\">(leader)</span>' : ''}</td>` +\n `<td>${num(row.quality)}</td>${pairedCells(row.vsBaseline)\n .map((cell) => `<td>${cell}</td>`)\n .join('')}</tr>`,\n )\n return [\n `<p>Stopped because ${reason}, after ${race.casesRaced.length} cases: ${race.cellsRun} of ` +\n `${race.plannedCells} planned cells run (${pct(saved)} not spent). Survivors: ${race.survivors.map(esc).join(', ')}.</p>`,\n '<h3>Elimination log</h3>',\n table(\n [\n 'Batch',\n 'Cases seen',\n 'Leader',\n 'Profile',\n 'Paired n',\n 'Δ vs leader',\n 'Interval',\n 'Decision',\n ],\n log,\n ),\n `<h3>Final comparison on ${race.final.cases} cases every survivor scored</h3>`,\n table(['Profile', 'Quality', 'Paired n', 'Δ vs baseline, nominal'], final),\n `<p class=\"callout\">${esc(race.selectionBias)}</p>`,\n ].join('\\n')\n}\n","/**\n * `runProfileMatrix` — the missing keystone between `runAgentMatrix` and the\n * backend-integrity guard.\n *\n * The gap it closes: `runAgentMatrix` is a topology-opaque scheduler whose\n * cells return a bare `{ output, verdict, costUsd }` — no `tokenUsage`, not a\n * `RunRecord`. `assertRealBackend` / `summarizeBackendIntegrity` key on\n * `RunRecord.tokenUsage`, so they cannot run on a raw matrix result. Every\n * consumer therefore hand-writes the same bridge: fan a profile × scenario\n * cartesian, call dispatch, fabricate a `RunRecord` with token usage, thread it\n * back, run the integrity guard. That hand-rolled bridge is exactly the pile of\n * bespoke `eval:*` scripts the adoption skills keep trying (and failing) to\n * forbid.\n *\n * `runProfileMatrix` IS that bridge, once:\n *\n * - axis 3 (PROFILE) = `profiles: AgentProfile[]`\n * - axis 1 (PERSONA/SCENARIO) = `scenarios: Scenario[]` (each scenario carries\n * its persona; `personaOf` groups them for the `byPersona` pivot)\n * - the scoring axis = `judges`\n *\n * It runs `runCampaign` once per profile (reusing its seeds, reps, bootstrap\n * CIs, resumability, and the `LabeledScenarioStore` capture flywheel), maps\n * every cell to a validated `RunRecord` carrying the real `tokenUsage` the\n * dispatch committed via `ctx.cost.runPaidCall`, and runs `assertRealBackend`\n * BY CONSTRUCTION before returning — so a stub-backend run fails loudly instead\n * of reporting a clean 0/N leaderboard.\n *\n * Dispatch contract: a dispatch that calls an LLM MUST report usage via\n * `ctx.cost.runPaidCall({ execute, receipt })`.\n * The integrity guard judges each `RunRecord` by tokens alone, whatever cost\n * it states, because a run record carries no declaration that its call was\n * free; a matrix of free calls sets `integrity: 'off'`.\n */\n\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileHash,\n agentProfileId,\n agentProfileModelId,\n HARNESS_NATIVE_MODEL,\n harnessAxisOf,\n} from '../../agent-profile'\nimport { type AgentProfileCell, buildAgentProfileCell } from '../../agent-profile-cell'\nimport { mapConcurrent } from '../../concurrency'\nimport type { CostProvenance } from '../../cost-ledger'\nimport { AgentEvalError } from '../../errors'\nimport {\n assertRealBackend,\n type BackendIntegrityReport,\n summarizeBackendIntegrity,\n} from '../../integrity/backend-integrity'\nimport {\n modelHasSnapshot,\n modelSnapshot,\n type RunRecord,\n type RunSplitTag,\n runTaskScore,\n UNKNOWN_MODEL,\n validateRunRecord,\n} from '../../run-record'\nimport { mean, meanOrNull } from '../../statistics/mean'\nimport { computeManifestHash } from '../campaign-manifest'\nimport { cellReceiptModels } from '../cell-cache'\nimport { runCampaign } from '../run-campaign'\nimport { campaignCellToRunRecord } from '../run-record'\nimport type { CampaignStorage } from '../storage'\nimport type {\n CampaignCellResult,\n CampaignResult,\n DispatchContext,\n JudgeConfig,\n LabeledScenarioSource,\n LabeledScenarioStore,\n Scenario,\n} from '../types'\n\n/** Thrown when the matrix is misconfigured (no profiles, missing resolved model evidence,\n * etc.). Distinct from `BackendIntegrityError`,\n * which signals a stub backend at run time. */\nexport class ProfileMatrixError extends AgentEvalError {\n constructor(message: string) {\n super('profile_matrix', message)\n }\n}\n\n/** Dispatch for one cell: render `profile` against `scenario`, returning the\n * artifact the judges score. Run LLM work through `ctx.cost.runPaidCall` —\n * the integrity check depends on its receipt. */\nexport type ProfileDispatchFn<TScenario extends Scenario, TArtifact> = (\n profile: AgentProfile,\n scenario: TScenario,\n ctx: DispatchContext,\n) => Promise<TArtifact>\n\nexport interface RunProfileMatrixOptions<TScenario extends Scenario, TArtifact> {\n /** Axis 3 — the agent-under-test configurations. Each is one column. */\n profiles: AgentProfile[]\n /** Axis 1 — the persona/scenario corpus, run against every profile. */\n scenarios: TScenario[]\n /** Renders one (profile, scenario) cell. */\n dispatch: ProfileDispatchFn<TScenario, TArtifact>\n /** The scoring axis. */\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Where each profile's campaign writes artifacts/traces. One subdir per\n * profile. */\n runDir: string\n /** Git SHA the harness ran from — stamped onto every RunRecord (mandatory\n * for paper-grade records). */\n commitSha: string\n /** Additional stable identity for dispatch behavior that can change without\n * changing `commitSha`, such as a caller-owned executable or remote config. */\n dispatchRef?: string\n /** Logical experiment id shared across the whole matrix so the promotion\n * gate can pair profiles on matched scenarios. Default: a hash of the\n * profile + scenario ids. */\n experimentId?: string\n /** Which split these runs belong to. Default `'search'`. */\n splitTag?: RunSplitTag\n /** Replicates per (profile, scenario) cell for CI bands. Default 1. */\n reps?: number\n /** Campaign seed (per profile). Default 42. */\n seed?: number\n /**\n * Backend-integrity posture, enforced AFTER the matrix completes:\n * - `'assert'` (default) — throw `BackendIntegrityError` if the run was a\n * stub (and, with `allowMixed:false`, if it was mixed).\n * - `'warn'` — log the verdict but never throw.\n * - `'off'` — skip the guard entirely (only for offline/replay analysis).\n */\n integrity?: 'assert' | 'warn' | 'off'\n /** Forwarded to `assertRealBackend`. Default true (tolerate partial 429\n * cascades); set false for strict CI gates. */\n allowMixed?: boolean\n /** Max concurrent cells WITHIN each profile's campaign. Default 2. */\n maxConcurrency?: number\n /** Max profile campaigns in flight. Default 1. Each profile keeps its own\n * run directory and cost ceiling; raise this when those resources are independent. */\n maxProfileConcurrency?: number\n /** Cumulative USD cap per profile campaign. */\n costCeiling?: number\n /** Capture flywheel — forwarded to each campaign. */\n labeledStore?: LabeledScenarioStore | 'off'\n captureSource?: LabeledScenarioSource\n /** Storage backend. Default `fsCampaignStorage`. Pass\n * `inMemoryCampaignStorage()` for edge/CF-Worker/test runs. */\n storage?: CampaignStorage\n /** Test seam — override the wall clock. */\n now?: () => Date\n /** Optional persona key per scenario — drives the `byPersona` pivot. When\n * unset, `byPersona` is omitted. */\n personaOf?: (scenario: TScenario) => string\n /** Validate every produced RunRecord with `validateRunRecord` (fail-loud).\n * Default true — catches bad model snapshots and non-finite judge dims at\n * the boundary instead of letting them poison downstream analysis. */\n validate?: boolean\n /** Corpus-by-default: derive the trajectory text (`prompt` + `completion`)\n * for each cell from its artifact + scenario. When set, every produced\n * record carries `prompt`/`completion` (a `CorpusRecord`) so the run's\n * graded trajectories can be appended to the durable RL corpus with no\n * side-channel — `appendToCorpus(result.records, path)`. Fail-soft: a\n * throwing or undefined-returning extractor just omits the text. */\n corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n /**\n * Optional explicit row selection. The matrix identity remains based on the\n * complete profiles × scenarios × reps design; this invocation executes only\n * rows accepted by the predicate.\n */\n rowFilter?: (input: { profile: AgentProfile; scenario: TScenario; rep: number }) => boolean\n /** Stable matrix identity supplied by a persisted profile-matrix plan. */\n matrixId?: string\n /** Reuse cached failed cells. Normal matrix runs retry them by default. */\n reuseFailedCells?: boolean\n}\n\nexport interface ProfileSummary {\n profileId: string\n profileHash: string\n model: string\n /** RunRecords produced for this profile (= scenarios × reps). */\n records: number\n /** Mean across scored records, or null when the profile has no task labels. */\n meanComposite: number | null\n /** Total cost, or null when any call's cost was not captured. */\n totalCostUsd: number | null\n costProvenance: CostProvenance\n /** Per-profile integrity verdict — surfaces a single profile that ran stub\n * even when the matrix as a whole looks real. */\n integrity: BackendIntegrityReport\n}\n\nexport interface ScenarioRollup {\n meanComposite: number\n n: number\n}\n\nexport interface RunProfileMatrixResult<TArtifact, TScenario extends Scenario> {\n matrixId: string\n experimentId: string\n /** One RunRecord per (profile, scenario, rep) cell — the integrity-checked,\n * paper-grade output. Feed straight into `analyzeRuns`, `HeldOutGate`,\n * scorecards, the hosted wire format. */\n records: RunRecord[]\n byProfile: Record<string, ProfileSummary>\n byScenario: Record<string, ScenarioRollup>\n /** Present only when `personaOf` was supplied. */\n byPersona?: Record<string, ScenarioRollup>\n /** Whole-matrix integrity report (the one `integrity:'assert'` enforces). */\n integrity: BackendIntegrityReport\n /** The raw per-profile campaign results, keyed by profile id. */\n campaigns: Record<string, CampaignResult<TArtifact, TScenario>>\n}\n\n/**\n * Return the exact per-profile campaign identity used by `runProfileMatrix`.\n * Segmented profile matrices use this to validate durable cell caches before\n * finalization without dispatching a probe request.\n */\nexport function profileMatrixCampaignIdentity<TScenario extends Scenario, TArtifact>(opts: {\n profile: AgentProfile\n scenarios: TScenario[]\n judges?: JudgeConfig<TArtifact, TScenario>[]\n commitSha: string\n dispatchRef?: string\n splitTag?: RunSplitTag\n seed?: number\n reps?: number\n}): {\n profileHash: string\n profileId: string\n configHash: string\n dispatchRef: string\n manifestHash: string\n} {\n const seed = opts.seed ?? 42\n const splitTag = opts.splitTag ?? 'search'\n const reps = opts.reps ?? 1\n const profileHash = agentProfileHash(opts.profile)\n const profileId = agentProfileId(opts.profile)\n const configHash = sha({\n profile: profileHash,\n judges: (opts.judges ?? []).map((judge) => judge.name),\n seed,\n splitTag,\n dispatchRef: opts.dispatchRef ?? null,\n })\n const dispatchRef = `profile-matrix:${sha({\n commitSha: opts.commitSha,\n caller: opts.dispatchRef ?? null,\n profileId,\n profileHash,\n configHash,\n })}`\n const manifestHash = computeManifestHash({\n scenarios: opts.scenarios,\n judges: (opts.judges ?? []) as unknown as JudgeConfig<unknown>[],\n dispatchRef,\n seed,\n reps,\n })\n return { profileHash, profileId, configHash, dispatchRef, manifestHash }\n}\n\nfunction sanitize(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction sha(input: unknown): string {\n return createHash('sha256').update(JSON.stringify(input)).digest('hex')\n}\n\ninterface BuildRecordArgs<TScenario extends Scenario, TArtifact> {\n cell: CampaignCellResult<TArtifact>\n profile: AgentProfile\n profileHash: string\n configHash: string\n experimentId: string\n splitTag: RunSplitTag\n commitSha: string\n matrixId: string\n /** The (profile, harness, model, dimensions) identity of this cell — attached to\n * every record so results group by the canonical `groupRunsByAgentProfileCell`\n * (harness/model aware) instead of profileId alone. */\n agentProfileCell?: AgentProfileCell\n scenario?: TScenario\n corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n}\n\nfunction isUnknownModelOnly(reported: string[]): boolean {\n return reported.length > 0 && reported.every((model) => model === UNKNOWN_MODEL)\n}\n\n/** Resolve and validate every paid-call model used by one cell. */\nfunction recordModel(\n cell: CampaignCellResult<unknown>,\n profileId: string,\n declaredModel: string,\n): string {\n const reported = cellReceiptModels(cell)\n // A dispatch failure can happen before the provider returns any model\n // identity. Preserve that failed row with an explicit absence marker; a\n // failure must not be converted into a made-up snapshot or discarded.\n // When a settled receipt exists, retain and validate its real identity.\n if (cell.error !== undefined && (reported.length === 0 || isUnknownModelOnly(reported))) {\n return UNKNOWN_MODEL\n }\n if (modelHasSnapshot(declaredModel)) {\n for (const model of reported) {\n if (model !== declaredModel) {\n throw new ProfileMatrixError(\n `profile '${profileId}' paid-call model '${model}' for cell '${cell.cellId}' does not match its declared exact model '${declaredModel}'`,\n )\n }\n }\n return declaredModel\n }\n\n if (reported.length === 0) {\n throw new ProfileMatrixError(\n `profile '${profileId}' declared a moving model but its dispatch reported no resolved model for cell '${cell.cellId}' — return a snapshot-bearing model in the ctx.cost.runPaidCall receipt`,\n )\n }\n for (const model of reported) {\n if (!modelHasSnapshot(model)) {\n throw new ProfileMatrixError(\n `profile '${profileId}' resolved to model '${model}' for cell '${cell.cellId}', which lacks a snapshot version — pin it in the paid-call receipt`,\n )\n }\n if (declaredModel !== HARNESS_NATIVE_MODEL && !sameMovingModel(declaredModel, model)) {\n throw new ProfileMatrixError(\n `profile '${profileId}' declared model '${declaredModel}' but cell '${cell.cellId}' reported unrelated snapshot '${model}'`,\n )\n }\n }\n if (reported.length !== 1) {\n throw new ProfileMatrixError(\n `profile '${profileId}' cell '${cell.cellId}' reported multiple paid-call model snapshots: ${reported.join(', ')}`,\n )\n }\n return reported[0]!\n}\n\nfunction sameMovingModel(declared: string, resolved: string): boolean {\n const resolvedBase = modelSnapshot(resolved)?.name ?? resolved\n return (\n resolvedBase === declared ||\n resolvedBase.endsWith(`/${declared}`) ||\n declared.endsWith(`/${resolvedBase}`)\n )\n}\n\nfunction buildRunRecord<TScenario extends Scenario, TArtifact>(\n args: BuildRecordArgs<TScenario, TArtifact>,\n): RunRecord {\n const { cell, profile, profileHash, configHash, experimentId, splitTag, commitSha, matrixId } =\n args\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n // Every successful record pins a snapshot. When a profile intentionally\n // carries the provider-facing moving alias, the paid-call receipt supplies\n // the immutable identity used here. Failed rows use explicit unknown data.\n const model = recordModel(cell, profileId, declaredModel)\n const record = campaignCellToRunRecord(cell, {\n runId: `${matrixId}:${profileId}:${cell.cellId}`,\n experimentId,\n candidateId: profileId,\n model,\n promptHash: profileHash,\n configHash,\n commitSha,\n splitTag,\n agentProfile: args.agentProfileCell,\n }) as RunRecord & { prompt?: string; completion?: string }\n\n // Corpus-by-default: stamp the trajectory text onto the record (CorpusRecord\n // shape — the validator ignores the extra keys) so the run is dataset-able\n // with no side-channel. Fail-soft: a bad extractor never fails the run.\n if (args.corpusText && args.scenario) {\n try {\n const text = args.corpusText(cell.artifact, args.scenario)\n if (text && typeof text.prompt === 'string' && typeof text.completion === 'string') {\n record.prompt = text.prompt\n record.completion = text.completion\n }\n } catch {\n // extractor threw — omit trajectory text, keep the graded record.\n }\n }\n return record\n}\n\n/**\n * Profile × scenario matrix runner: fan N agent profiles across M scenarios, project each cell to a validated `RunRecord` with real token usage, and enforce the backend-integrity guard before returning.\n */\nexport async function runProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: RunProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<RunProfileMatrixResult<TArtifact, TScenario>> {\n if (opts.profiles.length === 0) throw new ProfileMatrixError('profiles must not be empty')\n if (opts.scenarios.length === 0) throw new ProfileMatrixError('scenarios must not be empty')\n\n const splitTag = opts.splitTag ?? 'search'\n const seed = opts.seed ?? 42\n const validate = opts.validate ?? true\n const integrityMode = opts.integrity ?? 'assert'\n const maxProfileConcurrency = opts.maxProfileConcurrency ?? 1\n const profileIds = opts.profiles.map(agentProfileId)\n if (opts.dispatchRef !== undefined && opts.dispatchRef.trim().length === 0) {\n throw new ProfileMatrixError('dispatchRef must be a non-empty string when provided')\n }\n const duplicateProfileIds = profileIds.filter((id, index) => profileIds.indexOf(id) !== index)\n if (duplicateProfileIds.length > 0) {\n throw new ProfileMatrixError(\n `duplicate agentProfileId values are not allowed: ${[...new Set(duplicateProfileIds)].join(', ')}`,\n )\n }\n const experimentId =\n opts.experimentId ??\n `pm_${sha({ profileIds, scenarios: opts.scenarios.map((s) => s.id) }).slice(0, 16)}`\n const derivedMatrixId = `mtx_${sha({\n experimentId,\n profileIds,\n seed,\n splitTag,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef ?? null,\n }).slice(0, 16)}`\n const matrixId = opts.matrixId ?? derivedMatrixId\n if (typeof matrixId !== 'string' || matrixId.trim().length === 0) {\n throw new ProfileMatrixError('matrixId must be a non-empty string when provided')\n }\n // Scenario lookup for the corpus-text extractor (records carry trajectory text).\n const scenarioById = new Map(opts.scenarios.map((s) => [s.id, s]))\n\n // Preflight: every profile must hash and every static record field must validate before spend.\n //\n // A moving provider alias or `HARNESS_NATIVE_MODEL` cannot be a durable record identity.\n // Probe it with a placeholder here so the remaining profile checks still run before spend;\n // every completed cell must later supply its actual snapshot in the paid-call receipt.\n for (const profile of opts.profiles) {\n const profileHash = agentProfileHash(profile)\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n const model = modelHasSnapshot(declaredModel)\n ? declaredModel\n : `${declaredModel}@runtime-resolved`\n try {\n validateRunRecord({\n runId: `${matrixId}:${profileId}:probe`,\n experimentId,\n candidateId: profileId,\n seed,\n model,\n promptHash: profileHash,\n configHash: profileHash,\n commitSha: opts.commitSha,\n wallMs: 0,\n costUsd: null,\n costProvenance: { kind: 'uncaptured', usd: null },\n tokenUsage: { input: 0, output: 0 },\n terminalOutcome: 'succeeded',\n outcome: { raw: { execution_error_count: 0 } },\n splitTag,\n scenarioId: 'recordability-probe',\n })\n } catch (err) {\n throw new ProfileMatrixError(\n `profile '${profileId}' is not recordable: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n\n const records: RunRecord[] = []\n const campaigns: Record<string, CampaignResult<TArtifact, TScenario>> = {}\n const byProfile: Record<string, ProfileSummary> = {}\n\n const columns = await mapConcurrent(\n opts.profiles,\n maxProfileConcurrency,\n async (profile, _index, signal) => {\n const identity = profileMatrixCampaignIdentity({\n profile,\n scenarios: opts.scenarios,\n judges: opts.judges,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef,\n splitTag,\n seed,\n reps: opts.reps,\n })\n const { profileHash, profileId, configHash, dispatchRef } = identity\n const declaredModel = agentProfileModelId(profile)\n\n // Bind the profile into a campaign dispatch. Name it so the campaign's\n // manifest hash is stable + distinct per profile.\n const dispatch = (scenario: TScenario, ctx: DispatchContext): Promise<TArtifact> =>\n opts.dispatch(profile, scenario, ctx)\n Object.defineProperty(dispatch, 'name', { value: `profile_${sanitize(profileId)}` })\n\n const campaign = await runCampaign<TScenario, TArtifact>({\n scenarios: opts.scenarios,\n dispatch,\n dispatchRef,\n signal,\n judges: opts.judges,\n seed,\n reps: opts.reps,\n maxConcurrency: opts.maxConcurrency,\n costCeiling: opts.costCeiling,\n cellFilter: opts.rowFilter\n ? ({ scenario, rep }) => opts.rowFilter?.({ profile, scenario, rep }) ?? false\n : undefined,\n reuseFailedCells: opts.reuseFailedCells,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n storage: opts.storage,\n now: opts.now,\n runDir: join(opts.runDir, sanitize(profileId)),\n })\n\n // The canonical (profile, harness, model) identity for every record in this\n // column, so results group by `groupRunsByAgentProfileCell` (harness/model\n // aware). Harness comes from the axis stamp `expandProfileAxes` left on the\n // profile; a profile that wasn't axis-expanded simply has no harness in its\n // cell (unchanged grouping). A moving model alias means the cell identity\n // must carry the resolved snapshot per cell (surfaced via\n // `cell.resolvedModels`), so the pivot groups by the model that actually ran and\n // the cell identity matches the RunRecord's pinned model.\n const axis = harnessAxisOf(profile)\n const buildCellIdentity = (cellModel?: string): Promise<AgentProfileCell> =>\n buildAgentProfileCell({\n profileId,\n sourceProfile: { kind: 'agent-interface-profile', hash: profileHash },\n ...(cellModel && cellModel !== UNKNOWN_MODEL ? { model: cellModel } : {}),\n ...(axis ? { harness: { id: axis.harness } } : {}),\n })\n // A profile with a pinned declared model builds its cell identity once and\n // shares it; a moving alias builds one per cell after resolution.\n const sharedCellIdentity = modelHasSnapshot(declaredModel)\n ? await buildCellIdentity(declaredModel)\n : undefined\n\n const profileRecords: RunRecord[] = []\n for (const cell of campaign.cells) {\n const cellModel = recordModel(cell, profileId, declaredModel)\n const agentProfileCell =\n cellModel === UNKNOWN_MODEL\n ? await buildCellIdentity()\n : (sharedCellIdentity ?? (await buildCellIdentity(cellModel)))\n const record = buildRunRecord({\n cell,\n profile,\n profileHash,\n configHash,\n experimentId,\n splitTag,\n commitSha: opts.commitSha,\n matrixId,\n agentProfileCell,\n scenario: scenarioById.get(cell.scenarioId),\n corpusText: opts.corpusText,\n })\n if (validate) validateRunRecord(record)\n profileRecords.push(record)\n }\n\n const recordedModels = [\n ...new Set(\n profileRecords\n .map((record) => record.model)\n .filter((model): model is string => model !== UNKNOWN_MODEL),\n ),\n ]\n if (recordedModels.length > 1) {\n throw new ProfileMatrixError(\n `profile '${profileId}' resolved to multiple model snapshots: ${recordedModels.join(', ')}`,\n )\n }\n\n const costProvenance = campaign.aggregates.cost.costProvenance\n const totalCostUsd = costProvenance.kind === 'uncaptured' ? null : costProvenance.usd\n return {\n profileId,\n campaign,\n records: profileRecords,\n summary: {\n profileId,\n profileHash,\n model: recordedModels[0] ?? UNKNOWN_MODEL,\n records: profileRecords.length,\n meanComposite: meanOrNull(\n profileRecords.map(scoreOf).filter((score): score is number => score !== undefined),\n ),\n totalCostUsd,\n costProvenance,\n integrity: summarizeBackendIntegrity(profileRecords),\n },\n }\n },\n )\n\n // Merge in caller order so concurrency cannot change output or report ordering.\n for (const column of columns) {\n campaigns[column.profileId] = column.campaign\n byProfile[column.profileId] = column.summary\n records.push(...column.records)\n }\n\n // Integrity by construction — the whole point of the primitive.\n const integrity = summarizeBackendIntegrity(records)\n if (integrityMode === 'assert') {\n assertRealBackend(records, { allowMixed: opts.allowMixed ?? true })\n } else if (integrityMode === 'warn' && integrity.verdict !== 'real') {\n // eslint-disable-next-line no-console\n console.warn(\n `[runProfileMatrix] backend integrity: ${integrity.verdict} — ${integrity.diagnosis}`,\n )\n }\n\n // Pivots.\n const byScenario = rollup(records, (r) => r.scenarioId)\n const byPersona = opts.personaOf\n ? rollupByPersona(records, opts.scenarios, opts.personaOf)\n : undefined\n\n return { matrixId, experimentId, records, byProfile, byScenario, byPersona, integrity, campaigns }\n}\n\n/** Score for a produced RunRecord, absent when the campaign cell was unscored.\n * Ungated (`runTaskScore` is raw) — a matrix pivot reports measured scores;\n * it is not a training input. */\nfunction scoreOf(r: RunRecord): number | undefined {\n return runTaskScore(r)\n}\n\nfunction rollup(\n records: RunRecord[],\n keyOf: (r: RunRecord) => string | undefined,\n): Record<string, ScenarioRollup> {\n const groups = new Map<string, number[]>()\n for (const r of records) {\n const key = keyOf(r)\n if (key === undefined) continue\n const score = scoreOf(r)\n if (score === undefined) continue\n const arr = groups.get(key) ?? []\n arr.push(score)\n groups.set(key, arr)\n }\n const out: Record<string, ScenarioRollup> = {}\n for (const [key, xs] of groups) out[key] = { meanComposite: mean(xs), n: xs.length }\n return out\n}\n\nfunction rollupByPersona<TScenario extends Scenario>(\n records: RunRecord[],\n scenarios: TScenario[],\n personaOf: (s: TScenario) => string,\n): Record<string, ScenarioRollup> {\n const personaByScenarioId = new Map<string, string>()\n for (const s of scenarios) personaByScenarioId.set(s.id, personaOf(s))\n return rollup(records, (r) => (r.scenarioId ? personaByScenarioId.get(r.scenarioId) : undefined))\n}\n","/**\n * Eval-owned execution for profile matrices whose external authorization is\n * shorter than the complete matrix.\n *\n * A plan freezes the complete profile × scenario × replicate design. A\n * segment claims an explicit, disjoint set of rows and uses the campaign cell\n * cache as the durable per-cell record. Finalization first checks that every\n * planned row has one claim and one valid record, then replays the ordinary\n * `runProfileMatrix` projection from those records without dispatching work.\n */\n\nimport { dirname, join } from 'node:path'\nimport { type AgentProfile, agentProfileHash, agentProfileId } from '../../agent-profile'\nimport { canonicalJson, contentHash } from '../../verdict-cache'\nimport { cellCachePath } from '../cell-schedule'\nimport { assertCampaignDesign, campaignScenarioIdentity } from '../coverage'\nimport { resolveRunDir } from '../run-dir'\nimport { campaignCellCostProvenance, projectCampaignCellQuality } from '../run-record'\nimport type { CampaignStorage } from '../storage'\nimport { fsCampaignStorage } from '../storage'\nimport type { CampaignCellResult, JudgeConfig, Scenario } from '../types'\nimport {\n type ProfileDispatchFn,\n ProfileMatrixError,\n profileMatrixCampaignIdentity,\n type RunProfileMatrixOptions,\n type RunProfileMatrixResult,\n runProfileMatrix,\n} from './run-profile-matrix'\n\nconst PLAN_FILE = 'profile-matrix-plan.json'\nconst SEGMENTS_FILE = 'profile-matrix-segments.jsonl'\n\nclass SegmentedProfileMatrixError extends ProfileMatrixError {\n constructor(message: string) {\n super(`segmented matrix: ${message}`)\n }\n}\n\nexport interface ProfileMatrixRow {\n rowId: string\n ordinal: number\n profileId: string\n scenarioId: string\n rep: number\n}\n\nexport interface ProfileMatrixPlan<TScenario extends Scenario, TArtifact> {\n readonly schemaVersion: 1\n readonly matrixId: string\n readonly experimentId: string\n readonly planDigest: `sha256:${string}`\n readonly profiles: readonly AgentProfile[]\n readonly scenarios: readonly TScenario[]\n readonly judges: readonly JudgeConfig<TArtifact, TScenario>[]\n readonly reps: number\n readonly seed: number\n readonly splitTag: NonNullable<RunProfileMatrixOptions<TScenario, TArtifact>['splitTag']>\n readonly commitSha: string\n /** Stable dispatch implementation/configuration identity used by cell caches. */\n readonly dispatchRef: string\n readonly integrity: NonNullable<RunProfileMatrixOptions<TScenario, TArtifact>['integrity']>\n readonly allowMixed: boolean\n readonly validate: boolean\n readonly personaOf?: (scenario: TScenario) => string\n readonly corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n readonly rows: readonly ProfileMatrixRow[]\n}\n\nexport interface CreateProfileMatrixPlanOptions<TScenario extends Scenario, TArtifact>\n extends Pick<\n RunProfileMatrixOptions<TScenario, TArtifact>,\n | 'profiles'\n | 'scenarios'\n | 'judges'\n | 'commitSha'\n | 'experimentId'\n | 'splitTag'\n | 'reps'\n | 'seed'\n | 'integrity'\n | 'allowMixed'\n | 'validate'\n | 'personaOf'\n | 'corpusText'\n > {\n /** Stable dispatch implementation/configuration identity used by cell caches. */\n dispatchRef: string\n}\n\nexport interface ProfileMatrixCoverage {\n expected: number\n present: number\n missing: string[]\n failed: string[]\n zeroScore: string[]\n}\n\nexport interface RunProfileMatrixSegmentOptions<TScenario extends Scenario, TArtifact> {\n plan: ProfileMatrixPlan<TScenario, TArtifact>\n /** Stable external grant or attempt identity. Reuse it to resume. */\n segmentId: string\n /** Explicit row ids from `plan.rows`; duplicate or unknown rows fail. */\n rows: readonly (string | ProfileMatrixRow)[]\n dispatch: ProfileDispatchFn<TScenario, TArtifact>\n runDir: string\n storage?: CampaignStorage\n maxConcurrency?: number\n maxProfileConcurrency?: number\n costCeiling?: number\n labeledStore?: RunProfileMatrixOptions<TScenario, TArtifact>['labeledStore']\n captureSource?: RunProfileMatrixOptions<TScenario, TArtifact>['captureSource']\n now?: () => Date\n}\n\nexport interface ProfileMatrixSegmentResult<TArtifact, TScenario extends Scenario> {\n segmentId: string\n rowIds: string[]\n matrix: RunProfileMatrixResult<TArtifact, TScenario>\n coverage: ProfileMatrixCoverage\n}\n\nexport interface FinalizeProfileMatrixOptions<TScenario extends Scenario, TArtifact> {\n plan: ProfileMatrixPlan<TScenario, TArtifact>\n runDir: string\n storage?: CampaignStorage\n maxConcurrency?: number\n maxProfileConcurrency?: number\n now?: () => Date\n}\n\nexport interface FinalizedProfileMatrixResult<TArtifact, TScenario extends Scenario>\n extends RunProfileMatrixResult<TArtifact, TScenario> {\n coverage: ProfileMatrixCoverage\n}\n\nexport function createProfileMatrixPlan<TScenario extends Scenario, TArtifact>(\n opts: CreateProfileMatrixPlanOptions<TScenario, TArtifact>,\n): ProfileMatrixPlan<TScenario, TArtifact> {\n if (!Array.isArray(opts.profiles) || opts.profiles.length === 0) {\n throw new SegmentedProfileMatrixError('profiles must not be empty')\n }\n if (!Array.isArray(opts.scenarios) || opts.scenarios.length === 0) {\n throw new SegmentedProfileMatrixError('scenarios must not be empty')\n }\n const reps = opts.reps ?? 1\n const seed = opts.seed ?? 42\n const splitTag = opts.splitTag ?? 'search'\n const integrity = opts.integrity ?? 'assert'\n const allowMixed = opts.allowMixed ?? true\n const validate = opts.validate ?? true\n if (typeof opts.commitSha !== 'string' || opts.commitSha.trim().length === 0) {\n throw new SegmentedProfileMatrixError('commitSha must be a non-empty string')\n }\n if (typeof opts.dispatchRef !== 'string' || opts.dispatchRef.trim().length === 0) {\n throw new SegmentedProfileMatrixError(\n 'dispatchRef must be a non-empty stable identity for segmented execution',\n )\n }\n assertCampaignDesign(opts.scenarios, reps)\n\n const profiles = [...opts.profiles]\n const scenarios = [...opts.scenarios]\n const judges = [...(opts.judges ?? [])]\n const profileIds = profiles.map(agentProfileId)\n const duplicateProfiles = profileIds.filter((id, index) => profileIds.indexOf(id) !== index)\n if (duplicateProfiles.length > 0) {\n throw new SegmentedProfileMatrixError(\n `duplicate profile ids: ${[...new Set(duplicateProfiles)].join(', ')}`,\n )\n }\n\n const experimentId =\n opts.experimentId ??\n `pm_${contentHash({ profileIds, scenarios: scenarios.map((scenario) => scenario.id) }).slice(0, 16)}`\n if (experimentId.trim().length === 0) {\n throw new SegmentedProfileMatrixError('experimentId must be non-empty')\n }\n\n const identityMaterial = {\n schema: 'tangle.profile-matrix-plan.v1',\n profiles: profiles.map((profile, index) => ({\n ordinal: index,\n id: profileIds[index],\n hash: `sha256:${agentProfileHash(profile)}`,\n profile,\n })),\n scenarios: scenarios.map((scenario, index) => ({\n ordinal: index,\n identity: campaignScenarioIdentity(scenario),\n scenario,\n })),\n judges: judges.map((judge) => ({\n name: judge.name,\n dimensions: judge.dimensions,\n judgeVersion: judge.judgeVersion ?? null,\n score: judge.score.toString(),\n appliesTo: judge.appliesTo?.toString() ?? null,\n })),\n reps,\n seed,\n splitTag,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef,\n experimentId,\n integrity,\n allowMixed,\n validate,\n personaOf: opts.personaOf?.toString() ?? null,\n corpusText: opts.corpusText?.toString() ?? null,\n }\n const planDigest = `sha256:${contentHash(identityMaterial)}` as const\n const matrixId = `pmx_${planDigest.slice('sha256:'.length, 'sha256:'.length + 24)}`\n const rows: ProfileMatrixRow[] = []\n const seenCellIds = new Set<string>()\n let ordinal = 0\n for (const profileId of profileIds) {\n for (const scenario of scenarios) {\n for (let rep = 0; rep < reps; rep += 1) {\n const cellId = `${scenario.id}:${rep}`\n if (seenCellIds.has(`${profileId}:${cellId}`)) {\n throw new SegmentedProfileMatrixError(\n `profile/scenario/rep cell id collision for '${profileId}:${cellId}'`,\n )\n }\n seenCellIds.add(`${profileId}:${cellId}`)\n rows.push({\n rowId: `row_${contentHash({ matrixId, profileId, scenarioId: scenario.id, rep }).slice(0, 24)}`,\n ordinal,\n profileId,\n scenarioId: scenario.id,\n rep,\n })\n ordinal += 1\n }\n }\n }\n\n return Object.freeze({\n schemaVersion: 1,\n matrixId,\n experimentId,\n planDigest,\n profiles: Object.freeze(profiles),\n scenarios: Object.freeze(scenarios),\n judges: Object.freeze(judges),\n reps,\n seed,\n splitTag,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef,\n integrity,\n allowMixed,\n validate,\n ...(opts.personaOf === undefined ? {} : { personaOf: opts.personaOf }),\n ...(opts.corpusText === undefined ? {} : { corpusText: opts.corpusText }),\n rows: Object.freeze(rows),\n }) as ProfileMatrixPlan<TScenario, TArtifact>\n}\n\nexport async function runProfileMatrixSegment<TScenario extends Scenario, TArtifact>(\n opts: RunProfileMatrixSegmentOptions<TScenario, TArtifact>,\n): Promise<ProfileMatrixSegmentResult<TArtifact, TScenario>> {\n const segmentId = requireIdentifier(opts.segmentId, 'segmentId')\n const storage = opts.storage ?? fsCampaignStorage()\n const runDir = resolveRunDir(opts.runDir)\n assertPlan(opts.plan)\n const selected = normalizeRows(opts.plan, opts.rows)\n ensureManifest(storage, runDir, manifestFor(opts.plan))\n claimSegment(storage, runDir, opts.plan, segmentId, selected)\n\n const selectedIds = new Set(selected.map((row) => row.rowId))\n const selectedProfileIds = new Set(selected.map((row) => row.profileId))\n const profiles = opts.plan.profiles.filter((profile) =>\n selectedProfileIds.has(agentProfileId(profile)),\n )\n\n const matrix = await runProfileMatrix<TScenario, TArtifact>({\n profiles,\n scenarios: [...opts.plan.scenarios],\n dispatch: opts.dispatch,\n judges: [...opts.plan.judges],\n runDir,\n commitSha: opts.plan.commitSha,\n dispatchRef: opts.plan.dispatchRef,\n experimentId: opts.plan.experimentId,\n matrixId: opts.plan.matrixId,\n splitTag: opts.plan.splitTag,\n reps: opts.plan.reps,\n seed: opts.plan.seed,\n integrity: 'off',\n allowMixed: opts.plan.allowMixed,\n maxConcurrency: opts.maxConcurrency,\n maxProfileConcurrency: opts.maxProfileConcurrency,\n costCeiling: opts.costCeiling,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n storage,\n now: opts.now,\n personaOf: opts.plan.personaOf,\n validate: opts.plan.validate,\n corpusText: opts.plan.corpusText,\n reuseFailedCells: false,\n rowFilter: ({ profile, scenario, rep }) =>\n selectedIds.has(rowIdFor(opts.plan, agentProfileId(profile), scenario.id, rep)),\n })\n\n persistSegmentCells(storage, runDir, matrix)\n const coverage = readCoverage(storage, runDir, opts.plan)\n return { segmentId, rowIds: selected.map((row) => row.rowId), matrix, coverage }\n}\n\nexport async function finalizeProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: FinalizeProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<FinalizedProfileMatrixResult<TArtifact, TScenario>> {\n const storage = opts.storage ?? fsCampaignStorage()\n const runDir = resolveRunDir(opts.runDir)\n assertPlan(opts.plan)\n ensureManifest(storage, runDir, manifestFor(opts.plan))\n const claims = readSegmentClaims(storage, runDir)\n assertCompleteClaims(opts.plan, claims)\n const coverage = readCoverage(storage, runDir, opts.plan)\n if (coverage.missing.length > 0) {\n throw new SegmentedProfileMatrixError(\n `cannot finalize with missing rows: ${coverage.missing.join(', ')}`,\n )\n }\n\n const matrix = await runProfileMatrix<TScenario, TArtifact>({\n profiles: [...opts.plan.profiles],\n scenarios: [...opts.plan.scenarios],\n dispatch: async () => {\n throw new SegmentedProfileMatrixError(\n 'finalization attempted to dispatch an uncached row; the persisted coverage changed during finalization',\n )\n },\n judges: [...opts.plan.judges],\n runDir,\n commitSha: opts.plan.commitSha,\n dispatchRef: opts.plan.dispatchRef,\n experimentId: opts.plan.experimentId,\n matrixId: opts.plan.matrixId,\n splitTag: opts.plan.splitTag,\n reps: opts.plan.reps,\n seed: opts.plan.seed,\n integrity: opts.plan.integrity,\n allowMixed: opts.plan.allowMixed,\n maxConcurrency: opts.maxConcurrency,\n maxProfileConcurrency: opts.maxProfileConcurrency,\n storage,\n now: opts.now,\n personaOf: opts.plan.personaOf,\n validate: opts.plan.validate,\n corpusText: opts.plan.corpusText,\n reuseFailedCells: true,\n })\n assertFinalRows(opts.plan, matrix)\n return { ...matrix, coverage }\n}\n\ninterface PersistedMatrixManifest {\n schemaVersion: 1\n matrixId: string\n experimentId: string\n planDigest: string\n profiles: Array<{ id: string; hash: string }>\n scenarios: Array<{ id: string; kind: string; scenarioDigest: string }>\n reps: number\n seed: number\n splitTag: string\n commitSha: string\n dispatchRef: string\n rows: ProfileMatrixRow[]\n}\n\ninterface SegmentClaim {\n schemaVersion: 1\n segmentId: string\n planDigest: string\n rowIds: string[]\n}\n\nfunction manifestFor<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n): PersistedMatrixManifest {\n return {\n schemaVersion: 1,\n matrixId: plan.matrixId,\n experimentId: plan.experimentId,\n planDigest: plan.planDigest,\n profiles: plan.profiles.map((profile) => ({\n id: agentProfileId(profile),\n hash: `sha256:${agentProfileHash(profile)}`,\n })),\n scenarios: plan.scenarios.map((scenario) => campaignScenarioIdentity(scenario)),\n reps: plan.reps,\n seed: plan.seed,\n splitTag: plan.splitTag,\n commitSha: plan.commitSha,\n dispatchRef: plan.dispatchRef,\n rows: [...plan.rows],\n }\n}\n\nfunction assertPlan<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n): void {\n const rebuilt = createProfileMatrixPlan({\n profiles: [...plan.profiles],\n scenarios: [...plan.scenarios],\n judges: [...plan.judges],\n commitSha: plan.commitSha,\n dispatchRef: plan.dispatchRef,\n experimentId: plan.experimentId,\n splitTag: plan.splitTag,\n reps: plan.reps,\n seed: plan.seed,\n integrity: plan.integrity,\n allowMixed: plan.allowMixed,\n validate: plan.validate,\n personaOf: plan.personaOf,\n corpusText: plan.corpusText,\n })\n if (\n rebuilt.planDigest !== plan.planDigest ||\n rebuilt.matrixId !== plan.matrixId ||\n canonicalJson(rebuilt.rows) !== canonicalJson(plan.rows)\n ) {\n throw new SegmentedProfileMatrixError('plan inputs changed after identity was created')\n }\n}\n\nfunction ensureManifest(\n storage: CampaignStorage,\n runDir: string,\n expected: PersistedMatrixManifest,\n): void {\n storage.ensureDir(runDir)\n const path = join(runDir, PLAN_FILE)\n const existing = storage.read(path)\n if (existing === undefined) {\n const content = `${canonicalJson(expected)}\\n`\n if (storage.append(path, content, 0) !== undefined) return\n }\n const persisted = storage.read(path)\n if (persisted === undefined) {\n throw new SegmentedProfileMatrixError('persisted plan is unreadable')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(persisted)\n } catch {\n throw new SegmentedProfileMatrixError('persisted plan is corrupt JSON')\n }\n if (canonicalJson(parsed) !== canonicalJson(expected)) {\n throw new SegmentedProfileMatrixError(\n 'persisted plan identity does not match the supplied inputs',\n )\n }\n}\n\nfunction normalizeRows<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n rows: readonly (string | ProfileMatrixRow)[],\n): ProfileMatrixRow[] {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new SegmentedProfileMatrixError('a segment must select at least one row')\n }\n const byId = new Map(plan.rows.map((row) => [row.rowId, row]))\n const selected: ProfileMatrixRow[] = []\n const seen = new Set<string>()\n for (const input of rows) {\n const rowId = typeof input === 'string' ? input : input?.rowId\n if (typeof rowId !== 'string' || rowId.length === 0) {\n throw new SegmentedProfileMatrixError('segment rows must contain row ids')\n }\n if (seen.has(rowId))\n throw new SegmentedProfileMatrixError(`duplicate row '${rowId}' in segment`)\n const row = byId.get(rowId)\n if (!row) throw new SegmentedProfileMatrixError(`row '${rowId}' is not declared by the plan`)\n if (typeof input !== 'string' && canonicalJson(input) !== canonicalJson(row)) {\n throw new SegmentedProfileMatrixError(`row '${rowId}' does not match the declared plan row`)\n }\n seen.add(rowId)\n selected.push(row)\n }\n return selected.sort((left, right) => left.ordinal - right.ordinal)\n}\n\nfunction claimSegment<TScenario extends Scenario, TArtifact>(\n storage: CampaignStorage,\n runDir: string,\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n segmentId: string,\n selected: readonly ProfileMatrixRow[],\n): void {\n const path = join(runDir, SEGMENTS_FILE)\n const expected = canonicalJson({\n schemaVersion: 1,\n segmentId,\n planDigest: plan.planDigest,\n rowIds: selected.map((row) => row.rowId).sort(),\n } satisfies SegmentClaim)\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const raw = storage.read(path) ?? ''\n const claims = parseSegmentClaims(raw, path)\n const existing = claims.find((claim) => claim.segmentId === segmentId)\n if (existing) {\n if (canonicalJson(existing) !== expected) {\n throw new SegmentedProfileMatrixError(\n `segment '${segmentId}' was resumed with different rows or plan identity`,\n )\n }\n return\n }\n const selectedIds = new Set(selected.map((row) => row.rowId))\n const overlap = claims.flatMap((claim) =>\n claim.rowIds\n .filter((rowId) => selectedIds.has(rowId))\n .map((rowId) => `${rowId} (${claim.segmentId})`),\n )\n if (overlap.length > 0) {\n throw new SegmentedProfileMatrixError(\n `segment rows overlap existing claims: ${overlap.join(', ')}`,\n )\n }\n const event = `${expected}\\n`\n const next = storage.append(path, event, byteLength(raw))\n if (next !== undefined) return\n }\n throw new SegmentedProfileMatrixError(\n `could not claim segment '${segmentId}' after concurrent updates`,\n )\n}\n\nfunction readSegmentClaims(storage: CampaignStorage, runDir: string): SegmentClaim[] {\n const path = join(runDir, SEGMENTS_FILE)\n const raw = storage.read(path)\n if (raw === undefined) return []\n return parseSegmentClaims(raw, path)\n}\n\nfunction parseSegmentClaims(raw: string, path: string): SegmentClaim[] {\n const claims: SegmentClaim[] = []\n const seenSegments = new Set<string>()\n const seenRows = new Map<string, string>()\n for (const [index, line] of raw.split('\\n').entries()) {\n if (line.trim() === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n throw new SegmentedProfileMatrixError(`segment registry is corrupt at ${path}:${index + 1}`)\n }\n if (canonicalJson(parsed) !== line) {\n throw new SegmentedProfileMatrixError(\n `segment registry is not canonical at ${path}:${index + 1}`,\n )\n }\n const claim = parsed as Partial<SegmentClaim>\n if (\n claim.schemaVersion !== 1 ||\n typeof claim.segmentId !== 'string' ||\n typeof claim.planDigest !== 'string' ||\n !Array.isArray(claim.rowIds) ||\n claim.rowIds.some((rowId) => typeof rowId !== 'string') ||\n new Set(claim.rowIds).size !== claim.rowIds.length\n ) {\n throw new SegmentedProfileMatrixError(\n `segment registry has an invalid claim at ${path}:${index + 1}`,\n )\n }\n if (seenSegments.has(claim.segmentId)) {\n throw new SegmentedProfileMatrixError(`segment registry repeats segment '${claim.segmentId}'`)\n }\n seenSegments.add(claim.segmentId)\n const normalized = {\n schemaVersion: 1 as const,\n segmentId: claim.segmentId,\n planDigest: claim.planDigest,\n rowIds: [...claim.rowIds].sort(),\n }\n for (const rowId of normalized.rowIds) {\n const owner = seenRows.get(rowId)\n if (owner) {\n throw new SegmentedProfileMatrixError(\n `segment registry overlaps row '${rowId}' between '${owner}' and '${normalized.segmentId}'`,\n )\n }\n seenRows.set(rowId, normalized.segmentId)\n }\n claims.push(normalized)\n }\n return claims\n}\n\nfunction assertCompleteClaims<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n claims: readonly SegmentClaim[],\n): void {\n const expected = new Set(plan.rows.map((row) => row.rowId))\n const claimed = new Set<string>()\n for (const claim of claims) {\n if (claim.planDigest !== plan.planDigest) {\n throw new SegmentedProfileMatrixError(\n `segment '${claim.segmentId}' belongs to a different plan identity`,\n )\n }\n for (const rowId of claim.rowIds) {\n if (!expected.has(rowId)) {\n throw new SegmentedProfileMatrixError(\n `segment '${claim.segmentId}' claims an undeclared row '${rowId}'`,\n )\n }\n claimed.add(rowId)\n }\n }\n const missingClaims = plan.rows.filter((row) => !claimed.has(row.rowId)).map((row) => row.rowId)\n if (missingClaims.length > 0) {\n throw new SegmentedProfileMatrixError(\n `cannot finalize until every row is claimed: ${missingClaims.join(', ')}`,\n )\n }\n}\n\nfunction persistSegmentCells<TArtifact, TScenario extends Scenario>(\n storage: CampaignStorage,\n runDir: string,\n matrix: RunProfileMatrixResult<TArtifact, TScenario>,\n): void {\n for (const [profileId, campaign] of Object.entries(matrix.campaigns)) {\n for (const cell of campaign.cells) {\n const path = cellCachePath(join(runDir, profileDirectory(profileId)), cell.cellId)\n storage.ensureDir(dirname(path))\n // Campaign caches already use JSON.stringify, which omits optional\n // undefined fields such as a successful cell's `error` property.\n storage.write(path, `${JSON.stringify(cell)}\\n`)\n }\n }\n}\n\nfunction readCoverage<TScenario extends Scenario, TArtifact>(\n storage: CampaignStorage,\n runDir: string,\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n): ProfileMatrixCoverage {\n const expectedManifestHashes = new Map<string, string>(\n plan.profiles.map((profile) => {\n const identity = profileMatrixCampaignIdentity({\n profile,\n scenarios: [...plan.scenarios],\n judges: [...plan.judges],\n commitSha: plan.commitSha,\n dispatchRef: plan.dispatchRef,\n splitTag: plan.splitTag,\n seed: plan.seed,\n reps: plan.reps,\n })\n return [identity.profileId, identity.manifestHash] as const\n }),\n )\n const missing: string[] = []\n const failed: string[] = []\n const zeroScore: string[] = []\n let present = 0\n for (const row of plan.rows) {\n const path = cellCachePath(\n join(runDir, profileDirectory(row.profileId)),\n `${row.scenarioId}:${row.rep}`,\n )\n const raw = storage.read(path)\n if (raw === undefined) {\n missing.push(row.rowId)\n continue\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new SegmentedProfileMatrixError(`cell '${row.rowId}' has corrupt JSON`)\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new SegmentedProfileMatrixError(`cell '${row.rowId}' has an invalid record shape`)\n }\n const cell = parsed as CampaignCellResult<TArtifact>\n if (\n cell.cellId !== `${row.scenarioId}:${row.rep}` ||\n cell.scenarioId !== row.scenarioId ||\n cell.rep !== row.rep ||\n cell.manifestHash !== expectedManifestHashes.get(row.profileId)\n ) {\n throw new SegmentedProfileMatrixError(\n `cell '${row.rowId}' has stale identity fields (manifest or row identity)`,\n )\n }\n try {\n campaignCellCostProvenance(cell)\n } catch (error) {\n throw new SegmentedProfileMatrixError(\n `cell '${row.rowId}' failed cost-record validation: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n present += 1\n if (cell.error !== undefined) {\n failed.push(row.rowId)\n continue\n }\n if (projectCampaignCellQuality(cell).score === 0) zeroScore.push(row.rowId)\n }\n return {\n expected: plan.rows.length,\n present,\n missing,\n failed,\n zeroScore,\n }\n}\n\nfunction assertFinalRows<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n matrix: RunProfileMatrixResult<TArtifact, TScenario>,\n): void {\n const expected = new Set(plan.rows.map((row) => `${row.profileId}:${row.scenarioId}:${row.rep}`))\n const seen = new Set<string>()\n for (const record of matrix.records) {\n const key = `${record.candidateId}:${record.scenarioId}:${record.outcome.raw.rep}`\n if (!expected.has(key) || seen.has(key)) {\n throw new SegmentedProfileMatrixError(\n `final matrix has an unexpected or duplicate row '${key}'`,\n )\n }\n seen.add(key)\n }\n if (seen.size !== expected.size) {\n throw new SegmentedProfileMatrixError(\n `final matrix returned ${seen.size}/${expected.size} declared rows`,\n )\n }\n}\n\nfunction rowIdFor<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n profileId: string,\n scenarioId: string,\n rep: number,\n): string {\n const row = plan.rows.find(\n (candidate) =>\n candidate.profileId === profileId &&\n candidate.scenarioId === scenarioId &&\n candidate.rep === rep,\n )\n if (!row)\n throw new SegmentedProfileMatrixError(`row is not declared: ${profileId}/${scenarioId}/${rep}`)\n return row.rowId\n}\n\nfunction profileDirectory(profileId: string): string {\n return profileId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction requireIdentifier(value: string, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new SegmentedProfileMatrixError(`${name} must be a non-empty string`)\n }\n return value\n}\n\nfunction byteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength\n}\n","/**\n * Race a profile matrix: run the surviving profiles on doubling case batches\n * and stop paying for a profile once it is clearly worse than the leader.\n *\n * The race is a sampling policy over a segmented plan. Each batch is one\n * `runProfileMatrixSegment` with a stable segment id, so a race interrupted\n * mid-batch resumes from the campaign cell cache and replays the same\n * decisions. Rows the race never ran stay unclaimed: running them later and\n * calling `finalizeProfileMatrix` completes the full matrix.\n */\n\nimport { ValidationError } from '../../errors'\nimport { assertRealBackend, summarizeBackendIntegrity } from '../../integrity/backend-integrity'\nimport type { RunRecord } from '../../run-record'\nimport { makeRng } from '../../statistics/internal'\nimport { mean } from '../../statistics/mean'\nimport type { Scenario } from '../types'\nimport {\n allPassFail,\n clusterResolver,\n type ProfileMatrixPairedDifference,\n type ProfilePairingRule,\n pairProfiles,\n scoresByProfile,\n} from './profile-matrix-analysis'\nimport {\n type ProfileMatrixPlan,\n type RunProfileMatrixSegmentOptions,\n runProfileMatrixSegment,\n} from './segmented-profile-matrix'\n\nexport interface RaceProfileMatrixOptions<TScenario extends Scenario, TArtifact>\n extends Omit<RunProfileMatrixSegmentOptions<TScenario, TArtifact>, 'segmentId' | 'rows'> {\n /** Profile id kept to the end whatever its standing; the final comparison is against it. */\n baseline: string\n /** Cases seen after each batch, strictly increasing. Default: `firstBatch`, doubling until every case is in. */\n batches?: readonly number[]\n /** Cases in the first batch when `batches` is not given. Default 8. */\n firstBatch?: number\n /** Most cells (one profile on one case and rep) the race may run; a batch that would pass it is not started. */\n cellBudget?: number\n /** Independent unit per case id; every raced case needs one. Default one unit per case. */\n clusters?: Readonly<Record<string, string>>\n /** Interval level of each elimination. Default 0.95. */\n level?: number\n /** `shuffled` (default) orders cases by a draw seeded with the plan seed; `plan` keeps the plan's order. */\n caseOrder?: 'shuffled' | 'plan'\n}\n\nexport interface ProfileMatrixRaceStanding {\n profileId: string\n /** Cases both this profile and the leader scored. */\n n: number\n /** Independent clusters among those cases. */\n clusters: number\n /** Mean paired difference from the leader; null without a shared scored case. */\n difference: number | null\n low: number | null\n high: number | null\n /** Exact cluster sign-flip p-value for a zero difference. */\n pValue: number | null\n /** Paired cases a test needs for 80% power at the observed difference. */\n casesToResolve: number | null\n dropped: boolean\n reason?: string\n}\n\nexport interface ProfileMatrixRaceBatch {\n batch: number\n casesSeen: number\n cellsRun: number\n leader: string\n standings: ProfileMatrixRaceStanding[]\n}\n\nexport interface ProfileMatrixRaceFinalRow {\n profileId: string\n quality: number | null\n /** Paired difference from the baseline on the final cases; null on the baseline itself. */\n vsBaseline: ProfileMatrixPairedDifference | null\n}\n\nexport interface ProfileMatrixRaceResult {\n matrixId: string\n planDigest: string\n baseline: string\n leader: string\n survivors: string[]\n stoppedBecause: 'one-left' | 'cell-budget' | 'batches-ended'\n casesRaced: string[]\n cellsRun: number\n /** Cells the complete plan holds. */\n plannedCells: number\n log: ProfileMatrixRaceBatch[]\n /** Survivors on the cases every survivor scored. */\n final: { cases: number; rows: ProfileMatrixRaceFinalRow[] }\n records: RunRecord[]\n /** The race chose its leader on these cases, so the leader's score here reads high. */\n selectionBias: string\n}\n\ntype Scores = Map<string, Map<string, number>>\n\ninterface RaceContext {\n baseline: string\n /** Pairing rule; `passFail` is read from the scores at each comparison. */\n rule: ProfilePairingRule\n /** Plan order with the baseline first; ties go to the earlier profile. */\n profileIds: string[]\n}\n\n/**\n * Successive halving over a profile-matrix plan. After each batch a profile\n * whose paired interval against the current leader lies wholly below zero is\n * dropped, as is one whose cells in the batch produced no score; the baseline\n * is always kept. The race stops when one profile is left, the next batch\n * would pass `cellBudget`, or the batch list ends.\n */\nexport async function raceProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: RaceProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<ProfileMatrixRaceResult> {\n const {\n baseline,\n batches: requestedBatches,\n firstBatch,\n cellBudget,\n clusters,\n level = 0.95,\n caseOrder = 'shuffled',\n ...segment\n } = opts\n const { plan } = segment\n const planned = [...new Set(plan.rows.map((row) => row.profileId))]\n if (!planned.includes(baseline)) {\n throw new ValidationError(`raceProfileMatrix: baseline '${baseline}' is not a planned profile`)\n }\n if (!(level > 0 && level < 1))\n throw new ValidationError('raceProfileMatrix: level must be in (0, 1)')\n if (cellBudget !== undefined && !(Number.isSafeInteger(cellBudget) && cellBudget > 0)) {\n throw new ValidationError('raceProfileMatrix: cellBudget must be a positive integer')\n }\n const ctx: RaceContext = {\n baseline,\n rule: {\n clusterOf: clusterResolver(clusters, 'raceProfileMatrix'),\n level,\n passScore: 0.5,\n passFail: true,\n },\n profileIds: [baseline, ...planned.filter((id) => id !== baseline)],\n }\n const order = orderCases(plan, caseOrder)\n const batches = batchSizes(requestedBatches, firstBatch, order.length)\n\n let survivors = [...ctx.profileIds]\n const records = new Map<string, RunRecord>()\n const log: ProfileMatrixRaceBatch[] = []\n let cellsRun = 0\n let seen = 0\n let stoppedBecause: ProfileMatrixRaceResult['stoppedBecause'] = 'batches-ended'\n for (const [index, total] of batches.entries()) {\n if (survivors.length === 1) break\n const batchCases = order.slice(seen, total)\n const inBatch = new Set(batchCases)\n const rows = plan.rows.filter(\n (row) => survivors.includes(row.profileId) && inBatch.has(row.scenarioId),\n )\n if (cellBudget !== undefined && cellsRun + rows.length > cellBudget) {\n if (index === 0) {\n throw new ValidationError(\n `raceProfileMatrix: cellBudget ${cellBudget} is below the first batch's ${rows.length} cells`,\n )\n }\n stoppedBecause = 'cell-budget'\n break\n }\n const result = await runProfileMatrixSegment({\n ...segment,\n segmentId: `race-batch-${index + 1}`,\n rows: rows.map((row) => row.rowId),\n })\n enforceIntegrity(plan, result.matrix.records)\n for (const record of result.matrix.records) records.set(record.runId, record)\n cellsRun += rows.length\n seen = total\n const entry = standings(\n ctx,\n scoresByProfile([...records.values()]),\n survivors,\n order.slice(0, seen),\n batchCases,\n )\n log.push({ batch: index + 1, casesSeen: seen, cellsRun: rows.length, ...entry })\n const dropped = new Set(entry.standings.filter((s) => s.dropped).map((s) => s.profileId))\n survivors = survivors.filter((id) => !dropped.has(id))\n }\n if (survivors.length === 1) stoppedBecause = 'one-left'\n\n const casesRaced = order.slice(0, seen)\n const final = finalComparison(ctx, scoresByProfile([...records.values()]), survivors, casesRaced)\n return {\n matrixId: plan.matrixId,\n planDigest: plan.planDigest,\n baseline,\n leader: final.leader,\n survivors,\n stoppedBecause,\n casesRaced,\n cellsRun,\n plannedCells: plan.rows.length,\n log,\n final: { cases: final.cases, rows: final.rows },\n records: [...records.values()],\n selectionBias:\n `${final.leader} leads on the ${casesRaced.length} raced cases, which the race also used to ` +\n 'choose it, so its score there is biased upward; confirm it on fresh held-out cases before acting on it.',\n }\n}\n\nfunction orderCases<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n caseOrder: 'shuffled' | 'plan',\n): string[] {\n const ids = plan.scenarios.map((scenario) => scenario.id)\n if (caseOrder === 'plan') return ids\n const rng = makeRng(plan.seed)\n for (let i = ids.length - 1; i > 0; i -= 1) {\n const j = Math.floor(rng() * (i + 1))\n ;[ids[i], ids[j]] = [ids[j]!, ids[i]!]\n }\n return ids\n}\n\nfunction batchSizes(\n requested: readonly number[] | undefined,\n firstBatch: number | undefined,\n caseCount: number,\n): number[] {\n if (requested !== undefined) {\n const valid =\n requested.length > 0 &&\n requested.every(\n (total, i) =>\n Number.isSafeInteger(total) &&\n total > (i === 0 ? 0 : requested[i - 1]!) &&\n total <= caseCount,\n )\n if (!valid) {\n throw new ValidationError(\n `raceProfileMatrix: batches must be strictly increasing case counts within 1..${caseCount}`,\n )\n }\n return [...requested]\n }\n const first = firstBatch ?? Math.min(8, caseCount)\n if (!(Number.isSafeInteger(first) && first > 0 && first <= caseCount)) {\n throw new ValidationError(\n `raceProfileMatrix: firstBatch must be an integer within 1..${caseCount}`,\n )\n }\n const sizes: number[] = []\n for (let total = first; total < caseCount; total *= 2) sizes.push(total)\n sizes.push(caseCount)\n return sizes\n}\n\nfunction enforceIntegrity<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n records: readonly RunRecord[],\n): void {\n if (plan.integrity === 'assert') assertRealBackend(records, { allowMixed: plan.allowMixed })\n if (plan.integrity !== 'warn') return\n const report = summarizeBackendIntegrity(records)\n if (report.verdict !== 'real') {\n console.warn(`[raceProfileMatrix] backend integrity: ${report.verdict} — ${report.diagnosis}`)\n }\n}\n\n/** The highest mean on the cases every candidate scored; ties go to the earlier profile. */\nfunction leaderOf(\n ctx: RaceContext,\n scores: Scores,\n candidates: readonly string[],\n cases: readonly string[],\n) {\n const shared = cases.filter((c) => candidates.every((p) => scores.get(p)?.has(c)))\n let leader = candidates.includes(ctx.baseline) ? ctx.baseline : candidates[0]!\n if (shared.length === 0) return { leader, shared }\n const quality = (p: string) => mean(shared.map((c) => scores.get(p)!.get(c)!))\n for (const p of ctx.profileIds) {\n if (candidates.includes(p) && quality(p) > quality(leader)) leader = p\n }\n return { leader, shared }\n}\n\n/** `p` against `q` on the cases both scored within `cases`, through the page's pairing helper. */\nfunction pairedAgainst(\n ctx: RaceContext,\n scores: Scores,\n p: string,\n q: string,\n cases: readonly string[],\n): ProfileMatrixPairedDifference | undefined {\n const rule = { ...ctx.rule, passFail: allPassFail(scores) }\n return pairProfiles(scores.get(p) ?? new Map(), scores.get(q) ?? new Map(), rule, cases)\n}\n\nfunction standings(\n ctx: RaceContext,\n scores: Scores,\n survivors: readonly string[],\n seen: readonly string[],\n batchCases: readonly string[],\n): Pick<ProfileMatrixRaceBatch, 'leader' | 'standings'> {\n const { leader } = leaderOf(ctx, scores, survivors, seen)\n return {\n leader,\n standings: survivors.map((profileId) => {\n const paired = pairedAgainst(ctx, scores, profileId, leader, seen)\n const base = {\n profileId,\n n: paired?.n ?? 0,\n clusters: paired?.clusters ?? 0,\n difference: paired?.estimate ?? null,\n low: paired?.low ?? null,\n high: paired?.high ?? null,\n pValue: paired?.pValue ?? null,\n casesToResolve: paired?.casesToResolve ?? null,\n }\n const protectedProfile = profileId === ctx.baseline || profileId === leader\n if (!batchCases.some((c) => scores.get(profileId)?.has(c))) {\n return protectedProfile\n ? { ...base, dropped: false, reason: 'kept: no cell in this batch produced a score' }\n : { ...base, dropped: true, reason: 'no cell in this batch produced a score' }\n }\n if (base.high === null || base.high >= 0) return { ...base, dropped: false }\n const interval = `[${base.low!.toFixed(3)}, ${base.high.toFixed(3)}]`\n return protectedProfile\n ? {\n ...base,\n dropped: false,\n reason: `kept as the baseline: interval ${interval} lies below zero`,\n }\n : {\n ...base,\n dropped: true,\n reason: `interval ${interval} against ${leader} lies below zero`,\n }\n }),\n }\n}\n\nfunction finalComparison(\n ctx: RaceContext,\n scores: Scores,\n survivors: readonly string[],\n casesRaced: readonly string[],\n) {\n const { leader, shared } = leaderOf(ctx, scores, survivors, casesRaced)\n const rows = survivors.map(\n (profileId): ProfileMatrixRaceFinalRow => ({\n profileId,\n quality: shared.length ? mean(shared.map((c) => scores.get(profileId)!.get(c)!)) : null,\n vsBaseline:\n profileId === ctx.baseline\n ? null\n : (pairedAgainst(ctx, scores, profileId, ctx.baseline, shared) ?? null),\n }),\n )\n return { leader, cases: shared.length, rows }\n}\n","// Reliability across seeded repeats: how often a scenario succeeds in every one\n// of k repeats, reported beside its mean success and counted per independent\n// unit. A conversation that resolves the user's problem on two seeds out of\n// four has a mean success of 0.5 and a pass^4 of 0; an agent a user can rely\n// on needs the second number, which a mean never shows.\n\nimport { passHatK } from '../statistics/paired-binary'\nimport type { CampaignCellResult } from './types'\n\nexport interface RepeatReliabilityOptions<TArtifact> {\n /** Repeats every success must hold over: pass^k. A scenario with fewer scored\n * repeats than `k` reports no pass^k and is listed as incomplete. */\n k: number\n /** Objective success of one repeat, decided by code from the artifact. */\n success: (artifact: TArtifact) => boolean\n /** Independent sampling unit for each scenario; scenarios sharing a unit are\n * averaged before units are weighted equally. Default: each scenario is its\n * own unit. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\nexport interface ScenarioRepeatReliability {\n scenarioId: string\n unit: string\n /** Scored repeats: cells that produced an artifact without an error. */\n repeats: number\n successes: number\n meanSuccess: number\n /** Unbiased pass^k over the scored repeats; null below `k` repeats. */\n passAllK: number | null\n}\n\nexport interface RepeatReliability {\n k: number\n /** Scenarios in first-seen cell order. */\n scenarios: ScenarioRepeatReliability[]\n /** Independent units with at least one scored repeat. */\n units: number\n /** Mean success, each unit weighted equally; null with no scored repeat. */\n meanSuccess: number | null\n /** pass^k, each unit weighted equally over its complete scenarios; null when\n * no scenario has `k` scored repeats. */\n passAllK: number | null\n /** Scenarios with fewer than `k` scored repeats. */\n incompleteScenarios: string[]\n /** Cells that failed in dispatch or judging. They are a service or\n * measurement failure, never a counted agent failure. */\n failedCells: number\n}\n\n/** pass^k beside mean success over a campaign's seeded repeats. */\nexport function repeatReliability<TArtifact>(\n cells: ReadonlyArray<CampaignCellResult<TArtifact>>,\n opts: RepeatReliabilityOptions<TArtifact>,\n): RepeatReliability {\n if (!Number.isSafeInteger(opts.k) || opts.k < 1) {\n throw new RangeError(`repeatReliability: k must be a positive integer, got ${opts.k}`)\n }\n const byScenario = new Map<string, { repeats: number; successes: number }>()\n let failedCells = 0\n for (const cell of cells) {\n if (cell.error !== undefined) {\n failedCells += 1\n continue\n }\n const row = byScenario.get(cell.scenarioId) ?? { repeats: 0, successes: 0 }\n const passed = opts.success(cell.artifact)\n if (typeof passed !== 'boolean') {\n throw new TypeError(\n `repeatReliability: success must return a boolean for '${cell.scenarioId}'`,\n )\n }\n row.repeats += 1\n if (passed) row.successes += 1\n byScenario.set(cell.scenarioId, row)\n }\n\n const scenarios: ScenarioRepeatReliability[] = [...byScenario].map(([scenarioId, row]) => ({\n scenarioId,\n unit: opts.independentUnitByScenarioId?.get(scenarioId) ?? scenarioId,\n repeats: row.repeats,\n successes: row.successes,\n meanSuccess: row.successes / row.repeats,\n passAllK: row.repeats >= opts.k ? passHatK(row.repeats, row.successes, opts.k) : null,\n }))\n const unitMean = (values: (row: ScenarioRepeatReliability) => number | null) => {\n const units = new Map<string, number[]>()\n for (const row of scenarios) {\n const value = values(row)\n if (value === null) continue\n units.set(row.unit, [...(units.get(row.unit) ?? []), value])\n }\n if (units.size === 0) return null\n const means = [...units.values()].map((list) => list.reduce((a, b) => a + b, 0) / list.length)\n return means.reduce((a, b) => a + b, 0) / means.length\n }\n return {\n k: opts.k,\n scenarios,\n units: new Set(scenarios.map((row) => row.unit)).size,\n meanSuccess: unitMean((row) => row.meanSuccess),\n passAllK: unitMean((row) => row.passAllK),\n incompleteScenarios: scenarios.filter((row) => row.passAllK === null).map((r) => r.scenarioId),\n failedCells,\n }\n}\n","import { join } from 'node:path'\nimport { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport {\n canonicalString,\n compareCodeUnits,\n hashCanonical,\n type LedgerHash,\n} from '../ledger-core/canonical'\nimport { type CampaignStorage, fsCampaignStorage } from './storage'\n\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst headerSchema = z\n .object({\n kind: z.literal('retained-dispatch-v1'),\n scope: digest,\n limits: z.array(z.tuple([z.string().min(1), z.number().int().nonnegative()])),\n })\n .strict()\nconst eventSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('started'), id: digest, lane: z.string().min(1) }).strict(),\n z.object({ kind: z.literal('settled'), id: digest, receipt: digest }).strict(),\n])\nconst resultSchema = z\n .object({\n kind: z.literal('retained-dispatch-result-v1'),\n id: digest,\n receipt: digest,\n value: z.unknown(),\n })\n .strict()\n/** The committed byte length and cumulative digest of retained dispatch history. */\nconst anchorEntrySchema = z\n .object({\n kind: z.literal('retained-dispatch-anchor-v1'),\n scope: digest,\n bytes: z.number().int().positive(),\n digest,\n })\n .strict()\ntype Event = z.infer<typeof eventSchema>\ntype AnchorEntry = z.infer<typeof anchorEntrySchema>\n\nexport type RetainedDispatchOutcome<T> =\n | {\n succeeded: true\n value: T\n dispatchId: LedgerHash\n receiptDigest: LedgerHash\n replayed: boolean\n }\n | { succeeded: false; reason: 'outcome_unknown'; dispatchId: LedgerHash; diagnostic?: string }\n | { succeeded: false; reason: 'allowance_exhausted'; dispatchId: LedgerHash }\n\n/** One logical run owns this directory. Callers bind authority and execution/decoder revisions in scope. */\nexport interface RetainedDispatchOptions<Lane extends string, T> {\n runDir: string\n scope: unknown\n /** Reserved allowances: one lane cannot spend another lane's calls. */\n limits: Readonly<Record<Lane, number>>\n /** Validate the complete retained result, including explicit failed/unknown execution outcomes. */\n parse: (value: unknown) => T\n storage?: CampaignStorage\n /** The owning durable Run has started this scope; missing history must not issue another allowance. */\n requireExisting?: boolean\n}\n\ntype Header = z.infer<typeof headerSchema>\n\n/** The loaded journal of one retained-dispatch scope: its paths, accounting and verified history. */\ninterface DispatchJournal<T> {\n storage: CampaignStorage\n parse: (value: unknown) => T\n header: Header\n limits: Map<string, number>\n counts: Map<string, number>\n calls: Map<string, { lane: string; receipt?: string }>\n indexPath: string\n scopePath: string\n anchorPath: string\n receiptsDir: string\n scopeText: string\n scopeDigest: LedgerHash\n /** The journal text already applied, its byte length, cumulative digest, and whether the header is in it. */\n retainedText: string\n revision: number\n chain: LedgerHash | null\n opened: boolean\n}\n\ntype DispatchRequest<Lane extends string, T> = {\n lane: Lane\n input: unknown\n dispatch: () => Promise<T>\n signal?: AbortSignal\n}\n\nfunction fail(message: string): never {\n throw new ValidationError(`retained dispatch: ${message}`)\n}\n\n/**\n * Persist dispatch intent before an external call and its validated result afterward.\n * Replays settled calls; never repeats an uncertain call or refunds its allowance.\n * Every journal event is durably anchored before it takes effect, and history that\n * cannot be proven equal to its durable anchor fails closed.\n * This wraps a campaign's dispatch; runEval still owns scheduling, judging and reports.\n * Uses CampaignStorage's existing compare-and-append, not another database or scheduler.\n */\nexport function createRetainedDispatch<Lane extends string, T>(\n options: RetainedDispatchOptions<Lane, T>,\n) {\n if (!options.runDir.trim())\n throw new ValidationError('retained dispatch requires a run directory')\n const storage = options.storage ?? fsCampaignStorage()\n const header = headerSchema.parse({\n kind: 'retained-dispatch-v1',\n scope: hashCanonical(options.scope),\n limits: Object.entries(options.limits).sort(([a], [b]) => compareCodeUnits(a, b)),\n })\n if (!header.limits.length)\n throw new ValidationError('retained dispatch requires named allowances')\n const journal: DispatchJournal<T> = {\n storage,\n parse: options.parse,\n header,\n limits: new Map(header.limits),\n counts: new Map<string, number>(),\n calls: new Map<string, { lane: string; receipt?: string }>(),\n indexPath: join(options.runDir, 'dispatches.jsonl'),\n scopePath: join(options.runDir, 'dispatch-scope.json'),\n anchorPath: join(options.runDir, 'dispatch-anchor.jsonl'),\n receiptsDir: join(options.runDir, 'dispatch-results'),\n scopeText: canonicalString(header),\n scopeDigest: hashCanonical(header),\n retainedText: '',\n revision: 0,\n chain: null,\n opened: false,\n }\n const active = new Map<string, Promise<RetainedDispatchOutcome<T>>>()\n storage.ensureDir(options.runDir)\n storage.ensureDir(journal.receiptsDir)\n openJournal(journal, options.requireExisting)\n\n return {\n /** The input binds all behavior-affecting request material, not just a caller-selected nonce. */\n run(request: DispatchRequest<Lane, T>): Promise<RetainedDispatchOutcome<T>> {\n const id = hashCanonical([header.scope, request.lane, request.input])\n const pending = active.get(id)\n if (pending) return pending\n const promise = dispatchOnce(journal, id, request)\n active.set(id, promise)\n void promise\n .finally(() => {\n active.delete(id)\n })\n .catch(() => {})\n return promise\n },\n /** Counts include uncertain dispatches, which keep their reservation. No pricing is inferred. */\n committed(): ReadonlyMap<Lane, number> {\n refreshJournal(journal)\n return new Map(header.limits.map(([lane]) => [lane as Lane, journal.counts.get(lane) ?? 0]))\n },\n }\n}\n\n/** Fold one journal event into the per-lane counts and pending-call map. */\nfunction applyEvent<T>(journal: DispatchJournal<T>, event: Event): void {\n const existing = journal.calls.get(event.id)\n if (event.kind === 'started') {\n const limit = journal.limits.get(event.lane)\n const count = journal.counts.get(event.lane) ?? 0\n if (existing || limit === undefined || count >= limit)\n fail('invalid or over-budget dispatch history')\n journal.calls.set(event.id, { lane: event.lane })\n journal.counts.set(event.lane, count + 1)\n } else {\n if (!existing || existing.receipt) fail('settlement has no unique pending dispatch')\n existing.receipt = event.receipt\n }\n}\n\n/** Read the durable anchor file, refusing a torn, empty-record, foreign-scope or non-monotonic one. */\nfunction readAnchor<T>(journal: DispatchJournal<T>): { text: string; entries: AnchorEntry[] } {\n const { storage, anchorPath } = journal\n const content = storage.read(anchorPath)\n if (content === undefined && storage.exists(anchorPath)) fail('cannot read durable anchor')\n const text = content ?? ''\n if (text && !text.endsWith('\\n')) fail('durable anchor is torn')\n const entries: AnchorEntry[] = []\n let previous = 0\n const lines = text.split('\\n')\n if (lines.at(-1) === '') lines.pop()\n if (lines.some((line) => !line)) fail('durable anchor contains an empty record')\n for (const line of lines) {\n const entry = anchorEntrySchema.parse(JSON.parse(line) as unknown)\n if (entry.scope !== journal.scopeDigest) fail('durable anchor scope changed')\n if (entry.bytes <= previous) fail('durable anchor is not append-only')\n previous = entry.bytes\n entries.push(entry)\n }\n return { text, entries }\n}\n\n/** Re-read the journal, prove it extends what was applied and matches its anchor, and apply the new events. */\nfunction refreshJournal<T>(journal: DispatchJournal<T>): void {\n const { storage } = journal\n if (storage.read(journal.scopePath) !== journal.scopeText)\n fail('scope anchor is missing or changed')\n const stored = storage.read(journal.indexPath)\n if (stored === undefined && storage.exists(journal.indexPath))\n fail('cannot read existing history')\n const text = stored ?? ''\n if (!text.startsWith(journal.retainedText) || (text && !text.endsWith('\\n')))\n fail('history was truncated, replaced or torn')\n const { entries } = readAnchor(journal)\n const bytes = Buffer.byteLength(text)\n const applied = Buffer.byteLength(journal.retainedText)\n if (text && !entries.length) fail('durable anchor is missing')\n const highWater = entries[entries.length - 1]\n if (highWater && bytes !== highWater.bytes) {\n // Bytes beyond the durable anchor are never trusted, shortened or synthesized.\n if (bytes < highWater.bytes) fail('history was truncated below its durable anchor')\n fail('history extends beyond its durable anchor')\n }\n let offset = 0\n let running: LedgerHash | null = null\n let entryIndex = 0\n let seenHeader = journal.opened\n for (const line of text.split('\\n')) {\n if (!line) continue\n running = hashCanonical([running, line])\n offset += Buffer.byteLength(line) + 1\n while (entryIndex < entries.length && entries[entryIndex]!.bytes === offset) {\n if (entries[entryIndex]!.digest !== running) fail('history diverges from its durable anchor')\n entryIndex += 1\n }\n if (offset <= applied) continue\n if (!seenHeader) {\n const value: unknown = JSON.parse(line)\n if (hashCanonical(headerSchema.parse(value)) !== hashCanonical(journal.header))\n fail('resume changed its scope or allowances')\n seenHeader = true\n } else applyEvent(journal, eventSchema.parse(JSON.parse(line) as unknown))\n }\n if (entries.length && entryIndex !== entries.length)\n fail('history diverges from its durable anchor')\n journal.chain = running\n journal.retainedText = text\n journal.revision = bytes\n journal.opened = seenHeader\n}\n\n/** Compare-and-append one event; a lost race refreshes the journal and returns false. */\nfunction appendEvent<T>(journal: DispatchJournal<T>, event: Header | Event): boolean {\n const encoded = canonicalString(event)\n const line = `${encoded}\\n`\n const next = journal.storage.append(journal.indexPath, line, journal.revision)\n if (next === undefined) {\n refreshJournal(journal)\n return false\n }\n if (next !== journal.revision + Buffer.byteLength(line))\n fail('storage returned an invalid append revision')\n journal.chain = hashCanonical([journal.chain, encoded])\n journal.retainedText += line\n journal.revision = next\n if (event.kind === 'retained-dispatch-v1') journal.opened = true\n else applyEvent(journal, event)\n return true\n}\n\n/** Record the journal's current length and digest in the durable anchor. */\nfunction advanceAnchor<T>(journal: DispatchJournal<T>): void {\n const currentChain = journal.chain ?? fail('cannot anchor an empty history')\n if (journal.revision <= 0) fail('cannot anchor an empty history')\n const { text, entries } = readAnchor(journal)\n const last = entries[entries.length - 1]\n if (last) {\n if (last.bytes > journal.revision) fail('history is behind its durable anchor')\n if (last.bytes === journal.revision) {\n if (last.digest !== currentChain) fail('history diverges from its durable anchor')\n return\n }\n }\n const line = `${canonicalString({\n kind: 'retained-dispatch-anchor-v1',\n scope: journal.scopeDigest,\n bytes: journal.revision,\n digest: currentChain,\n } satisfies AnchorEntry)}\\n`\n const next = journal.storage.append(journal.anchorPath, line, Buffer.byteLength(text))\n if (next === undefined) {\n const concurrent = readAnchor(journal).entries.at(-1)\n if (concurrent?.bytes === journal.revision && concurrent.digest === journal.chain) return\n fail('durable anchor append is busy; retry with the same run directory')\n }\n if (next !== Buffer.byteLength(text) + Buffer.byteLength(line))\n fail('storage returned an invalid durable anchor revision')\n}\n\n/** An event takes effect only after both its journal append and its anchor entry are durable. */\nfunction commitEvent<T>(journal: DispatchJournal<T>, event: Header | Event): boolean {\n if (!appendEvent(journal, event)) return false\n advanceAnchor(journal)\n return true\n}\n\n/** Create or verify the scope anchor, load existing history, and commit the header on a fresh journal. */\nfunction openJournal<T>(journal: DispatchJournal<T>, requireExisting: boolean | undefined): void {\n const { storage, scopePath, indexPath, anchorPath, scopeText } = journal\n // The immutable scope and append-only history anchor distinguish fresh runs from lost journals.\n // A half-initialized scope is held for reconciliation, never guessed to be unused.\n if (\n requireExisting &&\n (!storage.exists(scopePath) || !storage.exists(indexPath) || !storage.exists(anchorPath))\n )\n fail('required retained history is missing')\n if (storage.exists(scopePath)) {\n if (storage.read(scopePath) !== scopeText) fail('resume changed its scope or allowances')\n if (!storage.read(indexPath)?.trim()) fail('dispatch history is missing or empty')\n // A history without its committed high-water mark is never treated as unused.\n if (!storage.read(anchorPath)?.trim()) fail('durable anchor is missing')\n } else {\n if (storage.exists(indexPath) || storage.exists(anchorPath))\n fail('legacy history has no scope anchor; reconcile before migration')\n const created = storage.append(scopePath, scopeText, 0)\n if (created === undefined) {\n if (storage.read(scopePath) !== scopeText || !storage.read(indexPath)?.trim())\n fail('scope initialization is busy; retry the same scope')\n } else if (created !== Buffer.byteLength(scopeText)) {\n fail('storage returned an invalid scope revision')\n }\n }\n refreshJournal(journal)\n if (!journal.opened && !commitEvent(journal, journal.header) && !journal.opened)\n fail('history is busy; retry with the same run directory')\n}\n\n/** Read and verify a retained result file, or undefined when none was written. */\nfunction readResult<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n): { value: T; receipt: LedgerHash } | undefined {\n const content = journal.storage.read(resultPath(journal, id))\n if (content === undefined) return undefined\n const result = resultSchema.parse(JSON.parse(content))\n if (result.id !== id) return fail('retained result dispatch id mismatch')\n if (hashCanonical(result.value) !== result.receipt) return fail('retained result digest mismatch')\n const value = journal.parse(result.value)\n if (hashCanonical(value) !== result.receipt) return fail('result decoder changed retained output')\n return { value, receipt: result.receipt as LedgerHash }\n}\n\nfunction resultPath<T>(journal: DispatchJournal<T>, id: LedgerHash): string {\n return join(journal.receiptsDir, `${id.slice(7)}.json`)\n}\n\n/** Commit the settlement of a dispatch whose result is already durable. */\nfunction settle<T>(journal: DispatchJournal<T>, id: LedgerHash, receipt: LedgerHash): void {\n while (true) {\n const existing = journal.calls.get(id)\n if (existing?.receipt) {\n if (existing.receipt !== receipt) fail('settled result digest mismatch')\n return\n }\n if (!existing) fail('settlement has no pending dispatch')\n const previousRevision = journal.revision\n if (commitEvent(journal, { kind: 'settled', id, receipt })) return\n if (journal.revision === previousRevision)\n fail('settlement is busy; retained result awaits reconciliation')\n }\n}\n\n/** Replay a settled dispatch from its retained result. */\nfunction loadSettled<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n receipt: string,\n): RetainedDispatchOutcome<T> {\n const result = readResult(journal, id)\n if (!result) return fail('settled result is missing')\n if (result.receipt !== receipt) return fail('settled result digest mismatch')\n return {\n succeeded: true,\n value: result.value,\n dispatchId: id,\n receiptDigest: receipt as LedgerHash,\n replayed: true,\n }\n}\n\n/** Replay a known dispatch, or commit its started intent; returns the outcome when no call should be made. */\nfunction claimDispatch<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n lane: string,\n signal: AbortSignal | undefined,\n): RetainedDispatchOutcome<T> | undefined {\n while (true) {\n const existing = journal.calls.get(id)\n if (existing) {\n if (existing.receipt) return loadSettled(journal, id, existing.receipt)\n const result = readResult(journal, id)\n if (!result) return { succeeded: false, reason: 'outcome_unknown', dispatchId: id }\n settle(journal, id, result.receipt)\n return {\n succeeded: true,\n value: result.value,\n dispatchId: id,\n receiptDigest: result.receipt,\n replayed: true,\n }\n }\n signal?.throwIfAborted()\n if ((journal.counts.get(lane) ?? 0) >= journal.limits.get(lane)!) {\n return { succeeded: false, reason: 'allowance_exhausted', dispatchId: id }\n }\n const previousRevision = journal.revision\n if (commitEvent(journal, { kind: 'started', id, lane })) return undefined\n if (journal.revision === previousRevision)\n return fail('history is busy; retry with the same input')\n }\n}\n\n/** Retain a dispatched value's result file, settle it, and return the decoded outcome. */\nfunction retainResult<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n value: T,\n): RetainedDispatchOutcome<T> {\n const encoded = canonicalString(value)\n const decoded: unknown = JSON.parse(encoded)\n const retainedValue = journal.parse(decoded)\n if (canonicalString(retainedValue) !== encoded)\n return fail('result decoder is not stable across serialization')\n const receipt = hashCanonical(decoded)\n const retainedResult = canonicalString({\n kind: 'retained-dispatch-result-v1',\n id,\n receipt,\n value: decoded,\n })\n const file = resultPath(journal, id)\n if (\n journal.storage.append(file, retainedResult, 0) === undefined &&\n journal.storage.read(file) !== retainedResult\n )\n fail('cannot retain dispatch result')\n // The receipt is durable before the settlement event can make it reusable.\n settle(journal, id, receipt)\n return {\n succeeded: true,\n value: retainedValue,\n dispatchId: id,\n receiptDigest: receipt,\n replayed: false,\n }\n}\n\n/** Replay, claim an allowance, call the dispatch once, and retain its result. */\nasync function dispatchOnce<Lane extends string, T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n request: DispatchRequest<Lane, T>,\n): Promise<RetainedDispatchOutcome<T>> {\n const { lane, dispatch, signal } = request\n if (!journal.limits.has(lane)) return fail('unknown allowance lane')\n // Replay must also validate retained history, not trust a stale in-memory result.\n refreshJournal(journal)\n const claimed = claimDispatch(journal, id, lane, signal)\n if (claimed) return claimed\n // The started event is durably anchored above, so the external effect below is\n // attributable to a committed intent that survives restarts and truncation.\n // A rejection leaves the committed intent in doubt, so return its diagnostic without settling it.\n let value: T\n try {\n signal?.throwIfAborted()\n value = journal.parse(await dispatch())\n } catch (error) {\n return {\n succeeded: false,\n reason: 'outcome_unknown',\n dispatchId: id,\n diagnostic: error instanceof Error ? error.message : String(error),\n }\n }\n return retainResult(journal, id, value)\n}\n","/**\n * Discriminative scenario selection (research claim E2).\n *\n * The OR benchmark is SATURATING: run 7 measured ~75% tied holdout cells — most\n * problems are solved optimally by the baseline AND every candidate, so those\n * paired cells carry zero signal. A random/balanced holdout split spends its\n * budget on scenarios that cannot separate candidates.\n *\n * This picks the holdout by DISCRIMINATION power instead: a scenario every\n * candidate scores identically (variance ~0) carries no signal; one where the\n * scores spread carries the most. We drop fully saturated ties so each paired\n * holdout cell is spent on a scenario that can actually move a verdict.\n */\n\n/** Per-scenario observation: the composite scores each candidate earned on it. */\nexport interface ScenarioSignal {\n scenarioId: string\n /** Per-candidate composite scores observed for this scenario (>=1 values). */\n scores: number[]\n}\n\nexport interface DiscriminationScore {\n scenarioId: string\n /** Higher = separates candidates more (spread of their scores). */\n discrimination: number\n /** Higher = easier / more-saturated (mean of candidate scores). */\n meanScore: number\n variance: number\n /** variance ~0 AND meanScore at/above the ceiling ⇒ a saturated tie, no signal. */\n tied: boolean\n}\n\nconst DEFAULT_SATURATION_CEILING = 0.999\n/** Variance below this is treated as \"every candidate scored the same\". */\nconst VARIANCE_EPSILON = 1e-9\n\ninterface Moments {\n meanScore: number\n variance: number\n}\n\n/** Population mean + variance of the candidate scores. Empty ⇒ zeros (a signal\n * with no observations cannot discriminate). */\nfunction moments(scores: number[]): Moments {\n const n = scores.length\n if (n === 0) return { meanScore: 0, variance: 0 }\n let sum = 0\n for (const s of scores) sum += s\n const meanScore = sum / n\n let sqDev = 0\n for (const s of scores) {\n const d = s - meanScore\n sqDev += d * d\n }\n return { meanScore, variance: sqDev / n }\n}\n\n/** Deterministic ordering: discrimination desc, then meanScore asc (more\n * headroom first), then scenarioId asc. */\nfunction compareDiscrimination(a: DiscriminationScore, b: DiscriminationScore): number {\n if (b.discrimination !== a.discrimination) return b.discrimination - a.discrimination\n if (a.meanScore !== b.meanScore) return a.meanScore - b.meanScore\n return a.scenarioId < b.scenarioId ? -1 : a.scenarioId > b.scenarioId ? 1 : 0\n}\n\n/**\n * Rank scenarios by how well they DISCRIMINATE candidates.\n *\n * `discrimination = variance` (spread of the candidate scores) — kept simple on\n * purpose; the headroom term (`saturationCeiling - meanScore`) only breaks ties\n * so that, among equally spread scenarios, the one with more room to improve\n * ranks first. Returned sorted by the deterministic order above.\n */\nexport function scoreDiscrimination(\n signals: ScenarioSignal[],\n opts?: { saturationCeiling?: number },\n): DiscriminationScore[] {\n const saturationCeiling = opts?.saturationCeiling ?? DEFAULT_SATURATION_CEILING\n const scored = signals.map((signal): DiscriminationScore => {\n const { meanScore, variance } = moments(signal.scores)\n const tied = variance < VARIANCE_EPSILON && meanScore >= saturationCeiling\n return {\n scenarioId: signal.scenarioId,\n discrimination: variance,\n meanScore,\n variance,\n tied,\n }\n })\n return scored.sort(compareDiscrimination)\n}\n","/**\n * VCS-pluggable worktree adapter. One improvement = one worktree, PR-like\n * (multiple commits allowed). A code-tier proposer's `propose()` creates a\n * worktree, an agent commits the change into it, and `finalize()` returns a\n * content-addressed `CodeSurface` the measurement verifies before running.\n * On promotion the worktree becomes the PR branch.\n *\n * The interface is VCS-agnostic so a future `jj` ([jj-vcs](https://github.com/jj-vcs/jj))\n * adapter can slot in without touching proposer code. Only the git adapter\n * ships today. See `docs/design/loop-taxonomy.md`.\n */\n\nimport { execFileSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport {\n closeSync,\n existsSync,\n constants as fsConstants,\n fstatSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readlinkSync,\n readSync,\n realpathSync,\n rmSync,\n} from 'node:fs'\nimport { devNull, tmpdir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { assertCodeSurfaceIdentity, surfaceContentHash } from '../surface-identity'\nimport type { CodeSurface } from '../types'\n\nconst MAX_GIT_OUTPUT_BYTES = 256 * 1024 * 1024\nconst FILE_HASH_CHUNK_BYTES = 1024 * 1024\n\ntype GitOutput = string | Uint8Array\ntype GitEnvironment = Readonly<Record<string, string>>\ntype GitRunner = (args: string[], cwd: string, env?: GitEnvironment) => GitOutput\n\nconst GIT_REPOSITORY_ENV = new Set([\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES',\n 'GIT_COMMON_DIR',\n 'GIT_DIR',\n 'GIT_INDEX_FILE',\n 'GIT_NAMESPACE',\n 'GIT_OBJECT_DIRECTORY',\n 'GIT_PREFIX',\n 'GIT_QUARANTINE_PATH',\n 'GIT_WORK_TREE',\n])\n\nexport interface Worktree {\n /** Absolute path to the checked-out worktree directory. */\n readonly path: string\n /** The branch the worktree is on (becomes the PR branch on promotion). */\n readonly branch: string\n /** The ref the worktree was forked from. */\n readonly baseRef: string\n /** Exact commit `baseRef` resolved to before the worktree was created. */\n readonly baseCommit: string\n /** Exact tree object for `baseCommit`. */\n readonly baseTree: string\n}\n\nexport interface WorktreeAdapter {\n /** Create an isolated worktree on a fresh branch off `baseRef`. */\n create(opts: { baseRef: string; label: string }): Promise<Worktree>\n /** Commit pending changes, freeze the exact Git objects + binary patch, and\n * verify the worktree still matches that identity. */\n finalize(worktree: Worktree, summary: string): Promise<CodeSurface>\n /** Idempotently remove the worktree and branch. Safe to retry after partial cleanup. */\n discard(worktree: Worktree): Promise<void>\n}\n\n/** Typed failure from a `WorktreeAdapter` operation (create/finalize/discard) — wraps the underlying git error as `cause`. */\nexport class WorktreeAdapterError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message)\n this.name = 'WorktreeAdapterError'\n }\n}\n\nexport interface GitWorktreeAdapterOptions {\n /** Repo root the worktrees fork from. */\n repoRoot: string\n /** Directory worktrees are created under. Default: `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Branch-name prefix. Default: `improve`. */\n branchPrefix?: string\n /** Test seam — defaults to a real `git` runner. The return value must contain\n * stdout verbatim, and runners that execute Git must forward the optional\n * environment overrides used to isolate patch generation. */\n git?: GitRunner\n}\n\nfunction defaultGit(args: string[], cwd: string, overrides?: GitEnvironment): Uint8Array {\n try {\n const env = { ...process.env }\n for (const key of Object.keys(env)) {\n if (\n GIT_REPOSITORY_ENV.has(key) ||\n key === 'GIT_CONFIG' ||\n key.startsWith('GIT_CONFIG_') ||\n key.startsWith('GIT_ATTR_') ||\n key === 'GIT_DIFF_OPTS' ||\n key === 'GIT_EXTERNAL_DIFF'\n ) {\n delete env[key]\n }\n }\n Object.assign(env, overrides)\n env.GIT_NO_REPLACE_OBJECTS = '1'\n env.LC_ALL = 'C'\n env.LANG = 'C'\n return execFileSync('git', args, { cwd, env, maxBuffer: MAX_GIT_OUTPUT_BYTES })\n } catch (err) {\n const stderr =\n err && typeof err === 'object' && 'stderr' in err\n ? String((err as { stderr: unknown }).stderr)\n : ''\n throw new WorktreeAdapterError(`git ${args.join(' ')} failed: ${stderr || String(err)}`, err)\n }\n}\n\nfunction gitBytes(git: GitRunner, args: string[], cwd: string, env?: GitEnvironment): Buffer {\n try {\n const output = git(args, cwd, env)\n return typeof output === 'string' ? Buffer.from(output, 'utf8') : Buffer.from(output)\n } catch (err) {\n if (err instanceof WorktreeAdapterError) throw err\n throw new WorktreeAdapterError(`git ${args.join(' ')} failed: ${String(err)}`, err)\n }\n}\n\nfunction gitText(git: GitRunner, args: string[], cwd: string, env?: GitEnvironment): string {\n return gitBytes(git, args, cwd, env).toString('utf8').trim()\n}\n\nfunction hasRegisteredWorktree(git: GitRunner, repoRoot: string, path: string): boolean {\n const expected = Buffer.from(`worktree ${resolve(path)}`, 'utf8')\n const records = gitBytes(git, ['worktree', 'list', '--porcelain', '-z'], repoRoot)\n let start = 0\n while (start < records.length) {\n const end = records.indexOf(0, start)\n if (end < 0) {\n throw new WorktreeAdapterError('Git worktree list output was not NUL-terminated')\n }\n if (records.subarray(start, end).equals(expected)) return true\n start = end + 1\n }\n return false\n}\n\nfunction hasLocalBranch(git: GitRunner, repoRoot: string, branch: string): boolean {\n const ref = `refs/heads/${branch}`\n return gitText(git, ['for-each-ref', '--format=%(refname)', '--', ref], repoRoot)\n .split('\\n')\n .some((candidate) => candidate === ref)\n}\n\nfunction reconcileAbsent(exists: () => boolean, remove: () => void): unknown | undefined {\n try {\n if (!exists()) return undefined\n } catch (err) {\n return err\n }\n\n try {\n remove()\n return undefined\n } catch (removeError) {\n try {\n // Git may complete the mutation before the caller observes a failure, or\n // another cleanup may win the race. The desired end state is what matters.\n if (!exists()) return undefined\n } catch (recheckError) {\n return new AggregateError(\n [removeError, recheckError],\n 'Removal failed and the resulting resource state could not be checked',\n )\n }\n return removeError\n }\n}\n\nfunction sha256(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nconst PATCH_ARGS = [\n // Git binary patches embed a zlib stream. Pin no-compression at command\n // scope so repository/global config and compressor heuristics cannot change\n // the candidate identity for the same base and final tree.\n '-c',\n 'core.compression=0',\n '-c',\n `core.attributesFile=${devNull}`,\n '-c',\n 'core.quotePath=true',\n '-c',\n 'diff.suppressBlankEmpty=false',\n 'diff',\n '--unified=3',\n '--inter-hunk-context=0',\n `-O${devNull}`,\n '--binary',\n '--full-index',\n '--no-color',\n '--no-ext-diff',\n '--no-textconv',\n '--no-renames',\n '--diff-algorithm=myers',\n '--no-indent-heuristic',\n '--src-prefix=a/',\n '--dst-prefix=b/',\n] as const\n\nconst CANONICAL_GIT_ENV: GitEnvironment = {\n GIT_ATTR_GLOBAL: devNull,\n GIT_ATTR_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: devNull,\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_SYSTEM: devNull,\n}\n\n/** Render the transport patch from immutable objects through fresh Git metadata.\n * Source-repository config, info attributes, templates, and caller environment\n * therefore cannot alter bytes for the same two trees. */\nfunction patchBytes(\n git: GitRunner,\n cwd: string,\n baseCommit: string,\n candidateCommit: string,\n): Buffer {\n const scratch = mkdtempSync(join(tmpdir(), 'agent-eval-patch-'))\n const bareRepo = join(scratch, 'repo.git')\n const emptyTemplate = join(scratch, 'empty-template')\n mkdirSync(emptyTemplate)\n try {\n const objectFormat = gitObjectHashAlgorithm(candidateCommit)\n const sourceObjects = realpathSync(gitText(git, ['rev-parse', '--git-path', 'objects'], cwd))\n gitText(\n git,\n [\n 'init',\n '--bare',\n '--quiet',\n ...(objectFormat === 'sha256' ? ['--object-format=sha256'] : []),\n `--template=${emptyTemplate}`,\n bareRepo,\n ],\n scratch,\n CANONICAL_GIT_ENV,\n )\n return gitBytes(\n git,\n [`--git-dir=${bareRepo}`, ...PATCH_ARGS, baseCommit, candidateCommit, '--'],\n scratch,\n {\n ...CANONICAL_GIT_ENV,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: sourceObjects,\n },\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n}\n\nfunction resolveCommit(git: GitRunner, cwd: string, ref: string): string {\n return gitText(git, ['rev-parse', '--verify', `${ref}^{commit}`], cwd)\n}\n\nfunction unresolvedWorktreePath(surface: CodeSurface, worktreeDir?: string): string {\n if (isAbsolute(surface.worktreeRef)) return surface.worktreeRef\n if (worktreeDir) return join(worktreeDir, basename(surface.worktreeRef))\n return surface.worktreeRef\n}\n\ninterface GitTreeEntry {\n mode: string\n objectId: string\n path: string\n}\n\nfunction displayGitPath(path: string): string {\n return JSON.stringify(path)\n}\n\nfunction parseGitTreeEntries(bytes: Uint8Array): GitTreeEntry[] {\n const input = Buffer.from(bytes)\n const entries: GitTreeEntry[] = []\n let start = 0\n while (start < input.length) {\n const end = input.indexOf(0, start)\n if (end < 0) throw new WorktreeAdapterError('Git tree output was not NUL-terminated')\n const record = input.subarray(start, end)\n start = end + 1\n if (record.length === 0) continue\n\n const tab = record.indexOf(0x09)\n if (tab < 0) throw new WorktreeAdapterError('Git tree entry did not contain a path')\n const metadata = record.subarray(0, tab).toString('ascii').split(' ')\n if (metadata.length !== 3) throw new WorktreeAdapterError('Git tree entry was malformed')\n const mode = metadata[0]\n const type = metadata[1]\n const objectId = metadata[2]\n if (!mode || !type || !objectId) {\n throw new WorktreeAdapterError('Git tree entry was malformed')\n }\n const pathBytes = record.subarray(tab + 1)\n const path = pathBytes.toString('utf8')\n if (!Buffer.from(path, 'utf8').equals(pathBytes)) {\n throw new WorktreeAdapterError('CodeSurface paths must be valid UTF-8')\n }\n if (type !== 'blob' && type !== 'commit') {\n throw new WorktreeAdapterError(\n `CodeSurface contains unsupported Git object type ${type} at ${displayGitPath(path)}`,\n )\n }\n entries.push({ mode, objectId, path })\n }\n return entries\n}\n\nfunction parseGitPathList(bytes: Uint8Array): string[] {\n const input = Buffer.from(bytes)\n const paths: string[] = []\n let start = 0\n while (start < input.length) {\n const end = input.indexOf(0, start)\n if (end < 0) throw new WorktreeAdapterError('Git path output was not NUL-terminated')\n const pathBytes = input.subarray(start, end)\n start = end + 1\n if (pathBytes.length === 0) continue\n const path = pathBytes.toString('utf8')\n if (!Buffer.from(path, 'utf8').equals(pathBytes)) {\n throw new WorktreeAdapterError('CodeSurface paths must be valid UTF-8')\n }\n paths.push(path)\n }\n return paths\n}\n\nfunction isWithinRoot(root: string, candidate: string): boolean {\n const rel = relative(root, candidate)\n return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))\n}\n\nfunction assertSafeRelativePath(root: string, path: string): string {\n if (path.length === 0 || isAbsolute(path)) {\n throw new WorktreeAdapterError(`CodeSurface contains unsafe path ${displayGitPath(path)}`)\n }\n const absolutePath = resolve(root, path)\n if (!isWithinRoot(root, absolutePath) || absolutePath === root) {\n throw new WorktreeAdapterError(`CodeSurface path escapes its worktree: ${displayGitPath(path)}`)\n }\n\n const segments = path.split(/[\\\\/]/u)\n let parent = root\n for (const segment of segments.slice(0, -1)) {\n if (segment.length === 0 || segment === '.' || segment === '..') {\n throw new WorktreeAdapterError(`CodeSurface contains unsafe path ${displayGitPath(path)}`)\n }\n parent = join(parent, segment)\n const stat = lstatSync(parent)\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new WorktreeAdapterError(\n `CodeSurface path traverses a non-directory or symbolic link: ${displayGitPath(path)}`,\n )\n }\n }\n return absolutePath\n}\n\nfunction gitObjectHashAlgorithm(objectId: string): 'sha1' | 'sha256' {\n if (/^[a-f0-9]{40}$/.test(objectId)) return 'sha1'\n if (/^[a-f0-9]{64}$/.test(objectId)) return 'sha256'\n throw new WorktreeAdapterError(`Unsupported Git object id: ${objectId}`)\n}\n\nfunction hashGitBlobBytes(bytes: Uint8Array, objectId: string): string {\n const hash = createHash(gitObjectHashAlgorithm(objectId))\n hash.update(`blob ${bytes.byteLength}\\0`)\n hash.update(bytes)\n return hash.digest('hex')\n}\n\nfunction hashGitBlobFile(path: string, objectId: string): { hash: string; executable: boolean } {\n const before = lstatSync(path)\n if (!before.isFile() || before.isSymbolicLink()) {\n throw new WorktreeAdapterError(`CodeSurface expected a regular file at ${displayGitPath(path)}`)\n }\n\n const noFollow = process.platform === 'win32' ? 0 : fsConstants.O_NOFOLLOW\n const fd = openSync(path, fsConstants.O_RDONLY | noFollow)\n try {\n const opened = fstatSync(fd)\n if (\n !opened.isFile() ||\n opened.dev !== before.dev ||\n opened.ino !== before.ino ||\n opened.size !== before.size\n ) {\n throw new WorktreeAdapterError(\n `CodeSurface file changed while it was being verified: ${displayGitPath(path)}`,\n )\n }\n\n const hash = createHash(gitObjectHashAlgorithm(objectId))\n hash.update(`blob ${opened.size}\\0`)\n const chunk = Buffer.allocUnsafe(FILE_HASH_CHUNK_BYTES)\n let total = 0\n while (true) {\n const count = readSync(fd, chunk, 0, chunk.length, null)\n if (count === 0) break\n total += count\n hash.update(chunk.subarray(0, count))\n }\n if (total !== opened.size) {\n throw new WorktreeAdapterError(\n `CodeSurface file changed while it was being verified: ${displayGitPath(path)}`,\n )\n }\n return { hash: hash.digest('hex'), executable: (opened.mode & 0o111) !== 0 }\n } finally {\n closeSync(fd)\n }\n}\n\nfunction assertSymlinkTargetIsBound(\n root: string,\n linkPath: string,\n trackedPaths: ReadonlySet<string>,\n): void {\n const targetBytes = readlinkSync(linkPath, { encoding: 'buffer' })\n const target = targetBytes.toString('utf8')\n if (!Buffer.from(target, 'utf8').equals(targetBytes)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link has an unsafe target at ${displayGitPath(linkPath)}`,\n )\n }\n if (isAbsolute(target)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n const lexicalTarget = resolve(dirname(linkPath), target)\n if (!isWithinRoot(root, lexicalTarget)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n let resolvedTarget: string\n try {\n resolvedTarget = realpathSync(linkPath)\n } catch (err) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link target is missing or cyclic at ${displayGitPath(linkPath)}`,\n err,\n )\n }\n if (!isWithinRoot(root, resolvedTarget)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n\n const targetRelative = relative(root, resolvedTarget).split(sep).join('/')\n const targetIsTracked =\n trackedPaths.has(targetRelative) ||\n [...trackedPaths].some((trackedPath) => trackedPath.startsWith(`${targetRelative}/`))\n if (!targetIsTracked) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link resolves to untracked content at ${displayGitPath(linkPath)}`,\n )\n }\n}\n\nfunction assertRawTreeMatchesWorktree(git: GitRunner, root: string, candidateCommit: string): void {\n const entries = parseGitTreeEntries(\n gitBytes(git, ['ls-tree', '-r', '-z', '--full-tree', candidateCommit], root),\n )\n const trackedPaths = new Set(entries.map((entry) => entry.path))\n\n for (const entry of entries) {\n const absolutePath = assertSafeRelativePath(root, entry.path)\n if (entry.mode === '160000' || entry.mode === '040000') {\n throw new WorktreeAdapterError(\n `CodeSurface contains a Git submodule whose executable bytes are not bound: ${displayGitPath(entry.path)}`,\n )\n }\n if (entry.mode === '120000') {\n const stat = lstatSync(absolutePath)\n if (!stat.isSymbolicLink()) {\n throw new WorktreeAdapterError(\n `CodeSurface expected a symbolic link at ${displayGitPath(entry.path)}`,\n )\n }\n const targetBytes = readlinkSync(absolutePath, { encoding: 'buffer' })\n const actualObjectId = hashGitBlobBytes(targetBytes, entry.objectId)\n if (actualObjectId !== entry.objectId) {\n throw new WorktreeAdapterError(\n `CodeSurface raw symbolic-link bytes differ from the candidate tree at ${displayGitPath(entry.path)}`,\n )\n }\n assertSymlinkTargetIsBound(root, absolutePath, trackedPaths)\n continue\n }\n if (entry.mode !== '100644' && entry.mode !== '100755') {\n throw new WorktreeAdapterError(\n `CodeSurface contains unsupported Git mode ${entry.mode} at ${displayGitPath(entry.path)}`,\n )\n }\n\n const actual = hashGitBlobFile(absolutePath, entry.objectId)\n if (actual.hash !== entry.objectId) {\n throw new WorktreeAdapterError(\n `CodeSurface raw tracked bytes differ from the candidate tree because the worktree changed after finalization at ${displayGitPath(entry.path)}`,\n )\n }\n if (process.platform !== 'win32' && actual.executable !== (entry.mode === '100755')) {\n throw new WorktreeAdapterError(\n `CodeSurface executable mode differs from the candidate tree at ${displayGitPath(entry.path)}`,\n )\n }\n }\n}\n\nexport interface CodeSurfaceVerification {\n /** Verified worktree path. */\n path: string\n /** Git's canonical root for the verified checkout. */\n repoRoot: string\n /** Recomputed full content identity. */\n contentHash: `sha256:${string}`\n /** Exact verified binary-patch bytes. Candidate-bundle builders encode this\n * directly instead of reproducing Git diff options. */\n patchBytes: Uint8Array\n}\n\nfunction verifyCodeSurfaceWithGit(\n surface: CodeSurface,\n path: string,\n git: GitRunner,\n): CodeSurfaceVerification {\n assertCodeSurfaceIdentity(surface)\n if (!existsSync(path)) {\n throw new WorktreeAdapterError(`CodeSurface worktree does not exist: ${path}`)\n }\n const lexicalRoot = resolve(path)\n const canonicalRoot = realpathSync(path)\n if (\n lstatSync(lexicalRoot).isSymbolicLink() ||\n (process.platform !== 'win32' && lexicalRoot !== canonicalRoot)\n ) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree locator must not contain a symbolic link: ${path}`,\n )\n }\n const repoRoot = gitText(git, ['rev-parse', '--show-toplevel'], path)\n const canonicalRepoRoot = realpathSync(repoRoot)\n if (canonicalRepoRoot !== canonicalRoot) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree locator is not the repository root: expected ${repoRoot}, got ${path}`,\n )\n }\n\n const indexFlags = gitText(git, ['ls-files', '-v'], path)\n .split('\\n')\n .filter((line) => line.length > 0 && (line.startsWith('S ') || /^[a-z]/.test(line)))\n if (indexFlags.length > 0) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree uses hidden index entries that cannot be verified: ${path}\\n${indexFlags.join('\\n')}`,\n )\n }\n\n const extraPaths = [\n ...parseGitPathList(gitBytes(git, ['ls-files', '--others', '--exclude-standard', '-z'], path)),\n ...parseGitPathList(\n gitBytes(git, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z'], path),\n ),\n ]\n if (extraPaths.length > 0) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree changed after finalization: ${path}\\n${extraPaths.join('\\n')}`,\n )\n }\n\n const candidateCommit = resolveCommit(git, path, 'HEAD')\n if (candidateCommit !== surface.candidateCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface candidate commit mismatch: expected ${surface.candidateCommit}, got ${candidateCommit}`,\n )\n }\n\n const baseCommit = resolveCommit(git, path, surface.baseCommit)\n if (baseCommit !== surface.baseCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface base commit mismatch: expected ${surface.baseCommit}, got ${baseCommit}`,\n )\n }\n\n const baseTree = gitText(git, ['rev-parse', '--verify', `${surface.baseCommit}^{tree}`], path)\n if (baseTree !== surface.baseTree) {\n throw new WorktreeAdapterError(\n `CodeSurface base tree mismatch: expected ${surface.baseTree}, got ${baseTree}`,\n )\n }\n\n const candidateTree = gitText(\n git,\n ['rev-parse', '--verify', `${surface.candidateCommit}^{tree}`],\n path,\n )\n if (candidateTree !== surface.candidateTree) {\n throw new WorktreeAdapterError(\n `CodeSurface tree mismatch: expected ${surface.candidateTree}, got ${candidateTree}`,\n )\n }\n\n try {\n gitText(\n git,\n [\n 'diff-index',\n '--cached',\n '--quiet',\n '--no-ext-diff',\n '--no-textconv',\n surface.candidateCommit,\n '--',\n ],\n path,\n )\n } catch (err) {\n throw new WorktreeAdapterError(\n `CodeSurface index differs from finalized candidate: ${path}`,\n err,\n )\n }\n\n try {\n assertRawTreeMatchesWorktree(git, canonicalRepoRoot, surface.candidateCommit)\n } catch (err) {\n if (err instanceof WorktreeAdapterError) throw err\n throw new WorktreeAdapterError(`CodeSurface raw tree verification failed: ${path}`, err)\n }\n\n const mergeBase = gitText(git, ['merge-base', surface.baseCommit, surface.candidateCommit], path)\n if (mergeBase !== surface.baseCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface candidate ${surface.candidateCommit} does not descend from base ${surface.baseCommit}`,\n )\n }\n\n const patch = patchBytes(git, path, surface.baseCommit, surface.candidateCommit)\n const actualPatchHash = sha256(patch)\n if (actualPatchHash !== surface.patch.sha256 || patch.byteLength !== surface.patch.byteLength) {\n throw new WorktreeAdapterError(\n `CodeSurface patch mismatch: expected ${surface.patch.sha256}/${surface.patch.byteLength} bytes, got ${actualPatchHash}/${patch.byteLength} bytes`,\n )\n }\n\n return {\n path,\n repoRoot: canonicalRepoRoot,\n contentHash: surfaceContentHash(surface),\n patchBytes: new Uint8Array(patch),\n }\n}\n\n/** Slugify a label into a branch-safe segment. */\nfunction slug(label: string): string {\n return (\n label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 48) || 'candidate'\n )\n}\n\n/**\n * Git-backed `WorktreeAdapter`: creates isolated worktrees on fresh branches, commits agent changes, and discards losers.\n */\nexport function gitWorktreeAdapter(opts: GitWorktreeAdapterOptions): WorktreeAdapter {\n const git = opts.git ?? defaultGit\n const worktreeDir = opts.worktreeDir ?? join(opts.repoRoot, '.worktrees')\n const branchPrefix = opts.branchPrefix ?? 'improve'\n\n return {\n async create({ baseRef, label }) {\n const id = `${slug(label)}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`\n const branch = `${branchPrefix}/${id}`\n const path = join(worktreeDir, id)\n const baseCommit = resolveCommit(git, opts.repoRoot, baseRef)\n const baseTree = gitText(\n git,\n ['rev-parse', '--verify', `${baseCommit}^{tree}`],\n opts.repoRoot,\n )\n gitText(git, ['worktree', 'add', '-b', branch, path, baseCommit], opts.repoRoot)\n return {\n path: realpathSync(resolve(opts.repoRoot, path)),\n branch,\n baseRef,\n baseCommit,\n baseTree,\n }\n },\n\n async finalize(worktree, summary) {\n // Stage + commit any pending changes the agent left in the worktree.\n // A no-op commit is refused by git, so only commit when the tree is dirty.\n const status = gitText(\n git,\n ['status', '--porcelain=v1', '--untracked-files=all'],\n worktree.path,\n )\n if (status.length > 0) {\n gitText(git, ['add', '-A'], worktree.path)\n gitText(git, ['commit', '-m', summary], worktree.path)\n }\n const candidateCommit = resolveCommit(git, worktree.path, 'HEAD')\n const candidateTree = gitText(\n git,\n ['rev-parse', '--verify', `${candidateCommit}^{tree}`],\n worktree.path,\n )\n const patch = patchBytes(git, worktree.path, worktree.baseCommit, candidateCommit)\n const surface: CodeSurface = {\n kind: 'code',\n worktreeRef: worktree.path,\n baseRef: worktree.baseRef,\n baseCommit: worktree.baseCommit,\n baseTree: worktree.baseTree,\n candidateCommit,\n candidateTree,\n patch: {\n format: 'git-diff-binary',\n sha256: sha256(patch),\n byteLength: patch.byteLength,\n },\n summary,\n }\n verifyCodeSurfaceWithGit(surface, worktree.path, git)\n return surface\n },\n\n async discard(worktree) {\n // Reconcile both resources independently so a retry can finish cleanup\n // after either command succeeded alone. Force-remove because the worktree\n // may hold uncommitted experiment state we're discarding.\n const failures = [\n reconcileAbsent(\n () => hasRegisteredWorktree(git, opts.repoRoot, worktree.path),\n () => gitText(git, ['worktree', 'remove', '--force', '--', worktree.path], opts.repoRoot),\n ),\n reconcileAbsent(\n () => hasLocalBranch(git, opts.repoRoot, worktree.branch),\n () => gitText(git, ['branch', '-D', '--', worktree.branch], opts.repoRoot),\n ),\n ].filter((failure) => failure !== undefined)\n\n if (failures.length > 0) {\n const cause =\n failures.length === 1\n ? failures[0]\n : new AggregateError(failures, 'Multiple Git resources could not be removed')\n throw new WorktreeAdapterError(\n `Failed to discard worktree ${worktree.path} and branch ${worktree.branch}`,\n cause,\n )\n }\n },\n }\n}\n\n/** Verify a finalized code surface against its current checkout. This rejects\n * dirty/ignored files, moved refs, missing Git objects, raw byte/mode\n * mismatches, external symlinks, and submodules. */\nexport function verifyCodeSurface(\n surface: CodeSurface,\n worktreeDir?: string,\n): CodeSurfaceVerification {\n const path = unresolvedWorktreePath(surface, worktreeDir)\n return verifyCodeSurfaceWithGit(surface, path, defaultGit)\n}\n\n/** Resolve a code candidate for evaluation only after verifying its immutable\n * identity against the checkout at `worktreeRef`. */\nexport function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string {\n return verifyCodeSurface(surface, worktreeDir).path\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsB,oBAAoB,OAKf;CACzB,MAAM,UAAoC,CAAC;CAC3C,MAAM,UAAU;EAAE,MAAM;EAAc,KAAK;CAAK;CAChD,IAAI,MAAM,cAAc,KAAA,GAAW,OAAO,MAAM,WAAW,WAAW;CACtE,MAAM,SAAwB;EAC5B,QAAQ,MAAM,cAAc,KAAA,IAAY,UAAU;GAAE,MAAM;GAAY,KAAK,MAAM;EAAU;EAC3F,SAAS;EACT,aAAa;GAAE,MAAM;GAAc,SAAS;GAAM,QAAQ;EAAyB;EACnF;CACF;CACA,MAAM,OAAO,OAAO,QAAgB;EAClC,MAAM,WAAW,MAA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AAK,UAAU,SAAS,MAAM,SAClD,QAAQ,KAAK;IAAC;IAAU;IAAM;IAAM,SAAS;GAAM,GAAG,KAAK,QAAQ,CAC3E,CACF,CAAC,CAAC,QAAQ,YAAY,YAAY,KAAA,CAAS;GAE3C,IAAI,SAAS,SAAS,GAAG;IACvB,MAAM,QACJ,SAAS,WAAW,IAChB,SAAS,KACT,IAAI,eAAe,UAAU,6CAA6C;IAChF,MAAM,IAAI,qBACR,8BAA8B,SAAS,KAAK,cAAc,SAAS,UACnE,KACF;GACF;EACF;CACF;AACF;;;;AAKA,SAAgB,kBACd,SACA,aACyB;CAEzB,OAAO,yBAAyB,SADnB,uBAAuB,SAAS,WACD,GAAG,UAAU;AAC3D;;;AAIA,SAAgB,oBAAoB,SAAsB,aAA8B;CACtF,OAAO,kBAAkB,SAAS,WAAW,CAAC,CAAC;AACjD"}
|
|
1
|
+
{"version":3,"file":"campaign-CE08mvQO.js","names":["validateAndIndex","rowFor","componentSetKey","rowsFor","canonicalComponents","difficulty","calibration","scoreOf","esc","fsConstants"],"sources":["../src/campaign/cost-breakdown.ts","../src/campaign/cross-surface-context.ts","../src/campaign/cross-surface-evidence.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/neutralize.ts","../src/campaign/optimization-method-composition.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/profile-matrix-stability.ts","../src/campaign/presets/profile-matrix-analysis.ts","../src/campaign/presets/profile-matrix-report.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/segmented-profile-matrix.ts","../src/campaign/presets/race-profile-matrix.ts","../src/campaign/repeat-reliability.ts","../src/campaign/retained-dispatch.ts","../src/campaign/scenario-selection.ts","../src/campaign/worktree/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { CostBreakdown, CostUsage } from '../cost-ledger'\n\n/** Read the source rates for this execution, never a copied model price table.\n * inputTokens includes cachedTokens. Seat credits are standard model credits;\n * discounts and MCP charges require provider observations, not token guesses.\n * The existing USD receipt remains the Router charge. Sandbox is additional.\n */\nexport async function measureCampaignCost(input: {\n routerUsd?: number\n sandbox?: { seconds: number; cpu: number; memoryGB: number; diskGB: number; pool?: string }\n seat?: { model: string; usage: CostUsage & { usageUnknown?: boolean } }\n signal?: AbortSignal\n}): Promise<CostBreakdown> {\n const sources: CostBreakdown['sources'] = []\n const unknown = { kind: 'uncaptured', usd: null } as const\n if (input.routerUsd !== undefined) finite(input.routerUsd, 'routerUsd')\n const result: CostBreakdown = {\n router: input.routerUsd === undefined ? unknown : { kind: 'observed', usd: input.routerUsd },\n sandbox: unknown,\n seatCredits: { kind: 'uncaptured', credits: null, reason: 'No seat usage supplied' },\n sources,\n }\n const read = async (url: string) => {\n const response = await fetch(url, {\n signal: input.signal\n ? AbortSignal.any([input.signal, AbortSignal.timeout(15_000)])\n : AbortSignal.timeout(15_000),\n })\n if (!response.ok) throw new Error(`Rate source HTTP ${response.status}`)\n // Refuse a changed/unbounded document rather than importing arbitrary data.\n if (Number(response.headers.get('content-length')) > 1_000_000)\n throw new Error('Rate source too large')\n const chunks: Uint8Array[] = []\n let bytes = 0\n for await (const chunk of response.body ?? []) {\n bytes += chunk.byteLength\n if (bytes > 1_000_000) throw new Error('Rate source too large')\n chunks.push(chunk)\n }\n const text = Buffer.concat(chunks).toString('utf8')\n return {\n text,\n snapshot: {\n url,\n readAt: new Date().toISOString(),\n sha256: createHash('sha256').update(text).digest('hex'),\n },\n }\n }\n if (input.sandbox) {\n for (const [key, value] of Object.entries(input.sandbox))\n if (key !== 'pool') finite(value, `sandbox.${key}`)\n try {\n const { text, snapshot } = await read('https://sandbox.tangle.tools/v1/pricing/sandboxes')\n const card = JSON.parse(text).pools?.[input.sandbox.pool ?? 'general']\n const rates: Record<string, number> = {}\n for (const key of [\n 'cpuCoreHourUsd',\n 'memoryGBHourUsd',\n 'diskGBHourUsd',\n 'minChargeHourUsd',\n ]) {\n finite(card?.[key], key)\n rates[key] = card[key]\n }\n const s = input.sandbox\n const hourly = Math.max(\n rates.minChargeHourUsd!,\n s.cpu * rates.cpuCoreHourUsd! +\n s.memoryGB * rates.memoryGBHourUsd! +\n s.diskGB * rates.diskGBHourUsd!,\n )\n const usd = (hourly * s.seconds) / 3600\n finite(usd, 'sandbox USD estimate')\n result.sandbox = { kind: 'estimated', usd }\n sources.push({ ...snapshot, rates })\n } catch {\n // A missing rate leaves the estimate unknown while preserving Router observations.\n }\n }\n if (input.seat) {\n const { usage, model } = input.seat\n if (usage.usageUnknown || usage.cachedTokens === undefined) {\n result.seatCredits = {\n kind: 'uncaptured',\n credits: null,\n reason: 'Seat token or cached-input usage is unknown',\n }\n return result\n }\n for (const key of ['inputTokens', 'cachedTokens', 'outputTokens'] as const) {\n const value = usage[key]\n if (!Number.isSafeInteger(value) || value! < 0)\n throw new Error(`seat.${key} must be a known nonnegative token count`)\n }\n if (usage.cachedTokens! > usage.inputTokens) throw new Error('cachedTokens exceeds inputTokens')\n try {\n const { text, snapshot } = await read('https://docs.z.ai/devpack/overview.md')\n const modelName = model.split('/').at(-1)!.toLowerCase()\n const section = text\n .split('#### Credit Calculation')[1]\n ?.split('#### Estimated Token Allowance')[0]\n if (!section) throw new Error('Credit calculation section unavailable')\n const rows = [...section.matchAll(/<tr>\\s*([\\s\\S]*?)<\\/tr>/gu)]\n const matching = rows.filter((row) => {\n const cells = [...row[1]!.matchAll(/<td\\b[^>]*>([\\s\\S]*?)<\\/td>/gu)].map((cell) =>\n cell[1]!.trim(),\n )\n return cells.some(\n (cell) =>\n cell\n .split(/\\\\|\\n|</u)[0]!\n .trim()\n .toLowerCase() === modelName,\n )\n })\n if (matching.length !== 1) throw new Error(`No unique live credit row for '${model}'`)\n const cells = [...matching[0]![1]!.matchAll(/<td\\b[^>]*>([\\s\\S]*?)<\\/td>/gu)].map((cell) =>\n cell[1]!.trim(),\n )\n const rateCells = cells.slice(-3)\n if (rateCells.length !== 3 || rateCells.some((cell) => !/^(?:\\d+)(?:\\.\\d+)?$/u.test(cell)))\n throw new Error('Invalid live credit multipliers')\n const multipliers = rateCells.map(Number)\n for (const rate of multipliers) finite(rate, 'credit multiplier')\n const divisor = Number(\n section.match(/Model credit usage[^\\n]*\\/\\s*([\\d,]+)/u)?.[1]?.replaceAll(',', ''),\n )\n if (!Number.isFinite(divisor) || divisor <= 0) throw new Error('No live credit divisor')\n const [fresh, cached, output] = multipliers as [number, number, number]\n const credits =\n ((usage.inputTokens - usage.cachedTokens!) * fresh +\n usage.cachedTokens! * cached +\n usage.outputTokens * output) /\n divisor\n finite(credits, 'standard seat credits')\n result.seatCredits = { kind: 'estimated', credits }\n sources.push({\n ...snapshot,\n rates: {\n inputMultiplier: fresh,\n cachedInputMultiplier: cached,\n outputMultiplier: output,\n divisor,\n },\n })\n } catch (error) {\n result.seatCredits = {\n kind: 'uncaptured',\n credits: null,\n reason: error instanceof Error ? error.message : 'Credit source unavailable',\n }\n }\n }\n return result\n}\n\nfunction finite(value: unknown, label: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)\n throw new Error(`${label} must be finite and nonnegative`)\n}\n","import { ValidationError } from '../errors'\nimport type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceCandidate,\n CrossSurfaceComponent,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\n/** Validated indexes shared by analysis and deterministic selection. */\nexport interface CrossSurfaceAnalysisContext<TRow extends CrossSurfaceTaskRow> {\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>\n components: CrossSurfaceComponent[]\n candidates: CrossSurfaceCandidate[]\n componentById: Map<string, CrossSurfaceComponent>\n candidateById: Map<string, CrossSurfaceCandidate>\n candidateByComponents: Map<string, CrossSurfaceCandidate>\n singleByComponent: Map<string, CrossSurfaceCandidate>\n rowsByCandidate: Map<string, Map<string, TRow>>\n componentIndex: Map<string, number>\n candidateIndex: Map<string, number>\n}\n\nexport function validateCrossSurfaceInput<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): CrossSurfaceAnalysisContext<TRow> {\n assertNonEmptyUnique(input.taskOrder, 'taskOrder')\n assertNonEmptyUnique(input.componentOrder, 'componentOrder')\n if (input.componentOrder.length < 2) {\n throw new ValidationError(\n 'analyzeCrossSurfaceInteractions: componentOrder must contain at least two surfaces',\n )\n }\n assertNonEmptyUnique(input.candidateOrder, 'candidateOrder')\n assertNonEmptyUnique(input.costMetricOrder, 'costMetricOrder')\n if (input.costMetricOrder.includes('score')) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: costMetricOrder cannot contain reserved metric 'score'`,\n )\n }\n validateBootstrap(input)\n validateSelection(input)\n\n const componentById = indexUnique(\n input.components,\n (component) => component.componentId,\n 'component',\n )\n assertExactSet(input.componentOrder, componentById.keys(), 'componentOrder', 'components')\n const surfaces = new Set<string>()\n for (const component of componentById.values()) {\n assertNonEmpty(component.componentId, 'componentId')\n assertNonEmpty(component.surfaceId, `surfaceId for component '${component.componentId}'`)\n if (surfaces.has(component.surfaceId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: surfaceId '${component.surfaceId}' has more than one component; ` +\n 'the interaction stage requires one independently selected finalist per surface',\n )\n }\n surfaces.add(component.surfaceId)\n if (typeof component.bestSingleEligible !== 'boolean') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: component '${component.componentId}' must declare bestSingleEligible`,\n )\n }\n }\n\n const componentIndex = new Map(input.componentOrder.map((id, index) => [id, index]))\n const candidateById = indexUnique(\n input.candidates,\n (candidate) => candidate.candidateId,\n 'candidate',\n )\n assertExactSet(input.candidateOrder, candidateById.keys(), 'candidateOrder', 'candidates')\n if (!candidateById.has(input.baselineCandidateId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: unknown baselineCandidateId '${input.baselineCandidateId}'`,\n )\n }\n\n const candidateByComponents = new Map<string, CrossSurfaceCandidate>()\n const singleByComponent = new Map<string, CrossSurfaceCandidate>()\n for (const candidate of candidateById.values()) {\n validateCandidate(candidate, componentById, componentIndex, input.baselineCandidateId)\n const key = crossSurfaceComponentSetKey(candidate.componentIds)\n const duplicate = candidateByComponents.get(key)\n if (duplicate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidates '${duplicate.candidateId}' and ` +\n `'${candidate.candidateId}' materialize the same component set`,\n )\n }\n candidateByComponents.set(key, candidate)\n if (candidate.componentIds.length === 1) {\n singleByComponent.set(candidate.componentIds[0]!, candidate)\n }\n }\n const baseline = candidateById.get(input.baselineCandidateId)!\n if (baseline.componentIds.length !== 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: baseline '${baseline.candidateId}' must have zero components`,\n )\n }\n for (const componentId of input.componentOrder) {\n if (!singleByComponent.has(componentId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: no single-surface candidate for component '${componentId}'`,\n )\n }\n }\n for (let left = 0; left < input.componentOrder.length; left++) {\n for (let right = left + 1; right < input.componentOrder.length; right++) {\n const ids = [input.componentOrder[left]!, input.componentOrder[right]!]\n if (!candidateByComponents.has(crossSurfaceComponentSetKey(ids))) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: missing pair candidate for components [${ids.join(', ')}]`,\n )\n }\n }\n }\n\n const rowsByCandidate = new Map<string, Map<string, TRow>>()\n const taskIds = new Set(input.taskOrder)\n for (const row of input.rows) {\n const candidate = candidateById.get(row.candidateId)\n if (!candidate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row for task '${row.taskId}' names unknown candidate '${row.candidateId}'`,\n )\n }\n if (!taskIds.has(row.taskId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row for candidate '${row.candidateId}' names task '${row.taskId}' ` +\n 'outside the declared taskOrder',\n )\n }\n validateRow(input, row, candidate)\n const byTask = rowsByCandidate.get(row.candidateId) ?? new Map<string, TRow>()\n if (byTask.has(row.taskId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: duplicate row for candidate '${row.candidateId}' and task '${row.taskId}'`,\n )\n }\n byTask.set(row.taskId, row)\n rowsByCandidate.set(row.candidateId, byTask)\n }\n for (const candidateId of input.candidateOrder) {\n const byTask = rowsByCandidate.get(candidateId)\n const missing = input.taskOrder.filter((taskId) => !byTask?.has(taskId))\n if (missing.length > 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidateId}' is missing declared task row(s) ` +\n `[${missing.join(', ')}]; encode failed attempts explicitly instead of changing the task axis`,\n )\n }\n }\n const expectedRows = input.candidateOrder.length * input.taskOrder.length\n if (input.rows.length !== expectedRows) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: expected exactly ${expectedRows} candidate × task rows, got ${input.rows.length}`,\n )\n }\n\n return {\n input,\n components: input.componentOrder.map((id) => componentById.get(id)!),\n candidates: input.candidateOrder.map((id) => candidateById.get(id)!),\n componentById,\n candidateById,\n candidateByComponents,\n singleByComponent,\n rowsByCandidate,\n componentIndex,\n candidateIndex: new Map(input.candidateOrder.map((id, index) => [id, index])),\n }\n}\n\nexport function crossSurfaceRowsFor<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n candidateId: string,\n): TRow[] {\n return context.input.taskOrder.map((taskId) => crossSurfaceRowFor(context, candidateId, taskId))\n}\n\nexport function crossSurfaceRowFor<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n candidateId: string,\n taskId: string,\n): TRow {\n return context.rowsByCandidate.get(candidateId)!.get(taskId)!\n}\n\nexport function canonicalCrossSurfaceComponents<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n componentIds: string[],\n): string[] {\n return [...componentIds].sort(\n (left, right) => context.componentIndex.get(left)! - context.componentIndex.get(right)!,\n )\n}\n\nexport function crossSurfaceComponentSetKey(componentIds: readonly string[]): string {\n return JSON.stringify(componentIds)\n}\n\nfunction validateBootstrap<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): void {\n const { seed, resamples, confidence } = input.bootstrap\n if (!Number.isInteger(seed)) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: bootstrap.seed must be an integer`)\n }\n if (!Number.isInteger(resamples) || resamples <= 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: bootstrap.resamples must be a positive integer`,\n )\n }\n if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: bootstrap.confidence must be in (0,1)`,\n )\n }\n}\n\nfunction validateSelection<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): void {\n const policy = input.selection\n for (const [name, value] of [\n ['minimumFiringTasks', policy.minimumFiringTasks],\n ['minimumEffectTasks', policy.minimumEffectTasks],\n ] as const) {\n if (!Number.isInteger(value) || value < 0 || value > input.taskOrder.length) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: selection.${name} must be an integer in [0,${input.taskOrder.length}]`,\n )\n }\n }\n if (\n !Number.isInteger(policy.minimumBundleComponents) ||\n policy.minimumBundleComponents < 2 ||\n policy.minimumBundleComponents > input.componentOrder.length\n ) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: selection.minimumBundleComponents must be an integer in ` +\n `[2,${input.componentOrder.length}]`,\n )\n }\n for (const [metric, limit] of Object.entries(policy.maximumMedianCostRatioToBaseline)) {\n if (!input.costMetricOrder.includes(metric)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: cost limit names undeclared metric '${metric}'`,\n )\n }\n if (!Number.isFinite(limit) || limit <= 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: cost ratio limit for '${metric}' must be positive and finite`,\n )\n }\n }\n}\n\nfunction validateCandidate(\n candidate: CrossSurfaceCandidate,\n componentById: Map<string, CrossSurfaceComponent>,\n componentIndex: Map<string, number>,\n baselineCandidateId: string,\n): void {\n assertNonEmpty(candidate.candidateId, 'candidateId')\n assertNonEmpty(candidate.contentHash, `contentHash for candidate '${candidate.candidateId}'`)\n if (!Number.isInteger(candidate.artifactBytes) || candidate.artifactBytes < 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: artifactBytes for candidate '${candidate.candidateId}' must be a non-negative integer`,\n )\n }\n assertUnique(candidate.componentIds, `componentIds for candidate '${candidate.candidateId}'`)\n for (const componentId of candidate.componentIds) {\n if (!componentById.has(componentId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidate.candidateId}' names unknown component '${componentId}'`,\n )\n }\n }\n const canonical = [...candidate.componentIds].sort(\n (left, right) => componentIndex.get(left)! - componentIndex.get(right)!,\n )\n if (!arraysEqual(candidate.componentIds, canonical)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidate.candidateId}' components must follow componentOrder`,\n )\n }\n if (candidate.candidateId !== baselineCandidateId && candidate.componentIds.length === 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: only baseline '${baselineCandidateId}' may have zero components`,\n )\n }\n}\n\nfunction validateRow<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n row: TRow,\n candidate: CrossSurfaceCandidate,\n): void {\n if (!arraysEqual(row.componentIds, candidate.componentIds)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row '${row.candidateId}/${row.taskId}' componentIds do not match its candidate`,\n )\n }\n if (!['complete', 'missing', 'invalid'].includes(row.completeness)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row '${row.candidateId}/${row.taskId}' has unknown completeness '${String(row.completeness)}'`,\n )\n }\n if (row.completeness === 'complete') {\n if (typeof row.pass !== 'boolean' || !Number.isFinite(row.score)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: complete row '${row.candidateId}/${row.taskId}' requires boolean pass and finite score`,\n )\n }\n if (row.rejectReason !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: complete row '${row.candidateId}/${row.taskId}' cannot carry rejectReason`,\n )\n }\n } else {\n if (row.pass !== null || row.score !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${row.completeness} row '${row.candidateId}/${row.taskId}' must use null pass and score`,\n )\n }\n if (typeof row.rejectReason !== 'string' || row.rejectReason.trim() === '') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${row.completeness} row '${row.candidateId}/${row.taskId}' requires rejectReason`,\n )\n }\n }\n assertExactSet(\n input.costMetricOrder,\n Object.keys(row.cost),\n `cost keys for row '${row.candidateId}/${row.taskId}'`,\n 'costMetricOrder',\n )\n for (const metric of input.costMetricOrder) {\n const value = row.cost[metric]\n if (value === null || value === undefined || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: unknown or invalid cost '${metric}' on row ` +\n `'${row.candidateId}/${row.taskId}'; every attempt must report a non-negative finite value`,\n )\n }\n }\n const evidenceByComponent = indexUnique(\n row.componentEvidence,\n (evidence) => evidence.componentId,\n `componentEvidence on row '${row.candidateId}/${row.taskId}'`,\n )\n assertExactSet(\n candidate.componentIds,\n evidenceByComponent.keys(),\n `componentEvidence on row '${row.candidateId}/${row.taskId}'`,\n 'candidate components',\n )\n for (const evidence of evidenceByComponent.values()) {\n assertTriState(evidence.fired, 'fired', row)\n assertTriState(evidence.effectObserved, 'effectObserved', row)\n if (evidence.effectObserved === true && evidence.fired !== true) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: effectObserved=true requires fired=true for component ` +\n `'${evidence.componentId}' on row '${row.candidateId}/${row.taskId}'`,\n )\n }\n }\n}\n\nfunction assertTriState<TRow extends CrossSurfaceTaskRow>(\n value: boolean | null,\n field: string,\n row: TRow,\n): void {\n if (value !== true && value !== false && value !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${field} on row '${row.candidateId}/${row.taskId}' must be boolean or null`,\n )\n }\n}\n\nfunction indexUnique<T>(\n items: readonly T[],\n id: (item: T) => string,\n label: string,\n): Map<string, T> {\n const result = new Map<string, T>()\n for (const item of items) {\n const key = id(item)\n assertNonEmpty(key, `${label} id`)\n if (result.has(key)) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: duplicate ${label} id '${key}'`)\n }\n result.set(key, item)\n }\n return result\n}\n\nfunction assertNonEmptyUnique(values: readonly string[], label: string): void {\n if (values.length === 0) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: ${label} is empty`)\n }\n assertUnique(values, label)\n for (const value of values) assertNonEmpty(value, label)\n}\n\nfunction assertUnique(values: readonly string[], label: string): void {\n if (new Set(values).size !== values.length) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: ${label} contains duplicates`)\n }\n}\n\nfunction assertNonEmpty(value: string, label: string): void {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${label} must be a non-empty string`,\n )\n }\n}\n\nfunction assertExactSet(\n expected: readonly string[],\n actualIterable: Iterable<string>,\n actualLabel: string,\n expectedLabel: string,\n): void {\n const actual = [...actualIterable]\n const expectedSet = new Set(expected)\n const actualSet = new Set(actual)\n const missing = expected.filter((value) => !actualSet.has(value))\n const extra = actual.filter((value) => !expectedSet.has(value))\n if (missing.length > 0 || extra.length > 0 || actual.length !== expected.length) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${actualLabel} does not match ${expectedLabel}; ` +\n `missing=[${missing.join(', ')}], extra=[${extra.join(', ')}]`,\n )\n }\n}\n\nfunction arraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n","import type {\n CrossSurfaceCandidateEvidence,\n CrossSurfaceEvidenceBreakdown,\n CrossSurfacePairEvidence,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\nexport function summarizeCandidateEvidence<TRow extends CrossSurfaceTaskRow>(\n rows: TRow[],\n componentIds: string[],\n field: 'fired' | 'effectObserved',\n): CrossSurfaceCandidateEvidence {\n if (componentIds.length === 0) {\n return {\n byComponent: [],\n allObservedTaskIds: [],\n someObservedTaskIds: [],\n noneObservedTaskIds: [],\n unobservedTaskIds: [],\n }\n }\n const byComponent: CrossSurfaceEvidenceBreakdown[] = componentIds.map((componentId) => {\n const observedTaskIds: string[] = []\n const notObservedTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const value = evidenceValue(row, componentId, field)\n if (value === true) observedTaskIds.push(row.taskId)\n else if (value === false) notObservedTaskIds.push(row.taskId)\n else unobservedTaskIds.push(row.taskId)\n }\n return { componentId, observedTaskIds, notObservedTaskIds, unobservedTaskIds }\n })\n const allObservedTaskIds: string[] = []\n const someObservedTaskIds: string[] = []\n const noneObservedTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const values = componentIds.map((componentId) => evidenceValue(row, componentId, field))\n if (values.some((value) => value === null)) unobservedTaskIds.push(row.taskId)\n else if (values.every(Boolean)) allObservedTaskIds.push(row.taskId)\n else if (values.some(Boolean)) someObservedTaskIds.push(row.taskId)\n else noneObservedTaskIds.push(row.taskId)\n }\n return {\n byComponent,\n allObservedTaskIds,\n someObservedTaskIds,\n noneObservedTaskIds,\n unobservedTaskIds,\n }\n}\n\nexport function summarizePairEvidence<TRow extends CrossSurfaceTaskRow>(\n rows: TRow[],\n leftComponentId: string,\n rightComponentId: string,\n field: 'fired' | 'effectObserved',\n): CrossSurfacePairEvidence {\n const bothTaskIds: string[] = []\n const leftOnlyTaskIds: string[] = []\n const rightOnlyTaskIds: string[] = []\n const neitherTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const left = evidenceValue(row, leftComponentId, field)\n const right = evidenceValue(row, rightComponentId, field)\n if (left === null || right === null) unobservedTaskIds.push(row.taskId)\n else if (left && right) bothTaskIds.push(row.taskId)\n else if (left) leftOnlyTaskIds.push(row.taskId)\n else if (right) rightOnlyTaskIds.push(row.taskId)\n else neitherTaskIds.push(row.taskId)\n }\n return {\n bothTaskIds,\n leftOnlyTaskIds,\n rightOnlyTaskIds,\n neitherTaskIds,\n unobservedTaskIds,\n }\n}\n\nfunction evidenceValue(\n row: CrossSurfaceTaskRow,\n componentId: string,\n field: 'fired' | 'effectObserved',\n): boolean | null {\n return row.componentEvidence.find((evidence) => evidence.componentId === componentId)![field]\n}\n\nexport function appendEvidenceReasons<TReason extends string>(\n reasons: TReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: TReason,\n unobservedReason: TReason,\n): void {\n if (evidence.byComponent.some((component) => component.observedTaskIds.length < minimum)) {\n reasons.push(belowReason)\n }\n if (\n requireObserved &&\n evidence.byComponent.some((component) => component.unobservedTaskIds.length > 0)\n ) {\n reasons.push(unobservedReason)\n }\n}\n","/**\n * Task-paired comparison and deterministic selection for independently\n * proposed agent surfaces. Unlike factorial cell-mean attribution, every\n * benefit, regression, and interaction remains attached to its task row.\n */\n\nimport { ValidationError } from '../errors'\nimport { comparePairedArms, type PairedArmRow, type PairedArmsComparison } from '../paired-arms'\nimport { pairedBootstrap } from '../statistics'\nimport { meanOrNull } from '../statistics/mean'\nimport {\n type CrossSurfaceAnalysisContext as AnalysisContext,\n canonicalCrossSurfaceComponents as canonicalComponents,\n crossSurfaceComponentSetKey as componentSetKey,\n crossSurfaceRowFor as rowFor,\n crossSurfaceRowsFor as rowsFor,\n validateCrossSurfaceInput as validateAndIndex,\n} from './cross-surface-context'\nimport {\n appendEvidenceReasons as appendBundleEvidenceReasons,\n appendEvidenceReasons as appendEvidenceEligibilityReasons,\n summarizeCandidateEvidence,\n summarizePairEvidence,\n} from './cross-surface-evidence'\nimport type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceAdditionDecision,\n CrossSurfaceAdditionRejectionReason,\n CrossSurfaceCandidate,\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateOutcome,\n CrossSurfaceCandidateSummary,\n CrossSurfaceCompositionStep,\n CrossSurfaceDistribution,\n CrossSurfaceEligibility,\n CrossSurfaceIneligibilityReason,\n CrossSurfaceInteractionAwareSelection,\n CrossSurfaceInteractionEffect,\n CrossSurfaceInteractionPath,\n CrossSurfaceInteractionReport,\n CrossSurfaceNaiveStackSelection,\n CrossSurfacePairCompatibility,\n CrossSurfacePairEvidence,\n CrossSurfacePairIncompatibilityReason,\n CrossSurfacePairwiseEntry,\n CrossSurfaceRankedSingle,\n CrossSurfaceRelativeCost,\n CrossSurfaceSelections,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\n/**\n * Build the complete cross-surface evidence matrix and derive all three frozen\n * candidates. The task/candidate/component orders are part of the input so\n * neither insertion order nor an after-the-fact tie-break can change a result.\n */\nexport function analyzeCrossSurfaceInteractions<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): CrossSurfaceInteractionReport<TRow> {\n const context = validateAndIndex(input)\n const baseline = context.candidateById.get(input.baselineCandidateId)!\n\n const preliminary = context.candidates.map((candidate) =>\n summarizeCandidate(context, candidate, baseline),\n )\n const baselineSummary = preliminary.find(\n (summary) => summary.candidate.candidateId === input.baselineCandidateId,\n )!\n const summaries = preliminary.map((summary) =>\n summary.candidate.candidateId === input.baselineCandidateId\n ? summary\n : {\n ...summary,\n eligibility: candidateEligibility(context, summary, baselineSummary),\n },\n )\n const summaryById = new Map(summaries.map((summary) => [summary.candidate.candidateId, summary]))\n const eligibleSingles = rankedEligibleSingles(context, summaryById)\n const interactionReadySingles = rankedInteractionReadySingles(context, summaryById)\n const pairwise = buildPairwise(context, summaryById, interactionReadySingles, baselineSummary)\n const selections = selectCandidates(\n context,\n summaryById,\n eligibleSingles,\n interactionReadySingles,\n pairwise,\n )\n const rows = context.candidates.flatMap((candidate) =>\n input.taskOrder.map(\n (taskId) => context.rowsByCandidate.get(candidate.candidateId)!.get(taskId)!,\n ),\n )\n\n return {\n taskIds: [...input.taskOrder],\n componentIds: [...input.componentOrder],\n candidateIds: [...input.candidateOrder],\n costMetrics: [...input.costMetricOrder],\n rows,\n missingAttempts: rows.filter((row) => row.completeness === 'missing'),\n invalidAttempts: rows.filter((row) => row.completeness === 'invalid'),\n candidates: summaries,\n pairwise,\n selections,\n }\n}\n\nfunction compareCandidates<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n comparatorCandidateId: string,\n treatmentCandidateId: string,\n): CrossSurfaceCandidateComparison {\n const winsTaskIds: string[] = []\n const regressionTaskIds: string[] = []\n const missingTaskIds: string[] = []\n for (const taskId of context.input.taskOrder) {\n const comparator = rowFor(context, comparatorCandidateId, taskId)\n const treatment = rowFor(context, treatmentCandidateId, taskId)\n if (comparator.completeness !== 'complete' || treatment.completeness !== 'complete') {\n missingTaskIds.push(taskId)\n } else if (treatment.pass && !comparator.pass) winsTaskIds.push(taskId)\n else if (!treatment.pass && comparator.pass) regressionTaskIds.push(taskId)\n }\n return {\n comparatorCandidateId,\n treatmentCandidateId,\n winsTaskIds,\n regressionTaskIds,\n missingTaskIds,\n paired: pairedComparison(context, comparatorCandidateId, treatmentCandidateId),\n relativeCost: relativeCosts(\n context,\n summaryById.get(treatmentCandidateId)!,\n summaryById.get(comparatorCandidateId)!,\n ),\n }\n}\n\nfunction pairedComparison<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n comparatorCandidateId: string,\n treatmentCandidateId: string,\n): PairedArmsComparison {\n const rows: PairedArmRow[] = []\n for (const taskId of context.input.taskOrder) {\n rows.push(toPairedArmRow(context, rowFor(context, comparatorCandidateId, taskId)))\n rows.push(toPairedArmRow(context, rowFor(context, treatmentCandidateId, taskId)))\n }\n return comparePairedArms(rows, {\n baselineArm: comparatorCandidateId,\n treatmentArm: treatmentCandidateId,\n metricNames: ['score', ...context.input.costMetricOrder],\n bootstrap: { ...context.input.bootstrap, statistic: 'mean' },\n })\n}\n\nfunction toPairedArmRow<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n row: TRow,\n): PairedArmRow {\n const metrics: Record<string, number> = Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [metric, row.cost[metric] as number]),\n )\n if (row.completeness === 'complete') metrics.score = row.score as number\n return {\n pairKey: row.taskId,\n arm: row.candidateId,\n ...(row.completeness === 'complete' ? { pass: row.pass as boolean } : {}),\n metrics,\n }\n}\n\nfunction relativeCosts<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n treatment: CrossSurfaceCandidateSummary,\n comparator: CrossSurfaceCandidateSummary,\n): Record<string, CrossSurfaceRelativeCost> {\n return Object.fromEntries(\n context.input.costMetricOrder.map((metric) => {\n const treatmentMedian = treatment.costs[metric]!.median\n const comparatorMedian = comparator.costs[metric]!.median\n return [\n metric,\n {\n treatmentMedian,\n comparatorMedian,\n medianDelta: treatmentMedian - comparatorMedian,\n medianRatio:\n comparatorMedian === 0\n ? treatmentMedian === 0\n ? 1\n : null\n : treatmentMedian / comparatorMedian,\n },\n ]\n }),\n )\n}\n\nfunction withinCostLimits<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n treatment: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n): boolean {\n const relative = relativeCosts(context, treatment, baseline)\n return Object.entries(context.input.selection.maximumMedianCostRatioToBaseline).every(\n ([metric, limit]) => {\n const ratio = relative[metric]!.medianRatio\n return ratio !== null && ratio <= limit\n },\n )\n}\n\nfunction distribution(values: number[]): CrossSurfaceDistribution {\n const sorted = [...values].sort((left, right) => left - right)\n const total = sorted.reduce((sum, value) => sum + value, 0)\n const middle = Math.floor(sorted.length / 2)\n const median =\n sorted.length % 2 === 1 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2\n return {\n n: sorted.length,\n min: sorted[0]!,\n median,\n mean: total / sorted.length,\n max: sorted[sorted.length - 1]!,\n total,\n }\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n\nfunction buildPairwise<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n baseline: CrossSurfaceCandidateSummary,\n): CrossSurfacePairwiseEntry[] {\n const interactionReadyIds = new Set(\n interactionReadySingles.map((summary) => summary.candidate.candidateId),\n )\n const entries: CrossSurfacePairwiseEntry[] = []\n for (let leftIndex = 0; leftIndex < context.components.length; leftIndex++) {\n for (let rightIndex = leftIndex + 1; rightIndex < context.components.length; rightIndex++) {\n const leftComponent = context.components[leftIndex]!\n const rightComponent = context.components[rightIndex]!\n const leftSingle = context.singleByComponent.get(leftComponent.componentId)!\n const rightSingle = context.singleByComponent.get(rightComponent.componentId)!\n const pair = context.candidateByComponents.get(\n componentSetKey([leftComponent.componentId, rightComponent.componentId]),\n )!\n const pairSummary = summaryById.get(pair.candidateId)!\n const leftSummary = summaryById.get(leftSingle.candidateId)!\n const rightSummary = summaryById.get(rightSingle.candidateId)!\n const synergyTaskIds: string[] = []\n const interferenceTaskIds: string[] = []\n for (const taskId of context.input.taskOrder) {\n const pairRow = rowFor(context, pair.candidateId, taskId)\n const leftRow = rowFor(context, leftSingle.candidateId, taskId)\n const rightRow = rowFor(context, rightSingle.candidateId, taskId)\n if (![pairRow, leftRow, rightRow].every((row) => row.completeness === 'complete')) continue\n if (pairRow.pass && !leftRow.pass && !rightRow.pass) synergyTaskIds.push(taskId)\n if (!pairRow.pass && (leftRow.pass || rightRow.pass)) interferenceTaskIds.push(taskId)\n }\n const incrementalVsConstituents: [\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateComparison,\n ] = [\n compareCandidates(context, summaryById, leftSingle.candidateId, pair.candidateId),\n compareCandidates(context, summaryById, rightSingle.candidateId, pair.candidateId),\n ]\n const betterSingle =\n compareSingleSummaries(context, leftSummary, rightSummary) <= 0 ? leftSummary : rightSummary\n const firing = summarizePairEvidence(\n rowsFor(context, pair.candidateId),\n leftComponent.componentId,\n rightComponent.componentId,\n 'fired',\n )\n const effect = summarizePairEvidence(\n rowsFor(context, pair.candidateId),\n leftComponent.componentId,\n rightComponent.componentId,\n 'effectObserved',\n )\n const compatibility = pairCompatibility(\n context,\n pairSummary,\n baseline,\n betterSingle,\n incrementalVsConstituents,\n interactionReadyIds.has(leftSingle.candidateId) &&\n interactionReadyIds.has(rightSingle.candidateId),\n interferenceTaskIds,\n firing,\n effect,\n )\n entries.push({\n componentIds: [leftComponent.componentId, rightComponent.componentId],\n singleCandidateIds: [leftSingle.candidateId, rightSingle.candidateId],\n compositionCandidateId: pair.candidateId,\n benefitTaskIds: [...pairSummary.outcome.benefitTaskIds],\n regressionTaskIds: [...pairSummary.outcome.regressionTaskIds],\n synergyTaskIds,\n interferenceTaskIds,\n incrementalVsConstituents,\n relativeCostToBaseline: relativeCosts(context, pairSummary, baseline),\n firing,\n effect,\n interaction: interactionEffect(\n context,\n baseline.candidate,\n [leftSingle, rightSingle],\n pair,\n ),\n compatibility,\n })\n }\n }\n return entries\n}\n\nfunction pairCompatibility<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n pair: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n betterSingle: CrossSurfaceCandidateSummary,\n comparisons: [CrossSurfaceCandidateComparison, CrossSurfaceCandidateComparison],\n constituentsReady: boolean,\n interferenceTaskIds: string[],\n firing: CrossSurfacePairEvidence,\n effect: CrossSurfacePairEvidence,\n): CrossSurfacePairCompatibility {\n const reasons: CrossSurfacePairIncompatibilityReason[] = []\n if (!constituentsReady) reasons.push('constituent_not_ready')\n if (\n pair.outcome.missingTaskIds.length > 0 ||\n pair.outcome.invalidTaskIds.length > 0 ||\n pair.outcome.comparisonMissingTaskIds.length > 0\n ) {\n reasons.push('pair_incomplete')\n }\n if (pair.outcome.regressionTaskIds.length > 0) reasons.push('baseline_regression')\n if (interferenceTaskIds.length > 0) reasons.push('interference')\n const betterComparison = comparisons.find(\n (comparison) => comparison.comparatorCandidateId === betterSingle.candidate.candidateId,\n )!\n if (betterComparison.winsTaskIds.length === 0) reasons.push('no_incremental_resolution')\n appendPairEvidenceReasons(\n reasons,\n firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendPairEvidenceReasons(\n reasons,\n effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, pair, baseline)) reasons.push('cost_limit_exceeded')\n return {\n compatible: reasons.length === 0,\n reasons: unique(reasons),\n betterSingleCandidateId: betterSingle.candidate.candidateId,\n }\n}\n\nfunction appendPairEvidenceReasons(\n reasons: CrossSurfacePairIncompatibilityReason[],\n evidence: CrossSurfacePairEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfacePairIncompatibilityReason,\n unobservedReason: CrossSurfacePairIncompatibilityReason,\n): void {\n const leftObserved = evidence.bothTaskIds.length + evidence.leftOnlyTaskIds.length\n const rightObserved = evidence.bothTaskIds.length + evidence.rightOnlyTaskIds.length\n if (leftObserved < minimum || rightObserved < minimum) reasons.push(belowReason)\n if (requireObserved && evidence.unobservedTaskIds.length > 0) reasons.push(unobservedReason)\n}\n\nfunction interactionEffect<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n baseline: CrossSurfaceCandidate,\n singles: CrossSurfaceCandidate[],\n composition: CrossSurfaceCandidate,\n): CrossSurfaceInteractionEffect {\n const perTask = context.input.taskOrder.map((taskId) => {\n const baselineRow = rowFor(context, baseline.candidateId, taskId)\n const singleRows = singles.map((single) => rowFor(context, single.candidateId, taskId))\n const compositionRow = rowFor(context, composition.candidateId, taskId)\n const rows = [baselineRow, ...singleRows, compositionRow]\n if (!rows.every((row) => row.completeness === 'complete')) {\n return { taskId, passInteraction: null, scoreInteraction: null }\n }\n const additivePass =\n singleRows.reduce((sum, row) => sum + Number(row.pass), 0) -\n (singles.length - 1) * Number(baselineRow.pass)\n const additiveScore =\n singleRows.reduce((sum, row) => sum + (row.score as number), 0) -\n (singles.length - 1) * (baselineRow.score as number)\n return {\n taskId,\n passInteraction: Number(compositionRow.pass) - additivePass,\n scoreInteraction: (compositionRow.score as number) - additiveScore,\n }\n })\n const complete = perTask.filter(\n (row): row is { taskId: string; passInteraction: number; scoreInteraction: number } =>\n row.passInteraction !== null && row.scoreInteraction !== null,\n )\n const passInteractions = complete.map((row) => row.passInteraction)\n const scoreInteractions = complete.map((row) => row.scoreInteraction)\n return {\n perTask,\n n: complete.length,\n nMissing: perTask.length - complete.length,\n meanPassInteraction: meanOrNull(passInteractions),\n meanScoreInteraction: meanOrNull(scoreInteractions),\n passBootstrap: bootstrapInteraction(passInteractions, context),\n scoreBootstrap: bootstrapInteraction(scoreInteractions, context),\n }\n}\n\nfunction bootstrapInteraction<TRow extends CrossSurfaceTaskRow>(\n interactions: number[],\n context: AnalysisContext<TRow>,\n) {\n if (interactions.length === 0) return null\n return pairedBootstrap(new Array(interactions.length).fill(0), interactions, {\n ...context.input.bootstrap,\n statistic: 'mean',\n })\n}\n\nfunction selectCandidates<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n eligibleSingles: CrossSurfaceCandidateSummary[],\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairwise: CrossSurfacePairwiseEntry[],\n): CrossSurfaceSelections {\n const bestSingleRanking = eligibleSingles.filter((summary) => {\n const componentId = summary.candidate.componentIds[0]!\n return context.componentById.get(componentId)!.bestSingleEligible\n })\n const ranking: CrossSurfaceRankedSingle[] = bestSingleRanking.map((summary, index) => ({\n rank: index + 1,\n candidateId: summary.candidate.candidateId,\n componentId: summary.candidate.componentIds[0]!,\n }))\n const best = bestSingleRanking[0]\n const bestSingle = best\n ? {\n candidateId: best.candidate.candidateId,\n componentId: best.candidate.componentIds[0]!,\n ranking,\n }\n : null\n const naiveStack = selectNaiveStack(context, eligibleSingles)\n const interactionAware = selectInteractionAware(\n context,\n summaryById,\n interactionReadySingles,\n pairwise,\n )\n return { bestSingle, naiveStack, interactionAware }\n}\n\nfunction selectNaiveStack<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n eligibleSingles: CrossSurfaceCandidateSummary[],\n): CrossSurfaceNaiveStackSelection | null {\n if (eligibleSingles.length === 0) return null\n const componentIds = eligibleSingles\n .map((summary) => summary.candidate.componentIds[0]!)\n .sort((left, right) => context.componentIndex.get(left)! - context.componentIndex.get(right)!)\n const candidate = context.candidateByComponents.get(componentSetKey(componentIds))\n if (!candidate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: naive stack [${componentIds.join(', ')}] was not evaluated`,\n )\n }\n return { candidateId: candidate.candidateId, componentIds }\n}\n\nfunction selectInteractionAware<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairwise: CrossSurfacePairwiseEntry[],\n): CrossSurfaceInteractionAwareSelection | null {\n const baseline = summaryById.get(context.input.baselineCandidateId)!\n const pairByComponents = new Map(\n pairwise.map((entry) => [componentSetKey(entry.componentIds), entry]),\n )\n const paths = pairwise\n .filter((entry) => entry.compatibility.compatible)\n .map((entry) =>\n growInteractionPath(\n context,\n summaryById,\n interactionReadySingles,\n pairByComponents,\n baseline,\n summaryById.get(entry.compositionCandidateId)!,\n ),\n )\n if (paths.length === 0) return null\n\n const qualified = paths\n .filter((path) => path.qualified)\n .sort((left, right) => compareInteractionPaths(context, summaryById, left, right))\n const winning =\n qualified[0] ??\n [...paths].sort((left, right) => compareInteractionPaths(context, summaryById, left, right))[0]!\n return {\n seedCandidateId: winning.seedCandidateId,\n terminalCandidateId: winning.terminalCandidateId,\n terminalComponentIds: [...winning.terminalComponentIds],\n selectedCandidateId: qualified.length > 0 ? winning.terminalCandidateId : null,\n qualified: qualified.length > 0,\n evaluatedPaths: paths,\n steps: winning.steps,\n }\n}\n\nfunction growInteractionPath<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairByComponents: Map<string, CrossSurfacePairwiseEntry>,\n baseline: CrossSurfaceCandidateSummary,\n seed: CrossSurfaceCandidateSummary,\n): CrossSurfaceInteractionPath {\n let current = seed\n let retained = [...seed.candidate.componentIds]\n let remaining = interactionReadySingles.filter(\n (summary) => !retained.includes(summary.candidate.componentIds[0]!),\n )\n const steps: CrossSurfaceCompositionStep[] = []\n\n while (remaining.length > 0) {\n const decisions = remaining.map((addition) =>\n evaluateAddition(\n context,\n summaryById,\n pairByComponents,\n baseline,\n current,\n retained,\n addition,\n ),\n )\n const eligible = decisions\n .filter((decision) => decision.eligible)\n .sort((left, right) => compareAdditionDecisions(context, summaryById, left, right))\n const selected = eligible[0]\n if (selected) selected.selected = true\n steps.push({\n fromCandidateId: current.candidate.candidateId,\n retainedComponentIds: [...retained],\n considered: decisions.sort(\n (left, right) =>\n context.candidateIndex.get(left.additionCandidateId)! -\n context.candidateIndex.get(right.additionCandidateId)!,\n ),\n selectedCandidateId: selected?.bundleCandidateId ?? null,\n })\n if (!selected?.bundleCandidateId) break\n current = summaryById.get(selected.bundleCandidateId)!\n retained = [...current.candidate.componentIds]\n remaining = remaining.filter(\n (summary) => summary.candidate.candidateId !== selected.additionCandidateId,\n )\n }\n\n const qualified = retained.length >= context.input.selection.minimumBundleComponents\n return {\n seedCandidateId: seed.candidate.candidateId,\n terminalCandidateId: current.candidate.candidateId,\n terminalComponentIds: retained,\n qualified,\n steps,\n }\n}\n\nfunction compareInteractionPaths<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n left: CrossSurfaceInteractionPath,\n right: CrossSurfaceInteractionPath,\n): number {\n const leftSummary = summaryById.get(left.terminalCandidateId)!\n const rightSummary = summaryById.get(right.terminalCandidateId)!\n const byNetBenefit = rightSummary.outcome.netBenefit - leftSummary.outcome.netBenefit\n if (byNetBenefit !== 0) return byNetBenefit\n const byBenefit =\n rightSummary.outcome.benefitTaskIds.length - leftSummary.outcome.benefitTaskIds.length\n if (byBenefit !== 0) return byBenefit\n const byRegression =\n leftSummary.outcome.regressionTaskIds.length - rightSummary.outcome.regressionTaskIds.length\n if (byRegression !== 0) return byRegression\n for (const metric of context.input.costMetricOrder) {\n const byCost = leftSummary.costs[metric]!.median - rightSummary.costs[metric]!.median\n if (byCost !== 0) return byCost\n }\n const byBytes = leftSummary.candidate.artifactBytes - rightSummary.candidate.artifactBytes\n if (byBytes !== 0) return byBytes\n const byCandidateOrder =\n context.candidateIndex.get(left.terminalCandidateId)! -\n context.candidateIndex.get(right.terminalCandidateId)!\n if (byCandidateOrder !== 0) return byCandidateOrder\n return (\n context.candidateIndex.get(left.seedCandidateId)! -\n context.candidateIndex.get(right.seedCandidateId)!\n )\n}\n\nfunction evaluateAddition<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n pairByComponents: Map<string, CrossSurfacePairwiseEntry>,\n baseline: CrossSurfaceCandidateSummary,\n current: CrossSurfaceCandidateSummary,\n retained: string[],\n addition: CrossSurfaceCandidateSummary,\n): CrossSurfaceAdditionDecision {\n const additionComponentId = addition.candidate.componentIds[0]!\n const reasons: CrossSurfaceAdditionRejectionReason[] = []\n for (const retainedComponentId of retained) {\n const pair = pairByComponents.get(\n componentSetKey(canonicalComponents(context, [retainedComponentId, additionComponentId])),\n )\n if (!pair?.compatibility.compatible) reasons.push('pair_incompatible')\n }\n const bundleComponents = canonicalComponents(context, [...retained, additionComponentId])\n const bundle = context.candidateByComponents.get(componentSetKey(bundleComponents))\n if (!bundle) {\n reasons.push('full_bundle_not_evaluated')\n return emptyAdditionDecision(addition, additionComponentId, reasons)\n }\n const bundleSummary = summaryById.get(bundle.candidateId)!\n if (\n bundleSummary.outcome.missingTaskIds.length > 0 ||\n bundleSummary.outcome.invalidTaskIds.length > 0 ||\n bundleSummary.outcome.comparisonMissingTaskIds.length > 0\n ) {\n reasons.push('bundle_incomplete')\n }\n if (bundleSummary.outcome.regressionTaskIds.length > 0) reasons.push('baseline_regression')\n const comparison = compareCandidates(\n context,\n summaryById,\n current.candidate.candidateId,\n bundle.candidateId,\n )\n if (comparison.winsTaskIds.length === 0) reasons.push('no_incremental_resolution')\n if (comparison.regressionTaskIds.length > 0) reasons.push('incremental_regression')\n appendBundleEvidenceReasons(\n reasons,\n bundleSummary.firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendBundleEvidenceReasons(\n reasons,\n bundleSummary.effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, bundleSummary, baseline)) reasons.push('cost_limit_exceeded')\n return {\n additionCandidateId: addition.candidate.candidateId,\n additionComponentId,\n bundleCandidateId: bundle.candidateId,\n incrementalResolutionTaskIds: comparison.winsTaskIds,\n incrementalRegressionTaskIds: comparison.regressionTaskIds,\n incrementalMedianCost: Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [\n metric,\n bundleSummary.costs[metric]!.median - current.costs[metric]!.median,\n ]),\n ),\n eligible: reasons.length === 0,\n selected: false,\n reasons: unique(reasons),\n }\n}\n\nfunction emptyAdditionDecision(\n addition: CrossSurfaceCandidateSummary,\n additionComponentId: string,\n reasons: CrossSurfaceAdditionRejectionReason[],\n): CrossSurfaceAdditionDecision {\n return {\n additionCandidateId: addition.candidate.candidateId,\n additionComponentId,\n bundleCandidateId: null,\n incrementalResolutionTaskIds: [],\n incrementalRegressionTaskIds: [],\n incrementalMedianCost: null,\n eligible: false,\n selected: false,\n reasons: unique(reasons),\n }\n}\n\nfunction compareAdditionDecisions<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n left: CrossSurfaceAdditionDecision,\n right: CrossSurfaceAdditionDecision,\n): number {\n const byWins =\n right.incrementalResolutionTaskIds.length - left.incrementalResolutionTaskIds.length\n if (byWins !== 0) return byWins\n for (const metric of context.input.costMetricOrder) {\n const byCost = left.incrementalMedianCost![metric]! - right.incrementalMedianCost![metric]!\n if (byCost !== 0) return byCost\n }\n const leftBytes = summaryById.get(left.additionCandidateId)!.candidate.artifactBytes\n const rightBytes = summaryById.get(right.additionCandidateId)!.candidate.artifactBytes\n const byBytes = leftBytes - rightBytes\n if (byBytes !== 0) return byBytes\n return (\n context.candidateIndex.get(left.additionCandidateId)! -\n context.candidateIndex.get(right.additionCandidateId)!\n )\n}\n\nfunction summarizeCandidate<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n candidate: CrossSurfaceCandidate,\n baseline: CrossSurfaceCandidate,\n): CrossSurfaceCandidateSummary {\n const rows = rowsFor(context, candidate.candidateId)\n const baselineRows = rowsFor(context, baseline.candidateId)\n const outcome = summarizeOutcome(\n context,\n rows,\n baselineRows,\n candidate.candidateId === baseline.candidateId,\n )\n const completeScores = rows\n .filter((row) => row.completeness === 'complete')\n .map((row) => row.score as number)\n const costs = Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [\n metric,\n distribution(rows.map((row) => row.cost[metric] as number)),\n ]),\n )\n return {\n candidate,\n outcome,\n score: completeScores.length === 0 ? null : distribution(completeScores),\n costs,\n firing: summarizeCandidateEvidence(rows, candidate.componentIds, 'fired'),\n effect: summarizeCandidateEvidence(rows, candidate.componentIds, 'effectObserved'),\n comparisonToBaseline:\n candidate.candidateId === baseline.candidateId\n ? null\n : pairedComparison(context, baseline.candidateId, candidate.candidateId),\n eligibility: null,\n }\n}\n\nfunction summarizeOutcome<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n rows: TRow[],\n baselineRows: TRow[],\n isBaseline: boolean,\n): CrossSurfaceCandidateOutcome {\n const resolvedTaskIds: string[] = []\n const failedTaskIds: string[] = []\n const missingTaskIds: string[] = []\n const invalidTaskIds: string[] = []\n const benefitTaskIds: string[] = []\n const regressionTaskIds: string[] = []\n const comparisonMissingTaskIds: string[] = []\n for (let index = 0; index < context.input.taskOrder.length; index++) {\n const row = rows[index]!\n const baseline = baselineRows[index]!\n if (row.completeness === 'missing') missingTaskIds.push(row.taskId)\n else if (row.completeness === 'invalid') invalidTaskIds.push(row.taskId)\n else if (row.pass) resolvedTaskIds.push(row.taskId)\n else failedTaskIds.push(row.taskId)\n\n if (isBaseline) continue\n if (row.completeness !== 'complete' || baseline.completeness !== 'complete') {\n comparisonMissingTaskIds.push(row.taskId)\n } else if (row.pass && !baseline.pass) benefitTaskIds.push(row.taskId)\n else if (!row.pass && baseline.pass) regressionTaskIds.push(row.taskId)\n }\n return {\n resolvedTaskIds,\n failedTaskIds,\n missingTaskIds,\n invalidTaskIds,\n benefitTaskIds,\n regressionTaskIds,\n comparisonMissingTaskIds,\n netBenefit: benefitTaskIds.length - regressionTaskIds.length,\n }\n}\n\nfunction candidateEligibility<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summary: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n): CrossSurfaceEligibility {\n const reasons: CrossSurfaceIneligibilityReason[] = []\n if (summary.outcome.missingTaskIds.length > 0) reasons.push('missing_attempt')\n if (summary.outcome.invalidTaskIds.length > 0) reasons.push('invalid_attempt')\n if (summary.outcome.comparisonMissingTaskIds.length > 0) reasons.push('baseline_outcome_missing')\n if (summary.outcome.benefitTaskIds.length <= summary.outcome.regressionTaskIds.length) {\n reasons.push('benefit_not_greater_than_regression')\n }\n appendEvidenceEligibilityReasons(\n reasons,\n summary.firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendEvidenceEligibilityReasons(\n reasons,\n summary.effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, summary, baseline)) reasons.push('cost_limit_exceeded')\n return { eligible: reasons.length === 0, reasons: unique(reasons) }\n}\n\nfunction rankedEligibleSingles<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n): CrossSurfaceCandidateSummary[] {\n return [...context.singleByComponent.values()]\n .map((candidate) => summaryById.get(candidate.candidateId)!)\n .filter((summary) => summary.eligibility?.eligible)\n .sort((left, right) => compareSingleSummaries(context, left, right))\n}\n\n/**\n * A neutral constituent may seed a composition when it has complete, bounded,\n * observed evidence and causes no baseline regression. Individual benefit is\n * deliberately left to the best-single arm rather than used as a pair gate.\n */\nfunction rankedInteractionReadySingles<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n): CrossSurfaceCandidateSummary[] {\n return [...context.singleByComponent.values()]\n .map((candidate) => summaryById.get(candidate.candidateId)!)\n .filter(\n (summary) =>\n summary.outcome.regressionTaskIds.length === 0 &&\n summary.eligibility?.reasons.every(\n (reason) => reason === 'benefit_not_greater_than_regression',\n ),\n )\n .sort((left, right) => compareSingleSummaries(context, left, right))\n}\n\nfunction compareSingleSummaries<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n left: CrossSurfaceCandidateSummary,\n right: CrossSurfaceCandidateSummary,\n): number {\n const byNetBenefit = right.outcome.netBenefit - left.outcome.netBenefit\n if (byNetBenefit !== 0) return byNetBenefit\n const byBenefit = right.outcome.benefitTaskIds.length - left.outcome.benefitTaskIds.length\n if (byBenefit !== 0) return byBenefit\n const byRegression =\n left.outcome.regressionTaskIds.length - right.outcome.regressionTaskIds.length\n if (byRegression !== 0) return byRegression\n for (const metric of context.input.costMetricOrder) {\n const byCost = left.costs[metric]!.median - right.costs[metric]!.median\n if (byCost !== 0) return byCost\n }\n const byBytes = left.candidate.artifactBytes - right.candidate.artifactBytes\n if (byBytes !== 0) return byBytes\n return (\n context.candidateIndex.get(left.candidate.candidateId)! -\n context.candidateIndex.get(right.candidate.candidateId)!\n )\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve } from 'node:path'\nimport { contentHash } from '../verdict-cache'\nimport { type CampaignRunPlan, type PlanCampaignRunOptions, planCampaignRun } from './run-campaign'\nimport type { CampaignStorage } from './storage'\nimport type { JudgeConfig, Scenario } from './types'\n\nexport type EvalFixtureValidationMode = 'vitest' | 'none'\n\nexport interface EvalFixtureFile {\n path: string\n sha256: string\n bytes: number\n}\n\nexport interface EvalFixture {\n name: string\n path: string\n promptPath: string\n evalPath?: string\n packageJsonPath?: string\n prompt: string\n files: EvalFixtureFile[]\n fingerprint: string\n}\n\nexport interface EvalFixtureScenario extends Scenario {\n kind: 'eval-fixture'\n fixtureName: string\n fixturePath: string\n promptPath: string\n evalPath?: string\n packageJsonPath?: string\n prompt: string\n fingerprint: string\n}\n\nexport interface EvalFixtureLoadOptions {\n /** `vitest` requires EVAL.ts/EVAL.tsx and package.json type=module. `none` only requires PROMPT.md. */\n validation?: EvalFixtureValidationMode\n /** Extra caller-owned knobs that affect fixture behavior, folded into the fingerprint. */\n fingerprintConfig?: unknown\n}\n\nexport interface LoadEvalFixtureScenariosOptions extends EvalFixtureLoadOptions {\n names?: string[]\n}\n\nexport interface PlanEvalFixtureRunOptions<TArtifact = unknown>\n extends Pick<\n PlanCampaignRunOptions<EvalFixtureScenario, TArtifact>,\n 'dispatchRef' | 'judges' | 'seed' | 'reps' | 'resumable' | 'runDir'\n > {\n evalsDir: string\n validation?: EvalFixtureValidationMode\n fingerprintConfig?: unknown\n names?: string[]\n storage?: CampaignStorage\n}\n\nexport type EvalFixtureRunPlan = CampaignRunPlan & {\n fixtures: Array<Pick<EvalFixtureScenario, 'fixtureName' | 'fixturePath' | 'fingerprint'>>\n}\n\n/** Walk `evalsDir` and return the relative name of every fixture directory (one containing an exact-case `PROMPT.md`). */\nexport function discoverEvalFixtures(evalsDir: string): string[] {\n const root = resolve(evalsDir)\n if (!existsSync(root)) throw new Error(`discoverEvalFixtures: evalsDir not found: ${root}`)\n\n const fixtures: string[] = []\n const walk = (dir: string, base = '') => {\n for (const entry of readdirSync(dir).sort()) {\n if (entry.startsWith('.') || entry === 'node_modules') continue\n const fullPath = join(dir, entry)\n if (!statSync(fullPath).isDirectory()) continue\n\n const name = base ? `${base}/${entry}` : entry\n if (existsWithExactCase(fullPath, 'PROMPT.md')) {\n fixtures.push(name)\n } else {\n walk(fullPath, name)\n }\n }\n }\n\n walk(root)\n return fixtures\n}\n\n/**\n * Load ONE fixture by name: reads `PROMPT.md` (plus `EVAL.ts`/`EVAL.tsx` and `package.json` under\n * `vitest` validation) and content-fingerprints the full file set for cache identity.\n */\nexport function loadEvalFixture(\n evalsDir: string,\n name: string,\n options: EvalFixtureLoadOptions = {},\n): EvalFixture {\n const validation = options.validation ?? 'vitest'\n const root = resolve(evalsDir)\n const fixturePath = resolve(root, name)\n assertInside(root, fixturePath, name)\n\n if (!existsSync(fixturePath) || !statSync(fixturePath).isDirectory()) {\n throw new Error(`loadEvalFixture: fixture not found: ${name}`)\n }\n if (!existsWithExactCase(fixturePath, 'PROMPT.md')) {\n throw new Error(`loadEvalFixture: ${name} is missing exact-case PROMPT.md`)\n }\n\n const promptPath = join(fixturePath, 'PROMPT.md')\n const evalPath = resolveEvalPath(fixturePath)\n const packageJsonPath = existsWithExactCase(fixturePath, 'package.json')\n ? join(fixturePath, 'package.json')\n : undefined\n\n if (validation !== 'none') {\n if (!evalPath)\n throw new Error(`loadEvalFixture: ${name} is missing exact-case EVAL.ts or EVAL.tsx`)\n if (!packageJsonPath)\n throw new Error(`loadEvalFixture: ${name} is missing exact-case package.json`)\n assertModulePackage(packageJsonPath, name)\n }\n\n const files = collectFixtureFiles(fixturePath)\n return {\n name,\n path: fixturePath,\n promptPath,\n evalPath,\n packageJsonPath,\n prompt: readFileSync(promptPath, 'utf8'),\n files,\n fingerprint: contentHash({\n files,\n config: options.fingerprintConfig ?? null,\n }),\n }\n}\n\n/** Load fixtures (all discovered, or just `names`) as campaign `Scenario`s tagged `eval-fixture`. */\nexport function loadEvalFixtureScenarios(\n evalsDir: string,\n options: LoadEvalFixtureScenariosOptions = {},\n): EvalFixtureScenario[] {\n const names = options.names ?? discoverEvalFixtures(evalsDir)\n return names.map((name) => {\n const fixture = loadEvalFixture(evalsDir, name, options)\n return {\n id: fixture.name,\n kind: 'eval-fixture',\n tags: ['eval-fixture'],\n fixtureName: fixture.name,\n fixturePath: fixture.path,\n promptPath: fixture.promptPath,\n evalPath: fixture.evalPath,\n packageJsonPath: fixture.packageJsonPath,\n prompt: fixture.prompt,\n fingerprint: fixture.fingerprint,\n }\n })\n}\n\n/**\n * Dry-run planner for a fixture campaign: loads the scenarios, delegates to `planCampaignRun`,\n * and returns the plan plus each fixture's name/path/fingerprint.\n */\nexport function planEvalFixtureRun<TArtifact = unknown>(\n options: PlanEvalFixtureRunOptions<TArtifact>,\n): EvalFixtureRunPlan {\n const scenarios = loadEvalFixtureScenarios(options.evalsDir, {\n names: options.names,\n validation: options.validation,\n fingerprintConfig: options.fingerprintConfig,\n })\n const plan = planCampaignRun<EvalFixtureScenario, TArtifact>({\n scenarios,\n dispatchRef: options.dispatchRef ?? 'eval-fixture-dispatch',\n judges: options.judges as JudgeConfig<TArtifact, EvalFixtureScenario>[] | undefined,\n seed: options.seed,\n reps: options.reps,\n resumable: options.resumable,\n runDir: options.runDir,\n storage: options.storage,\n })\n\n return {\n ...plan,\n fixtures: scenarios.map((scenario) => ({\n fixtureName: scenario.fixtureName,\n fixturePath: scenario.fixturePath,\n fingerprint: scenario.fingerprint,\n })),\n }\n}\n\nfunction existsWithExactCase(dirPath: string, fileName: string): boolean {\n try {\n return readdirSync(dirPath).includes(fileName)\n } catch {\n return false\n }\n}\n\nfunction resolveEvalPath(fixturePath: string): string | undefined {\n if (existsWithExactCase(fixturePath, 'EVAL.ts')) return join(fixturePath, 'EVAL.ts')\n if (existsWithExactCase(fixturePath, 'EVAL.tsx')) return join(fixturePath, 'EVAL.tsx')\n return undefined\n}\n\nfunction assertModulePackage(packageJsonPath: string, name: string): void {\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(packageJsonPath, 'utf8'))\n } catch (err) {\n throw new Error(\n `loadEvalFixture: ${name} package.json is invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n (parsed as { type?: unknown }).type !== 'module'\n ) {\n throw new Error(`loadEvalFixture: ${name} package.json must set \"type\": \"module\"`)\n }\n}\n\nfunction collectFixtureFiles(fixturePath: string, base = ''): EvalFixtureFile[] {\n const files: EvalFixtureFile[] = []\n for (const entry of readdirSync(join(fixturePath, base)).sort()) {\n if (entry === 'node_modules' || entry === '.git') continue\n const relativePath = base ? `${base}/${entry}` : entry\n const fullPath = join(fixturePath, relativePath)\n const stat = statSync(fullPath)\n if (stat.isDirectory()) {\n files.push(...collectFixtureFiles(fixturePath, relativePath))\n continue\n }\n const bytes = readFileSync(fullPath)\n files.push({\n path: relativePath,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n bytes: bytes.byteLength,\n })\n }\n return files\n}\n\nfunction assertInside(root: string, target: string, label: string): void {\n const rel = relative(root, target)\n if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) return\n throw new Error(`loadEvalFixture: fixture path escapes evalsDir: ${label}`)\n}\n","/**\n * @module\n * Composable placebo / neutralization promotion gate.\n *\n * A held-out gate proves a candidate beat baseline. It CANNOT prove the lift came\n * from the candidate's CONTENT rather than from the prompt/mount FOOTPRINT the\n * content happened to add (more bytes, a longer prompt). This gate closes that\n * hole: it compares the candidate's held-out lift against the lift of a\n * FOOTPRINT-MATCHED neutralized variant (same layout + length, zero content, via\n * `neutralizeText`). If the neutralized variant reproduces more than\n * `maxDecorativeFraction` of the candidate's lift, the lift is decorative — it\n * survives blanking the content — and the candidate is HELD regardless of how\n * large or significant its raw lift is.\n *\n * Compose it AFTER the significance gate — significance says the lift is real,\n * this says the lift is CAUSED BY THE CONTENT:\n * composeGate(heldOutGate({ ... }), neutralizationGate({ ... }))\n *\n * Requires `ctx.neutralizedJudgeScores`, populated by `runImprovementLoop` when it\n * is given a `neutralize` function. A gate composed without that wiring fails\n * loud rather than silently passing an unproven candidate.\n */\n\nimport { mean } from '../../statistics/mean'\nimport type { Gate, GateContext, GateResult, Scenario } from '../types'\nimport { pairHoldout } from './statistical-heldout'\n\nexport interface NeutralizationGateOptions<TScenario extends Scenario = Scenario> {\n scenarios: TScenario[]\n /** Reject when the neutralized (content-blanked, footprint-matched) variant\n * reproduces at least this fraction of the candidate's held-out lift. Default\n * 0.5 — if blanking the content keeps half the lift, the content is decorative.\n * Equality rejects: a neutralized lift == threshold·candidateLift is decorative. */\n maxDecorativeFraction?: number\n}\n\n/** Paired mean held-out lift of `arm` over baseline, on the in-scope cells. */\nfunction pairedLift(\n arm: Map<string, Record<string, { composite: number }>>,\n baseline: Map<string, Record<string, { composite: number }>>,\n scenarioIds: Set<string>,\n): { lift: number; n: number } {\n const paired = pairHoldout(arm as never, baseline as never, scenarioIds, (s) => s.composite)\n const deltas = paired.after.map((a, i) => a - (paired.before[i] ?? 0))\n return { lift: deltas.length ? mean(deltas) : 0, n: deltas.length }\n}\n\n/**\n * Composable placebo gate: ships only when the candidate's held-out lift is NOT\n * mostly reproduced by a footprint-matched neutralized variant.\n */\nexport function neutralizationGate<TArtifact, TScenario extends Scenario>(\n options: NeutralizationGateOptions<TScenario>,\n): Gate<TArtifact, TScenario> {\n const maxDecorativeFraction = options.maxDecorativeFraction ?? 0.5\n return {\n name: 'neutralizationGate',\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n 'neutralizationGate: ctx.baselineJudgeScores is required — the placebo control measures lift OVER baseline.',\n )\n }\n if (!ctx.neutralizedJudgeScores) {\n throw new Error(\n 'neutralizationGate: ctx.neutralizedJudgeScores is required. It is populated by runImprovementLoop only when a `neutralize` function is supplied — composing this gate without that wiring would pass an unproven candidate.',\n )\n }\n const scenarioIds = new Set(options.scenarios.map((s) => s.id))\n const cand = pairedLift(\n ctx.judgeScores as never,\n ctx.baselineJudgeScores as never,\n scenarioIds,\n )\n const neut = pairedLift(\n ctx.neutralizedJudgeScores as never,\n ctx.baselineJudgeScores as never,\n scenarioIds,\n )\n\n // No positive candidate lift → nothing to attribute. Fail closed: the\n // placebo control has no basis to clear the candidate (the significance\n // gate is what judges lift magnitude; this one only judges its CAUSE).\n if (cand.lift <= 0) {\n return {\n decision: 'hold',\n reasons: [\n `neutralization: candidate held-out lift ${cand.lift.toFixed(3)} ≤ 0 — no positive lift to attribute to content`,\n ],\n contributingGates: [\n {\n name: 'neutralizationGate',\n status: 'fail',\n detail: { candidateLift: cand.lift, neutralizedLift: neut.lift, n: cand.n },\n },\n ],\n delta: cand.lift,\n }\n }\n\n const decorativeFraction = neut.lift / cand.lift\n const passed = decorativeFraction < maxDecorativeFraction\n const pct = (decorativeFraction * 100).toFixed(0)\n return {\n decision: passed ? 'ship' : 'hold',\n reasons: passed\n ? [\n `neutralization: content is causal — blanked variant reproduces ${pct}% of the lift (< ${(maxDecorativeFraction * 100).toFixed(0)}%); candidate Δ ${cand.lift.toFixed(3)}, neutralized Δ ${neut.lift.toFixed(3)}`,\n ]\n : [\n `neutralization: lift is DECORATIVE — blanking the content (footprint-matched) reproduces ${pct}% of the lift (≥ ${(maxDecorativeFraction * 100).toFixed(0)}%); candidate Δ ${cand.lift.toFixed(3)}, neutralized Δ ${neut.lift.toFixed(3)}`,\n ],\n contributingGates: [\n {\n name: 'neutralizationGate',\n status: passed ? 'pass' : 'fail',\n detail: {\n candidateLift: cand.lift,\n neutralizedLift: neut.lift,\n decorativeFraction,\n maxDecorativeFraction,\n n: cand.n,\n },\n },\n ],\n delta: cand.lift,\n }\n },\n }\n}\n","/**\n * @module\n * Footprint-matched neutralization — the placebo control for content-vs-footprint\n * attribution in a promotion gate.\n *\n * A promoted surface can raise a held-out score two different ways:\n * 1. its CONTENT is informative (the thing we want to promote), or\n * 2. it merely added prompt/mount FOOTPRINT — more bytes, more lines, a longer\n * more authoritative-looking prompt — that the model spends attention on\n * regardless of what the bytes say.\n *\n * A held-out gate proves the candidate beat baseline; it cannot separate (1) from\n * (2). `neutralizeText` produces a variant that keeps the input's layout and\n * length while carrying ZERO information, so scoring it isolates the footprint\n * contribution (2). Feed the neutralized variant's scores to `neutralizationGate`:\n * any lift it still holds over baseline is decorative, and a candidate whose lift\n * survives neutralization is rejected however large its raw lift.\n */\n\n/** Filler for blanked content. A single ASCII byte, so a run of it preserves an\n * ASCII source's exact byte length; for multibyte sources it preserves CHARACTER\n * count and layout (what the tokenizer footprint tracks), not raw byte count. */\nconst FILLER = '#'\n\n/**\n * Blank every non-whitespace character to a 1-byte filler while preserving all\n * whitespace. Line count, indentation, and word/line lengths are unchanged — so\n * the neutralized variant has the same layout and (for ASCII) the same byte\n * footprint as the input, but no readable content. Whitespace is preserved\n * deliberately: collapsing it would change the token structure and stop the\n * variant from being a true footprint match.\n */\nexport function neutralizeText(content: string): string {\n return content.replace(/\\S/g, FILLER)\n}\n","import { join } from 'node:path'\nimport { combineComparisonCosts } from './optimization-cost'\nimport type { OptimizationMethod, OptimizationMethodComposition } from './optimization-method'\nimport { executeOptimizationMethod } from './optimization-method'\nimport { fsCampaignStorage } from './storage'\nimport { surfaceContentHash } from './surface-identity'\nimport type { MutableSurface, Scenario } from './types'\n\n/** A composition owns artifact description when a method it composes does, so the\n * entry points refuse a caller's `describeArtifact` before the first stage spends. */\nfunction ownedArtifactDescription(\n methods: readonly Pick<OptimizationMethod, 'ownsArtifactDescription'>[],\n): { ownsArtifactDescription?: true } {\n return methods.some((method) => method.ownsArtifactDescription === true)\n ? { ownsArtifactDescription: true }\n : {}\n}\n\n/** Optimize a projection while evaluating every proposal in the complete candidate. */\nexport function scopedOptimizationMethod<S extends Scenario, A>(options: {\n name: string\n method: OptimizationMethod<S, A>\n project: (surface: MutableSurface) => MutableSurface\n merge: (baseline: MutableSurface, selected: MutableSurface) => MutableSurface\n}): OptimizationMethod<S, A> {\n return {\n name: options.name,\n ...ownedArtifactDescription([options.method]),\n async optimize(input) {\n const baseline = structuredClone(input.baselineSurface)\n const projected = options.project(structuredClone(baseline))\n const merge = (surface: MutableSurface) =>\n options.merge(structuredClone(baseline), structuredClone(surface))\n const baselineSurfaceHash = surfaceContentHash(baseline)\n if (surfaceContentHash(merge(projected)) !== baselineSurfaceHash)\n throw new Error('scoped optimization project/merge must preserve the baseline')\n const { selected, cost } = await executeOptimizationMethod({\n method: options.method,\n input: {\n ...input,\n baselineSurface: projected,\n surfaceToRoot: (surface) => {\n const merged = merge(surface)\n return input.surfaceToRoot ? input.surfaceToRoot(merged) : merged\n },\n runDir: join(input.runDir, `scope-${baselineSurfaceHash.slice('sha256:'.length)}`),\n runOptions: {\n ...input.runOptions,\n dispatchRef: JSON.stringify([\n input.runOptions.dispatchRef ?? null,\n options.name,\n baselineSurfaceHash,\n ]),\n },\n dispatchWithSurface: (surface, scenario, ctx) =>\n input.dispatchWithSurface(merge(surface), scenario, ctx),\n },\n storage: input.runOptions.storage ?? fsCampaignStorage(),\n })\n return {\n winnerSurface: merge(selected.winnerSurface),\n cost,\n ...(selected.durationMs === undefined ? {} : { durationMs: selected.durationMs }),\n composition: {\n kind: 'scoped',\n baselineSurfaceHash,\n stages: [\n {\n name: options.method.name,\n baselineSurfaceHash: surfaceContentHash(projected),\n result: { ...selected, cost },\n },\n ],\n },\n }\n },\n }\n}\n\n/** Each stage starts from the previous selected candidate, without an intervening release gate. */\nexport function sequentialOptimizationMethod<S extends Scenario, A>(options: {\n name: string\n methods: readonly OptimizationMethod<S, A>[]\n}): OptimizationMethod<S, A> {\n if (!options.methods.length)\n throw new Error('sequential optimization requires at least one method')\n const methods = [...options.methods]\n return {\n name: options.name,\n ...ownedArtifactDescription(methods),\n async optimize(input) {\n const started = Date.now()\n const stages: OptimizationMethodComposition['stages'] = []\n let winnerSurface = structuredClone(input.baselineSurface)\n for (const [index, method] of methods.entries()) {\n input.runOptions.signal?.throwIfAborted()\n const baselineSurfaceHash = surfaceContentHash(winnerSurface)\n const { selected, cost } = await executeOptimizationMethod({\n method,\n input: {\n ...input,\n baselineSurface: winnerSurface,\n runDir: join(input.runDir, `stage-${index}`),\n },\n storage: input.runOptions.storage ?? fsCampaignStorage(),\n })\n stages.push({ name: method.name, baselineSurfaceHash, result: { ...selected, cost } })\n winnerSurface = structuredClone(selected.winnerSurface)\n }\n return {\n winnerSurface,\n cost: combineComparisonCosts(\n stages.map((stage) => ({ label: stage.name, cost: stage.result.cost })),\n ),\n durationMs: Date.now() - started,\n composition: {\n kind: 'sequential',\n baselineSurfaceHash: surfaceContentHash(input.baselineSurface),\n stages,\n },\n }\n },\n }\n}\n","/**\n * Product-flow playback — drive the REAL product through a user story and\n * score the produced state per requirement (the launch \"Jira tick-off\").\n *\n * This is the substrate adapter + contract only. It plugs a `PlaybackDriver`\n * into the existing `runProfileMatrix` dispatch seam: a driver drives the real\n * product (a Playwright UI session or a sandbox workspace) and returns the\n * runtime event stream; `extractProducedState` + `verifyCompletion` then score\n * each requirement PASS/FAIL. The concrete drivers live in consumers — they\n * depend on browser / runtime infra the substrate must not import — so\n * agent-eval owns the seam, the `UserStory` contract, and the scoreboard.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n type CompletionRequirement,\n type CompletionVerdict,\n type CorrectnessChecker,\n type ProducedState,\n verifyCompletion,\n} from '../../completion-verifier'\nimport type { RuntimeEventLike } from '../../produced-state'\nimport type { DispatchContext, Scenario } from '../types'\n\n/** One step of a user story — what the user does. The driver interprets\n * `payload` (a Playwright selector + action, or a sandbox chat turn). */\nexport interface PlaybackStep {\n /** Human-readable action, captured verbatim in the UX narrative. */\n action: string\n /** Driver-specific payload (e.g. `{ selector, fill }` or `{ turn }`). */\n payload?: Record<string, unknown>\n}\n\n/**\n * A user story = a runnable product journey plus the requirements that define\n * \"this story works\". Each requirement is one Jira ticket line. Extends\n * `Scenario` so a catalog drops straight into `runProfileMatrix({ scenarios })`.\n */\nexport interface UserStory extends Scenario {\n /** Human-readable story title (the ticket headline). */\n title: string\n /** Ordered steps the driver executes. */\n steps: PlaybackStep[]\n /** What must hold in the produced state for the story to pass. */\n requirements: CompletionRequirement[]\n}\n\n/** Dispatch context plus the profile under test (which cheap model, etc.). */\nexport interface PlaybackContext extends DispatchContext {\n profile: AgentProfile\n}\n\n/**\n * Drives the real product through a story and returns the runtime event stream\n * `extractProducedState` consumes. Implemented by CONSUMERS —\n * `SandboxPlaybackDriver` (real API / sandbox workspace) and\n * `PlaywrightPlaybackDriver` (real UI) — because they depend on runtime /\n * browser infra the substrate must not import. The driver MUST report LLM\n * usage through `ctx.cost.runPaidCall` so the backend-integrity check sees real\n * tokens (a run that never reports tokens reads as a stub).\n */\nexport interface PlaybackDriver<TStory extends UserStory = UserStory> {\n run(story: TStory, ctx: PlaybackContext): Promise<readonly RuntimeEventLike[]>\n}\n\n/** A scored user story — the completion verdict plus its human title. */\nexport interface UserStoryVerdict extends CompletionVerdict {\n title: string\n}\n\n/**\n * Score one story's produced state against its requirements. Thin wrapper over\n * `verifyCompletion` that builds the gold from the story and returns a\n * per-requirement PASS/FAIL verdict. `checkCorrectness` is injected — a\n * deterministic stub in tests, `createLlmCorrectnessChecker` in production.\n */\nexport async function scoreUserStory(\n story: UserStory,\n state: ProducedState,\n checkCorrectness: CorrectnessChecker,\n): Promise<UserStoryVerdict> {\n const verdict = await verifyCompletion(\n { taskId: story.id, requirements: story.requirements },\n state,\n checkCorrectness,\n )\n return { ...verdict, title: story.title }\n}\n\n/** One row of the launch scoreboard — story × requirement → PASS/FAIL. */\nexport interface ScoreboardRow {\n storyId: string\n storyTitle: string\n reqId: string\n reqTitle: string\n status: 'PASS' | 'FAIL'\n evidence: string[]\n}\n\n/**\n * Flatten story verdicts into the per-requirement scoreboard — the literal\n * Jira tick-off: one row per (story, requirement) with PASS/FAIL and the\n * evidence behind the verdict.\n */\nexport function userStoryScoreboard(verdicts: readonly UserStoryVerdict[]): ScoreboardRow[] {\n const rows: ScoreboardRow[] = []\n for (const v of verdicts) {\n for (const r of v.requirements) {\n rows.push({\n storyId: v.taskId,\n storyTitle: v.title,\n reqId: r.reqId,\n reqTitle: r.title,\n status: r.satisfied ? 'PASS' : 'FAIL',\n evidence: r.evidence,\n })\n }\n }\n return rows\n}\n\n/** Launch-readiness headline counts rolled up from the per-requirement rows. */\nexport interface ScoreboardSummary {\n /** Distinct user stories on the board. */\n stories: number\n /** Stories whose every requirement passed. */\n storiesFullyComplete: number\n /** Total (story, requirement) rows. */\n requirements: number\n /** Rows with status PASS. */\n passed: number\n /** Rows with status FAIL. */\n failed: number\n /** passed / requirements; 0 when there are no rows. */\n passRate: number\n}\n\n/** Roll the per-requirement rows up into the launch headline counts. */\nexport function scoreboardSummary(rows: readonly ScoreboardRow[]): ScoreboardSummary {\n const byStory = new Map<string, { total: number; passed: number }>()\n let passed = 0\n for (const r of rows) {\n const s = byStory.get(r.storyId) ?? { total: 0, passed: 0 }\n s.total++\n if (r.status === 'PASS') {\n s.passed++\n passed++\n }\n byStory.set(r.storyId, s)\n }\n let storiesFullyComplete = 0\n for (const s of byStory.values()) if (s.total > 0 && s.passed === s.total) storiesFullyComplete++\n return {\n stories: byStory.size,\n storiesFullyComplete,\n requirements: rows.length,\n passed,\n failed: rows.length - passed,\n passRate: rows.length === 0 ? 0 : passed / rows.length,\n }\n}\n\nexport interface ScoreboardRenderOptions {\n /** Document H1. Defaults to a generic playback title. */\n title?: string\n /** Key/value run metadata rendered under the headline (runId, backend, model, date). */\n meta?: Record<string, string>\n /** Max chars of joined evidence shown per row. Default 160. */\n maxEvidenceChars?: number\n}\n\nfunction escapeCell(s: string): string {\n return s.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}…`\n}\n\n/**\n * Render the scoreboard as a launch-readiness Markdown document — the literal\n * \"tick off every user story\" artifact: a headline roll-up, the open tickets\n * (FAIL rows) up top as the launch blockers, then a per-story table of\n * requirement → PASS/FAIL with the evidence behind each verdict. Pure: same\n * rows in, same bytes out (no clock/random), so it is safe to snapshot.\n */\nexport function renderScoreboardMarkdown(\n rows: readonly ScoreboardRow[],\n opts: ScoreboardRenderOptions = {},\n): string {\n const maxEv = opts.maxEvidenceChars ?? 160\n const sum = scoreboardSummary(rows)\n const pct = (n: number) => `${Math.round(n * 100)}%`\n const ev = (e: string[]) => escapeCell(truncate(e.join('; '), maxEv)) || '—'\n const out: string[] = [`# ${opts.title ?? 'Product-flow playback scoreboard'}`, '']\n if (opts.meta) {\n for (const [k, v] of Object.entries(opts.meta)) out.push(`- **${k}:** ${v}`)\n out.push('')\n }\n out.push(\n `**${sum.storiesFullyComplete}/${sum.stories}** user stories fully shipped · ` +\n `**${sum.passed}/${sum.requirements}** requirements passing (${pct(sum.passRate)}) · ` +\n `**${sum.failed}** open`,\n '',\n )\n const fails = rows.filter((r) => r.status === 'FAIL')\n if (fails.length > 0) {\n out.push('## Open tickets', '', '| Story | Requirement | Evidence |', '| --- | --- | --- |')\n for (const r of fails) {\n out.push(`| ${escapeCell(r.storyTitle)} | ${escapeCell(r.reqTitle)} | ${ev(r.evidence)} |`)\n }\n out.push('')\n } else {\n out.push('_All requirements passing — no open tickets._', '')\n }\n out.push('## Per-story tick-off', '')\n for (const storyId of [...new Set(rows.map((r) => r.storyId))]) {\n const storyRows = rows.filter((r) => r.storyId === storyId)\n const passed = storyRows.filter((r) => r.status === 'PASS').length\n const mark = passed === storyRows.length ? '✅' : '⚠️'\n out.push(\n `### ${escapeCell(storyRows[0]!.storyTitle)} — ${passed}/${storyRows.length} ${mark}`,\n '',\n '| Requirement | Status | Evidence |',\n '| --- | --- | --- |',\n )\n for (const r of storyRows) {\n out.push(\n `| ${escapeCell(r.reqTitle)} | ${r.status === 'PASS' ? '✅ PASS' : '❌ FAIL'} | ${ev(r.evidence)} |`,\n )\n }\n out.push('')\n }\n return out.join('\\n')\n}\n","/**\n * How far a profile-matrix verdict can be trusted: the familywise adjustment that turns each\n * profile's paired difference from the baseline into a verdict, and the run-to-run noise of a\n * profile run more than once. `analyzeProfileMatrix` calls both and re-exports these types.\n */\n\nimport { type RunRecord, runTaskScore } from '../../run-record'\nimport { holm } from '../../statistics'\nimport { zQuantile } from '../../statistics/internal'\nimport { mean } from '../../statistics/mean'\nimport type { ProfileMatrixProfileStats } from './profile-matrix-analysis'\n\n/**\n * A profile against the baseline after the family adjustment. `better` and `worse`: the nominal\n * interval excludes zero and the Holm-adjusted p over the page's family is at most 1 - level.\n * `candidate`: the nominal interval excludes zero but the adjusted p does not pass.\n * `unresolved`: the nominal interval includes zero, or there is no paired case.\n */\nexport type ProfileMatrixVerdict = 'better' | 'worse' | 'candidate' | 'unresolved'\n\n/** The family of profile-against-baseline comparisons the verdicts control the error over. */\nexport interface ProfileMatrixFamily {\n method: 'holm'\n /** Familywise error rate the verdicts control: 1 - level. */\n alpha: number\n /** Comparisons with a p-value, one per profile other than the baseline. */\n comparisons: number\n}\n\n/** A share measured on each pair of runs: its mean over the pairs, and the lowest and highest. */\nexport interface ProfileMatrixPairwiseShare {\n mean: number\n min: number\n max: number\n}\n\n/** How much one profile's runs differ with nothing changed between them. */\nexport interface ProfileMatrixRunStability {\n profileId: string\n runs: number\n /** Cases every run of this profile scored; every number below is on them. */\n n: number\n /** Each run's mean score, in run order; null when `n` is 0. */\n runQuality: { run: number; quality: number | null }[]\n /** Highest run quality minus the lowest; null when `n` is 0. */\n spread: number | null\n /** Share of cases one run got right and the other did not, over run pairs; null when `n` is 0. */\n correctnessDisagreement: ProfileMatrixPairwiseShare | null\n /** Share of the cases both runs answered where the answers differ; null without such a case. */\n answerDisagreement: ProfileMatrixPairwiseShare | null\n /**\n * Half-width of the range, at the analysis level, within which two runs of this profile land\n * on the panel's common cases with nothing changed: z·√(m / n), where m is the mean squared\n * per-case score difference between two runs (for right/wrong scores, the correctness\n * disagreement) and each case's change is taken as independent. Null without common cases.\n */\n rerunMargin: number | null\n}\n\n/** Whether an interval lies wholly above zero, wholly below it, or includes it. */\nexport function intervalSide(i: {\n low: number | null\n high: number | null\n}): 'up' | 'down' | 'flat' {\n if (i.low !== null && i.low > 0) return 'up'\n if (i.high !== null && i.high < 0) return 'down'\n return 'flat'\n}\n\n/** The run a record belongs to: the campaign's `outcome.raw.rep`, or run 0 when absent. */\nexport function runOf(record: RunRecord): number {\n const rep = record.outcome.raw.rep\n return Number.isFinite(rep) ? rep! : 0\n}\n\n/**\n * Holm over every profile-against-baseline p-value on the page, so the better and worse verdicts\n * together keep the familywise error at `alpha`. A comparison without a p-value cannot pass, so\n * it stays out of the family instead of raising everyone else's bar.\n */\nexport function withVerdicts(\n stats: readonly ProfileMatrixProfileStats[],\n baseline: string,\n alpha: number,\n): { profiles: ProfileMatrixProfileStats[]; family: ProfileMatrixFamily } {\n const tested = stats.filter((p) => typeof p.vsBaseline?.pValue === 'number')\n const { adjusted } = holm(\n tested.map((p) => p.vsBaseline!.pValue!),\n alpha,\n )\n const adjustedOf = new Map(tested.map((p, index) => [p.profileId, adjusted[index]!]))\n const profiles = stats.map((p) => {\n if (p.profileId === baseline) return p\n const adjustedPValue = adjustedOf.get(p.profileId) ?? null\n const side = p.vsBaseline ? intervalSide(p.vsBaseline) : 'flat'\n const verdict: ProfileMatrixVerdict =\n side === 'flat'\n ? 'unresolved'\n : adjustedPValue !== null && adjustedPValue <= alpha\n ? side === 'up'\n ? 'better'\n : 'worse'\n : 'candidate'\n return { ...p, adjustedPValue, verdict }\n })\n return { profiles, family: { method: 'holm', alpha, comparisons: tested.length } }\n}\n\n/**\n * Each profile with two or more runs, on the cases every one of its runs scored. A run's score\n * on a case is the mean of its records there, and its answer the last one `answerOf` returned.\n */\nexport function runStability(input: {\n profileIds: readonly string[]\n recordsByProfile: ReadonlyMap<string, readonly RunRecord[]>\n answerOf: ((record: RunRecord) => string | undefined) | undefined\n level: number\n passScore: number\n /** Common cases of the panel: the n the rerun margin is stated at. */\n commonCases: number\n}): ProfileMatrixRunStability[] {\n const z = zQuantile(1 - (1 - input.level) / 2)\n const panelN = input.commonCases\n const right = (score: number) => score >= input.passScore\n const share = (values: number[]): ProfileMatrixPairwiseShare | null =>\n values.length\n ? { mean: mean(values), min: Math.min(...values), max: Math.max(...values) }\n : null\n return input.profileIds.flatMap((profileId) => {\n const scores = new Map<number, Map<string, number[]>>()\n const answers = new Map<number, Map<string, string>>()\n for (const record of input.recordsByProfile.get(profileId)!) {\n const run = runOf(record)\n const own = scores.get(run) ?? new Map<string, number[]>()\n scores.set(run, own)\n const score = runTaskScore(record)\n if (score === undefined) continue\n own.set(record.scenarioId, [...(own.get(record.scenarioId) ?? []), score])\n const answer = input.answerOf?.(record)\n if (answer === undefined) continue\n const given = answers.get(run) ?? new Map<string, string>()\n given.set(record.scenarioId, answer)\n answers.set(run, given)\n }\n if (scores.size < 2) return []\n const runs = [...scores.keys()].sort((a, b) => a - b)\n const scoreIn = (run: number, caseId: string) => mean(scores.get(run)!.get(caseId)!)\n const cases = [...scores.get(runs[0]!)!.keys()]\n .filter((caseId) => runs.every((run) => scores.get(run)!.has(caseId)))\n .sort()\n const n = cases.length\n const pairs = runs.flatMap((a, index) => runs.slice(index + 1).map((b) => [a, b] as const))\n const runQuality = runs.map((run) => ({\n run,\n quality: n ? mean(cases.map((caseId) => scoreIn(run, caseId))) : null,\n }))\n const qualities = runQuality.flatMap((r) => (r.quality === null ? [] : [r.quality]))\n const correctness = n\n ? pairs.map(\n ([a, b]) => cases.filter((c) => right(scoreIn(a, c)) !== right(scoreIn(b, c))).length / n,\n )\n : []\n const answered = pairs.flatMap(([a, b]) => {\n const both = cases.filter((c) => answers.get(a)?.has(c) && answers.get(b)?.has(c))\n const differ = both.filter((c) => answers.get(a)!.get(c) !== answers.get(b)!.get(c))\n return both.length ? [differ.length / both.length] : []\n })\n const squared = n\n ? mean(pairs.map(([a, b]) => mean(cases.map((c) => (scoreIn(a, c) - scoreIn(b, c)) ** 2))))\n : null\n return [\n {\n profileId,\n runs: runs.length,\n n,\n runQuality,\n spread: qualities.length ? Math.max(...qualities) - Math.min(...qualities) : null,\n correctnessDisagreement: share(correctness),\n answerDisagreement: share(answered),\n rerunMargin: squared !== null && panelN > 0 ? z * Math.sqrt(squared / panelN) : null,\n },\n ]\n })\n}\n","/**\n * The numbers behind a profile-matrix decision page, computed once from the\n * matrix's RunRecords so the page and any caller read the same analysis.\n *\n * Cells often run on different numbers of cases, so the analysis keeps two\n * case sets apart. Every paired difference (from the baseline, inside a factor\n * effect, in a race) is measured on the cases both profiles scored, so each\n * comparison uses all the evidence it has and carries its own n. The panels\n * that need one case set for every profile (the frontiers, error overlap, item\n * difficulty, slices and power) use the common set of the panel profiles: the\n * profiles that scored at least `minCoverage` of the baseline's scored cases. A\n * profile under that line is reported in its own partial-coverage rows instead\n * of shrinking the common set for everyone.\n *\n * A case a profile failed has no score, so it leaves that profile's cases\n * instead of counting as wrong, and the failure shows as its failure rate.\n * Cases drawn from one source (a docket, a repository, a user) are not\n * independent, so intervals resample whole clusters when the caller names them.\n */\n\nimport { ValidationError } from '../../errors'\nimport { clusteredPower } from '../../experiment/power'\nimport { brierScore, type CalibrationBin, calibrationFromPairs } from '../../meta-eval/calibration'\nimport { paretoFrontier } from '../../pareto'\nimport { type RunRecord, runTaskScore } from '../../run-record'\nimport {\n clusteredPairedContrast,\n clusterJackknife,\n mcnemarRequiredN,\n percentileNearestRank,\n requiredPairedSampleSize,\n wilson,\n} from '../../statistics'\nimport { mean } from '../../statistics/mean'\nimport {\n type ProfileMatrixFamily,\n type ProfileMatrixRunStability,\n type ProfileMatrixVerdict,\n runOf,\n runStability,\n withVerdicts,\n} from './profile-matrix-stability'\nimport type { ProfileMatrixRaceResult } from './race-profile-matrix'\n\n/** A cost drawn against quality. `seconds` is the latency axis. */\nexport type ProfileMatrixCostAxis = 'usd' | 'tokens' | 'seconds'\n\nexport const PROFILE_MATRIX_COST_AXES: readonly ProfileMatrixCostAxis[] = [\n 'usd',\n 'tokens',\n 'seconds',\n]\n\nexport interface ProfileMatrixReportOptions {\n /** A `runProfileMatrix` or `raceProfileMatrix` result, or the RunRecords alone. */\n source: { readonly records: readonly RunRecord[] } | readonly RunRecord[]\n /** Profile id (`candidateId`) every paired difference is measured against. */\n baseline: string\n /** Profiles to compare, in display order. Default: every profile in the records, baseline first. */\n profiles?: readonly string[]\n /**\n * Share of the baseline's scored cases a profile must also have scored to join the\n * common-set panels, in (0, 1]. Default 0.9. When the source is a race result, its\n * survivors form the panel instead.\n */\n minCoverage?: number\n /** Independent unit per case id. Every scored case needs one; default one unit per case. */\n clusters?: Readonly<Record<string, string>>\n /** Slice per case id for the slice heatmap. */\n slices?: Readonly<Record<string, string>>\n /** Factor levels per profile id, such as model, harness, effort or instructions. */\n factors?: Readonly<Record<string, Readonly<Record<string, string>>>>\n /** Costs to draw against quality. Default all three; an axis without measurements is reported, not drawn. */\n costAxes?: readonly ProfileMatrixCostAxis[]\n /** A case counts as correct at or above this score. Default 0.5, which pass/fail scores do not notice. */\n passScore?: number\n /** The profile's own forecast, in [0, 1], that its answer is correct, when it returned one. */\n probabilityOf?: (record: RunRecord) => number | undefined\n /**\n * The answer a record gave, such as its label, so the run-to-run panel can count answers that\n * change between runs; without it the panel counts only changes of correctness.\n */\n answerOf?: (record: RunRecord) => string | undefined\n /** A race over these profiles: the page prints its elimination log and its selection-bias note. */\n race?: ProfileMatrixRaceResult\n /** Interval level. Default 0.95. */\n level?: number\n title?: string\n}\n\nexport interface ProfileMatrixInterval {\n estimate: number\n /** Null when the interval is undefined, as with fewer than two clusters. */\n low: number | null\n high: number | null\n}\n\n/** One profile against another on the cases both scored. */\nexport interface ProfileMatrixPairedDifference extends ProfileMatrixInterval {\n /** Cases both profiles scored. */\n n: number\n /** Independent clusters among those cases. */\n clusters: number\n /** Exact cluster sign-flip p-value for a zero difference. */\n pValue: number | null\n /** Share of the paired cases where exactly one of the two profiles was correct. */\n discordance: number\n /** Paired cases a two-sided test needs for 80% power at the observed difference; null at a zero difference. Ignores clustering. */\n casesToResolve: number | null\n}\n\nexport {\n intervalSide,\n type ProfileMatrixFamily,\n type ProfileMatrixPairwiseShare,\n type ProfileMatrixRunStability,\n type ProfileMatrixVerdict,\n} from './profile-matrix-stability'\n\nexport interface ProfileMatrixProfileStats {\n profileId: string\n factors: Readonly<Record<string, string>>\n /** Distinct runs among this profile's records by `outcome.raw.rep`; a record without one is run 0. */\n runs: number\n casesAttempted: number\n casesScored: number\n /** Share of this profile's records without a score: a dispatch or judge failure. */\n failureRate: number\n /** Share of the baseline's scored cases this profile also scored. */\n coverage: number\n /** In the common-set panels: the frontiers, error overlap, difficulty, slices and power. */\n panel: boolean\n /** Cases this profile and the baseline both scored, the n of `vsBaseline`; on the baseline, its own scored cases. */\n pairedN: number\n /** The race batch whose standings dropped this profile. */\n droppedAtBatch?: number\n /** Mean score on this profile's own scored cases. */\n ownQuality: ProfileMatrixInterval | null\n /** Mean score on the common set; null outside the panel. */\n quality: ProfileMatrixInterval | null\n /** Paired difference from the baseline on the cases both scored; absent on the baseline. */\n vsBaseline?: ProfileMatrixPairedDifference\n /** Holm-adjusted `vsBaseline.pValue` over the family; null without a p-value. */\n adjustedPValue?: number | null\n /** Standing against the baseline after the family adjustment; absent on the baseline. */\n verdict?: ProfileMatrixVerdict\n /** Mean per common case; null outside the panel or when a record in it did not measure that cost. */\n costPerCase: Record<ProfileMatrixCostAxis, number | null>\n /** Common-set total divided by the common cases answered correctly; null outside the panel or with none correct. */\n costPerCorrect: Record<ProfileMatrixCostAxis, number | null>\n /** Seconds per common case; null outside the panel. */\n latency: { p50: number; p90: number } | null\n}\n\nexport interface ProfileMatrixAxisSummary {\n axis: ProfileMatrixCostAxis\n drawn: boolean\n /** What the axis measures, or why it is not drawn. */\n note: string\n /** Panel profiles on the quality-versus-this-axis Pareto set, cheapest first. */\n frontier: string[]\n}\n\nexport interface ProfileMatrixFactorEffect {\n factor: string\n level: string\n /** The baseline's level of this factor, or its most common level. */\n reference: string\n /** Profile pairs that differ only in this factor; zero means the effect is confounded. */\n matchedPairs: number\n /** Cases at least one matched pair scored on both sides. */\n n: number\n /** Fewest and most cases one matched pair shares; null without a matched pair. */\n pairCases: { min: number; max: number } | null\n /** Mean over those cases of the matched pairs' mean difference on each case. */\n effect: ProfileMatrixInterval | null\n pValue: number | null\n}\n\nexport interface ProfileMatrixSliceCell {\n profileId: string\n slice: string\n /** Common cases in the slice. */\n n: number\n quality: number | null\n}\n\nexport interface ProfileMatrixErrorOverlap {\n a: string\n b: string\n /** Share of common cases both got wrong. */\n bothWrong: number\n /** Share of common cases exactly one got right. */\n disagree: number\n}\n\nexport interface ProfileMatrixCaseDifficulty {\n caseId: string\n slice?: string\n /** Panel profiles that got the case right. */\n solved: number\n /** Panel profiles that scored the case. */\n scored: number\n share: number\n}\n\nexport interface ProfileMatrixCalibration {\n profileId: string\n n: number\n ece: number\n brier: number\n bins: CalibrationBin[]\n}\n\nexport interface ProfileMatrixPower {\n n: number\n clusters: number\n /** Median share of common cases on which a panel profile and the baseline disagree on correctness. */\n discordance: number\n /** Smallest paired difference detected with 80% power; null when not even a difference of 1 is. */\n detectable: number | null\n /** False when this many clusters cannot reach the level by an exact sign-flip test at any effect. */\n certifiable: boolean\n minClusters: number\n}\n\nexport interface ProfileMatrixAnalysis {\n title: string\n baseline: string\n level: number\n passScore: number\n /** True when every per-case score is 0 or 1. */\n passFail: boolean\n minCoverage: number\n /** `coverage`: profiles at `minCoverage` or above; `race-survivors`: the source race's survivors. */\n panelRule: 'coverage' | 'race-survivors'\n /** Profiles in the common-set panels, baseline first. */\n panelProfiles: string[]\n /** Cases every panel profile scored: the set the frontiers, overlap, difficulty, slices and power use. */\n commonCases: string[]\n commonClusters: number\n axes: ProfileMatrixAxisSummary[]\n /** Every profile, baseline first; `panel` marks the panel profiles. */\n profiles: ProfileMatrixProfileStats[]\n /** The comparisons each profile's `verdict` is adjusted over. */\n family: ProfileMatrixFamily\n /** Every profile with two or more runs, in profile order. */\n stability: ProfileMatrixRunStability[]\n factorEffects: ProfileMatrixFactorEffect[]\n /** Slice names, the slice with the most common cases first. */\n slices: string[]\n sliceCells: ProfileMatrixSliceCell[]\n errorOverlap: ProfileMatrixErrorOverlap[]\n /** Share of common cases at least one panel profile got right. */\n oracle: number | null\n difficulty: ProfileMatrixCaseDifficulty[]\n calibration: ProfileMatrixCalibration[]\n power: ProfileMatrixPower | null\n}\n\n/** How two profiles are paired: clusters, level, and what counts as correct. */\nexport interface ProfilePairingRule {\n clusterOf: (caseId: string) => string\n level: number\n passScore: number\n /** Every score is 0 or 1, so the required n follows McNemar. */\n passFail: boolean\n}\n\nconst TARGET_POWER = 0.8\nconst UNLABELLED_SLICE = 'unlabelled'\n\n/** One profile's records on one case, reps averaged. */\ninterface CaseCost {\n usd: number | null\n tokens: number | null\n seconds: number\n}\n\ninterface Context {\n options: ProfileMatrixReportOptions\n rule: ProfilePairingRule\n minCoverage: number\n race: ProfileMatrixRaceResult | undefined\n panelRule: ProfileMatrixAnalysis['panelRule']\n profileIds: string[]\n panel: string[]\n scores: Map<string, Map<string, number>>\n costs: Map<string, Map<string, CaseCost>>\n recordsByProfile: Map<string, RunRecord[]>\n baselineCases: string[]\n common: string[]\n}\n\n/**\n * Compare profile-matrix cells against one baseline: quality with clustered\n * intervals, paired differences, the cost and latency frontiers, factor main\n * effects, slices, error overlap, item difficulty, calibration and power.\n *\n * A profile run more than once (its records carry `outcome.raw.rep`, as campaign\n * records do) scores each case at its mean over the runs, and `stability` measures\n * how far its runs differ with nothing changed. Each verdict against the baseline\n * is Holm-adjusted over every profile-against-baseline comparison, so with dozens\n * of profiles one lucky interval reads as a candidate, not a win.\n */\nexport function analyzeProfileMatrix(options: ProfileMatrixReportOptions): ProfileMatrixAnalysis {\n const ctx = buildContext(options)\n const { profiles, family } = withVerdicts(\n ctx.profileIds.map((profileId) => profileStats(ctx, profileId)),\n options.baseline,\n 1 - ctx.rule.level,\n )\n const panel = profiles.filter((stats) => stats.panel)\n const slices = sliceNames(ctx)\n return {\n title: options.title ?? 'Profile matrix',\n baseline: options.baseline,\n level: ctx.rule.level,\n passScore: ctx.rule.passScore,\n passFail: ctx.rule.passFail,\n minCoverage: ctx.minCoverage,\n panelRule: ctx.panelRule,\n panelProfiles: ctx.panel,\n commonCases: ctx.common,\n commonClusters: new Set(ctx.common.map((caseId) => ctx.rule.clusterOf(caseId))).size,\n axes: axisSummaries(ctx, panel),\n profiles,\n family,\n stability: runStability({\n profileIds: ctx.profileIds,\n recordsByProfile: ctx.recordsByProfile,\n answerOf: options.answerOf,\n level: ctx.rule.level,\n passScore: ctx.rule.passScore,\n commonCases: ctx.common.length,\n }),\n factorEffects: factorEffects(ctx),\n slices,\n sliceCells: sliceCells(ctx, slices),\n ...errorOverlap(ctx),\n difficulty: difficulty(ctx),\n calibration: calibration(ctx),\n power: power(ctx, panel),\n }\n}\n\n/** Mean score per profile and case over its scored reps; a case without a scored rep is absent. */\nexport function scoresByProfile(records: readonly RunRecord[]): Map<string, Map<string, number>> {\n const scored = new Map<string, Map<string, number[]>>()\n for (const record of records) {\n const score = runTaskScore(record)\n if (score === undefined) continue\n const cases = scored.get(record.candidateId) ?? new Map<string, number[]>()\n cases.set(record.scenarioId, [...(cases.get(record.scenarioId) ?? []), score])\n scored.set(record.candidateId, cases)\n }\n return new Map(\n [...scored].map(([id, cases]) => [id, new Map([...cases].map(([c, xs]) => [c, mean(xs)]))]),\n )\n}\n\n/**\n * Profile `a` against profile `b` on the cases both scored, restricted to `cases` when\n * given. Every paired number on the page and in the race comes from here.\n */\nexport function pairProfiles(\n a: ReadonlyMap<string, number>,\n b: ReadonlyMap<string, number>,\n rule: ProfilePairingRule,\n cases?: readonly string[],\n): ProfileMatrixPairedDifference | undefined {\n const both = (cases ?? [...a.keys()]).filter((c) => a.has(c) && b.has(c)).sort()\n if (both.length === 0) return undefined\n const deltas = both.map((caseId) => ({ caseId, delta: a.get(caseId)! - b.get(caseId)! }))\n const right = (score: number) => score >= rule.passScore\n const wins = both.filter((c) => right(a.get(c)!) && !right(b.get(c)!)).length\n const losses = both.filter((c) => !right(a.get(c)!) && right(b.get(c)!)).length\n return {\n ...clusteredDifference(deltas, rule.clusterOf, rule.level),\n discordance: (wins + losses) / both.length,\n casesToResolve: casesToResolve(\n rule,\n deltas.map((d) => d.delta),\n wins / both.length,\n losses / both.length,\n ),\n }\n}\n\n/** True when every score is 0 or 1. */\nexport function allPassFail(scores: ReadonlyMap<string, ReadonlyMap<string, number>>): boolean {\n return [...scores.values()].every((cases) =>\n [...cases.values()].every((score) => score === 0 || score === 1),\n )\n}\n\n/**\n * Each case's independent unit, one per case when no clusters are given. A case missing from\n * a given cluster map is refused rather than counted as its own unit. Shared with the race.\n */\nexport function clusterResolver(\n clusters: Readonly<Record<string, string>> | undefined,\n owner: string,\n): (caseId: string) => string {\n return (caseId) => {\n if (!clusters) return caseId\n const cluster = clusters[caseId]\n if (typeof cluster !== 'string' || cluster.length === 0) {\n throw new ValidationError(`${owner}: case '${caseId}' has no cluster`)\n }\n return cluster\n }\n}\n\n/** Mean of per-case differences with its cluster-jackknife interval and exact sign-flip p. */\nfunction clusteredDifference(\n deltas: readonly { caseId: string; delta: number }[],\n clusterOf: (caseId: string) => string,\n level: number,\n): ProfileMatrixInterval & { n: number; clusters: number; pValue: number | null } {\n const units = deltas.map(({ caseId, delta }) => ({ cluster: clusterOf(caseId), delta }))\n const result = clusteredPairedContrast(units, { level, seed: 1 })\n return {\n estimate: mean(deltas.map((d) => d.delta)),\n low: result.low,\n high: result.high,\n pValue: result.pValue,\n n: deltas.length,\n clusters: new Set(units.map((unit) => unit.cluster)).size,\n }\n}\n\nfunction casesToResolve(\n rule: ProfilePairingRule,\n deltas: number[],\n p10: number,\n p01: number,\n): number | null {\n const alpha = 1 - rule.level\n if (rule.passFail) {\n const needed = mcnemarRequiredN({ p10, p01, alpha, power: TARGET_POWER })\n return Number.isFinite(needed) ? needed : null\n }\n if (deltas.length < 2) return null\n const average = mean(deltas)\n const sd = Math.sqrt(deltas.reduce((sum, d) => sum + (d - average) ** 2, 0) / (deltas.length - 1))\n if (sd === 0 || average === 0) return null\n const needed = requiredPairedSampleSize({\n effect: Math.abs(average) / sd,\n alpha,\n power: TARGET_POWER,\n })\n return Number.isFinite(needed) ? needed : null\n}\n\n/** True when the source is a `raceProfileMatrix` result. */\nexport function isRaceResult(\n source: ProfileMatrixReportOptions['source'],\n): source is ProfileMatrixRaceResult {\n return 'survivors' in source && 'log' in source\n}\n\nfunction buildContext(options: ProfileMatrixReportOptions): Context {\n const level = options.level ?? 0.95\n if (!(level > 0 && level < 1))\n throw new ValidationError('profile matrix: level must be in (0, 1)')\n const passScore = options.passScore ?? 0.5\n if (!Number.isFinite(passScore))\n throw new ValidationError('profile matrix: passScore must be finite')\n const minCoverage = options.minCoverage ?? 0.9\n if (!(minCoverage > 0 && minCoverage <= 1))\n throw new ValidationError('profile matrix: minCoverage must be in (0, 1]')\n const raceSource = isRaceResult(options.source) ? options.source : undefined\n const records = 'records' in options.source ? options.source.records : options.source\n const recordsByProfile = new Map<string, RunRecord[]>()\n for (const record of records) {\n const list = recordsByProfile.get(record.candidateId) ?? []\n list.push(record)\n recordsByProfile.set(record.candidateId, list)\n }\n const listed = options.profiles ? [...options.profiles] : [...recordsByProfile.keys()]\n if (new Set(listed).size !== listed.length) {\n throw new ValidationError('profile matrix: profiles must be distinct')\n }\n const baseline = options.baseline\n const profileIds = [baseline, ...listed.filter((id) => id !== baseline)]\n for (const profileId of profileIds) {\n if (!recordsByProfile.has(profileId)) {\n throw new ValidationError(`profile matrix: profile '${profileId}' has no records`)\n }\n }\n const scored = scoresByProfile(records)\n const scores = new Map(profileIds.map((id) => [id, scored.get(id) ?? new Map<string, number>()]))\n const baselineCases = [...scores.get(baseline)!.keys()].sort()\n if (baselineCases.length === 0) {\n throw new ValidationError(`profile matrix: baseline '${baseline}' scored no case`)\n }\n const clusterOf = clusterResolver(options.clusters, 'profile matrix')\n for (const cases of scores.values()) for (const caseId of cases.keys()) clusterOf(caseId)\n const covers = (id: string) => coverageOf(scores, baselineCases, id) >= minCoverage\n const panel = raceSource\n ? profileIds.filter((id) => id === baseline || raceSource.survivors.includes(id))\n : profileIds.filter((id) => id === baseline || covers(id))\n return {\n options,\n rule: { clusterOf, level, passScore, passFail: allPassFail(scores) },\n minCoverage,\n race: options.race ?? raceSource,\n panelRule: raceSource ? 'race-survivors' : 'coverage',\n profileIds,\n panel,\n scores,\n costs: new Map(profileIds.map((id) => [id, caseCosts(recordsByProfile.get(id)!)])),\n recordsByProfile,\n baselineCases,\n common: baselineCases.filter((caseId) => panel.every((id) => scores.get(id)!.has(caseId))),\n }\n}\n\nfunction coverageOf(\n scores: Map<string, Map<string, number>>,\n baselineCases: readonly string[],\n profileId: string,\n): number {\n const own = scores.get(profileId)!\n return baselineCases.filter((caseId) => own.has(caseId)).length / baselineCases.length\n}\n\nfunction caseCosts(records: readonly RunRecord[]): Map<string, CaseCost> {\n const grouped = new Map<string, RunRecord[]>()\n for (const record of records) {\n const list = grouped.get(record.scenarioId) ?? []\n list.push(record)\n grouped.set(record.scenarioId, list)\n }\n const costs = new Map<string, CaseCost>()\n for (const [caseId, reps] of grouped) {\n costs.set(caseId, {\n usd: reps.every((r) => r.costUsd !== null) ? mean(reps.map((r) => r.costUsd!)) : null,\n tokens: reps.every((r) => r.tokenUsage.tokensKnown !== false)\n ? mean(reps.map(tokenTotal))\n : null,\n seconds: mean(reps.map(latencySeconds)),\n })\n }\n return costs\n}\n\n/** Every prompt token (fresh, cached and cache-write) plus output; reasoning is counted inside output. */\nfunction tokenTotal(record: RunRecord): number {\n const usage = record.tokenUsage\n return usage.input + (usage.cached ?? 0) + (usage.cacheWrite ?? 0) + usage.output\n}\n\n/** Dispatch time when the cell recorded it, so judging does not count as latency; else the wall clock. */\nfunction latencySeconds(record: RunRecord): number {\n const dispatchMs = record.outcome.raw.dispatch_ms\n return (Number.isFinite(dispatchMs) ? dispatchMs! : record.wallMs) / 1000\n}\n\nfunction scoreOf(ctx: Context, profileId: string, caseId: string): number {\n return ctx.scores.get(profileId)!.get(caseId)!\n}\n\nfunction correct(ctx: Context, profileId: string, caseId: string): boolean {\n return scoreOf(ctx, profileId, caseId) >= ctx.rule.passScore\n}\n\nconst NO_COST: Record<ProfileMatrixCostAxis, null> = { usd: null, tokens: null, seconds: null }\n\nfunction profileStats(ctx: Context, profileId: string): ProfileMatrixProfileStats {\n const own = [...ctx.scores.get(profileId)!.keys()]\n const records = ctx.recordsByProfile.get(profileId)!\n const isBaseline = profileId === ctx.options.baseline\n const vsBaseline = isBaseline\n ? undefined\n : pairProfiles(ctx.scores.get(profileId)!, ctx.scores.get(ctx.options.baseline)!, ctx.rule)\n const droppedAtBatch = ctx.race?.log.find((batch) =>\n batch.standings.some((s) => s.profileId === profileId && s.dropped),\n )?.batch\n const base = {\n profileId,\n factors: ctx.options.factors?.[profileId] ?? {},\n runs: new Set(records.map(runOf)).size,\n casesAttempted: ctx.costs.get(profileId)!.size,\n casesScored: own.length,\n failureRate: records.filter((r) => runTaskScore(r) === undefined).length / records.length,\n coverage: coverageOf(ctx.scores, ctx.baselineCases, profileId),\n panel: ctx.panel.includes(profileId),\n pairedN: isBaseline ? own.length : (vsBaseline?.n ?? 0),\n ...(droppedAtBatch === undefined ? {} : { droppedAtBatch }),\n ownQuality: qualityOn(ctx, profileId, own),\n ...(vsBaseline ? { vsBaseline } : {}),\n }\n if (!base.panel) {\n return { ...base, quality: null, costPerCase: NO_COST, costPerCorrect: NO_COST, latency: null }\n }\n const costs = ctx.common.map((caseId) => ctx.costs.get(profileId)!.get(caseId)!)\n const correctCount = ctx.common.filter((caseId) => correct(ctx, profileId, caseId)).length\n const costPerCase = {} as Record<ProfileMatrixCostAxis, number | null>\n const costPerCorrect = {} as Record<ProfileMatrixCostAxis, number | null>\n for (const axis of PROFILE_MATRIX_COST_AXES) {\n const values = costs.map((cost) => cost[axis])\n const known = values.length > 0 && values.every((value) => value !== null)\n costPerCase[axis] = known ? mean(values as number[]) : null\n costPerCorrect[axis] =\n known && correctCount > 0\n ? (values as number[]).reduce((a, b) => a + b, 0) / correctCount\n : null\n }\n const seconds = costs.map((cost) => cost.seconds)\n return {\n ...base,\n quality: qualityOn(ctx, profileId, ctx.common),\n costPerCase,\n costPerCorrect,\n latency:\n seconds.length > 0\n ? { p50: percentileNearestRank(seconds, 50), p90: percentileNearestRank(seconds, 90) }\n : null,\n }\n}\n\n/** Mean score on `cases`: Wilson for unclustered pass/fail scores, the cluster jackknife otherwise. */\nfunction qualityOn(\n ctx: Context,\n profileId: string,\n cases: readonly string[],\n): ProfileMatrixInterval | null {\n const items = cases.map((caseId) => ({ caseId, score: scoreOf(ctx, profileId, caseId) }))\n if (items.length === 0) return null\n const estimate = mean(items.map((item) => item.score))\n if (ctx.rule.passFail && !ctx.options.clusters) {\n const successes = items.filter((item) => item.score === 1).length\n const interval = wilson(successes, items.length, ctx.rule.level)\n return { estimate, low: interval.lower, high: interval.upper }\n }\n const interval = clusterJackknife(\n items,\n (item) => ctx.rule.clusterOf(item.caseId),\n (sample) => mean(sample.map((item) => item.score)),\n { level: ctx.rule.level },\n )\n return { estimate, low: interval.low, high: interval.high }\n}\n\nfunction axisSummaries(\n ctx: Context,\n panel: readonly ProfileMatrixProfileStats[],\n): ProfileMatrixAxisSummary[] {\n const requested = ctx.options.costAxes ?? PROFILE_MATRIX_COST_AXES\n return requested.map((axis) => {\n const x = (stats: ProfileMatrixProfileStats) =>\n axis === 'seconds' ? (stats.latency?.p50 ?? null) : stats.costPerCase[axis]\n const unmeasured = panel.filter((stats) => x(stats) === null)\n const reason =\n ctx.common.length === 0\n ? 'no case was scored by every panel profile'\n : unmeasured.length > 0\n ? `${unmeasured.length} of ${panel.length} panel profiles did not measure it on every common case`\n : axis === 'usd' && panel.every((stats) => x(stats) === 0)\n ? 'every profile costs $0 at the margin, as on flat-rate seats'\n : null\n if (reason !== null) return { axis, drawn: false, note: reason, frontier: [] }\n const { frontier } = paretoFrontier(\n [...panel],\n [\n { name: 'quality', direction: 'maximize', value: (stats) => stats.quality!.estimate },\n { name: axis, direction: 'minimize', value: (stats) => x(stats)! },\n ],\n )\n return {\n axis,\n drawn: true,\n note: AXIS_NOTES[axis],\n frontier: frontier.sort((a, b) => x(a)! - x(b)!).map((stats) => stats.profileId),\n }\n })\n}\n\nconst AXIS_NOTES: Record<ProfileMatrixCostAxis, string> = {\n usd: 'mean dollars per common case',\n tokens:\n 'mean tokens per common case: every prompt token, cached included, plus output with reasoning counted once',\n seconds:\n 'median seconds per common case: dispatch time, or the cell wall clock where dispatch time was not recorded',\n}\n\n/**\n * Each level against the reference over matched pairs: profiles that differ only in this\n * factor. Each pair is compared on the cases it shares; a case's delta is the mean over the\n * pairs that share it, so a case counts once and the clusters stay independent.\n */\nfunction factorEffects(ctx: Context): ProfileMatrixFactorEffect[] {\n const factors = ctx.options.factors\n if (!factors) return []\n const levelOf = (profileId: string, factor: string) => factors[profileId]?.[factor]\n const names = [...new Set(ctx.profileIds.flatMap((id) => Object.keys(factors[id] ?? {})))].sort()\n const effects: ProfileMatrixFactorEffect[] = []\n for (const factor of names) {\n const defined = ctx.profileIds.filter((id) => levelOf(id, factor) !== undefined)\n const counts = new Map<string, number>()\n for (const id of defined)\n counts.set(levelOf(id, factor)!, (counts.get(levelOf(id, factor)!) ?? 0) + 1)\n const reference =\n levelOf(ctx.options.baseline, factor) ??\n [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]![0]\n for (const level of [...counts.keys()].filter((l) => l !== reference).sort()) {\n const matched = defined.flatMap((p) =>\n levelOf(p, factor) !== level\n ? []\n : defined\n .filter(\n (q) => levelOf(q, factor) === reference && differOnlyIn(factors, p, q, factor),\n )\n .map((q) => [p, q] as const),\n )\n const perCase = new Map<string, number[]>()\n const pairSizes = matched.map(([p, q]) => {\n const [a, b] = [ctx.scores.get(p)!, ctx.scores.get(q)!]\n const both = [...a.keys()].filter((caseId) => b.has(caseId))\n for (const caseId of both) {\n perCase.set(caseId, [...(perCase.get(caseId) ?? []), a.get(caseId)! - b.get(caseId)!])\n }\n return both.length\n })\n const base = {\n factor,\n level,\n reference,\n matchedPairs: matched.length,\n n: perCase.size,\n pairCases: matched.length\n ? { min: Math.min(...pairSizes), max: Math.max(...pairSizes) }\n : null,\n }\n if (perCase.size === 0) {\n effects.push({ ...base, effect: null, pValue: null })\n continue\n }\n const deltas = [...perCase]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([caseId, values]) => ({ caseId, delta: mean(values) }))\n const { pValue, estimate, low, high } = clusteredDifference(\n deltas,\n ctx.rule.clusterOf,\n ctx.rule.level,\n )\n effects.push({ ...base, effect: { estimate, low, high }, pValue })\n }\n }\n return effects\n}\n\nfunction differOnlyIn(\n factors: Readonly<Record<string, Readonly<Record<string, string>>>>,\n p: string,\n q: string,\n factor: string,\n): boolean {\n const keys = new Set([...Object.keys(factors[p] ?? {}), ...Object.keys(factors[q] ?? {})])\n return [...keys].every((key) => key === factor || factors[p]?.[key] === factors[q]?.[key])\n}\n\nfunction sliceOf(ctx: Context, caseId: string): string | undefined {\n const slices = ctx.options.slices\n return slices ? (slices[caseId] ?? UNLABELLED_SLICE) : undefined\n}\n\n/** Slices with the most common cases first, so the columns that carry evidence lead. */\nfunction sliceNames(ctx: Context): string[] {\n if (!ctx.options.slices) return []\n const counts = new Map<string, number>()\n for (const caseId of ctx.common) {\n const slice = sliceOf(ctx, caseId)!\n counts.set(slice, (counts.get(slice) ?? 0) + 1)\n }\n return [...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([slice]) => slice)\n}\n\nfunction sliceCells(ctx: Context, slices: readonly string[]): ProfileMatrixSliceCell[] {\n return ctx.panel.flatMap((profileId) =>\n slices.map((slice) => {\n const cases = ctx.common.filter((caseId) => sliceOf(ctx, caseId) === slice)\n const scores = cases.map((caseId) => scoreOf(ctx, profileId, caseId))\n return { profileId, slice, n: scores.length, quality: scores.length ? mean(scores) : null }\n }),\n )\n}\n\nfunction errorOverlap(ctx: Context): Pick<ProfileMatrixAnalysis, 'errorOverlap' | 'oracle'> {\n const n = ctx.common.length\n const pairs: ProfileMatrixErrorOverlap[] = []\n ctx.panel.forEach((a, index) => {\n for (const b of ctx.panel.slice(index + 1)) {\n const right = ctx.common.map((c) => [correct(ctx, a, c), correct(ctx, b, c)] as const)\n pairs.push({\n a,\n b,\n bothWrong: n ? right.filter(([x, y]) => !x && !y).length / n : 0,\n disagree: n ? right.filter(([x, y]) => x !== y).length / n : 0,\n })\n }\n })\n const solved = ctx.common.filter((c) => ctx.panel.some((p) => correct(ctx, p, c))).length\n return { errorOverlap: pairs, oracle: n ? solved / n : null }\n}\n\nfunction difficulty(ctx: Context): ProfileMatrixCaseDifficulty[] {\n return ctx.common\n .map((caseId) => {\n const solved = ctx.panel.filter((p) => correct(ctx, p, caseId)).length\n const slice = sliceOf(ctx, caseId)\n return {\n caseId,\n ...(slice === undefined ? {} : { slice }),\n solved,\n scored: ctx.panel.length,\n share: solved / ctx.panel.length,\n }\n })\n .sort((a, b) => a.share - b.share || a.caseId.localeCompare(b.caseId))\n}\n\nfunction calibration(ctx: Context): ProfileMatrixCalibration[] {\n const probabilityOf = ctx.options.probabilityOf\n if (!probabilityOf) return []\n return ctx.profileIds.flatMap((profileId) => {\n const pairs = ctx.recordsByProfile.get(profileId)!.flatMap((record) => {\n const score = runTaskScore(record)\n const probability = probabilityOf(record)\n if (score === undefined || probability === undefined) return []\n if (!(probability >= 0 && probability <= 1)) {\n throw new ValidationError(\n `profile matrix: profile '${profileId}' returned probability ${probability} outside [0, 1]`,\n )\n }\n return [{ evalScore: probability, outcome: score >= ctx.rule.passScore ? 1 : 0 }]\n })\n const report = calibrationFromPairs(pairs, 'probability', 'correct', {\n bins: 10,\n range: { lo: 0, hi: 1 },\n })\n if (report === null) return []\n return [\n { profileId, n: report.n, ece: report.ece, brier: brierScore(pairs), bins: report.bins },\n ]\n })\n}\n\nfunction power(\n ctx: Context,\n panel: readonly ProfileMatrixProfileStats[],\n): ProfileMatrixPower | null {\n const baselineScores = ctx.scores.get(ctx.options.baseline)!\n const discordances = panel\n .filter((stats) => stats.profileId !== ctx.options.baseline)\n .map(\n (stats) =>\n pairProfiles(ctx.scores.get(stats.profileId)!, baselineScores, ctx.rule, ctx.common)\n ?.discordance,\n )\n .filter((value) => value !== undefined)\n .sort((a, b) => a - b)\n if (ctx.common.length < 2 || discordances.length === 0) return null\n const discordance = discordances[Math.floor((discordances.length - 1) / 2)]!\n const sizes = new Map<string, number>()\n for (const caseId of ctx.common) {\n const cluster = ctx.rule.clusterOf(caseId)\n sizes.set(cluster, (sizes.get(cluster) ?? 0) + 1)\n }\n const clusterSizes = [...sizes.values()]\n // The observed discordance is the noise floor: half of it wins and half of\n // it loses under no effect, and an effect adds wins on top of it.\n const powerAt = (effect: number) =>\n clusteredPower({\n clusterSizes,\n effects: [effect],\n minimumEffect: effect,\n seed: 1,\n trials: 400,\n resamples: 800,\n confidence: ctx.rule.level,\n alpha: 1 - ctx.rule.level,\n targetPower: TARGET_POWER,\n baseWinRate: discordance / 2,\n baseLossRate: discordance / 2,\n })\n const largest = powerAt(1)\n let detectable: number | null = null\n if (largest.powerAtMinimumEffect >= TARGET_POWER) {\n let [low, high] = [0, 1]\n for (let step = 0; step < 7; step++) {\n const middle = (low + high) / 2\n if (powerAt(middle).powerAtMinimumEffect >= TARGET_POWER) high = middle\n else low = middle\n }\n detectable = high\n }\n return {\n n: ctx.common.length,\n clusters: clusterSizes.length,\n discordance,\n detectable,\n certifiable: largest.signFlipFloor.certifiableAtAlpha,\n minClusters: largest.signFlipFloor.minClustersForAlpha,\n }\n}\n","/**\n * The profile-matrix decision page: one self-contained HTML string (inline\n * SVG and CSS, no network, light and dark) rendered from\n * `analyzeProfileMatrix`, so the page shows exactly the numbers a caller reads.\n */\n\nimport { escapeHtml as esc } from '../../reporting-html'\nimport {\n analyzeProfileMatrix,\n intervalSide,\n isRaceResult,\n type ProfileMatrixAnalysis,\n type ProfileMatrixAxisSummary,\n type ProfileMatrixCostAxis,\n type ProfileMatrixFactorEffect,\n type ProfileMatrixInterval,\n type ProfileMatrixPairedDifference,\n type ProfileMatrixPairwiseShare,\n type ProfileMatrixProfileStats,\n type ProfileMatrixReportOptions,\n type ProfileMatrixVerdict,\n} from './profile-matrix-analysis'\nimport type { ProfileMatrixRaceResult } from './race-profile-matrix'\n\n/** Render the decision page for a profile matrix or a race over one. */\nexport function renderProfileMatrixReport(options: ProfileMatrixReportOptions): string {\n const a = analyzeProfileMatrix(options)\n const race = options.race ?? (isRaceResult(options.source) ? options.source : undefined)\n const sections = [\n section('Frontier', frontier(a)),\n section('Profiles', profileTable(a)),\n ...(a.profiles.some((p) => !p.panel) ? [section('Partial coverage', partialTable(a))] : []),\n section('Run-to-run stability', stability(a)),\n section('Factor main effects', factorTable(a)),\n section('Slices', sliceHeatmap(a)),\n section('Error overlap', overlap(a)),\n section('Item difficulty', difficulty(a)),\n section('Calibration', calibration(a)),\n section('Power', `<p>${powerSentence(a)}</p>`),\n ...(race ? [section('Race', raceSection(race))] : []),\n ]\n return [\n '<!doctype html>',\n '<html lang=\"en\">',\n '<head>',\n '<meta charset=\"utf-8\">',\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">',\n `<title>${esc(a.title)}</title>`,\n `<meta name=\"description\" content=\"${esc(description(a))}\">`,\n `<style>${STYLE}</style>`,\n '</head>',\n '<body><main>',\n `<h1>${esc(a.title)}</h1>`,\n `<div class=\"decision\">${decision(a, race)}</div>`,\n ...sections,\n '</main></body></html>',\n ].join('\\n')\n}\n\nconst STYLE = `\n:root{color-scheme:light;--surface:#fcfcfb;--panel:#ffffff;--border:#e4e3de;--grid:#ecebe7;\n--text:#0b0b0b;--text-2:#52514e;--text-3:#7a7974;--accent:#2a78d6;--base:#eb6834;--better:#2a78d6;\n--worse:#e34948;--flat:#9b9a95;--seq:#1c5cab;--seq-2:#eb6834;--on-seq:#ffffff;--thin:#efeeea}\n@media (prefers-color-scheme:dark){:root:not([data-theme=\"light\"]){color-scheme:dark;--surface:#1a1a19;\n--panel:#222221;--border:#383835;--grid:#2c2c2a;--text:#f0efec;--text-2:#c3c2b7;--text-3:#8f8e86;\n--accent:#3987e5;--base:#d95926;--better:#3987e5;--worse:#e66767;--flat:#77766f;--seq:#6da7ec;\n--seq-2:#d95926;--on-seq:#0b0b0b;--thin:#2a2a28}}\n:root[data-theme=\"dark\"]{color-scheme:dark;--surface:#1a1a19;--panel:#222221;--border:#383835;\n--grid:#2c2c2a;--text:#f0efec;--text-2:#c3c2b7;--text-3:#8f8e86;--accent:#3987e5;--base:#d95926;\n--better:#3987e5;--worse:#e66767;--flat:#77766f;--seq:#6da7ec;--seq-2:#d95926;--on-seq:#0b0b0b;--thin:#2a2a28}\n*{box-sizing:border-box}\nbody{margin:0;background:var(--surface);color:var(--text);\nfont:15px/1.5 ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",sans-serif}\nmain{max-width:1120px;margin:0 auto;padding:32px 16px 64px}\nh1{font-size:28px;line-height:1.2;margin:0 0 16px}\nh2{font-size:19px;margin:40px 0 8px;padding-top:20px;border-top:1px solid var(--border)}\np{margin:8px 0}.muted{color:var(--text-3)}.note{color:var(--text-2);font-size:13px}\n.decision{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:12px 16px}\n.decision p{margin:6px 0}\n.scroll{overflow-x:auto;margin:12px 0}\ntable{border-collapse:collapse;font-size:13px;font-variant-numeric:tabular-nums}\nth,td{padding:6px 8px;border-bottom:1px solid var(--border);text-align:right;white-space:nowrap}\nth{color:var(--text-2);font-weight:600}th:first-child,td:first-child{text-align:left}\ntd .sub{display:block;color:var(--text-3);font-size:11px}\ntd.cell{text-align:center;min-width:64px}td.cell .sub{color:inherit;opacity:.75}\ntd.tight{min-width:40px;padding:6px 3px}td.thin{background:var(--thin);color:var(--text-3)}\ntd.diag{color:var(--text-3)}\n.charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,460px),1fr));gap:16px}\nfigure{margin:12px 0;background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:8px}\nfigcaption{font-size:12px;color:var(--text-2);padding:4px 6px}\nsvg{display:block;width:100%;height:auto}svg text{fill:var(--text-2);font-size:11px}\nsvg .title{fill:var(--text);font-size:12px;font-weight:600}\n.grid{stroke:var(--grid);stroke-width:1}.zero{stroke:var(--text-3);stroke-width:1}\n.whisker{stroke:var(--flat);stroke-width:1.5;stroke-opacity:.45}\n.leader{stroke:var(--text-2);stroke-width:.75;stroke-opacity:.6}.step{fill:none;stroke:var(--accent);stroke-width:2;stroke-dasharray:4 3}\n.pt{fill:var(--flat);stroke:var(--panel);stroke-width:2}.pt.front{fill:var(--accent)}\n.ring{fill:none;stroke:var(--base);stroke-width:2}.pt:hover{stroke:var(--text)}\n.forest{width:120px;height:16px;display:inline-block;vertical-align:middle}\n.ci{stroke-width:2}.ci.up,.up{stroke:var(--better);fill:var(--better)}\n.ci.down,.down{stroke:var(--worse);fill:var(--worse)}.ci.flat,.flat{stroke:var(--flat);fill:var(--flat)}\n.ci.cand{stroke-dasharray:3 2}circle.cand{fill:var(--panel);stroke-width:1.5}\n.bar{fill:var(--accent)}.bar:hover{fill:var(--text-2)}.diagonal{stroke:var(--text-3);stroke-dasharray:3 3}\n.cal{fill:none;stroke:var(--accent);stroke-width:2}.calpt{fill:var(--accent);stroke:var(--panel);stroke-width:2}\n.callout{border-left:3px solid var(--base);padding:6px 12px;background:var(--panel)}\n.small-multiples{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}\n`\n\nfunction section(title: string, body: string): string {\n return `<section><h2>${esc(title)}</h2>\\n${body}\\n</section>`\n}\n\nfunction num(value: number | null | undefined, digits = 3): string {\n return value === null || value === undefined || !Number.isFinite(value)\n ? '—'\n : value.toFixed(digits)\n}\n\nfunction signed(value: number | null | undefined, digits = 3): string {\n if (value === null || value === undefined || !Number.isFinite(value)) return '—'\n return `${value > 0 ? '+' : value < 0 ? '-' : '±'}${Math.abs(value).toFixed(digits)}`\n}\n\nfunction pct(value: number | null | undefined): string {\n return value === null || value === undefined ? '—' : `${Math.round(value * 100)}%`\n}\n\n/** An interval as text; a zero-width one says so, since it means no spread to measure, not certainty. */\nfunction bounds(i: { low: number | null; high: number | null }, f = signed): string {\n if (i.low === null || i.high === null) return 'no interval'\n return i.low === i.high ? 'no spread across clusters' : `[${f(i.low)}, ${f(i.high)}]`\n}\n\nfunction grouped(value: number): string {\n return Math.round(value)\n .toString()\n .replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n}\n\nfunction cost(axis: ProfileMatrixCostAxis, value: number | null): string {\n if (value === null) return '—'\n if (axis === 'usd') return `$${value < 0.1 ? value.toFixed(4) : value.toFixed(2)}`\n if (axis === 'tokens') return grouped(value)\n return `${value < 10 ? value.toFixed(1) : grouped(value)} s`\n}\n\nfunction pct1(value: number): string {\n return `${(value * 100).toFixed(1)}%`\n}\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`\n}\n\n/** One value, or the lowest to the highest of several. */\nfunction lowToHigh(values: readonly number[], f: (value: number) => string): string {\n const [low, high] = [Math.min(...values), Math.max(...values)]\n return f(low) === f(high) ? f(low) : `${f(low)} to ${f(high)}`\n}\n\nconst DIRECTION_WORD = { up: 'better', down: 'worse', flat: 'unresolved' } as const\n\nconst P_NOTE =\n 'Better and worse follow the interval. p is the exact sign-flip test over clusters, which ' +\n 'stays high when few clusters disagree even if the interval excludes zero: read both.'\n\nfunction common(a: ProfileMatrixAnalysis): string {\n return `${a.commonCases.length} common case${a.commonCases.length === 1 ? '' : 's'}`\n}\n\nfunction panelOf(a: ProfileMatrixAnalysis): ProfileMatrixProfileStats[] {\n return a.profiles.filter((p) => p.panel)\n}\n\nfunction withVerdict(a: ProfileMatrixAnalysis, verdict: ProfileMatrixVerdict) {\n return a.profiles.filter((p) => p.verdict === verdict)\n}\n\n/** The family the verdicts are adjusted over, as the page names it everywhere. */\nfunction familyName(a: ProfileMatrixAnalysis): string {\n const { alpha, comparisons } = a.family\n return `familywise ${pct(alpha)} (Holm) over ${plural(comparisons, 'comparison')}`\n}\n\nfunction description(a: ProfileMatrixAnalysis): string {\n const count = (verdict: ProfileMatrixVerdict) => withVerdict(a, verdict).length\n return (\n `${a.profiles.length} profiles against ${a.baseline}, each paired on the cases it shares with it: ` +\n `${count('better')} better and ${count('worse')} worse at ${familyName(a)}, ` +\n `${plural(count('candidate'), 'candidate')} whose nominal ${pct(a.level)} interval excludes zero, ` +\n `${count('unresolved')} unresolved; ${a.panelProfiles.length} panel profiles on ${common(a)}; ` +\n `${plural(a.stability.length, 'profile')} run more than once.`\n )\n}\n\n/**\n * A paired difference as two cells: its own n with clusters, then the estimate with a word, the\n * interval and p. The word is the nominal interval's side unless a standing replaces it.\n */\nfunction pairedCells(\n vs: ProfileMatrixPairedDifference | null | undefined,\n standing?: { word: string; sub: string },\n): [string, string] {\n if (!vs) return ['—', '—']\n return [\n `${vs.n}<span class=\"sub\">${vs.clusters} cluster${vs.clusters === 1 ? '' : 's'}</span>`,\n `${signed(vs.estimate)} ${standing?.word ?? DIRECTION_WORD[intervalSide(vs)]}` +\n `<span class=\"sub\">${bounds(vs)}, p ${num(vs.pValue)}${standing?.sub ?? ''}</span>`,\n ]\n}\n\n/** A profile's paired difference from the baseline with its family-adjusted verdict. */\nfunction verdictCells(p: ProfileMatrixProfileStats): [string, string] {\n const oneRun = p.verdict !== 'unresolved' && p.runs === 1\n return pairedCells(p.vsBaseline, {\n word: `${p.verdict}${oneRun ? ' <span class=\"muted\">1 run</span>' : ''}`,\n sub: `, Holm p ${num(p.adjustedPValue)}`,\n })\n}\n\nfunction verdictNote(a: ProfileMatrixAnalysis): string {\n return (\n `Better and worse are at ${familyName(a)}: the nominal ${pct(a.level)} interval excludes zero ` +\n `and the Holm-adjusted p (Holm p) is at most ${num(a.family.alpha, 2)}. A candidate’s interval ` +\n 'excludes zero but its Holm p does not pass, drawn hollow; a verdict other than unresolved that ' +\n 'rests on one run of the profile is marked 1 run. p is the sign-flip test over clusters, which ' +\n 'stays high when few clusters disagree even if the interval excludes zero.'\n )\n}\n\nfunction scoredCell(p: ProfileMatrixProfileStats): string {\n return `${p.casesScored} / ${p.casesAttempted}<span class=\"sub\">${pct(p.failureRate)} failed</span>`\n}\n\nfunction profileCell(a: ProfileMatrixAnalysis, p: ProfileMatrixProfileStats): string {\n const levels = Object.values(p.factors).join(' · ')\n const named = Object.entries(p.factors)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')\n return (\n `${esc(p.profileId)}${p.profileId === a.baseline ? ' <span class=\"muted\">(baseline)</span>' : ''}` +\n (levels ? `<span class=\"sub\" title=\"${esc(named)}\">${esc(levels)}</span>` : '')\n )\n}\n\nfunction panelRuleText(a: ProfileMatrixAnalysis): string {\n return a.panelRule === 'race-survivors'\n ? 'the race survivors'\n : `the profiles that scored at least ${pct(a.minCoverage)} of the baseline’s ${a.profiles[0]!.casesScored} cases`\n}\n\nfunction decision(a: ProfileMatrixAnalysis, race: ProfileMatrixRaceResult | undefined): string {\n const base = a.profiles[0]!\n const partial = a.profiles.length - a.panelProfiles.length\n const lines = [\n `Every profile is paired with the baseline <strong>${esc(a.baseline)}</strong> on the cases the two ` +\n `both scored. The panel (${a.panelProfiles.length} of ${a.profiles.length} profiles: ${panelRuleText(a)}) ` +\n `shares ${common(a)} in ${a.commonClusters} independent cluster${a.commonClusters === 1 ? '' : 's'}, ` +\n `where the baseline scores ${num(base.quality?.estimate)} ${base.quality ? bounds(base.quality, num) : ''}` +\n `${partial ? `; ${partial} partial-coverage profile${partial === 1 ? '' : 's'} sit outside the frontier` : ''}.`,\n ]\n if (a.panelProfiles.length === 1 && partial > 0) {\n lines.push(\n a.panelRule === 'race-survivors'\n ? 'The race left the baseline alone, so the frontier, overlap and power have nothing to compare.'\n : `No other profile scored ${pct(a.minCoverage)} of the baseline’s cases, so the frontier, overlap ` +\n 'and power have nothing to compare; a lower <code>minCoverage</code> widens the panel.',\n )\n }\n const list = (verdict: ProfileMatrixVerdict) => {\n const named = withVerdict(a, verdict).map((p) => {\n const vs = p.vsBaseline!\n return `${esc(p.profileId)} (${signed(vs.estimate)}, n ${vs.n}, ${plural(p.runs, 'run')})`\n })\n return named.length ? named.join(', ') : 'none'\n }\n lines.push(\n `Better than the baseline at ${familyName(a)}: ${list('better')}. Worse: ${list('worse')}. ` +\n `Candidates, whose nominal ${pct(a.level)} interval excludes zero but which do not pass the ` +\n `adjustment: ${list('candidate')}. Unresolved: ${withVerdict(a, 'unresolved').length}.`,\n familySentence(a),\n )\n for (const axis of a.axes.filter((x) => x.drawn)) {\n lines.push(`Pareto set on ${AXIS_NAME[axis.axis]}: ${axis.frontier.map(esc).join(', ')}.`)\n }\n const top = Math.max(...panelOf(a).map((p) => p.quality?.estimate ?? 0))\n const leaders = panelOf(a).filter((p) => p.quality?.estimate === top)\n if (a.oracle !== null && leaders.length > 0) {\n const named =\n leaders.length === 1\n ? esc(leaders[0]!.profileId)\n : `${esc(leaders[0]!.profileId)} and ${leaders.length - 1} tied`\n lines.push(\n `On the common cases, choosing the right panel profile per case would score ${num(a.oracle)}; the best single one ` +\n `(${named}) scores ${num(top)}.`,\n )\n }\n if (typeof a.power?.detectable === 'number') {\n lines.push(\n `Differences below about ${num(a.power.detectable, 2)} are beyond what this n resolves.`,\n )\n }\n if (race) {\n lines.push(\n `Raced: ${race.cellsRun} of ${race.plannedCells} planned cells run; leader ` +\n `<strong>${esc(race.leader)}</strong>. ${esc(race.selectionBias)}`,\n )\n }\n return lines.map((line) => `<p>${line}</p>`).join('\\n')\n}\n\n/** How many comparisons the family holds and what a candidate needs to pass it. */\nfunction familySentence(a: ProfileMatrixAnalysis): string {\n const { alpha, comparisons } = a.family\n if (comparisons === 0) {\n return 'No profile has a p-value against the baseline, so none can read as better or worse.'\n }\n return (\n `The family holds ${plural(comparisons, 'comparison')}, one per profile compared with the baseline, ` +\n `so Holm passes the smallest p only at ${num(alpha / comparisons, 4)} (${pct(alpha)} ÷ ${comparisons}) ` +\n 'or below; a candidate needs more cases or repeated runs before it reads as better or worse.'\n )\n}\n\nconst AXIS_NAME: Record<ProfileMatrixCostAxis, string> = {\n usd: 'dollars',\n tokens: 'tokens',\n seconds: 'latency',\n}\n\nconst AXIS_TITLE: Record<ProfileMatrixCostAxis, string> = {\n usd: 'Dollars per case',\n tokens: 'Tokens per case',\n seconds: 'Median seconds per case',\n}\n\nfunction ticks(min: number, max: number, count = 5): number[] {\n const span = max - min\n const raw = span / count\n const power = 10 ** Math.floor(Math.log10(raw))\n const step = [1, 2, 2.5, 5, 10].map((m) => m * power).find((s) => span / s <= count)!\n const out: number[] = []\n for (let v = Math.ceil(min / step) * step; v <= max + step * 1e-9; v += step) {\n out.push(Number(v.toFixed(10)))\n }\n return out\n}\n\nfunction extent(values: readonly number[], clamp?: readonly [number, number]): [number, number] {\n let low = Math.min(...values)\n let high = Math.max(...values)\n if (low === high) {\n low -= Math.abs(low) * 0.1 || 0.5\n high += Math.abs(high) * 0.1 || 0.5\n }\n const pad = (high - low) * 0.08\n low -= pad\n high += pad\n return clamp ? [Math.max(clamp[0], low), Math.min(clamp[1], high)] : [low, high]\n}\n\nfunction tickLabel(axis: ProfileMatrixCostAxis | 'quality', value: number): string {\n const short = (v: number) => Number(v.toPrecision(3)).toString()\n if (axis === 'tokens' && Math.abs(value) >= 1000) return `${short(value / 1000)}k`\n if (axis === 'usd') return `$${short(value)}`\n return short(value)\n}\n\nfunction frontier(a: ProfileMatrixAnalysis): string {\n const drawn = a.axes.filter((axis) => axis.drawn)\n const skipped = a.axes\n .filter((axis) => !axis.drawn)\n .map(\n (axis) => `<p class=\"note\">${esc(AXIS_TITLE[axis.axis])} not drawn: ${esc(axis.note)}.</p>`,\n )\n return [\n `<p class=\"note\">Panel profiles’ quality on the ${common(a)} against each cost; whiskers are ${pct(a.level)} intervals. ` +\n 'Filled blue points form the Pareto set (no other profile is both better and cheaper), joined ' +\n 'by the dashed staircase; the orange ring marks the baseline.</p>',\n `<div class=\"charts\">${drawn.map((axis) => scatter(a, axis)).join('')}</div>`,\n ...skipped,\n ].join('\\n')\n}\n\nfunction scatter(a: ProfileMatrixAnalysis, axis: ProfileMatrixAxisSummary): string {\n const [W, H, L, R, T, B] = [560, 330, 52, 16, 14, 46]\n const xOf = (p: ProfileMatrixProfileStats) =>\n axis.axis === 'seconds' ? p.latency!.p50 : p.costPerCase[axis.axis]!\n const points = panelOf(a).map((p) => ({ p, x: xOf(p), q: p.quality! }))\n const ys = points.flatMap(({ q }) => [q.estimate, q.low ?? q.estimate, q.high ?? q.estimate])\n const [x0, x1] = extent(points.map((pt) => pt.x))\n const [y0, y1] = extent(ys, ys.every((y) => y >= 0 && y <= 1) ? [0, 1] : undefined)\n const sx = (v: number) => L + ((v - x0) / (x1 - x0)) * (W - L - R)\n const sy = (v: number) => H - B - ((v - y0) / (y1 - y0)) * (H - T - B)\n const parts: string[] = []\n for (const t of ticks(y0, y1)) {\n parts.push(`<line class=\"grid\" x1=\"${L}\" x2=\"${W - R}\" y1=\"${sy(t)}\" y2=\"${sy(t)}\"/>`)\n parts.push(\n `<text x=\"${L - 6}\" y=\"${sy(t) + 4}\" text-anchor=\"end\">${tickLabel('quality', t)}</text>`,\n )\n }\n for (const t of ticks(x0, x1)) {\n parts.push(\n `<text x=\"${sx(t)}\" y=\"${H - B + 16}\" text-anchor=\"middle\">${tickLabel(axis.axis, t)}</text>`,\n )\n }\n const front = axis.frontier.map((id) => points.find((pt) => pt.p.profileId === id)!)\n if (front.length > 1) {\n const path = front\n .map((pt, i) =>\n i === 0 ? `M${sx(pt.x)} ${sy(pt.q.estimate)}` : `H${sx(pt.x)} V${sy(pt.q.estimate)}`,\n )\n .join(' ')\n parts.push(`<path class=\"step\" d=\"${path}\"/>`)\n }\n for (const { x, q } of points) {\n if (q.low === null || q.high === null) continue\n const cx = sx(x)\n parts.push(`<line class=\"whisker\" x1=\"${cx}\" x2=\"${cx}\" y1=\"${sy(q.low)}\" y2=\"${sy(q.high)}\"/>`)\n }\n // Every point is an obstacle, so a label never covers a mark.\n const placed: LabelBox[] = points.map(({ x, q }) => {\n const [cx, cy] = [sx(x), sy(q.estimate)]\n return [cx - 6, cx + 6, cy - 6, cy + 6]\n })\n for (const { p, x, q } of points) {\n const onFront = axis.frontier.includes(p.profileId)\n const [cx, cy] = [sx(x), sy(q.estimate)]\n const tip = `${p.profileId}: quality ${num(q.estimate)} ${bounds(q, num)}, ${cost(axis.axis, x)}`\n parts.push(\n `<circle class=\"pt${onFront ? ' front' : ''}\" cx=\"${cx}\" cy=\"${cy}\" r=\"5.5\">` +\n `<title>${esc(tip)}</title></circle>`,\n )\n if (p.profileId === a.baseline) parts.push(`<circle class=\"ring\" cx=\"${cx}\" cy=\"${cy}\" r=\"9\"/>`)\n if (onFront || p.profileId === a.baseline) {\n const at = placeLabel(cx, cy, p.profileId, placed, [L, W - R, T, H - B])\n if (Math.abs(at.y - cy) > 16) {\n const edge = at.anchor === 'start' ? at.x - 2 : at.x + 2\n parts.push(`<line class=\"leader\" x1=\"${cx}\" y1=\"${cy}\" x2=\"${edge}\" y2=\"${at.y - 4}\"/>`)\n }\n parts.push(\n `<text x=\"${at.x}\" y=\"${at.y}\" text-anchor=\"${at.anchor}\">${esc(p.profileId)}</text>`,\n )\n }\n }\n parts.push(\n `<text class=\"title\" x=\"${(L + W - R) / 2}\" y=\"${H - 8}\" text-anchor=\"middle\">${AXIS_TITLE[axis.axis]}</text>`,\n )\n parts.push(\n `<text class=\"title\" transform=\"translate(14 ${(T + H - B) / 2}) rotate(-90)\" text-anchor=\"middle\">Quality</text>`,\n )\n const label = `Quality against ${AXIS_NAME[axis.axis]} for ${points.length} profiles`\n return (\n `<figure><svg viewBox=\"0 0 ${W} ${H}\" role=\"img\" aria-label=\"${esc(label)}\">${parts.join('')}</svg>` +\n `<figcaption>${esc(AXIS_TITLE[axis.axis])}: ${esc(axis.note)}.</figcaption></figure>`\n )\n}\n\ntype LabelBox = readonly [x0: number, x1: number, y0: number, y1: number]\n\n/**\n * Place a point label beside its point where it overlaps no label or point already placed and\n * stays inside the plot, trying right then left at widening vertical offsets across the plot's\n * height; a label set far from its point gets a leader line. Width is estimated from the 11px\n * label font.\n */\nfunction placeLabel(\n cx: number,\n cy: number,\n text: string,\n placed: LabelBox[],\n [left, right, top, bottom]: readonly [number, number, number, number],\n): { x: number; y: number; anchor: 'start' | 'end' } {\n const width = text.length * 6.2\n const offsets = Array.from({ length: 2 * Math.ceil((bottom - top) / 7) }, (_, k) =>\n k % 2 ? 8 + 7 * k : -(8 + 7 * k),\n )\n const candidates = offsets.flatMap((dy) =>\n (['start', 'end'] as const).map((anchor) => {\n const x = anchor === 'start' ? cx + 11 : cx - 11\n const box: LabelBox = [\n anchor === 'start' ? x : x - width,\n anchor === 'start' ? x + width : x,\n cy + dy - 10,\n cy + dy + 2,\n ]\n return { x, y: cy + dy, anchor, box }\n }),\n )\n const inside = ({ box }: (typeof candidates)[number]) =>\n box[0] >= left && box[1] <= right && box[2] >= top && box[3] <= bottom\n const free = ({ box }: (typeof candidates)[number]) =>\n placed.every((o) => box[1] <= o[0] || box[0] >= o[1] || box[3] <= o[2] || box[2] >= o[3])\n const at =\n candidates.find((c) => inside(c) && free(c)) ?? candidates.find(inside) ?? candidates[0]!\n placed.push(at.box)\n return at\n}\n\n/** An interval against zero; a candidate is drawn dashed and hollow. */\nfunction forest(\n i: ProfileMatrixInterval | null | undefined,\n span: number,\n candidate = false,\n): string {\n if (!i) return ''\n const W = 120\n const sx = (v: number) => Math.max(1, Math.min(W - 1, ((v + span) / (2 * span)) * W))\n const d = `${intervalSide(i)}${candidate ? ' cand' : ''}`\n const ci =\n i.low !== null && i.high !== null\n ? `<line class=\"ci ${d}\" x1=\"${sx(i.low)}\" x2=\"${sx(i.high)}\" y1=\"8\" y2=\"8\"/>`\n : ''\n return (\n `<svg class=\"forest\" viewBox=\"0 0 ${W} 16\" aria-hidden=\"true\">` +\n `<line class=\"zero\" x1=\"${W / 2}\" x2=\"${W / 2}\" y1=\"1\" y2=\"15\"/>${ci}` +\n `<circle class=\"${d}\" cx=\"${sx(i.estimate)}\" cy=\"8\" r=\"4\"/></svg>`\n )\n}\n\nfunction forestSpan(intervals: readonly (ProfileMatrixInterval | null | undefined)[]): number {\n const values = intervals.flatMap((i) => (i ? [i.estimate, i.low ?? 0, i.high ?? 0] : []))\n return Math.max(0.05, ...values.map(Math.abs)) * 1.05\n}\n\nfunction profileTable(a: ProfileMatrixAnalysis): string {\n const usd = a.axes.some((axis) => axis.axis === 'usd' && axis.drawn)\n const panel = panelOf(a)\n const span = forestSpan(a.profiles.map((p) => p.vsBaseline))\n const head = [\n 'Profile',\n 'Scored',\n 'Runs',\n `Quality [${pct(a.level)}]`,\n 'Paired n',\n 'Δ vs baseline',\n '',\n 'To resolve',\n 'Tokens / correct',\n ...(usd ? ['$ / correct'] : []),\n 'Seconds p50 · p90',\n ]\n const rows = panel.map((p) => {\n const cells = [\n profileCell(a, p),\n scoredCell(p),\n `${p.runs}`,\n p.quality\n ? `${num(p.quality.estimate)} <span class=\"sub\">${bounds(p.quality, num)}</span>`\n : '—',\n ...verdictCells(p),\n forest(p.vsBaseline, span, p.verdict === 'candidate'),\n resolveCell(p.vsBaseline),\n cost('tokens', p.costPerCorrect.tokens),\n ...(usd ? [cost('usd', p.costPerCorrect.usd)] : []),\n `${num(p.latency?.p50, 1)} · ${num(p.latency?.p90, 1)}`,\n ]\n return `<tr>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`\n })\n return [\n `<p class=\"note\">The panel: ${panelRuleText(a)}. Scored is each profile’s own cases with a score out of ` +\n 'those it attempted, with the share of attempts that failed beneath. Runs is how many times the profile ' +\n 'ran the cases; with several, a case scores its mean over them. ' +\n `Quality, tokens and seconds are on the ${common(a)}, so ` +\n `the panel compares like with like. Δ is paired with the baseline on every case the two both scored, ` +\n `so each row carries its own paired n and clusters. A case counts as correct at a score of ${a.passScore} or more. ` +\n 'To resolve is the number of paired cases a two-sided test needs for 80% power at the observed ' +\n 'difference and discordance (unclustered). Seconds are dispatch time where the cell recorded ' +\n `it. ${verdictNote(a)}</p>`,\n table(head, rows),\n ].join('\\n')\n}\n\nfunction resolveCell(vs: ProfileMatrixPairedDifference | undefined): string {\n return vs?.casesToResolve == null ? '—' : grouped(vs.casesToResolve)\n}\n\nfunction partialTable(a: ProfileMatrixAnalysis): string {\n const partial = a.profiles.filter((p) => !p.panel)\n const raced = partial.some((p) => p.droppedAtBatch !== undefined)\n const span = forestSpan(a.profiles.map((p) => p.vsBaseline))\n const head = [\n 'Profile',\n 'Scored',\n 'Runs',\n 'Coverage',\n `Own accuracy [${pct(a.level)}]`,\n 'Paired n',\n 'Δ vs baseline',\n '',\n 'To resolve',\n ...(raced ? ['Dropped after batch'] : []),\n ]\n const rows = partial.map((p) => {\n const cells = [\n profileCell(a, p),\n scoredCell(p),\n `${p.runs}`,\n pct(p.coverage),\n p.ownQuality\n ? `${num(p.ownQuality.estimate)} <span class=\"sub\">${bounds(p.ownQuality, num)}</span>`\n : '—',\n ...verdictCells(p),\n forest(p.vsBaseline, span, p.verdict === 'candidate'),\n resolveCell(p.vsBaseline),\n ...(raced ? [p.droppedAtBatch === undefined ? '—' : `${p.droppedAtBatch}`] : []),\n ]\n return `<tr>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`\n })\n const why =\n (a.panelRule === 'race-survivors'\n ? 'The race dropped these profiles, so they stopped running cases'\n : `These profiles scored fewer than ${pct(a.minCoverage)} of the baseline’s cases`) +\n '; in the frontier they would cut every common-set panel down to the cases they ran.'\n return [\n `<p class=\"note\">${why} Each is paired with the baseline on the cases the two both scored instead. ` +\n 'Coverage is the share of the baseline’s scored cases this profile also scored; own accuracy is on ' +\n 'its own cases, which can be easier or harder than the panel’s, so read Δ, not own accuracy, ' +\n 'against the panel. Runs and the verdict read as in the profiles table, in the same family.</p>',\n table(head, rows),\n ].join('\\n')\n}\n\nfunction shareCell(share: ProfileMatrixPairwiseShare | null): string {\n if (!share) return '—'\n const pairs =\n share.min === share.max\n ? ''\n : `<span class=\"sub\">pairs ${lowToHigh([share.min, share.max], pct1)}</span>`\n return `${pct1(share.mean)}${pairs}`\n}\n\n/** Each profile run more than once, and the reading rule its rerun noise gives at the panel's n. */\nfunction stability(a: ProfileMatrixAnalysis): string {\n if (a.stability.length === 0) {\n return (\n '<p class=\"note\">No profile was run more than once, so this page cannot measure rerun noise: ' +\n 'every difference above rests on one run of each profile and carries noise the page does not show.</p>'\n )\n }\n const answers = a.stability.some((s) => s.answerDisagreement !== null)\n const n = a.commonCases.length\n const head = [\n 'Profile',\n 'Runs',\n 'Cases',\n 'Quality per run',\n 'Spread',\n 'Correctness differs',\n ...(answers ? ['Answers differ'] : []),\n `Rerun margin at n ${n}`,\n ]\n const rows = a.stability.map((s) => {\n const cells = [\n profileCell(a, a.profiles.find((p) => p.profileId === s.profileId)!),\n `${s.runs}`,\n `${s.n}`,\n s.runQuality.map((r) => num(r.quality)).join(' · '),\n num(s.spread),\n shareCell(s.correctnessDisagreement),\n ...(answers ? [shareCell(s.answerDisagreement)] : []),\n s.rerunMargin === null ? '—' : `±${num(s.rerunMargin)}`,\n ]\n return `<tr>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`\n })\n const margins = a.stability.flatMap((s) => (s.rerunMargin === null ? [] : [s.rerunMargin]))\n const differ = a.stability.flatMap((s) =>\n s.correctnessDisagreement ? [s.correctnessDisagreement.mean] : [],\n )\n const rule =\n margins.length && differ.length\n ? `<p><strong>Reading rule:</strong> two runs of one profile disagree on correctness on ` +\n `${lowToHigh(differ, pct1)} of cases, so on the panel’s ${common(a)} two runs with nothing ` +\n `changed differ in quality by up to about ${lowToHigh(margins, (m) => num(m))} in ` +\n `${pct(a.level)} of reruns; a single-run difference from the baseline smaller than that can be ` +\n 'rerun noise alone.</p>'\n : '<p>The panel has no common case, so the page cannot turn this noise into a margin.</p>'\n return [\n '<p class=\"note\">Every profile run more than once, on the cases every one of its runs scored. ' +\n 'Quality per run is each run’s mean score there, in run order, and spread is the highest minus the ' +\n 'lowest. Correctness differs is the share of those cases one run got right and the other did not' +\n (answers ? '; answers differ, the share where the two runs gave different answers' : '') +\n '; each is the mean over pairs of runs, with the range over pairs beneath. ' +\n (answers ? '' : 'Answers are not compared: pass <code>answerOf</code> to read them. ') +\n `Rerun margin is z·√(m/n) at the panel’s ${common(a)}, where m is the mean squared per-case score ` +\n 'difference between two runs (for right/wrong scores, the correctness disagreement) and each ' +\n 'case’s change is taken as independent.</p>',\n table(head, rows),\n rule,\n ].join('\\n')\n}\n\nfunction table(head: readonly string[], rows: readonly string[]): string {\n return (\n `<div class=\"scroll\"><table><thead><tr>${head.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead>` +\n `<tbody>${rows.join('\\n')}</tbody></table></div>`\n )\n}\n\nfunction pairCases({ pairCases: range }: ProfileMatrixFactorEffect): string {\n if (!range) return '—'\n return range.min === range.max ? `${range.min}` : `${range.min}–${range.max}`\n}\n\nfunction factorTable(a: ProfileMatrixAnalysis): string {\n if (a.factorEffects.length === 0) return '<p class=\"note\">No factor levels were given.</p>'\n const span = forestSpan(a.factorEffects.map((e) => e.effect))\n const rows = a.factorEffects.map((e) =>\n [\n `<tr><td>${esc(e.factor)}</td>`,\n `<td>${esc(e.level)} <span class=\"muted\">vs ${esc(e.reference)}</span></td>`,\n `<td>${e.matchedPairs}</td>`,\n `<td>${pairCases(e)}</td>`,\n e.effect\n ? `<td>${signed(e.effect.estimate)} ${DIRECTION_WORD[intervalSide(e.effect)]}` +\n `<span class=\"sub\">${bounds(e.effect)}, p ${num(e.pValue)}, n ${e.n}</span></td>`\n : `<td class=\"muted\">${e.matchedPairs ? 'no case scored by both sides of a pair' : 'confounded: no profile pair differs only here'}</td>`,\n `<td>${forest(e.effect, span)}</td></tr>`,\n ].join(''),\n )\n return [\n '<p class=\"note\">The effect of moving one factor from the reference level, all else equal. Each ' +\n 'matched pair (two profiles that differ only in that factor) is compared on the cases it shares; ' +\n 'the effect is the mean, over the cases any pair shares, of the pairs’ difference on that case, ' +\n `with a clustered ${pct(a.level)} interval. Pair cases is the fewest and most cases one pair shares. ${P_NOTE}</p>`,\n table(['Factor', 'Level', 'Matched pairs', 'Pair cases', 'Effect', ''], rows),\n ].join('\\n')\n}\n\nfunction shade(value: number | null, variable: '--seq' | '--seq-2'): string {\n if (value === null) return ''\n const share = Math.round(Math.max(0, Math.min(1, value)) * 85)\n const ink = share > 50 ? 'color:var(--on-seq);' : ''\n return ` style=\"${ink}background:color-mix(in oklab,var(${variable}) ${share}%,var(--panel))\"`\n}\n\nfunction sliceHeatmap(a: ProfileMatrixAnalysis): string {\n if (a.slices.length === 0) return '<p class=\"note\">No slices were given.</p>'\n const rows = panelOf(a).map((p) => {\n const cells = a.slices.map((slice) => {\n const cell = a.sliceCells.find((c) => c.profileId === p.profileId && c.slice === slice)!\n const tip = `${p.profileId} on ${slice}: ${num(cell.quality)} over ${cell.n} cases`\n if (cell.n === 0) return `<td class=\"cell thin\" title=\"${esc(tip)}\"></td>`\n if (cell.n < 5) {\n return `<td class=\"cell thin\" title=\"${esc(tip)}\">${num(cell.quality, 2)}<span class=\"sub\">n ${cell.n}</span></td>`\n }\n return `<td class=\"cell\"${shade(cell.quality, '--seq')} title=\"${esc(tip)}\">${num(cell.quality, 2)}<span class=\"sub\">n ${cell.n}</span></td>`\n })\n return `<tr><td>${esc(p.profileId)}</td>${cells.join('')}</tr>`\n })\n return [\n `<p class=\"note\">Each panel profile’s mean score on the ${common(a)} in each slice, the largest slice ` +\n 'first. Cells with fewer than five cases are greyed: too few to read.</p>',\n table(['Profile', ...a.slices], rows),\n ].join('\\n')\n}\n\nfunction overlap(a: ProfileMatrixAnalysis): string {\n if (a.commonCases.length === 0)\n return '<p class=\"note\">No case was scored by every panel profile.</p>'\n const ids = a.panelProfiles\n const pair = (x: string, y: string) =>\n a.errorOverlap.find((o) => (o.a === x && o.b === y) || (o.a === y && o.b === x))!\n const rows = ids.map((row, i) => {\n const cells = ids.map((col, j) => {\n if (i === j) {\n const wrong = 1 - (a.profiles.find((p) => p.profileId === row)!.quality?.estimate ?? 0)\n return `<td class=\"cell tight diag\" title=\"${esc(row)} error rate\">${pct(wrong)}</td>`\n }\n const o = pair(row, col)\n const [value, variable, what] =\n j > i\n ? [o.bothWrong, '--seq-2' as const, 'both wrong']\n : [o.disagree, '--seq' as const, 'disagree']\n return `<td class=\"cell tight\"${shade(value, variable)} title=\"${esc(`${row} and ${col}: ${what} ${pct(value)}`)}\">${pct(value)}</td>`\n })\n return `<tr><td>${i + 1}. ${esc(row)}</td>${cells.join('')}</tr>`\n })\n const best = Math.max(...panelOf(a).map((p) => p.quality?.estimate ?? 0))\n return [\n `<p class=\"note\">Panel profiles on the ${common(a)}, numbered as in the rows. Above the diagonal (orange): share both profiles got wrong. ` +\n 'Below it (blue): share exactly one got right. The diagonal is each profile’s error rate. Profiles ' +\n 'that disagree often and rarely fail together are candidates to route between.</p>',\n table(['', ...ids.map((_, i) => `${i + 1}`)], rows),\n `<p>Oracle ceiling: ${num(a.oracle)} (a case counts when any panel profile got it right), against ${num(best)} for the best single one.</p>`,\n ].join('\\n')\n}\n\nfunction difficulty(a: ProfileMatrixAnalysis): string {\n const items = a.difficulty\n if (items.length === 0) return '<p class=\"note\">No case was scored.</p>'\n const [H, L, T, B] = [160, 36, 8, 22]\n const barW = Math.max(2, Math.min(14, Math.floor(860 / items.length)))\n const W = L + items.length * barW + 8\n const sy = (v: number) => H - B - v * (H - T - B)\n const parts = [0, 0.5, 1].map(\n (t) =>\n `<line class=\"grid\" x1=\"${L}\" x2=\"${W - 8}\" y1=\"${sy(t)}\" y2=\"${sy(t)}\"/>` +\n `<text x=\"${L - 6}\" y=\"${sy(t) + 4}\" text-anchor=\"end\">${t}</text>`,\n )\n items.forEach((item, i) => {\n const tip = `${item.caseId}${item.slice ? ` (${item.slice})` : ''}: ${item.solved} of ${item.scored} profiles right`\n const h = Math.max(1, item.share * (H - T - B))\n const y = sy(item.share) - (item.share === 0 ? 1 : 0)\n parts.push(\n `<rect class=\"bar\" x=\"${L + i * barW + 1}\" y=\"${y}\" width=\"${barW - 2}\" height=\"${h}\" rx=\"1\">` +\n `<title>${esc(tip)}</title></rect>`,\n )\n })\n parts.push(\n `<text x=\"${L}\" y=\"${H - 6}\">hardest</text><text x=\"${W - 8}\" y=\"${H - 6}\" text-anchor=\"end\">easiest</text>`,\n )\n const none = items.filter((item) => item.solved === 0)\n const all = items.filter((item) => item.solved === item.scored)\n const listed = none.slice(0, 24).map((item) => esc(item.caseId))\n const more = none.length > listed.length ? ` and ${none.length - listed.length} more` : ''\n return [\n `<p class=\"note\">Each bar is one of the ${common(a)}: the share of the ${a.panelProfiles.length} panel ` +\n 'profiles that got it right, hardest first.</p>',\n `<figure><svg viewBox=\"0 0 ${W} ${H}\" role=\"img\" aria-label=\"Share of panel profiles right per case\">${parts.join('')}</svg></figure>`,\n `<p>Of the ${common(a)}, ${none.length} were missed by every panel profile` +\n `${none.length ? ` (${listed.join(', ')}${more})` : ''} and ${all.length} were solved by every one. ` +\n 'Cases nobody solves are worth reading for label errors before they are read as hard.</p>',\n ].join('\\n')\n}\n\nfunction calibration(a: ProfileMatrixAnalysis): string {\n if (a.calibration.length === 0) {\n return '<p class=\"note\">No profile returned a probability (pass <code>probabilityOf</code> to read one).</p>'\n }\n const S = 200\n const pad = 26\n const sc = (v: number) => pad + v * (S - 2 * pad)\n const plots = a.calibration.map((c) => {\n const maxN = Math.max(...c.bins.map((b) => b.n))\n const pts = c.bins.map((b) => ({ x: sc(b.evalMean), y: S - sc(b.outcomeMean), b }))\n const line = pts.map((p, i) => `${i ? 'L' : 'M'}${p.x} ${p.y}`).join(' ')\n const dots = pts\n .map(\n (p) =>\n `<circle class=\"calpt\" cx=\"${p.x}\" cy=\"${p.y}\" r=\"${3 + 4 * Math.sqrt(p.b.n / maxN)}\">` +\n `<title>${esc(`forecast ${num(p.b.evalMean, 2)}, right ${num(p.b.outcomeMean, 2)}, n ${p.b.n}`)}</title></circle>`,\n )\n .join('')\n return (\n `<figure><svg viewBox=\"0 0 ${S} ${S}\" role=\"img\" aria-label=\"${esc(`Calibration of ${c.profileId}`)}\">` +\n `<line class=\"grid\" x1=\"${pad}\" x2=\"${S - pad}\" y1=\"${S - pad}\" y2=\"${S - pad}\"/>` +\n `<line class=\"diagonal\" x1=\"${sc(0)}\" y1=\"${S - sc(0)}\" x2=\"${sc(1)}\" y2=\"${S - sc(1)}\"/>` +\n `<path class=\"cal\" d=\"${line}\"/>${dots}` +\n `<text x=\"${pad}\" y=\"${S - 8}\">forecast</text><text x=\"4\" y=\"${pad - 8}\">right</text></svg>` +\n `<figcaption>${esc(c.profileId)}: n ${c.n}, ECE ${num(c.ece)}, Brier ${num(c.brier)}</figcaption></figure>`\n )\n })\n return [\n '<p class=\"note\">Forecast probability of being right against the share actually right, in ten bins; ' +\n 'the dashed diagonal is perfect calibration and dot area follows the bin count.</p>',\n `<div class=\"small-multiples\">${plots.join('')}</div>`,\n ].join('\\n')\n}\n\nfunction powerSentence(a: ProfileMatrixAnalysis): string {\n const p = a.power\n if (!p)\n return 'Power is not computed: it needs at least two common cases and one panel profile besides the baseline.'\n const base =\n `With ${p.n} common cases in ${p.clusters} independent cluster${p.clusters === 1 ? '' : 's'} and a ` +\n `median discordance of ${pct(p.discordance)} against the baseline, `\n const finding =\n p.detectable === null\n ? 'no paired difference up to 1.0 reaches 80% power at this n.'\n : `the smallest paired difference this design detects with 80% power is about ${num(p.detectable, 2)} ` +\n `(whole-cluster bootstrap, ${pct(a.level)} interval); a smaller difference in the table is not resolvable here.`\n const floor = p.certifiable\n ? ''\n : ` With ${p.clusters} clusters an exact sign-flip test cannot reach the ${pct(1 - a.level)} level at any effect; it needs at least ${p.minClusters}.`\n return base + finding + floor\n}\n\nfunction raceSection(race: ProfileMatrixRaceResult): string {\n const reason = {\n 'one-left': 'one profile was left',\n 'cell-budget': 'the next batch would have passed the cell budget',\n 'batches-ended': 'the batch list ended',\n }[race.stoppedBecause]\n const saved = race.plannedCells ? 1 - race.cellsRun / race.plannedCells : 0\n const log = race.log.flatMap((batch) =>\n batch.standings.map(\n (s) =>\n `<tr><td>${batch.batch}</td><td>${batch.casesSeen}</td><td>${esc(batch.leader)}</td>` +\n `<td>${esc(s.profileId)}</td><td>${s.n}</td><td>${signed(s.difference)}</td>` +\n `<td>${bounds(s)}<span class=\"sub\">p ${num(s.pValue)}, ${s.clusters} clusters</span></td><td>${s.dropped ? '<strong>dropped</strong>' : 'kept'}` +\n `${s.reason ? `<span class=\"sub\">${esc(s.reason)}</span>` : ''}</td></tr>`,\n ),\n )\n const final = race.final.rows.map(\n (row) =>\n `<tr><td>${esc(row.profileId)}${row.profileId === race.leader ? ' <span class=\"muted\">(leader)</span>' : ''}</td>` +\n `<td>${num(row.quality)}</td>${pairedCells(row.vsBaseline)\n .map((cell) => `<td>${cell}</td>`)\n .join('')}</tr>`,\n )\n return [\n `<p>Stopped because ${reason}, after ${race.casesRaced.length} cases: ${race.cellsRun} of ` +\n `${race.plannedCells} planned cells run (${pct(saved)} not spent). Survivors: ${race.survivors.map(esc).join(', ')}.</p>`,\n '<h3>Elimination log</h3>',\n table(\n [\n 'Batch',\n 'Cases seen',\n 'Leader',\n 'Profile',\n 'Paired n',\n 'Δ vs leader',\n 'Interval',\n 'Decision',\n ],\n log,\n ),\n `<h3>Final comparison on ${race.final.cases} cases every survivor scored</h3>`,\n table(['Profile', 'Quality', 'Paired n', 'Δ vs baseline, nominal'], final),\n `<p class=\"callout\">${esc(race.selectionBias)}</p>`,\n ].join('\\n')\n}\n","/**\n * `runProfileMatrix` — the missing keystone between `runAgentMatrix` and the\n * backend-integrity guard.\n *\n * The gap it closes: `runAgentMatrix` is a topology-opaque scheduler whose\n * cells return a bare `{ output, verdict, costUsd }` — no `tokenUsage`, not a\n * `RunRecord`. `assertRealBackend` / `summarizeBackendIntegrity` key on\n * `RunRecord.tokenUsage`, so they cannot run on a raw matrix result. Every\n * consumer therefore hand-writes the same bridge: fan a profile × scenario\n * cartesian, call dispatch, fabricate a `RunRecord` with token usage, thread it\n * back, run the integrity guard. That hand-rolled bridge is exactly the pile of\n * bespoke `eval:*` scripts the adoption skills keep trying (and failing) to\n * forbid.\n *\n * `runProfileMatrix` IS that bridge, once:\n *\n * - axis 3 (PROFILE) = `profiles: AgentProfile[]`\n * - axis 1 (PERSONA/SCENARIO) = `scenarios: Scenario[]` (each scenario carries\n * its persona; `personaOf` groups them for the `byPersona` pivot)\n * - the scoring axis = `judges`\n *\n * It runs `runCampaign` once per profile (reusing its seeds, reps, bootstrap\n * CIs, resumability, and the `LabeledScenarioStore` capture flywheel), maps\n * every cell to a validated `RunRecord` carrying the real `tokenUsage` the\n * dispatch committed via `ctx.cost.runPaidCall`, and runs `assertRealBackend`\n * BY CONSTRUCTION before returning — so a stub-backend run fails loudly instead\n * of reporting a clean 0/N leaderboard.\n *\n * Dispatch contract: a dispatch that calls an LLM MUST report usage via\n * `ctx.cost.runPaidCall({ execute, receipt })`.\n * The integrity guard judges each `RunRecord` by tokens alone, whatever cost\n * it states, because a run record carries no declaration that its call was\n * free; a matrix of free calls sets `integrity: 'off'`.\n */\n\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileHash,\n agentProfileId,\n agentProfileModelId,\n HARNESS_NATIVE_MODEL,\n harnessAxisOf,\n} from '../../agent-profile'\nimport { type AgentProfileCell, buildAgentProfileCell } from '../../agent-profile-cell'\nimport { mapConcurrent } from '../../concurrency'\nimport type { CostProvenance } from '../../cost-ledger'\nimport { AgentEvalError } from '../../errors'\nimport {\n assertRealBackend,\n type BackendIntegrityReport,\n summarizeBackendIntegrity,\n} from '../../integrity/backend-integrity'\nimport {\n modelHasSnapshot,\n modelSnapshot,\n type RunRecord,\n type RunSplitTag,\n runTaskScore,\n UNKNOWN_MODEL,\n validateRunRecord,\n} from '../../run-record'\nimport { mean, meanOrNull } from '../../statistics/mean'\nimport { computeManifestHash } from '../campaign-manifest'\nimport { cellReceiptModels } from '../cell-cache'\nimport { runCampaign } from '../run-campaign'\nimport { campaignCellToRunRecord } from '../run-record'\nimport type { CampaignStorage } from '../storage'\nimport type {\n CampaignCellResult,\n CampaignResult,\n DispatchContext,\n JudgeConfig,\n LabeledScenarioSource,\n LabeledScenarioStore,\n Scenario,\n} from '../types'\n\n/** Thrown when the matrix is misconfigured (no profiles, missing resolved model evidence,\n * etc.). Distinct from `BackendIntegrityError`,\n * which signals a stub backend at run time. */\nexport class ProfileMatrixError extends AgentEvalError {\n constructor(message: string) {\n super('profile_matrix', message)\n }\n}\n\n/** Dispatch for one cell: render `profile` against `scenario`, returning the\n * artifact the judges score. Run LLM work through `ctx.cost.runPaidCall` —\n * the integrity check depends on its receipt. */\nexport type ProfileDispatchFn<TScenario extends Scenario, TArtifact> = (\n profile: AgentProfile,\n scenario: TScenario,\n ctx: DispatchContext,\n) => Promise<TArtifact>\n\nexport interface RunProfileMatrixOptions<TScenario extends Scenario, TArtifact> {\n /** Axis 3 — the agent-under-test configurations. Each is one column. */\n profiles: AgentProfile[]\n /** Axis 1 — the persona/scenario corpus, run against every profile. */\n scenarios: TScenario[]\n /** Renders one (profile, scenario) cell. */\n dispatch: ProfileDispatchFn<TScenario, TArtifact>\n /** The scoring axis. */\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Where each profile's campaign writes artifacts/traces. One subdir per\n * profile. */\n runDir: string\n /** Git SHA the harness ran from — stamped onto every RunRecord (mandatory\n * for paper-grade records). */\n commitSha: string\n /** Additional stable identity for dispatch behavior that can change without\n * changing `commitSha`, such as a caller-owned executable or remote config. */\n dispatchRef?: string\n /** Logical experiment id shared across the whole matrix so the promotion\n * gate can pair profiles on matched scenarios. Default: a hash of the\n * profile + scenario ids. */\n experimentId?: string\n /** Which split these runs belong to. Default `'search'`. */\n splitTag?: RunSplitTag\n /** Replicates per (profile, scenario) cell for CI bands. Default 1. */\n reps?: number\n /** Campaign seed (per profile). Default 42. */\n seed?: number\n /**\n * Backend-integrity posture, enforced AFTER the matrix completes:\n * - `'assert'` (default) — throw `BackendIntegrityError` if the run was a\n * stub (and, with `allowMixed:false`, if it was mixed).\n * - `'warn'` — log the verdict but never throw.\n * - `'off'` — skip the guard entirely (only for offline/replay analysis).\n */\n integrity?: 'assert' | 'warn' | 'off'\n /** Forwarded to `assertRealBackend`. Default true (tolerate partial 429\n * cascades); set false for strict CI gates. */\n allowMixed?: boolean\n /** Max concurrent cells WITHIN each profile's campaign. Default 2. */\n maxConcurrency?: number\n /** Max profile campaigns in flight. Default 1. Each profile keeps its own\n * run directory and cost ceiling; raise this when those resources are independent. */\n maxProfileConcurrency?: number\n /** Cumulative USD cap per profile campaign. */\n costCeiling?: number\n /** Capture flywheel — forwarded to each campaign. */\n labeledStore?: LabeledScenarioStore | 'off'\n captureSource?: LabeledScenarioSource\n /** Storage backend. Default `fsCampaignStorage`. Pass\n * `inMemoryCampaignStorage()` for edge/CF-Worker/test runs. */\n storage?: CampaignStorage\n /** Test seam — override the wall clock. */\n now?: () => Date\n /** Optional persona key per scenario — drives the `byPersona` pivot. When\n * unset, `byPersona` is omitted. */\n personaOf?: (scenario: TScenario) => string\n /** Validate every produced RunRecord with `validateRunRecord` (fail-loud).\n * Default true — catches bad model snapshots and non-finite judge dims at\n * the boundary instead of letting them poison downstream analysis. */\n validate?: boolean\n /** Corpus-by-default: derive the trajectory text (`prompt` + `completion`)\n * for each cell from its artifact + scenario. When set, every produced\n * record carries `prompt`/`completion` (a `CorpusRecord`) so the run's\n * graded trajectories can be appended to the durable RL corpus with no\n * side-channel — `appendToCorpus(result.records, path)`. Fail-soft: a\n * throwing or undefined-returning extractor just omits the text. */\n corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n /**\n * Optional explicit row selection. The matrix identity remains based on the\n * complete profiles × scenarios × reps design; this invocation executes only\n * rows accepted by the predicate.\n */\n rowFilter?: (input: { profile: AgentProfile; scenario: TScenario; rep: number }) => boolean\n /** Stable matrix identity supplied by a persisted profile-matrix plan. */\n matrixId?: string\n /** Reuse cached failed cells. Normal matrix runs retry them by default. */\n reuseFailedCells?: boolean\n}\n\nexport interface ProfileSummary {\n profileId: string\n profileHash: string\n model: string\n /** RunRecords produced for this profile (= scenarios × reps). */\n records: number\n /** Mean across scored records, or null when the profile has no task labels. */\n meanComposite: number | null\n /** Total cost, or null when any call's cost was not captured. */\n totalCostUsd: number | null\n costProvenance: CostProvenance\n /** Per-profile integrity verdict — surfaces a single profile that ran stub\n * even when the matrix as a whole looks real. */\n integrity: BackendIntegrityReport\n}\n\nexport interface ScenarioRollup {\n meanComposite: number\n n: number\n}\n\nexport interface RunProfileMatrixResult<TArtifact, TScenario extends Scenario> {\n matrixId: string\n experimentId: string\n /** One RunRecord per (profile, scenario, rep) cell — the integrity-checked,\n * paper-grade output. Feed straight into `analyzeRuns`, `HeldOutGate`,\n * scorecards, the hosted wire format. */\n records: RunRecord[]\n byProfile: Record<string, ProfileSummary>\n byScenario: Record<string, ScenarioRollup>\n /** Present only when `personaOf` was supplied. */\n byPersona?: Record<string, ScenarioRollup>\n /** Whole-matrix integrity report (the one `integrity:'assert'` enforces). */\n integrity: BackendIntegrityReport\n /** The raw per-profile campaign results, keyed by profile id. */\n campaigns: Record<string, CampaignResult<TArtifact, TScenario>>\n}\n\n/**\n * Return the exact per-profile campaign identity used by `runProfileMatrix`.\n * Segmented profile matrices use this to validate durable cell caches before\n * finalization without dispatching a probe request.\n */\nexport function profileMatrixCampaignIdentity<TScenario extends Scenario, TArtifact>(opts: {\n profile: AgentProfile\n scenarios: TScenario[]\n judges?: JudgeConfig<TArtifact, TScenario>[]\n commitSha: string\n dispatchRef?: string\n splitTag?: RunSplitTag\n seed?: number\n reps?: number\n}): {\n profileHash: string\n profileId: string\n configHash: string\n dispatchRef: string\n manifestHash: string\n} {\n const seed = opts.seed ?? 42\n const splitTag = opts.splitTag ?? 'search'\n const reps = opts.reps ?? 1\n const profileHash = agentProfileHash(opts.profile)\n const profileId = agentProfileId(opts.profile)\n const configHash = sha({\n profile: profileHash,\n judges: (opts.judges ?? []).map((judge) => judge.name),\n seed,\n splitTag,\n dispatchRef: opts.dispatchRef ?? null,\n })\n const dispatchRef = `profile-matrix:${sha({\n commitSha: opts.commitSha,\n caller: opts.dispatchRef ?? null,\n profileId,\n profileHash,\n configHash,\n })}`\n const manifestHash = computeManifestHash({\n scenarios: opts.scenarios,\n judges: (opts.judges ?? []) as unknown as JudgeConfig<unknown>[],\n dispatchRef,\n seed,\n reps,\n })\n return { profileHash, profileId, configHash, dispatchRef, manifestHash }\n}\n\nfunction sanitize(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction sha(input: unknown): string {\n return createHash('sha256').update(JSON.stringify(input)).digest('hex')\n}\n\ninterface BuildRecordArgs<TScenario extends Scenario, TArtifact> {\n cell: CampaignCellResult<TArtifact>\n profile: AgentProfile\n profileHash: string\n configHash: string\n experimentId: string\n splitTag: RunSplitTag\n commitSha: string\n matrixId: string\n /** The (profile, harness, model, dimensions) identity of this cell — attached to\n * every record so results group by the canonical `groupRunsByAgentProfileCell`\n * (harness/model aware) instead of profileId alone. */\n agentProfileCell?: AgentProfileCell\n scenario?: TScenario\n corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n}\n\nfunction isUnknownModelOnly(reported: string[]): boolean {\n return reported.length > 0 && reported.every((model) => model === UNKNOWN_MODEL)\n}\n\n/** Resolve and validate every paid-call model used by one cell. */\nfunction recordModel(\n cell: CampaignCellResult<unknown>,\n profileId: string,\n declaredModel: string,\n): string {\n const reported = cellReceiptModels(cell)\n // A dispatch failure can happen before the provider returns any model\n // identity. Preserve that failed row with an explicit absence marker; a\n // failure must not be converted into a made-up snapshot or discarded.\n // When a settled receipt exists, retain and validate its real identity.\n if (cell.error !== undefined && (reported.length === 0 || isUnknownModelOnly(reported))) {\n return UNKNOWN_MODEL\n }\n if (modelHasSnapshot(declaredModel)) {\n for (const model of reported) {\n if (model !== declaredModel) {\n throw new ProfileMatrixError(\n `profile '${profileId}' paid-call model '${model}' for cell '${cell.cellId}' does not match its declared exact model '${declaredModel}'`,\n )\n }\n }\n return declaredModel\n }\n\n if (reported.length === 0) {\n throw new ProfileMatrixError(\n `profile '${profileId}' declared a moving model but its dispatch reported no resolved model for cell '${cell.cellId}' — return a snapshot-bearing model in the ctx.cost.runPaidCall receipt`,\n )\n }\n for (const model of reported) {\n if (!modelHasSnapshot(model)) {\n throw new ProfileMatrixError(\n `profile '${profileId}' resolved to model '${model}' for cell '${cell.cellId}', which lacks a snapshot version — pin it in the paid-call receipt`,\n )\n }\n if (declaredModel !== HARNESS_NATIVE_MODEL && !sameMovingModel(declaredModel, model)) {\n throw new ProfileMatrixError(\n `profile '${profileId}' declared model '${declaredModel}' but cell '${cell.cellId}' reported unrelated snapshot '${model}'`,\n )\n }\n }\n if (reported.length !== 1) {\n throw new ProfileMatrixError(\n `profile '${profileId}' cell '${cell.cellId}' reported multiple paid-call model snapshots: ${reported.join(', ')}`,\n )\n }\n return reported[0]!\n}\n\nfunction sameMovingModel(declared: string, resolved: string): boolean {\n const resolvedBase = modelSnapshot(resolved)?.name ?? resolved\n return (\n resolvedBase === declared ||\n resolvedBase.endsWith(`/${declared}`) ||\n declared.endsWith(`/${resolvedBase}`)\n )\n}\n\nfunction buildRunRecord<TScenario extends Scenario, TArtifact>(\n args: BuildRecordArgs<TScenario, TArtifact>,\n): RunRecord {\n const { cell, profile, profileHash, configHash, experimentId, splitTag, commitSha, matrixId } =\n args\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n // Every successful record pins a snapshot. When a profile intentionally\n // carries the provider-facing moving alias, the paid-call receipt supplies\n // the immutable identity used here. Failed rows use explicit unknown data.\n const model = recordModel(cell, profileId, declaredModel)\n const record = campaignCellToRunRecord(cell, {\n runId: `${matrixId}:${profileId}:${cell.cellId}`,\n experimentId,\n candidateId: profileId,\n model,\n promptHash: profileHash,\n configHash,\n commitSha,\n splitTag,\n agentProfile: args.agentProfileCell,\n }) as RunRecord & { prompt?: string; completion?: string }\n\n // Corpus-by-default: stamp the trajectory text onto the record (CorpusRecord\n // shape — the validator ignores the extra keys) so the run is dataset-able\n // with no side-channel. Fail-soft: a bad extractor never fails the run.\n if (args.corpusText && args.scenario) {\n try {\n const text = args.corpusText(cell.artifact, args.scenario)\n if (text && typeof text.prompt === 'string' && typeof text.completion === 'string') {\n record.prompt = text.prompt\n record.completion = text.completion\n }\n } catch {\n // extractor threw — omit trajectory text, keep the graded record.\n }\n }\n return record\n}\n\n/**\n * Profile × scenario matrix runner: fan N agent profiles across M scenarios, project each cell to a validated `RunRecord` with real token usage, and enforce the backend-integrity guard before returning.\n */\nexport async function runProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: RunProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<RunProfileMatrixResult<TArtifact, TScenario>> {\n if (opts.profiles.length === 0) throw new ProfileMatrixError('profiles must not be empty')\n if (opts.scenarios.length === 0) throw new ProfileMatrixError('scenarios must not be empty')\n\n const splitTag = opts.splitTag ?? 'search'\n const seed = opts.seed ?? 42\n const validate = opts.validate ?? true\n const integrityMode = opts.integrity ?? 'assert'\n const maxProfileConcurrency = opts.maxProfileConcurrency ?? 1\n const profileIds = opts.profiles.map(agentProfileId)\n if (opts.dispatchRef !== undefined && opts.dispatchRef.trim().length === 0) {\n throw new ProfileMatrixError('dispatchRef must be a non-empty string when provided')\n }\n const duplicateProfileIds = profileIds.filter((id, index) => profileIds.indexOf(id) !== index)\n if (duplicateProfileIds.length > 0) {\n throw new ProfileMatrixError(\n `duplicate agentProfileId values are not allowed: ${[...new Set(duplicateProfileIds)].join(', ')}`,\n )\n }\n const experimentId =\n opts.experimentId ??\n `pm_${sha({ profileIds, scenarios: opts.scenarios.map((s) => s.id) }).slice(0, 16)}`\n const derivedMatrixId = `mtx_${sha({\n experimentId,\n profileIds,\n seed,\n splitTag,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef ?? null,\n }).slice(0, 16)}`\n const matrixId = opts.matrixId ?? derivedMatrixId\n if (typeof matrixId !== 'string' || matrixId.trim().length === 0) {\n throw new ProfileMatrixError('matrixId must be a non-empty string when provided')\n }\n // Scenario lookup for the corpus-text extractor (records carry trajectory text).\n const scenarioById = new Map(opts.scenarios.map((s) => [s.id, s]))\n\n // Preflight: every profile must hash and every static record field must validate before spend.\n //\n // A moving provider alias or `HARNESS_NATIVE_MODEL` cannot be a durable record identity.\n // Probe it with a placeholder here so the remaining profile checks still run before spend;\n // every completed cell must later supply its actual snapshot in the paid-call receipt.\n for (const profile of opts.profiles) {\n const profileHash = agentProfileHash(profile)\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n const model = modelHasSnapshot(declaredModel)\n ? declaredModel\n : `${declaredModel}@runtime-resolved`\n try {\n validateRunRecord({\n runId: `${matrixId}:${profileId}:probe`,\n experimentId,\n candidateId: profileId,\n seed,\n model,\n promptHash: profileHash,\n configHash: profileHash,\n commitSha: opts.commitSha,\n wallMs: 0,\n costUsd: null,\n costProvenance: { kind: 'uncaptured', usd: null },\n tokenUsage: { input: 0, output: 0 },\n terminalOutcome: 'succeeded',\n outcome: { raw: { execution_error_count: 0 } },\n splitTag,\n scenarioId: 'recordability-probe',\n })\n } catch (err) {\n throw new ProfileMatrixError(\n `profile '${profileId}' is not recordable: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n\n const records: RunRecord[] = []\n const campaigns: Record<string, CampaignResult<TArtifact, TScenario>> = {}\n const byProfile: Record<string, ProfileSummary> = {}\n\n const columns = await mapConcurrent(\n opts.profiles,\n maxProfileConcurrency,\n async (profile, _index, signal) => {\n const identity = profileMatrixCampaignIdentity({\n profile,\n scenarios: opts.scenarios,\n judges: opts.judges,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef,\n splitTag,\n seed,\n reps: opts.reps,\n })\n const { profileHash, profileId, configHash, dispatchRef } = identity\n const declaredModel = agentProfileModelId(profile)\n\n // Bind the profile into a campaign dispatch. Name it so the campaign's\n // manifest hash is stable + distinct per profile.\n const dispatch = (scenario: TScenario, ctx: DispatchContext): Promise<TArtifact> =>\n opts.dispatch(profile, scenario, ctx)\n Object.defineProperty(dispatch, 'name', { value: `profile_${sanitize(profileId)}` })\n\n const campaign = await runCampaign<TScenario, TArtifact>({\n scenarios: opts.scenarios,\n dispatch,\n dispatchRef,\n signal,\n judges: opts.judges,\n seed,\n reps: opts.reps,\n maxConcurrency: opts.maxConcurrency,\n costCeiling: opts.costCeiling,\n cellFilter: opts.rowFilter\n ? ({ scenario, rep }) => opts.rowFilter?.({ profile, scenario, rep }) ?? false\n : undefined,\n reuseFailedCells: opts.reuseFailedCells,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n storage: opts.storage,\n now: opts.now,\n runDir: join(opts.runDir, sanitize(profileId)),\n })\n\n // The canonical (profile, harness, model) identity for every record in this\n // column, so results group by `groupRunsByAgentProfileCell` (harness/model\n // aware). Harness comes from the axis stamp `expandProfileAxes` left on the\n // profile; a profile that wasn't axis-expanded simply has no harness in its\n // cell (unchanged grouping). A moving model alias means the cell identity\n // must carry the resolved snapshot per cell (surfaced via\n // `cell.resolvedModels`), so the pivot groups by the model that actually ran and\n // the cell identity matches the RunRecord's pinned model.\n const axis = harnessAxisOf(profile)\n const buildCellIdentity = (cellModel?: string): Promise<AgentProfileCell> =>\n buildAgentProfileCell({\n profileId,\n sourceProfile: { kind: 'agent-interface-profile', hash: profileHash },\n ...(cellModel && cellModel !== UNKNOWN_MODEL ? { model: cellModel } : {}),\n ...(axis ? { harness: { id: axis.harness } } : {}),\n })\n // A profile with a pinned declared model builds its cell identity once and\n // shares it; a moving alias builds one per cell after resolution.\n const sharedCellIdentity = modelHasSnapshot(declaredModel)\n ? await buildCellIdentity(declaredModel)\n : undefined\n\n const profileRecords: RunRecord[] = []\n for (const cell of campaign.cells) {\n const cellModel = recordModel(cell, profileId, declaredModel)\n const agentProfileCell =\n cellModel === UNKNOWN_MODEL\n ? await buildCellIdentity()\n : (sharedCellIdentity ?? (await buildCellIdentity(cellModel)))\n const record = buildRunRecord({\n cell,\n profile,\n profileHash,\n configHash,\n experimentId,\n splitTag,\n commitSha: opts.commitSha,\n matrixId,\n agentProfileCell,\n scenario: scenarioById.get(cell.scenarioId),\n corpusText: opts.corpusText,\n })\n if (validate) validateRunRecord(record)\n profileRecords.push(record)\n }\n\n const recordedModels = [\n ...new Set(\n profileRecords\n .map((record) => record.model)\n .filter((model): model is string => model !== UNKNOWN_MODEL),\n ),\n ]\n if (recordedModels.length > 1) {\n throw new ProfileMatrixError(\n `profile '${profileId}' resolved to multiple model snapshots: ${recordedModels.join(', ')}`,\n )\n }\n\n const costProvenance = campaign.aggregates.cost.costProvenance\n const totalCostUsd = costProvenance.kind === 'uncaptured' ? null : costProvenance.usd\n return {\n profileId,\n campaign,\n records: profileRecords,\n summary: {\n profileId,\n profileHash,\n model: recordedModels[0] ?? UNKNOWN_MODEL,\n records: profileRecords.length,\n meanComposite: meanOrNull(\n profileRecords.map(scoreOf).filter((score): score is number => score !== undefined),\n ),\n totalCostUsd,\n costProvenance,\n integrity: summarizeBackendIntegrity(profileRecords),\n },\n }\n },\n )\n\n // Merge in caller order so concurrency cannot change output or report ordering.\n for (const column of columns) {\n campaigns[column.profileId] = column.campaign\n byProfile[column.profileId] = column.summary\n records.push(...column.records)\n }\n\n // Integrity by construction — the whole point of the primitive.\n const integrity = summarizeBackendIntegrity(records)\n if (integrityMode === 'assert') {\n assertRealBackend(records, { allowMixed: opts.allowMixed ?? true })\n } else if (integrityMode === 'warn' && integrity.verdict !== 'real') {\n // eslint-disable-next-line no-console\n console.warn(\n `[runProfileMatrix] backend integrity: ${integrity.verdict} — ${integrity.diagnosis}`,\n )\n }\n\n // Pivots.\n const byScenario = rollup(records, (r) => r.scenarioId)\n const byPersona = opts.personaOf\n ? rollupByPersona(records, opts.scenarios, opts.personaOf)\n : undefined\n\n return { matrixId, experimentId, records, byProfile, byScenario, byPersona, integrity, campaigns }\n}\n\n/** Score for a produced RunRecord, absent when the campaign cell was unscored.\n * Ungated (`runTaskScore` is raw) — a matrix pivot reports measured scores;\n * it is not a training input. */\nfunction scoreOf(r: RunRecord): number | undefined {\n return runTaskScore(r)\n}\n\nfunction rollup(\n records: RunRecord[],\n keyOf: (r: RunRecord) => string | undefined,\n): Record<string, ScenarioRollup> {\n const groups = new Map<string, number[]>()\n for (const r of records) {\n const key = keyOf(r)\n if (key === undefined) continue\n const score = scoreOf(r)\n if (score === undefined) continue\n const arr = groups.get(key) ?? []\n arr.push(score)\n groups.set(key, arr)\n }\n const out: Record<string, ScenarioRollup> = {}\n for (const [key, xs] of groups) out[key] = { meanComposite: mean(xs), n: xs.length }\n return out\n}\n\nfunction rollupByPersona<TScenario extends Scenario>(\n records: RunRecord[],\n scenarios: TScenario[],\n personaOf: (s: TScenario) => string,\n): Record<string, ScenarioRollup> {\n const personaByScenarioId = new Map<string, string>()\n for (const s of scenarios) personaByScenarioId.set(s.id, personaOf(s))\n return rollup(records, (r) => (r.scenarioId ? personaByScenarioId.get(r.scenarioId) : undefined))\n}\n","/**\n * Eval-owned execution for profile matrices whose external authorization is\n * shorter than the complete matrix.\n *\n * A plan freezes the complete profile × scenario × replicate design. A\n * segment claims an explicit, disjoint set of rows and uses the campaign cell\n * cache as the durable per-cell record. Finalization first checks that every\n * planned row has one claim and one valid record, then replays the ordinary\n * `runProfileMatrix` projection from those records without dispatching work.\n */\n\nimport { dirname, join } from 'node:path'\nimport { type AgentProfile, agentProfileHash, agentProfileId } from '../../agent-profile'\nimport { canonicalJson, contentHash } from '../../verdict-cache'\nimport { cellCachePath } from '../cell-schedule'\nimport { assertCampaignDesign, campaignScenarioIdentity } from '../coverage'\nimport { resolveRunDir } from '../run-dir'\nimport { campaignCellCostProvenance, projectCampaignCellQuality } from '../run-record'\nimport type { CampaignStorage } from '../storage'\nimport { fsCampaignStorage } from '../storage'\nimport type { CampaignCellResult, JudgeConfig, Scenario } from '../types'\nimport {\n type ProfileDispatchFn,\n ProfileMatrixError,\n profileMatrixCampaignIdentity,\n type RunProfileMatrixOptions,\n type RunProfileMatrixResult,\n runProfileMatrix,\n} from './run-profile-matrix'\n\nconst PLAN_FILE = 'profile-matrix-plan.json'\nconst SEGMENTS_FILE = 'profile-matrix-segments.jsonl'\n\nclass SegmentedProfileMatrixError extends ProfileMatrixError {\n constructor(message: string) {\n super(`segmented matrix: ${message}`)\n }\n}\n\nexport interface ProfileMatrixRow {\n rowId: string\n ordinal: number\n profileId: string\n scenarioId: string\n rep: number\n}\n\nexport interface ProfileMatrixPlan<TScenario extends Scenario, TArtifact> {\n readonly schemaVersion: 1\n readonly matrixId: string\n readonly experimentId: string\n readonly planDigest: `sha256:${string}`\n readonly profiles: readonly AgentProfile[]\n readonly scenarios: readonly TScenario[]\n readonly judges: readonly JudgeConfig<TArtifact, TScenario>[]\n readonly reps: number\n readonly seed: number\n readonly splitTag: NonNullable<RunProfileMatrixOptions<TScenario, TArtifact>['splitTag']>\n readonly commitSha: string\n /** Stable dispatch implementation/configuration identity used by cell caches. */\n readonly dispatchRef: string\n readonly integrity: NonNullable<RunProfileMatrixOptions<TScenario, TArtifact>['integrity']>\n readonly allowMixed: boolean\n readonly validate: boolean\n readonly personaOf?: (scenario: TScenario) => string\n readonly corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n readonly rows: readonly ProfileMatrixRow[]\n}\n\nexport interface CreateProfileMatrixPlanOptions<TScenario extends Scenario, TArtifact>\n extends Pick<\n RunProfileMatrixOptions<TScenario, TArtifact>,\n | 'profiles'\n | 'scenarios'\n | 'judges'\n | 'commitSha'\n | 'experimentId'\n | 'splitTag'\n | 'reps'\n | 'seed'\n | 'integrity'\n | 'allowMixed'\n | 'validate'\n | 'personaOf'\n | 'corpusText'\n > {\n /** Stable dispatch implementation/configuration identity used by cell caches. */\n dispatchRef: string\n}\n\nexport interface ProfileMatrixCoverage {\n expected: number\n present: number\n missing: string[]\n failed: string[]\n zeroScore: string[]\n}\n\nexport interface RunProfileMatrixSegmentOptions<TScenario extends Scenario, TArtifact> {\n plan: ProfileMatrixPlan<TScenario, TArtifact>\n /** Stable external grant or attempt identity. Reuse it to resume. */\n segmentId: string\n /** Explicit row ids from `plan.rows`; duplicate or unknown rows fail. */\n rows: readonly (string | ProfileMatrixRow)[]\n dispatch: ProfileDispatchFn<TScenario, TArtifact>\n runDir: string\n storage?: CampaignStorage\n maxConcurrency?: number\n maxProfileConcurrency?: number\n costCeiling?: number\n labeledStore?: RunProfileMatrixOptions<TScenario, TArtifact>['labeledStore']\n captureSource?: RunProfileMatrixOptions<TScenario, TArtifact>['captureSource']\n now?: () => Date\n}\n\nexport interface ProfileMatrixSegmentResult<TArtifact, TScenario extends Scenario> {\n segmentId: string\n rowIds: string[]\n matrix: RunProfileMatrixResult<TArtifact, TScenario>\n coverage: ProfileMatrixCoverage\n}\n\nexport interface FinalizeProfileMatrixOptions<TScenario extends Scenario, TArtifact> {\n plan: ProfileMatrixPlan<TScenario, TArtifact>\n runDir: string\n storage?: CampaignStorage\n maxConcurrency?: number\n maxProfileConcurrency?: number\n now?: () => Date\n}\n\nexport interface FinalizedProfileMatrixResult<TArtifact, TScenario extends Scenario>\n extends RunProfileMatrixResult<TArtifact, TScenario> {\n coverage: ProfileMatrixCoverage\n}\n\nexport function createProfileMatrixPlan<TScenario extends Scenario, TArtifact>(\n opts: CreateProfileMatrixPlanOptions<TScenario, TArtifact>,\n): ProfileMatrixPlan<TScenario, TArtifact> {\n if (!Array.isArray(opts.profiles) || opts.profiles.length === 0) {\n throw new SegmentedProfileMatrixError('profiles must not be empty')\n }\n if (!Array.isArray(opts.scenarios) || opts.scenarios.length === 0) {\n throw new SegmentedProfileMatrixError('scenarios must not be empty')\n }\n const reps = opts.reps ?? 1\n const seed = opts.seed ?? 42\n const splitTag = opts.splitTag ?? 'search'\n const integrity = opts.integrity ?? 'assert'\n const allowMixed = opts.allowMixed ?? true\n const validate = opts.validate ?? true\n if (typeof opts.commitSha !== 'string' || opts.commitSha.trim().length === 0) {\n throw new SegmentedProfileMatrixError('commitSha must be a non-empty string')\n }\n if (typeof opts.dispatchRef !== 'string' || opts.dispatchRef.trim().length === 0) {\n throw new SegmentedProfileMatrixError(\n 'dispatchRef must be a non-empty stable identity for segmented execution',\n )\n }\n assertCampaignDesign(opts.scenarios, reps)\n\n const profiles = [...opts.profiles]\n const scenarios = [...opts.scenarios]\n const judges = [...(opts.judges ?? [])]\n const profileIds = profiles.map(agentProfileId)\n const duplicateProfiles = profileIds.filter((id, index) => profileIds.indexOf(id) !== index)\n if (duplicateProfiles.length > 0) {\n throw new SegmentedProfileMatrixError(\n `duplicate profile ids: ${[...new Set(duplicateProfiles)].join(', ')}`,\n )\n }\n\n const experimentId =\n opts.experimentId ??\n `pm_${contentHash({ profileIds, scenarios: scenarios.map((scenario) => scenario.id) }).slice(0, 16)}`\n if (experimentId.trim().length === 0) {\n throw new SegmentedProfileMatrixError('experimentId must be non-empty')\n }\n\n const identityMaterial = {\n schema: 'tangle.profile-matrix-plan.v1',\n profiles: profiles.map((profile, index) => ({\n ordinal: index,\n id: profileIds[index],\n hash: `sha256:${agentProfileHash(profile)}`,\n profile,\n })),\n scenarios: scenarios.map((scenario, index) => ({\n ordinal: index,\n identity: campaignScenarioIdentity(scenario),\n scenario,\n })),\n judges: judges.map((judge) => ({\n name: judge.name,\n dimensions: judge.dimensions,\n judgeVersion: judge.judgeVersion ?? null,\n score: judge.score.toString(),\n appliesTo: judge.appliesTo?.toString() ?? null,\n })),\n reps,\n seed,\n splitTag,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef,\n experimentId,\n integrity,\n allowMixed,\n validate,\n personaOf: opts.personaOf?.toString() ?? null,\n corpusText: opts.corpusText?.toString() ?? null,\n }\n const planDigest = `sha256:${contentHash(identityMaterial)}` as const\n const matrixId = `pmx_${planDigest.slice('sha256:'.length, 'sha256:'.length + 24)}`\n const rows: ProfileMatrixRow[] = []\n const seenCellIds = new Set<string>()\n let ordinal = 0\n for (const profileId of profileIds) {\n for (const scenario of scenarios) {\n for (let rep = 0; rep < reps; rep += 1) {\n const cellId = `${scenario.id}:${rep}`\n if (seenCellIds.has(`${profileId}:${cellId}`)) {\n throw new SegmentedProfileMatrixError(\n `profile/scenario/rep cell id collision for '${profileId}:${cellId}'`,\n )\n }\n seenCellIds.add(`${profileId}:${cellId}`)\n rows.push({\n rowId: `row_${contentHash({ matrixId, profileId, scenarioId: scenario.id, rep }).slice(0, 24)}`,\n ordinal,\n profileId,\n scenarioId: scenario.id,\n rep,\n })\n ordinal += 1\n }\n }\n }\n\n return Object.freeze({\n schemaVersion: 1,\n matrixId,\n experimentId,\n planDigest,\n profiles: Object.freeze(profiles),\n scenarios: Object.freeze(scenarios),\n judges: Object.freeze(judges),\n reps,\n seed,\n splitTag,\n commitSha: opts.commitSha,\n dispatchRef: opts.dispatchRef,\n integrity,\n allowMixed,\n validate,\n ...(opts.personaOf === undefined ? {} : { personaOf: opts.personaOf }),\n ...(opts.corpusText === undefined ? {} : { corpusText: opts.corpusText }),\n rows: Object.freeze(rows),\n }) as ProfileMatrixPlan<TScenario, TArtifact>\n}\n\nexport async function runProfileMatrixSegment<TScenario extends Scenario, TArtifact>(\n opts: RunProfileMatrixSegmentOptions<TScenario, TArtifact>,\n): Promise<ProfileMatrixSegmentResult<TArtifact, TScenario>> {\n const segmentId = requireIdentifier(opts.segmentId, 'segmentId')\n const storage = opts.storage ?? fsCampaignStorage()\n const runDir = resolveRunDir(opts.runDir)\n assertPlan(opts.plan)\n const selected = normalizeRows(opts.plan, opts.rows)\n ensureManifest(storage, runDir, manifestFor(opts.plan))\n claimSegment(storage, runDir, opts.plan, segmentId, selected)\n\n const selectedIds = new Set(selected.map((row) => row.rowId))\n const selectedProfileIds = new Set(selected.map((row) => row.profileId))\n const profiles = opts.plan.profiles.filter((profile) =>\n selectedProfileIds.has(agentProfileId(profile)),\n )\n\n const matrix = await runProfileMatrix<TScenario, TArtifact>({\n profiles,\n scenarios: [...opts.plan.scenarios],\n dispatch: opts.dispatch,\n judges: [...opts.plan.judges],\n runDir,\n commitSha: opts.plan.commitSha,\n dispatchRef: opts.plan.dispatchRef,\n experimentId: opts.plan.experimentId,\n matrixId: opts.plan.matrixId,\n splitTag: opts.plan.splitTag,\n reps: opts.plan.reps,\n seed: opts.plan.seed,\n integrity: 'off',\n allowMixed: opts.plan.allowMixed,\n maxConcurrency: opts.maxConcurrency,\n maxProfileConcurrency: opts.maxProfileConcurrency,\n costCeiling: opts.costCeiling,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n storage,\n now: opts.now,\n personaOf: opts.plan.personaOf,\n validate: opts.plan.validate,\n corpusText: opts.plan.corpusText,\n reuseFailedCells: false,\n rowFilter: ({ profile, scenario, rep }) =>\n selectedIds.has(rowIdFor(opts.plan, agentProfileId(profile), scenario.id, rep)),\n })\n\n persistSegmentCells(storage, runDir, matrix)\n const coverage = readCoverage(storage, runDir, opts.plan)\n return { segmentId, rowIds: selected.map((row) => row.rowId), matrix, coverage }\n}\n\nexport async function finalizeProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: FinalizeProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<FinalizedProfileMatrixResult<TArtifact, TScenario>> {\n const storage = opts.storage ?? fsCampaignStorage()\n const runDir = resolveRunDir(opts.runDir)\n assertPlan(opts.plan)\n ensureManifest(storage, runDir, manifestFor(opts.plan))\n const claims = readSegmentClaims(storage, runDir)\n assertCompleteClaims(opts.plan, claims)\n const coverage = readCoverage(storage, runDir, opts.plan)\n if (coverage.missing.length > 0) {\n throw new SegmentedProfileMatrixError(\n `cannot finalize with missing rows: ${coverage.missing.join(', ')}`,\n )\n }\n\n const matrix = await runProfileMatrix<TScenario, TArtifact>({\n profiles: [...opts.plan.profiles],\n scenarios: [...opts.plan.scenarios],\n dispatch: async () => {\n throw new SegmentedProfileMatrixError(\n 'finalization attempted to dispatch an uncached row; the persisted coverage changed during finalization',\n )\n },\n judges: [...opts.plan.judges],\n runDir,\n commitSha: opts.plan.commitSha,\n dispatchRef: opts.plan.dispatchRef,\n experimentId: opts.plan.experimentId,\n matrixId: opts.plan.matrixId,\n splitTag: opts.plan.splitTag,\n reps: opts.plan.reps,\n seed: opts.plan.seed,\n integrity: opts.plan.integrity,\n allowMixed: opts.plan.allowMixed,\n maxConcurrency: opts.maxConcurrency,\n maxProfileConcurrency: opts.maxProfileConcurrency,\n storage,\n now: opts.now,\n personaOf: opts.plan.personaOf,\n validate: opts.plan.validate,\n corpusText: opts.plan.corpusText,\n reuseFailedCells: true,\n })\n assertFinalRows(opts.plan, matrix)\n return { ...matrix, coverage }\n}\n\ninterface PersistedMatrixManifest {\n schemaVersion: 1\n matrixId: string\n experimentId: string\n planDigest: string\n profiles: Array<{ id: string; hash: string }>\n scenarios: Array<{ id: string; kind: string; scenarioDigest: string }>\n reps: number\n seed: number\n splitTag: string\n commitSha: string\n dispatchRef: string\n rows: ProfileMatrixRow[]\n}\n\ninterface SegmentClaim {\n schemaVersion: 1\n segmentId: string\n planDigest: string\n rowIds: string[]\n}\n\nfunction manifestFor<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n): PersistedMatrixManifest {\n return {\n schemaVersion: 1,\n matrixId: plan.matrixId,\n experimentId: plan.experimentId,\n planDigest: plan.planDigest,\n profiles: plan.profiles.map((profile) => ({\n id: agentProfileId(profile),\n hash: `sha256:${agentProfileHash(profile)}`,\n })),\n scenarios: plan.scenarios.map((scenario) => campaignScenarioIdentity(scenario)),\n reps: plan.reps,\n seed: plan.seed,\n splitTag: plan.splitTag,\n commitSha: plan.commitSha,\n dispatchRef: plan.dispatchRef,\n rows: [...plan.rows],\n }\n}\n\nfunction assertPlan<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n): void {\n const rebuilt = createProfileMatrixPlan({\n profiles: [...plan.profiles],\n scenarios: [...plan.scenarios],\n judges: [...plan.judges],\n commitSha: plan.commitSha,\n dispatchRef: plan.dispatchRef,\n experimentId: plan.experimentId,\n splitTag: plan.splitTag,\n reps: plan.reps,\n seed: plan.seed,\n integrity: plan.integrity,\n allowMixed: plan.allowMixed,\n validate: plan.validate,\n personaOf: plan.personaOf,\n corpusText: plan.corpusText,\n })\n if (\n rebuilt.planDigest !== plan.planDigest ||\n rebuilt.matrixId !== plan.matrixId ||\n canonicalJson(rebuilt.rows) !== canonicalJson(plan.rows)\n ) {\n throw new SegmentedProfileMatrixError('plan inputs changed after identity was created')\n }\n}\n\nfunction ensureManifest(\n storage: CampaignStorage,\n runDir: string,\n expected: PersistedMatrixManifest,\n): void {\n storage.ensureDir(runDir)\n const path = join(runDir, PLAN_FILE)\n const existing = storage.read(path)\n if (existing === undefined) {\n const content = `${canonicalJson(expected)}\\n`\n if (storage.append(path, content, 0) !== undefined) return\n }\n const persisted = storage.read(path)\n if (persisted === undefined) {\n throw new SegmentedProfileMatrixError('persisted plan is unreadable')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(persisted)\n } catch {\n throw new SegmentedProfileMatrixError('persisted plan is corrupt JSON')\n }\n if (canonicalJson(parsed) !== canonicalJson(expected)) {\n throw new SegmentedProfileMatrixError(\n 'persisted plan identity does not match the supplied inputs',\n )\n }\n}\n\nfunction normalizeRows<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n rows: readonly (string | ProfileMatrixRow)[],\n): ProfileMatrixRow[] {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new SegmentedProfileMatrixError('a segment must select at least one row')\n }\n const byId = new Map(plan.rows.map((row) => [row.rowId, row]))\n const selected: ProfileMatrixRow[] = []\n const seen = new Set<string>()\n for (const input of rows) {\n const rowId = typeof input === 'string' ? input : input?.rowId\n if (typeof rowId !== 'string' || rowId.length === 0) {\n throw new SegmentedProfileMatrixError('segment rows must contain row ids')\n }\n if (seen.has(rowId))\n throw new SegmentedProfileMatrixError(`duplicate row '${rowId}' in segment`)\n const row = byId.get(rowId)\n if (!row) throw new SegmentedProfileMatrixError(`row '${rowId}' is not declared by the plan`)\n if (typeof input !== 'string' && canonicalJson(input) !== canonicalJson(row)) {\n throw new SegmentedProfileMatrixError(`row '${rowId}' does not match the declared plan row`)\n }\n seen.add(rowId)\n selected.push(row)\n }\n return selected.sort((left, right) => left.ordinal - right.ordinal)\n}\n\nfunction claimSegment<TScenario extends Scenario, TArtifact>(\n storage: CampaignStorage,\n runDir: string,\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n segmentId: string,\n selected: readonly ProfileMatrixRow[],\n): void {\n const path = join(runDir, SEGMENTS_FILE)\n const expected = canonicalJson({\n schemaVersion: 1,\n segmentId,\n planDigest: plan.planDigest,\n rowIds: selected.map((row) => row.rowId).sort(),\n } satisfies SegmentClaim)\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const raw = storage.read(path) ?? ''\n const claims = parseSegmentClaims(raw, path)\n const existing = claims.find((claim) => claim.segmentId === segmentId)\n if (existing) {\n if (canonicalJson(existing) !== expected) {\n throw new SegmentedProfileMatrixError(\n `segment '${segmentId}' was resumed with different rows or plan identity`,\n )\n }\n return\n }\n const selectedIds = new Set(selected.map((row) => row.rowId))\n const overlap = claims.flatMap((claim) =>\n claim.rowIds\n .filter((rowId) => selectedIds.has(rowId))\n .map((rowId) => `${rowId} (${claim.segmentId})`),\n )\n if (overlap.length > 0) {\n throw new SegmentedProfileMatrixError(\n `segment rows overlap existing claims: ${overlap.join(', ')}`,\n )\n }\n const event = `${expected}\\n`\n const next = storage.append(path, event, byteLength(raw))\n if (next !== undefined) return\n }\n throw new SegmentedProfileMatrixError(\n `could not claim segment '${segmentId}' after concurrent updates`,\n )\n}\n\nfunction readSegmentClaims(storage: CampaignStorage, runDir: string): SegmentClaim[] {\n const path = join(runDir, SEGMENTS_FILE)\n const raw = storage.read(path)\n if (raw === undefined) return []\n return parseSegmentClaims(raw, path)\n}\n\nfunction parseSegmentClaims(raw: string, path: string): SegmentClaim[] {\n const claims: SegmentClaim[] = []\n const seenSegments = new Set<string>()\n const seenRows = new Map<string, string>()\n for (const [index, line] of raw.split('\\n').entries()) {\n if (line.trim() === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n throw new SegmentedProfileMatrixError(`segment registry is corrupt at ${path}:${index + 1}`)\n }\n if (canonicalJson(parsed) !== line) {\n throw new SegmentedProfileMatrixError(\n `segment registry is not canonical at ${path}:${index + 1}`,\n )\n }\n const claim = parsed as Partial<SegmentClaim>\n if (\n claim.schemaVersion !== 1 ||\n typeof claim.segmentId !== 'string' ||\n typeof claim.planDigest !== 'string' ||\n !Array.isArray(claim.rowIds) ||\n claim.rowIds.some((rowId) => typeof rowId !== 'string') ||\n new Set(claim.rowIds).size !== claim.rowIds.length\n ) {\n throw new SegmentedProfileMatrixError(\n `segment registry has an invalid claim at ${path}:${index + 1}`,\n )\n }\n if (seenSegments.has(claim.segmentId)) {\n throw new SegmentedProfileMatrixError(`segment registry repeats segment '${claim.segmentId}'`)\n }\n seenSegments.add(claim.segmentId)\n const normalized = {\n schemaVersion: 1 as const,\n segmentId: claim.segmentId,\n planDigest: claim.planDigest,\n rowIds: [...claim.rowIds].sort(),\n }\n for (const rowId of normalized.rowIds) {\n const owner = seenRows.get(rowId)\n if (owner) {\n throw new SegmentedProfileMatrixError(\n `segment registry overlaps row '${rowId}' between '${owner}' and '${normalized.segmentId}'`,\n )\n }\n seenRows.set(rowId, normalized.segmentId)\n }\n claims.push(normalized)\n }\n return claims\n}\n\nfunction assertCompleteClaims<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n claims: readonly SegmentClaim[],\n): void {\n const expected = new Set(plan.rows.map((row) => row.rowId))\n const claimed = new Set<string>()\n for (const claim of claims) {\n if (claim.planDigest !== plan.planDigest) {\n throw new SegmentedProfileMatrixError(\n `segment '${claim.segmentId}' belongs to a different plan identity`,\n )\n }\n for (const rowId of claim.rowIds) {\n if (!expected.has(rowId)) {\n throw new SegmentedProfileMatrixError(\n `segment '${claim.segmentId}' claims an undeclared row '${rowId}'`,\n )\n }\n claimed.add(rowId)\n }\n }\n const missingClaims = plan.rows.filter((row) => !claimed.has(row.rowId)).map((row) => row.rowId)\n if (missingClaims.length > 0) {\n throw new SegmentedProfileMatrixError(\n `cannot finalize until every row is claimed: ${missingClaims.join(', ')}`,\n )\n }\n}\n\nfunction persistSegmentCells<TArtifact, TScenario extends Scenario>(\n storage: CampaignStorage,\n runDir: string,\n matrix: RunProfileMatrixResult<TArtifact, TScenario>,\n): void {\n for (const [profileId, campaign] of Object.entries(matrix.campaigns)) {\n for (const cell of campaign.cells) {\n const path = cellCachePath(join(runDir, profileDirectory(profileId)), cell.cellId)\n storage.ensureDir(dirname(path))\n // Campaign caches already use JSON.stringify, which omits optional\n // undefined fields such as a successful cell's `error` property.\n storage.write(path, `${JSON.stringify(cell)}\\n`)\n }\n }\n}\n\nfunction readCoverage<TScenario extends Scenario, TArtifact>(\n storage: CampaignStorage,\n runDir: string,\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n): ProfileMatrixCoverage {\n const expectedManifestHashes = new Map<string, string>(\n plan.profiles.map((profile) => {\n const identity = profileMatrixCampaignIdentity({\n profile,\n scenarios: [...plan.scenarios],\n judges: [...plan.judges],\n commitSha: plan.commitSha,\n dispatchRef: plan.dispatchRef,\n splitTag: plan.splitTag,\n seed: plan.seed,\n reps: plan.reps,\n })\n return [identity.profileId, identity.manifestHash] as const\n }),\n )\n const missing: string[] = []\n const failed: string[] = []\n const zeroScore: string[] = []\n let present = 0\n for (const row of plan.rows) {\n const path = cellCachePath(\n join(runDir, profileDirectory(row.profileId)),\n `${row.scenarioId}:${row.rep}`,\n )\n const raw = storage.read(path)\n if (raw === undefined) {\n missing.push(row.rowId)\n continue\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new SegmentedProfileMatrixError(`cell '${row.rowId}' has corrupt JSON`)\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new SegmentedProfileMatrixError(`cell '${row.rowId}' has an invalid record shape`)\n }\n const cell = parsed as CampaignCellResult<TArtifact>\n if (\n cell.cellId !== `${row.scenarioId}:${row.rep}` ||\n cell.scenarioId !== row.scenarioId ||\n cell.rep !== row.rep ||\n cell.manifestHash !== expectedManifestHashes.get(row.profileId)\n ) {\n throw new SegmentedProfileMatrixError(\n `cell '${row.rowId}' has stale identity fields (manifest or row identity)`,\n )\n }\n try {\n campaignCellCostProvenance(cell)\n } catch (error) {\n throw new SegmentedProfileMatrixError(\n `cell '${row.rowId}' failed cost-record validation: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n present += 1\n if (cell.error !== undefined) {\n failed.push(row.rowId)\n continue\n }\n if (projectCampaignCellQuality(cell).score === 0) zeroScore.push(row.rowId)\n }\n return {\n expected: plan.rows.length,\n present,\n missing,\n failed,\n zeroScore,\n }\n}\n\nfunction assertFinalRows<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n matrix: RunProfileMatrixResult<TArtifact, TScenario>,\n): void {\n const expected = new Set(plan.rows.map((row) => `${row.profileId}:${row.scenarioId}:${row.rep}`))\n const seen = new Set<string>()\n for (const record of matrix.records) {\n const key = `${record.candidateId}:${record.scenarioId}:${record.outcome.raw.rep}`\n if (!expected.has(key) || seen.has(key)) {\n throw new SegmentedProfileMatrixError(\n `final matrix has an unexpected or duplicate row '${key}'`,\n )\n }\n seen.add(key)\n }\n if (seen.size !== expected.size) {\n throw new SegmentedProfileMatrixError(\n `final matrix returned ${seen.size}/${expected.size} declared rows`,\n )\n }\n}\n\nfunction rowIdFor<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n profileId: string,\n scenarioId: string,\n rep: number,\n): string {\n const row = plan.rows.find(\n (candidate) =>\n candidate.profileId === profileId &&\n candidate.scenarioId === scenarioId &&\n candidate.rep === rep,\n )\n if (!row)\n throw new SegmentedProfileMatrixError(`row is not declared: ${profileId}/${scenarioId}/${rep}`)\n return row.rowId\n}\n\nfunction profileDirectory(profileId: string): string {\n return profileId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction requireIdentifier(value: string, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new SegmentedProfileMatrixError(`${name} must be a non-empty string`)\n }\n return value\n}\n\nfunction byteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength\n}\n","/**\n * Race a profile matrix: run the surviving profiles on doubling case batches\n * and stop paying for a profile once it is clearly worse than the leader.\n *\n * The race is a sampling policy over a segmented plan. Each batch is one\n * `runProfileMatrixSegment` with a stable segment id, so a race interrupted\n * mid-batch resumes from the campaign cell cache and replays the same\n * decisions. Rows the race never ran stay unclaimed: running them later and\n * calling `finalizeProfileMatrix` completes the full matrix.\n */\n\nimport { ValidationError } from '../../errors'\nimport { assertRealBackend, summarizeBackendIntegrity } from '../../integrity/backend-integrity'\nimport type { RunRecord } from '../../run-record'\nimport { makeRng } from '../../statistics/internal'\nimport { mean } from '../../statistics/mean'\nimport type { Scenario } from '../types'\nimport {\n allPassFail,\n clusterResolver,\n type ProfileMatrixPairedDifference,\n type ProfilePairingRule,\n pairProfiles,\n scoresByProfile,\n} from './profile-matrix-analysis'\nimport {\n type ProfileMatrixPlan,\n type RunProfileMatrixSegmentOptions,\n runProfileMatrixSegment,\n} from './segmented-profile-matrix'\n\nexport interface RaceProfileMatrixOptions<TScenario extends Scenario, TArtifact>\n extends Omit<RunProfileMatrixSegmentOptions<TScenario, TArtifact>, 'segmentId' | 'rows'> {\n /** Profile id kept to the end whatever its standing; the final comparison is against it. */\n baseline: string\n /** Cases seen after each batch, strictly increasing. Default: `firstBatch`, doubling until every case is in. */\n batches?: readonly number[]\n /** Cases in the first batch when `batches` is not given. Default 8. */\n firstBatch?: number\n /** Most cells (one profile on one case and rep) the race may run; a batch that would pass it is not started. */\n cellBudget?: number\n /** Independent unit per case id; every raced case needs one. Default one unit per case. */\n clusters?: Readonly<Record<string, string>>\n /** Interval level of each elimination. Default 0.95. */\n level?: number\n /** `shuffled` (default) orders cases by a draw seeded with the plan seed; `plan` keeps the plan's order. */\n caseOrder?: 'shuffled' | 'plan'\n}\n\nexport interface ProfileMatrixRaceStanding {\n profileId: string\n /** Cases both this profile and the leader scored. */\n n: number\n /** Independent clusters among those cases. */\n clusters: number\n /** Mean paired difference from the leader; null without a shared scored case. */\n difference: number | null\n low: number | null\n high: number | null\n /** Exact cluster sign-flip p-value for a zero difference. */\n pValue: number | null\n /** Paired cases a test needs for 80% power at the observed difference. */\n casesToResolve: number | null\n dropped: boolean\n reason?: string\n}\n\nexport interface ProfileMatrixRaceBatch {\n batch: number\n casesSeen: number\n cellsRun: number\n leader: string\n standings: ProfileMatrixRaceStanding[]\n}\n\nexport interface ProfileMatrixRaceFinalRow {\n profileId: string\n quality: number | null\n /** Paired difference from the baseline on the final cases; null on the baseline itself. */\n vsBaseline: ProfileMatrixPairedDifference | null\n}\n\nexport interface ProfileMatrixRaceResult {\n matrixId: string\n planDigest: string\n baseline: string\n leader: string\n survivors: string[]\n stoppedBecause: 'one-left' | 'cell-budget' | 'batches-ended'\n casesRaced: string[]\n cellsRun: number\n /** Cells the complete plan holds. */\n plannedCells: number\n log: ProfileMatrixRaceBatch[]\n /** Survivors on the cases every survivor scored. */\n final: { cases: number; rows: ProfileMatrixRaceFinalRow[] }\n records: RunRecord[]\n /** The race chose its leader on these cases, so the leader's score here reads high. */\n selectionBias: string\n}\n\ntype Scores = Map<string, Map<string, number>>\n\ninterface RaceContext {\n baseline: string\n /** Pairing rule; `passFail` is read from the scores at each comparison. */\n rule: ProfilePairingRule\n /** Plan order with the baseline first; ties go to the earlier profile. */\n profileIds: string[]\n}\n\n/**\n * Successive halving over a profile-matrix plan. After each batch a profile\n * whose paired interval against the current leader lies wholly below zero is\n * dropped, as is one whose cells in the batch produced no score; the baseline\n * is always kept. The race stops when one profile is left, the next batch\n * would pass `cellBudget`, or the batch list ends.\n */\nexport async function raceProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: RaceProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<ProfileMatrixRaceResult> {\n const {\n baseline,\n batches: requestedBatches,\n firstBatch,\n cellBudget,\n clusters,\n level = 0.95,\n caseOrder = 'shuffled',\n ...segment\n } = opts\n const { plan } = segment\n const planned = [...new Set(plan.rows.map((row) => row.profileId))]\n if (!planned.includes(baseline)) {\n throw new ValidationError(`raceProfileMatrix: baseline '${baseline}' is not a planned profile`)\n }\n if (!(level > 0 && level < 1))\n throw new ValidationError('raceProfileMatrix: level must be in (0, 1)')\n if (cellBudget !== undefined && !(Number.isSafeInteger(cellBudget) && cellBudget > 0)) {\n throw new ValidationError('raceProfileMatrix: cellBudget must be a positive integer')\n }\n const ctx: RaceContext = {\n baseline,\n rule: {\n clusterOf: clusterResolver(clusters, 'raceProfileMatrix'),\n level,\n passScore: 0.5,\n passFail: true,\n },\n profileIds: [baseline, ...planned.filter((id) => id !== baseline)],\n }\n const order = orderCases(plan, caseOrder)\n const batches = batchSizes(requestedBatches, firstBatch, order.length)\n\n let survivors = [...ctx.profileIds]\n const records = new Map<string, RunRecord>()\n const log: ProfileMatrixRaceBatch[] = []\n let cellsRun = 0\n let seen = 0\n let stoppedBecause: ProfileMatrixRaceResult['stoppedBecause'] = 'batches-ended'\n for (const [index, total] of batches.entries()) {\n if (survivors.length === 1) break\n const batchCases = order.slice(seen, total)\n const inBatch = new Set(batchCases)\n const rows = plan.rows.filter(\n (row) => survivors.includes(row.profileId) && inBatch.has(row.scenarioId),\n )\n if (cellBudget !== undefined && cellsRun + rows.length > cellBudget) {\n if (index === 0) {\n throw new ValidationError(\n `raceProfileMatrix: cellBudget ${cellBudget} is below the first batch's ${rows.length} cells`,\n )\n }\n stoppedBecause = 'cell-budget'\n break\n }\n const result = await runProfileMatrixSegment({\n ...segment,\n segmentId: `race-batch-${index + 1}`,\n rows: rows.map((row) => row.rowId),\n })\n enforceIntegrity(plan, result.matrix.records)\n for (const record of result.matrix.records) records.set(record.runId, record)\n cellsRun += rows.length\n seen = total\n const entry = standings(\n ctx,\n scoresByProfile([...records.values()]),\n survivors,\n order.slice(0, seen),\n batchCases,\n )\n log.push({ batch: index + 1, casesSeen: seen, cellsRun: rows.length, ...entry })\n const dropped = new Set(entry.standings.filter((s) => s.dropped).map((s) => s.profileId))\n survivors = survivors.filter((id) => !dropped.has(id))\n }\n if (survivors.length === 1) stoppedBecause = 'one-left'\n\n const casesRaced = order.slice(0, seen)\n const final = finalComparison(ctx, scoresByProfile([...records.values()]), survivors, casesRaced)\n return {\n matrixId: plan.matrixId,\n planDigest: plan.planDigest,\n baseline,\n leader: final.leader,\n survivors,\n stoppedBecause,\n casesRaced,\n cellsRun,\n plannedCells: plan.rows.length,\n log,\n final: { cases: final.cases, rows: final.rows },\n records: [...records.values()],\n selectionBias:\n `${final.leader} leads on the ${casesRaced.length} raced cases, which the race also used to ` +\n 'choose it, so its score there is biased upward; confirm it on fresh held-out cases before acting on it.',\n }\n}\n\nfunction orderCases<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n caseOrder: 'shuffled' | 'plan',\n): string[] {\n const ids = plan.scenarios.map((scenario) => scenario.id)\n if (caseOrder === 'plan') return ids\n const rng = makeRng(plan.seed)\n for (let i = ids.length - 1; i > 0; i -= 1) {\n const j = Math.floor(rng() * (i + 1))\n ;[ids[i], ids[j]] = [ids[j]!, ids[i]!]\n }\n return ids\n}\n\nfunction batchSizes(\n requested: readonly number[] | undefined,\n firstBatch: number | undefined,\n caseCount: number,\n): number[] {\n if (requested !== undefined) {\n const valid =\n requested.length > 0 &&\n requested.every(\n (total, i) =>\n Number.isSafeInteger(total) &&\n total > (i === 0 ? 0 : requested[i - 1]!) &&\n total <= caseCount,\n )\n if (!valid) {\n throw new ValidationError(\n `raceProfileMatrix: batches must be strictly increasing case counts within 1..${caseCount}`,\n )\n }\n return [...requested]\n }\n const first = firstBatch ?? Math.min(8, caseCount)\n if (!(Number.isSafeInteger(first) && first > 0 && first <= caseCount)) {\n throw new ValidationError(\n `raceProfileMatrix: firstBatch must be an integer within 1..${caseCount}`,\n )\n }\n const sizes: number[] = []\n for (let total = first; total < caseCount; total *= 2) sizes.push(total)\n sizes.push(caseCount)\n return sizes\n}\n\nfunction enforceIntegrity<TScenario extends Scenario, TArtifact>(\n plan: ProfileMatrixPlan<TScenario, TArtifact>,\n records: readonly RunRecord[],\n): void {\n if (plan.integrity === 'assert') assertRealBackend(records, { allowMixed: plan.allowMixed })\n if (plan.integrity !== 'warn') return\n const report = summarizeBackendIntegrity(records)\n if (report.verdict !== 'real') {\n console.warn(`[raceProfileMatrix] backend integrity: ${report.verdict} — ${report.diagnosis}`)\n }\n}\n\n/** The highest mean on the cases every candidate scored; ties go to the earlier profile. */\nfunction leaderOf(\n ctx: RaceContext,\n scores: Scores,\n candidates: readonly string[],\n cases: readonly string[],\n) {\n const shared = cases.filter((c) => candidates.every((p) => scores.get(p)?.has(c)))\n let leader = candidates.includes(ctx.baseline) ? ctx.baseline : candidates[0]!\n if (shared.length === 0) return { leader, shared }\n const quality = (p: string) => mean(shared.map((c) => scores.get(p)!.get(c)!))\n for (const p of ctx.profileIds) {\n if (candidates.includes(p) && quality(p) > quality(leader)) leader = p\n }\n return { leader, shared }\n}\n\n/** `p` against `q` on the cases both scored within `cases`, through the page's pairing helper. */\nfunction pairedAgainst(\n ctx: RaceContext,\n scores: Scores,\n p: string,\n q: string,\n cases: readonly string[],\n): ProfileMatrixPairedDifference | undefined {\n const rule = { ...ctx.rule, passFail: allPassFail(scores) }\n return pairProfiles(scores.get(p) ?? new Map(), scores.get(q) ?? new Map(), rule, cases)\n}\n\nfunction standings(\n ctx: RaceContext,\n scores: Scores,\n survivors: readonly string[],\n seen: readonly string[],\n batchCases: readonly string[],\n): Pick<ProfileMatrixRaceBatch, 'leader' | 'standings'> {\n const { leader } = leaderOf(ctx, scores, survivors, seen)\n return {\n leader,\n standings: survivors.map((profileId) => {\n const paired = pairedAgainst(ctx, scores, profileId, leader, seen)\n const base = {\n profileId,\n n: paired?.n ?? 0,\n clusters: paired?.clusters ?? 0,\n difference: paired?.estimate ?? null,\n low: paired?.low ?? null,\n high: paired?.high ?? null,\n pValue: paired?.pValue ?? null,\n casesToResolve: paired?.casesToResolve ?? null,\n }\n const protectedProfile = profileId === ctx.baseline || profileId === leader\n if (!batchCases.some((c) => scores.get(profileId)?.has(c))) {\n return protectedProfile\n ? { ...base, dropped: false, reason: 'kept: no cell in this batch produced a score' }\n : { ...base, dropped: true, reason: 'no cell in this batch produced a score' }\n }\n if (base.high === null || base.high >= 0) return { ...base, dropped: false }\n const interval = `[${base.low!.toFixed(3)}, ${base.high.toFixed(3)}]`\n return protectedProfile\n ? {\n ...base,\n dropped: false,\n reason: `kept as the baseline: interval ${interval} lies below zero`,\n }\n : {\n ...base,\n dropped: true,\n reason: `interval ${interval} against ${leader} lies below zero`,\n }\n }),\n }\n}\n\nfunction finalComparison(\n ctx: RaceContext,\n scores: Scores,\n survivors: readonly string[],\n casesRaced: readonly string[],\n) {\n const { leader, shared } = leaderOf(ctx, scores, survivors, casesRaced)\n const rows = survivors.map(\n (profileId): ProfileMatrixRaceFinalRow => ({\n profileId,\n quality: shared.length ? mean(shared.map((c) => scores.get(profileId)!.get(c)!)) : null,\n vsBaseline:\n profileId === ctx.baseline\n ? null\n : (pairedAgainst(ctx, scores, profileId, ctx.baseline, shared) ?? null),\n }),\n )\n return { leader, cases: shared.length, rows }\n}\n","// Reliability across seeded repeats: how often a scenario succeeds in every one\n// of k repeats, reported beside its mean success and counted per independent\n// unit. A conversation that resolves the user's problem on two seeds out of\n// four has a mean success of 0.5 and a pass^4 of 0; an agent a user can rely\n// on needs the second number, which a mean never shows.\n\nimport { passHatK } from '../statistics/paired-binary'\nimport type { CampaignCellResult } from './types'\n\nexport interface RepeatReliabilityOptions<TArtifact> {\n /** Repeats every success must hold over: pass^k. A scenario with fewer scored\n * repeats than `k` reports no pass^k and is listed as incomplete. */\n k: number\n /** Objective success of one repeat, decided by code from the artifact. */\n success: (artifact: TArtifact) => boolean\n /** Independent sampling unit for each scenario; scenarios sharing a unit are\n * averaged before units are weighted equally. Default: each scenario is its\n * own unit. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\nexport interface ScenarioRepeatReliability {\n scenarioId: string\n unit: string\n /** Scored repeats: cells that produced an artifact without an error. */\n repeats: number\n successes: number\n meanSuccess: number\n /** Unbiased pass^k over the scored repeats; null below `k` repeats. */\n passAllK: number | null\n}\n\nexport interface RepeatReliability {\n k: number\n /** Scenarios in first-seen cell order. */\n scenarios: ScenarioRepeatReliability[]\n /** Independent units with at least one scored repeat. */\n units: number\n /** Mean success, each unit weighted equally; null with no scored repeat. */\n meanSuccess: number | null\n /** pass^k, each unit weighted equally over its complete scenarios; null when\n * no scenario has `k` scored repeats. */\n passAllK: number | null\n /** Scenarios with fewer than `k` scored repeats. */\n incompleteScenarios: string[]\n /** Cells that failed in dispatch or judging. They are a service or\n * measurement failure, never a counted agent failure. */\n failedCells: number\n}\n\n/** pass^k beside mean success over a campaign's seeded repeats. */\nexport function repeatReliability<TArtifact>(\n cells: ReadonlyArray<CampaignCellResult<TArtifact>>,\n opts: RepeatReliabilityOptions<TArtifact>,\n): RepeatReliability {\n if (!Number.isSafeInteger(opts.k) || opts.k < 1) {\n throw new RangeError(`repeatReliability: k must be a positive integer, got ${opts.k}`)\n }\n const byScenario = new Map<string, { repeats: number; successes: number }>()\n let failedCells = 0\n for (const cell of cells) {\n if (cell.error !== undefined) {\n failedCells += 1\n continue\n }\n const row = byScenario.get(cell.scenarioId) ?? { repeats: 0, successes: 0 }\n const passed = opts.success(cell.artifact)\n if (typeof passed !== 'boolean') {\n throw new TypeError(\n `repeatReliability: success must return a boolean for '${cell.scenarioId}'`,\n )\n }\n row.repeats += 1\n if (passed) row.successes += 1\n byScenario.set(cell.scenarioId, row)\n }\n\n const scenarios: ScenarioRepeatReliability[] = [...byScenario].map(([scenarioId, row]) => ({\n scenarioId,\n unit: opts.independentUnitByScenarioId?.get(scenarioId) ?? scenarioId,\n repeats: row.repeats,\n successes: row.successes,\n meanSuccess: row.successes / row.repeats,\n passAllK: row.repeats >= opts.k ? passHatK(row.repeats, row.successes, opts.k) : null,\n }))\n const unitMean = (values: (row: ScenarioRepeatReliability) => number | null) => {\n const units = new Map<string, number[]>()\n for (const row of scenarios) {\n const value = values(row)\n if (value === null) continue\n units.set(row.unit, [...(units.get(row.unit) ?? []), value])\n }\n if (units.size === 0) return null\n const means = [...units.values()].map((list) => list.reduce((a, b) => a + b, 0) / list.length)\n return means.reduce((a, b) => a + b, 0) / means.length\n }\n return {\n k: opts.k,\n scenarios,\n units: new Set(scenarios.map((row) => row.unit)).size,\n meanSuccess: unitMean((row) => row.meanSuccess),\n passAllK: unitMean((row) => row.passAllK),\n incompleteScenarios: scenarios.filter((row) => row.passAllK === null).map((r) => r.scenarioId),\n failedCells,\n }\n}\n","import { join } from 'node:path'\nimport { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport {\n canonicalString,\n compareCodeUnits,\n hashCanonical,\n type LedgerHash,\n} from '../ledger-core/canonical'\nimport { type CampaignStorage, fsCampaignStorage } from './storage'\n\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst headerSchema = z\n .object({\n kind: z.literal('retained-dispatch-v1'),\n scope: digest,\n limits: z.array(z.tuple([z.string().min(1), z.number().int().nonnegative()])),\n })\n .strict()\nconst eventSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('started'), id: digest, lane: z.string().min(1) }).strict(),\n z.object({ kind: z.literal('settled'), id: digest, receipt: digest }).strict(),\n])\nconst resultSchema = z\n .object({\n kind: z.literal('retained-dispatch-result-v1'),\n id: digest,\n receipt: digest,\n value: z.unknown(),\n })\n .strict()\n/** The committed byte length and cumulative digest of retained dispatch history. */\nconst anchorEntrySchema = z\n .object({\n kind: z.literal('retained-dispatch-anchor-v1'),\n scope: digest,\n bytes: z.number().int().positive(),\n digest,\n })\n .strict()\ntype Event = z.infer<typeof eventSchema>\ntype AnchorEntry = z.infer<typeof anchorEntrySchema>\n\nexport type RetainedDispatchOutcome<T> =\n | {\n succeeded: true\n value: T\n dispatchId: LedgerHash\n receiptDigest: LedgerHash\n replayed: boolean\n }\n | { succeeded: false; reason: 'outcome_unknown'; dispatchId: LedgerHash; diagnostic?: string }\n | { succeeded: false; reason: 'allowance_exhausted'; dispatchId: LedgerHash }\n\n/** One logical run owns this directory. Callers bind authority and execution/decoder revisions in scope. */\nexport interface RetainedDispatchOptions<Lane extends string, T> {\n runDir: string\n scope: unknown\n /** Reserved allowances: one lane cannot spend another lane's calls. */\n limits: Readonly<Record<Lane, number>>\n /** Validate the complete retained result, including explicit failed/unknown execution outcomes. */\n parse: (value: unknown) => T\n storage?: CampaignStorage\n /** The owning durable Run has started this scope; missing history must not issue another allowance. */\n requireExisting?: boolean\n}\n\ntype Header = z.infer<typeof headerSchema>\n\n/** The loaded journal of one retained-dispatch scope: its paths, accounting and verified history. */\ninterface DispatchJournal<T> {\n storage: CampaignStorage\n parse: (value: unknown) => T\n header: Header\n limits: Map<string, number>\n counts: Map<string, number>\n calls: Map<string, { lane: string; receipt?: string }>\n indexPath: string\n scopePath: string\n anchorPath: string\n receiptsDir: string\n scopeText: string\n scopeDigest: LedgerHash\n /** The journal text already applied, its byte length, cumulative digest, and whether the header is in it. */\n retainedText: string\n revision: number\n chain: LedgerHash | null\n opened: boolean\n}\n\ntype DispatchRequest<Lane extends string, T> = {\n lane: Lane\n input: unknown\n dispatch: () => Promise<T>\n signal?: AbortSignal\n}\n\nfunction fail(message: string): never {\n throw new ValidationError(`retained dispatch: ${message}`)\n}\n\n/**\n * Persist dispatch intent before an external call and its validated result afterward.\n * Replays settled calls; never repeats an uncertain call or refunds its allowance.\n * Every journal event is durably anchored before it takes effect, and history that\n * cannot be proven equal to its durable anchor fails closed.\n * This wraps a campaign's dispatch; runEval still owns scheduling, judging and reports.\n * Uses CampaignStorage's existing compare-and-append, not another database or scheduler.\n */\nexport function createRetainedDispatch<Lane extends string, T>(\n options: RetainedDispatchOptions<Lane, T>,\n) {\n if (!options.runDir.trim())\n throw new ValidationError('retained dispatch requires a run directory')\n const storage = options.storage ?? fsCampaignStorage()\n const header = headerSchema.parse({\n kind: 'retained-dispatch-v1',\n scope: hashCanonical(options.scope),\n limits: Object.entries(options.limits).sort(([a], [b]) => compareCodeUnits(a, b)),\n })\n if (!header.limits.length)\n throw new ValidationError('retained dispatch requires named allowances')\n const journal: DispatchJournal<T> = {\n storage,\n parse: options.parse,\n header,\n limits: new Map(header.limits),\n counts: new Map<string, number>(),\n calls: new Map<string, { lane: string; receipt?: string }>(),\n indexPath: join(options.runDir, 'dispatches.jsonl'),\n scopePath: join(options.runDir, 'dispatch-scope.json'),\n anchorPath: join(options.runDir, 'dispatch-anchor.jsonl'),\n receiptsDir: join(options.runDir, 'dispatch-results'),\n scopeText: canonicalString(header),\n scopeDigest: hashCanonical(header),\n retainedText: '',\n revision: 0,\n chain: null,\n opened: false,\n }\n const active = new Map<string, Promise<RetainedDispatchOutcome<T>>>()\n storage.ensureDir(options.runDir)\n storage.ensureDir(journal.receiptsDir)\n openJournal(journal, options.requireExisting)\n\n return {\n /** The input binds all behavior-affecting request material, not just a caller-selected nonce. */\n run(request: DispatchRequest<Lane, T>): Promise<RetainedDispatchOutcome<T>> {\n const id = hashCanonical([header.scope, request.lane, request.input])\n const pending = active.get(id)\n if (pending) return pending\n const promise = dispatchOnce(journal, id, request)\n active.set(id, promise)\n void promise\n .finally(() => {\n active.delete(id)\n })\n .catch(() => {})\n return promise\n },\n /** Counts include uncertain dispatches, which keep their reservation. No pricing is inferred. */\n committed(): ReadonlyMap<Lane, number> {\n refreshJournal(journal)\n return new Map(header.limits.map(([lane]) => [lane as Lane, journal.counts.get(lane) ?? 0]))\n },\n }\n}\n\n/** Fold one journal event into the per-lane counts and pending-call map. */\nfunction applyEvent<T>(journal: DispatchJournal<T>, event: Event): void {\n const existing = journal.calls.get(event.id)\n if (event.kind === 'started') {\n const limit = journal.limits.get(event.lane)\n const count = journal.counts.get(event.lane) ?? 0\n if (existing || limit === undefined || count >= limit)\n fail('invalid or over-budget dispatch history')\n journal.calls.set(event.id, { lane: event.lane })\n journal.counts.set(event.lane, count + 1)\n } else {\n if (!existing || existing.receipt) fail('settlement has no unique pending dispatch')\n existing.receipt = event.receipt\n }\n}\n\n/** Read the durable anchor file, refusing a torn, empty-record, foreign-scope or non-monotonic one. */\nfunction readAnchor<T>(journal: DispatchJournal<T>): { text: string; entries: AnchorEntry[] } {\n const { storage, anchorPath } = journal\n const content = storage.read(anchorPath)\n if (content === undefined && storage.exists(anchorPath)) fail('cannot read durable anchor')\n const text = content ?? ''\n if (text && !text.endsWith('\\n')) fail('durable anchor is torn')\n const entries: AnchorEntry[] = []\n let previous = 0\n const lines = text.split('\\n')\n if (lines.at(-1) === '') lines.pop()\n if (lines.some((line) => !line)) fail('durable anchor contains an empty record')\n for (const line of lines) {\n const entry = anchorEntrySchema.parse(JSON.parse(line) as unknown)\n if (entry.scope !== journal.scopeDigest) fail('durable anchor scope changed')\n if (entry.bytes <= previous) fail('durable anchor is not append-only')\n previous = entry.bytes\n entries.push(entry)\n }\n return { text, entries }\n}\n\n/** Re-read the journal, prove it extends what was applied and matches its anchor, and apply the new events. */\nfunction refreshJournal<T>(journal: DispatchJournal<T>): void {\n const { storage } = journal\n if (storage.read(journal.scopePath) !== journal.scopeText)\n fail('scope anchor is missing or changed')\n const stored = storage.read(journal.indexPath)\n if (stored === undefined && storage.exists(journal.indexPath))\n fail('cannot read existing history')\n const text = stored ?? ''\n if (!text.startsWith(journal.retainedText) || (text && !text.endsWith('\\n')))\n fail('history was truncated, replaced or torn')\n const { entries } = readAnchor(journal)\n const bytes = Buffer.byteLength(text)\n const applied = Buffer.byteLength(journal.retainedText)\n if (text && !entries.length) fail('durable anchor is missing')\n const highWater = entries[entries.length - 1]\n if (highWater && bytes !== highWater.bytes) {\n // Bytes beyond the durable anchor are never trusted, shortened or synthesized.\n if (bytes < highWater.bytes) fail('history was truncated below its durable anchor')\n fail('history extends beyond its durable anchor')\n }\n let offset = 0\n let running: LedgerHash | null = null\n let entryIndex = 0\n let seenHeader = journal.opened\n for (const line of text.split('\\n')) {\n if (!line) continue\n running = hashCanonical([running, line])\n offset += Buffer.byteLength(line) + 1\n while (entryIndex < entries.length && entries[entryIndex]!.bytes === offset) {\n if (entries[entryIndex]!.digest !== running) fail('history diverges from its durable anchor')\n entryIndex += 1\n }\n if (offset <= applied) continue\n if (!seenHeader) {\n const value: unknown = JSON.parse(line)\n if (hashCanonical(headerSchema.parse(value)) !== hashCanonical(journal.header))\n fail('resume changed its scope or allowances')\n seenHeader = true\n } else applyEvent(journal, eventSchema.parse(JSON.parse(line) as unknown))\n }\n if (entries.length && entryIndex !== entries.length)\n fail('history diverges from its durable anchor')\n journal.chain = running\n journal.retainedText = text\n journal.revision = bytes\n journal.opened = seenHeader\n}\n\n/** Compare-and-append one event; a lost race refreshes the journal and returns false. */\nfunction appendEvent<T>(journal: DispatchJournal<T>, event: Header | Event): boolean {\n const encoded = canonicalString(event)\n const line = `${encoded}\\n`\n const next = journal.storage.append(journal.indexPath, line, journal.revision)\n if (next === undefined) {\n refreshJournal(journal)\n return false\n }\n if (next !== journal.revision + Buffer.byteLength(line))\n fail('storage returned an invalid append revision')\n journal.chain = hashCanonical([journal.chain, encoded])\n journal.retainedText += line\n journal.revision = next\n if (event.kind === 'retained-dispatch-v1') journal.opened = true\n else applyEvent(journal, event)\n return true\n}\n\n/** Record the journal's current length and digest in the durable anchor. */\nfunction advanceAnchor<T>(journal: DispatchJournal<T>): void {\n const currentChain = journal.chain ?? fail('cannot anchor an empty history')\n if (journal.revision <= 0) fail('cannot anchor an empty history')\n const { text, entries } = readAnchor(journal)\n const last = entries[entries.length - 1]\n if (last) {\n if (last.bytes > journal.revision) fail('history is behind its durable anchor')\n if (last.bytes === journal.revision) {\n if (last.digest !== currentChain) fail('history diverges from its durable anchor')\n return\n }\n }\n const line = `${canonicalString({\n kind: 'retained-dispatch-anchor-v1',\n scope: journal.scopeDigest,\n bytes: journal.revision,\n digest: currentChain,\n } satisfies AnchorEntry)}\\n`\n const next = journal.storage.append(journal.anchorPath, line, Buffer.byteLength(text))\n if (next === undefined) {\n const concurrent = readAnchor(journal).entries.at(-1)\n if (concurrent?.bytes === journal.revision && concurrent.digest === journal.chain) return\n fail('durable anchor append is busy; retry with the same run directory')\n }\n if (next !== Buffer.byteLength(text) + Buffer.byteLength(line))\n fail('storage returned an invalid durable anchor revision')\n}\n\n/** An event takes effect only after both its journal append and its anchor entry are durable. */\nfunction commitEvent<T>(journal: DispatchJournal<T>, event: Header | Event): boolean {\n if (!appendEvent(journal, event)) return false\n advanceAnchor(journal)\n return true\n}\n\n/** Create or verify the scope anchor, load existing history, and commit the header on a fresh journal. */\nfunction openJournal<T>(journal: DispatchJournal<T>, requireExisting: boolean | undefined): void {\n const { storage, scopePath, indexPath, anchorPath, scopeText } = journal\n // The immutable scope and append-only history anchor distinguish fresh runs from lost journals.\n // A half-initialized scope is held for reconciliation, never guessed to be unused.\n if (\n requireExisting &&\n (!storage.exists(scopePath) || !storage.exists(indexPath) || !storage.exists(anchorPath))\n )\n fail('required retained history is missing')\n if (storage.exists(scopePath)) {\n if (storage.read(scopePath) !== scopeText) fail('resume changed its scope or allowances')\n if (!storage.read(indexPath)?.trim()) fail('dispatch history is missing or empty')\n // A history without its committed high-water mark is never treated as unused.\n if (!storage.read(anchorPath)?.trim()) fail('durable anchor is missing')\n } else {\n if (storage.exists(indexPath) || storage.exists(anchorPath))\n fail('legacy history has no scope anchor; reconcile before migration')\n const created = storage.append(scopePath, scopeText, 0)\n if (created === undefined) {\n if (storage.read(scopePath) !== scopeText || !storage.read(indexPath)?.trim())\n fail('scope initialization is busy; retry the same scope')\n } else if (created !== Buffer.byteLength(scopeText)) {\n fail('storage returned an invalid scope revision')\n }\n }\n refreshJournal(journal)\n if (!journal.opened && !commitEvent(journal, journal.header) && !journal.opened)\n fail('history is busy; retry with the same run directory')\n}\n\n/** Read and verify a retained result file, or undefined when none was written. */\nfunction readResult<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n): { value: T; receipt: LedgerHash } | undefined {\n const content = journal.storage.read(resultPath(journal, id))\n if (content === undefined) return undefined\n const result = resultSchema.parse(JSON.parse(content))\n if (result.id !== id) return fail('retained result dispatch id mismatch')\n if (hashCanonical(result.value) !== result.receipt) return fail('retained result digest mismatch')\n const value = journal.parse(result.value)\n if (hashCanonical(value) !== result.receipt) return fail('result decoder changed retained output')\n return { value, receipt: result.receipt as LedgerHash }\n}\n\nfunction resultPath<T>(journal: DispatchJournal<T>, id: LedgerHash): string {\n return join(journal.receiptsDir, `${id.slice(7)}.json`)\n}\n\n/** Commit the settlement of a dispatch whose result is already durable. */\nfunction settle<T>(journal: DispatchJournal<T>, id: LedgerHash, receipt: LedgerHash): void {\n while (true) {\n const existing = journal.calls.get(id)\n if (existing?.receipt) {\n if (existing.receipt !== receipt) fail('settled result digest mismatch')\n return\n }\n if (!existing) fail('settlement has no pending dispatch')\n const previousRevision = journal.revision\n if (commitEvent(journal, { kind: 'settled', id, receipt })) return\n if (journal.revision === previousRevision)\n fail('settlement is busy; retained result awaits reconciliation')\n }\n}\n\n/** Replay a settled dispatch from its retained result. */\nfunction loadSettled<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n receipt: string,\n): RetainedDispatchOutcome<T> {\n const result = readResult(journal, id)\n if (!result) return fail('settled result is missing')\n if (result.receipt !== receipt) return fail('settled result digest mismatch')\n return {\n succeeded: true,\n value: result.value,\n dispatchId: id,\n receiptDigest: receipt as LedgerHash,\n replayed: true,\n }\n}\n\n/** Replay a known dispatch, or commit its started intent; returns the outcome when no call should be made. */\nfunction claimDispatch<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n lane: string,\n signal: AbortSignal | undefined,\n): RetainedDispatchOutcome<T> | undefined {\n while (true) {\n const existing = journal.calls.get(id)\n if (existing) {\n if (existing.receipt) return loadSettled(journal, id, existing.receipt)\n const result = readResult(journal, id)\n if (!result) return { succeeded: false, reason: 'outcome_unknown', dispatchId: id }\n settle(journal, id, result.receipt)\n return {\n succeeded: true,\n value: result.value,\n dispatchId: id,\n receiptDigest: result.receipt,\n replayed: true,\n }\n }\n signal?.throwIfAborted()\n if ((journal.counts.get(lane) ?? 0) >= journal.limits.get(lane)!) {\n return { succeeded: false, reason: 'allowance_exhausted', dispatchId: id }\n }\n const previousRevision = journal.revision\n if (commitEvent(journal, { kind: 'started', id, lane })) return undefined\n if (journal.revision === previousRevision)\n return fail('history is busy; retry with the same input')\n }\n}\n\n/** Retain a dispatched value's result file, settle it, and return the decoded outcome. */\nfunction retainResult<T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n value: T,\n): RetainedDispatchOutcome<T> {\n const encoded = canonicalString(value)\n const decoded: unknown = JSON.parse(encoded)\n const retainedValue = journal.parse(decoded)\n if (canonicalString(retainedValue) !== encoded)\n return fail('result decoder is not stable across serialization')\n const receipt = hashCanonical(decoded)\n const retainedResult = canonicalString({\n kind: 'retained-dispatch-result-v1',\n id,\n receipt,\n value: decoded,\n })\n const file = resultPath(journal, id)\n if (\n journal.storage.append(file, retainedResult, 0) === undefined &&\n journal.storage.read(file) !== retainedResult\n )\n fail('cannot retain dispatch result')\n // The receipt is durable before the settlement event can make it reusable.\n settle(journal, id, receipt)\n return {\n succeeded: true,\n value: retainedValue,\n dispatchId: id,\n receiptDigest: receipt,\n replayed: false,\n }\n}\n\n/** Replay, claim an allowance, call the dispatch once, and retain its result. */\nasync function dispatchOnce<Lane extends string, T>(\n journal: DispatchJournal<T>,\n id: LedgerHash,\n request: DispatchRequest<Lane, T>,\n): Promise<RetainedDispatchOutcome<T>> {\n const { lane, dispatch, signal } = request\n if (!journal.limits.has(lane)) return fail('unknown allowance lane')\n // Replay must also validate retained history, not trust a stale in-memory result.\n refreshJournal(journal)\n const claimed = claimDispatch(journal, id, lane, signal)\n if (claimed) return claimed\n // The started event is durably anchored above, so the external effect below is\n // attributable to a committed intent that survives restarts and truncation.\n // A rejection leaves the committed intent in doubt, so return its diagnostic without settling it.\n let value: T\n try {\n signal?.throwIfAborted()\n value = journal.parse(await dispatch())\n } catch (error) {\n return {\n succeeded: false,\n reason: 'outcome_unknown',\n dispatchId: id,\n diagnostic: error instanceof Error ? error.message : String(error),\n }\n }\n return retainResult(journal, id, value)\n}\n","/**\n * Discriminative scenario selection (research claim E2).\n *\n * The OR benchmark is SATURATING: run 7 measured ~75% tied holdout cells — most\n * problems are solved optimally by the baseline AND every candidate, so those\n * paired cells carry zero signal. A random/balanced holdout split spends its\n * budget on scenarios that cannot separate candidates.\n *\n * This picks the holdout by DISCRIMINATION power instead: a scenario every\n * candidate scores identically (variance ~0) carries no signal; one where the\n * scores spread carries the most. We drop fully saturated ties so each paired\n * holdout cell is spent on a scenario that can actually move a verdict.\n */\n\n/** Per-scenario observation: the composite scores each candidate earned on it. */\nexport interface ScenarioSignal {\n scenarioId: string\n /** Per-candidate composite scores observed for this scenario (>=1 values). */\n scores: number[]\n}\n\nexport interface DiscriminationScore {\n scenarioId: string\n /** Higher = separates candidates more (spread of their scores). */\n discrimination: number\n /** Higher = easier / more-saturated (mean of candidate scores). */\n meanScore: number\n variance: number\n /** variance ~0 AND meanScore at/above the ceiling ⇒ a saturated tie, no signal. */\n tied: boolean\n}\n\nconst DEFAULT_SATURATION_CEILING = 0.999\n/** Variance below this is treated as \"every candidate scored the same\". */\nconst VARIANCE_EPSILON = 1e-9\n\ninterface Moments {\n meanScore: number\n variance: number\n}\n\n/** Population mean + variance of the candidate scores. Empty ⇒ zeros (a signal\n * with no observations cannot discriminate). */\nfunction moments(scores: number[]): Moments {\n const n = scores.length\n if (n === 0) return { meanScore: 0, variance: 0 }\n let sum = 0\n for (const s of scores) sum += s\n const meanScore = sum / n\n let sqDev = 0\n for (const s of scores) {\n const d = s - meanScore\n sqDev += d * d\n }\n return { meanScore, variance: sqDev / n }\n}\n\n/** Deterministic ordering: discrimination desc, then meanScore asc (more\n * headroom first), then scenarioId asc. */\nfunction compareDiscrimination(a: DiscriminationScore, b: DiscriminationScore): number {\n if (b.discrimination !== a.discrimination) return b.discrimination - a.discrimination\n if (a.meanScore !== b.meanScore) return a.meanScore - b.meanScore\n return a.scenarioId < b.scenarioId ? -1 : a.scenarioId > b.scenarioId ? 1 : 0\n}\n\n/**\n * Rank scenarios by how well they DISCRIMINATE candidates.\n *\n * `discrimination = variance` (spread of the candidate scores) — kept simple on\n * purpose; the headroom term (`saturationCeiling - meanScore`) only breaks ties\n * so that, among equally spread scenarios, the one with more room to improve\n * ranks first. Returned sorted by the deterministic order above.\n */\nexport function scoreDiscrimination(\n signals: ScenarioSignal[],\n opts?: { saturationCeiling?: number },\n): DiscriminationScore[] {\n const saturationCeiling = opts?.saturationCeiling ?? DEFAULT_SATURATION_CEILING\n const scored = signals.map((signal): DiscriminationScore => {\n const { meanScore, variance } = moments(signal.scores)\n const tied = variance < VARIANCE_EPSILON && meanScore >= saturationCeiling\n return {\n scenarioId: signal.scenarioId,\n discrimination: variance,\n meanScore,\n variance,\n tied,\n }\n })\n return scored.sort(compareDiscrimination)\n}\n","/**\n * VCS-pluggable worktree adapter. One improvement = one worktree, PR-like\n * (multiple commits allowed). A code-tier proposer's `propose()` creates a\n * worktree, an agent commits the change into it, and `finalize()` returns a\n * content-addressed `CodeSurface` the measurement verifies before running.\n * On promotion the worktree becomes the PR branch.\n *\n * The interface is VCS-agnostic so a future `jj` ([jj-vcs](https://github.com/jj-vcs/jj))\n * adapter can slot in without touching proposer code. Only the git adapter\n * ships today. See `docs/design/loop-taxonomy.md`.\n */\n\nimport { execFileSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport {\n closeSync,\n existsSync,\n constants as fsConstants,\n fstatSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readlinkSync,\n readSync,\n realpathSync,\n rmSync,\n} from 'node:fs'\nimport { devNull, tmpdir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { assertCodeSurfaceIdentity, surfaceContentHash } from '../surface-identity'\nimport type { CodeSurface } from '../types'\n\nconst MAX_GIT_OUTPUT_BYTES = 256 * 1024 * 1024\nconst FILE_HASH_CHUNK_BYTES = 1024 * 1024\n\ntype GitOutput = string | Uint8Array\ntype GitEnvironment = Readonly<Record<string, string>>\ntype GitRunner = (args: string[], cwd: string, env?: GitEnvironment) => GitOutput\n\nconst GIT_REPOSITORY_ENV = new Set([\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES',\n 'GIT_COMMON_DIR',\n 'GIT_DIR',\n 'GIT_INDEX_FILE',\n 'GIT_NAMESPACE',\n 'GIT_OBJECT_DIRECTORY',\n 'GIT_PREFIX',\n 'GIT_QUARANTINE_PATH',\n 'GIT_WORK_TREE',\n])\n\nexport interface Worktree {\n /** Absolute path to the checked-out worktree directory. */\n readonly path: string\n /** The branch the worktree is on (becomes the PR branch on promotion). */\n readonly branch: string\n /** The ref the worktree was forked from. */\n readonly baseRef: string\n /** Exact commit `baseRef` resolved to before the worktree was created. */\n readonly baseCommit: string\n /** Exact tree object for `baseCommit`. */\n readonly baseTree: string\n}\n\nexport interface WorktreeAdapter {\n /** Create an isolated worktree on a fresh branch off `baseRef`. */\n create(opts: { baseRef: string; label: string }): Promise<Worktree>\n /** Commit pending changes, freeze the exact Git objects + binary patch, and\n * verify the worktree still matches that identity. */\n finalize(worktree: Worktree, summary: string): Promise<CodeSurface>\n /** Idempotently remove the worktree and branch. Safe to retry after partial cleanup. */\n discard(worktree: Worktree): Promise<void>\n}\n\n/** Typed failure from a `WorktreeAdapter` operation (create/finalize/discard) — wraps the underlying git error as `cause`. */\nexport class WorktreeAdapterError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message)\n this.name = 'WorktreeAdapterError'\n }\n}\n\nexport interface GitWorktreeAdapterOptions {\n /** Repo root the worktrees fork from. */\n repoRoot: string\n /** Directory worktrees are created under. Default: `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Branch-name prefix. Default: `improve`. */\n branchPrefix?: string\n /** Test seam — defaults to a real `git` runner. The return value must contain\n * stdout verbatim, and runners that execute Git must forward the optional\n * environment overrides used to isolate patch generation. */\n git?: GitRunner\n}\n\nfunction defaultGit(args: string[], cwd: string, overrides?: GitEnvironment): Uint8Array {\n try {\n const env = { ...process.env }\n for (const key of Object.keys(env)) {\n if (\n GIT_REPOSITORY_ENV.has(key) ||\n key === 'GIT_CONFIG' ||\n key.startsWith('GIT_CONFIG_') ||\n key.startsWith('GIT_ATTR_') ||\n key === 'GIT_DIFF_OPTS' ||\n key === 'GIT_EXTERNAL_DIFF'\n ) {\n delete env[key]\n }\n }\n Object.assign(env, overrides)\n env.GIT_NO_REPLACE_OBJECTS = '1'\n env.LC_ALL = 'C'\n env.LANG = 'C'\n return execFileSync('git', args, { cwd, env, maxBuffer: MAX_GIT_OUTPUT_BYTES })\n } catch (err) {\n const stderr =\n err && typeof err === 'object' && 'stderr' in err\n ? String((err as { stderr: unknown }).stderr)\n : ''\n throw new WorktreeAdapterError(`git ${args.join(' ')} failed: ${stderr || String(err)}`, err)\n }\n}\n\nfunction gitBytes(git: GitRunner, args: string[], cwd: string, env?: GitEnvironment): Buffer {\n try {\n const output = git(args, cwd, env)\n return typeof output === 'string' ? Buffer.from(output, 'utf8') : Buffer.from(output)\n } catch (err) {\n if (err instanceof WorktreeAdapterError) throw err\n throw new WorktreeAdapterError(`git ${args.join(' ')} failed: ${String(err)}`, err)\n }\n}\n\nfunction gitText(git: GitRunner, args: string[], cwd: string, env?: GitEnvironment): string {\n return gitBytes(git, args, cwd, env).toString('utf8').trim()\n}\n\nfunction hasRegisteredWorktree(git: GitRunner, repoRoot: string, path: string): boolean {\n const expected = Buffer.from(`worktree ${resolve(path)}`, 'utf8')\n const records = gitBytes(git, ['worktree', 'list', '--porcelain', '-z'], repoRoot)\n let start = 0\n while (start < records.length) {\n const end = records.indexOf(0, start)\n if (end < 0) {\n throw new WorktreeAdapterError('Git worktree list output was not NUL-terminated')\n }\n if (records.subarray(start, end).equals(expected)) return true\n start = end + 1\n }\n return false\n}\n\nfunction hasLocalBranch(git: GitRunner, repoRoot: string, branch: string): boolean {\n const ref = `refs/heads/${branch}`\n return gitText(git, ['for-each-ref', '--format=%(refname)', '--', ref], repoRoot)\n .split('\\n')\n .some((candidate) => candidate === ref)\n}\n\nfunction reconcileAbsent(exists: () => boolean, remove: () => void): unknown | undefined {\n try {\n if (!exists()) return undefined\n } catch (err) {\n return err\n }\n\n try {\n remove()\n return undefined\n } catch (removeError) {\n try {\n // Git may complete the mutation before the caller observes a failure, or\n // another cleanup may win the race. The desired end state is what matters.\n if (!exists()) return undefined\n } catch (recheckError) {\n return new AggregateError(\n [removeError, recheckError],\n 'Removal failed and the resulting resource state could not be checked',\n )\n }\n return removeError\n }\n}\n\nfunction sha256(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nconst PATCH_ARGS = [\n // Git binary patches embed a zlib stream. Pin no-compression at command\n // scope so repository/global config and compressor heuristics cannot change\n // the candidate identity for the same base and final tree.\n '-c',\n 'core.compression=0',\n '-c',\n `core.attributesFile=${devNull}`,\n '-c',\n 'core.quotePath=true',\n '-c',\n 'diff.suppressBlankEmpty=false',\n 'diff',\n '--unified=3',\n '--inter-hunk-context=0',\n `-O${devNull}`,\n '--binary',\n '--full-index',\n '--no-color',\n '--no-ext-diff',\n '--no-textconv',\n '--no-renames',\n '--diff-algorithm=myers',\n '--no-indent-heuristic',\n '--src-prefix=a/',\n '--dst-prefix=b/',\n] as const\n\nconst CANONICAL_GIT_ENV: GitEnvironment = {\n GIT_ATTR_GLOBAL: devNull,\n GIT_ATTR_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: devNull,\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_SYSTEM: devNull,\n}\n\n/** Render the transport patch from immutable objects through fresh Git metadata.\n * Source-repository config, info attributes, templates, and caller environment\n * therefore cannot alter bytes for the same two trees. */\nfunction patchBytes(\n git: GitRunner,\n cwd: string,\n baseCommit: string,\n candidateCommit: string,\n): Buffer {\n const scratch = mkdtempSync(join(tmpdir(), 'agent-eval-patch-'))\n const bareRepo = join(scratch, 'repo.git')\n const emptyTemplate = join(scratch, 'empty-template')\n mkdirSync(emptyTemplate)\n try {\n const objectFormat = gitObjectHashAlgorithm(candidateCommit)\n const sourceObjects = realpathSync(gitText(git, ['rev-parse', '--git-path', 'objects'], cwd))\n gitText(\n git,\n [\n 'init',\n '--bare',\n '--quiet',\n ...(objectFormat === 'sha256' ? ['--object-format=sha256'] : []),\n `--template=${emptyTemplate}`,\n bareRepo,\n ],\n scratch,\n CANONICAL_GIT_ENV,\n )\n return gitBytes(\n git,\n [`--git-dir=${bareRepo}`, ...PATCH_ARGS, baseCommit, candidateCommit, '--'],\n scratch,\n {\n ...CANONICAL_GIT_ENV,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: sourceObjects,\n },\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n}\n\nfunction resolveCommit(git: GitRunner, cwd: string, ref: string): string {\n return gitText(git, ['rev-parse', '--verify', `${ref}^{commit}`], cwd)\n}\n\nfunction unresolvedWorktreePath(surface: CodeSurface, worktreeDir?: string): string {\n if (isAbsolute(surface.worktreeRef)) return surface.worktreeRef\n if (worktreeDir) return join(worktreeDir, basename(surface.worktreeRef))\n return surface.worktreeRef\n}\n\ninterface GitTreeEntry {\n mode: string\n objectId: string\n path: string\n}\n\nfunction displayGitPath(path: string): string {\n return JSON.stringify(path)\n}\n\nfunction parseGitTreeEntries(bytes: Uint8Array): GitTreeEntry[] {\n const input = Buffer.from(bytes)\n const entries: GitTreeEntry[] = []\n let start = 0\n while (start < input.length) {\n const end = input.indexOf(0, start)\n if (end < 0) throw new WorktreeAdapterError('Git tree output was not NUL-terminated')\n const record = input.subarray(start, end)\n start = end + 1\n if (record.length === 0) continue\n\n const tab = record.indexOf(0x09)\n if (tab < 0) throw new WorktreeAdapterError('Git tree entry did not contain a path')\n const metadata = record.subarray(0, tab).toString('ascii').split(' ')\n if (metadata.length !== 3) throw new WorktreeAdapterError('Git tree entry was malformed')\n const mode = metadata[0]\n const type = metadata[1]\n const objectId = metadata[2]\n if (!mode || !type || !objectId) {\n throw new WorktreeAdapterError('Git tree entry was malformed')\n }\n const pathBytes = record.subarray(tab + 1)\n const path = pathBytes.toString('utf8')\n if (!Buffer.from(path, 'utf8').equals(pathBytes)) {\n throw new WorktreeAdapterError('CodeSurface paths must be valid UTF-8')\n }\n if (type !== 'blob' && type !== 'commit') {\n throw new WorktreeAdapterError(\n `CodeSurface contains unsupported Git object type ${type} at ${displayGitPath(path)}`,\n )\n }\n entries.push({ mode, objectId, path })\n }\n return entries\n}\n\nfunction parseGitPathList(bytes: Uint8Array): string[] {\n const input = Buffer.from(bytes)\n const paths: string[] = []\n let start = 0\n while (start < input.length) {\n const end = input.indexOf(0, start)\n if (end < 0) throw new WorktreeAdapterError('Git path output was not NUL-terminated')\n const pathBytes = input.subarray(start, end)\n start = end + 1\n if (pathBytes.length === 0) continue\n const path = pathBytes.toString('utf8')\n if (!Buffer.from(path, 'utf8').equals(pathBytes)) {\n throw new WorktreeAdapterError('CodeSurface paths must be valid UTF-8')\n }\n paths.push(path)\n }\n return paths\n}\n\nfunction isWithinRoot(root: string, candidate: string): boolean {\n const rel = relative(root, candidate)\n return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))\n}\n\nfunction assertSafeRelativePath(root: string, path: string): string {\n if (path.length === 0 || isAbsolute(path)) {\n throw new WorktreeAdapterError(`CodeSurface contains unsafe path ${displayGitPath(path)}`)\n }\n const absolutePath = resolve(root, path)\n if (!isWithinRoot(root, absolutePath) || absolutePath === root) {\n throw new WorktreeAdapterError(`CodeSurface path escapes its worktree: ${displayGitPath(path)}`)\n }\n\n const segments = path.split(/[\\\\/]/u)\n let parent = root\n for (const segment of segments.slice(0, -1)) {\n if (segment.length === 0 || segment === '.' || segment === '..') {\n throw new WorktreeAdapterError(`CodeSurface contains unsafe path ${displayGitPath(path)}`)\n }\n parent = join(parent, segment)\n const stat = lstatSync(parent)\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new WorktreeAdapterError(\n `CodeSurface path traverses a non-directory or symbolic link: ${displayGitPath(path)}`,\n )\n }\n }\n return absolutePath\n}\n\nfunction gitObjectHashAlgorithm(objectId: string): 'sha1' | 'sha256' {\n if (/^[a-f0-9]{40}$/.test(objectId)) return 'sha1'\n if (/^[a-f0-9]{64}$/.test(objectId)) return 'sha256'\n throw new WorktreeAdapterError(`Unsupported Git object id: ${objectId}`)\n}\n\nfunction hashGitBlobBytes(bytes: Uint8Array, objectId: string): string {\n const hash = createHash(gitObjectHashAlgorithm(objectId))\n hash.update(`blob ${bytes.byteLength}\\0`)\n hash.update(bytes)\n return hash.digest('hex')\n}\n\nfunction hashGitBlobFile(path: string, objectId: string): { hash: string; executable: boolean } {\n const before = lstatSync(path)\n if (!before.isFile() || before.isSymbolicLink()) {\n throw new WorktreeAdapterError(`CodeSurface expected a regular file at ${displayGitPath(path)}`)\n }\n\n const noFollow = process.platform === 'win32' ? 0 : fsConstants.O_NOFOLLOW\n const fd = openSync(path, fsConstants.O_RDONLY | noFollow)\n try {\n const opened = fstatSync(fd)\n if (\n !opened.isFile() ||\n opened.dev !== before.dev ||\n opened.ino !== before.ino ||\n opened.size !== before.size\n ) {\n throw new WorktreeAdapterError(\n `CodeSurface file changed while it was being verified: ${displayGitPath(path)}`,\n )\n }\n\n const hash = createHash(gitObjectHashAlgorithm(objectId))\n hash.update(`blob ${opened.size}\\0`)\n const chunk = Buffer.allocUnsafe(FILE_HASH_CHUNK_BYTES)\n let total = 0\n while (true) {\n const count = readSync(fd, chunk, 0, chunk.length, null)\n if (count === 0) break\n total += count\n hash.update(chunk.subarray(0, count))\n }\n if (total !== opened.size) {\n throw new WorktreeAdapterError(\n `CodeSurface file changed while it was being verified: ${displayGitPath(path)}`,\n )\n }\n return { hash: hash.digest('hex'), executable: (opened.mode & 0o111) !== 0 }\n } finally {\n closeSync(fd)\n }\n}\n\nfunction assertSymlinkTargetIsBound(\n root: string,\n linkPath: string,\n trackedPaths: ReadonlySet<string>,\n): void {\n const targetBytes = readlinkSync(linkPath, { encoding: 'buffer' })\n const target = targetBytes.toString('utf8')\n if (!Buffer.from(target, 'utf8').equals(targetBytes)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link has an unsafe target at ${displayGitPath(linkPath)}`,\n )\n }\n if (isAbsolute(target)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n const lexicalTarget = resolve(dirname(linkPath), target)\n if (!isWithinRoot(root, lexicalTarget)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n let resolvedTarget: string\n try {\n resolvedTarget = realpathSync(linkPath)\n } catch (err) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link target is missing or cyclic at ${displayGitPath(linkPath)}`,\n err,\n )\n }\n if (!isWithinRoot(root, resolvedTarget)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n\n const targetRelative = relative(root, resolvedTarget).split(sep).join('/')\n const targetIsTracked =\n trackedPaths.has(targetRelative) ||\n [...trackedPaths].some((trackedPath) => trackedPath.startsWith(`${targetRelative}/`))\n if (!targetIsTracked) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link resolves to untracked content at ${displayGitPath(linkPath)}`,\n )\n }\n}\n\nfunction assertRawTreeMatchesWorktree(git: GitRunner, root: string, candidateCommit: string): void {\n const entries = parseGitTreeEntries(\n gitBytes(git, ['ls-tree', '-r', '-z', '--full-tree', candidateCommit], root),\n )\n const trackedPaths = new Set(entries.map((entry) => entry.path))\n\n for (const entry of entries) {\n const absolutePath = assertSafeRelativePath(root, entry.path)\n if (entry.mode === '160000' || entry.mode === '040000') {\n throw new WorktreeAdapterError(\n `CodeSurface contains a Git submodule whose executable bytes are not bound: ${displayGitPath(entry.path)}`,\n )\n }\n if (entry.mode === '120000') {\n const stat = lstatSync(absolutePath)\n if (!stat.isSymbolicLink()) {\n throw new WorktreeAdapterError(\n `CodeSurface expected a symbolic link at ${displayGitPath(entry.path)}`,\n )\n }\n const targetBytes = readlinkSync(absolutePath, { encoding: 'buffer' })\n const actualObjectId = hashGitBlobBytes(targetBytes, entry.objectId)\n if (actualObjectId !== entry.objectId) {\n throw new WorktreeAdapterError(\n `CodeSurface raw symbolic-link bytes differ from the candidate tree at ${displayGitPath(entry.path)}`,\n )\n }\n assertSymlinkTargetIsBound(root, absolutePath, trackedPaths)\n continue\n }\n if (entry.mode !== '100644' && entry.mode !== '100755') {\n throw new WorktreeAdapterError(\n `CodeSurface contains unsupported Git mode ${entry.mode} at ${displayGitPath(entry.path)}`,\n )\n }\n\n const actual = hashGitBlobFile(absolutePath, entry.objectId)\n if (actual.hash !== entry.objectId) {\n throw new WorktreeAdapterError(\n `CodeSurface raw tracked bytes differ from the candidate tree because the worktree changed after finalization at ${displayGitPath(entry.path)}`,\n )\n }\n if (process.platform !== 'win32' && actual.executable !== (entry.mode === '100755')) {\n throw new WorktreeAdapterError(\n `CodeSurface executable mode differs from the candidate tree at ${displayGitPath(entry.path)}`,\n )\n }\n }\n}\n\nexport interface CodeSurfaceVerification {\n /** Verified worktree path. */\n path: string\n /** Git's canonical root for the verified checkout. */\n repoRoot: string\n /** Recomputed full content identity. */\n contentHash: `sha256:${string}`\n /** Exact verified binary-patch bytes. Candidate-bundle builders encode this\n * directly instead of reproducing Git diff options. */\n patchBytes: Uint8Array\n}\n\nfunction verifyCodeSurfaceWithGit(\n surface: CodeSurface,\n path: string,\n git: GitRunner,\n): CodeSurfaceVerification {\n assertCodeSurfaceIdentity(surface)\n if (!existsSync(path)) {\n throw new WorktreeAdapterError(`CodeSurface worktree does not exist: ${path}`)\n }\n const lexicalRoot = resolve(path)\n const canonicalRoot = realpathSync(path)\n if (\n lstatSync(lexicalRoot).isSymbolicLink() ||\n (process.platform !== 'win32' && lexicalRoot !== canonicalRoot)\n ) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree locator must not contain a symbolic link: ${path}`,\n )\n }\n const repoRoot = gitText(git, ['rev-parse', '--show-toplevel'], path)\n const canonicalRepoRoot = realpathSync(repoRoot)\n if (canonicalRepoRoot !== canonicalRoot) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree locator is not the repository root: expected ${repoRoot}, got ${path}`,\n )\n }\n\n const indexFlags = gitText(git, ['ls-files', '-v'], path)\n .split('\\n')\n .filter((line) => line.length > 0 && (line.startsWith('S ') || /^[a-z]/.test(line)))\n if (indexFlags.length > 0) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree uses hidden index entries that cannot be verified: ${path}\\n${indexFlags.join('\\n')}`,\n )\n }\n\n const extraPaths = [\n ...parseGitPathList(gitBytes(git, ['ls-files', '--others', '--exclude-standard', '-z'], path)),\n ...parseGitPathList(\n gitBytes(git, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z'], path),\n ),\n ]\n if (extraPaths.length > 0) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree changed after finalization: ${path}\\n${extraPaths.join('\\n')}`,\n )\n }\n\n const candidateCommit = resolveCommit(git, path, 'HEAD')\n if (candidateCommit !== surface.candidateCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface candidate commit mismatch: expected ${surface.candidateCommit}, got ${candidateCommit}`,\n )\n }\n\n const baseCommit = resolveCommit(git, path, surface.baseCommit)\n if (baseCommit !== surface.baseCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface base commit mismatch: expected ${surface.baseCommit}, got ${baseCommit}`,\n )\n }\n\n const baseTree = gitText(git, ['rev-parse', '--verify', `${surface.baseCommit}^{tree}`], path)\n if (baseTree !== surface.baseTree) {\n throw new WorktreeAdapterError(\n `CodeSurface base tree mismatch: expected ${surface.baseTree}, got ${baseTree}`,\n )\n }\n\n const candidateTree = gitText(\n git,\n ['rev-parse', '--verify', `${surface.candidateCommit}^{tree}`],\n path,\n )\n if (candidateTree !== surface.candidateTree) {\n throw new WorktreeAdapterError(\n `CodeSurface tree mismatch: expected ${surface.candidateTree}, got ${candidateTree}`,\n )\n }\n\n try {\n gitText(\n git,\n [\n 'diff-index',\n '--cached',\n '--quiet',\n '--no-ext-diff',\n '--no-textconv',\n surface.candidateCommit,\n '--',\n ],\n path,\n )\n } catch (err) {\n throw new WorktreeAdapterError(\n `CodeSurface index differs from finalized candidate: ${path}`,\n err,\n )\n }\n\n try {\n assertRawTreeMatchesWorktree(git, canonicalRepoRoot, surface.candidateCommit)\n } catch (err) {\n if (err instanceof WorktreeAdapterError) throw err\n throw new WorktreeAdapterError(`CodeSurface raw tree verification failed: ${path}`, err)\n }\n\n const mergeBase = gitText(git, ['merge-base', surface.baseCommit, surface.candidateCommit], path)\n if (mergeBase !== surface.baseCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface candidate ${surface.candidateCommit} does not descend from base ${surface.baseCommit}`,\n )\n }\n\n const patch = patchBytes(git, path, surface.baseCommit, surface.candidateCommit)\n const actualPatchHash = sha256(patch)\n if (actualPatchHash !== surface.patch.sha256 || patch.byteLength !== surface.patch.byteLength) {\n throw new WorktreeAdapterError(\n `CodeSurface patch mismatch: expected ${surface.patch.sha256}/${surface.patch.byteLength} bytes, got ${actualPatchHash}/${patch.byteLength} bytes`,\n )\n }\n\n return {\n path,\n repoRoot: canonicalRepoRoot,\n contentHash: surfaceContentHash(surface),\n patchBytes: new Uint8Array(patch),\n }\n}\n\n/** Slugify a label into a branch-safe segment. */\nfunction slug(label: string): string {\n return (\n label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 48) || 'candidate'\n )\n}\n\n/**\n * Git-backed `WorktreeAdapter`: creates isolated worktrees on fresh branches, commits agent changes, and discards losers.\n */\nexport function gitWorktreeAdapter(opts: GitWorktreeAdapterOptions): WorktreeAdapter {\n const git = opts.git ?? defaultGit\n const worktreeDir = opts.worktreeDir ?? join(opts.repoRoot, '.worktrees')\n const branchPrefix = opts.branchPrefix ?? 'improve'\n\n return {\n async create({ baseRef, label }) {\n const id = `${slug(label)}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`\n const branch = `${branchPrefix}/${id}`\n const path = join(worktreeDir, id)\n const baseCommit = resolveCommit(git, opts.repoRoot, baseRef)\n const baseTree = gitText(\n git,\n ['rev-parse', '--verify', `${baseCommit}^{tree}`],\n opts.repoRoot,\n )\n gitText(git, ['worktree', 'add', '-b', branch, path, baseCommit], opts.repoRoot)\n return {\n path: realpathSync(resolve(opts.repoRoot, path)),\n branch,\n baseRef,\n baseCommit,\n baseTree,\n }\n },\n\n async finalize(worktree, summary) {\n // Stage + commit any pending changes the agent left in the worktree.\n // A no-op commit is refused by git, so only commit when the tree is dirty.\n const status = gitText(\n git,\n ['status', '--porcelain=v1', '--untracked-files=all'],\n worktree.path,\n )\n if (status.length > 0) {\n gitText(git, ['add', '-A'], worktree.path)\n gitText(git, ['commit', '-m', summary], worktree.path)\n }\n const candidateCommit = resolveCommit(git, worktree.path, 'HEAD')\n const candidateTree = gitText(\n git,\n ['rev-parse', '--verify', `${candidateCommit}^{tree}`],\n worktree.path,\n )\n const patch = patchBytes(git, worktree.path, worktree.baseCommit, candidateCommit)\n const surface: CodeSurface = {\n kind: 'code',\n worktreeRef: worktree.path,\n baseRef: worktree.baseRef,\n baseCommit: worktree.baseCommit,\n baseTree: worktree.baseTree,\n candidateCommit,\n candidateTree,\n patch: {\n format: 'git-diff-binary',\n sha256: sha256(patch),\n byteLength: patch.byteLength,\n },\n summary,\n }\n verifyCodeSurfaceWithGit(surface, worktree.path, git)\n return surface\n },\n\n async discard(worktree) {\n // Reconcile both resources independently so a retry can finish cleanup\n // after either command succeeded alone. Force-remove because the worktree\n // may hold uncommitted experiment state we're discarding.\n const failures = [\n reconcileAbsent(\n () => hasRegisteredWorktree(git, opts.repoRoot, worktree.path),\n () => gitText(git, ['worktree', 'remove', '--force', '--', worktree.path], opts.repoRoot),\n ),\n reconcileAbsent(\n () => hasLocalBranch(git, opts.repoRoot, worktree.branch),\n () => gitText(git, ['branch', '-D', '--', worktree.branch], opts.repoRoot),\n ),\n ].filter((failure) => failure !== undefined)\n\n if (failures.length > 0) {\n const cause =\n failures.length === 1\n ? failures[0]\n : new AggregateError(failures, 'Multiple Git resources could not be removed')\n throw new WorktreeAdapterError(\n `Failed to discard worktree ${worktree.path} and branch ${worktree.branch}`,\n cause,\n )\n }\n },\n }\n}\n\n/** Verify a finalized code surface against its current checkout. This rejects\n * dirty/ignored files, moved refs, missing Git objects, raw byte/mode\n * mismatches, external symlinks, and submodules. */\nexport function verifyCodeSurface(\n surface: CodeSurface,\n worktreeDir?: string,\n): CodeSurfaceVerification {\n const path = unresolvedWorktreePath(surface, worktreeDir)\n return verifyCodeSurfaceWithGit(surface, path, defaultGit)\n}\n\n/** Resolve a code candidate for evaluation only after verifying its immutable\n * identity against the checkout at `worktreeRef`. */\nexport function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string {\n return verifyCodeSurface(surface, worktreeDir).path\n}\n"],"mappings":";;;;;;;;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