@tangle-network/agent-eval 0.43.2 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,642 @@
1
+ import {
2
+ runCampaign
3
+ } from "./chunk-RXK7FXLV.js";
4
+ import {
5
+ buildReflectionPrompt,
6
+ parseReflectionResponse,
7
+ runCanaries,
8
+ scoreRedTeamOutput
9
+ } from "./chunk-N4SBKEPJ.js";
10
+ import {
11
+ detectRewardHacking
12
+ } from "./chunk-YV7J7X5N.js";
13
+ import {
14
+ callLlm
15
+ } from "./chunk-VXNVVBZO.js";
16
+
17
+ // src/campaign/auto-pr.ts
18
+ import { execSync } from "child_process";
19
+ import { writeFileSync } from "fs";
20
+ import { tmpdir } from "os";
21
+ import { join } from "path";
22
+ function openAutoPr(options) {
23
+ if (options.gate.decision !== "ship") {
24
+ return {
25
+ opened: false,
26
+ dryRun: false,
27
+ reason: `gate verdict was "${options.gate.decision}" \u2014 refusing to open PR`
28
+ };
29
+ }
30
+ const dryRun = options.dryRun ?? !process.env.GH_AUTO_PR_TOKEN;
31
+ const branch = options.branch ?? `auto/${options.result.manifestHash.slice(0, 12)}`;
32
+ const title = options.title ?? `auto: campaign ${options.result.manifestHash.slice(0, 8)} promoted by gate`;
33
+ const body = renderPrBody(options.result, options.gate, options.promotedDiff);
34
+ const bodyPath = join(tmpdir(), `auto-pr-body-${Date.now()}.md`);
35
+ writeFileSync(bodyPath, body);
36
+ if (dryRun) {
37
+ return {
38
+ opened: false,
39
+ dryRun: true,
40
+ reason: `dry-run (GH_AUTO_PR_TOKEN not set). Would create PR on ${options.ghOwner}/${options.ghRepo} branch ${branch}. Body at ${bodyPath}.`
41
+ };
42
+ }
43
+ const ghExec = options.ghExec ?? defaultGhExec;
44
+ const result = ghExec([
45
+ "pr",
46
+ "create",
47
+ "--repo",
48
+ `${options.ghOwner}/${options.ghRepo}`,
49
+ "--head",
50
+ branch,
51
+ "--title",
52
+ title,
53
+ "--body-file",
54
+ bodyPath
55
+ ]);
56
+ if (result.status !== 0) {
57
+ return {
58
+ opened: false,
59
+ dryRun: false,
60
+ reason: `gh pr create failed (exit ${result.status}): ${result.stderr.slice(0, 400)}`
61
+ };
62
+ }
63
+ const prUrl = result.stdout.trim();
64
+ return { opened: true, prUrl, dryRun: false, reason: "PR opened" };
65
+ }
66
+ function renderPrBody(result, gate, diff) {
67
+ const lines = [];
68
+ lines.push(`## Automated promotion by \`runImprovementLoop\``);
69
+ lines.push("");
70
+ lines.push(`**Manifest**: \`${result.manifestHash}\``);
71
+ lines.push(`**Seed**: ${result.seed}`);
72
+ lines.push(`**Duration**: ${Math.round(result.durationMs / 1e3)}s`);
73
+ lines.push(
74
+ `**Cells**: executed ${result.aggregates.cellsExecuted}, cached ${result.aggregates.cellsCached}, skipped ${result.aggregates.cellsSkipped}, failed ${result.aggregates.cellsFailed}`
75
+ );
76
+ lines.push(`**Total spend**: $${result.aggregates.totalCostUsd.toFixed(2)}`);
77
+ lines.push("");
78
+ lines.push(`### Gate verdict: \`${gate.decision}\``);
79
+ lines.push("");
80
+ for (const reason of gate.reasons) lines.push(`- ${reason}`);
81
+ if (gate.delta !== void 0) lines.push(`- delta: ${gate.delta.toFixed(3)}`);
82
+ lines.push("");
83
+ lines.push("### Contributing gates");
84
+ lines.push("");
85
+ lines.push("| gate | passed | detail |");
86
+ lines.push("|---|---|---|");
87
+ for (const c of gate.contributingGates) {
88
+ const detail = typeof c.detail === "object" ? JSON.stringify(c.detail).slice(0, 80) : String(c.detail).slice(0, 80);
89
+ lines.push(`| ${c.name} | ${c.passed ? "\u2713" : "\u2717"} | ${detail} |`);
90
+ }
91
+ lines.push("");
92
+ lines.push("### Promoted surface");
93
+ lines.push("");
94
+ lines.push("```diff");
95
+ lines.push(diff.slice(0, 8e3));
96
+ lines.push("```");
97
+ lines.push("");
98
+ lines.push("### By-judge aggregates");
99
+ lines.push("");
100
+ lines.push("| judge | mean | ci95 | n |");
101
+ lines.push("|---|---|---|---|");
102
+ for (const [name, agg] of Object.entries(result.aggregates.byJudge)) {
103
+ lines.push(
104
+ `| ${name} | ${agg.mean.toFixed(3)} | [${agg.ci95[0].toFixed(3)}, ${agg.ci95[1].toFixed(3)}] | ${agg.n} |`
105
+ );
106
+ }
107
+ return lines.join("\n");
108
+ }
109
+ function defaultGhExec(args) {
110
+ try {
111
+ const stdout = execSync(`gh ${args.map(quoteArg).join(" ")}`, {
112
+ env: { ...process.env, GH_TOKEN: process.env.GH_AUTO_PR_TOKEN ?? process.env.GH_TOKEN ?? "" },
113
+ stdio: ["ignore", "pipe", "pipe"]
114
+ }).toString("utf8");
115
+ return { stdout, stderr: "", status: 0 };
116
+ } catch (err) {
117
+ const e = err;
118
+ return {
119
+ stdout: e.stdout?.toString("utf8") ?? "",
120
+ stderr: e.stderr?.toString("utf8") ?? "",
121
+ status: e.status ?? 1
122
+ };
123
+ }
124
+ }
125
+ function quoteArg(arg) {
126
+ if (/^[a-zA-Z0-9_/\-:.@]+$/.test(arg)) return arg;
127
+ return `"${arg.replace(/"/g, '\\"')}"`;
128
+ }
129
+
130
+ // src/campaign/drivers/evolutionary.ts
131
+ function evolutionaryDriver(opts) {
132
+ return {
133
+ kind: `evolutionary:${opts.mutator.kind}`,
134
+ async propose({ currentSurface, findings, populationSize, signal }) {
135
+ return opts.mutator.mutate({
136
+ findings: findings.length > 0 ? findings : opts.findings ?? [],
137
+ currentSurface,
138
+ populationSize,
139
+ signal
140
+ });
141
+ }
142
+ };
143
+ }
144
+
145
+ // src/campaign/drivers/gepa.ts
146
+ var REFLECTION_SYSTEM = 'You are an expert prompt engineer. Output ONLY a JSON object of shape {"proposals":[{"label":string,"rationale":string,"payload":string}]} where each `payload` is the FULL improved surface text. No prose outside the JSON.';
147
+ function gepaDriver(opts) {
148
+ const evidenceK = opts.evidenceK ?? 3;
149
+ return {
150
+ kind: "gepa",
151
+ async propose(ctx) {
152
+ const parent = typeof ctx.currentSurface === "string" ? ctx.currentSurface : JSON.stringify(ctx.currentSurface);
153
+ const { top, bottom, target } = buildEvidence(ctx, evidenceK, opts.target);
154
+ const userPrompt = buildReflectionPrompt({
155
+ target,
156
+ parentPayload: parent,
157
+ topTrials: top,
158
+ bottomTrials: bottom,
159
+ childCount: ctx.populationSize,
160
+ mutationPrimitives: opts.mutationPrimitives
161
+ });
162
+ const result = await callLlm(
163
+ {
164
+ model: opts.model,
165
+ messages: [
166
+ { role: "system", content: REFLECTION_SYSTEM },
167
+ { role: "user", content: userPrompt }
168
+ ],
169
+ jsonMode: true,
170
+ temperature: opts.temperature ?? 0.7,
171
+ maxTokens: opts.maxTokens ?? 6e3
172
+ },
173
+ opts.llm
174
+ );
175
+ const proposals = parseReflectionResponse(result.content, ctx.populationSize);
176
+ const out = [];
177
+ for (const proposal of proposals) {
178
+ const text = typeof proposal.payload === "string" ? proposal.payload.trim() : "";
179
+ if (text && text !== parent && !out.includes(text)) out.push(text);
180
+ }
181
+ return out;
182
+ }
183
+ };
184
+ }
185
+ function buildEvidence(ctx, evidenceK, baseTarget) {
186
+ const last = ctx.history.at(-1);
187
+ if (!last || last.candidates.length === 0) {
188
+ return { top: [], bottom: [], target: baseTarget };
189
+ }
190
+ const best = [...last.candidates].sort((a, b) => b.composite - a.composite)[0];
191
+ if (!best) return { top: [], bottom: [], target: baseTarget };
192
+ const byScore = [...best.scenarios].sort((a, b) => b.composite - a.composite);
193
+ const toTrace = (s) => ({
194
+ id: s.scenarioId,
195
+ score: s.composite
196
+ });
197
+ const top = byScore.slice(0, evidenceK).map(toTrace);
198
+ const bottom = byScore.slice(-evidenceK).reverse().map(toTrace);
199
+ const weakest = Object.entries(best.dimensions).sort((a, b) => a[1] - b[1]).slice(0, 3).map(([dim, value]) => `${dim} (${value.toFixed(2)})`);
200
+ const target = weakest.length > 0 ? `${baseTarget} \u2014 weakest dimensions: ${weakest.join(", ")}` : baseTarget;
201
+ return { top, bottom, target };
202
+ }
203
+
204
+ // src/campaign/gates/compose.ts
205
+ function composeGate(...gates) {
206
+ if (gates.length === 0) {
207
+ throw new Error("composeGate requires at least one gate");
208
+ }
209
+ return {
210
+ name: `composed(${gates.map((g) => g.name).join(",")})`,
211
+ async decide(ctx) {
212
+ const results = [];
213
+ for (const gate of gates) {
214
+ const res = await gate.decide(ctx);
215
+ results.push({ gate, res });
216
+ }
217
+ const decisions = results.map((r) => r.res.decision);
218
+ const overall = decisions.every((d) => d === "ship") ? "ship" : decisions.includes("arch_ceiling") ? "arch_ceiling" : decisions.includes("model_ceiling") ? "model_ceiling" : decisions.includes("hold") ? "hold" : "need_more_work";
219
+ const contributing = results.flatMap(
220
+ (r) => r.res.contributingGates.length > 0 ? r.res.contributingGates : [{ name: r.gate.name, passed: r.res.decision === "ship", detail: r.res }]
221
+ );
222
+ const reasons = results.flatMap(
223
+ (r) => r.res.reasons.map((reason) => `[${r.gate.name}] ${reason}`)
224
+ );
225
+ return {
226
+ decision: overall,
227
+ reasons,
228
+ contributingGates: contributing,
229
+ delta: results[0]?.res.delta
230
+ };
231
+ }
232
+ };
233
+ }
234
+
235
+ // src/campaign/gates/default-production-gate.ts
236
+ function defaultProductionGate(options) {
237
+ const deltaThreshold = options.deltaThreshold ?? 0.5;
238
+ const blockOnGaming = options.blockOnRewardHackingGaming ?? true;
239
+ return {
240
+ name: "defaultProductionGate",
241
+ async decide(ctx) {
242
+ const reasons = [];
243
+ const contributing = [];
244
+ const baselineComposite = meanComposite(
245
+ ctx.baselineArtifacts,
246
+ ctx.baselineJudgeScores ?? ctx.judgeScores,
247
+ options.holdoutScenarios
248
+ );
249
+ const candidateComposite = meanComposite(
250
+ ctx.candidateArtifacts,
251
+ ctx.judgeScores,
252
+ options.holdoutScenarios
253
+ );
254
+ const delta = candidateComposite - baselineComposite;
255
+ const heldoutPass = delta >= deltaThreshold;
256
+ contributing.push({
257
+ name: "heldout-delta",
258
+ passed: heldoutPass,
259
+ detail: { baselineComposite, candidateComposite, delta, deltaThreshold }
260
+ });
261
+ if (!heldoutPass) {
262
+ reasons.push(`heldout delta ${delta.toFixed(3)} < threshold ${deltaThreshold}`);
263
+ }
264
+ const budgetPass = options.budgetUsd === void 0 || ctx.cost.candidate + ctx.cost.baseline <= options.budgetUsd;
265
+ contributing.push({
266
+ name: "budget",
267
+ passed: budgetPass,
268
+ detail: {
269
+ candidateUsd: ctx.cost.candidate,
270
+ baselineUsd: ctx.cost.baseline,
271
+ budgetUsd: options.budgetUsd
272
+ }
273
+ });
274
+ if (!budgetPass) {
275
+ reasons.push(
276
+ `spend ${(ctx.cost.candidate + ctx.cost.baseline).toFixed(2)} > budget ${options.budgetUsd}`
277
+ );
278
+ }
279
+ const redTeamFindings = options.redTeamBattery ? probeRedTeam(ctx.candidateArtifacts, options.redTeamBattery) : { passed: true, findings: [] };
280
+ contributing.push({
281
+ name: "red-team",
282
+ passed: redTeamFindings.passed,
283
+ detail: {
284
+ failures: redTeamFindings.findings.length,
285
+ sample: redTeamFindings.findings.slice(0, 3)
286
+ }
287
+ });
288
+ if (!redTeamFindings.passed) {
289
+ reasons.push(`red-team probe failed (${redTeamFindings.findings.length} findings)`);
290
+ }
291
+ let rewardHackingReport = null;
292
+ if (options.recentRuns && options.recentRuns.length >= 10) {
293
+ rewardHackingReport = detectRewardHacking({ runs: options.recentRuns });
294
+ }
295
+ const gamingThreshold = 0.6;
296
+ const gamingFindings = (rewardHackingReport?.findings ?? []).filter(
297
+ (f) => f.severity >= gamingThreshold
298
+ );
299
+ const rewardHackingPass = !rewardHackingReport || !blockOnGaming || gamingFindings.length === 0 && rewardHackingReport.verdict !== "gaming";
300
+ contributing.push({
301
+ name: "reward-hacking",
302
+ passed: rewardHackingPass,
303
+ detail: { report: rewardHackingReport, gamingFindingCount: gamingFindings.length }
304
+ });
305
+ if (!rewardHackingPass) {
306
+ reasons.push(
307
+ `reward-hacking detector flagged ${gamingFindings.length} gaming-severity findings (verdict=${rewardHackingReport.verdict})`
308
+ );
309
+ }
310
+ let canaryReport = null;
311
+ if (options.recentRuns && options.recentRuns.length >= 10) {
312
+ canaryReport = runCanaries(options.recentRuns, {});
313
+ }
314
+ const errorAlerts = (canaryReport?.alerts ?? []).filter((a) => a.severity === "error");
315
+ const canaryPass = errorAlerts.length === 0;
316
+ contributing.push({
317
+ name: "canary",
318
+ passed: canaryPass,
319
+ detail: { totalAlerts: canaryReport?.alerts.length ?? 0, errorAlerts: errorAlerts.length }
320
+ });
321
+ if (!canaryPass) {
322
+ reasons.push(`canary error alerts: ${errorAlerts.length}`);
323
+ }
324
+ const allPassed = contributing.every((c) => c.passed);
325
+ const decision = allPassed ? "ship" : "hold";
326
+ return {
327
+ decision,
328
+ reasons: reasons.length > 0 ? reasons : ["all gates passed"],
329
+ contributingGates: contributing,
330
+ delta
331
+ };
332
+ }
333
+ };
334
+ }
335
+ function meanComposite(artifacts, judgeScoresByCell, scenarios) {
336
+ if (!artifacts || artifacts.size === 0) return 0;
337
+ const scenarioIds = new Set(scenarios.map((s) => s.id));
338
+ const composites = [];
339
+ for (const [cellId, scores] of judgeScoresByCell) {
340
+ const scenarioId = cellId.split(":")[0] ?? "";
341
+ if (!scenarioIds.has(scenarioId)) continue;
342
+ const cellComposites = Object.values(scores).map((s) => s.composite);
343
+ if (cellComposites.length === 0) continue;
344
+ composites.push(cellComposites.reduce((a, b) => a + b, 0) / cellComposites.length);
345
+ }
346
+ if (composites.length === 0) return 0;
347
+ return composites.reduce((a, b) => a + b, 0) / composites.length;
348
+ }
349
+ function probeRedTeam(artifacts, battery) {
350
+ const findings = [];
351
+ for (const [_cellId, artifact] of artifacts) {
352
+ const text = extractText(artifact);
353
+ if (text === void 0) continue;
354
+ for (const rtCase of battery) {
355
+ const finding = scoreRedTeamOutput(text, [], rtCase);
356
+ if (!finding.passed) {
357
+ findings.push({ scenarioId: rtCase.id, reason: finding.reason ?? "red-team probe failed" });
358
+ }
359
+ }
360
+ }
361
+ return { passed: findings.length === 0, findings };
362
+ }
363
+ function extractText(artifact) {
364
+ if (typeof artifact === "string") return artifact;
365
+ if (artifact && typeof artifact === "object") {
366
+ const rec = artifact;
367
+ if (typeof rec.text === "string") return rec.text;
368
+ if (typeof rec.output === "string") return rec.output;
369
+ if (typeof rec.content === "string") return rec.content;
370
+ }
371
+ return void 0;
372
+ }
373
+
374
+ // src/campaign/gates/heldout-gate.ts
375
+ function heldOutGate(options) {
376
+ const deltaThreshold = options.deltaThreshold ?? 0.5;
377
+ return {
378
+ name: "heldOutGate",
379
+ async decide(ctx) {
380
+ const scenarioIds = new Set(options.scenarios.map((s) => s.id));
381
+ const baseline = meanForScenarios(ctx.baselineJudgeScores ?? ctx.judgeScores, scenarioIds);
382
+ const candidate = meanForScenarios(ctx.judgeScores, scenarioIds);
383
+ const delta = candidate - baseline;
384
+ const passed = delta >= deltaThreshold;
385
+ return {
386
+ decision: passed ? "ship" : "hold",
387
+ reasons: passed ? [`held-out delta ${delta.toFixed(3)} \u2265 ${deltaThreshold}`] : [`held-out delta ${delta.toFixed(3)} < ${deltaThreshold}`],
388
+ contributingGates: [
389
+ { name: "heldOutGate", passed, detail: { baseline, candidate, delta, deltaThreshold } }
390
+ ],
391
+ delta
392
+ };
393
+ }
394
+ };
395
+ }
396
+ function meanForScenarios(judgeScoresByCell, scenarioIds) {
397
+ const composites = [];
398
+ for (const [cellId, scores] of judgeScoresByCell) {
399
+ const scenarioId = cellId.split(":")[0] ?? "";
400
+ if (!scenarioIds.has(scenarioId)) continue;
401
+ const vals = Object.values(scores).map((s) => s.composite);
402
+ if (vals.length > 0) composites.push(vals.reduce((a, b) => a + b, 0) / vals.length);
403
+ }
404
+ return composites.length === 0 ? 0 : composites.reduce((a, b) => a + b, 0) / composites.length;
405
+ }
406
+
407
+ // src/campaign/presets/run-eval.ts
408
+ async function runEval(opts) {
409
+ return runCampaign(opts);
410
+ }
411
+
412
+ // src/campaign/presets/run-optimization.ts
413
+ import { createHash } from "crypto";
414
+ async function runOptimization(opts) {
415
+ const promoteTopK = opts.promoteTopK ?? 2;
416
+ const baselineCampaign = await runCampaign({
417
+ ...opts,
418
+ dispatch: (scenario, ctx) => opts.dispatchWithSurface(opts.baselineSurface, scenario, ctx),
419
+ runDir: `${opts.runDir}/baseline`
420
+ });
421
+ const generations = [];
422
+ const history = [];
423
+ let currentSurfaces = [opts.baselineSurface];
424
+ let winnerSurface = opts.baselineSurface;
425
+ let winnerSurfaceHash = surfaceHash(opts.baselineSurface);
426
+ let winnerComposite = meanComposite2(baselineCampaign);
427
+ for (let gen = 0; gen < opts.maxGenerations; gen++) {
428
+ if (opts.driver.decide?.({ history }).stop) break;
429
+ const candidates = await opts.driver.propose({
430
+ currentSurface: currentSurfaces[0] ?? opts.baselineSurface,
431
+ history,
432
+ findings: [],
433
+ populationSize: opts.populationSize,
434
+ generation: gen,
435
+ signal: new AbortController().signal,
436
+ report: opts.report,
437
+ dataset: opts.labeledStore && opts.labeledStore !== "off" ? opts.labeledStore : void 0,
438
+ maxImprovementShots: opts.maxImprovementShots
439
+ });
440
+ const surfaceResults = [];
441
+ for (let i = 0; i < candidates.length; i++) {
442
+ const surface = candidates[i];
443
+ const hash = surfaceHash(surface);
444
+ const campaign = await runCampaign({
445
+ ...opts,
446
+ dispatch: (scenario, ctx) => opts.dispatchWithSurface(surface, scenario, ctx),
447
+ runDir: `${opts.runDir}/gen-${gen}/candidate-${i}`
448
+ });
449
+ const composite = meanComposite2(campaign);
450
+ surfaceResults.push({ surfaceHash: hash, surface, campaign, composite });
451
+ }
452
+ surfaceResults.sort((a, b) => b.composite - a.composite);
453
+ const promoted = surfaceResults.slice(0, promoteTopK);
454
+ currentSurfaces = promoted.map((p) => p.surface);
455
+ const top = surfaceResults[0];
456
+ if (top && top.composite > winnerComposite) {
457
+ winnerSurface = top.surface;
458
+ winnerSurfaceHash = top.surfaceHash;
459
+ winnerComposite = top.composite;
460
+ }
461
+ const record = {
462
+ generationIndex: gen,
463
+ candidates: surfaceResults.map((s) => {
464
+ const breakdown = candidateBreakdown(s.campaign);
465
+ return {
466
+ surfaceHash: s.surfaceHash,
467
+ composite: s.composite,
468
+ ci95: [s.composite, s.composite],
469
+ dimensions: breakdown.dimensions,
470
+ scenarios: breakdown.scenarios
471
+ };
472
+ }),
473
+ promoted: promoted.map((p) => p.surfaceHash)
474
+ };
475
+ history.push(record);
476
+ generations.push({
477
+ record,
478
+ surfaces: surfaceResults.map((s) => ({
479
+ surfaceHash: s.surfaceHash,
480
+ surface: s.surface,
481
+ campaign: s.campaign
482
+ }))
483
+ });
484
+ }
485
+ return {
486
+ generations,
487
+ winnerSurface,
488
+ winnerSurfaceHash,
489
+ baselineCampaign
490
+ };
491
+ }
492
+ function surfaceHash(surface) {
493
+ const material = typeof surface === "string" ? surface : JSON.stringify({
494
+ kind: surface.kind,
495
+ worktreeRef: surface.worktreeRef,
496
+ baseRef: surface.baseRef ?? null
497
+ });
498
+ return createHash("sha256").update(material).digest("hex").slice(0, 16);
499
+ }
500
+ function meanComposite2(campaign) {
501
+ const composites = [];
502
+ for (const cell of campaign.cells) {
503
+ const cellComposites = Object.values(cell.judgeScores).map((s) => s.composite);
504
+ if (cellComposites.length > 0) {
505
+ composites.push(cellComposites.reduce((a, b) => a + b, 0) / cellComposites.length);
506
+ }
507
+ }
508
+ return composites.length === 0 ? 0 : composites.reduce((a, b) => a + b, 0) / composites.length;
509
+ }
510
+ function candidateBreakdown(campaign) {
511
+ const dimSums = {};
512
+ const dimCounts = {};
513
+ const byScenario = /* @__PURE__ */ new Map();
514
+ for (const cell of campaign.cells) {
515
+ const judgeScores = Object.values(cell.judgeScores);
516
+ if (judgeScores.length === 0) continue;
517
+ const cellComposite = judgeScores.reduce((a, s) => a + s.composite, 0) / judgeScores.length;
518
+ const arr = byScenario.get(cell.scenarioId) ?? [];
519
+ arr.push(cellComposite);
520
+ byScenario.set(cell.scenarioId, arr);
521
+ for (const score of judgeScores) {
522
+ for (const [key, value] of Object.entries(score.dimensions)) {
523
+ dimSums[key] = (dimSums[key] ?? 0) + value;
524
+ dimCounts[key] = (dimCounts[key] ?? 0) + 1;
525
+ }
526
+ }
527
+ }
528
+ const dimensions = {};
529
+ for (const key of Object.keys(dimSums)) {
530
+ const count = dimCounts[key] ?? 0;
531
+ dimensions[key] = count > 0 ? (dimSums[key] ?? 0) / count : 0;
532
+ }
533
+ const scenarios = [...byScenario.entries()].map(([scenarioId, comps]) => ({
534
+ scenarioId,
535
+ composite: comps.reduce((a, b) => a + b, 0) / comps.length
536
+ }));
537
+ return { dimensions, scenarios };
538
+ }
539
+
540
+ // src/campaign/presets/run-improvement-loop.ts
541
+ async function runImprovementLoop(opts) {
542
+ if (opts.autoOnPromote === "config") {
543
+ throw new Error(
544
+ "runImprovementLoop: autoOnPromote='config' is deferred to Pass B (requires shadow deploy + rollback + ensemble judges). Use 'pr' or 'none' in v0.40."
545
+ );
546
+ }
547
+ if (opts.tracing === "off" && opts.driver) {
548
+ throw new Error(
549
+ "runImprovementLoop: tracing='off' is forbidden when a driver is wired. The improvement loop without traces is unattributable; candidate surfaces cannot be cited back to spans and the optimization dataset goes unfed."
550
+ );
551
+ }
552
+ if (opts.autoOnPromote === "pr" && (!opts.ghOwner || !opts.ghRepo)) {
553
+ throw new Error("runImprovementLoop: autoOnPromote='pr' requires ghOwner + ghRepo.");
554
+ }
555
+ const optimization = await runOptimization(opts);
556
+ const { runCampaign: runCampaign2 } = await import("./run-campaign-GNDO66B4.js");
557
+ const baselineOnHoldout = await runCampaign2({
558
+ ...opts,
559
+ scenarios: opts.holdoutScenarios,
560
+ dispatch: (scenario, ctx) => opts.dispatchWithSurface(opts.baselineSurface, scenario, ctx),
561
+ runDir: `${opts.runDir}/holdout-baseline`
562
+ });
563
+ const winnerOnHoldout = await runCampaign2({
564
+ ...opts,
565
+ scenarios: opts.holdoutScenarios,
566
+ dispatch: (scenario, ctx) => opts.dispatchWithSurface(optimization.winnerSurface, scenario, ctx),
567
+ runDir: `${opts.runDir}/holdout-winner`
568
+ });
569
+ const candidateArtifacts = /* @__PURE__ */ new Map();
570
+ const baselineArtifacts = /* @__PURE__ */ new Map();
571
+ const judgeScores = /* @__PURE__ */ new Map();
572
+ const baselineJudgeScores = /* @__PURE__ */ new Map();
573
+ for (const cell of winnerOnHoldout.cells) {
574
+ candidateArtifacts.set(cell.cellId, cell.artifact);
575
+ judgeScores.set(cell.cellId, cell.judgeScores);
576
+ }
577
+ for (const cell of baselineOnHoldout.cells) {
578
+ baselineArtifacts.set(cell.cellId, cell.artifact);
579
+ baselineJudgeScores.set(cell.cellId, cell.judgeScores);
580
+ }
581
+ const gateResult = await opts.gate.decide({
582
+ candidateArtifacts,
583
+ baselineArtifacts,
584
+ judgeScores,
585
+ baselineJudgeScores,
586
+ scenarios: opts.holdoutScenarios,
587
+ cost: {
588
+ candidate: winnerOnHoldout.aggregates.totalCostUsd,
589
+ baseline: baselineOnHoldout.aggregates.totalCostUsd
590
+ },
591
+ signal: new AbortController().signal
592
+ });
593
+ let prResult;
594
+ if (opts.autoOnPromote === "pr" && gateResult.decision === "ship") {
595
+ const render = opts.renderPromotedDiff ?? defaultRenderDiff;
596
+ const promotedDiff = render(optimization.winnerSurface, opts.baselineSurface);
597
+ prResult = openAutoPr({
598
+ result: winnerOnHoldout,
599
+ gate: gateResult,
600
+ promotedDiff,
601
+ ghOwner: opts.ghOwner,
602
+ ghRepo: opts.ghRepo
603
+ });
604
+ }
605
+ return {
606
+ ...optimization,
607
+ baselineOnHoldout,
608
+ winnerOnHoldout,
609
+ gateResult,
610
+ prResult
611
+ };
612
+ }
613
+ function defaultRenderDiff(winnerSurface, baselineSurface) {
614
+ if (typeof winnerSurface !== "string" || typeof baselineSurface !== "string") {
615
+ const fmt = (s) => typeof s === "string" ? "(prompt surface)" : `worktree=${s.worktreeRef}${s.baseRef ? ` base=${s.baseRef}` : ""}${s.summary ? `
616
+ ${s.summary}` : ""}`;
617
+ return `--- baseline
618
+ ${fmt(baselineSurface)}
619
+ +++ winner
620
+ ${fmt(winnerSurface)}`;
621
+ }
622
+ const lines = [];
623
+ lines.push("--- baseline");
624
+ lines.push("+++ winner");
625
+ for (const l of baselineSurface.split("\n")) lines.push(`- ${l}`);
626
+ for (const l of winnerSurface.split("\n")) lines.push(`+ ${l}`);
627
+ return lines.join("\n");
628
+ }
629
+
630
+ export {
631
+ openAutoPr,
632
+ evolutionaryDriver,
633
+ gepaDriver,
634
+ composeGate,
635
+ defaultProductionGate,
636
+ heldOutGate,
637
+ runEval,
638
+ runOptimization,
639
+ surfaceHash,
640
+ runImprovementLoop
641
+ };
642
+ //# sourceMappingURL=chunk-H5BGRSN4.js.map