@tangle-network/agent-eval 0.65.0 → 0.67.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.
- package/CHANGELOG.md +25 -0
- package/dist/adapters/otel.d.ts +1 -1
- package/dist/campaign/index.d.ts +110 -6
- package/dist/campaign/index.js +26 -19
- package/dist/campaign/index.js.map +1 -1
- package/dist/{chunk-7TPYV2ER.js → chunk-6XQIEUQ2.js} +140 -7
- package/dist/chunk-6XQIEUQ2.js.map +1 -0
- package/dist/{chunk-HKINEDRZ.js → chunk-DFS3FEXO.js} +3 -2
- package/dist/chunk-DFS3FEXO.js.map +1 -0
- package/dist/chunk-MZ2IYGGN.js +592 -0
- package/dist/chunk-MZ2IYGGN.js.map +1 -0
- package/dist/{chunk-4ODZXQV2.js → chunk-NV2PF37Q.js} +645 -2
- package/dist/chunk-NV2PF37Q.js.map +1 -0
- package/dist/contract/index.d.ts +11 -9
- package/dist/contract/index.js +11 -12
- package/dist/contract/index.js.map +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-CzhtwYBT.d.ts → index-DSEHMwvS.d.ts} +4 -2
- package/dist/index.d.ts +251 -7
- package/dist/index.js +292 -2
- package/dist/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/provenance-CChUqexv.d.ts +314 -0
- package/dist/{registry-DPly4_hZ.d.ts → registry-BGKyX6bw.d.ts} +2 -2
- package/dist/release-report-CN8hJlhk.d.ts +233 -0
- package/dist/reporting.d.ts +4 -3
- package/dist/{run-campaign-5J3ED2UJ.js → run-campaign-BVY3RGAZ.js} +2 -3
- package/dist/{provenance-lqyLpOYR.d.ts → run-improvement-loop-BKpM5T4t.d.ts} +51 -329
- package/dist/statistics-B7yCbi9i.d.ts +253 -0
- package/dist/{types-DhqpAi_z.d.ts → types-Croy5h7V.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-4ODZXQV2.js.map +0 -1
- package/dist/chunk-7TPYV2ER.js.map +0 -1
- package/dist/chunk-CZRKD2X2.js +0 -1104
- package/dist/chunk-CZRKD2X2.js.map +0 -1
- package/dist/chunk-E22YUOAL.js +0 -111
- package/dist/chunk-E22YUOAL.js.map +0 -1
- package/dist/chunk-HKINEDRZ.js.map +0 -1
- package/dist/release-report-DGoeObZT.d.ts +0 -484
- /package/dist/{run-campaign-5J3ED2UJ.js.map → run-campaign-BVY3RGAZ.js.map} +0 -0
|
@@ -1,6 +1,12 @@
|
|
|
1
|
+
import {
|
|
2
|
+
runCampaign
|
|
3
|
+
} from "./chunk-6XQIEUQ2.js";
|
|
1
4
|
import {
|
|
2
5
|
DEFAULT_REDACTION_RULES
|
|
3
6
|
} from "./chunk-GGE4NNQT.js";
|
|
7
|
+
import {
|
|
8
|
+
callLlm
|
|
9
|
+
} from "./chunk-IHDHUN2X.js";
|
|
4
10
|
import {
|
|
5
11
|
ValidationError
|
|
6
12
|
} from "./chunk-3BFEG2F6.js";
|
|
@@ -828,6 +834,630 @@ function parseReflectionResponse(raw, maxProposals) {
|
|
|
828
834
|
return out;
|
|
829
835
|
}
|
|
830
836
|
|
|
837
|
+
// src/campaign/drivers/gepa.ts
|
|
838
|
+
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.';
|
|
839
|
+
var COMBINE_SYSTEM = 'You are an expert prompt engineer performing a GEPA "combine complementary lessons" merge. You are given several non-dominated versions of one surface; each is uniquely best on different scenarios. Produce ONE new version that keeps what makes each version strong on its winning scenarios and resolves conflicts in favor of the more general rule. Output ONLY a JSON object of shape {"proposals":[{"label":string,"rationale":string,"payload":string}]} with exactly one proposal whose `payload` is the FULL merged surface text. No prose outside the JSON.';
|
|
840
|
+
function gepaDriver(opts) {
|
|
841
|
+
const evidenceK = opts.evidenceK ?? 3;
|
|
842
|
+
const combineParents = opts.combineParents ?? true;
|
|
843
|
+
const combineMaxParents = opts.combineMaxParents ?? 4;
|
|
844
|
+
if (combineParents && combineMaxParents < 1) {
|
|
845
|
+
throw new Error("gepaDriver: combineMaxParents must be >= 1 when combineParents is enabled");
|
|
846
|
+
}
|
|
847
|
+
return {
|
|
848
|
+
kind: "gepa",
|
|
849
|
+
async propose(ctx) {
|
|
850
|
+
const parent = typeof ctx.currentSurface === "string" ? ctx.currentSurface : JSON.stringify(ctx.currentSurface);
|
|
851
|
+
const constraints = opts.constraints;
|
|
852
|
+
const preserveSections = constraints?.preserveSections !== void 0 ? constraints.preserveSections.length === 0 ? extractH2Sections(parent) : constraints.preserveSections : null;
|
|
853
|
+
const maxEdits = constraints?.maxSentenceEdits;
|
|
854
|
+
const out = [];
|
|
855
|
+
const seen = /* @__PURE__ */ new Set();
|
|
856
|
+
const accept = (payload, label, rationale) => {
|
|
857
|
+
const text = typeof payload === "string" ? payload.trim() : "";
|
|
858
|
+
if (!text || text === parent || seen.has(text)) return;
|
|
859
|
+
if (preserveSections && !validatePreservedSections(text, preserveSections)) return;
|
|
860
|
+
if (maxEdits !== void 0 && countSentenceEdits(parent, text) > maxEdits * 2) return;
|
|
861
|
+
seen.add(text);
|
|
862
|
+
out.push({ surface: text, label, rationale });
|
|
863
|
+
};
|
|
864
|
+
const stringParents = (combineParents ? ctx.paretoParents ?? [] : []).filter((p) => typeof p.surface === "string").sort((a, b) => b.composite - a.composite).slice(0, combineMaxParents);
|
|
865
|
+
if (stringParents.length > 1) {
|
|
866
|
+
const combinePrompt = buildCombinePrompt({
|
|
867
|
+
target: opts.target,
|
|
868
|
+
parents: stringParents,
|
|
869
|
+
evidenceK
|
|
870
|
+
});
|
|
871
|
+
const combineResult = await callLlm(
|
|
872
|
+
{
|
|
873
|
+
model: opts.model,
|
|
874
|
+
messages: [
|
|
875
|
+
{ role: "system", content: COMBINE_SYSTEM },
|
|
876
|
+
{ role: "user", content: combinePrompt }
|
|
877
|
+
],
|
|
878
|
+
jsonMode: true,
|
|
879
|
+
temperature: opts.temperature ?? 0.7,
|
|
880
|
+
maxTokens: opts.maxTokens ?? 6e3
|
|
881
|
+
},
|
|
882
|
+
opts.llm
|
|
883
|
+
);
|
|
884
|
+
const merged = parseReflectionResponse(combineResult.content, 1)[0];
|
|
885
|
+
if (merged) {
|
|
886
|
+
accept(
|
|
887
|
+
merged.payload,
|
|
888
|
+
merged.label || "pareto-combine",
|
|
889
|
+
merged.rationale || `combined ${stringParents.length} non-dominated parents (gen ${stringParents.map((p) => p.generation).join(",")})`
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const reflectCount = Math.max(0, ctx.populationSize - out.length);
|
|
894
|
+
if (reflectCount > 0) {
|
|
895
|
+
const { top, bottom, target } = buildEvidence(ctx, evidenceK, opts.target);
|
|
896
|
+
const userPrompt = buildReflectionPrompt({
|
|
897
|
+
target,
|
|
898
|
+
parentPayload: parent,
|
|
899
|
+
topTrials: top,
|
|
900
|
+
bottomTrials: bottom,
|
|
901
|
+
childCount: reflectCount,
|
|
902
|
+
mutationPrimitives: opts.mutationPrimitives
|
|
903
|
+
});
|
|
904
|
+
const result = await callLlm(
|
|
905
|
+
{
|
|
906
|
+
model: opts.model,
|
|
907
|
+
messages: [
|
|
908
|
+
{ role: "system", content: REFLECTION_SYSTEM },
|
|
909
|
+
{ role: "user", content: userPrompt }
|
|
910
|
+
],
|
|
911
|
+
jsonMode: true,
|
|
912
|
+
temperature: opts.temperature ?? 0.7,
|
|
913
|
+
maxTokens: opts.maxTokens ?? 6e3
|
|
914
|
+
},
|
|
915
|
+
opts.llm
|
|
916
|
+
);
|
|
917
|
+
for (const proposal of parseReflectionResponse(result.content, reflectCount)) {
|
|
918
|
+
accept(proposal.payload, proposal.label, proposal.rationale);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return out.slice(0, ctx.populationSize);
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
function buildCombinePrompt(args) {
|
|
926
|
+
const lines = [
|
|
927
|
+
`You are merging ${args.parents.length} versions of: ${args.target}.`,
|
|
928
|
+
"",
|
|
929
|
+
"Each version is on the Pareto frontier \u2014 none dominates the others; each",
|
|
930
|
+
"wins on different scenarios. Combine their complementary strengths into",
|
|
931
|
+
"ONE version. Below, each version lists the scenarios it scores highest on.",
|
|
932
|
+
""
|
|
933
|
+
];
|
|
934
|
+
args.parents.forEach((p, i) => {
|
|
935
|
+
const tag = String.fromCharCode(65 + i);
|
|
936
|
+
const best = Object.entries(p.objectives).sort((a, b) => b[1] - a[1]).slice(0, args.evidenceK).map(([id, score]) => `${id} (${score.toFixed(2)})`);
|
|
937
|
+
lines.push(
|
|
938
|
+
`### Version ${tag} (mean ${p.composite.toFixed(2)}; strongest on: ${best.join(", ") || "n/a"})`,
|
|
939
|
+
"```",
|
|
940
|
+
p.surface,
|
|
941
|
+
"```",
|
|
942
|
+
""
|
|
943
|
+
);
|
|
944
|
+
});
|
|
945
|
+
lines.push(
|
|
946
|
+
"Return ONE merged version that would score well on the union of every",
|
|
947
|
+
"version's winning scenarios. Keep each version's specific winning rule;",
|
|
948
|
+
"where two rules conflict, prefer the more general one and note the choice",
|
|
949
|
+
"in your rationale."
|
|
950
|
+
);
|
|
951
|
+
return lines.join("\n");
|
|
952
|
+
}
|
|
953
|
+
function extractH2Sections(text) {
|
|
954
|
+
const out = [];
|
|
955
|
+
for (const line of text.split("\n")) {
|
|
956
|
+
const match = /^##\s+(.+?)\s*$/.exec(line);
|
|
957
|
+
if (match) out.push(match[1]);
|
|
958
|
+
}
|
|
959
|
+
return out;
|
|
960
|
+
}
|
|
961
|
+
function countSentenceEdits(baseline, candidate) {
|
|
962
|
+
const norm = (s) => s.split(/(?<=[.!?])\s+|\n/g).map((p) => p.trim()).filter((p) => p.length > 0);
|
|
963
|
+
const a = new Set(norm(baseline));
|
|
964
|
+
const b = new Set(norm(candidate));
|
|
965
|
+
let edits = 0;
|
|
966
|
+
for (const s of a) if (!b.has(s)) edits++;
|
|
967
|
+
for (const s of b) if (!a.has(s)) edits++;
|
|
968
|
+
return edits;
|
|
969
|
+
}
|
|
970
|
+
function validatePreservedSections(candidate, required) {
|
|
971
|
+
if (required.length === 0) return true;
|
|
972
|
+
const have = new Set(extractH2Sections(candidate));
|
|
973
|
+
for (const section of required) {
|
|
974
|
+
if (!have.has(section)) return false;
|
|
975
|
+
}
|
|
976
|
+
return true;
|
|
977
|
+
}
|
|
978
|
+
function buildEvidence(ctx, evidenceK, baseTarget) {
|
|
979
|
+
const last = ctx.history.at(-1);
|
|
980
|
+
if (!last || last.candidates.length === 0) {
|
|
981
|
+
return { top: [], bottom: [], target: baseTarget };
|
|
982
|
+
}
|
|
983
|
+
const best = [...last.candidates].sort((a, b) => b.composite - a.composite)[0];
|
|
984
|
+
if (!best) return { top: [], bottom: [], target: baseTarget };
|
|
985
|
+
const byScore = [...best.scenarios].sort((a, b) => b.composite - a.composite);
|
|
986
|
+
const toTrace = (s) => ({
|
|
987
|
+
id: s.scenarioId,
|
|
988
|
+
score: s.composite
|
|
989
|
+
});
|
|
990
|
+
const top = byScore.slice(0, evidenceK).map(toTrace);
|
|
991
|
+
const bottom = byScore.slice(-evidenceK).reverse().map(toTrace);
|
|
992
|
+
const weakest = Object.entries(best.dimensions).sort((a, b) => a[1] - b[1]).slice(0, 3).map(([dim, value]) => `${dim} (${value.toFixed(2)})`);
|
|
993
|
+
const target = weakest.length > 0 ? `${baseTarget} \u2014 weakest dimensions: ${weakest.join(", ")}` : baseTarget;
|
|
994
|
+
return { top, bottom, target };
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
// src/campaign/gates/heldout-gate.ts
|
|
998
|
+
function heldOutGate(options) {
|
|
999
|
+
const deltaThreshold = options.deltaThreshold ?? 0.5;
|
|
1000
|
+
return {
|
|
1001
|
+
name: "heldOutGate",
|
|
1002
|
+
async decide(ctx) {
|
|
1003
|
+
const scenarioIds = new Set(options.scenarios.map((s) => s.id));
|
|
1004
|
+
const baseline = meanForScenarios(ctx.baselineJudgeScores ?? ctx.judgeScores, scenarioIds);
|
|
1005
|
+
const candidate = meanForScenarios(ctx.judgeScores, scenarioIds);
|
|
1006
|
+
const delta = candidate - baseline;
|
|
1007
|
+
const passed = delta >= deltaThreshold;
|
|
1008
|
+
return {
|
|
1009
|
+
decision: passed ? "ship" : "hold",
|
|
1010
|
+
reasons: passed ? [`held-out delta ${delta.toFixed(3)} \u2265 ${deltaThreshold}`] : [`held-out delta ${delta.toFixed(3)} < ${deltaThreshold}`],
|
|
1011
|
+
contributingGates: [
|
|
1012
|
+
{ name: "heldOutGate", passed, detail: { baseline, candidate, delta, deltaThreshold } }
|
|
1013
|
+
],
|
|
1014
|
+
delta
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
function meanForScenarios(judgeScoresByCell, scenarioIds) {
|
|
1020
|
+
const composites = [];
|
|
1021
|
+
for (const [cellId, scores] of judgeScoresByCell) {
|
|
1022
|
+
const scenarioId = cellId.split(":")[0] ?? "";
|
|
1023
|
+
if (!scenarioIds.has(scenarioId)) continue;
|
|
1024
|
+
const vals = Object.values(scores).map((s) => s.composite);
|
|
1025
|
+
if (vals.length > 0) composites.push(vals.reduce((a, b) => a + b, 0) / vals.length);
|
|
1026
|
+
}
|
|
1027
|
+
return composites.length === 0 ? 0 : composites.reduce((a, b) => a + b, 0) / composites.length;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// src/campaign/auto-pr.ts
|
|
1031
|
+
import { execSync } from "child_process";
|
|
1032
|
+
import { writeFileSync } from "fs";
|
|
1033
|
+
import { tmpdir } from "os";
|
|
1034
|
+
import { join } from "path";
|
|
1035
|
+
function openAutoPr(options) {
|
|
1036
|
+
if (options.gate.decision !== "ship") {
|
|
1037
|
+
return {
|
|
1038
|
+
opened: false,
|
|
1039
|
+
dryRun: false,
|
|
1040
|
+
reason: `gate verdict was "${options.gate.decision}" \u2014 refusing to open PR`
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
const dryRun = options.dryRun ?? !process.env.GH_AUTO_PR_TOKEN;
|
|
1044
|
+
const branch = options.branch ?? `auto/${options.result.manifestHash.slice(0, 12)}`;
|
|
1045
|
+
const title = options.title ?? `auto: campaign ${options.result.manifestHash.slice(0, 8)} promoted by gate`;
|
|
1046
|
+
const body = renderPrBody(options.result, options.gate, options.promotedDiff);
|
|
1047
|
+
const bodyPath = join(tmpdir(), `auto-pr-body-${Date.now()}.md`);
|
|
1048
|
+
writeFileSync(bodyPath, body);
|
|
1049
|
+
if (dryRun) {
|
|
1050
|
+
return {
|
|
1051
|
+
opened: false,
|
|
1052
|
+
dryRun: true,
|
|
1053
|
+
reason: `dry-run (GH_AUTO_PR_TOKEN not set). Would create PR on ${options.ghOwner}/${options.ghRepo} branch ${branch}. Body at ${bodyPath}.`
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
const ghExec = options.ghExec ?? defaultGhExec;
|
|
1057
|
+
const result = ghExec([
|
|
1058
|
+
"pr",
|
|
1059
|
+
"create",
|
|
1060
|
+
"--repo",
|
|
1061
|
+
`${options.ghOwner}/${options.ghRepo}`,
|
|
1062
|
+
"--head",
|
|
1063
|
+
branch,
|
|
1064
|
+
"--title",
|
|
1065
|
+
title,
|
|
1066
|
+
"--body-file",
|
|
1067
|
+
bodyPath
|
|
1068
|
+
]);
|
|
1069
|
+
if (result.status !== 0) {
|
|
1070
|
+
return {
|
|
1071
|
+
opened: false,
|
|
1072
|
+
dryRun: false,
|
|
1073
|
+
reason: `gh pr create failed (exit ${result.status}): ${result.stderr.slice(0, 400)}`
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
const prUrl = result.stdout.trim();
|
|
1077
|
+
return { opened: true, prUrl, dryRun: false, reason: "PR opened" };
|
|
1078
|
+
}
|
|
1079
|
+
function renderPrBody(result, gate, diff) {
|
|
1080
|
+
const lines = [];
|
|
1081
|
+
lines.push(`## Automated promotion by \`runImprovementLoop\``);
|
|
1082
|
+
lines.push("");
|
|
1083
|
+
lines.push(`**Manifest**: \`${result.manifestHash}\``);
|
|
1084
|
+
lines.push(`**Seed**: ${result.seed}`);
|
|
1085
|
+
lines.push(`**Duration**: ${Math.round(result.durationMs / 1e3)}s`);
|
|
1086
|
+
lines.push(
|
|
1087
|
+
`**Cells**: executed ${result.aggregates.cellsExecuted}, cached ${result.aggregates.cellsCached}, skipped ${result.aggregates.cellsSkipped}, failed ${result.aggregates.cellsFailed}`
|
|
1088
|
+
);
|
|
1089
|
+
lines.push(`**Total spend**: $${result.aggregates.totalCostUsd.toFixed(2)}`);
|
|
1090
|
+
lines.push("");
|
|
1091
|
+
lines.push(`### Gate verdict: \`${gate.decision}\``);
|
|
1092
|
+
lines.push("");
|
|
1093
|
+
for (const reason of gate.reasons) lines.push(`- ${reason}`);
|
|
1094
|
+
if (gate.delta !== void 0) lines.push(`- delta: ${gate.delta.toFixed(3)}`);
|
|
1095
|
+
lines.push("");
|
|
1096
|
+
lines.push("### Contributing gates");
|
|
1097
|
+
lines.push("");
|
|
1098
|
+
lines.push("| gate | passed | detail |");
|
|
1099
|
+
lines.push("|---|---|---|");
|
|
1100
|
+
for (const c of gate.contributingGates) {
|
|
1101
|
+
const detail = typeof c.detail === "object" ? JSON.stringify(c.detail).slice(0, 80) : String(c.detail).slice(0, 80);
|
|
1102
|
+
lines.push(`| ${c.name} | ${c.passed ? "\u2713" : "\u2717"} | ${detail} |`);
|
|
1103
|
+
}
|
|
1104
|
+
lines.push("");
|
|
1105
|
+
lines.push("### Promoted surface");
|
|
1106
|
+
lines.push("");
|
|
1107
|
+
lines.push("```diff");
|
|
1108
|
+
lines.push(diff.slice(0, 8e3));
|
|
1109
|
+
lines.push("```");
|
|
1110
|
+
lines.push("");
|
|
1111
|
+
lines.push("### By-judge aggregates");
|
|
1112
|
+
lines.push("");
|
|
1113
|
+
lines.push("| judge | mean | ci95 | n |");
|
|
1114
|
+
lines.push("|---|---|---|---|");
|
|
1115
|
+
for (const [name, agg] of Object.entries(result.aggregates.byJudge)) {
|
|
1116
|
+
lines.push(
|
|
1117
|
+
`| ${name} | ${agg.mean.toFixed(3)} | [${agg.ci95[0].toFixed(3)}, ${agg.ci95[1].toFixed(3)}] | ${agg.n} |`
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
return lines.join("\n");
|
|
1121
|
+
}
|
|
1122
|
+
function defaultGhExec(args) {
|
|
1123
|
+
try {
|
|
1124
|
+
const stdout = execSync(`gh ${args.map(quoteArg).join(" ")}`, {
|
|
1125
|
+
env: { ...process.env, GH_TOKEN: process.env.GH_AUTO_PR_TOKEN ?? process.env.GH_TOKEN ?? "" },
|
|
1126
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1127
|
+
}).toString("utf8");
|
|
1128
|
+
return { stdout, stderr: "", status: 0 };
|
|
1129
|
+
} catch (err) {
|
|
1130
|
+
const e = err;
|
|
1131
|
+
return {
|
|
1132
|
+
stdout: e.stdout?.toString("utf8") ?? "",
|
|
1133
|
+
stderr: e.stderr?.toString("utf8") ?? "",
|
|
1134
|
+
status: e.status ?? 1
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
function quoteArg(arg) {
|
|
1139
|
+
if (/^[a-zA-Z0-9_/\-:.@]+$/.test(arg)) return arg;
|
|
1140
|
+
return `"${arg.replace(/"/g, '\\"')}"`;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// src/campaign/score-utils.ts
|
|
1144
|
+
function campaignMeanComposite(campaign) {
|
|
1145
|
+
const composites = [];
|
|
1146
|
+
for (const cell of campaign.cells) {
|
|
1147
|
+
const cellComposites = Object.values(cell.judgeScores).map((s) => s.composite);
|
|
1148
|
+
if (cellComposites.length > 0) {
|
|
1149
|
+
composites.push(cellComposites.reduce((a, b) => a + b, 0) / cellComposites.length);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
return composites.length === 0 ? 0 : composites.reduce((a, b) => a + b, 0) / composites.length;
|
|
1153
|
+
}
|
|
1154
|
+
function campaignBreakdown(campaign) {
|
|
1155
|
+
const dimSums = {};
|
|
1156
|
+
const dimCounts = {};
|
|
1157
|
+
const byScenario = /* @__PURE__ */ new Map();
|
|
1158
|
+
for (const cell of campaign.cells) {
|
|
1159
|
+
const judgeScores = Object.values(cell.judgeScores);
|
|
1160
|
+
if (judgeScores.length === 0) continue;
|
|
1161
|
+
const cellComposite = judgeScores.reduce((a, s) => a + s.composite, 0) / judgeScores.length;
|
|
1162
|
+
const arr = byScenario.get(cell.scenarioId) ?? [];
|
|
1163
|
+
arr.push(cellComposite);
|
|
1164
|
+
byScenario.set(cell.scenarioId, arr);
|
|
1165
|
+
for (const score of judgeScores) {
|
|
1166
|
+
for (const [key, value] of Object.entries(score.dimensions)) {
|
|
1167
|
+
dimSums[key] = (dimSums[key] ?? 0) + value;
|
|
1168
|
+
dimCounts[key] = (dimCounts[key] ?? 0) + 1;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
const dimensions = {};
|
|
1173
|
+
for (const key of Object.keys(dimSums)) {
|
|
1174
|
+
const count = dimCounts[key] ?? 0;
|
|
1175
|
+
dimensions[key] = count > 0 ? (dimSums[key] ?? 0) / count : 0;
|
|
1176
|
+
}
|
|
1177
|
+
const scenarios = [...byScenario.entries()].map(([scenarioId, comps]) => ({
|
|
1178
|
+
scenarioId,
|
|
1179
|
+
composite: comps.reduce((a, b) => a + b, 0) / comps.length
|
|
1180
|
+
}));
|
|
1181
|
+
return { dimensions, scenarios };
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
// src/campaign/types.ts
|
|
1185
|
+
function isProposedCandidate(value) {
|
|
1186
|
+
return typeof value === "object" && value !== null && "surface" in value && "label" in value && "rationale" in value;
|
|
1187
|
+
}
|
|
1188
|
+
var LABEL_TRUST_RANK = {
|
|
1189
|
+
unverified: 0,
|
|
1190
|
+
"verified-signal": 1,
|
|
1191
|
+
"human-rated": 2
|
|
1192
|
+
};
|
|
1193
|
+
function labelTrustRank(trust) {
|
|
1194
|
+
return LABEL_TRUST_RANK[trust ?? "unverified"];
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// src/campaign/presets/run-optimization.ts
|
|
1198
|
+
import { createHash } from "crypto";
|
|
1199
|
+
async function runOptimization(opts) {
|
|
1200
|
+
const promoteTopK = opts.promoteTopK ?? 2;
|
|
1201
|
+
const baselineCampaign = await runCampaign({
|
|
1202
|
+
...opts,
|
|
1203
|
+
dispatch: (scenario, ctx) => opts.dispatchWithSurface(opts.baselineSurface, scenario, ctx),
|
|
1204
|
+
runDir: `${opts.runDir}/baseline`
|
|
1205
|
+
});
|
|
1206
|
+
const generations = [];
|
|
1207
|
+
const history = [];
|
|
1208
|
+
let currentSurfaces = [opts.baselineSurface];
|
|
1209
|
+
let winnerSurface = opts.baselineSurface;
|
|
1210
|
+
let winnerSurfaceHash = surfaceHash(opts.baselineSurface);
|
|
1211
|
+
let winnerComposite = campaignMeanComposite(baselineCampaign);
|
|
1212
|
+
let winnerLabel;
|
|
1213
|
+
let winnerRationale;
|
|
1214
|
+
const scored = [
|
|
1215
|
+
toParetoParent(opts.baselineSurface, winnerSurfaceHash, baselineCampaign, -1)
|
|
1216
|
+
];
|
|
1217
|
+
for (let gen = 0; gen < opts.maxGenerations; gen++) {
|
|
1218
|
+
if (opts.driver.decide?.({ history }).stop) break;
|
|
1219
|
+
const paretoParents = computeParetoFrontier(scored);
|
|
1220
|
+
const proposed = await opts.driver.propose({
|
|
1221
|
+
currentSurface: currentSurfaces[0] ?? opts.baselineSurface,
|
|
1222
|
+
history,
|
|
1223
|
+
findings: [],
|
|
1224
|
+
populationSize: opts.populationSize,
|
|
1225
|
+
generation: gen,
|
|
1226
|
+
signal: new AbortController().signal,
|
|
1227
|
+
report: opts.report,
|
|
1228
|
+
dataset: opts.labeledStore && opts.labeledStore !== "off" ? opts.labeledStore : void 0,
|
|
1229
|
+
maxImprovementShots: opts.maxImprovementShots,
|
|
1230
|
+
paretoParents
|
|
1231
|
+
});
|
|
1232
|
+
const candidates = proposed.map(
|
|
1233
|
+
(p) => isProposedCandidate(p) ? p : { surface: p, label: "", rationale: "" }
|
|
1234
|
+
);
|
|
1235
|
+
const surfaceResults = [];
|
|
1236
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
1237
|
+
const { surface, label, rationale } = candidates[i];
|
|
1238
|
+
const hash = surfaceHash(surface);
|
|
1239
|
+
const campaign = await runCampaign({
|
|
1240
|
+
...opts,
|
|
1241
|
+
dispatch: (scenario, ctx) => opts.dispatchWithSurface(surface, scenario, ctx),
|
|
1242
|
+
runDir: `${opts.runDir}/gen-${gen}/candidate-${i}`
|
|
1243
|
+
});
|
|
1244
|
+
const composite = campaignMeanComposite(campaign);
|
|
1245
|
+
surfaceResults.push({ surfaceHash: hash, surface, label, rationale, campaign, composite });
|
|
1246
|
+
scored.push(
|
|
1247
|
+
toParetoParent(surface, hash, campaign, gen, label || void 0, rationale || void 0)
|
|
1248
|
+
);
|
|
1249
|
+
}
|
|
1250
|
+
surfaceResults.sort((a, b) => b.composite - a.composite);
|
|
1251
|
+
const promoted = surfaceResults.slice(0, promoteTopK);
|
|
1252
|
+
currentSurfaces = promoted.map((p) => p.surface);
|
|
1253
|
+
const top = surfaceResults[0];
|
|
1254
|
+
if (top && top.composite > winnerComposite) {
|
|
1255
|
+
winnerSurface = top.surface;
|
|
1256
|
+
winnerSurfaceHash = top.surfaceHash;
|
|
1257
|
+
winnerComposite = top.composite;
|
|
1258
|
+
winnerLabel = top.label || void 0;
|
|
1259
|
+
winnerRationale = top.rationale || void 0;
|
|
1260
|
+
}
|
|
1261
|
+
const record = {
|
|
1262
|
+
generationIndex: gen,
|
|
1263
|
+
candidates: surfaceResults.map((s) => {
|
|
1264
|
+
const breakdown = campaignBreakdown(s.campaign);
|
|
1265
|
+
const candidate = {
|
|
1266
|
+
surfaceHash: s.surfaceHash,
|
|
1267
|
+
composite: s.composite,
|
|
1268
|
+
ci95: [s.composite, s.composite],
|
|
1269
|
+
dimensions: breakdown.dimensions,
|
|
1270
|
+
scenarios: breakdown.scenarios
|
|
1271
|
+
};
|
|
1272
|
+
if (s.label) candidate.label = s.label;
|
|
1273
|
+
if (s.rationale) candidate.rationale = s.rationale;
|
|
1274
|
+
return candidate;
|
|
1275
|
+
}),
|
|
1276
|
+
promoted: promoted.map((p) => p.surfaceHash)
|
|
1277
|
+
};
|
|
1278
|
+
history.push(record);
|
|
1279
|
+
generations.push({
|
|
1280
|
+
record,
|
|
1281
|
+
surfaces: surfaceResults.map((s) => ({
|
|
1282
|
+
surfaceHash: s.surfaceHash,
|
|
1283
|
+
surface: s.surface,
|
|
1284
|
+
campaign: s.campaign
|
|
1285
|
+
}))
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
return {
|
|
1289
|
+
generations,
|
|
1290
|
+
winnerSurface,
|
|
1291
|
+
winnerSurfaceHash,
|
|
1292
|
+
winnerLabel,
|
|
1293
|
+
winnerRationale,
|
|
1294
|
+
baselineCampaign,
|
|
1295
|
+
paretoFrontier: computeParetoFrontier(scored)
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
function toParetoParent(surface, hash, campaign, generation, label, rationale) {
|
|
1299
|
+
const objectives = {};
|
|
1300
|
+
for (const { scenarioId, composite } of campaignBreakdown(campaign).scenarios) {
|
|
1301
|
+
objectives[scenarioId] = composite;
|
|
1302
|
+
}
|
|
1303
|
+
const parent = {
|
|
1304
|
+
surface,
|
|
1305
|
+
surfaceHash: hash,
|
|
1306
|
+
objectives,
|
|
1307
|
+
composite: campaignMeanComposite(campaign),
|
|
1308
|
+
generation
|
|
1309
|
+
};
|
|
1310
|
+
if (label) parent.label = label;
|
|
1311
|
+
if (rationale) parent.rationale = rationale;
|
|
1312
|
+
return parent;
|
|
1313
|
+
}
|
|
1314
|
+
function computeParetoFrontier(scored) {
|
|
1315
|
+
if (scored.length <= 1) return [...scored];
|
|
1316
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1317
|
+
for (const p of scored) for (const id of Object.keys(p.objectives)) ids.add(id);
|
|
1318
|
+
if (ids.size === 0) return [...scored];
|
|
1319
|
+
const floor = {};
|
|
1320
|
+
for (const id of ids) {
|
|
1321
|
+
let min = Number.POSITIVE_INFINITY;
|
|
1322
|
+
for (const p of scored) {
|
|
1323
|
+
const v = p.objectives[id];
|
|
1324
|
+
if (typeof v === "number" && Number.isFinite(v) && v < min) min = v;
|
|
1325
|
+
}
|
|
1326
|
+
floor[id] = Number.isFinite(min) ? min : 0;
|
|
1327
|
+
}
|
|
1328
|
+
const objectives = [...ids].map((id) => ({
|
|
1329
|
+
name: id,
|
|
1330
|
+
direction: "maximize",
|
|
1331
|
+
value: (p) => {
|
|
1332
|
+
const v = p.objectives[id];
|
|
1333
|
+
return typeof v === "number" && Number.isFinite(v) ? v : floor[id] ?? 0;
|
|
1334
|
+
}
|
|
1335
|
+
}));
|
|
1336
|
+
return paretoFrontier(scored, objectives).frontier;
|
|
1337
|
+
}
|
|
1338
|
+
function surfaceHash(surface) {
|
|
1339
|
+
const material = typeof surface === "string" ? surface : JSON.stringify({
|
|
1340
|
+
kind: surface.kind,
|
|
1341
|
+
worktreeRef: surface.worktreeRef,
|
|
1342
|
+
baseRef: surface.baseRef ?? null
|
|
1343
|
+
});
|
|
1344
|
+
return createHash("sha256").update(material).digest("hex").slice(0, 16);
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
// src/campaign/presets/run-improvement-loop.ts
|
|
1348
|
+
var DEFAULT_DISPATCH_TIMEOUT_MS = 6e5;
|
|
1349
|
+
async function runImprovementLoop(opts) {
|
|
1350
|
+
if (opts.autoOnPromote === "config") {
|
|
1351
|
+
throw new Error(
|
|
1352
|
+
"runImprovementLoop: autoOnPromote='config' is deferred to Pass B (requires shadow deploy + rollback + ensemble judges). Use 'pr' or 'none' in v0.40."
|
|
1353
|
+
);
|
|
1354
|
+
}
|
|
1355
|
+
if (opts.tracing === "off" && opts.driver) {
|
|
1356
|
+
throw new Error(
|
|
1357
|
+
"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."
|
|
1358
|
+
);
|
|
1359
|
+
}
|
|
1360
|
+
if (opts.autoOnPromote === "pr" && (!opts.ghOwner || !opts.ghRepo)) {
|
|
1361
|
+
throw new Error("runImprovementLoop: autoOnPromote='pr' requires ghOwner + ghRepo.");
|
|
1362
|
+
}
|
|
1363
|
+
const dispatchTimeoutMs = opts.dispatchTimeoutMs ?? DEFAULT_DISPATCH_TIMEOUT_MS;
|
|
1364
|
+
const optimization = await runOptimization({ ...opts, dispatchTimeoutMs });
|
|
1365
|
+
const winnerIsBaseline = optimization.winnerSurfaceHash === surfaceHash(opts.baselineSurface);
|
|
1366
|
+
const { runCampaign: runCampaign2 } = await import("./run-campaign-BVY3RGAZ.js");
|
|
1367
|
+
const baselineOnHoldout = await runCampaign2({
|
|
1368
|
+
...opts,
|
|
1369
|
+
dispatchTimeoutMs,
|
|
1370
|
+
scenarios: opts.holdoutScenarios,
|
|
1371
|
+
dispatch: (scenario, ctx) => opts.dispatchWithSurface(opts.baselineSurface, scenario, ctx),
|
|
1372
|
+
runDir: `${opts.runDir}/holdout-baseline`
|
|
1373
|
+
});
|
|
1374
|
+
const winnerOnHoldout = winnerIsBaseline ? baselineOnHoldout : await runCampaign2({
|
|
1375
|
+
...opts,
|
|
1376
|
+
dispatchTimeoutMs,
|
|
1377
|
+
scenarios: opts.holdoutScenarios,
|
|
1378
|
+
dispatch: (scenario, ctx) => opts.dispatchWithSurface(optimization.winnerSurface, scenario, ctx),
|
|
1379
|
+
runDir: `${opts.runDir}/holdout-winner`
|
|
1380
|
+
});
|
|
1381
|
+
const scorable = (r) => r.cells.filter((c) => !c.error && c.artifact != null);
|
|
1382
|
+
const baseScorable = scorable(baselineOnHoldout);
|
|
1383
|
+
const winnerScorable = scorable(winnerOnHoldout);
|
|
1384
|
+
if (baseScorable.length === 0 || winnerScorable.length === 0) {
|
|
1385
|
+
const firstErr = (r) => r.cells.find((c) => c.error)?.error ?? "unknown";
|
|
1386
|
+
throw new Error(
|
|
1387
|
+
`runImprovementLoop: holdout produced no scorable cells (baseline ${baseScorable.length}/${baselineOnHoldout.cells.length}, winner ${winnerScorable.length}/${winnerOnHoldout.cells.length}) \u2014 every holdout dispatch or judge failed. Refusing to emit a gate decision over an empty holdout. First baseline error: "${firstErr(baselineOnHoldout)}"; first winner error: "${firstErr(winnerOnHoldout)}".`
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
const candidateArtifacts = /* @__PURE__ */ new Map();
|
|
1391
|
+
const baselineArtifacts = /* @__PURE__ */ new Map();
|
|
1392
|
+
const judgeScores = /* @__PURE__ */ new Map();
|
|
1393
|
+
const baselineJudgeScores = /* @__PURE__ */ new Map();
|
|
1394
|
+
for (const cell of winnerOnHoldout.cells) {
|
|
1395
|
+
candidateArtifacts.set(cell.cellId, cell.artifact);
|
|
1396
|
+
judgeScores.set(cell.cellId, cell.judgeScores);
|
|
1397
|
+
}
|
|
1398
|
+
for (const cell of baselineOnHoldout.cells) {
|
|
1399
|
+
baselineArtifacts.set(cell.cellId, cell.artifact);
|
|
1400
|
+
baselineJudgeScores.set(cell.cellId, cell.judgeScores);
|
|
1401
|
+
}
|
|
1402
|
+
const gateResult = winnerIsBaseline ? {
|
|
1403
|
+
decision: "hold",
|
|
1404
|
+
reasons: [
|
|
1405
|
+
"no candidate beat the training baseline \u2014 winner == baseline (empty diff); nothing to promote"
|
|
1406
|
+
],
|
|
1407
|
+
contributingGates: [
|
|
1408
|
+
{ name: "no-op-guard", passed: false, detail: { winnerIsBaseline: true } }
|
|
1409
|
+
],
|
|
1410
|
+
delta: 0
|
|
1411
|
+
} : await opts.gate.decide({
|
|
1412
|
+
candidateArtifacts,
|
|
1413
|
+
baselineArtifacts,
|
|
1414
|
+
judgeScores,
|
|
1415
|
+
baselineJudgeScores,
|
|
1416
|
+
scenarios: opts.holdoutScenarios,
|
|
1417
|
+
cost: {
|
|
1418
|
+
candidate: winnerOnHoldout.aggregates.totalCostUsd,
|
|
1419
|
+
baseline: baselineOnHoldout.aggregates.totalCostUsd
|
|
1420
|
+
},
|
|
1421
|
+
signal: new AbortController().signal
|
|
1422
|
+
});
|
|
1423
|
+
const render = opts.renderPromotedDiff ?? defaultRenderDiff;
|
|
1424
|
+
const promotedDiff = optimization.winnerSurfaceHash === surfaceHash(opts.baselineSurface) ? "" : render(optimization.winnerSurface, opts.baselineSurface);
|
|
1425
|
+
let prResult;
|
|
1426
|
+
if (opts.autoOnPromote === "pr" && gateResult.decision === "ship") {
|
|
1427
|
+
prResult = openAutoPr({
|
|
1428
|
+
result: winnerOnHoldout,
|
|
1429
|
+
gate: gateResult,
|
|
1430
|
+
promotedDiff,
|
|
1431
|
+
ghOwner: opts.ghOwner,
|
|
1432
|
+
ghRepo: opts.ghRepo
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
return {
|
|
1436
|
+
...optimization,
|
|
1437
|
+
baselineOnHoldout,
|
|
1438
|
+
winnerOnHoldout,
|
|
1439
|
+
gateResult,
|
|
1440
|
+
promotedDiff,
|
|
1441
|
+
prResult
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
function defaultRenderDiff(winnerSurface, baselineSurface) {
|
|
1445
|
+
if (typeof winnerSurface !== "string" || typeof baselineSurface !== "string") {
|
|
1446
|
+
const fmt = (s) => typeof s === "string" ? "(prompt surface)" : `worktree=${s.worktreeRef}${s.baseRef ? ` base=${s.baseRef}` : ""}${s.summary ? `
|
|
1447
|
+
${s.summary}` : ""}`;
|
|
1448
|
+
return `--- baseline
|
|
1449
|
+
${fmt(baselineSurface)}
|
|
1450
|
+
+++ winner
|
|
1451
|
+
${fmt(winnerSurface)}`;
|
|
1452
|
+
}
|
|
1453
|
+
const lines = [];
|
|
1454
|
+
lines.push("--- baseline");
|
|
1455
|
+
lines.push("+++ winner");
|
|
1456
|
+
for (const l of baselineSurface.split("\n")) lines.push(`- ${l}`);
|
|
1457
|
+
for (const l of winnerSurface.split("\n")) lines.push(`+ ${l}`);
|
|
1458
|
+
return lines.join("\n");
|
|
1459
|
+
}
|
|
1460
|
+
|
|
831
1461
|
export {
|
|
832
1462
|
dominates,
|
|
833
1463
|
paretoFrontier,
|
|
@@ -845,6 +1475,19 @@ export {
|
|
|
845
1475
|
runCanaries,
|
|
846
1476
|
DEFAULT_MUTATION_PRIMITIVES,
|
|
847
1477
|
buildReflectionPrompt,
|
|
848
|
-
parseReflectionResponse
|
|
1478
|
+
parseReflectionResponse,
|
|
1479
|
+
gepaDriver,
|
|
1480
|
+
extractH2Sections,
|
|
1481
|
+
countSentenceEdits,
|
|
1482
|
+
heldOutGate,
|
|
1483
|
+
openAutoPr,
|
|
1484
|
+
campaignMeanComposite,
|
|
1485
|
+
campaignBreakdown,
|
|
1486
|
+
isProposedCandidate,
|
|
1487
|
+
labelTrustRank,
|
|
1488
|
+
runOptimization,
|
|
1489
|
+
surfaceHash,
|
|
1490
|
+
runImprovementLoop,
|
|
1491
|
+
defaultRenderDiff
|
|
849
1492
|
};
|
|
850
|
-
//# sourceMappingURL=chunk-
|
|
1493
|
+
//# sourceMappingURL=chunk-NV2PF37Q.js.map
|