@tangle-network/agent-eval 0.122.1 → 0.122.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/analyst/index.js +4 -5
  3. package/dist/analyst/index.js.map +1 -1
  4. package/dist/benchmarks/index.js +6 -7
  5. package/dist/campaign/index.d.ts +25 -3
  6. package/dist/campaign/index.js +5 -6
  7. package/dist/{chunk-3A246TSA.js → chunk-BD2OK6ZW.js} +2 -2
  8. package/dist/{chunk-VZ6VKOJT.js → chunk-DHJJACEX.js} +90 -38
  9. package/dist/{chunk-VZ6VKOJT.js.map → chunk-DHJJACEX.js.map} +1 -1
  10. package/dist/{chunk-S5TT5R3L.js → chunk-EAWKAVID.js} +75 -2
  11. package/dist/chunk-EAWKAVID.js.map +1 -0
  12. package/dist/{chunk-TDHX3BVA.js → chunk-IDC74VDL.js} +62 -47
  13. package/dist/chunk-IDC74VDL.js.map +1 -0
  14. package/dist/{chunk-XDIRG3TO.js → chunk-N3QPYIVG.js} +201 -103
  15. package/dist/chunk-N3QPYIVG.js.map +1 -0
  16. package/dist/{chunk-4I2E3LLO.js → chunk-NMN4WGSJ.js} +2 -2
  17. package/dist/{chunk-PICTDURQ.js → chunk-OZFTLMGS.js} +2 -2
  18. package/dist/{chunk-QWMPPZ3X.js → chunk-SFXDMFGV.js} +2 -2
  19. package/dist/{chunk-P62I523A.js → chunk-ULW7AATT.js} +4 -6
  20. package/dist/{chunk-P62I523A.js.map → chunk-ULW7AATT.js.map} +1 -1
  21. package/dist/{chunk-JHOJHHU7.js → chunk-ZMXDQ4K7.js} +8 -5
  22. package/dist/{chunk-JHOJHHU7.js.map → chunk-ZMXDQ4K7.js.map} +1 -1
  23. package/dist/cli.js +2 -2
  24. package/dist/contract/index.d.ts +18 -0
  25. package/dist/contract/index.js +6 -6
  26. package/dist/fuzz.js +1 -1
  27. package/dist/index.d.ts +7 -1
  28. package/dist/index.js +12 -12
  29. package/dist/index.js.map +1 -1
  30. package/dist/openapi.json +1 -1
  31. package/dist/{run-campaign-HNFPJET4.js → run-campaign-2YJ3Z6JS.js} +3 -3
  32. package/dist/wire/index.js +2 -2
  33. package/docs/eval-surface-map.md +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-3YYRZDON.js +0 -45
  36. package/dist/chunk-3YYRZDON.js.map +0 -1
  37. package/dist/chunk-S5TT5R3L.js.map +0 -1
  38. package/dist/chunk-TDHX3BVA.js.map +0 -1
  39. package/dist/chunk-XDIRG3TO.js.map +0 -1
  40. /package/dist/{chunk-3A246TSA.js.map → chunk-BD2OK6ZW.js.map} +0 -0
  41. /package/dist/{chunk-4I2E3LLO.js.map → chunk-NMN4WGSJ.js.map} +0 -0
  42. /package/dist/{chunk-PICTDURQ.js.map → chunk-OZFTLMGS.js.map} +0 -0
  43. /package/dist/{chunk-QWMPPZ3X.js.map → chunk-SFXDMFGV.js.map} +0 -0
  44. /package/dist/{run-campaign-HNFPJET4.js.map → run-campaign-2YJ3Z6JS.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,12 @@ All notable changes to `@tangle-network/agent-eval` and its sibling `agent-eval-
4
4
 
5
5
  ---
6
6
 
7
+ ## [0.122.2] — 2026-07-17 — premeasured optimization continuation
8
+
9
+ ### Added
10
+
11
+ - `runOptimization()` accepts a surface-bound, split-validated complete campaign as `premeasuredBaseline`, preserves its artifacts for analysis, and skips duplicate baseline dispatch.
12
+
7
13
  ## [0.121.0] — 2026-07-15 — one measured-comparison contract
8
14
 
9
15
  ### Changed
@@ -9,15 +9,14 @@ import {
9
9
  diffFindings,
10
10
  emitSkillUsageFindings,
11
11
  runSemanticConceptJudge
12
- } from "../chunk-P62I523A.js";
12
+ } from "../chunk-ULW7AATT.js";
13
13
  import {
14
14
  behavioralAnalyst,
15
15
  buildDefaultAnalystRegistry,
16
16
  createChatClient,
17
17
  deriveEfficiencyFindings
18
- } from "../chunk-QWMPPZ3X.js";
18
+ } from "../chunk-SFXDMFGV.js";
19
19
  import "../chunk-HHWE3POT.js";
20
- import "../chunk-3YYRZDON.js";
21
20
  import {
22
21
  ANALYST_SEVERITIES,
23
22
  AnalystRegistry,
@@ -72,11 +71,11 @@ import {
72
71
  validatePolicyEdit,
73
72
  validatePolicyEditCandidateRecord,
74
73
  validateUsageSettlementTimeout
75
- } from "../chunk-S5TT5R3L.js";
74
+ } from "../chunk-EAWKAVID.js";
76
75
  import "../chunk-NJC7U437.js";
77
76
  import {
78
77
  CostLedger
79
- } from "../chunk-JHOJHHU7.js";
78
+ } from "../chunk-ZMXDQ4K7.js";
80
79
  import "../chunk-VI2UW6B6.js";
81
80
  import "../chunk-PXD6ZFNY.js";
82
81
  import "../chunk-PC4UYEBM.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/analyst/adapters.ts"],"sourcesContent":["/**\n * Adapter factories — lift each existing agent-eval primitive into the\n * Analyst contract without re-implementing it.\n *\n * Five primitives, five factories. Each one:\n * - Builds an Analyst with a stable id (caller chooses; defaults\n * given), a sensible default `inputKind`, a version derived from\n * the wrapped primitive's version + an adapter revision, and an\n * `analyze()` that calls the primitive and lifts its output to\n * AnalystFinding[] using `makeFinding()`.\n * - Maps severities: the existing `Severity` ('critical' | 'major' |\n * 'minor' | 'info') projects onto AnalystSeverity ('critical' |\n * 'high' | 'medium' | 'low' | 'info'); 'major' → 'high', 'minor' →\n * 'medium'. Domain analysts that want finer-grained mapping override.\n *\n * Adapters never own state. Calling the same factory twice with the\n * same primitive instance is safe.\n */\n\nimport { CostLedger } from '../cost-ledger'\nimport type {\n Finding as LayerFinding,\n Severity as LayerSeverity,\n MultiLayerVerifier,\n VerifyOptions,\n} from '../multi-layer-verifier'\nimport { RunCritic, type RunTrace } from '../run-critic'\nimport {\n runSemanticConceptJudge,\n SEMANTIC_CONCEPT_JUDGE_VERSION,\n type SemanticConceptJudgeInput,\n type SemanticConceptJudgeOptions,\n type SemanticConceptJudgeResult,\n} from '../semantic-concept-judge'\nimport type { JudgeFn, JudgeInput, JudgeScore, TCloud } from '../types'\nimport type { Analyst, AnalystFinding, AnalystSeverity } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\nconst ADAPTER_REV = '1'\n\n// ── Severity bridges ───────────────────────────────────────────────\n\nexport function liftSeverity(s: LayerSeverity): AnalystSeverity {\n switch (s) {\n case 'critical':\n return 'critical'\n case 'major':\n return 'high'\n case 'minor':\n return 'medium'\n case 'info':\n return 'info'\n }\n}\n\n// ── 1. MultiLayerVerifier → Analyst ─────────────────────────────────\n\nexport interface VerifierAdapterOpts<Env> {\n id?: string\n area?: string\n verifier: MultiLayerVerifier<Env>\n /**\n * The verifier expects an `env` per run. Adapters take it from\n * `AnalystRunInputs.custom[<id>]` via the registry's 'custom' routing.\n */\n options?: Omit<VerifyOptions<Env>, 'env'>\n}\n\nexport function createVerifierAdapter<Env>(opts: VerifierAdapterOpts<Env>): Analyst<Env> {\n const id = opts.id ?? 'multi-layer-verifier'\n const area = opts.area ?? 'verification'\n return {\n id,\n description:\n \"Runs a MultiLayerVerifier and lifts each layer's findings into the analyst envelope.\",\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: `verifier-${ADAPTER_REV}`,\n async analyze(env, ctx) {\n const report = await opts.verifier.run({ env, ...opts.options })\n const out: AnalystFinding[] = []\n for (const layer of report.layers) {\n for (const finding of layer.findings) {\n out.push(liftLayerFinding(id, area, layer.layer, finding))\n }\n // Layer-level signal: a failed/error layer is itself a finding\n // even if it didn't emit per-finding rows.\n if (layer.status === 'fail' || layer.status === 'error' || layer.status === 'timeout') {\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: layer.layer,\n claim: `layer \"${layer.layer}\" ${layer.status}: ${layer.reason ?? 'no reason given'}`,\n severity:\n layer.status === 'error' ? 'high' : layer.status === 'timeout' ? 'medium' : 'high',\n confidence: 1,\n evidence_refs: [],\n metadata: {\n layer_status: layer.status,\n duration_ms: layer.durationMs,\n score: layer.score,\n diagnostics: layer.diagnostics,\n },\n }),\n )\n }\n }\n ctx.log?.('verifier complete', {\n layers: report.layers.length,\n blended: report.blendedScore,\n all_pass: report.allPass,\n })\n return out\n },\n }\n}\n\nfunction liftLayerFinding(\n analyst_id: string,\n area: string,\n layer: string,\n f: LayerFinding,\n): AnalystFinding {\n return makeFinding({\n analyst_id,\n area,\n subject: f.layer ?? layer,\n claim: f.message,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: f.evidence\n ? [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }]\n : [],\n metadata: f.detail,\n })\n}\n\n// ── 2. RunCritic → Analyst ──────────────────────────────────────────\n\nexport interface RunCriticAdapterOpts {\n id?: string\n area?: string\n critic?: RunCritic\n /** Optional threshold below which a dimension is reported as a finding. Default 0.5. */\n threshold?: number\n}\n\nexport function createRunCriticAdapter(opts: RunCriticAdapterOpts = {}): Analyst<RunTrace> {\n const id = opts.id ?? 'run-critic'\n const area = opts.area ?? 'run-quality'\n const critic = opts.critic ?? new RunCritic()\n const threshold = opts.threshold ?? 0.5\n return {\n id,\n description:\n 'Scores a single run across success / grounding / drift / tool-quality and surfaces below-threshold dimensions.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: `run-critic-${ADAPTER_REV}`,\n async analyze(trace) {\n const score = critic.scoreTrace(trace)\n const out: AnalystFinding[] = []\n const dims: Array<[keyof typeof score, AnalystSeverity, string]> = [\n ['success', 'critical', 'run did not complete successfully'],\n ['goalProgress', 'high', 'goal progress is low'],\n ['repoGroundedness', 'high', 'output is poorly grounded in the repository'],\n ['toolUseQuality', 'medium', 'tool use quality is low'],\n ['patchQuality', 'medium', 'no real patch/edit evidence'],\n ['testReality', 'high', 'no real test/build evidence'],\n ['finalGate', 'critical', 'final gate is blocking'],\n ]\n for (const [dim, sev, msg] of dims) {\n const value = score[dim] as number\n if (typeof value === 'number' && value < threshold) {\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: dim,\n claim: msg,\n rationale: `${dim}=${value.toFixed(2)} below threshold ${threshold}`,\n severity: sev,\n confidence: 1,\n evidence_refs: [],\n metadata: { dimension: dim, value, threshold, run_id: trace.run.runId },\n }),\n )\n }\n }\n // Drift penalty is high → surface as a finding (inverse threshold).\n if (score.driftPenalty > 1 - threshold) {\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: 'drift',\n claim: 'agent output drifted from repository signal',\n rationale: `driftPenalty=${score.driftPenalty.toFixed(2)}`,\n severity: 'medium',\n confidence: 0.9,\n evidence_refs: [],\n metadata: { drift_penalty: score.driftPenalty, notes: score.notes },\n }),\n )\n }\n return out\n },\n }\n}\n\n// ── 3. JudgeFn → Analyst ────────────────────────────────────────────\n\nexport interface JudgeAdapterOpts {\n id?: string\n area?: string\n judge: JudgeFn\n /** TCloud handle the JudgeFn calls. */\n tcloud: TCloud\n /** Optional cost classification — most judges call an LLM. */\n cost?: Analyst['cost']\n /** Optional threshold below which a JudgeScore becomes a finding. Default 6 (on 0-10 scale). */\n threshold?: number\n}\n\nexport function createJudgeAdapter(opts: JudgeAdapterOpts): Analyst<JudgeInput> {\n const id = opts.id ?? 'judge'\n const area = opts.area ?? 'judge'\n const threshold = opts.threshold ?? 6\n return {\n id,\n description:\n 'Wraps an agent-eval JudgeFn into an analyst; below-threshold dimensions surface as findings.',\n inputKind: 'judge-input',\n cost: opts.cost ?? { kind: 'llm' },\n version: `judge-${ADAPTER_REV}`,\n async analyze(input) {\n const scores = await opts.judge(opts.tcloud, input)\n return scores\n .filter((s) => normalize10(s.score) < threshold)\n .map((s) => liftJudgeScore(id, area, s))\n },\n }\n}\n\nfunction normalize10(s: number): number {\n // JudgeScore convention is 0-10 but some judges emit 0-1. Coerce to 0-10.\n return s <= 1 ? s * 10 : s\n}\n\nfunction liftJudgeScore(analyst_id: string, area: string, s: JudgeScore): AnalystFinding {\n const score10 = normalize10(s.score)\n const severity: AnalystSeverity =\n score10 < 3 ? 'critical' : score10 < 5 ? 'high' : score10 < 7 ? 'medium' : 'low'\n return makeFinding({\n analyst_id,\n area,\n subject: s.dimension,\n claim: `${s.judgeName}/${s.dimension} scored ${score10.toFixed(1)}/10`,\n rationale: s.reasoning,\n severity,\n confidence: 0.8,\n evidence_refs: s.evidence\n ? [{ kind: 'artifact', uri: 'inline:evidence', excerpt: s.evidence }]\n : [],\n // Provenance: this finding IS a judge verdict (an acceptance score), not an\n // observation of behavior. The steer firewall (assertNoJudgeVerdict) rejects\n // it from steering — even when it cites an artifact above — because letting a\n // verdict steer the next attempt is the held-out judge leaking into the loop.\n derived_from_judge: true,\n metadata: { judge_name: s.judgeName, dimension: s.dimension, score_10: score10 },\n })\n}\n\n// ── 4. SemanticConceptJudge → Analyst ──────────────────────────────\n\nexport interface SemanticConceptJudgeAdapterOpts {\n id?: string\n area?: string\n /** Registry context owns cancellation and the per-analyst cost ledger. */\n options?: Omit<SemanticConceptJudgeOptions, 'costLedger' | 'signal'>\n /** Maximum post-cancellation wait for a provider receipt. Default 5 seconds. */\n settlementTimeoutMs?: number\n}\n\nexport function createSemanticConceptJudgeAdapter(\n opts: SemanticConceptJudgeAdapterOpts = {},\n): Analyst<SemanticConceptJudgeInput> {\n const id = opts.id ?? 'semantic-concept-judge'\n const area = opts.area ?? 'concept-coverage'\n const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs)\n return {\n id,\n description:\n 'Runs the semantic-concept judge and surfaces missing / weak concepts as findings.',\n inputKind: 'custom',\n cost: {\n kind: 'llm',\n models: opts.options?.model ? [opts.options.model] : undefined,\n settlement_timeout_ms: settlementTimeoutMs,\n },\n version: `${SEMANTIC_CONCEPT_JUDGE_VERSION}-adapter-${ADAPTER_REV}`,\n async analyze(input, ctx) {\n const costLedger = new CostLedger(ctx.budgetUsd)\n let result: SemanticConceptJudgeResult\n try {\n result = await runSemanticConceptJudge(input, {\n ...opts.options,\n costLedger,\n signal: ctx.signal,\n })\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n channel: 'judge',\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n ctx.log?.('semantic-concept judge provider settlement timed out', {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n ctx.recordUsage?.(usage.receipt)\n }\n if (!result.available) {\n return [\n makeFinding({\n analyst_id: id,\n area,\n claim: 'semantic-concept judge unavailable',\n rationale: result.error,\n severity: 'info',\n confidence: 1,\n evidence_refs: [],\n metadata: { reason: result.error },\n }),\n ]\n }\n const out: AnalystFinding[] = []\n for (const f of result.findings) {\n // Only surface gaps: missing concepts or low scores. Concepts at\n // 7+/10 with present=true are not findings — they're successes.\n if (f.present && f.score >= 7) continue\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: f.concept,\n claim: f.present\n ? `concept \"${f.concept}\" is weak (${f.score}/10)`\n : `concept \"${f.concept}\" is missing`,\n rationale: f.evidence,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }],\n metadata: {\n concept: f.concept,\n present: f.present,\n score_10: f.score,\n },\n }),\n )\n }\n return out\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,cAAc;AAIb,SAAS,aAAa,GAAmC;AAC9D,UAAQ,GAAG;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EACX;AACF;AAeO,SAAS,sBAA2B,MAA8C;AACvF,QAAM,KAAK,KAAK,MAAM;AACtB,QAAM,OAAO,KAAK,QAAQ;AAC1B,SAAO;AAAA,IACL;AAAA,IACA,aACE;AAAA,IACF,WAAW;AAAA,IACX,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AA,MACjC;AACA,UAAI,CAAC,OAAO,WAAW;AACrB,eAAO;AAAA,UACL,YAAY;AAAA,YACV,YAAY;AAAA,YACZ;AAAA,YACA,OAAO;AAAA,YACP,WAAW,OAAO;AAAA,YAClB,UAAU;AAAA,YACV,YAAY;AAAA,YACZ,eAAe,CAAC;AAAA,YAChB,UAAU,EAAE,QAAQ,OAAO,MAAM;AAAA,UACnC,CAAC;AAAA,QACH;AAAA,MACF;AACA,YAAM,MAAwB,CAAC;AAC/B,iBAAW,KAAK,OAAO,UAAU;AAG/B,YAAI,EAAE,WAAW,EAAE,SAAS,EAAG;AAC/B,YAAI;AAAA,UACF,YAAY;AAAA,YACV,YAAY;AAAA,YACZ;AAAA,YACA,SAAS,EAAE;AAAA,YACX,OAAO,EAAE,UACL,YAAY,EAAE,OAAO,cAAc,EAAE,KAAK,SAC1C,YAAY,EAAE,OAAO;AAAA,YACzB,WAAW,EAAE;AAAA,YACb,UAAU,aAAa,EAAE,QAAQ;AAAA,YACjC,YAAY;AAAA,YACZ,eAAe,CAAC,EAAE,MAAM,YAAY,KAAK,mBAAmB,SAAS,EAAE,SAAS,CAAC;AAAA,YACjF,UAAU;AAAA,cACR,SAAS,EAAE;AAAA,cACX,SAAS,EAAE;AAAA,cACX,UAAU,EAAE;AAAA,YACd;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/analyst/adapters.ts"],"sourcesContent":["/**\n * Adapter factories — lift each existing agent-eval primitive into the\n * Analyst contract without re-implementing it.\n *\n * Five primitives, five factories. Each one:\n * - Builds an Analyst with a stable id (caller chooses; defaults\n * given), a sensible default `inputKind`, a version derived from\n * the wrapped primitive's version + an adapter revision, and an\n * `analyze()` that calls the primitive and lifts its output to\n * AnalystFinding[] using `makeFinding()`.\n * - Maps severities: the existing `Severity` ('critical' | 'major' |\n * 'minor' | 'info') projects onto AnalystSeverity ('critical' |\n * 'high' | 'medium' | 'low' | 'info'); 'major' → 'high', 'minor' →\n * 'medium'. Domain analysts that want finer-grained mapping override.\n *\n * Adapters never own state. Calling the same factory twice with the\n * same primitive instance is safe.\n */\n\nimport { CostLedger } from '../cost-ledger'\nimport type {\n Finding as LayerFinding,\n Severity as LayerSeverity,\n MultiLayerVerifier,\n VerifyOptions,\n} from '../multi-layer-verifier'\nimport { RunCritic, type RunTrace } from '../run-critic'\nimport {\n runSemanticConceptJudge,\n SEMANTIC_CONCEPT_JUDGE_VERSION,\n type SemanticConceptJudgeInput,\n type SemanticConceptJudgeOptions,\n type SemanticConceptJudgeResult,\n} from '../semantic-concept-judge'\nimport type { JudgeFn, JudgeInput, JudgeScore, TCloud } from '../types'\nimport type { Analyst, AnalystFinding, AnalystSeverity } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\nconst ADAPTER_REV = '1'\n\n// ── Severity bridges ───────────────────────────────────────────────\n\nexport function liftSeverity(s: LayerSeverity): AnalystSeverity {\n switch (s) {\n case 'critical':\n return 'critical'\n case 'major':\n return 'high'\n case 'minor':\n return 'medium'\n case 'info':\n return 'info'\n }\n}\n\n// ── 1. MultiLayerVerifier → Analyst ─────────────────────────────────\n\nexport interface VerifierAdapterOpts<Env> {\n id?: string\n area?: string\n verifier: MultiLayerVerifier<Env>\n /**\n * The verifier expects an `env` per run. Adapters take it from\n * `AnalystRunInputs.custom[<id>]` via the registry's 'custom' routing.\n */\n options?: Omit<VerifyOptions<Env>, 'env'>\n}\n\nexport function createVerifierAdapter<Env>(opts: VerifierAdapterOpts<Env>): Analyst<Env> {\n const id = opts.id ?? 'multi-layer-verifier'\n const area = opts.area ?? 'verification'\n return {\n id,\n description:\n \"Runs a MultiLayerVerifier and lifts each layer's findings into the analyst envelope.\",\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: `verifier-${ADAPTER_REV}`,\n async analyze(env, ctx) {\n const report = await opts.verifier.run({ env, ...opts.options })\n const out: AnalystFinding[] = []\n for (const layer of report.layers) {\n for (const finding of layer.findings) {\n out.push(liftLayerFinding(id, area, layer.layer, finding))\n }\n // Layer-level signal: a failed/error layer is itself a finding\n // even if it didn't emit per-finding rows.\n if (layer.status === 'fail' || layer.status === 'error' || layer.status === 'timeout') {\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: layer.layer,\n claim: `layer \"${layer.layer}\" ${layer.status}: ${layer.reason ?? 'no reason given'}`,\n severity:\n layer.status === 'error' ? 'high' : layer.status === 'timeout' ? 'medium' : 'high',\n confidence: 1,\n evidence_refs: [],\n metadata: {\n layer_status: layer.status,\n duration_ms: layer.durationMs,\n score: layer.score,\n diagnostics: layer.diagnostics,\n },\n }),\n )\n }\n }\n ctx.log?.('verifier complete', {\n layers: report.layers.length,\n blended: report.blendedScore,\n all_pass: report.allPass,\n })\n return out\n },\n }\n}\n\nfunction liftLayerFinding(\n analyst_id: string,\n area: string,\n layer: string,\n f: LayerFinding,\n): AnalystFinding {\n return makeFinding({\n analyst_id,\n area,\n subject: f.layer ?? layer,\n claim: f.message,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: f.evidence\n ? [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }]\n : [],\n metadata: f.detail,\n })\n}\n\n// ── 2. RunCritic → Analyst ──────────────────────────────────────────\n\nexport interface RunCriticAdapterOpts {\n id?: string\n area?: string\n critic?: RunCritic\n /** Optional threshold below which a dimension is reported as a finding. Default 0.5. */\n threshold?: number\n}\n\nexport function createRunCriticAdapter(opts: RunCriticAdapterOpts = {}): Analyst<RunTrace> {\n const id = opts.id ?? 'run-critic'\n const area = opts.area ?? 'run-quality'\n const critic = opts.critic ?? new RunCritic()\n const threshold = opts.threshold ?? 0.5\n return {\n id,\n description:\n 'Scores a single run across success / grounding / drift / tool-quality and surfaces below-threshold dimensions.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: `run-critic-${ADAPTER_REV}`,\n async analyze(trace) {\n const score = critic.scoreTrace(trace)\n const out: AnalystFinding[] = []\n const dims: Array<[keyof typeof score, AnalystSeverity, string]> = [\n ['success', 'critical', 'run did not complete successfully'],\n ['goalProgress', 'high', 'goal progress is low'],\n ['repoGroundedness', 'high', 'output is poorly grounded in the repository'],\n ['toolUseQuality', 'medium', 'tool use quality is low'],\n ['patchQuality', 'medium', 'no real patch/edit evidence'],\n ['testReality', 'high', 'no real test/build evidence'],\n ['finalGate', 'critical', 'final gate is blocking'],\n ]\n for (const [dim, sev, msg] of dims) {\n const value = score[dim] as number\n if (typeof value === 'number' && value < threshold) {\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: dim,\n claim: msg,\n rationale: `${dim}=${value.toFixed(2)} below threshold ${threshold}`,\n severity: sev,\n confidence: 1,\n evidence_refs: [],\n metadata: { dimension: dim, value, threshold, run_id: trace.run.runId },\n }),\n )\n }\n }\n // Drift penalty is high → surface as a finding (inverse threshold).\n if (score.driftPenalty > 1 - threshold) {\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: 'drift',\n claim: 'agent output drifted from repository signal',\n rationale: `driftPenalty=${score.driftPenalty.toFixed(2)}`,\n severity: 'medium',\n confidence: 0.9,\n evidence_refs: [],\n metadata: { drift_penalty: score.driftPenalty, notes: score.notes },\n }),\n )\n }\n return out\n },\n }\n}\n\n// ── 3. JudgeFn → Analyst ────────────────────────────────────────────\n\nexport interface JudgeAdapterOpts {\n id?: string\n area?: string\n judge: JudgeFn\n /** TCloud handle the JudgeFn calls. */\n tcloud: TCloud\n /** Optional cost classification — most judges call an LLM. */\n cost?: Analyst['cost']\n /** Optional threshold below which a JudgeScore becomes a finding. Default 6 (on 0-10 scale). */\n threshold?: number\n}\n\nexport function createJudgeAdapter(opts: JudgeAdapterOpts): Analyst<JudgeInput> {\n const id = opts.id ?? 'judge'\n const area = opts.area ?? 'judge'\n const threshold = opts.threshold ?? 6\n return {\n id,\n description:\n 'Wraps an agent-eval JudgeFn into an analyst; below-threshold dimensions surface as findings.',\n inputKind: 'judge-input',\n cost: opts.cost ?? { kind: 'llm' },\n version: `judge-${ADAPTER_REV}`,\n async analyze(input) {\n const scores = await opts.judge(opts.tcloud, input)\n return scores\n .filter((s) => normalize10(s.score) < threshold)\n .map((s) => liftJudgeScore(id, area, s))\n },\n }\n}\n\nfunction normalize10(s: number): number {\n // JudgeScore convention is 0-10 but some judges emit 0-1. Coerce to 0-10.\n return s <= 1 ? s * 10 : s\n}\n\nfunction liftJudgeScore(analyst_id: string, area: string, s: JudgeScore): AnalystFinding {\n const score10 = normalize10(s.score)\n const severity: AnalystSeverity =\n score10 < 3 ? 'critical' : score10 < 5 ? 'high' : score10 < 7 ? 'medium' : 'low'\n return makeFinding({\n analyst_id,\n area,\n subject: s.dimension,\n claim: `${s.judgeName}/${s.dimension} scored ${score10.toFixed(1)}/10`,\n rationale: s.reasoning,\n severity,\n confidence: 0.8,\n evidence_refs: s.evidence\n ? [{ kind: 'artifact', uri: 'inline:evidence', excerpt: s.evidence }]\n : [],\n // Provenance: this finding IS a judge verdict (an acceptance score), not an\n // observation of behavior. The steer firewall (assertNoJudgeVerdict) rejects\n // it from steering — even when it cites an artifact above — because letting a\n // verdict steer the next attempt is the held-out judge leaking into the loop.\n derived_from_judge: true,\n metadata: { judge_name: s.judgeName, dimension: s.dimension, score_10: score10 },\n })\n}\n\n// ── 4. SemanticConceptJudge → Analyst ──────────────────────────────\n\nexport interface SemanticConceptJudgeAdapterOpts {\n id?: string\n area?: string\n /** Registry context owns cancellation and the per-analyst cost ledger. */\n options?: Omit<SemanticConceptJudgeOptions, 'costLedger' | 'signal'>\n /** Maximum post-cancellation wait for a provider receipt. Default 5 seconds. */\n settlementTimeoutMs?: number\n}\n\nexport function createSemanticConceptJudgeAdapter(\n opts: SemanticConceptJudgeAdapterOpts = {},\n): Analyst<SemanticConceptJudgeInput> {\n const id = opts.id ?? 'semantic-concept-judge'\n const area = opts.area ?? 'concept-coverage'\n const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs)\n return {\n id,\n description:\n 'Runs the semantic-concept judge and surfaces missing / weak concepts as findings.',\n inputKind: 'custom',\n cost: {\n kind: 'llm',\n models: opts.options?.model ? [opts.options.model] : undefined,\n settlement_timeout_ms: settlementTimeoutMs,\n },\n version: `${SEMANTIC_CONCEPT_JUDGE_VERSION}-adapter-${ADAPTER_REV}`,\n async analyze(input, ctx) {\n const costLedger = new CostLedger(ctx.budgetUsd)\n let result: SemanticConceptJudgeResult\n try {\n result = await runSemanticConceptJudge(input, {\n ...opts.options,\n costLedger,\n signal: ctx.signal,\n })\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n channel: 'judge',\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n ctx.log?.('semantic-concept judge provider settlement timed out', {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n ctx.recordUsage?.(usage.receipt)\n }\n if (!result.available) {\n return [\n makeFinding({\n analyst_id: id,\n area,\n claim: 'semantic-concept judge unavailable',\n rationale: result.error,\n severity: 'info',\n confidence: 1,\n evidence_refs: [],\n metadata: { reason: result.error },\n }),\n ]\n }\n const out: AnalystFinding[] = []\n for (const f of result.findings) {\n // Only surface gaps: missing concepts or low scores. Concepts at\n // 7+/10 with present=true are not findings — they're successes.\n if (f.present && f.score >= 7) continue\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: f.concept,\n claim: f.present\n ? `concept \"${f.concept}\" is weak (${f.score}/10)`\n : `concept \"${f.concept}\" is missing`,\n rationale: f.evidence,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }],\n metadata: {\n concept: f.concept,\n present: f.present,\n score_10: f.score,\n },\n }),\n )\n }\n return out\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -16,16 +16,15 @@ import {
16
16
  routing_exports,
17
17
  runBenchmarkAdapter,
18
18
  summarizeBenchmarkCampaign
19
- } from "../chunk-PICTDURQ.js";
20
- import "../chunk-TDHX3BVA.js";
21
- import "../chunk-VZ6VKOJT.js";
22
- import "../chunk-XDIRG3TO.js";
23
- import "../chunk-3YYRZDON.js";
24
- import "../chunk-S5TT5R3L.js";
19
+ } from "../chunk-OZFTLMGS.js";
20
+ import "../chunk-IDC74VDL.js";
21
+ import "../chunk-DHJJACEX.js";
22
+ import "../chunk-N3QPYIVG.js";
23
+ import "../chunk-EAWKAVID.js";
25
24
  import "../chunk-ARU2PZFM.js";
26
25
  import "../chunk-NJC7U437.js";
27
26
  import "../chunk-PJQFMIOX.js";
28
- import "../chunk-JHOJHHU7.js";
27
+ import "../chunk-ZMXDQ4K7.js";
29
28
  import "../chunk-VI2UW6B6.js";
30
29
  import "../chunk-WW2A73HW.js";
31
30
  import "../chunk-GGE4NNQT.js";
@@ -4131,9 +4131,24 @@ declare function parameterSweepProposer(opts: ParameterSweepProposerOptions): Su
4131
4131
  * re-score + release gate + optional PR.
4132
4132
  */
4133
4133
 
4134
+ interface PremeasuredOptimizationBaseline<TArtifact, TScenario extends Scenario> {
4135
+ /** Hash of the exact surface that produced `campaign`. */
4136
+ surfaceHash: string;
4137
+ /** Complete prior measurement reused by identity, including artifactsByPath. */
4138
+ campaign: CampaignResult<TArtifact, TScenario>;
4139
+ }
4134
4140
  interface RunOptimizationBaseOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch'> {
4135
4141
  /** Initial mutable surface (typically system prompt or addendum). */
4136
4142
  baselineSurface: MutableSurface;
4143
+ /**
4144
+ * Complete prior measurement of `baselineSurface`. When present,
4145
+ * `runOptimization` validates its surface, scenario split, seed, reps, and
4146
+ * normal campaign coverage, then skips the baseline campaign entirely — no
4147
+ * dispatch or resumability-cache lookup. Candidate campaigns still run
4148
+ * normally. Prior spend remains in the imported campaign aggregates and is
4149
+ * not added again to this continuation's CostLedger.
4150
+ */
4151
+ premeasuredBaseline?: PremeasuredOptimizationBaseline<TArtifact, TScenario>;
4137
4152
  /** Dispatcher that takes the CURRENT surface + scenario → artifact. */
4138
4153
  dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: Parameters<RunCampaignOptions<TScenario, TArtifact>['dispatch']>[1]) => Promise<TArtifact>;
4139
4154
  /** The candidate-generation strategy. Wrap a population `Mutator` via
@@ -4142,6 +4157,9 @@ interface RunOptimizationBaseOptions<TScenario extends Scenario, TArtifact> exte
4142
4157
  proposer: SurfaceProposer;
4143
4158
  populationSize: number;
4144
4159
  maxGenerations: number;
4160
+ /** Candidate campaigns run at once. Default 1. Total concurrent cells are
4161
+ * bounded by candidateConcurrency * maxConcurrency. */
4162
+ candidateConcurrency?: number;
4145
4163
  /** @deprecated The loop has one global incumbent and can promote only the
4146
4164
  * single candidate that beats it. Retained for source compatibility. */
4147
4165
  promoteTopK?: number;
@@ -5058,6 +5076,9 @@ interface RunLineageLoopOptions<TScenario extends Scenario, TArtifact> {
5058
5076
  /** Candidates proposed per extend/branch step (BREADTH within one step).
5059
5077
  * Default 4. The merge always proposes a single crossover. */
5060
5078
  populationSize?: number;
5079
+ /** Candidate surfaces measured at once. Default 1. Total concurrent cells are
5080
+ * bounded by candidateConcurrency * maxConcurrency. */
5081
+ candidateConcurrency?: number;
5061
5082
  /** Agent-managed decision layer. Default {@link heuristicGovernor}. */
5062
5083
  governor?: Governor;
5063
5084
  budget: {
@@ -7324,7 +7345,7 @@ interface SingleRunLockOptions {
7324
7345
  readonly alsoCheck?: readonly string[];
7325
7346
  /** Install a process 'exit' hook that releases the lock. Default true. */
7326
7347
  readonly releaseOnExit?: boolean;
7327
- /** Owner pid recorded in the lockfile. Default process.pid. */
7348
+ /** Owner pid recorded in the lockfile metadata. Default process.pid. */
7328
7349
  readonly pid?: number;
7329
7350
  }
7330
7351
  interface SingleRunLock {
@@ -7333,7 +7354,8 @@ interface SingleRunLock {
7333
7354
  }
7334
7355
  /**
7335
7356
  * Acquire the lock or throw naming the live holder. A stale lock (holder pid
7336
- * no longer running) is reclaimed silently.
7357
+ * no longer running) is reclaimed by one contender. An interrupted reclaim
7358
+ * leaves a marker that fails closed instead of admitting overlapping runs.
7337
7359
  */
7338
7360
  declare function acquireSingleRunLock(opts: SingleRunLockOptions): SingleRunLock;
7339
7361
 
@@ -7464,4 +7486,4 @@ declare function verifyCodeSurface(surface: CodeSurface, worktreeDir?: string):
7464
7486
  * identity against the checkout at `worktreeRef`. */
7465
7487
  declare function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string;
7466
7488
 
7467
- export { type AcceptedEdit, type AceProposerOptions, type AnalystArtifact, type AnalystScenario, type AnalyzeCrossSurfaceInteractionsInput, type ApplySkillPatchResult, 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 CompareProposersOptions, type CompositeProposerOptions, 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, DEFAULT_POLICY_EDIT_HISTORY_LIMITS, 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 EvolutionaryProposerOptions, type FailureModeRecallJudgeOptions, type FapoAttributionSignals, type FapoEntryConfig, type FapoFailureCluster, type FapoOptimizationLevel, type FapoProposerOptions, type FapoReviewInput, type FapoReviewIssue, type FapoReviewResult, type FapoScopeContract, FileSearchLedger, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaProposerConstraints, type GepaProposerOptions, type GitWorktreeAdapterOptions, type Governor, type GovernorContext, type GovernorOp, type HaloProposerOptions, type HeldOutGateOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type HeuristicGovernorOptions, type JsonPolicyEditTargetSurface, type JsonPrimitive, type JsonValue, type JudgeAggregate, type JudgeConfig, type JudgeDimension, type JudgeScore, type LabelTrust, type LabeledScenarioRecord, type LabeledScenarioSampleArgs, type LabeledScenarioSource, type LabeledScenarioStore, LabeledScenarioStoreError, type LabeledScenarioWrite, Lineage, type LineageEdge, type LineageGraph, type LineageNode, type LineageNodeInput, type LineageStore, type LlmJudgeDimension, type LlmJudgeOptions, type LlmPolicyEditProposerOptions, type LoadEvalFixtureScenariosOptions, type LoopProvenanceArgsFromResult, type LoopProvenanceBackend, type LoopProvenanceCandidate, type LoopProvenanceEvidence, type LoopProvenanceRecord, type MemoryCurationProposerOptions, type MutableSurface, type Mutator, type NeutralizationGateOptions, type ObjectiveSource, type OpenAutoPrOptions, type OpenAutoPrResult, type OpenSearchLedgerOptions, type OptimizationProposer, type OptimizerConfig, type OptimizerEntryConfig, POLICY_EDIT_CANDIDATE_RECORD_SCHEMA, type PairedHoldout, type ParameterCandidate, type ParameterChange, type ParameterSweepProposerOptions, type ParetoParent, type ParetoSignificanceGateOptions, type PlanCampaignRunOptions, type PlanEvalFixtureRunOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type PolicyEditAuthorScenarioRow, type PolicyEditCandidateRecord, type PolicyEditCandidateSummary, type PolicyEditFindingInput, type PolicyEditFindingSource, type PolicyEditHistoryCandidateContext, type PolicyEditHistoryGenerationContext, type PolicyEditHistoryProjectionOptions, type PolicyEditObjective, type PolicyEditOutcomeContext, type PolicyEditProposerOptions, type PowerPreflight, type PowerPreflightOptions, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type PromotionObjective, type PromotionPolicy, type ProposeContext, type ProposePatchesArgs, type ProposedCandidate, type ProposerComparison, type ProposerEntry, type ProposerPairwise, type ProposerScore, type RedactionStatus, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceScenario, type RejectedEdit, type RolloutArgumentDiff, type RolloutArgumentDiffOptions, type RolloutCall, type RunCampaignOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunLineageLoopOptions, type RunLineageLoopResult, type RunLineageLoopSeed, type RunLineageOptions, type RunLineageResult, type RunLineageSeed, type RunLineageStepResult, type RunOptimizationOptions, type RunOptimizationResult, type RunProfileMatrixOptions, type RunProfileMatrixResult, type RunSkillOptOptions, type RunSkillOptResult, 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 SelectPolicyEditAuthorRowsOptions, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SerializedJsonBudget, type SessionScript, type SingleRunLock, type SingleRunLockOptions, type SkillOptEpochRecord, type SkillOptEvidence, type SkillOptProposer, type SkillOptProposerOptions, type SkillPatch, type SkillPatchOp, SkillPatchParseError, type SkillPatchRejection, type SurfaceProposer, type SurfaceScore, type TraceAnalystProposerOptions, type TraceSpan, type TransientFailureOptions, type UngroundedLiteralReport, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, aceProposer, acquireSingleRunLock, analyzeCrossSurfaceInteractions, applySkillPatch, assertCampaignDesign, assertCampaignSplitIdentity, assertCodeSurfaceIdentity, assertPolicyEditAuthorContextBudget, buildAnalystSurfaceDispatch, buildEvidenceVector, buildLoopProvenanceRecord, callbackGovernor, campaignBreakdown, campaignMeanComposite, campaignMeasurementDigest, campaignScenarioIdentity, campaignSplitDigest, campaignSplitDigestFromIdentities, canonicalDigest, classifyUngroundedLiterals, codeSurfaceIdentityMaterial, compareProposers, composeGate, compositeProposer, countSentenceEdits, createReferenceEquivalenceJudge, createRunCostLedger, defaultProductionGate, detectScale, dimensionRegressions, discoverEvalFixtures, emitLoopProvenance, evolutionaryProposer, extractFapoAttributionSignals, extractH2Sections, failureModeRecallJudge, fapoEscalationEntry, fapoProposer, fsCampaignStorage, fsLineageStore, gepaParetoEntry, gepaProposer, gepaReflectionEntry, gitWorktreeAdapter, haloProposer, heldOutGate, heldoutSignificance, heuristicGovernor, inMemoryCampaignStorage, isProposedCandidate, isTransientTransportFailure, labelTrustRank, lineageNodeId, llmJudge, llmPolicyEditProposer, loadEvalFixture, loadEvalFixtureScenarios, loopProvenanceArgsFromResult, loopProvenanceSpans, makePlaybackDispatch, memLineageStore, memoryCurationProposer, neutralizationGate, neutralizeText, openAutoPr, openSearchLedger, pairHoldout, parameterSweepProposer, paretoPolicy, paretoSignificanceGate, parseSkillPatchResponse, patchEditCount, planCampaignRun, planEvalFixtureRun, policyEditProposer, powerPreflight, projectPolicyEditHistory, provenanceRecordPath, provenanceSpansPath, renderScoreboardMarkdown, renderSurfaceDiff, resolveRunDir, resolveWorktreePath, rolloutArgumentDiff, runCampaign, runEval, runImprovementLoop, runLineage, runLineageLoop, runOptimization, runProfileMatrix, runSkillOpt, scoreDiscrimination, scoreUserStory, scoreboardSummary, selectDiscriminative, selectPolicyEditAuthorRows, sequentialDecide, sequentialPairedGate, skillOptEntry, skillOptProposer, surfaceContentHash, surfaceHash, tangleTracesRoot, traceAnalystProposer, userStoryScoreboard, validatePolicyEditCandidateRecord, validateSearchLedgerEvent, verifyCodeSurface, verifyLoopProvenanceRecord };
7489
+ export { type AcceptedEdit, type AceProposerOptions, type AnalystArtifact, type AnalystScenario, type AnalyzeCrossSurfaceInteractionsInput, type ApplySkillPatchResult, 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 CompareProposersOptions, type CompositeProposerOptions, 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, DEFAULT_POLICY_EDIT_HISTORY_LIMITS, 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 EvolutionaryProposerOptions, type FailureModeRecallJudgeOptions, type FapoAttributionSignals, type FapoEntryConfig, type FapoFailureCluster, type FapoOptimizationLevel, type FapoProposerOptions, type FapoReviewInput, type FapoReviewIssue, type FapoReviewResult, type FapoScopeContract, FileSearchLedger, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaProposerConstraints, type GepaProposerOptions, type GitWorktreeAdapterOptions, type Governor, type GovernorContext, type GovernorOp, type HaloProposerOptions, type HeldOutGateOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type HeuristicGovernorOptions, type JsonPolicyEditTargetSurface, type JsonPrimitive, type JsonValue, type JudgeAggregate, type JudgeConfig, type JudgeDimension, type JudgeScore, type LabelTrust, type LabeledScenarioRecord, type LabeledScenarioSampleArgs, type LabeledScenarioSource, type LabeledScenarioStore, LabeledScenarioStoreError, type LabeledScenarioWrite, Lineage, type LineageEdge, type LineageGraph, type LineageNode, type LineageNodeInput, type LineageStore, type LlmJudgeDimension, type LlmJudgeOptions, type LlmPolicyEditProposerOptions, type LoadEvalFixtureScenariosOptions, type LoopProvenanceArgsFromResult, type LoopProvenanceBackend, type LoopProvenanceCandidate, type LoopProvenanceEvidence, type LoopProvenanceRecord, type MemoryCurationProposerOptions, type MutableSurface, type Mutator, type NeutralizationGateOptions, type ObjectiveSource, type OpenAutoPrOptions, type OpenAutoPrResult, type OpenSearchLedgerOptions, type OptimizationProposer, type OptimizerConfig, type OptimizerEntryConfig, POLICY_EDIT_CANDIDATE_RECORD_SCHEMA, type PairedHoldout, type ParameterCandidate, type ParameterChange, type ParameterSweepProposerOptions, type ParetoParent, type ParetoSignificanceGateOptions, type PlanCampaignRunOptions, type PlanEvalFixtureRunOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type PolicyEditAuthorScenarioRow, type PolicyEditCandidateRecord, type PolicyEditCandidateSummary, type PolicyEditFindingInput, type PolicyEditFindingSource, type PolicyEditHistoryCandidateContext, type PolicyEditHistoryGenerationContext, type PolicyEditHistoryProjectionOptions, type PolicyEditObjective, type PolicyEditOutcomeContext, type PolicyEditProposerOptions, type PowerPreflight, type PowerPreflightOptions, type PremeasuredOptimizationBaseline, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type PromotionObjective, type PromotionPolicy, type ProposeContext, type ProposePatchesArgs, type ProposedCandidate, type ProposerComparison, type ProposerEntry, type ProposerPairwise, type ProposerScore, type RedactionStatus, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceScenario, type RejectedEdit, type RolloutArgumentDiff, type RolloutArgumentDiffOptions, type RolloutCall, type RunCampaignOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunLineageLoopOptions, type RunLineageLoopResult, type RunLineageLoopSeed, type RunLineageOptions, type RunLineageResult, type RunLineageSeed, type RunLineageStepResult, type RunOptimizationOptions, type RunOptimizationResult, type RunProfileMatrixOptions, type RunProfileMatrixResult, type RunSkillOptOptions, type RunSkillOptResult, 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 SelectPolicyEditAuthorRowsOptions, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SerializedJsonBudget, type SessionScript, type SingleRunLock, type SingleRunLockOptions, type SkillOptEpochRecord, type SkillOptEvidence, type SkillOptProposer, type SkillOptProposerOptions, type SkillPatch, type SkillPatchOp, SkillPatchParseError, type SkillPatchRejection, type SurfaceProposer, type SurfaceScore, type TraceAnalystProposerOptions, type TraceSpan, type TransientFailureOptions, type UngroundedLiteralReport, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, aceProposer, acquireSingleRunLock, analyzeCrossSurfaceInteractions, applySkillPatch, assertCampaignDesign, assertCampaignSplitIdentity, assertCodeSurfaceIdentity, assertPolicyEditAuthorContextBudget, buildAnalystSurfaceDispatch, buildEvidenceVector, buildLoopProvenanceRecord, callbackGovernor, campaignBreakdown, campaignMeanComposite, campaignMeasurementDigest, campaignScenarioIdentity, campaignSplitDigest, campaignSplitDigestFromIdentities, canonicalDigest, classifyUngroundedLiterals, codeSurfaceIdentityMaterial, compareProposers, composeGate, compositeProposer, countSentenceEdits, createReferenceEquivalenceJudge, createRunCostLedger, defaultProductionGate, detectScale, dimensionRegressions, discoverEvalFixtures, emitLoopProvenance, evolutionaryProposer, extractFapoAttributionSignals, extractH2Sections, failureModeRecallJudge, fapoEscalationEntry, fapoProposer, fsCampaignStorage, fsLineageStore, gepaParetoEntry, gepaProposer, gepaReflectionEntry, gitWorktreeAdapter, haloProposer, heldOutGate, heldoutSignificance, heuristicGovernor, inMemoryCampaignStorage, isProposedCandidate, isTransientTransportFailure, labelTrustRank, lineageNodeId, llmJudge, llmPolicyEditProposer, loadEvalFixture, loadEvalFixtureScenarios, loopProvenanceArgsFromResult, loopProvenanceSpans, makePlaybackDispatch, memLineageStore, memoryCurationProposer, neutralizationGate, neutralizeText, openAutoPr, openSearchLedger, pairHoldout, parameterSweepProposer, paretoPolicy, paretoSignificanceGate, parseSkillPatchResponse, patchEditCount, planCampaignRun, planEvalFixtureRun, policyEditProposer, powerPreflight, projectPolicyEditHistory, provenanceRecordPath, provenanceSpansPath, renderScoreboardMarkdown, renderSurfaceDiff, resolveRunDir, resolveWorktreePath, rolloutArgumentDiff, runCampaign, runEval, runImprovementLoop, runLineage, runLineageLoop, runOptimization, runProfileMatrix, runSkillOpt, scoreDiscrimination, scoreUserStory, scoreboardSummary, selectDiscriminative, selectPolicyEditAuthorRows, sequentialDecide, sequentialPairedGate, skillOptEntry, skillOptProposer, surfaceContentHash, surfaceHash, tangleTracesRoot, traceAnalystProposer, userStoryScoreboard, validatePolicyEditCandidateRecord, validateSearchLedgerEvent, verifyCodeSurface, verifyLoopProvenanceRecord };
@@ -66,7 +66,7 @@ import {
66
66
  userStoryScoreboard,
67
67
  validateSearchLedgerEvent,
68
68
  verifyCodeSurface
69
- } from "../chunk-TDHX3BVA.js";
69
+ } from "../chunk-IDC74VDL.js";
70
70
  import {
71
71
  assertCodeSurfaceIdentity,
72
72
  buildEvidenceVector,
@@ -107,7 +107,7 @@ import {
107
107
  surfaceContentHash,
108
108
  surfaceHash,
109
109
  verifyLoopProvenanceRecord
110
- } from "../chunk-VZ6VKOJT.js";
110
+ } from "../chunk-DHJJACEX.js";
111
111
  import {
112
112
  SearchLedgerConflictError,
113
113
  SearchLedgerError,
@@ -124,16 +124,15 @@ import {
124
124
  resolveRunDir,
125
125
  runCampaign,
126
126
  tangleTracesRoot
127
- } from "../chunk-XDIRG3TO.js";
128
- import "../chunk-3YYRZDON.js";
127
+ } from "../chunk-N3QPYIVG.js";
129
128
  import {
130
129
  POLICY_EDIT_CANDIDATE_RECORD_SCHEMA,
131
130
  validatePolicyEditCandidateRecord
132
- } from "../chunk-S5TT5R3L.js";
131
+ } from "../chunk-EAWKAVID.js";
133
132
  import "../chunk-ARU2PZFM.js";
134
133
  import "../chunk-NJC7U437.js";
135
134
  import "../chunk-PJQFMIOX.js";
136
- import "../chunk-JHOJHHU7.js";
135
+ import "../chunk-ZMXDQ4K7.js";
137
136
  import "../chunk-VI2UW6B6.js";
138
137
  import "../chunk-WW2A73HW.js";
139
138
  import "../chunk-GGE4NNQT.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  summarizeBackendIntegrity
3
- } from "./chunk-XDIRG3TO.js";
3
+ } from "./chunk-N3QPYIVG.js";
4
4
  import {
5
5
  paretoChart
6
6
  } from "./chunk-DPZAEKA6.js";
@@ -995,4 +995,4 @@ export {
995
995
  summarizeExecution,
996
996
  analyzeRuns
997
997
  };
998
- //# sourceMappingURL=chunk-3A246TSA.js.map
998
+ //# sourceMappingURL=chunk-BD2OK6ZW.js.map
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  assertCampaignSplitIdentity,
3
3
  campaignCoverage,
4
+ campaignSplitDigest,
4
5
  canonicalJson,
5
6
  contentHash,
6
7
  createRunCostLedger,
@@ -9,11 +10,12 @@ import {
9
10
  resolveRunDir,
10
11
  runCampaign,
11
12
  summarizeAgentReceiptIntegrity
12
- } from "./chunk-XDIRG3TO.js";
13
+ } from "./chunk-N3QPYIVG.js";
13
14
  import {
14
15
  clamp01,
16
+ mapConcurrent,
15
17
  validatePolicyEditCandidateRecord
16
- } from "./chunk-S5TT5R3L.js";
18
+ } from "./chunk-EAWKAVID.js";
17
19
  import {
18
20
  detectRewardHacking
19
21
  } from "./chunk-ARU2PZFM.js";
@@ -30,7 +32,7 @@ import {
30
32
  } from "./chunk-PJQFMIOX.js";
31
33
  import {
32
34
  CostLedger
33
- } from "./chunk-JHOJHHU7.js";
35
+ } from "./chunk-ZMXDQ4K7.js";
34
36
  import {
35
37
  DEFAULT_REDACTION_RULES
36
38
  } from "./chunk-GGE4NNQT.js";
@@ -2646,9 +2648,13 @@ function campaignBreakdown(campaign) {
2646
2648
  // src/campaign/presets/run-optimization.ts
2647
2649
  async function runOptimization(opts) {
2648
2650
  const { proposer } = opts;
2651
+ const candidateConcurrency = opts.candidateConcurrency ?? 1;
2649
2652
  if (typeof opts.runDir !== "string" || opts.runDir.trim().length === 0) {
2650
2653
  throw new Error("runOptimization: runDir is required and must be a non-empty string");
2651
2654
  }
2655
+ if (!Number.isInteger(candidateConcurrency) || candidateConcurrency < 1) {
2656
+ throw new Error("runOptimization: candidateConcurrency must be a positive integer");
2657
+ }
2652
2658
  opts.runDir = resolveRunDir(opts.runDir, opts.repo);
2653
2659
  const storage = opts.storage ?? fsCampaignStorage();
2654
2660
  const costLedger = opts.costLedger ?? createRunCostLedger({
@@ -2661,23 +2667,32 @@ async function runOptimization(opts) {
2661
2667
  "runOptimization: promoteTopK must be 1 because the loop has one global incumbent"
2662
2668
  );
2663
2669
  }
2664
- const baselineCampaign = await runCampaign({
2670
+ const requireJudgeScore = (opts.judges?.length ?? 0) > 0;
2671
+ const reps = opts.reps ?? 1;
2672
+ const premeasuredBaseline = opts.premeasuredBaseline;
2673
+ const baselineCampaign = premeasuredBaseline ? validatedPremeasuredBaseline({
2674
+ input: premeasuredBaseline,
2675
+ baselineSurface: opts.baselineSurface,
2676
+ scenarios: opts.scenarios,
2677
+ reps,
2678
+ seed: opts.seed ?? 42
2679
+ }) : await runCampaign({
2665
2680
  ...opts,
2666
2681
  costLedger,
2667
2682
  costPhase: "search.baseline",
2668
2683
  dispatch: (scenario, ctx) => opts.dispatchWithSurface(opts.baselineSurface, scenario, ctx),
2669
2684
  runDir: `${opts.runDir}/baseline`
2670
2685
  });
2671
- const requireJudgeScore = (opts.judges?.length ?? 0) > 0;
2672
2686
  const baselineCoverage = campaignCoverage(
2673
2687
  baselineCampaign.cells,
2674
2688
  opts.scenarios,
2675
- opts.reps ?? 1,
2689
+ reps,
2676
2690
  requireJudgeScore
2677
2691
  );
2678
2692
  if (!baselineCoverage.complete) {
2693
+ const label = opts.premeasuredBaseline ? "premeasured baseline" : "baseline";
2679
2694
  throw new Error(
2680
- `runOptimization: baseline is incomplete (${baselineCoverage.scorableCellIds.length}/${baselineCoverage.expectedCellIds.length} designed cells scorable) \u2014 ${formatCoverageFailures(baselineCoverage)}. Refusing to optimize against an incomplete incumbent.`
2695
+ `runOptimization: ${label} is incomplete (${baselineCoverage.scorableCellIds.length}/${baselineCoverage.expectedCellIds.length} designed cells scorable) \u2014 ${formatCoverageFailures(baselineCoverage)}. Refusing to optimize against an incomplete incumbent.`
2681
2696
  );
2682
2697
  }
2683
2698
  const generations = [];
@@ -2701,7 +2716,7 @@ async function runOptimization(opts) {
2701
2716
  if (opts.analyzeGeneration && opts.maxGenerations > 0 && baselineCampaign.cells.length > 0) {
2702
2717
  const fresh = await opts.analyzeGeneration({
2703
2718
  generation: -1,
2704
- runDir: `${opts.runDir}/baseline`,
2719
+ runDir: baselineCampaign.runDir,
2705
2720
  candidates: [
2706
2721
  { surfaceHash: winnerSurfaceHash, campaign: baselineCampaign, composite: winnerComposite }
2707
2722
  ],
@@ -2739,34 +2754,39 @@ async function runOptimization(opts) {
2739
2754
  const candidates = proposed.map(
2740
2755
  (p) => isProposedCandidate(p) ? p : { surface: p, label: "", rationale: "" }
2741
2756
  );
2742
- const surfaceResults = [];
2743
- for (let i = 0; i < candidates.length; i++) {
2744
- const { surface, label, rationale, candidateRecord } = candidates[i];
2745
- const hash = surfaceHash(surface);
2746
- const campaign = await runCampaign({
2747
- ...opts,
2748
- costLedger,
2749
- costPhase: "search.candidate",
2750
- dispatch: (scenario, ctx) => opts.dispatchWithSurface(surface, scenario, ctx),
2751
- runDir: `${opts.runDir}/gen-${gen}/candidate-${i}`
2752
- });
2753
- const composite = campaignMeanComposite(campaign);
2754
- const coverage = campaignCoverage(
2755
- campaign.cells,
2756
- opts.scenarios,
2757
- opts.reps ?? 1,
2758
- requireJudgeScore
2759
- );
2760
- surfaceResults.push({
2761
- surfaceHash: hash,
2762
- surface,
2763
- label,
2764
- rationale,
2765
- ...candidateRecord ? { candidateRecord } : {},
2766
- campaign,
2767
- composite,
2768
- coverage
2769
- });
2757
+ const surfaceResults = await mapConcurrent(
2758
+ candidates,
2759
+ candidateConcurrency,
2760
+ async ({ surface, label, rationale, candidateRecord }, i) => {
2761
+ const hash = surfaceHash(surface);
2762
+ const campaign = await runCampaign({
2763
+ ...opts,
2764
+ costLedger,
2765
+ costPhase: "search.candidate",
2766
+ dispatch: (scenario, ctx) => opts.dispatchWithSurface(surface, scenario, ctx),
2767
+ runDir: `${opts.runDir}/gen-${gen}/candidate-${i}`
2768
+ });
2769
+ const composite = campaignMeanComposite(campaign);
2770
+ const coverage = campaignCoverage(
2771
+ campaign.cells,
2772
+ opts.scenarios,
2773
+ opts.reps ?? 1,
2774
+ requireJudgeScore
2775
+ );
2776
+ return {
2777
+ surfaceHash: hash,
2778
+ surface,
2779
+ label,
2780
+ rationale,
2781
+ ...candidateRecord ? { candidateRecord } : {},
2782
+ campaign,
2783
+ composite,
2784
+ coverage
2785
+ };
2786
+ }
2787
+ );
2788
+ for (const result of surfaceResults) {
2789
+ const { surface, surfaceHash: hash, campaign, coverage, label, rationale } = result;
2770
2790
  if (coverage.complete) {
2771
2791
  scored.push(
2772
2792
  toParetoParent(surface, hash, campaign, gen, label || void 0, rationale || void 0)
@@ -2852,6 +2872,38 @@ async function runOptimization(opts) {
2852
2872
  cost: costLedger.summary()
2853
2873
  };
2854
2874
  }
2875
+ function validatedPremeasuredBaseline(args) {
2876
+ const { input } = args;
2877
+ if (input.surfaceHash !== surfaceHash(args.baselineSurface)) {
2878
+ throw new Error(
2879
+ "runOptimization: premeasured baseline surface hash does not match baselineSurface"
2880
+ );
2881
+ }
2882
+ const campaign = input.campaign;
2883
+ if (campaign.reps !== args.reps) {
2884
+ throw new Error(
2885
+ `runOptimization: premeasured baseline reps ${campaign.reps} do not match requested reps ${args.reps}`
2886
+ );
2887
+ }
2888
+ if (campaign.seed !== args.seed) {
2889
+ throw new Error(
2890
+ `runOptimization: premeasured baseline seed ${campaign.seed} does not match requested seed ${args.seed}`
2891
+ );
2892
+ }
2893
+ try {
2894
+ assertCampaignSplitIdentity(campaign.scenarios, campaign.reps, campaign.splitDigest);
2895
+ } catch (error) {
2896
+ throw new Error(
2897
+ `runOptimization: premeasured baseline has an invalid retained split identity \u2014 ${error instanceof Error ? error.message : String(error)}`
2898
+ );
2899
+ }
2900
+ if (campaign.splitDigest !== campaignSplitDigest(args.scenarios, args.reps)) {
2901
+ throw new Error(
2902
+ "runOptimization: premeasured baseline split does not match the requested scenarios"
2903
+ );
2904
+ }
2905
+ return campaign;
2906
+ }
2855
2907
  function toParetoParent(surface, hash, campaign, generation, label, rationale) {
2856
2908
  const objectives = {};
2857
2909
  for (const { scenarioId, composite } of campaignBreakdown(campaign).scenarios) {
@@ -2946,7 +2998,7 @@ async function runImprovementLoop(opts) {
2946
2998
  const dispatchTimeoutMs = opts.dispatchTimeoutMs ?? DEFAULT_DISPATCH_TIMEOUT_MS;
2947
2999
  const optimization = await runOptimization({ ...opts, dispatchTimeoutMs, costLedger });
2948
3000
  const winnerIsBaseline = optimization.winnerSurfaceHash === surfaceHash(opts.baselineSurface);
2949
- const { runCampaign: runCampaign2 } = await import("./run-campaign-HNFPJET4.js");
3001
+ const { runCampaign: runCampaign2 } = await import("./run-campaign-2YJ3Z6JS.js");
2950
3002
  const baselineOnHoldout = await runCampaign2({
2951
3003
  ...opts,
2952
3004
  costLedger,
@@ -3738,4 +3790,4 @@ export {
3738
3790
  provenanceSpansPath,
3739
3791
  emitLoopProvenance
3740
3792
  };
3741
- //# sourceMappingURL=chunk-VZ6VKOJT.js.map
3793
+ //# sourceMappingURL=chunk-DHJJACEX.js.map