@tangle-network/agent-eval 0.173.3 → 0.174.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/{proposal-findings-bko3GGy-.js → abort-signal-CtzAM_sJ.js} +11 -11
  3. package/dist/abort-signal-CtzAM_sJ.js.map +1 -0
  4. package/dist/adapters/http.d.ts +2 -2
  5. package/dist/agent-profile-_xPxqVJt.d.ts +488 -0
  6. package/dist/agent-profile-_xPxqVJt.d.ts.map +1 -0
  7. package/dist/analyst/index.d.ts +7 -9
  8. package/dist/analyst/index.d.ts.map +1 -1
  9. package/dist/analyst/index.js +8 -8
  10. package/dist/{benchmark-C4wk_Sjr.js → benchmark-DQKzykkO.js} +2 -2
  11. package/dist/{benchmark-C4wk_Sjr.js.map → benchmark-DQKzykkO.js.map} +1 -1
  12. package/dist/{benchmark-command-BY9oscke.js → benchmark-command-mZIlR-ra.js} +13 -13
  13. package/dist/{benchmark-command-BY9oscke.js.map → benchmark-command-mZIlR-ra.js.map} +1 -1
  14. package/dist/benchmarks/index.d.ts +3 -4
  15. package/dist/benchmarks/index.d.ts.map +1 -1
  16. package/dist/benchmarks/index.js +3 -3
  17. package/dist/campaign/index.d.ts +5 -9
  18. package/dist/campaign/index.js +7 -7
  19. package/dist/{campaign-B3kPMU8S.js → campaign-BzMSCejE.js} +8 -8
  20. package/dist/{campaign-B3kPMU8S.js.map → campaign-BzMSCejE.js.map} +1 -1
  21. package/dist/cli.js +1 -1
  22. package/dist/{client-DlqdbM7n.d.ts → client-vyYQg3bm.d.ts} +2 -2
  23. package/dist/{client-DlqdbM7n.d.ts.map → client-vyYQg3bm.d.ts.map} +1 -1
  24. package/dist/contract/index.d.ts +9 -10
  25. package/dist/contract/index.js +8 -8
  26. package/dist/{default-registry-B0bKikCb.js → default-registry-CrAp0pYq.js} +4 -4
  27. package/dist/{default-registry-B0bKikCb.js.map → default-registry-CrAp0pYq.js.map} +1 -1
  28. package/dist/{default-registry-BKwc8bN5.d.ts → default-registry-FfNzaUHV.d.ts} +3 -3
  29. package/dist/{default-registry-BKwc8bN5.d.ts.map → default-registry-FfNzaUHV.d.ts.map} +1 -1
  30. package/dist/{define-agent-eval-CY6qdlGV.d.ts → define-agent-eval-V1jQyCDR.d.ts} +102 -11
  31. package/dist/define-agent-eval-V1jQyCDR.d.ts.map +1 -0
  32. package/dist/{define-agent-eval-8h3lXXee.js → define-agent-eval-ox5McL6e.js} +331 -144
  33. package/dist/define-agent-eval-ox5McL6e.js.map +1 -0
  34. package/dist/{dspy-rlm-engine-CF0t2ITD.js → dspy-rlm-engine-Caz2pl4L.js} +3 -3
  35. package/dist/{dspy-rlm-engine-CF0t2ITD.js.map → dspy-rlm-engine-Caz2pl4L.js.map} +1 -1
  36. package/dist/{engine-DhFir3Ys.d.ts → engine-CvW_I72-.d.ts} +2 -2
  37. package/dist/{engine-DhFir3Ys.d.ts.map → engine-CvW_I72-.d.ts.map} +1 -1
  38. package/dist/experiment/index.d.ts +1 -4
  39. package/dist/experiment/index.d.ts.map +1 -1
  40. package/dist/{external-optimizer-process-BwITA9Jp.js → external-optimizer-process-CxnFL1hd.js} +2 -2
  41. package/dist/{external-optimizer-process-BwITA9Jp.js.map → external-optimizer-process-CxnFL1hd.js.map} +1 -1
  42. package/dist/{external-optimizer-subprocess-wBWeoG6A.js → external-optimizer-subprocess-CQi27uEI.js} +2 -2
  43. package/dist/{external-optimizer-subprocess-wBWeoG6A.js.map → external-optimizer-subprocess-CQi27uEI.js.map} +1 -1
  44. package/dist/fuzz.js +1 -1
  45. package/dist/fuzz.js.map +1 -1
  46. package/dist/hosted/index.d.ts +1 -1
  47. package/dist/{index-BQqOjerE.d.ts → index-BTrx5s8m.d.ts} +8 -9
  48. package/dist/index-BTrx5s8m.d.ts.map +1 -0
  49. package/dist/{index-D0Db5X-4.d.ts → index-Bn-nlnSV.d.ts} +4 -4
  50. package/dist/{index-D0Db5X-4.d.ts.map → index-Bn-nlnSV.d.ts.map} +1 -1
  51. package/dist/index-DKXuBPXf.d.ts +3840 -0
  52. package/dist/index-DKXuBPXf.d.ts.map +1 -0
  53. package/dist/index.d.ts +11 -13
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +10 -10
  56. package/dist/{kind-factory-gP6lDySe.js → kind-factory-BLvL-E44.js} +2 -2
  57. package/dist/{kind-factory-gP6lDySe.js.map → kind-factory-BLvL-E44.js.map} +1 -1
  58. package/dist/{llm-judge-BfqMFo4h.js → llm-judge-DmNaBrXB.js} +2541 -2435
  59. package/dist/llm-judge-DmNaBrXB.js.map +1 -0
  60. package/dist/{matrix-DGu8KhSs.d.ts → matrix-CJtXz1ky.d.ts} +2 -2
  61. package/dist/{matrix-DGu8KhSs.d.ts.map → matrix-CJtXz1ky.d.ts.map} +1 -1
  62. package/dist/multishot/golden/index.d.ts +1 -1
  63. package/dist/multishot/index.d.ts +2 -2
  64. package/dist/openapi.json +1 -1
  65. package/dist/{produced-state-D91uDvQw.js → produced-state-B8mw6zj9.js} +2 -2
  66. package/dist/{produced-state-D91uDvQw.js.map → produced-state-B8mw6zj9.js.map} +1 -1
  67. package/dist/rl.d.ts +1 -1
  68. package/dist/rl.d.ts.map +1 -1
  69. package/dist/rl.js.map +1 -1
  70. package/dist/{semantic-concept-judge-Dok7_35a.js → semantic-concept-judge-E3s_fEjB.js} +3 -3
  71. package/dist/{semantic-concept-judge-Dok7_35a.js.map → semantic-concept-judge-E3s_fEjB.js.map} +1 -1
  72. package/dist/{skillopt-optimization-method-DDw3v3gA.js → skillopt-optimization-method-f7399oGb.js} +5 -5
  73. package/dist/{skillopt-optimization-method-DDw3v3gA.js.map → skillopt-optimization-method-f7399oGb.js.map} +1 -1
  74. package/dist/statistical-heldout-Cqb73yE9.d.ts +1127 -0
  75. package/dist/statistical-heldout-Cqb73yE9.d.ts.map +1 -0
  76. package/dist/{store-otlp-Dow0pk_5.js → store-otlp-DV_H2HDu.js} +2 -2
  77. package/dist/{store-otlp-Dow0pk_5.js.map → store-otlp-DV_H2HDu.js.map} +1 -1
  78. package/dist/{store-tool-spans-CCZNsihA.d.ts → store-tool-spans-4o55ABER.d.ts} +3 -3
  79. package/dist/{store-tool-spans-CCZNsihA.d.ts.map → store-tool-spans-4o55ABER.d.ts.map} +1 -1
  80. package/dist/{store-tool-spans-CeNj_m2L.js → store-tool-spans-B9tjys_h.js} +3 -3
  81. package/dist/{store-tool-spans-CeNj_m2L.js.map → store-tool-spans-B9tjys_h.js.map} +1 -1
  82. package/dist/{task-failure-attributes-CZjZeBsY.js → task-failure-attributes-CUy9mkIY.js} +2 -2
  83. package/dist/{task-failure-attributes-CZjZeBsY.js.map → task-failure-attributes-CUy9mkIY.js.map} +1 -1
  84. package/dist/{tool-groups-Cp4Xdzrp.d.ts → tool-groups-DAe1t6zb.d.ts} +2 -2
  85. package/dist/tool-groups-DAe1t6zb.d.ts.map +1 -0
  86. package/dist/trace-repair/index.d.ts +1 -1
  87. package/dist/traces.d.ts +2 -2
  88. package/dist/traces.js +4 -4
  89. package/dist/{types-Ba5UQyVD.d.ts → types-BJz2CPTM.d.ts} +2 -2
  90. package/dist/{types-Ba5UQyVD.d.ts.map → types-BJz2CPTM.d.ts.map} +1 -1
  91. package/dist/{types-CiWITkGo.js → types-DQ0e2E7y.js} +2 -2
  92. package/dist/types-DQ0e2E7y.js.map +1 -0
  93. package/dist/{types-BDV4PiMR.d.ts → types-Dd1ejaeI.d.ts} +2 -2
  94. package/dist/{types-BDV4PiMR.d.ts.map → types-Dd1ejaeI.d.ts.map} +1 -1
  95. package/docs/campaign-proposers.md +42 -0
  96. package/package.json +1 -1
  97. package/dist/agent-profile-B9_GGsG8.d.ts +0 -84
  98. package/dist/agent-profile-B9_GGsG8.d.ts.map +0 -1
  99. package/dist/backend-integrity-CeuTgqsd.d.ts +0 -280
  100. package/dist/backend-integrity-CeuTgqsd.d.ts.map +0 -1
  101. package/dist/benchmark-BjLGkfnN.d.ts +0 -236
  102. package/dist/benchmark-BjLGkfnN.d.ts.map +0 -1
  103. package/dist/define-agent-eval-8h3lXXee.js.map +0 -1
  104. package/dist/define-agent-eval-CY6qdlGV.d.ts.map +0 -1
  105. package/dist/external-optimizer-contracts-CQCpyrIL.d.ts +0 -172
  106. package/dist/external-optimizer-contracts-CQCpyrIL.d.ts.map +0 -1
  107. package/dist/heldout-gate-Df5hsqmm.d.ts +0 -453
  108. package/dist/heldout-gate-Df5hsqmm.d.ts.map +0 -1
  109. package/dist/index-BQqOjerE.d.ts.map +0 -1
  110. package/dist/index-CFDffsKz.d.ts +0 -1135
  111. package/dist/index-CFDffsKz.d.ts.map +0 -1
  112. package/dist/llm-judge-BfqMFo4h.js.map +0 -1
  113. package/dist/power-preflight-Ptse_Kq7.d.ts +0 -117
  114. package/dist/power-preflight-Ptse_Kq7.d.ts.map +0 -1
  115. package/dist/pre-registration-BoI4ucR3.d.ts +0 -592
  116. package/dist/pre-registration-BoI4ucR3.d.ts.map +0 -1
  117. package/dist/promotion-policy-CvMda3kU.d.ts +0 -134
  118. package/dist/promotion-policy-CvMda3kU.d.ts.map +0 -1
  119. package/dist/proposal-findings-bko3GGy-.js.map +0 -1
  120. package/dist/provenance-CRY67X50.d.ts +0 -1995
  121. package/dist/provenance-CRY67X50.d.ts.map +0 -1
  122. package/dist/statistical-heldout-DTyB_6-1.d.ts +0 -295
  123. package/dist/statistical-heldout-DTyB_6-1.d.ts.map +0 -1
  124. package/dist/tool-groups-Cp4Xdzrp.d.ts.map +0 -1
  125. package/dist/types-CiWITkGo.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"campaign-B3kPMU8S.js","names":["validateAndIndex","rowsFor","componentSetKey","rowFor","meanOrNull","canonicalComponents","mean","sha256","fsConstants"],"sources":["../src/campaign/analyst-surface.ts","../src/campaign/cross-surface-context.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/grounded-reflection.ts","../src/campaign/labeled-store/fs-adapter.ts","../src/campaign/neutralize.ts","../src/campaign/parent-selection.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/segmented-profile-matrix.ts","../src/campaign/scenario-selection.ts","../src/campaign/upstream-evaluators.ts","../src/campaign/worktree/index.ts"],"sourcesContent":["import type {\n AnalystBenchmarkCase,\n AnalystBenchmarkLabelState,\n AnalystFindingScore,\n AnalystIssueExpectation,\n} from '../analyst/benchmark'\nimport { scoreAnalystFindings } from '../analyst/benchmark'\nimport type { AnalystFinding, AnalystRunResult, AnalystUsageReceipt } from '../analyst/types'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { DispatchContext, JudgeConfig, MutableSurface, Scenario } from './types'\n\nexport interface TraceAnalystScenario extends Scenario {\n kind: 'trace-analyst'\n traceStore: TraceAnalysisStore\n labelState: AnalystBenchmarkLabelState\n expectedIssues: readonly AnalystIssueExpectation[]\n labeledEvidence?: AnalystBenchmarkCase['labeledEvidence']\n}\n\nexport interface TraceAnalystArtifact {\n findings: readonly AnalystFinding[]\n usage?: AnalystUsageReceipt\n run?: AnalystRunResult\n}\n\nexport interface BuildTraceAnalystSurfaceDispatchOptions {\n analyze(input: {\n instructions: string\n traceStore: TraceAnalysisStore\n runId: string\n signal: AbortSignal\n }): Promise<TraceAnalystArtifact>\n}\n\nexport function buildTraceAnalystSurfaceDispatch(\n options: BuildTraceAnalystSurfaceDispatchOptions,\n): (\n surface: MutableSurface,\n scenario: TraceAnalystScenario,\n context: DispatchContext,\n) => Promise<TraceAnalystArtifact> {\n return async (surface, scenario, context) => {\n if (typeof surface !== 'string') {\n throw new TypeError(\n `buildTraceAnalystSurfaceDispatch requires a string prompt, received ${surface.kind}`,\n )\n }\n return options.analyze({\n instructions: surface,\n traceStore: scenario.traceStore,\n runId: `${context.cellId}:${scenario.id}`,\n signal: context.signal,\n })\n }\n}\n\nexport function traceAnalystQualityJudge(): JudgeConfig<\n TraceAnalystArtifact,\n TraceAnalystScenario\n> {\n return {\n name: 'trace-analyst-quality',\n judgeVersion: 'agent-eval:trace-analyst-quality:v3',\n dimensions: [\n { key: 'issue_recall', description: 'share of labeled issues found' },\n { key: 'finding_precision', description: 'share of findings tied to a labeled issue' },\n { key: 'f1', description: 'harmonic mean of issue recall and finding precision' },\n { key: 'critical_step_accuracy', description: 'share of labeled causal steps cited' },\n { key: 'citation_coverage', description: 'share of findings with evidence citations' },\n {\n key: 'citation_label_agreement',\n description: 'share of citations matching a labeled case location',\n },\n { key: 'clean', description: '1 when a clean case produces no findings' },\n ],\n appliesTo: (scenario) =>\n scenario.kind === 'trace-analyst' && scenario.labelState !== 'unlabeled',\n score({ artifact, scenario }) {\n assertScorableScenario(scenario)\n const score = scoreAnalystFindings(\n {\n id: scenario.id,\n expectedIssues: scenario.expectedIssues,\n labeledEvidence: scenario.labeledEvidence,\n },\n artifact.findings,\n )\n return traceAnalystJudgeScore(score)\n },\n }\n}\n\nfunction assertScorableScenario(scenario: TraceAnalystScenario): void {\n if (scenario.labelState === 'unlabeled') {\n throw new TypeError(`trace analyst scenario '${scenario.id}' has no quality labels`)\n }\n if (scenario.labelState === 'positive' && scenario.expectedIssues.length === 0) {\n throw new TypeError(`positive trace analyst scenario '${scenario.id}' requires expected issues`)\n }\n if (scenario.labelState === 'trusted-negative' && scenario.expectedIssues.length > 0) {\n throw new TypeError(\n `trusted-negative trace analyst scenario '${scenario.id}' cannot contain expected issues`,\n )\n }\n}\n\nfunction traceAnalystJudgeScore(score: AnalystFindingScore) {\n const dimensions: Record<string, number> = {\n issue_recall: score.issueRecall,\n finding_precision: score.findingPrecision,\n f1: score.f1,\n clean: score.predictionOnLabelEmptyCase ? 0 : 1,\n }\n if (score.criticalStepAccuracy !== null) {\n dimensions.critical_step_accuracy = score.criticalStepAccuracy\n }\n if (score.citationCoverage !== null) dimensions.citation_coverage = score.citationCoverage\n if (score.citationLabelAgreement !== null) {\n dimensions.citation_label_agreement = score.citationLabelAgreement\n }\n const notes = [\n `${score.matchedIssueIds.length}/${score.expectedIssueCount} issues found`,\n `${score.supportedFindingIndexes.length}/${score.supportedFindingIndexes.length + score.unsupportedFindingIndexes.length} findings supported`,\n `${score.unlabeledEvidence.length} citations outside labeled locations`,\n ].join('; ')\n const composite =\n score.criticalStepAccuracy === null ? score.f1 : (score.f1 + score.criticalStepAccuracy) / 2\n return { dimensions, composite, notes }\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","/**\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 {\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 type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceAdditionDecision,\n CrossSurfaceAdditionRejectionReason,\n CrossSurfaceCandidate,\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateEvidence,\n CrossSurfaceCandidateOutcome,\n CrossSurfaceCandidateSummary,\n CrossSurfaceCompositionStep,\n CrossSurfaceDistribution,\n CrossSurfaceEligibility,\n CrossSurfaceEvidenceBreakdown,\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 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 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\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 appendEvidenceEligibilityReasons(\n reasons: CrossSurfaceIneligibilityReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfaceIneligibilityReason,\n unobservedReason: CrossSurfaceIneligibilityReason,\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\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\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 appendBundleEvidenceReasons(\n reasons: CrossSurfaceAdditionRejectionReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfaceAdditionRejectionReason,\n unobservedReason: CrossSurfaceAdditionRejectionReason,\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\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 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 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 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 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\nfunction meanOrNull(values: number[]): number | null {\n return values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\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 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/** Mean of a numeric array; 0 for an empty array (callers guard n separately). */\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\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: mean(deltas), 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 * Evidence grounding for reflective optimizers (GEPA-style revise loops).\n *\n * Two failure modes recur when an LLM revises an artifact from raw rollout\n * traces (first measured in agent-lab R358, where naive reflection REGRESSED\n * the score 0.375 -> 0.125 before these helpers fixed it):\n *\n * 1. The environment often hides WHY a rollout failed - a tool call can\n * succeed while an invisible downstream check fails - so the reviser\n * cannot see the cause in the transcript. The only reliable signal is the\n * field-level difference between what passing and failing rollouts did.\n * `rolloutArgumentDiff` computes that difference deterministically so the\n * reviser is handed the diff instead of being trusted to derive it.\n *\n * 2. Revisers invent plausible-but-wrong literal values (\"use 'new'\",\n * \"use 'sent'\") that no passing rollout ever used, turning every rollout\n * into a failure. `classifyUngroundedLiterals` mechanically detects them,\n * separating HARMFUL literals (ones failing rollouts actually used -\n * proven damage) from benign illustrations (e.g. a name example like\n * 'Doe'), so callers can hard-reject the former and merely log the latter.\n * Rejecting every ungrounded quoted word is too blunt: it killed a run\n * over a surname illustration before the severity split existed.\n *\n * Pure data in, data out: no LLM calls, no filesystem, no domain knowledge.\n */\n\n/** One tool/action call observed in a rollout: a name plus its arguments. */\nexport interface RolloutCall {\n readonly name: string\n readonly args: Readonly<Record<string, unknown>>\n}\n\n/** A scored rollout: its calls plus the scalar outcome used to split pass/fail. */\nexport interface ScoredRollout {\n /** Caller-meaningful identifier (task id, cell id) used only for reporting. */\n readonly id: string\n /** Scalar outcome in [0, 1]; `passThreshold` splits passing from failing. */\n readonly score: number\n readonly calls: readonly RolloutCall[]\n}\n\nexport interface RolloutArgumentDiffOptions {\n /** Rollouts with `score >= passThreshold` count as passing. Default 1. */\n readonly passThreshold?: number\n /** Max distinct values listed per field per side in the rendered text. Default 4. */\n readonly maxValuesPerField?: number\n}\n\nexport interface RolloutArgumentDiff {\n /** Human/LLM-readable per-field diff, one line per field. */\n readonly text: string\n /** Lowercased stringified argument values seen in passing rollouts. */\n readonly passingValues: ReadonlySet<string>\n /** Lowercased stringified argument values seen in failing rollouts. */\n readonly failingValues: ReadonlySet<string>\n}\n\n/**\n * Deterministic per-field diff of call arguments between passing and failing\n * rollouts. A field set by failing rollouts but left unset by passing ones is\n * the classic poison-input signature; a field whose values differ across the\n * split points at the correct value. Feed `text` to the reviser verbatim.\n */\nexport function rolloutArgumentDiff(\n rollouts: readonly ScoredRollout[],\n opts: RolloutArgumentDiffOptions = {},\n): RolloutArgumentDiff {\n const passThreshold = opts.passThreshold ?? 1\n const maxValues = opts.maxValuesPerField ?? 4\n const collect = (pass: boolean): Map<string, Set<string>> => {\n const byField = new Map<string, Set<string>>()\n for (const r of rollouts) {\n if (pass !== r.score >= passThreshold) continue\n for (const c of r.calls) {\n for (const [k, v] of Object.entries(c.args)) {\n const set = byField.get(k) ?? new Set<string>()\n set.add(String(v))\n byField.set(k, set)\n }\n }\n }\n return byField\n }\n const passing = collect(true)\n const failing = collect(false)\n const lines: string[] = []\n for (const field of new Set([...passing.keys(), ...failing.keys()])) {\n const pv = [...(passing.get(field) ?? [])].slice(0, maxValues)\n const fv = [...(failing.get(field) ?? [])].slice(0, maxValues)\n const render = (vals: string[]) => (vals.length ? JSON.stringify(vals) : 'NOT SET (omitted)')\n lines.push(` ${field}: passing runs -> ${render(pv)} | failing runs -> ${render(fv)}`)\n }\n const lower = (m: Map<string, Set<string>>): Set<string> => {\n const out = new Set<string>()\n for (const vals of m.values()) for (const v of vals) out.add(v.toLowerCase())\n return out\n }\n return {\n text: lines.join('\\n') || ' (no calls observed)',\n passingValues: lower(passing),\n failingValues: lower(failing),\n }\n}\n\nexport interface UngroundedLiteralReport {\n /** Quoted single-word literals in the text that no passing rollout used. */\n readonly ungrounded: readonly string[]\n /** The subset failing rollouts actually used - prescribing these is proven harmful. */\n readonly harmful: readonly string[]\n}\n\n/**\n * Scan revised artifact text for single-quoted single-word literals (the\n * \"use exactly 'new'\" pattern) that appear in no passing rollout's argument\n * values. Multi-word quotes pass (they are prose, not prescriptions).\n * Callers should reject on `harmful` (with a bounded retry) and at most log\n * `ungrounded` - see the module header for why the severities differ.\n */\nexport function classifyUngroundedLiterals(\n text: string,\n diff: Pick<RolloutArgumentDiff, 'passingValues' | 'failingValues'>,\n): UngroundedLiteralReport {\n const ungrounded = new Set<string>()\n for (const m of text.matchAll(/'([a-z][a-z_-]{1,19})'/gi)) {\n const w = (m[1] as string).toLowerCase()\n if (!diff.passingValues.has(w)) ungrounded.add(w)\n }\n const all = [...ungrounded]\n return {\n ungrounded: all,\n harmful: all.filter((w) => diff.failingValues.has(w)),\n }\n}\n","/**\n * Filesystem `LabeledScenarioStore` adapter. The default capture sink for\n * traces + eval artifacts. Production deployments typically swap for a\n * Turso/SQLite adapter (same interface).\n *\n * Records land as one JSONL file per source under `<root>/<source>.jsonl`.\n * Each line is a `LabeledScenarioRecord`. Append-only — no in-place edits.\n *\n * Safety properties enforced at write-time:\n *\n * - **Provenance required**: writes without `source`, `sourceVersionHash`,\n * `capturedAt`, `redactionStatus` are rejected. Closes the alignment\n * reviewer's data-poisoning gap.\n * - **Per-source rate limits**: optional `rateLimitBucket` + `maxWritesPerMinute`\n * stops a single tenant/source from flooding the store.\n *\n * Safety properties enforced at sample-time:\n *\n * - **Required split + capturedBefore**: substrate refuses to sample without\n * an explicit `split` ('train' | 'test') AND a temporal cutoff. Eliminates\n * accidental train/test contamination.\n * - **Default training-source filter**: when the store is sampled with\n * `split: 'train'`, production-trace records are EXCLUDED unless the\n * caller passes `filter.source: 'production-trace'` explicitly. Closes\n * the contamination-by-default gap flagged by the senior eval engineer.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { compareCodeUnits } from '../../ledger-core/canonical'\nimport type {\n LabeledScenarioRecord,\n LabeledScenarioSampleArgs,\n LabeledScenarioSource,\n LabeledScenarioStore,\n LabeledScenarioWrite,\n LabelTrust,\n} from '../types'\nimport { labelTrustRank } from '../types'\n\nexport interface FsLabeledScenarioStoreOptions {\n /** Root directory for JSONL files. Created if missing. */\n root: string\n /** Per-source rate limit. When set, writes exceeding the cap are rejected\n * with a typed error. Default: no limit. */\n maxWritesPerMinutePerBucket?: number\n /** Test seam — override `Date.now()` for deterministic tests. */\n now?: () => number\n}\n\n/** Typed rejection from a labeled-scenario store (bad provenance, rate limit, invalid sample args) — carries a stable string `code`. */\nexport class LabeledScenarioStoreError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message)\n this.name = 'LabeledScenarioStoreError'\n }\n}\n\ninterface RateLimitState {\n bucket: string\n windowStartMs: number\n count: number\n}\n\n/**\n * Filesystem `LabeledScenarioStore`: appends one JSONL file per source with provenance and\n * rate-limit guards. For tests, local dev, and small workloads — high-throughput lands in Turso.\n */\nexport class FsLabeledScenarioStore implements LabeledScenarioStore {\n private readonly now: () => number\n private readonly rateLimits = new Map<string, RateLimitState>()\n\n constructor(private readonly options: FsLabeledScenarioStoreOptions) {\n if (!existsSync(options.root)) mkdirSync(options.root, { recursive: true })\n this.now = options.now ?? Date.now\n }\n\n async observe(write: LabeledScenarioWrite): Promise<void> {\n this.assertProvenance(write)\n this.assertRateLimit(write)\n const record = this.toRecord(write)\n const path = this.pathForSource(write.source)\n const line = `${JSON.stringify(record)}\\n`\n // Append atomically. For high-throughput a writev-friendly buffered\n // implementation lands in the Turso adapter; FS adapter is for tests +\n // local dev + small workloads.\n appendLine(path, line)\n }\n\n async sample(args: LabeledScenarioSampleArgs): Promise<LabeledScenarioRecord[]> {\n if (!args.split) {\n throw new LabeledScenarioStoreError(\n 'split_required',\n 'sample() requires an explicit `split` (train | test) — substrate refuses ambiguous reads',\n )\n }\n if (!args.capturedBefore) {\n throw new LabeledScenarioStoreError(\n 'capturedBefore_required',\n 'sample() requires an explicit `capturedBefore` timestamp for temporal-split discipline',\n )\n }\n\n const all: LabeledScenarioRecord[] = []\n for (const source of ALL_SOURCES) {\n // Default training-source filter: when sampling train, EXCLUDE\n // production-trace records unless the caller asks for them.\n if (args.split === 'train' && source === 'production-trace') {\n const explicit = sourceFilterContains(args.filter?.source, 'production-trace')\n if (!explicit) continue\n }\n const path = this.pathForSource(source)\n if (!existsSync(path)) continue\n const lines = readFileSync(path, 'utf8').split('\\n').filter(Boolean)\n for (const line of lines) {\n let record: LabeledScenarioRecord\n try {\n record = JSON.parse(line) as LabeledScenarioRecord\n } catch {\n continue\n }\n if (!matchesFilter(record, args, source)) continue\n all.push(record)\n }\n }\n\n // Deterministic order: by capturedAt ascending, then recordHash.\n all.sort((a, b) => {\n if (a.capturedAt !== b.capturedAt) return compareCodeUnits(a.capturedAt, b.capturedAt)\n return compareCodeUnits(a.recordHash, b.recordHash)\n })\n\n return all.slice(0, args.count)\n }\n\n async size(): Promise<{\n train: number\n test: number\n bySource: Record<string, number>\n byTrust: Record<LabelTrust, number>\n }> {\n const bySource: Record<string, number> = {}\n const byTrust: Record<LabelTrust, number> = {\n unverified: 0,\n 'verified-signal': 0,\n 'human-rated': 0,\n }\n let total = 0\n for (const source of ALL_SOURCES) {\n const path = this.pathForSource(source)\n if (!existsSync(path)) {\n bySource[source] = 0\n continue\n }\n const lines = readFileSync(path, 'utf8').split('\\n').filter(Boolean)\n bySource[source] = lines.length\n total += lines.length\n for (const line of lines) {\n let trust: LabelTrust = 'unverified'\n try {\n trust = (JSON.parse(line) as LabeledScenarioRecord).labelTrust ?? 'unverified'\n } catch {\n // A malformed line counts as unverified — never silently gold.\n }\n byTrust[trust] += 1\n }\n }\n // FS adapter doesn't track split assignments per-record (split is\n // computed at sample-time based on `capturedBefore`). For size(), we\n // report `train`+`test` as the same total — split is a sampling concept.\n return { train: total, test: total, bySource, byTrust }\n }\n\n private assertProvenance(write: LabeledScenarioWrite): void {\n if (!write.source) {\n throw new LabeledScenarioStoreError(\n 'missing_source',\n 'LabeledScenarioWrite requires `source`',\n )\n }\n if (!write.sourceVersionHash || write.sourceVersionHash.length === 0) {\n throw new LabeledScenarioStoreError(\n 'missing_source_version',\n 'LabeledScenarioWrite requires `sourceVersionHash` (git sha or substrate version)',\n )\n }\n if (!write.capturedAt) {\n throw new LabeledScenarioStoreError(\n 'missing_captured_at',\n 'LabeledScenarioWrite requires `capturedAt` ISO timestamp',\n )\n }\n if (!write.redactionStatus) {\n throw new LabeledScenarioStoreError(\n 'missing_redaction_status',\n 'LabeledScenarioWrite requires explicit `redactionStatus` — raw / redacted-pii / redacted-secrets / fully-redacted',\n )\n }\n if (!ALL_SOURCES.includes(write.source)) {\n throw new LabeledScenarioStoreError(\n 'unknown_source',\n `LabeledScenarioWrite.source must be one of: ${ALL_SOURCES.join(', ')}`,\n )\n }\n }\n\n private assertRateLimit(write: LabeledScenarioWrite): void {\n const cap = this.options.maxWritesPerMinutePerBucket\n if (!cap || !write.rateLimitBucket) return\n const now = this.now()\n const windowMs = 60_000\n let state = this.rateLimits.get(write.rateLimitBucket)\n if (!state || now - state.windowStartMs >= windowMs) {\n state = { bucket: write.rateLimitBucket, windowStartMs: now, count: 0 }\n this.rateLimits.set(write.rateLimitBucket, state)\n }\n if (state.count >= cap) {\n throw new LabeledScenarioStoreError(\n 'rate_limit_exceeded',\n `LabeledScenarioStore: bucket ${write.rateLimitBucket} exceeded ${cap} writes/min`,\n )\n }\n state.count += 1\n }\n\n private toRecord(write: LabeledScenarioWrite): LabeledScenarioRecord {\n const recordHash = sha256(\n JSON.stringify({\n id: write.scenario.id,\n src: write.source,\n at: write.capturedAt,\n ver: write.sourceVersionHash,\n }),\n )\n // FS adapter assigns split at sample-time, but we cache a hint here\n // based on capturedAt vs the world's \"now\" — sampler overrides this.\n return {\n ...write,\n recordHash,\n split: 'train',\n }\n }\n\n private pathForSource(source: string): string {\n return join(this.options.root, `${source}.jsonl`)\n }\n}\n\nconst ALL_SOURCES: LabeledScenarioWrite['source'][] = [\n 'production-trace',\n 'eval-run',\n 'manual',\n 'red-team',\n 'synthetic',\n]\n\nfunction sourceFilterContains(\n filter: LabeledScenarioSource | LabeledScenarioSource[] | undefined,\n needle: LabeledScenarioSource,\n): boolean {\n if (!filter) return false\n if (Array.isArray(filter)) return filter.includes(needle)\n return filter === needle\n}\n\nfunction matchesFilter(\n record: LabeledScenarioRecord,\n args: LabeledScenarioSampleArgs,\n source: string,\n): boolean {\n // Temporal cutoff — train must be capturedAt < capturedBefore.\n if (args.split === 'train' && record.capturedAt >= args.capturedBefore) return false\n if (args.split === 'test' && record.capturedAt < args.capturedBefore) return false\n\n const f = args.filter\n if (!f) return true\n if (f.kind && record.scenario.kind !== f.kind) return false\n if (f.source) {\n const sources = Array.isArray(f.source) ? f.source : [f.source]\n if (!sources.includes(source as never)) return false\n }\n if (f.minComposite !== undefined || f.maxComposite !== undefined) {\n const composites = Object.values(record.judgeScores).map((s) => s.composite)\n const max = composites.length === 0 ? 0 : Math.max(...composites)\n if (f.minComposite !== undefined && max < f.minComposite) return false\n if (f.maxComposite !== undefined && max > f.maxComposite) return false\n }\n if (f.minTrust !== undefined && labelTrustRank(record.labelTrust) < labelTrustRank(f.minTrust)) {\n return false\n }\n return true\n}\n\nfunction sha256(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 16)\n}\n\nfunction appendLine(path: string, line: string): void {\n if (existsSync(path)) {\n const existing = readFileSync(path, 'utf8')\n writeFileSync(path, existing + line)\n } else {\n writeFileSync(path, line)\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","/**\n * Parent selection for `runOptimization`.\n *\n * Each generation mutates one parent surface. The default parent is the\n * global incumbent, so the search is a hill-climb and the lineage recorded in\n * `GenerationCandidate.parentSurfaceHash` is a chain. A `ParentSelector` draws\n * the parent from the Pareto frontier instead, so the recorded lineage becomes\n * a tree. Promotion is unchanged: a candidate still has to beat the incumbent.\n */\n\nimport { type Objective, paretoFrontierWithCrowding } from '../pareto'\nimport { mulberry32 } from '../statistics/random'\nimport type { GenerationRecord, ParetoParent, ScoredSurfaceOutcome } from './types'\n\n/** Search state supplied to one parent-selection call. */\nexport interface ParentSelectionContext {\n /** Non-dominated scored surfaces across the whole run so far, including the\n * baseline (`generation: -1`). Never empty. */\n readonly frontier: ReadonlyArray<ParetoParent>\n /** Measured result of the global incumbent, the promotion bar. Under the\n * default `selectionRankKey` the incumbent is always on `frontier`. */\n readonly incumbent: ScoredSurfaceOutcome\n /** Every completed generation so far. */\n readonly history: ReadonlyArray<GenerationRecord>\n /** Index of the generation about to propose. */\n readonly generation: number\n}\n\n/** Chooses the surface the next generation mutates. Returns one frontier\n * parent; `runOptimization` refuses a parent it has not measured to\n * completion or whose surface does not match its `surfaceHash`. */\nexport type ParentSelector = (ctx: ParentSelectionContext) => ParetoParent\n\nexport interface CrowdedFrontierParentOptions {\n /** Integer seed for the per-generation draw. The same seed, frontier, and\n * generation index select the same parent. */\n seed: number\n}\n\n/**\n * NSGA-II crowded tournament selection over the frontier. Each generation\n * draws two distinct frontier members with a PRNG seeded from `seed` and the\n * generation index, and keeps the one with the larger crowding distance (more\n * isolated on the frontier). Boundary parents carry infinite distance, so a\n * boundary parent always beats an interior one. A tie on distance falls back\n * to the higher mean composite, then to the smaller surface hash. A frontier\n * of one member returns that member.\n */\nexport function crowdedFrontierParent(options: CrowdedFrontierParentOptions): ParentSelector {\n const { seed } = options\n if (!Number.isInteger(seed)) {\n throw new TypeError(`crowdedFrontierParent: seed must be an integer, got ${String(seed)}`)\n }\n return ({ frontier, generation }) => {\n if (frontier.length === 0) {\n throw new Error('crowdedFrontierParent: frontier is empty')\n }\n if (frontier.length === 1) return frontier[0]!\n const distances = new Map<ParetoParent, number>()\n for (const { candidate, distance } of paretoFrontierWithCrowding(\n [...frontier],\n frontierObjectives(frontier),\n )) {\n distances.set(candidate, distance)\n }\n const rng = mulberry32(tournamentSeed(seed, generation))\n const first = Math.floor(rng() * frontier.length)\n const offset = Math.floor(rng() * (frontier.length - 1))\n const second = offset >= first ? offset + 1 : offset\n const a = frontier[first]!\n const b = frontier[second]!\n return compareCrowded(a, distanceOf(distances, a), b, distanceOf(distances, b)) <= 0 ? a : b\n }\n}\n\nfunction distanceOf(distances: ReadonlyMap<ParetoParent, number>, parent: ParetoParent): number {\n const distance = distances.get(parent)\n if (distance === undefined) {\n throw new Error(\n `crowdedFrontierParent: frontier member \"${parent.surfaceHash}\" is dominated or has a non-finite objective`,\n )\n }\n return distance\n}\n\n/** Negative when `a` wins the tournament, positive when `b` wins. */\nfunction compareCrowded(a: ParetoParent, da: number, b: ParetoParent, db: number): number {\n if (da !== db) return da > db ? -1 : 1\n if (a.composite !== b.composite) return a.composite > b.composite ? -1 : 1\n if (a.surfaceHash === b.surfaceHash) return 0\n return a.surfaceHash < b.surfaceHash ? -1 : 1\n}\n\n/** One `maximize` objective per scenario id present on the frontier. */\nfunction frontierObjectives(frontier: ReadonlyArray<ParetoParent>): Objective<ParetoParent>[] {\n const ids = new Set<string>()\n for (const parent of frontier) for (const id of Object.keys(parent.objectives)) ids.add(id)\n if (ids.size === 0) {\n throw new Error('crowdedFrontierParent: frontier parents carry no objectives')\n }\n return [...ids].sort().map((id) => ({\n name: id,\n direction: 'maximize',\n value: (parent) => {\n const value = parent.objectives[id]\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(\n `crowdedFrontierParent: frontier member \"${parent.surfaceHash}\" has no finite objective \"${id}\"`,\n )\n }\n return value\n },\n }))\n}\n\nfunction tournamentSeed(seed: number, generation: number): number {\n return (seed ^ Math.imul(generation + 1, 0x9e3779b1)) | 0\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 { extractProducedState, type RuntimeEventLike } from '../../produced-state'\nimport type { DispatchContext, Scenario } from '../types'\nimport type { ProfileDispatchFn } from './run-profile-matrix'\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/**\n * Adapt a `PlaybackDriver` into a `runProfileMatrix` dispatch. The artifact the\n * matrix scores is the `ProducedState` extracted from the driver's event\n * stream — grade it with `scoreUserStory` (or a judge wrapping it).\n */\nexport function makePlaybackDispatch<TStory extends UserStory>(\n driver: PlaybackDriver<TStory>,\n): ProfileDispatchFn<TStory, ProducedState> {\n return async (profile, scenario, ctx) => {\n const events = await driver.run(scenario, { ...ctx, profile })\n return extractProducedState(events)\n }\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 * `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 * A dispatch that reports zero tokens is indistinguishable from a stub and the\n * integrity guard treats it as one.\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 type RunRecord,\n type RunSplitTag,\n runTaskScore,\n UNKNOWN_MODEL,\n validateRunRecord,\n} from '../../run-record'\nimport { computeManifestHash } from '../campaign-manifest'\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\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\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 receiptModels(cell: CampaignCellResult<unknown>): string[] {\n const reported = cell.resolvedModels ?? (cell.resolvedModel ? [cell.resolvedModel] : [])\n return [...new Set(reported.map((model) => model.trim()).filter(Boolean))]\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 = receiptModels(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 = resolved\n .replace(/@[^/]+$/u, '')\n .replace(/-\\d{8}$/u, '')\n .replace(/-\\d{4}-\\d{2}-\\d{2}$/u, '')\n .replace(/-\\d{4}$/u, '')\n .replace(/:date-[^/]+$/u, '')\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 durableCell = durableCellForRecord(cell)\n const record = campaignCellToRunRecord(durableCell, {\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 * Keep failed rows truthful at the RunRecord boundary.\n *\n * A cell with no settled call currently has a zero subtotal and an observed\n * zero from the ledger. That is not measured provider usage or cost, so mark\n * usage incomplete and cost uncaptured while retaining the known subtotal.\n */\nfunction durableCellForRecord<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n): CampaignCellResult<TArtifact> {\n if (cell.error === undefined) return cell\n\n const hasSettledAgentCalls = receiptModels(cell).some((model) => model !== UNKNOWN_MODEL)\n return {\n ...cell,\n tokenUsage:\n cell.tokenUsage.tokensKnown === false || hasSettledAgentCalls\n ? cell.tokenUsage\n : { ...cell.tokenUsage, tokensKnown: false },\n costProvenance:\n !hasSettledAgentCalls && cell.costProvenance.kind === 'observed' && cell.costUsd === 0\n ? { kind: 'uncaptured', usd: null }\n : cell.costProvenance,\n }\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 meanOrNull(values: number[]): number | null {\n return values.length === 0 ? null : mean(values)\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 * 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/**\n * Select the top-`k` most discriminative scenario ids for a holdout, EXCLUDING\n * fully saturated ties when enough non-tied scenarios exist (a tie in the\n * holdout wastes a paired cell).\n *\n * Prefers non-tied scenarios; if fewer than `k` non-tied exist, fills with the\n * least-saturated tied ones (tied scenarios are already ordered least-saturated\n * first by `meanScore` asc). Deterministic. Throws if `k < 1`. If\n * `signals.length <= k`, returns all ids in discrimination order.\n */\nexport function selectDiscriminative(\n signals: ScenarioSignal[],\n k: number,\n opts?: { saturationCeiling?: number },\n): string[] {\n if (k < 1) throw new Error(`selectDiscriminative: k must be >= 1 (got ${k})`)\n const ranked = scoreDiscrimination(signals, opts)\n if (ranked.length <= k) return ranked.map((s) => s.scenarioId)\n const nonTied = ranked.filter((s) => !s.tied)\n if (nonTied.length >= k) return nonTied.slice(0, k).map((s) => s.scenarioId)\n const tied = ranked.filter((s) => s.tied)\n const fill = tied.slice(0, k - nonTied.length)\n return [...nonTied, ...fill].map((s) => s.scenarioId)\n}\n","import {\n CostAccountingIncompleteError,\n type CostLedgerHandle,\n type RunPaidCallInput,\n} from '../cost-ledger'\nimport type { JudgeConfig, JudgeScore, Scenario } from './types'\n\nexport interface PhoenixEvaluationResultLike {\n score?: number\n label?: string\n explanation?: string\n}\n\nexport interface PhoenixEvaluatorLike<TRecord extends Record<string, unknown>> {\n name: string\n kind: 'LLM' | 'CODE'\n optimizationDirection?: 'MAXIMIZE' | 'MINIMIZE' | 'NEUTRAL'\n evaluate(\n record: TRecord,\n context: UpstreamEvaluationContext,\n ): Promise<PhoenixEvaluationResultLike>\n}\n\nexport interface AutoevalsScoreLike {\n name: string\n score: number | null\n metadata?: Record<string, unknown>\n}\n\nexport type AutoevalsScorerLike<TInput extends Record<string, unknown>> = (\n input: TInput,\n context: UpstreamEvaluationContext,\n) => AutoevalsScoreLike | Promise<AutoevalsScoreLike>\n\nexport interface UpstreamEvaluationContext {\n readonly signal: AbortSignal\n readonly callId?: string\n}\n\ntype PaidEvaluationOptions<TResult> = Pick<\n RunPaidCallInput<TResult>,\n 'maximumCharge' | 'receipt' | 'receiptFromError'\n> & {\n model: string\n}\n\ninterface UpstreamJudgeOptions<TScenario extends Scenario> {\n name?: string\n dimension?: string\n judgeVersion?: string\n appliesTo?: (scenario: TScenario) => boolean\n /** Convert the upstream score when its native scale is not higher-is-better. */\n toComposite?: (score: number) => number\n}\n\nexport function phoenixEvaluatorJudge<\n TRecord extends Record<string, unknown>,\n TArtifact,\n TScenario extends Scenario = Scenario,\n>(\n evaluator: PhoenixEvaluatorLike<TRecord>,\n options: UpstreamJudgeOptions<TScenario> & {\n mapInput(input: { artifact: TArtifact; scenario: TScenario }): TRecord\n paidCall?: PaidEvaluationOptions<PhoenixEvaluationResultLike>\n },\n): JudgeConfig<TArtifact, TScenario> {\n if (\n (evaluator.optimizationDirection === 'MINIMIZE' ||\n evaluator.optimizationDirection === 'NEUTRAL') &&\n !options.toComposite\n ) {\n throw new TypeError(\n `phoenixEvaluatorJudge requires toComposite for a ${evaluator.optimizationDirection} evaluator`,\n )\n }\n const paidCall = validatePaidEvaluation(evaluator.name, evaluator.kind, options.paidCall)\n return upstreamJudge(\n {\n name: options.name ?? evaluator.name,\n dimension: options.dimension,\n judgeVersion: options.judgeVersion,\n appliesTo: options.appliesTo,\n toComposite: options.toComposite,\n },\n async (input) => {\n const result = await runUpstreamEvaluation({\n name: evaluator.name,\n kind: evaluator.kind,\n signal: input.signal,\n costLedger: input.costLedger,\n costPhase: input.costPhase,\n costTags: input.costTags,\n scenarioId: input.scenario.id,\n paidCall,\n execute: (context) =>\n evaluator.evaluate(\n options.mapInput({ artifact: input.artifact, scenario: input.scenario }),\n context,\n ),\n })\n if (result.score === undefined || !Number.isFinite(result.score)) {\n throw new Error(`${evaluator.name}: Phoenix evaluator returned no finite score`)\n }\n return {\n score: result.score,\n notes: [result.label, result.explanation].filter(Boolean).join(': ') || evaluator.name,\n }\n },\n )\n}\n\nexport function autoevalsScorerJudge<\n TInput extends Record<string, unknown>,\n TArtifact,\n TScenario extends Scenario = Scenario,\n>(\n scorer: AutoevalsScorerLike<TInput>,\n options: UpstreamJudgeOptions<TScenario> & {\n name: string\n mapInput(input: { artifact: TArtifact; scenario: TScenario }): TInput\n } & (\n | { kind: 'CODE'; paidCall?: never }\n | { kind: 'LLM'; paidCall: PaidEvaluationOptions<AutoevalsScoreLike> }\n ),\n): JudgeConfig<TArtifact, TScenario> {\n const paidCall = validatePaidEvaluation(options.name, options.kind, options.paidCall)\n return upstreamJudge(options, async (input) => {\n const result = await runUpstreamEvaluation({\n name: options.name,\n kind: options.kind,\n signal: input.signal,\n costLedger: input.costLedger,\n costPhase: input.costPhase,\n costTags: input.costTags,\n scenarioId: input.scenario.id,\n paidCall,\n execute: (context) =>\n scorer(options.mapInput({ artifact: input.artifact, scenario: input.scenario }), context),\n })\n if (result.score === null || !Number.isFinite(result.score)) {\n throw new Error(`${options.name}: Autoevals scorer returned no finite score`)\n }\n return {\n score: result.score,\n notes: result.metadata ? JSON.stringify(result.metadata) : result.name,\n }\n })\n}\n\nfunction upstreamJudge<TArtifact, TScenario extends Scenario>(\n options: UpstreamJudgeOptions<TScenario> & { name: string },\n evaluate: (\n input: Parameters<JudgeConfig<TArtifact, TScenario>['score']>[0],\n ) => Promise<{ score: number; notes: string }>,\n): JudgeConfig<TArtifact, TScenario> {\n const dimension = options.dimension ?? options.name\n return {\n name: options.name,\n judgeVersion: options.judgeVersion,\n dimensions: [{ key: dimension, description: `Score from ${options.name}` }],\n appliesTo: options.appliesTo,\n async score(input): Promise<JudgeScore> {\n const result = await evaluate(input)\n const composite = options.toComposite ? options.toComposite(result.score) : result.score\n if (!Number.isFinite(composite)) {\n throw new Error(`${options.name}: toComposite returned a non-finite score`)\n }\n return {\n dimensions: { [dimension]: result.score },\n composite,\n notes: result.notes,\n }\n },\n }\n}\n\nfunction validatePaidEvaluation<TResult>(\n name: string,\n kind: 'LLM' | 'CODE',\n paidCall: PaidEvaluationOptions<TResult> | undefined,\n): PaidEvaluationOptions<TResult> | undefined {\n if (kind === 'CODE') {\n if (paidCall) {\n throw new TypeError(`${name}: CODE evaluator cannot declare paidCall`)\n }\n return undefined\n }\n if (!paidCall) {\n throw new TypeError(`${name}: LLM evaluator requires paidCall cost and token capture`)\n }\n if (!paidCall.model.trim()) {\n throw new TypeError(`${name}: paidCall.model must be non-empty`)\n }\n return paidCall\n}\n\nasync function runUpstreamEvaluation<TResult>(input: {\n name: string\n kind: 'LLM' | 'CODE'\n signal: AbortSignal\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n scenarioId: string\n paidCall?: PaidEvaluationOptions<TResult>\n execute(context: UpstreamEvaluationContext): Promise<TResult> | TResult\n}): Promise<TResult> {\n if (input.kind === 'CODE') {\n return abortableEvaluation(input.signal, () => input.execute({ signal: input.signal }))\n }\n if (!input.paidCall) {\n throw new CostAccountingIncompleteError(`${input.name}: missing paid-call configuration`)\n }\n if (!input.costLedger) {\n throw new CostAccountingIncompleteError(\n `${input.name}: LLM evaluator requires the campaign cost ledger`,\n )\n }\n\n const paid = await input.costLedger.runPaidCall({\n channel: 'judge',\n phase: input.costPhase ?? 'judge',\n actor: input.name,\n model: input.paidCall.model,\n ...(input.paidCall.maximumCharge ? { maximumCharge: input.paidCall.maximumCharge } : {}),\n tags: { ...input.costTags, scenarioId: input.scenarioId },\n signal: input.signal,\n execute: (signal, callId) => Promise.resolve(input.execute({ signal, callId })),\n receipt: input.paidCall.receipt,\n ...(input.paidCall.receiptFromError\n ? { receiptFromError: input.paidCall.receiptFromError }\n : {}),\n })\n if (!paid.succeeded) throw paid.error\n\n const recorded = input.costLedger.list().find((receipt) => receipt.callId === paid.callId)\n if (!recorded) {\n throw new CostAccountingIncompleteError(\n `${input.name}: paid evaluator returned without a recorded cost receipt`,\n )\n }\n if (recorded.costUnknown || recorded.usageUnknown) {\n throw new CostAccountingIncompleteError(\n `${input.name}: paid evaluator returned without complete cost and token usage`,\n )\n }\n return paid.value\n}\n\nasync function abortableEvaluation<TResult>(\n signal: AbortSignal,\n execute: () => Promise<TResult> | TResult,\n): Promise<TResult> {\n if (signal.aborted) throw signal.reason\n\n let rejectAborted!: (reason: unknown) => void\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAborted = reject\n })\n const onAbort = (): void => rejectAborted(signal.reason)\n signal.addEventListener('abort', onAbort, { once: true })\n try {\n return await Promise.race([Promise.resolve().then(execute), aborted])\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\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 { path, branch, baseRef, baseCommit, baseTree }\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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,KAAK,UAAU,SAAS,IAAI,SACvD,QAAQ,KAAK;IAAC;IAAY;IAAU;IAAW;IAAM,SAAS;GAAI,GAAG,KAAK,QAAQ,CAC1F,GACA,sBACQ,eAAe,KAAK,KAAK,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-BzMSCejE.js","names":["validateAndIndex","rowsFor","componentSetKey","rowFor","meanOrNull","canonicalComponents","mean","sha256","fsConstants"],"sources":["../src/campaign/analyst-surface.ts","../src/campaign/cross-surface-context.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/grounded-reflection.ts","../src/campaign/labeled-store/fs-adapter.ts","../src/campaign/neutralize.ts","../src/campaign/parent-selection.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/segmented-profile-matrix.ts","../src/campaign/scenario-selection.ts","../src/campaign/upstream-evaluators.ts","../src/campaign/worktree/index.ts"],"sourcesContent":["import type {\n AnalystBenchmarkCase,\n AnalystBenchmarkLabelState,\n AnalystFindingScore,\n AnalystIssueExpectation,\n} from '../analyst/benchmark'\nimport { scoreAnalystFindings } from '../analyst/benchmark'\nimport type { AnalystFinding, AnalystRunResult, AnalystUsageReceipt } from '../analyst/types'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { DispatchContext, JudgeConfig, MutableSurface, Scenario } from './types'\n\nexport interface TraceAnalystScenario extends Scenario {\n kind: 'trace-analyst'\n traceStore: TraceAnalysisStore\n labelState: AnalystBenchmarkLabelState\n expectedIssues: readonly AnalystIssueExpectation[]\n labeledEvidence?: AnalystBenchmarkCase['labeledEvidence']\n}\n\nexport interface TraceAnalystArtifact {\n findings: readonly AnalystFinding[]\n usage?: AnalystUsageReceipt\n run?: AnalystRunResult\n}\n\nexport interface BuildTraceAnalystSurfaceDispatchOptions {\n analyze(input: {\n instructions: string\n traceStore: TraceAnalysisStore\n runId: string\n signal: AbortSignal\n }): Promise<TraceAnalystArtifact>\n}\n\nexport function buildTraceAnalystSurfaceDispatch(\n options: BuildTraceAnalystSurfaceDispatchOptions,\n): (\n surface: MutableSurface,\n scenario: TraceAnalystScenario,\n context: DispatchContext,\n) => Promise<TraceAnalystArtifact> {\n return async (surface, scenario, context) => {\n if (typeof surface !== 'string') {\n throw new TypeError(\n `buildTraceAnalystSurfaceDispatch requires a string prompt, received ${surface.kind}`,\n )\n }\n return options.analyze({\n instructions: surface,\n traceStore: scenario.traceStore,\n runId: `${context.cellId}:${scenario.id}`,\n signal: context.signal,\n })\n }\n}\n\nexport function traceAnalystQualityJudge(): JudgeConfig<\n TraceAnalystArtifact,\n TraceAnalystScenario\n> {\n return {\n name: 'trace-analyst-quality',\n judgeVersion: 'agent-eval:trace-analyst-quality:v3',\n dimensions: [\n { key: 'issue_recall', description: 'share of labeled issues found' },\n { key: 'finding_precision', description: 'share of findings tied to a labeled issue' },\n { key: 'f1', description: 'harmonic mean of issue recall and finding precision' },\n { key: 'critical_step_accuracy', description: 'share of labeled causal steps cited' },\n { key: 'citation_coverage', description: 'share of findings with evidence citations' },\n {\n key: 'citation_label_agreement',\n description: 'share of citations matching a labeled case location',\n },\n { key: 'clean', description: '1 when a clean case produces no findings' },\n ],\n appliesTo: (scenario) =>\n scenario.kind === 'trace-analyst' && scenario.labelState !== 'unlabeled',\n score({ artifact, scenario }) {\n assertScorableScenario(scenario)\n const score = scoreAnalystFindings(\n {\n id: scenario.id,\n expectedIssues: scenario.expectedIssues,\n labeledEvidence: scenario.labeledEvidence,\n },\n artifact.findings,\n )\n return traceAnalystJudgeScore(score)\n },\n }\n}\n\nfunction assertScorableScenario(scenario: TraceAnalystScenario): void {\n if (scenario.labelState === 'unlabeled') {\n throw new TypeError(`trace analyst scenario '${scenario.id}' has no quality labels`)\n }\n if (scenario.labelState === 'positive' && scenario.expectedIssues.length === 0) {\n throw new TypeError(`positive trace analyst scenario '${scenario.id}' requires expected issues`)\n }\n if (scenario.labelState === 'trusted-negative' && scenario.expectedIssues.length > 0) {\n throw new TypeError(\n `trusted-negative trace analyst scenario '${scenario.id}' cannot contain expected issues`,\n )\n }\n}\n\nfunction traceAnalystJudgeScore(score: AnalystFindingScore) {\n const dimensions: Record<string, number> = {\n issue_recall: score.issueRecall,\n finding_precision: score.findingPrecision,\n f1: score.f1,\n clean: score.predictionOnLabelEmptyCase ? 0 : 1,\n }\n if (score.criticalStepAccuracy !== null) {\n dimensions.critical_step_accuracy = score.criticalStepAccuracy\n }\n if (score.citationCoverage !== null) dimensions.citation_coverage = score.citationCoverage\n if (score.citationLabelAgreement !== null) {\n dimensions.citation_label_agreement = score.citationLabelAgreement\n }\n const notes = [\n `${score.matchedIssueIds.length}/${score.expectedIssueCount} issues found`,\n `${score.supportedFindingIndexes.length}/${score.supportedFindingIndexes.length + score.unsupportedFindingIndexes.length} findings supported`,\n `${score.unlabeledEvidence.length} citations outside labeled locations`,\n ].join('; ')\n const composite =\n score.criticalStepAccuracy === null ? score.f1 : (score.f1 + score.criticalStepAccuracy) / 2\n return { dimensions, composite, notes }\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","/**\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 {\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 type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceAdditionDecision,\n CrossSurfaceAdditionRejectionReason,\n CrossSurfaceCandidate,\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateEvidence,\n CrossSurfaceCandidateOutcome,\n CrossSurfaceCandidateSummary,\n CrossSurfaceCompositionStep,\n CrossSurfaceDistribution,\n CrossSurfaceEligibility,\n CrossSurfaceEvidenceBreakdown,\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 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 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\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 appendEvidenceEligibilityReasons(\n reasons: CrossSurfaceIneligibilityReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfaceIneligibilityReason,\n unobservedReason: CrossSurfaceIneligibilityReason,\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\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\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 appendBundleEvidenceReasons(\n reasons: CrossSurfaceAdditionRejectionReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfaceAdditionRejectionReason,\n unobservedReason: CrossSurfaceAdditionRejectionReason,\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\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 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 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 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 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\nfunction meanOrNull(values: number[]): number | null {\n return values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\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 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/** Mean of a numeric array; 0 for an empty array (callers guard n separately). */\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\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: mean(deltas), 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 * Evidence grounding for reflective optimizers (GEPA-style revise loops).\n *\n * Two failure modes recur when an LLM revises an artifact from raw rollout\n * traces (first measured in agent-lab R358, where naive reflection REGRESSED\n * the score 0.375 -> 0.125 before these helpers fixed it):\n *\n * 1. The environment often hides WHY a rollout failed - a tool call can\n * succeed while an invisible downstream check fails - so the reviser\n * cannot see the cause in the transcript. The only reliable signal is the\n * field-level difference between what passing and failing rollouts did.\n * `rolloutArgumentDiff` computes that difference deterministically so the\n * reviser is handed the diff instead of being trusted to derive it.\n *\n * 2. Revisers invent plausible-but-wrong literal values (\"use 'new'\",\n * \"use 'sent'\") that no passing rollout ever used, turning every rollout\n * into a failure. `classifyUngroundedLiterals` mechanically detects them,\n * separating HARMFUL literals (ones failing rollouts actually used -\n * proven damage) from benign illustrations (e.g. a name example like\n * 'Doe'), so callers can hard-reject the former and merely log the latter.\n * Rejecting every ungrounded quoted word is too blunt: it killed a run\n * over a surname illustration before the severity split existed.\n *\n * Pure data in, data out: no LLM calls, no filesystem, no domain knowledge.\n */\n\n/** One tool/action call observed in a rollout: a name plus its arguments. */\nexport interface RolloutCall {\n readonly name: string\n readonly args: Readonly<Record<string, unknown>>\n}\n\n/** A scored rollout: its calls plus the scalar outcome used to split pass/fail. */\nexport interface ScoredRollout {\n /** Caller-meaningful identifier (task id, cell id) used only for reporting. */\n readonly id: string\n /** Scalar outcome in [0, 1]; `passThreshold` splits passing from failing. */\n readonly score: number\n readonly calls: readonly RolloutCall[]\n}\n\nexport interface RolloutArgumentDiffOptions {\n /** Rollouts with `score >= passThreshold` count as passing. Default 1. */\n readonly passThreshold?: number\n /** Max distinct values listed per field per side in the rendered text. Default 4. */\n readonly maxValuesPerField?: number\n}\n\nexport interface RolloutArgumentDiff {\n /** Human/LLM-readable per-field diff, one line per field. */\n readonly text: string\n /** Lowercased stringified argument values seen in passing rollouts. */\n readonly passingValues: ReadonlySet<string>\n /** Lowercased stringified argument values seen in failing rollouts. */\n readonly failingValues: ReadonlySet<string>\n}\n\n/**\n * Deterministic per-field diff of call arguments between passing and failing\n * rollouts. A field set by failing rollouts but left unset by passing ones is\n * the classic poison-input signature; a field whose values differ across the\n * split points at the correct value. Feed `text` to the reviser verbatim.\n */\nexport function rolloutArgumentDiff(\n rollouts: readonly ScoredRollout[],\n opts: RolloutArgumentDiffOptions = {},\n): RolloutArgumentDiff {\n const passThreshold = opts.passThreshold ?? 1\n const maxValues = opts.maxValuesPerField ?? 4\n const collect = (pass: boolean): Map<string, Set<string>> => {\n const byField = new Map<string, Set<string>>()\n for (const r of rollouts) {\n if (pass !== r.score >= passThreshold) continue\n for (const c of r.calls) {\n for (const [k, v] of Object.entries(c.args)) {\n const set = byField.get(k) ?? new Set<string>()\n set.add(String(v))\n byField.set(k, set)\n }\n }\n }\n return byField\n }\n const passing = collect(true)\n const failing = collect(false)\n const lines: string[] = []\n for (const field of new Set([...passing.keys(), ...failing.keys()])) {\n const pv = [...(passing.get(field) ?? [])].slice(0, maxValues)\n const fv = [...(failing.get(field) ?? [])].slice(0, maxValues)\n const render = (vals: string[]) => (vals.length ? JSON.stringify(vals) : 'NOT SET (omitted)')\n lines.push(` ${field}: passing runs -> ${render(pv)} | failing runs -> ${render(fv)}`)\n }\n const lower = (m: Map<string, Set<string>>): Set<string> => {\n const out = new Set<string>()\n for (const vals of m.values()) for (const v of vals) out.add(v.toLowerCase())\n return out\n }\n return {\n text: lines.join('\\n') || ' (no calls observed)',\n passingValues: lower(passing),\n failingValues: lower(failing),\n }\n}\n\nexport interface UngroundedLiteralReport {\n /** Quoted single-word literals in the text that no passing rollout used. */\n readonly ungrounded: readonly string[]\n /** The subset failing rollouts actually used - prescribing these is proven harmful. */\n readonly harmful: readonly string[]\n}\n\n/**\n * Scan revised artifact text for single-quoted single-word literals (the\n * \"use exactly 'new'\" pattern) that appear in no passing rollout's argument\n * values. Multi-word quotes pass (they are prose, not prescriptions).\n * Callers should reject on `harmful` (with a bounded retry) and at most log\n * `ungrounded` - see the module header for why the severities differ.\n */\nexport function classifyUngroundedLiterals(\n text: string,\n diff: Pick<RolloutArgumentDiff, 'passingValues' | 'failingValues'>,\n): UngroundedLiteralReport {\n const ungrounded = new Set<string>()\n for (const m of text.matchAll(/'([a-z][a-z_-]{1,19})'/gi)) {\n const w = (m[1] as string).toLowerCase()\n if (!diff.passingValues.has(w)) ungrounded.add(w)\n }\n const all = [...ungrounded]\n return {\n ungrounded: all,\n harmful: all.filter((w) => diff.failingValues.has(w)),\n }\n}\n","/**\n * Filesystem `LabeledScenarioStore` adapter. The default capture sink for\n * traces + eval artifacts. Production deployments typically swap for a\n * Turso/SQLite adapter (same interface).\n *\n * Records land as one JSONL file per source under `<root>/<source>.jsonl`.\n * Each line is a `LabeledScenarioRecord`. Append-only — no in-place edits.\n *\n * Safety properties enforced at write-time:\n *\n * - **Provenance required**: writes without `source`, `sourceVersionHash`,\n * `capturedAt`, `redactionStatus` are rejected. Closes the alignment\n * reviewer's data-poisoning gap.\n * - **Per-source rate limits**: optional `rateLimitBucket` + `maxWritesPerMinute`\n * stops a single tenant/source from flooding the store.\n *\n * Safety properties enforced at sample-time:\n *\n * - **Required split + capturedBefore**: substrate refuses to sample without\n * an explicit `split` ('train' | 'test') AND a temporal cutoff. Eliminates\n * accidental train/test contamination.\n * - **Default training-source filter**: when the store is sampled with\n * `split: 'train'`, production-trace records are EXCLUDED unless the\n * caller passes `filter.source: 'production-trace'` explicitly. Closes\n * the contamination-by-default gap flagged by the senior eval engineer.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { compareCodeUnits } from '../../ledger-core/canonical'\nimport type {\n LabeledScenarioRecord,\n LabeledScenarioSampleArgs,\n LabeledScenarioSource,\n LabeledScenarioStore,\n LabeledScenarioWrite,\n LabelTrust,\n} from '../types'\nimport { labelTrustRank } from '../types'\n\nexport interface FsLabeledScenarioStoreOptions {\n /** Root directory for JSONL files. Created if missing. */\n root: string\n /** Per-source rate limit. When set, writes exceeding the cap are rejected\n * with a typed error. Default: no limit. */\n maxWritesPerMinutePerBucket?: number\n /** Test seam — override `Date.now()` for deterministic tests. */\n now?: () => number\n}\n\n/** Typed rejection from a labeled-scenario store (bad provenance, rate limit, invalid sample args) — carries a stable string `code`. */\nexport class LabeledScenarioStoreError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message)\n this.name = 'LabeledScenarioStoreError'\n }\n}\n\ninterface RateLimitState {\n bucket: string\n windowStartMs: number\n count: number\n}\n\n/**\n * Filesystem `LabeledScenarioStore`: appends one JSONL file per source with provenance and\n * rate-limit guards. For tests, local dev, and small workloads — high-throughput lands in Turso.\n */\nexport class FsLabeledScenarioStore implements LabeledScenarioStore {\n private readonly now: () => number\n private readonly rateLimits = new Map<string, RateLimitState>()\n\n constructor(private readonly options: FsLabeledScenarioStoreOptions) {\n if (!existsSync(options.root)) mkdirSync(options.root, { recursive: true })\n this.now = options.now ?? Date.now\n }\n\n async observe(write: LabeledScenarioWrite): Promise<void> {\n this.assertProvenance(write)\n this.assertRateLimit(write)\n const record = this.toRecord(write)\n const path = this.pathForSource(write.source)\n const line = `${JSON.stringify(record)}\\n`\n // Append atomically. For high-throughput a writev-friendly buffered\n // implementation lands in the Turso adapter; FS adapter is for tests +\n // local dev + small workloads.\n appendLine(path, line)\n }\n\n async sample(args: LabeledScenarioSampleArgs): Promise<LabeledScenarioRecord[]> {\n if (!args.split) {\n throw new LabeledScenarioStoreError(\n 'split_required',\n 'sample() requires an explicit `split` (train | test) — substrate refuses ambiguous reads',\n )\n }\n if (!args.capturedBefore) {\n throw new LabeledScenarioStoreError(\n 'capturedBefore_required',\n 'sample() requires an explicit `capturedBefore` timestamp for temporal-split discipline',\n )\n }\n\n const all: LabeledScenarioRecord[] = []\n for (const source of ALL_SOURCES) {\n // Default training-source filter: when sampling train, EXCLUDE\n // production-trace records unless the caller asks for them.\n if (args.split === 'train' && source === 'production-trace') {\n const explicit = sourceFilterContains(args.filter?.source, 'production-trace')\n if (!explicit) continue\n }\n const path = this.pathForSource(source)\n if (!existsSync(path)) continue\n const lines = readFileSync(path, 'utf8').split('\\n').filter(Boolean)\n for (const line of lines) {\n let record: LabeledScenarioRecord\n try {\n record = JSON.parse(line) as LabeledScenarioRecord\n } catch {\n continue\n }\n if (!matchesFilter(record, args, source)) continue\n all.push(record)\n }\n }\n\n // Deterministic order: by capturedAt ascending, then recordHash.\n all.sort((a, b) => {\n if (a.capturedAt !== b.capturedAt) return compareCodeUnits(a.capturedAt, b.capturedAt)\n return compareCodeUnits(a.recordHash, b.recordHash)\n })\n\n return all.slice(0, args.count)\n }\n\n async size(): Promise<{\n train: number\n test: number\n bySource: Record<string, number>\n byTrust: Record<LabelTrust, number>\n }> {\n const bySource: Record<string, number> = {}\n const byTrust: Record<LabelTrust, number> = {\n unverified: 0,\n 'verified-signal': 0,\n 'human-rated': 0,\n }\n let total = 0\n for (const source of ALL_SOURCES) {\n const path = this.pathForSource(source)\n if (!existsSync(path)) {\n bySource[source] = 0\n continue\n }\n const lines = readFileSync(path, 'utf8').split('\\n').filter(Boolean)\n bySource[source] = lines.length\n total += lines.length\n for (const line of lines) {\n let trust: LabelTrust = 'unverified'\n try {\n trust = (JSON.parse(line) as LabeledScenarioRecord).labelTrust ?? 'unverified'\n } catch {\n // A malformed line counts as unverified — never silently gold.\n }\n byTrust[trust] += 1\n }\n }\n // FS adapter doesn't track split assignments per-record (split is\n // computed at sample-time based on `capturedBefore`). For size(), we\n // report `train`+`test` as the same total — split is a sampling concept.\n return { train: total, test: total, bySource, byTrust }\n }\n\n private assertProvenance(write: LabeledScenarioWrite): void {\n if (!write.source) {\n throw new LabeledScenarioStoreError(\n 'missing_source',\n 'LabeledScenarioWrite requires `source`',\n )\n }\n if (!write.sourceVersionHash || write.sourceVersionHash.length === 0) {\n throw new LabeledScenarioStoreError(\n 'missing_source_version',\n 'LabeledScenarioWrite requires `sourceVersionHash` (git sha or substrate version)',\n )\n }\n if (!write.capturedAt) {\n throw new LabeledScenarioStoreError(\n 'missing_captured_at',\n 'LabeledScenarioWrite requires `capturedAt` ISO timestamp',\n )\n }\n if (!write.redactionStatus) {\n throw new LabeledScenarioStoreError(\n 'missing_redaction_status',\n 'LabeledScenarioWrite requires explicit `redactionStatus` — raw / redacted-pii / redacted-secrets / fully-redacted',\n )\n }\n if (!ALL_SOURCES.includes(write.source)) {\n throw new LabeledScenarioStoreError(\n 'unknown_source',\n `LabeledScenarioWrite.source must be one of: ${ALL_SOURCES.join(', ')}`,\n )\n }\n }\n\n private assertRateLimit(write: LabeledScenarioWrite): void {\n const cap = this.options.maxWritesPerMinutePerBucket\n if (!cap || !write.rateLimitBucket) return\n const now = this.now()\n const windowMs = 60_000\n let state = this.rateLimits.get(write.rateLimitBucket)\n if (!state || now - state.windowStartMs >= windowMs) {\n state = { bucket: write.rateLimitBucket, windowStartMs: now, count: 0 }\n this.rateLimits.set(write.rateLimitBucket, state)\n }\n if (state.count >= cap) {\n throw new LabeledScenarioStoreError(\n 'rate_limit_exceeded',\n `LabeledScenarioStore: bucket ${write.rateLimitBucket} exceeded ${cap} writes/min`,\n )\n }\n state.count += 1\n }\n\n private toRecord(write: LabeledScenarioWrite): LabeledScenarioRecord {\n const recordHash = sha256(\n JSON.stringify({\n id: write.scenario.id,\n src: write.source,\n at: write.capturedAt,\n ver: write.sourceVersionHash,\n }),\n )\n // FS adapter assigns split at sample-time, but we cache a hint here\n // based on capturedAt vs the world's \"now\" — sampler overrides this.\n return {\n ...write,\n recordHash,\n split: 'train',\n }\n }\n\n private pathForSource(source: string): string {\n return join(this.options.root, `${source}.jsonl`)\n }\n}\n\nconst ALL_SOURCES: LabeledScenarioWrite['source'][] = [\n 'production-trace',\n 'eval-run',\n 'manual',\n 'red-team',\n 'synthetic',\n]\n\nfunction sourceFilterContains(\n filter: LabeledScenarioSource | LabeledScenarioSource[] | undefined,\n needle: LabeledScenarioSource,\n): boolean {\n if (!filter) return false\n if (Array.isArray(filter)) return filter.includes(needle)\n return filter === needle\n}\n\nfunction matchesFilter(\n record: LabeledScenarioRecord,\n args: LabeledScenarioSampleArgs,\n source: string,\n): boolean {\n // Temporal cutoff — train must be capturedAt < capturedBefore.\n if (args.split === 'train' && record.capturedAt >= args.capturedBefore) return false\n if (args.split === 'test' && record.capturedAt < args.capturedBefore) return false\n\n const f = args.filter\n if (!f) return true\n if (f.kind && record.scenario.kind !== f.kind) return false\n if (f.source) {\n const sources = Array.isArray(f.source) ? f.source : [f.source]\n if (!sources.includes(source as never)) return false\n }\n if (f.minComposite !== undefined || f.maxComposite !== undefined) {\n const composites = Object.values(record.judgeScores).map((s) => s.composite)\n const max = composites.length === 0 ? 0 : Math.max(...composites)\n if (f.minComposite !== undefined && max < f.minComposite) return false\n if (f.maxComposite !== undefined && max > f.maxComposite) return false\n }\n if (f.minTrust !== undefined && labelTrustRank(record.labelTrust) < labelTrustRank(f.minTrust)) {\n return false\n }\n return true\n}\n\nfunction sha256(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 16)\n}\n\nfunction appendLine(path: string, line: string): void {\n if (existsSync(path)) {\n const existing = readFileSync(path, 'utf8')\n writeFileSync(path, existing + line)\n } else {\n writeFileSync(path, line)\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","/**\n * Parent selection for `runOptimization`.\n *\n * Each generation mutates one parent surface. The default parent is the\n * global incumbent, so the search is a hill-climb and the lineage recorded in\n * `GenerationCandidate.parentSurfaceHash` is a chain. A `ParentSelector` draws\n * the parent from the Pareto frontier instead, so the recorded lineage becomes\n * a tree. Promotion is unchanged: a candidate still has to beat the incumbent.\n */\n\nimport { type Objective, paretoFrontierWithCrowding } from '../pareto'\nimport { mulberry32 } from '../statistics/random'\nimport type { GenerationRecord, ParetoParent, ScoredSurfaceOutcome } from './types'\n\n/** Search state supplied to one parent-selection call. */\nexport interface ParentSelectionContext {\n /** Non-dominated scored surfaces across the whole run so far, including the\n * baseline (`generation: -1`). Never empty. */\n readonly frontier: ReadonlyArray<ParetoParent>\n /** Measured result of the global incumbent, the promotion bar. Under the\n * default `selectionRankKey` the incumbent is always on `frontier`. */\n readonly incumbent: ScoredSurfaceOutcome\n /** Every completed generation so far. */\n readonly history: ReadonlyArray<GenerationRecord>\n /** Index of the generation about to propose. */\n readonly generation: number\n}\n\n/** Chooses the surface the next generation mutates. Returns one frontier\n * parent; `runOptimization` refuses a parent it has not measured to\n * completion or whose surface does not match its `surfaceHash`. */\nexport type ParentSelector = (ctx: ParentSelectionContext) => ParetoParent\n\nexport interface CrowdedFrontierParentOptions {\n /** Integer seed for the per-generation draw. The same seed, frontier, and\n * generation index select the same parent. */\n seed: number\n}\n\n/**\n * NSGA-II crowded tournament selection over the frontier. Each generation\n * draws two distinct frontier members with a PRNG seeded from `seed` and the\n * generation index, and keeps the one with the larger crowding distance (more\n * isolated on the frontier). Boundary parents carry infinite distance, so a\n * boundary parent always beats an interior one. A tie on distance falls back\n * to the higher mean composite, then to the smaller surface hash. A frontier\n * of one member returns that member.\n */\nexport function crowdedFrontierParent(options: CrowdedFrontierParentOptions): ParentSelector {\n const { seed } = options\n if (!Number.isInteger(seed)) {\n throw new TypeError(`crowdedFrontierParent: seed must be an integer, got ${String(seed)}`)\n }\n return ({ frontier, generation }) => {\n if (frontier.length === 0) {\n throw new Error('crowdedFrontierParent: frontier is empty')\n }\n if (frontier.length === 1) return frontier[0]!\n const distances = new Map<ParetoParent, number>()\n for (const { candidate, distance } of paretoFrontierWithCrowding(\n [...frontier],\n frontierObjectives(frontier),\n )) {\n distances.set(candidate, distance)\n }\n const rng = mulberry32(tournamentSeed(seed, generation))\n const first = Math.floor(rng() * frontier.length)\n const offset = Math.floor(rng() * (frontier.length - 1))\n const second = offset >= first ? offset + 1 : offset\n const a = frontier[first]!\n const b = frontier[second]!\n return compareCrowded(a, distanceOf(distances, a), b, distanceOf(distances, b)) <= 0 ? a : b\n }\n}\n\nfunction distanceOf(distances: ReadonlyMap<ParetoParent, number>, parent: ParetoParent): number {\n const distance = distances.get(parent)\n if (distance === undefined) {\n throw new Error(\n `crowdedFrontierParent: frontier member \"${parent.surfaceHash}\" is dominated or has a non-finite objective`,\n )\n }\n return distance\n}\n\n/** Negative when `a` wins the tournament, positive when `b` wins. */\nfunction compareCrowded(a: ParetoParent, da: number, b: ParetoParent, db: number): number {\n if (da !== db) return da > db ? -1 : 1\n if (a.composite !== b.composite) return a.composite > b.composite ? -1 : 1\n if (a.surfaceHash === b.surfaceHash) return 0\n return a.surfaceHash < b.surfaceHash ? -1 : 1\n}\n\n/** One `maximize` objective per scenario id present on the frontier. */\nfunction frontierObjectives(frontier: ReadonlyArray<ParetoParent>): Objective<ParetoParent>[] {\n const ids = new Set<string>()\n for (const parent of frontier) for (const id of Object.keys(parent.objectives)) ids.add(id)\n if (ids.size === 0) {\n throw new Error('crowdedFrontierParent: frontier parents carry no objectives')\n }\n return [...ids].sort().map((id) => ({\n name: id,\n direction: 'maximize',\n value: (parent) => {\n const value = parent.objectives[id]\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(\n `crowdedFrontierParent: frontier member \"${parent.surfaceHash}\" has no finite objective \"${id}\"`,\n )\n }\n return value\n },\n }))\n}\n\nfunction tournamentSeed(seed: number, generation: number): number {\n return (seed ^ Math.imul(generation + 1, 0x9e3779b1)) | 0\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 { extractProducedState, type RuntimeEventLike } from '../../produced-state'\nimport type { DispatchContext, Scenario } from '../types'\nimport type { ProfileDispatchFn } from './run-profile-matrix'\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/**\n * Adapt a `PlaybackDriver` into a `runProfileMatrix` dispatch. The artifact the\n * matrix scores is the `ProducedState` extracted from the driver's event\n * stream — grade it with `scoreUserStory` (or a judge wrapping it).\n */\nexport function makePlaybackDispatch<TStory extends UserStory>(\n driver: PlaybackDriver<TStory>,\n): ProfileDispatchFn<TStory, ProducedState> {\n return async (profile, scenario, ctx) => {\n const events = await driver.run(scenario, { ...ctx, profile })\n return extractProducedState(events)\n }\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 * `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 * A dispatch that reports zero tokens is indistinguishable from a stub and the\n * integrity guard treats it as one.\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 type RunRecord,\n type RunSplitTag,\n runTaskScore,\n UNKNOWN_MODEL,\n validateRunRecord,\n} from '../../run-record'\nimport { computeManifestHash } from '../campaign-manifest'\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\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\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 receiptModels(cell: CampaignCellResult<unknown>): string[] {\n const reported = cell.resolvedModels ?? (cell.resolvedModel ? [cell.resolvedModel] : [])\n return [...new Set(reported.map((model) => model.trim()).filter(Boolean))]\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 = receiptModels(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 = resolved\n .replace(/@[^/]+$/u, '')\n .replace(/-\\d{8}$/u, '')\n .replace(/-\\d{4}-\\d{2}-\\d{2}$/u, '')\n .replace(/-\\d{4}$/u, '')\n .replace(/:date-[^/]+$/u, '')\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 durableCell = durableCellForRecord(cell)\n const record = campaignCellToRunRecord(durableCell, {\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 * Keep failed rows truthful at the RunRecord boundary.\n *\n * A cell with no settled call currently has a zero subtotal and an observed\n * zero from the ledger. That is not measured provider usage or cost, so mark\n * usage incomplete and cost uncaptured while retaining the known subtotal.\n */\nfunction durableCellForRecord<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n): CampaignCellResult<TArtifact> {\n if (cell.error === undefined) return cell\n\n const hasSettledAgentCalls = receiptModels(cell).some((model) => model !== UNKNOWN_MODEL)\n return {\n ...cell,\n tokenUsage:\n cell.tokenUsage.tokensKnown === false || hasSettledAgentCalls\n ? cell.tokenUsage\n : { ...cell.tokenUsage, tokensKnown: false },\n costProvenance:\n !hasSettledAgentCalls && cell.costProvenance.kind === 'observed' && cell.costUsd === 0\n ? { kind: 'uncaptured', usd: null }\n : cell.costProvenance,\n }\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 meanOrNull(values: number[]): number | null {\n return values.length === 0 ? null : mean(values)\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 * 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/**\n * Select the top-`k` most discriminative scenario ids for a holdout, EXCLUDING\n * fully saturated ties when enough non-tied scenarios exist (a tie in the\n * holdout wastes a paired cell).\n *\n * Prefers non-tied scenarios; if fewer than `k` non-tied exist, fills with the\n * least-saturated tied ones (tied scenarios are already ordered least-saturated\n * first by `meanScore` asc). Deterministic. Throws if `k < 1`. If\n * `signals.length <= k`, returns all ids in discrimination order.\n */\nexport function selectDiscriminative(\n signals: ScenarioSignal[],\n k: number,\n opts?: { saturationCeiling?: number },\n): string[] {\n if (k < 1) throw new Error(`selectDiscriminative: k must be >= 1 (got ${k})`)\n const ranked = scoreDiscrimination(signals, opts)\n if (ranked.length <= k) return ranked.map((s) => s.scenarioId)\n const nonTied = ranked.filter((s) => !s.tied)\n if (nonTied.length >= k) return nonTied.slice(0, k).map((s) => s.scenarioId)\n const tied = ranked.filter((s) => s.tied)\n const fill = tied.slice(0, k - nonTied.length)\n return [...nonTied, ...fill].map((s) => s.scenarioId)\n}\n","import {\n CostAccountingIncompleteError,\n type CostLedgerHandle,\n type RunPaidCallInput,\n} from '../cost-ledger'\nimport type { JudgeConfig, JudgeScore, Scenario } from './types'\n\nexport interface PhoenixEvaluationResultLike {\n score?: number\n label?: string\n explanation?: string\n}\n\nexport interface PhoenixEvaluatorLike<TRecord extends Record<string, unknown>> {\n name: string\n kind: 'LLM' | 'CODE'\n optimizationDirection?: 'MAXIMIZE' | 'MINIMIZE' | 'NEUTRAL'\n evaluate(\n record: TRecord,\n context: UpstreamEvaluationContext,\n ): Promise<PhoenixEvaluationResultLike>\n}\n\nexport interface AutoevalsScoreLike {\n name: string\n score: number | null\n metadata?: Record<string, unknown>\n}\n\nexport type AutoevalsScorerLike<TInput extends Record<string, unknown>> = (\n input: TInput,\n context: UpstreamEvaluationContext,\n) => AutoevalsScoreLike | Promise<AutoevalsScoreLike>\n\nexport interface UpstreamEvaluationContext {\n readonly signal: AbortSignal\n readonly callId?: string\n}\n\ntype PaidEvaluationOptions<TResult> = Pick<\n RunPaidCallInput<TResult>,\n 'maximumCharge' | 'receipt' | 'receiptFromError'\n> & {\n model: string\n}\n\ninterface UpstreamJudgeOptions<TScenario extends Scenario> {\n name?: string\n dimension?: string\n judgeVersion?: string\n appliesTo?: (scenario: TScenario) => boolean\n /** Convert the upstream score when its native scale is not higher-is-better. */\n toComposite?: (score: number) => number\n}\n\nexport function phoenixEvaluatorJudge<\n TRecord extends Record<string, unknown>,\n TArtifact,\n TScenario extends Scenario = Scenario,\n>(\n evaluator: PhoenixEvaluatorLike<TRecord>,\n options: UpstreamJudgeOptions<TScenario> & {\n mapInput(input: { artifact: TArtifact; scenario: TScenario }): TRecord\n paidCall?: PaidEvaluationOptions<PhoenixEvaluationResultLike>\n },\n): JudgeConfig<TArtifact, TScenario> {\n if (\n (evaluator.optimizationDirection === 'MINIMIZE' ||\n evaluator.optimizationDirection === 'NEUTRAL') &&\n !options.toComposite\n ) {\n throw new TypeError(\n `phoenixEvaluatorJudge requires toComposite for a ${evaluator.optimizationDirection} evaluator`,\n )\n }\n const paidCall = validatePaidEvaluation(evaluator.name, evaluator.kind, options.paidCall)\n return upstreamJudge(\n {\n name: options.name ?? evaluator.name,\n dimension: options.dimension,\n judgeVersion: options.judgeVersion,\n appliesTo: options.appliesTo,\n toComposite: options.toComposite,\n },\n async (input) => {\n const result = await runUpstreamEvaluation({\n name: evaluator.name,\n kind: evaluator.kind,\n signal: input.signal,\n costLedger: input.costLedger,\n costPhase: input.costPhase,\n costTags: input.costTags,\n scenarioId: input.scenario.id,\n paidCall,\n execute: (context) =>\n evaluator.evaluate(\n options.mapInput({ artifact: input.artifact, scenario: input.scenario }),\n context,\n ),\n })\n if (result.score === undefined || !Number.isFinite(result.score)) {\n throw new Error(`${evaluator.name}: Phoenix evaluator returned no finite score`)\n }\n return {\n score: result.score,\n notes: [result.label, result.explanation].filter(Boolean).join(': ') || evaluator.name,\n }\n },\n )\n}\n\nexport function autoevalsScorerJudge<\n TInput extends Record<string, unknown>,\n TArtifact,\n TScenario extends Scenario = Scenario,\n>(\n scorer: AutoevalsScorerLike<TInput>,\n options: UpstreamJudgeOptions<TScenario> & {\n name: string\n mapInput(input: { artifact: TArtifact; scenario: TScenario }): TInput\n } & (\n | { kind: 'CODE'; paidCall?: never }\n | { kind: 'LLM'; paidCall: PaidEvaluationOptions<AutoevalsScoreLike> }\n ),\n): JudgeConfig<TArtifact, TScenario> {\n const paidCall = validatePaidEvaluation(options.name, options.kind, options.paidCall)\n return upstreamJudge(options, async (input) => {\n const result = await runUpstreamEvaluation({\n name: options.name,\n kind: options.kind,\n signal: input.signal,\n costLedger: input.costLedger,\n costPhase: input.costPhase,\n costTags: input.costTags,\n scenarioId: input.scenario.id,\n paidCall,\n execute: (context) =>\n scorer(options.mapInput({ artifact: input.artifact, scenario: input.scenario }), context),\n })\n if (result.score === null || !Number.isFinite(result.score)) {\n throw new Error(`${options.name}: Autoevals scorer returned no finite score`)\n }\n return {\n score: result.score,\n notes: result.metadata ? JSON.stringify(result.metadata) : result.name,\n }\n })\n}\n\nfunction upstreamJudge<TArtifact, TScenario extends Scenario>(\n options: UpstreamJudgeOptions<TScenario> & { name: string },\n evaluate: (\n input: Parameters<JudgeConfig<TArtifact, TScenario>['score']>[0],\n ) => Promise<{ score: number; notes: string }>,\n): JudgeConfig<TArtifact, TScenario> {\n const dimension = options.dimension ?? options.name\n return {\n name: options.name,\n judgeVersion: options.judgeVersion,\n dimensions: [{ key: dimension, description: `Score from ${options.name}` }],\n appliesTo: options.appliesTo,\n async score(input): Promise<JudgeScore> {\n const result = await evaluate(input)\n const composite = options.toComposite ? options.toComposite(result.score) : result.score\n if (!Number.isFinite(composite)) {\n throw new Error(`${options.name}: toComposite returned a non-finite score`)\n }\n return {\n dimensions: { [dimension]: result.score },\n composite,\n notes: result.notes,\n }\n },\n }\n}\n\nfunction validatePaidEvaluation<TResult>(\n name: string,\n kind: 'LLM' | 'CODE',\n paidCall: PaidEvaluationOptions<TResult> | undefined,\n): PaidEvaluationOptions<TResult> | undefined {\n if (kind === 'CODE') {\n if (paidCall) {\n throw new TypeError(`${name}: CODE evaluator cannot declare paidCall`)\n }\n return undefined\n }\n if (!paidCall) {\n throw new TypeError(`${name}: LLM evaluator requires paidCall cost and token capture`)\n }\n if (!paidCall.model.trim()) {\n throw new TypeError(`${name}: paidCall.model must be non-empty`)\n }\n return paidCall\n}\n\nasync function runUpstreamEvaluation<TResult>(input: {\n name: string\n kind: 'LLM' | 'CODE'\n signal: AbortSignal\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n scenarioId: string\n paidCall?: PaidEvaluationOptions<TResult>\n execute(context: UpstreamEvaluationContext): Promise<TResult> | TResult\n}): Promise<TResult> {\n if (input.kind === 'CODE') {\n return abortableEvaluation(input.signal, () => input.execute({ signal: input.signal }))\n }\n if (!input.paidCall) {\n throw new CostAccountingIncompleteError(`${input.name}: missing paid-call configuration`)\n }\n if (!input.costLedger) {\n throw new CostAccountingIncompleteError(\n `${input.name}: LLM evaluator requires the campaign cost ledger`,\n )\n }\n\n const paid = await input.costLedger.runPaidCall({\n channel: 'judge',\n phase: input.costPhase ?? 'judge',\n actor: input.name,\n model: input.paidCall.model,\n ...(input.paidCall.maximumCharge ? { maximumCharge: input.paidCall.maximumCharge } : {}),\n tags: { ...input.costTags, scenarioId: input.scenarioId },\n signal: input.signal,\n execute: (signal, callId) => Promise.resolve(input.execute({ signal, callId })),\n receipt: input.paidCall.receipt,\n ...(input.paidCall.receiptFromError\n ? { receiptFromError: input.paidCall.receiptFromError }\n : {}),\n })\n if (!paid.succeeded) throw paid.error\n\n const recorded = input.costLedger.list().find((receipt) => receipt.callId === paid.callId)\n if (!recorded) {\n throw new CostAccountingIncompleteError(\n `${input.name}: paid evaluator returned without a recorded cost receipt`,\n )\n }\n if (recorded.costUnknown || recorded.usageUnknown) {\n throw new CostAccountingIncompleteError(\n `${input.name}: paid evaluator returned without complete cost and token usage`,\n )\n }\n return paid.value\n}\n\nasync function abortableEvaluation<TResult>(\n signal: AbortSignal,\n execute: () => Promise<TResult> | TResult,\n): Promise<TResult> {\n if (signal.aborted) throw signal.reason\n\n let rejectAborted!: (reason: unknown) => void\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAborted = reject\n })\n const onAbort = (): void => rejectAborted(signal.reason)\n signal.addEventListener('abort', onAbort, { once: true })\n try {\n return await Promise.race([Promise.resolve().then(execute), aborted])\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\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":";;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,iCACd,SAKiC;CACjC,OAAO,OAAO,SAAS,UAAU,YAAY;EAC3C,IAAI,OAAO,YAAY,UACrB,MAAM,IAAI,UACR,uEAAuE,QAAQ,MACjF;EAEF,OAAO,QAAQ,QAAQ;GACrB,cAAc;GACd,YAAY,SAAS;GACrB,OAAO,GAA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