@tangle-network/agent-eval 0.126.1 → 0.126.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,7 +4,29 @@ All notable changes to `@tangle-network/agent-eval` and its sibling `agent-eval-
4
4
 
5
5
  ---
6
6
 
7
- ## [Unreleased]
7
+ ## [0.126.3] - 2026-07-24 - execution-bound optimizer resume
8
+
9
+ ### Added
10
+
11
+ - `runCampaign({ abortOnCellError: true })` stops scheduling after the first dispatch or judge error, aborts and drains active sibling cells, then rejects with the original error.
12
+ - Failed cells write `<cell>/failure-receipt.json` before cancellation, including the exact cell result, call IDs, and settled agent-plus-judge cost and token totals.
13
+
14
+ ### Fixed
15
+
16
+ - Official GEPA, SkillOpt, and generic external optimizer resume identities include the caller's exact dispatch identity, so changed agent, retrieval, judge, model, or service behavior cannot restore incompatible optimizer state.
17
+ - `compareOptimizationMethods()` passes its final-scoring dispatch identity into method optimization and rejects conflicting identities.
18
+
19
+ ## [0.126.2] - 2026-07-24 - fail-closed candidate ranking
20
+
21
+ ### Added
22
+
23
+ - `runOptimization()` and `selfImprove()` accept a fixed-length `selectionRankKey` so domain-specific reliability metrics can choose candidates during every generation.
24
+
25
+ ### Fixed
26
+
27
+ - Candidate rank keys must be non-empty, fixed-length, and finite.
28
+ - A candidate must strictly beat the incumbent on the configured rank key before it can become the next parent or final winner.
29
+ - Method-reported spend above `costCeiling` is rejected before final scoring.
8
30
 
9
31
  ## [0.126.1] - 2026-07-24 - optimizer lifecycle integrity
10
32
 
package/README.md CHANGED
@@ -90,6 +90,26 @@ console.log(
90
90
  Each call runs every case, records the artifact, applies the same judge, and returns score distributions.
91
91
  The surface is the value being changed, such as a prompt, skill, or serialized configuration.
92
92
 
93
+ ### Stop after the first failed cell
94
+
95
+ `runCampaign()` normally records a dispatch or judge error on that cell and continues the remaining cases.
96
+ Set `abortOnCellError: true` when another failed cell would only waste time or money:
97
+
98
+ ```ts
99
+ await runCampaign({
100
+ scenarios,
101
+ dispatch,
102
+ judges: [judge],
103
+ runDir: 'release-candidate',
104
+ abortOnCellError: true,
105
+ })
106
+ ```
107
+
108
+ The failed cell is written first to `<runDir>/<cell>/failure-receipt.json`.
109
+ That receipt contains the original error, the cell result, exact call IDs, and settled agent-plus-judge cost and token totals.
110
+ Active sibling cells are cancelled and allowed to finish recording their own receipts before the campaign rejects with the original cell error.
111
+ Leaving `abortOnCellError` unset preserves continue-on-error behavior.
112
+
93
113
  ## Adapt Another Text Optimizer
94
114
 
95
115
  Use `externalTextOptimizationMethod()` when an existing package owns search and selection for a text prompt or named text components.
@@ -97,7 +117,7 @@ Its `run` callback receives the starting candidate plus serialized train and sel
97
117
  The optimizer must score candidates through `context.evaluate()` so Agent Eval can enforce the evaluation limit and use the configured execution and judges.
98
118
  Every optimizer-owned paid call must use `context.cost.runPaidCall()`.
99
119
  Set `source` to the package version and revision, and set `evaluationId` to a commit, content hash, or other stable identity for the execution and scoring behavior.
100
- Agent Eval derives the run identity from those values, the optimizer settings, the starting surface, the described data, and the seed.
120
+ Agent Eval derives the run identity from those values, the exact dispatch identity, the optimizer settings, the starting surface, the described data, and the seed.
101
121
  The callback returns the selected candidate, whether compatible state was restored, and how optimizer spend was recorded.
102
122
 
103
123
  See [Adapt A Third-Party Text Optimizer](./docs/campaign-proposers.md#adapt-a-third-party-text-optimizer) for a complete minimal adapter.
@@ -16,10 +16,10 @@ import {
16
16
  routing_exports,
17
17
  runBenchmarkAdapter,
18
18
  summarizeBenchmarkCampaign
19
- } from "../chunk-W4L6C2XT.js";
20
- import "../chunk-NGUYT5CI.js";
21
- import "../chunk-VMUENW6F.js";
22
- import "../chunk-UCLVDLCH.js";
19
+ } from "../chunk-CGG5SLH3.js";
20
+ import "../chunk-P6WN2KF5.js";
21
+ import "../chunk-3I74FLK6.js";
22
+ import "../chunk-ZVCHKKOP.js";
23
23
  import "../chunk-WGXIEX7P.js";
24
24
  import "../chunk-ARU2PZFM.js";
25
25
  import "../chunk-J5SQWP6Y.js";
@@ -2368,6 +2368,14 @@ interface RunCampaignOptions<TScenario extends Scenario, TArtifact> {
2368
2368
  costTags?: Readonly<Record<string, string>>;
2369
2369
  /** Max concurrent cells. Default 2. */
2370
2370
  maxConcurrency?: number;
2371
+ /**
2372
+ * Stop after the first dispatch or judge error. The failed cell is persisted
2373
+ * before active sibling cells are aborted and drained, then the campaign
2374
+ * rejects with the exact error thrown by that dispatch or judge.
2375
+ * Default false preserves the normal behavior of returning failed cells and
2376
+ * continuing the remaining schedule.
2377
+ */
2378
+ abortOnCellError?: boolean;
2371
2379
  /**
2372
2380
  * Per-cell dispatch deadline in ms. A `dispatch` that neither resolves nor
2373
2381
  * rejects within this window is a hang (a stalled model request, an
@@ -2432,6 +2440,26 @@ interface RunCampaignOptions<TScenario extends Scenario, TArtifact> {
2432
2440
  generation?: number;
2433
2441
  }) => string | undefined;
2434
2442
  }
2443
+ /** Durable `<cell>/failure-receipt.json` written before a failed cell can
2444
+ * trigger campaign-wide cancellation. The cell keeps its dispatch-only usage
2445
+ * fields for compatibility; `cost` covers every settled agent and judge call
2446
+ * attributed to this exact run attempt. */
2447
+ interface CampaignCellFailureReceipt<TArtifact = unknown> {
2448
+ schemaVersion: 1;
2449
+ runAttemptId: string;
2450
+ recordedAt: string;
2451
+ failure: {
2452
+ stage: 'dispatch' | 'judge';
2453
+ judge?: string;
2454
+ error: {
2455
+ name: string;
2456
+ message: string;
2457
+ stack?: string;
2458
+ };
2459
+ };
2460
+ cell: CampaignCellResult<TArtifact>;
2461
+ cost: CostLedgerSummary;
2462
+ }
2435
2463
  /**
2436
2464
  * Core campaign orchestrator: fan scenarios through dispatch, score with judges, aggregate bootstrap CIs, and persist reproducible `CampaignResult` records.
2437
2465
  */
@@ -4457,6 +4485,24 @@ interface RunOptimizationBaseOptions<TScenario extends Scenario, TArtifact> exte
4457
4485
  costLedger?: CostLedgerHandle;
4458
4486
  costPhase?: string;
4459
4487
  }) => Promise<unknown[]>;
4488
+ /**
4489
+ * Optional override for how the WINNER is selected among coverage-complete
4490
+ * candidates (and how the incumbent bar is set). Returns a lexicographic rank
4491
+ * key — each element higher-is-better; candidates are ranked by descending key
4492
+ * (`compareRankKeys`) and the top must STRICTLY beat the incumbent's key to
4493
+ * promote. Defaults to `[campaignMeanComposite(campaign)]`, i.e. the historical
4494
+ * scalar-mean ranking (single-element key ⇒ identical behavior).
4495
+ *
4496
+ * A binary-with-replicates consumer (e.g. swe-arena, whose ship-gate counts an
4497
+ * instance resolved only when EVERY replicate resolved) passes a fail-closed
4498
+ * key built from the SAME reduction its gate uses, so winner-selection and the
4499
+ * ship-gate rank on the identical metric and can never invert — the selector
4500
+ * cannot promote a flaky per-cell-mean candidate the gate would reject over a
4501
+ * fail-closed candidate the gate would accept. Only the winner CHOICE changes;
4502
+ * the descriptive `composite` (mean) on every record and the Pareto objective
4503
+ * vectors are untouched, so proposer diversity and reporting are unaffected.
4504
+ */
4505
+ selectionRankKey?: (campaign: CampaignResult<TArtifact, TScenario>) => number[];
4460
4506
  }
4461
4507
  type RunOptimizationOptions<TScenario extends Scenario, TArtifact> = RunOptimizationBaseOptions<TScenario, TArtifact>;
4462
4508
  interface RunOptimizationResult<TArtifact, TScenario extends Scenario> {
@@ -5487,6 +5533,10 @@ declare function selectDiscriminative(signals: ScenarioSignal[], k: number, opts
5487
5533
  * descriptive aggregate with NaN. Cells with no valid scores are skipped.
5488
5534
  * Empty ⇒ 0. */
5489
5535
  declare function campaignMeanComposite<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): number;
5536
+ /** Compare fixed-length lexicographic rank keys where each element is higher-is-better.
5537
+ * Returns a positive number when `a` ranks above `b`, negative when below, and
5538
+ * zero when equal. */
5539
+ declare function compareRankKeys(a: readonly number[], b: readonly number[]): number;
5490
5540
  interface CampaignBreakdown {
5491
5541
  /** Mean score per judge dimension across all cells. */
5492
5542
  dimensions: Record<string, number>;
@@ -6054,4 +6104,4 @@ declare function verifyCodeSurface(surface: CodeSurface, worktreeDir?: string):
6054
6104
  * identity against the checkout at `worktreeRef`. */
6055
6105
  declare function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string;
6056
6106
 
6057
- export { type AnalystArtifact, type AnalystScenario, type AnalyzeCrossSurfaceInteractionsInput, type AxisEvidence, type AxisVerdict, type BuildAnalystSurfaceDispatchOptions, type BuildEvidenceVectorOptions, type BuildLoopProvenanceArgs, type CampaignAggregates, type CampaignArtifactWriter, type CampaignBreakdown, type CampaignCellResult, type CampaignCostMeter, type CampaignResult, type CampaignRunPlan, type CampaignRunPlanCell, type CampaignScenarioIdentity, type CampaignStorage, type CampaignTokenUsage, type CampaignTraceWriter, type CodeSurface, type CodeSurfaceVerification, type CompareOptimizationMethodsOptions, type ComparisonCost, type ComponentSurface, type CostLedgerHandle, type CrossSurfaceAdditionDecision, type CrossSurfaceAdditionRejectionReason, type CrossSurfaceAttemptCompleteness, type CrossSurfaceBestSingleSelection, type CrossSurfaceBootstrapPolicy, type CrossSurfaceCandidate, type CrossSurfaceCandidateComparison, type CrossSurfaceCandidateEvidence, type CrossSurfaceCandidateOutcome, type CrossSurfaceCandidateSummary, type CrossSurfaceComponent, type CrossSurfaceComponentEvidence, type CrossSurfaceCompositionStep, type CrossSurfaceDistribution, type CrossSurfaceEligibility, type CrossSurfaceEvidenceBreakdown, type CrossSurfaceIneligibilityReason, type CrossSurfaceInteractionAwareSelection, type CrossSurfaceInteractionEffect, type CrossSurfaceInteractionPath, type CrossSurfaceInteractionReport, type CrossSurfaceInteractionTask, type CrossSurfaceNaiveStackSelection, type CrossSurfacePairCompatibility, type CrossSurfacePairEvidence, type CrossSurfacePairIncompatibilityReason, type CrossSurfacePairwiseEntry, type CrossSurfaceRankedSingle, type CrossSurfaceRelativeCost, type CrossSurfaceSelectionPolicy, type CrossSurfaceSelections, type CrossSurfaceTaskRow, type DefaultProductionGateOptions, type DimensionRegression, type DiscriminationScore, type DispatchContext, type DispatchFn, type EmitLoopProvenanceArgs, type EmitLoopProvenanceResult, type EvalFixture, type EvalFixtureFile, type EvalFixtureLoadOptions, type EvalFixtureRunPlan, type EvalFixtureScenario, type EvalFixtureValidationMode, type EvidenceVector, type ExternalOptimizationExample, type ExternalTextEvaluationResponse, type ExternalTextOptimizationMethodConfig, type ExternalTextOptimizerContext, type ExternalTextOptimizerResult, type FailureModeRecallJudgeOptions, FileSearchLedger, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaAdaptiveEngineRun, type GepaEngineOptions, type GepaEngineRun, type GepaOptimizationMethodConfig, type GepaOptimizationRecipe, type GepaRunnerCommand, type GitWorktreeAdapterOptions, type HeldOutGateOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type JudgeAggregate, type JudgeConfig, type JudgeDimension, type JudgeScore, type LabelTrust, type LabeledScenarioRecord, type LabeledScenarioSampleArgs, type LabeledScenarioSource, type LabeledScenarioStore, LabeledScenarioStoreError, type LabeledScenarioWrite, type LlmJudgeDimension, type LlmJudgeOptions, type LoadEvalFixtureScenariosOptions, type LoopProvenanceArgsFromResult, type LoopProvenanceBackend, type LoopProvenanceCandidate, type LoopProvenanceEvidence, type LoopProvenanceOptimizationMethod, type LoopProvenanceRecord, type MutableSurface, type NeutralizationGateOptions, type ObjectiveSource, type OpenAICompatibleOptimizerModel, type OpenAutoPrOptions, type OpenAutoPrResult, type OpenSearchLedgerOptions, type OptimizationMethod, type OptimizationMethodComparison, type OptimizationMethodInput, type OptimizationMethodPairwise, type OptimizationMethodProvenance, type OptimizationMethodResult, type OptimizationMethodRunOptions, type OptimizationMethodScore, type OptimizationPackageSource, type OptimizationProposer, type OptimizationTokenUsage, type OptimizerConfig, type OptimizerModelBudget, type PairedHoldout, type ParetoParent, type ParetoSignificanceGateOptions, type PendingCostCallView, type PlanCampaignRunOptions, type PlanEvalFixtureRunOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type PowerPreflight, type PowerPreflightOptions, type PremeasuredOptimizationBaseline, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type PromotionObjective, type PromotionPolicy, type ProposalTrackContext, type ProposeContext, type ProposedCandidate, type RedactionStatus, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceScenario, type RolloutArgumentDiff, type RolloutArgumentDiffOptions, type RolloutCall, type RunCampaignOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunOptimizationOptions, type RunOptimizationResult, type RunProfileMatrixOptions, type RunProfileMatrixResult, SEARCH_LEDGER_SCHEMA, type Scenario, type ScenarioAggregate, type ScenarioRollup, type ScenarioSignal, type ScoreboardRenderOptions, type ScoreboardRow, type ScoreboardSummary, type ScoredRollout, type ScoredSurfaceOutcome, type SearchAccountingAudit, type SearchArtifactRef, type SearchAttemptAccounting, type SearchCandidateDecidedEvent, type SearchCandidateLineage, type SearchCandidateRegisteredEvent, type SearchCandidateSlot, type SearchCandidateSlotClosedEvent, type SearchCandidateSurface, type SearchCompletedEvent, type SearchCostAccounting, type SearchFailureReason, type SearchLedger, type SearchLedgerAppendResult, SearchLedgerConflictError, type SearchLedgerEntry, SearchLedgerError, type SearchLedgerEvent, type SearchLedgerHash, SearchLedgerIntegrityError, type SearchLedgerReplay, type SearchModelIdentity, type SearchOperationKind, type SearchOperationRecordedEvent, type SearchPlan, type SearchPlannedEvent, type SearchPlannedOperation, type SearchPlannedTask, type SearchSourceRef, type SearchSurfaceEffect, type SearchSurfaceEvidence, type SearchSurfaceKind, type SearchTaskAttemptedEvent, type SearchTaskOutcome, type SearchTokenAccounting, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SessionScript, type SingleRunLock, type SingleRunLockOptions, type SkillOptOptimizationMethodConfig, type SkillOptRunnerCommand, type SkillOptTrainerConfig, type SurfaceProposer, type TraceSpan, type TransientFailureOptions, type UngroundedLiteralReport, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, acquireSingleRunLock, analyzeCrossSurfaceInteractions, assertCampaignDesign, assertCampaignSplitIdentity, assertCodeSurfaceIdentity, assertComponentSurface, buildAnalystSurfaceDispatch, buildEvidenceVector, buildLoopProvenanceRecord, campaignBreakdown, campaignMeanComposite, campaignMeasurementDigest, campaignScenarioIdentity, campaignSplitDigest, campaignSplitDigestFromIdentities, canonicalDigest, classifyUngroundedLiterals, codeSurfaceIdentityMaterial, compareOptimizationMethods, componentSurfaceIdentityMaterial, composeGate, costFromLedgerSummary, createReferenceEquivalenceJudge, createRunCostLedger, defaultProductionGate, detectScale, dimensionRegressions, discoverEvalFixtures, emitLoopProvenance, externalTextOptimizationMethod, failureModeRecallJudge, fsCampaignStorage, gepaOptimizationMethod, gitWorktreeAdapter, heldOutGate, heldoutSignificance, inMemoryCampaignStorage, isProposedCandidate, isTransientTransportFailure, labelTrustRank, llmJudge, loadEvalFixture, loadEvalFixtureScenarios, loopProvenanceArgsFromResult, loopProvenanceSpans, makePlaybackDispatch, neutralizationGate, neutralizeText, openAutoPr, openSearchLedger, optimizationTokenUsageFromSummary, pairHoldout, paretoPolicy, paretoSignificanceGate, planCampaignRun, planEvalFixtureRun, powerPreflight, provenanceRecordPath, provenanceSpansPath, renderScoreboardMarkdown, renderSurfaceDiff, resolveRunDir, resolveWorktreePath, rolloutArgumentDiff, runCampaign, runEval, runImprovementLoop, runOptimization, runProfileMatrix, scoreDiscrimination, scoreUserStory, scoreboardSummary, selectDiscriminative, sequentialDecide, sequentialPairedGate, skillOptOptimizationMethod, surfaceContentHash, surfaceHash, tangleTracesRoot, userStoryScoreboard, validateSearchLedgerEvent, verifyCodeSurface, verifyLoopProvenanceRecord };
6107
+ export { type AnalystArtifact, type AnalystScenario, type AnalyzeCrossSurfaceInteractionsInput, type AxisEvidence, type AxisVerdict, type BuildAnalystSurfaceDispatchOptions, type BuildEvidenceVectorOptions, type BuildLoopProvenanceArgs, type CampaignAggregates, type CampaignArtifactWriter, type CampaignBreakdown, type CampaignCellFailureReceipt, type CampaignCellResult, type CampaignCostMeter, type CampaignResult, type CampaignRunPlan, type CampaignRunPlanCell, type CampaignScenarioIdentity, type CampaignStorage, type CampaignTokenUsage, type CampaignTraceWriter, type CodeSurface, type CodeSurfaceVerification, type CompareOptimizationMethodsOptions, type ComparisonCost, type ComponentSurface, type CostLedgerHandle, type CrossSurfaceAdditionDecision, type CrossSurfaceAdditionRejectionReason, type CrossSurfaceAttemptCompleteness, type CrossSurfaceBestSingleSelection, type CrossSurfaceBootstrapPolicy, type CrossSurfaceCandidate, type CrossSurfaceCandidateComparison, type CrossSurfaceCandidateEvidence, type CrossSurfaceCandidateOutcome, type CrossSurfaceCandidateSummary, type CrossSurfaceComponent, type CrossSurfaceComponentEvidence, type CrossSurfaceCompositionStep, type CrossSurfaceDistribution, type CrossSurfaceEligibility, type CrossSurfaceEvidenceBreakdown, type CrossSurfaceIneligibilityReason, type CrossSurfaceInteractionAwareSelection, type CrossSurfaceInteractionEffect, type CrossSurfaceInteractionPath, type CrossSurfaceInteractionReport, type CrossSurfaceInteractionTask, type CrossSurfaceNaiveStackSelection, type CrossSurfacePairCompatibility, type CrossSurfacePairEvidence, type CrossSurfacePairIncompatibilityReason, type CrossSurfacePairwiseEntry, type CrossSurfaceRankedSingle, type CrossSurfaceRelativeCost, type CrossSurfaceSelectionPolicy, type CrossSurfaceSelections, type CrossSurfaceTaskRow, type DefaultProductionGateOptions, type DimensionRegression, type DiscriminationScore, type DispatchContext, type DispatchFn, type EmitLoopProvenanceArgs, type EmitLoopProvenanceResult, type EvalFixture, type EvalFixtureFile, type EvalFixtureLoadOptions, type EvalFixtureRunPlan, type EvalFixtureScenario, type EvalFixtureValidationMode, type EvidenceVector, type ExternalOptimizationExample, type ExternalTextEvaluationResponse, type ExternalTextOptimizationMethodConfig, type ExternalTextOptimizerContext, type ExternalTextOptimizerResult, type FailureModeRecallJudgeOptions, FileSearchLedger, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaAdaptiveEngineRun, type GepaEngineOptions, type GepaEngineRun, type GepaOptimizationMethodConfig, type GepaOptimizationRecipe, type GepaRunnerCommand, type GitWorktreeAdapterOptions, type HeldOutGateOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type JudgeAggregate, type JudgeConfig, type JudgeDimension, type JudgeScore, type LabelTrust, type LabeledScenarioRecord, type LabeledScenarioSampleArgs, type LabeledScenarioSource, type LabeledScenarioStore, LabeledScenarioStoreError, type LabeledScenarioWrite, type LlmJudgeDimension, type LlmJudgeOptions, type LoadEvalFixtureScenariosOptions, type LoopProvenanceArgsFromResult, type LoopProvenanceBackend, type LoopProvenanceCandidate, type LoopProvenanceEvidence, type LoopProvenanceOptimizationMethod, type LoopProvenanceRecord, type MutableSurface, type NeutralizationGateOptions, type ObjectiveSource, type OpenAICompatibleOptimizerModel, type OpenAutoPrOptions, type OpenAutoPrResult, type OpenSearchLedgerOptions, type OptimizationMethod, type OptimizationMethodComparison, type OptimizationMethodInput, type OptimizationMethodPairwise, type OptimizationMethodProvenance, type OptimizationMethodResult, type OptimizationMethodRunOptions, type OptimizationMethodScore, type OptimizationPackageSource, type OptimizationProposer, type OptimizationTokenUsage, type OptimizerConfig, type OptimizerModelBudget, type PairedHoldout, type ParetoParent, type ParetoSignificanceGateOptions, type PendingCostCallView, type PlanCampaignRunOptions, type PlanEvalFixtureRunOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type PowerPreflight, type PowerPreflightOptions, type PremeasuredOptimizationBaseline, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type PromotionObjective, type PromotionPolicy, type ProposalTrackContext, type ProposeContext, type ProposedCandidate, type RedactionStatus, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceScenario, type RolloutArgumentDiff, type RolloutArgumentDiffOptions, type RolloutCall, type RunCampaignOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunOptimizationOptions, type RunOptimizationResult, type RunProfileMatrixOptions, type RunProfileMatrixResult, SEARCH_LEDGER_SCHEMA, type Scenario, type ScenarioAggregate, type ScenarioRollup, type ScenarioSignal, type ScoreboardRenderOptions, type ScoreboardRow, type ScoreboardSummary, type ScoredRollout, type ScoredSurfaceOutcome, type SearchAccountingAudit, type SearchArtifactRef, type SearchAttemptAccounting, type SearchCandidateDecidedEvent, type SearchCandidateLineage, type SearchCandidateRegisteredEvent, type SearchCandidateSlot, type SearchCandidateSlotClosedEvent, type SearchCandidateSurface, type SearchCompletedEvent, type SearchCostAccounting, type SearchFailureReason, type SearchLedger, type SearchLedgerAppendResult, SearchLedgerConflictError, type SearchLedgerEntry, SearchLedgerError, type SearchLedgerEvent, type SearchLedgerHash, SearchLedgerIntegrityError, type SearchLedgerReplay, type SearchModelIdentity, type SearchOperationKind, type SearchOperationRecordedEvent, type SearchPlan, type SearchPlannedEvent, type SearchPlannedOperation, type SearchPlannedTask, type SearchSourceRef, type SearchSurfaceEffect, type SearchSurfaceEvidence, type SearchSurfaceKind, type SearchTaskAttemptedEvent, type SearchTaskOutcome, type SearchTokenAccounting, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SessionScript, type SingleRunLock, type SingleRunLockOptions, type SkillOptOptimizationMethodConfig, type SkillOptRunnerCommand, type SkillOptTrainerConfig, type SurfaceProposer, type TraceSpan, type TransientFailureOptions, type UngroundedLiteralReport, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, acquireSingleRunLock, analyzeCrossSurfaceInteractions, assertCampaignDesign, assertCampaignSplitIdentity, assertCodeSurfaceIdentity, assertComponentSurface, buildAnalystSurfaceDispatch, buildEvidenceVector, buildLoopProvenanceRecord, campaignBreakdown, campaignMeanComposite, campaignMeasurementDigest, campaignScenarioIdentity, campaignSplitDigest, campaignSplitDigestFromIdentities, canonicalDigest, classifyUngroundedLiterals, codeSurfaceIdentityMaterial, compareOptimizationMethods, compareRankKeys, componentSurfaceIdentityMaterial, composeGate, costFromLedgerSummary, createReferenceEquivalenceJudge, createRunCostLedger, defaultProductionGate, detectScale, dimensionRegressions, discoverEvalFixtures, emitLoopProvenance, externalTextOptimizationMethod, failureModeRecallJudge, fsCampaignStorage, gepaOptimizationMethod, gitWorktreeAdapter, heldOutGate, heldoutSignificance, inMemoryCampaignStorage, isProposedCandidate, isTransientTransportFailure, labelTrustRank, llmJudge, loadEvalFixture, loadEvalFixtureScenarios, loopProvenanceArgsFromResult, loopProvenanceSpans, makePlaybackDispatch, neutralizationGate, neutralizeText, openAutoPr, openSearchLedger, optimizationTokenUsageFromSummary, pairHoldout, paretoPolicy, paretoSignificanceGate, planCampaignRun, planEvalFixtureRun, powerPreflight, provenanceRecordPath, provenanceSpansPath, renderScoreboardMarkdown, renderSurfaceDiff, resolveRunDir, resolveWorktreePath, rolloutArgumentDiff, runCampaign, runEval, runImprovementLoop, runOptimization, runProfileMatrix, scoreDiscrimination, scoreUserStory, scoreboardSummary, selectDiscriminative, sequentialDecide, sequentialPairedGate, skillOptOptimizationMethod, surfaceContentHash, surfaceHash, tangleTracesRoot, userStoryScoreboard, validateSearchLedgerEvent, verifyCodeSurface, verifyLoopProvenanceRecord };
@@ -32,7 +32,7 @@ import {
32
32
  userStoryScoreboard,
33
33
  validateSearchLedgerEvent,
34
34
  verifyCodeSurface
35
- } from "../chunk-NGUYT5CI.js";
35
+ } from "../chunk-P6WN2KF5.js";
36
36
  import {
37
37
  acquireSingleRunLock,
38
38
  assertCodeSurfaceIdentity,
@@ -45,6 +45,7 @@ import {
45
45
  canonicalDigest,
46
46
  codeSurfaceIdentityMaterial,
47
47
  compareOptimizationMethods,
48
+ compareRankKeys,
48
49
  componentSurfaceIdentityMaterial,
49
50
  composeGate,
50
51
  costFromLedgerSummary,
@@ -78,7 +79,7 @@ import {
78
79
  surfaceContentHash,
79
80
  surfaceHash,
80
81
  verifyLoopProvenanceRecord
81
- } from "../chunk-VMUENW6F.js";
82
+ } from "../chunk-3I74FLK6.js";
82
83
  import {
83
84
  SearchLedgerConflictError,
84
85
  SearchLedgerError,
@@ -95,7 +96,7 @@ import {
95
96
  resolveRunDir,
96
97
  runCampaign,
97
98
  tangleTracesRoot
98
- } from "../chunk-UCLVDLCH.js";
99
+ } from "../chunk-ZVCHKKOP.js";
99
100
  import "../chunk-WGXIEX7P.js";
100
101
  import "../chunk-ARU2PZFM.js";
101
102
  import "../chunk-J5SQWP6Y.js";
@@ -141,6 +142,7 @@ export {
141
142
  classifyUngroundedLiterals,
142
143
  codeSurfaceIdentityMaterial,
143
144
  compareOptimizationMethods,
145
+ compareRankKeys,
144
146
  componentSurfaceIdentityMaterial,
145
147
  composeGate,
146
148
  costFromLedgerSummary,
@@ -13,7 +13,7 @@ import {
13
13
  runCampaign,
14
14
  summarizeAgentReceiptIntegrity,
15
15
  tryAcquireAtomicFileLock
16
- } from "./chunk-UCLVDLCH.js";
16
+ } from "./chunk-ZVCHKKOP.js";
17
17
  import {
18
18
  clamp01,
19
19
  combineAbortSignals,
@@ -1514,6 +1514,29 @@ function campaignMeanComposite(campaign) {
1514
1514
  }
1515
1515
  return composites.length === 0 ? 0 : composites.reduce((a, b) => a + b, 0) / composites.length;
1516
1516
  }
1517
+ function assertFiniteRankKey(key, label, expectedLength) {
1518
+ if (!Array.isArray(key) || key.length === 0) {
1519
+ throw new Error(`${label} must return a non-empty array`);
1520
+ }
1521
+ if (expectedLength !== void 0 && key.length !== expectedLength) {
1522
+ throw new Error(`${label} returned ${key.length} elements; expected ${expectedLength}`);
1523
+ }
1524
+ for (let index = 0; index < key.length; index++) {
1525
+ if (!Number.isFinite(key[index])) {
1526
+ throw new Error(`${label}[${index}] must be finite`);
1527
+ }
1528
+ }
1529
+ }
1530
+ function compareRankKeys(a, b) {
1531
+ assertFiniteRankKey(a, "rank key a");
1532
+ assertFiniteRankKey(b, "rank key b", a.length);
1533
+ for (let i = 0; i < a.length; i++) {
1534
+ const av = a[i];
1535
+ const bv = b[i];
1536
+ if (av !== bv) return av - bv;
1537
+ }
1538
+ return 0;
1539
+ }
1517
1540
  function campaignBreakdown(campaign) {
1518
1541
  const dimSums = {};
1519
1542
  const dimCounts = {};
@@ -1775,6 +1798,16 @@ async function compareOptimizationMethods(opts) {
1775
1798
  throw error;
1776
1799
  }
1777
1800
  });
1801
+ assertReportedCostWithinCeiling(
1802
+ combineCosts(
1803
+ optimized.map((result) => ({
1804
+ label: `method '${result.name}'`,
1805
+ cost: result.cost
1806
+ }))
1807
+ ).totalCostUsd,
1808
+ opts.costCeiling,
1809
+ "optimization"
1810
+ );
1778
1811
  const testCostPhase = finalCostPhase(opts, baselineSurface, optimized, seed);
1779
1812
  const baselineArr = align(
1780
1813
  await scoreOnTest(baselineSurface, "test/baseline", testCostPhase),
@@ -1869,6 +1902,7 @@ async function compareOptimizationMethods(opts) {
1869
1902
  { label: "optimization", cost: optimizationCost },
1870
1903
  { label: "final test", cost: testCost }
1871
1904
  ]);
1905
+ assertReportedCostWithinCeiling(totalCost.totalCostUsd, opts.costCeiling, "total");
1872
1906
  return {
1873
1907
  scores,
1874
1908
  best,
@@ -1885,6 +1919,14 @@ async function compareOptimizationMethods(opts) {
1885
1919
  reps: opts.reps ?? 1
1886
1920
  };
1887
1921
  }
1922
+ function assertReportedCostWithinCeiling(totalCostUsd, costCeiling, phase) {
1923
+ const tolerance = Number.EPSILON * Math.max(1, Math.abs(totalCostUsd), Math.abs(costCeiling ?? 0)) * 8;
1924
+ if (costCeiling !== void 0 && totalCostUsd > costCeiling + tolerance) {
1925
+ throw new Error(
1926
+ `compareOptimizationMethods: reported ${phase} cost ${totalCostUsd} exceeds costCeiling ${costCeiling}`
1927
+ );
1928
+ }
1929
+ }
1888
1930
  function assertOptimizationMethods(methods) {
1889
1931
  if (!Array.isArray(methods) || methods.length === 0) {
1890
1932
  throw new Error("compareOptimizationMethods: no methods to compare");
@@ -1998,6 +2040,17 @@ function assertComparisonControls(opts, seed, resamples, confidence) {
1998
2040
  "compareOptimizationMethods: dispatchRef must be trimmed and non-empty when provided"
1999
2041
  );
2000
2042
  }
2043
+ const optimizationDispatchRef = opts.optimizationRunOptions?.dispatchRef;
2044
+ if (optimizationDispatchRef !== void 0 && (typeof optimizationDispatchRef !== "string" || optimizationDispatchRef.trim().length === 0 || optimizationDispatchRef.trim() !== optimizationDispatchRef)) {
2045
+ throw new Error(
2046
+ "compareOptimizationMethods: optimizationRunOptions.dispatchRef must be trimmed and non-empty when provided"
2047
+ );
2048
+ }
2049
+ if (opts.dispatchRef !== void 0 && optimizationDispatchRef !== void 0 && opts.dispatchRef !== optimizationDispatchRef) {
2050
+ throw new Error(
2051
+ "compareOptimizationMethods: dispatchRef must match optimizationRunOptions.dispatchRef when both are provided"
2052
+ );
2053
+ }
2001
2054
  try {
2002
2055
  surfaceContentHash(opts.baselineSurface);
2003
2056
  } catch (cause) {
@@ -2169,6 +2222,7 @@ function createOptimizationMethodInput(opts, methodName, resolvedRunDir, seed, b
2169
2222
  seed,
2170
2223
  runOptions: Object.freeze({
2171
2224
  ...opts.optimizationRunOptions ?? {},
2225
+ ...opts.optimizationRunOptions?.dispatchRef === void 0 && opts.dispatchRef !== void 0 ? { dispatchRef: opts.dispatchRef } : {},
2172
2226
  ...signal ? { signal } : {}
2173
2227
  }),
2174
2228
  costLedger
@@ -3758,28 +3812,30 @@ function externalTextOptimizationMethod(config) {
3758
3812
  )
3759
3813
  );
3760
3814
  const methodDir = `${input.runDir}/external/${safePathComponent(snapshot.name)}`;
3761
- const runId = externalOptimizerRunKey({
3762
- material: {
3763
- optimizer: {
3764
- kind: snapshot.source.kind,
3765
- package: snapshot.source.package,
3766
- version: snapshot.source.version,
3767
- ...snapshot.source.sourceUrl ? { sourceUrl: snapshot.source.sourceUrl } : {},
3768
- ...snapshot.source.revision ? { revision: snapshot.source.revision } : {}
3769
- },
3770
- method: snapshot.name,
3771
- evaluationId: snapshot.evaluationId,
3772
- objective: snapshot.objective,
3773
- background: snapshot.background ?? "",
3774
- seed: input.seed,
3775
- seedCandidate,
3776
- trainSet,
3777
- selectionSet,
3778
- maxEvaluations: snapshot.maxEvaluations,
3779
- maxOptimizerCostUsd: snapshot.maxOptimizerCostUsd,
3780
- maxCandidateChars,
3781
- maxEvidenceChars
3815
+ const runMaterial = {
3816
+ optimizer: {
3817
+ kind: snapshot.source.kind,
3818
+ package: snapshot.source.package,
3819
+ version: snapshot.source.version,
3820
+ ...snapshot.source.sourceUrl ? { sourceUrl: snapshot.source.sourceUrl } : {},
3821
+ ...snapshot.source.revision ? { revision: snapshot.source.revision } : {}
3782
3822
  },
3823
+ method: snapshot.name,
3824
+ evaluationId: snapshot.evaluationId,
3825
+ dispatchRef: input.runOptions.dispatchRef ?? null,
3826
+ objective: snapshot.objective,
3827
+ background: snapshot.background ?? "",
3828
+ seed: input.seed,
3829
+ seedCandidate,
3830
+ trainSet,
3831
+ selectionSet,
3832
+ maxEvaluations: snapshot.maxEvaluations,
3833
+ maxOptimizerCostUsd: snapshot.maxOptimizerCostUsd,
3834
+ maxCandidateChars,
3835
+ maxEvidenceChars
3836
+ };
3837
+ const runId = externalOptimizerRunKey({
3838
+ material: runMaterial,
3783
3839
  attemptId,
3784
3840
  resumeEnabled: resume !== "never"
3785
3841
  });
@@ -5454,6 +5510,7 @@ function gepaOptimizationMethod(config) {
5454
5510
  runtime: runtimeIdentity,
5455
5511
  method: name,
5456
5512
  evaluationId: config.evaluationId,
5513
+ dispatchRef: input.runOptions.dispatchRef ?? null,
5457
5514
  seed: input.seed,
5458
5515
  recipe: snapshotJson(config.recipe, "GEPA run settings"),
5459
5516
  engineModules: config.engineModules ?? [],
@@ -5739,9 +5796,12 @@ async function runOptimization(opts) {
5739
5796
  const generations = [];
5740
5797
  const history = [];
5741
5798
  let currentFindings = opts.findings ?? [];
5799
+ const selectionRankKey = opts.selectionRankKey ?? ((campaign) => [campaignMeanComposite(campaign)]);
5742
5800
  let winnerSurface = opts.baselineSurface;
5743
5801
  let winnerSurfaceHash = surfaceHash(opts.baselineSurface);
5744
5802
  let winnerComposite = campaignMeanComposite(baselineCampaign);
5803
+ let winnerRankKey = selectionRankKey(baselineCampaign);
5804
+ assertFiniteRankKey(winnerRankKey, "selectionRankKey for baseline");
5745
5805
  const baselineOutcome = toScoredSurfaceOutcome(
5746
5806
  winnerSurfaceHash,
5747
5807
  baselineCampaign,
@@ -5808,6 +5868,12 @@ async function runOptimization(opts) {
5808
5868
  runDir: `${opts.runDir}/gen-${gen}/candidate-${i}`
5809
5869
  });
5810
5870
  const composite = campaignMeanComposite(campaign);
5871
+ const rankKey = selectionRankKey(campaign);
5872
+ assertFiniteRankKey(
5873
+ rankKey,
5874
+ `selectionRankKey for generation ${gen} candidate ${i}`,
5875
+ winnerRankKey.length
5876
+ );
5811
5877
  const coverage = campaignCoverage(
5812
5878
  campaign.cells,
5813
5879
  opts.scenarios,
@@ -5821,6 +5887,7 @@ async function runOptimization(opts) {
5821
5887
  rationale,
5822
5888
  campaign,
5823
5889
  composite,
5890
+ rankKey,
5824
5891
  coverage
5825
5892
  };
5826
5893
  }
@@ -5835,16 +5902,17 @@ async function runOptimization(opts) {
5835
5902
  }
5836
5903
  surfaceResults.sort((a, b) => {
5837
5904
  if (a.coverage.complete !== b.coverage.complete) return a.coverage.complete ? -1 : 1;
5838
- return b.composite - a.composite;
5905
+ return compareRankKeys(b.rankKey, a.rankKey);
5839
5906
  });
5840
5907
  const eligibleResults = surfaceResults.filter((result) => result.coverage.complete);
5841
5908
  const top = eligibleResults[0];
5842
- const promoted = top && top.composite > winnerComposite ? [top] : [];
5909
+ const promoted = top && compareRankKeys(top.rankKey, winnerRankKey) > 0 ? [top] : [];
5843
5910
  if (promoted[0]) {
5844
5911
  const top2 = promoted[0];
5845
5912
  winnerSurface = top2.surface;
5846
5913
  winnerSurfaceHash = top2.surfaceHash;
5847
5914
  winnerComposite = top2.composite;
5915
+ winnerRankKey = top2.rankKey;
5848
5916
  winnerOutcome = toScoredSurfaceOutcome(top2.surfaceHash, top2.campaign, top2.coverage, gen);
5849
5917
  winnerLabel = top2.label || void 0;
5850
5918
  winnerRationale = top2.rationale || void 0;
@@ -6037,7 +6105,7 @@ async function runImprovementLoop(opts) {
6037
6105
  const dispatchTimeoutMs = opts.dispatchTimeoutMs ?? DEFAULT_DISPATCH_TIMEOUT_MS;
6038
6106
  const optimization = await runOptimization({ ...opts, dispatchTimeoutMs, costLedger });
6039
6107
  const winnerIsBaseline = optimization.winnerSurfaceHash === surfaceHash(opts.baselineSurface);
6040
- const { runCampaign: runCampaign2 } = await import("./run-campaign-LVFKZCEU.js");
6108
+ const { runCampaign: runCampaign2 } = await import("./run-campaign-FFRM3RH5.js");
6041
6109
  const holdoutDeferred = (opts.holdout ?? "measured") === "deferred";
6042
6110
  const baselineOnHoldout = holdoutDeferred ? await runCampaign2({
6043
6111
  ...opts,
@@ -6980,6 +7048,7 @@ function skillOptOptimizationMethod(config) {
6980
7048
  runtime: runtimeIdentity,
6981
7049
  method: name,
6982
7050
  evaluationId: config.evaluationId,
7051
+ dispatchRef: input.runOptions.dispatchRef ?? null,
6983
7052
  seed: input.seed,
6984
7053
  trainer: snapshotJson(config.trainer, "SkillOpt run settings"),
6985
7054
  objective: config.objective,
@@ -7228,6 +7297,7 @@ export {
7228
7297
  buildReflectionPrompt,
7229
7298
  parseReflectionResponse,
7230
7299
  campaignMeanComposite,
7300
+ compareRankKeys,
7231
7301
  campaignBreakdown,
7232
7302
  assertCodeSurfaceIdentity,
7233
7303
  assertComponentSurface,
@@ -7271,4 +7341,4 @@ export {
7271
7341
  emitLoopProvenance,
7272
7342
  skillOptOptimizationMethod
7273
7343
  };
7274
- //# sourceMappingURL=chunk-VMUENW6F.js.map
7344
+ //# sourceMappingURL=chunk-3I74FLK6.js.map