@warmdrift/kgauto-compiler 2.0.0-alpha.61 → 2.0.0-alpha.63

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 (36) hide show
  1. package/README.md +30 -12
  2. package/dist/brain-proxy.js +5 -1
  3. package/dist/brain-proxy.mjs +1 -1
  4. package/dist/{chunk-5TI6PNSK.mjs → chunk-3KQAID63.mjs} +5 -0
  5. package/dist/{chunk-IUWFML6Z.mjs → chunk-65ZMX5OT.mjs} +5 -1
  6. package/dist/{chunk-IIMPJZNH.mjs → chunk-YZRPNSSQ.mjs} +10 -0
  7. package/dist/{chunk-3RMLZCUK.mjs → chunk-ZU62HRWK.mjs} +1 -1
  8. package/dist/dialect.d.mts +14 -2
  9. package/dist/dialect.d.ts +14 -2
  10. package/dist/dialect.js +5 -0
  11. package/dist/dialect.mjs +1 -1
  12. package/dist/glassbox/index.d.mts +3 -3
  13. package/dist/glassbox/index.d.ts +3 -3
  14. package/dist/glassbox-routes/format.d.mts +2 -2
  15. package/dist/glassbox-routes/format.d.ts +2 -2
  16. package/dist/glassbox-routes/index.d.mts +4 -4
  17. package/dist/glassbox-routes/index.d.ts +4 -4
  18. package/dist/glassbox-routes/index.js +10 -0
  19. package/dist/glassbox-routes/index.mjs +1 -1
  20. package/dist/glassbox-routes/react/index.d.mts +2 -2
  21. package/dist/glassbox-routes/react/index.d.ts +2 -2
  22. package/dist/index.d.mts +193 -6
  23. package/dist/index.d.ts +193 -6
  24. package/dist/index.js +685 -2
  25. package/dist/index.mjs +655 -4
  26. package/dist/{ir-DAKlQsVb.d.mts → ir-B2dRyJXO.d.mts} +74 -9
  27. package/dist/{ir-DmUuJsWc.d.ts → ir-ClU56aBc.d.ts} +74 -9
  28. package/dist/key-health.js +1 -1
  29. package/dist/key-health.mjs +1 -1
  30. package/dist/profiles.d.mts +1 -1
  31. package/dist/profiles.d.ts +1 -1
  32. package/dist/{types-B8X1Pyhx.d.ts → types-ByN3r0_7.d.ts} +1 -1
  33. package/dist/{types-DR62iPcO.d.ts → types-C-Wp7HpI.d.ts} +1 -1
  34. package/dist/{types-MRMBUqzY.d.mts → types-CSDweZsl.d.mts} +1 -1
  35. package/dist/{types-CssWqd0X.d.mts → types-axAX1Bg0.d.mts} +1 -1
  36. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ __export(index_exports, {
30
30
  DIALECT_VERSION: () => DIALECT_VERSION,
31
31
  FamilyResolutionError: () => FamilyResolutionError,
32
32
  INTENT_ARCHETYPES: () => INTENT_ARCHETYPES,
33
+ JUDGE_RUBRICS: () => JUDGE_RUBRICS,
33
34
  LATENCY_TIER_MS: () => LATENCY_TIER_MS,
34
35
  LIBRARY_VERSION: () => LIBRARY_VERSION,
35
36
  MEASURED_GROUNDING_MIN_N: () => MEASURED_GROUNDING_MIN_N,
@@ -45,10 +46,14 @@ __export(index_exports, {
45
46
  bucketContext: () => bucketContext,
46
47
  bucketHistory: () => bucketHistory,
47
48
  bucketToolCount: () => bucketToolCount,
49
+ buildGoldenIrRow: () => buildGoldenIrRow,
48
50
  buildLLMJudge: () => buildLLMJudge,
51
+ buildPairwiseJudgePrompt: () => buildPairwiseJudgePrompt,
49
52
  buildShadowProbeRow: () => buildShadowProbeRow,
50
53
  call: () => call,
54
+ captureGoldenIr: () => captureGoldenIr,
51
55
  clearBrain: () => clearBrain,
56
+ combineOrderSwappedVerdicts: () => combineOrderSwappedVerdicts,
52
57
  compile: () => compile2,
53
58
  compileForAISDKv6: () => compileForAISDKv6,
54
59
  configureBrain: () => configureBrain,
@@ -94,20 +99,28 @@ __export(index_exports, {
94
99
  markAdvisoryResolved: () => markAdvisoryResolved,
95
100
  markExclusionFindingHandled: () => markExclusionFindingHandled,
96
101
  markPromoteReadyHandled: () => markPromoteReadyHandled,
102
+ parseGoldenCaptureRate: () => parseGoldenCaptureRate,
103
+ parseJudgeVerdict: () => parseJudgeVerdict,
97
104
  peekBrainDeadLetter: () => peekBrainDeadLetter,
98
105
  probeShadow: () => probeShadow,
99
106
  profileToRow: () => profileToRow,
100
107
  profilesByProvider: () => profilesByProvider,
101
108
  readBrainReadEnv: () => readBrainReadEnv,
102
109
  record: () => record,
110
+ recordGoldenIr: () => recordGoldenIr,
103
111
  recordOutcome: () => recordOutcome,
104
112
  recordShadowProbe: () => recordShadowProbe,
113
+ renderIrForJudge: () => renderIrForJudge,
105
114
  resetTokenizer: () => resetTokenizer,
106
115
  resolveConventionsForProfile: () => resolveConventionsForProfile,
116
+ resolveGoldenCaptureRate: () => resolveGoldenCaptureRate,
107
117
  resolvePricingAt: () => resolvePricingAt,
108
118
  resolveProviderKey: () => resolveProviderKey,
119
+ rubricFor: () => rubricFor,
109
120
  runAdvisor: () => runAdvisor,
121
+ runGoldenEval: () => runGoldenEval,
110
122
  setTokenizer: () => setTokenizer,
123
+ shouldCaptureGolden: () => shouldCaptureGolden,
111
124
  tryGetProfile: () => tryGetProfile
112
125
  });
113
126
  module.exports = __toCommonJS(index_exports);
@@ -2295,6 +2308,11 @@ var INTENT_ARCHETYPES = {
2295
2308
  name: "transform",
2296
2309
  description: "Change format or style while preserving content",
2297
2310
  examples: ["markdown \u2192 html", "formal \u2192 casual", "translate"]
2311
+ },
2312
+ judge: {
2313
+ name: "judge",
2314
+ description: "Pairwise comparison of two candidate outputs for the same input",
2315
+ examples: ["golden-set eval A/B verdict", "model-swap non-inferiority check", "response bake-off"]
2298
2316
  }
2299
2317
  };
2300
2318
  var ALL_ARCHETYPES = Object.keys(INTENT_ARCHETYPES);
@@ -5005,6 +5023,61 @@ async function recordShadowProbe(input) {
5005
5023
  void send();
5006
5024
  }
5007
5025
  }
5026
+ function peekRegisteredShapeKey(handle) {
5027
+ return compileRegistry.get(handle)?.shapeKey;
5028
+ }
5029
+ function buildGoldenIrRow(input) {
5030
+ return {
5031
+ app_id: input.appId,
5032
+ intent_archetype: input.archetype,
5033
+ shape_key: input.shapeKey ?? null,
5034
+ ir: input.ir,
5035
+ incumbent_model: input.incumbentModel,
5036
+ incumbent_output: input.incumbentOutput ?? null,
5037
+ incumbent_latency_ms: input.incumbentLatencyMs ?? null,
5038
+ incumbent_tokens_in: input.incumbentTokensIn ?? null,
5039
+ incumbent_tokens_out: input.incumbentTokensOut ?? null,
5040
+ source: input.source,
5041
+ consent: input.consent,
5042
+ outcome_handle: input.outcomeHandle ?? null
5043
+ };
5044
+ }
5045
+ async function recordGoldenIr(input) {
5046
+ if (!activeConfig) return;
5047
+ const config = activeConfig;
5048
+ const fetchFn = brainWriteFetch(config);
5049
+ const row = buildGoldenIrRow(input);
5050
+ const send = async () => {
5051
+ noteSent();
5052
+ try {
5053
+ const res = await fetchFn(`${config.endpoint}/golden_irs`, {
5054
+ method: "POST",
5055
+ headers: {
5056
+ "Content-Type": "application/json",
5057
+ Prefer: "return=minimal",
5058
+ ...config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}
5059
+ },
5060
+ body: JSON.stringify(row)
5061
+ });
5062
+ assertNotRedirected(res, "golden_irs");
5063
+ if (!res.ok) {
5064
+ const text = await res.text().catch(() => "<no body>");
5065
+ throw new Error(describeBrainWriteFailure(res.status, "golden_irs", text));
5066
+ }
5067
+ noteAck();
5068
+ maybeAutoFlush();
5069
+ } catch (err) {
5070
+ noteFailure(err);
5071
+ pushDeadLetter("golden_irs", config.endpoint, row, err);
5072
+ (config.onError ?? defaultOnError5)(err);
5073
+ }
5074
+ };
5075
+ if (config.sync) {
5076
+ await send();
5077
+ } else {
5078
+ void send();
5079
+ }
5080
+ }
5008
5081
 
5009
5082
  // src/ir.ts
5010
5083
  var CallError = class extends Error {
@@ -5020,6 +5093,45 @@ var CallError = class extends Error {
5020
5093
  }
5021
5094
  };
5022
5095
 
5096
+ // src/golden.ts
5097
+ function parseGoldenCaptureRate(raw) {
5098
+ if (raw === void 0 || raw.trim() === "") return 0;
5099
+ const n = Number(raw);
5100
+ if (!Number.isFinite(n)) return 0;
5101
+ return Math.max(0, Math.min(1, n));
5102
+ }
5103
+ function resolveGoldenCaptureRate(optRate) {
5104
+ if (optRate !== void 0 && Number.isFinite(optRate)) {
5105
+ return Math.max(0, Math.min(1, optRate));
5106
+ }
5107
+ const env = typeof process !== "undefined" && process.env ? process.env.KGAUTO_GOLDEN_CAPTURE : void 0;
5108
+ return parseGoldenCaptureRate(env);
5109
+ }
5110
+ function shouldCaptureGolden(rate, rng = Math.random) {
5111
+ if (rate <= 0) return false;
5112
+ if (rate >= 1) return true;
5113
+ return rng() < rate;
5114
+ }
5115
+ async function captureGoldenIr(ctx) {
5116
+ try {
5117
+ await recordGoldenIr({
5118
+ appId: ctx.ir.appId,
5119
+ archetype: ctx.ir.intent.archetype,
5120
+ shapeKey: ctx.shapeKey,
5121
+ ir: ctx.ir,
5122
+ incumbentModel: ctx.servedModel,
5123
+ incumbentOutput: ctx.response.text,
5124
+ incumbentLatencyMs: ctx.latencyMs,
5125
+ incumbentTokensIn: ctx.response.tokens.input,
5126
+ incumbentTokensOut: ctx.response.tokens.output,
5127
+ source: "sampled",
5128
+ consent: ctx.consent,
5129
+ outcomeHandle: ctx.handle
5130
+ });
5131
+ } catch {
5132
+ }
5133
+ }
5134
+
5023
5135
  // src/env.ts
5024
5136
  var SUPPORTED_PROVIDERS = Object.freeze([
5025
5137
  "anthropic",
@@ -5654,6 +5766,16 @@ var STARTER_CHAINS_GROUNDED = {
5654
5766
  { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor in similar quality bracket" },
5655
5767
  { id: "gpt-5.5", grounding: "judgment", reason: "alpha.16: third-provider frontier-tier floor (archetypePerf=9)" }
5656
5768
  ],
5769
+ // alpha.62 (eval spine) — pairwise output comparison. Same reasoning-floor
5770
+ // posture as critique (a verdict from a weak judge is worse than no
5771
+ // verdict); tier 0 anchored on the CURRENT opus (4-8, s64 roster). Strict
5772
+ // JSON output, so every tier declares native structured output.
5773
+ judge: [
5774
+ { id: "claude-opus-4-8", grounding: "judgment", reason: "Highest reasoning bar for pairwise verdicts \u2014 current opus (s64 roster)" },
5775
+ { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Same-provider walk-down on 429" },
5776
+ { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor in similar quality bracket" },
5777
+ { id: "gpt-5.5", grounding: "judgment", reason: "Third-provider frontier-tier floor" }
5778
+ ],
5657
5779
  // Reasoning matters — Sonnet primary; walk UP to Opus on 429.
5658
5780
  plan: [
5659
5781
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Reasoning + cost balance \u2014 engineer pick" },
@@ -6446,6 +6568,8 @@ async function call(ir, opts = {}) {
6446
6568
  );
6447
6569
  const fellOver = targetModel !== initial.target;
6448
6570
  const fallbackReason = fellOver ? normalizeFallbackReason(attempts) : void 0;
6571
+ const goldenRate = resolveGoldenCaptureRate(opts.goldenCapture?.sampleRate);
6572
+ const goldenShapeKey = goldenRate > 0 ? peekRegisteredShapeKey(initial.handle) : void 0;
6449
6573
  await record({
6450
6574
  handle: initial.handle,
6451
6575
  tokensIn: validated.response.tokens.input,
@@ -6498,6 +6622,23 @@ async function call(ir, opts = {}) {
6498
6622
  void probe;
6499
6623
  }
6500
6624
  }
6625
+ if (goldenRate > 0 && validated.response.tokens.output > 0 && shouldCaptureGolden(goldenRate)) {
6626
+ const consent = opts.goldenCapture?.sampleRate !== void 0 ? `CallOptions.goldenCapture.sampleRate=${goldenRate} (consumer code opt-in)` + (opts.goldenCapture.consentNote ? ` \u2014 ${opts.goldenCapture.consentNote}` : "") : `KGAUTO_GOLDEN_CAPTURE=${goldenRate} (consumer env opt-in)`;
6627
+ const capture = captureGoldenIr({
6628
+ ir,
6629
+ servedModel: targetModel,
6630
+ response: validated.response,
6631
+ latencyMs: latencyMs2,
6632
+ handle: initial.handle,
6633
+ shapeKey: goldenShapeKey,
6634
+ consent
6635
+ });
6636
+ if (isBrainSync()) {
6637
+ await capture;
6638
+ } else {
6639
+ void capture;
6640
+ }
6641
+ }
6501
6642
  return {
6502
6643
  handle: initial.handle,
6503
6644
  actualModel: targetModel,
@@ -6837,6 +6978,18 @@ function safeEmit(fn) {
6837
6978
  } catch {
6838
6979
  }
6839
6980
  }
6981
+ var _internal = {
6982
+ compileAndRegister,
6983
+ validateStructuredContract,
6984
+ extractPromptPreview,
6985
+ normalizeFallbackReason,
6986
+ generateTraceId,
6987
+ safeEmit,
6988
+ shouldSampleProbe,
6989
+ normalizeProbeCandidates,
6990
+ runShadowProbe,
6991
+ runProbeCandidates
6992
+ };
6840
6993
 
6841
6994
  // src/streamtext-helpers.ts
6842
6995
  function attachCacheControlToStreamTextInput(result, convertedMessages) {
@@ -6936,12 +7089,529 @@ function extractKeptToolNames(result) {
6936
7089
  return names;
6937
7090
  }
6938
7091
 
7092
+ // src/golden-eval.ts
7093
+ var GENERIC_RUBRIC = "overall correctness, completeness against the request, clarity, and adherence to any requested format";
7094
+ var JUDGE_RUBRICS = {
7095
+ summarize: "faithfulness to the source (no fabricated facts), coverage of the key points, concision, and adherence to the requested output format",
7096
+ classify: "assignment of the correct category from the allowed set, and nothing outside the allowed set",
7097
+ generate: "relevance to the brief, quality and coherence of the writing, and adherence to the requested format and tone",
7098
+ extract: "completeness of extraction (nothing relevant missed), precision (no invented fields or values), and exact schema adherence",
7099
+ ask: "correctness of the answer with respect to the provided data, relevance, and absence of fabrication",
7100
+ hunt: "relevance and novelty of the discovered entities, and absence of duplicates or fabricated entries",
7101
+ plan: "quality of the decomposition (complete, ordered, actionable steps) and realism of the sequencing",
7102
+ critique: "specificity and correctness of the assessment, and actionability of the feedback",
7103
+ transform: "preservation of the source content and correctness of the target format or style"
7104
+ };
7105
+ function rubricFor(archetype) {
7106
+ return JUDGE_RUBRICS[archetype] ?? GENERIC_RUBRIC;
7107
+ }
7108
+ var INPUT_TRUNCATE_CHARS = 24e3;
7109
+ var OUTPUT_TRUNCATE_CHARS = 12e3;
7110
+ function renderIrForJudge(ir) {
7111
+ const sections = (ir.sections ?? []).map((s) => s.text).filter(Boolean).join("\n\n");
7112
+ const turn = typeof ir.currentTurn?.content === "string" ? ir.currentTurn.content : "";
7113
+ const combined = [
7114
+ sections ? `[system]
7115
+ ${sections}` : "",
7116
+ turn ? `[user]
7117
+ ${turn}` : ""
7118
+ ].filter(Boolean).join("\n\n");
7119
+ return combined.length > INPUT_TRUNCATE_CHARS ? `${combined.slice(0, INPUT_TRUNCATE_CHARS)}
7120
+ \u2026[truncated]` : combined;
7121
+ }
7122
+ function buildPairwiseJudgePrompt(args) {
7123
+ const clip = (s) => s.length > OUTPUT_TRUNCATE_CHARS ? `${s.slice(0, OUTPUT_TRUNCATE_CHARS)}
7124
+ \u2026[truncated]` : s;
7125
+ return `You are a strict pairwise judge comparing two AI responses to the SAME request.
7126
+
7127
+ The request (archetype: ${args.archetype}):
7128
+ <request>
7129
+ ${args.renderedInput}
7130
+ </request>
7131
+
7132
+ Response A:
7133
+ <response_a>
7134
+ ${clip(args.outputA)}
7135
+ </response_a>
7136
+
7137
+ Response B:
7138
+ <response_b>
7139
+ ${clip(args.outputB)}
7140
+ </response_b>
7141
+
7142
+ Judge which response better satisfies the request. Rubric for ${args.archetype}: ${rubricFor(args.archetype)}.
7143
+
7144
+ A tie is a legitimate verdict \u2014 declare it when the responses are of genuinely comparable quality. Do NOT prefer a response merely for being longer.
7145
+
7146
+ Output ONLY this JSON, no other text:
7147
+ {"winner": "A" | "B" | "tie", "rationale": "<one sentence>"}`;
7148
+ }
7149
+ function parseJudgeVerdict(raw) {
7150
+ const cleaned = raw.replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim();
7151
+ let parsed;
7152
+ try {
7153
+ parsed = JSON.parse(cleaned);
7154
+ } catch {
7155
+ const match = cleaned.match(/\{[\s\S]*\}/);
7156
+ if (!match) return void 0;
7157
+ try {
7158
+ parsed = JSON.parse(match[0]);
7159
+ } catch {
7160
+ return void 0;
7161
+ }
7162
+ }
7163
+ if (!parsed || typeof parsed !== "object") return void 0;
7164
+ const obj = parsed;
7165
+ const winner = obj.winner;
7166
+ if (winner !== "A" && winner !== "B" && winner !== "tie") return void 0;
7167
+ return {
7168
+ winner,
7169
+ rationale: typeof obj.rationale === "string" ? obj.rationale : void 0
7170
+ };
7171
+ }
7172
+ function combineOrderSwappedVerdicts(run1, run2) {
7173
+ if (run1 === run2) return run1;
7174
+ return "tied";
7175
+ }
7176
+ function replayRetryDelayMs(errorCode) {
7177
+ return errorCode === "rate_limit" ? 65e3 : 2e3;
7178
+ }
7179
+ function p50(values) {
7180
+ if (values.length === 0) return null;
7181
+ const sorted = [...values].sort((a, b) => a - b);
7182
+ return sorted[Math.floor(sorted.length / 2)] ?? null;
7183
+ }
7184
+ function costUsd(model, tokensIn, tokensOut) {
7185
+ const profile = tryGetProfile(model);
7186
+ if (!profile) return null;
7187
+ return tokensIn / 1e6 * profile.costInputPer1m + tokensOut / 1e6 * profile.costOutputPer1m;
7188
+ }
7189
+ function hashForGolden(s) {
7190
+ let h = 5381;
7191
+ for (let i = 0; i < s.length; i += 1) {
7192
+ h = (h << 5) + h + s.charCodeAt(i) >>> 0;
7193
+ }
7194
+ return `g${h.toString(36)}`;
7195
+ }
7196
+ async function runGoldenEval(opts) {
7197
+ const fetchFn = opts.fetchImpl ?? fetch;
7198
+ const progress = opts.onProgress ?? (() => {
7199
+ });
7200
+ const limit = opts.limit ?? 50;
7201
+ const threshold = opts.winOrTieThreshold ?? 0.8;
7202
+ const latencyFloorRatio = opts.latencyFloorRatio ?? 3;
7203
+ const minJudgeable = opts.minJudgeableCases ?? 5;
7204
+ const judgeModel = opts.judgeModel ?? "claude-opus-4-8";
7205
+ const notes = [];
7206
+ const restHeaders = {
7207
+ apikey: opts.serviceKey,
7208
+ Authorization: `Bearer ${opts.serviceKey}`
7209
+ };
7210
+ const rest = (path) => `${opts.supabaseUrl}/rest/v1/${path}`;
7211
+ const setUrl = rest(
7212
+ `kgauto_golden_irs?app_id=eq.${encodeURIComponent(opts.appId)}&intent_archetype=eq.${encodeURIComponent(opts.archetype)}&active=is.true&select=id,app_id,intent_archetype,ir,incumbent_model&order=captured_at.desc&limit=${limit}`
7213
+ );
7214
+ const setRes = await fetchFn(setUrl, { headers: restHeaders });
7215
+ if (!setRes.ok) {
7216
+ throw new Error(
7217
+ `golden-eval: failed to load golden set (${setRes.status}): ${await setRes.text().catch(() => "<no body>")}`
7218
+ );
7219
+ }
7220
+ const goldenRows = await setRes.json();
7221
+ if (goldenRows.length === 0) {
7222
+ throw new Error(
7223
+ `golden-eval: no active golden IRs for (${opts.appId}, ${opts.archetype}) \u2014 seed via KGAUTO_GOLDEN_CAPTURE or scripts/seed-golden-set.mjs first.`
7224
+ );
7225
+ }
7226
+ progress(`Loaded ${goldenRows.length} golden case(s).`);
7227
+ let incumbentModel = opts.incumbentModel;
7228
+ if (!incumbentModel) {
7229
+ const counts = /* @__PURE__ */ new Map();
7230
+ for (const row of goldenRows) {
7231
+ counts.set(row.incumbent_model, (counts.get(row.incumbent_model) ?? 0) + 1);
7232
+ }
7233
+ const top = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];
7234
+ if (!top) throw new Error("golden-eval: could not resolve an incumbent from the golden set.");
7235
+ incumbentModel = top[0];
7236
+ notes.push(`incumbent defaulted to most-captured model: ${incumbentModel}`);
7237
+ }
7238
+ if (incumbentModel === opts.candidateModel) {
7239
+ throw new Error("golden-eval: candidate and incumbent are the same model.");
7240
+ }
7241
+ const judgeProfile = tryGetProfile(judgeModel);
7242
+ if (!judgeProfile) {
7243
+ throw new Error(`golden-eval: judge model '${judgeModel}' is not in the roster.`);
7244
+ }
7245
+ if (judgeProfile.family && [incumbentModel, opts.candidateModel].some(
7246
+ (m) => tryGetProfile(m)?.family === judgeProfile.family
7247
+ )) {
7248
+ notes.push(
7249
+ `WARNING: judge family (${judgeProfile.family}) overlaps a compared model \u2014 self-preference risk; consider --judge from another provider.`
7250
+ );
7251
+ }
7252
+ const replay = async (ir, model) => {
7253
+ try {
7254
+ const evalIr = {
7255
+ ...ir,
7256
+ models: [model],
7257
+ constraints: { ...ir.constraints ?? {}, forceModel: model }
7258
+ };
7259
+ const compiled = compile(evalIr);
7260
+ const attempt = () => execute(compiled.request, { apiKeys: opts.apiKeys, fetchImpl: opts.fetchImpl });
7261
+ let started = Date.now();
7262
+ let exec = await attempt();
7263
+ if (!exec.ok && exec.errorType === "retryable") {
7264
+ const delayMs = replayRetryDelayMs(exec.errorCode);
7265
+ await new Promise((r) => setTimeout(r, delayMs));
7266
+ started = Date.now();
7267
+ exec = await attempt();
7268
+ }
7269
+ const latencyMs = Date.now() - started;
7270
+ if (!exec.ok) {
7271
+ return {
7272
+ ok: false,
7273
+ text: "",
7274
+ structuredOutput: null,
7275
+ tokensIn: 0,
7276
+ tokensOut: 0,
7277
+ latencyMs,
7278
+ errorClass: exec.errorCode
7279
+ };
7280
+ }
7281
+ const validated = _internal.validateStructuredContract(exec, evalIr);
7282
+ if (!validated.ok) {
7283
+ return {
7284
+ ok: true,
7285
+ text: exec.response.text,
7286
+ structuredOutput: null,
7287
+ tokensIn: exec.response.tokens.input,
7288
+ tokensOut: exec.response.tokens.output,
7289
+ latencyMs,
7290
+ contractViolation: validated.errorCode
7291
+ };
7292
+ }
7293
+ return {
7294
+ ok: true,
7295
+ text: validated.response.text,
7296
+ structuredOutput: validated.response.structuredOutput,
7297
+ parseError: validated.response.parseError,
7298
+ tokensIn: validated.response.tokens.input,
7299
+ tokensOut: validated.response.tokens.output,
7300
+ latencyMs
7301
+ };
7302
+ } catch (err) {
7303
+ return {
7304
+ ok: false,
7305
+ text: "",
7306
+ structuredOutput: null,
7307
+ tokensIn: 0,
7308
+ tokensOut: 0,
7309
+ latencyMs: 0,
7310
+ errorClass: err instanceof Error ? `execute_rejected:${err.message}` : "execute_rejected"
7311
+ };
7312
+ }
7313
+ };
7314
+ const judgeOnce = async (ir, outputA, outputB) => {
7315
+ const judgeIr = {
7316
+ appId: opts.appId,
7317
+ intent: { name: "golden-eval-judge", archetype: "judge" },
7318
+ sections: [
7319
+ {
7320
+ id: "role",
7321
+ text: "You are a strict, impartial pairwise judge. You output only JSON.",
7322
+ weight: 10
7323
+ }
7324
+ ],
7325
+ currentTurn: {
7326
+ role: "user",
7327
+ content: buildPairwiseJudgePrompt({
7328
+ archetype: opts.archetype,
7329
+ renderedInput: renderIrForJudge(ir),
7330
+ outputA,
7331
+ outputB
7332
+ })
7333
+ },
7334
+ models: [judgeModel],
7335
+ constraints: { forceModel: judgeModel }
7336
+ };
7337
+ try {
7338
+ const compiled = compile(judgeIr);
7339
+ const exec = await execute(compiled.request, {
7340
+ apiKeys: opts.apiKeys,
7341
+ fetchImpl: opts.fetchImpl
7342
+ });
7343
+ if (!exec.ok) return void 0;
7344
+ return parseJudgeVerdict(exec.response.text);
7345
+ } catch {
7346
+ return void 0;
7347
+ }
7348
+ };
7349
+ const cases = [];
7350
+ const floorDetail = {};
7351
+ const bumpFloor = (k) => {
7352
+ floorDetail[k] = (floorDetail[k] ?? 0) + 1;
7353
+ };
7354
+ for (const [i, row] of goldenRows.entries()) {
7355
+ progress(
7356
+ `Case ${i + 1}/${goldenRows.length} (golden #${row.id}): replaying ${incumbentModel} + ${opts.candidateModel}\u2026`
7357
+ );
7358
+ const [inc, cand] = await Promise.all([
7359
+ replay(row.ir, incumbentModel),
7360
+ replay(row.ir, opts.candidateModel)
7361
+ ]);
7362
+ if (!inc.ok || inc.contractViolation) {
7363
+ const why = !inc.ok ? `incumbent replay failed (${inc.errorClass ?? "unknown"})` : `incumbent contract violation (${inc.contractViolation})`;
7364
+ cases.push({
7365
+ goldenIrId: row.id,
7366
+ verdict: "inconclusive",
7367
+ floorViolations: [],
7368
+ excludedReason: why
7369
+ });
7370
+ notes.push(`case #${row.id}: ${why} \u2014 excluded`);
7371
+ continue;
7372
+ }
7373
+ const incumbentLeg = {
7374
+ latencyMs: inc.latencyMs,
7375
+ tokensIn: inc.tokensIn,
7376
+ tokensOut: inc.tokensOut,
7377
+ text: inc.text
7378
+ };
7379
+ const violations = [];
7380
+ if (!cand.ok) {
7381
+ violations.push("candidate_error");
7382
+ bumpFloor("candidate_error");
7383
+ } else if (cand.tokensOut === 0 || cand.text.trim() === "" && !cand.structuredOutput) {
7384
+ violations.push("empty");
7385
+ bumpFloor("empty");
7386
+ } else if (cand.contractViolation) {
7387
+ violations.push("schema");
7388
+ bumpFloor("schema");
7389
+ }
7390
+ if (violations.length > 0) {
7391
+ cases.push({
7392
+ goldenIrId: row.id,
7393
+ verdict: "current-better",
7394
+ floorViolations: violations,
7395
+ errorClass: cand.errorClass ?? cand.contractViolation,
7396
+ incumbent: incumbentLeg,
7397
+ candidate: cand.ok ? { latencyMs: cand.latencyMs, tokensIn: cand.tokensIn, tokensOut: cand.tokensOut, text: cand.text } : void 0
7398
+ });
7399
+ continue;
7400
+ }
7401
+ const [order1, order2] = await Promise.all([
7402
+ judgeOnce(row.ir, inc.text, cand.text),
7403
+ judgeOnce(row.ir, cand.text, inc.text)
7404
+ ]);
7405
+ if (!order1 || !order2) {
7406
+ cases.push({
7407
+ goldenIrId: row.id,
7408
+ verdict: "inconclusive",
7409
+ floorViolations: [],
7410
+ incumbent: incumbentLeg,
7411
+ candidate: { latencyMs: cand.latencyMs, tokensIn: cand.tokensIn, tokensOut: cand.tokensOut, text: cand.text },
7412
+ excludedReason: "judge call failed or unparseable"
7413
+ });
7414
+ notes.push(`case #${row.id}: judge failed \u2014 excluded`);
7415
+ continue;
7416
+ }
7417
+ const v1 = order1.winner === "tie" ? "tied" : order1.winner === "B" ? "candidate-better" : "current-better";
7418
+ const v2 = order2.winner === "tie" ? "tied" : order2.winner === "A" ? "candidate-better" : "current-better";
7419
+ const verdict2 = combineOrderSwappedVerdicts(v1, v2);
7420
+ cases.push({
7421
+ goldenIrId: row.id,
7422
+ verdict: verdict2,
7423
+ judgeRationale: order1.rationale ?? order2.rationale,
7424
+ floorViolations: [],
7425
+ incumbent: incumbentLeg,
7426
+ candidate: { latencyMs: cand.latencyMs, tokensIn: cand.tokensIn, tokensOut: cand.tokensOut, text: cand.text }
7427
+ });
7428
+ }
7429
+ const evaluable = cases.filter((c) => !c.excludedReason);
7430
+ const wins = evaluable.filter((c) => c.verdict === "candidate-better").length;
7431
+ const ties = evaluable.filter((c) => c.verdict === "tied").length;
7432
+ const losses = evaluable.filter((c) => c.verdict === "current-better").length;
7433
+ const floorViolations = evaluable.reduce((n, c) => n + c.floorViolations.length, 0);
7434
+ const winOrTieRatio = evaluable.length > 0 ? (wins + ties) / evaluable.length : null;
7435
+ const incP50 = p50(evaluable.map((c) => c.incumbent?.latencyMs ?? NaN).filter(Number.isFinite));
7436
+ const candP50 = p50(evaluable.map((c) => c.candidate?.latencyMs ?? NaN).filter(Number.isFinite));
7437
+ const latencyRatio = incP50 && candP50 ? candP50 / incP50 : null;
7438
+ const sum = (xs) => xs.some((x) => x === null) ? null : xs.reduce((a, b) => a + b, 0);
7439
+ const costIncumbentUsd = sum(
7440
+ evaluable.map(
7441
+ (c) => c.incumbent ? costUsd(incumbentModel, c.incumbent.tokensIn, c.incumbent.tokensOut) : null
7442
+ )
7443
+ );
7444
+ const costCandidateUsd = sum(
7445
+ evaluable.map(
7446
+ (c) => c.candidate ? costUsd(opts.candidateModel, c.candidate.tokensIn, c.candidate.tokensOut) : null
7447
+ )
7448
+ );
7449
+ const latencyFloorOk = latencyRatio === null || latencyRatio <= latencyFloorRatio;
7450
+ if (!latencyFloorOk) bumpFloor("latency");
7451
+ let verdict;
7452
+ if (evaluable.length < minJudgeable) {
7453
+ verdict = "inconclusive";
7454
+ notes.push(
7455
+ `only ${evaluable.length} evaluable case(s) < minJudgeableCases=${minJudgeable}`
7456
+ );
7457
+ } else if (winOrTieRatio !== null && winOrTieRatio >= threshold && floorViolations === 0 && latencyFloorOk) {
7458
+ verdict = "promote-ready";
7459
+ } else {
7460
+ verdict = "not-inferior";
7461
+ }
7462
+ const result = {
7463
+ verdict,
7464
+ appId: opts.appId,
7465
+ archetype: opts.archetype,
7466
+ incumbentModel,
7467
+ candidateModel: opts.candidateModel,
7468
+ judgeModel,
7469
+ nCases: evaluable.length,
7470
+ wins,
7471
+ ties,
7472
+ losses,
7473
+ floorViolations: floorViolations + (latencyFloorOk ? 0 : 1),
7474
+ floorDetail,
7475
+ winOrTieRatio,
7476
+ latencyRatio,
7477
+ costIncumbentUsd,
7478
+ costCandidateUsd,
7479
+ cases,
7480
+ notes
7481
+ };
7482
+ if (opts.dryRun) {
7483
+ notes.push("dry-run: no brain rows written");
7484
+ return result;
7485
+ }
7486
+ progress("Writing eval evidence to the brain\u2026");
7487
+ const runRes = await fetchFn(rest("kgauto_golden_eval_runs"), {
7488
+ method: "POST",
7489
+ headers: {
7490
+ ...restHeaders,
7491
+ "Content-Type": "application/json",
7492
+ Prefer: "return=representation"
7493
+ },
7494
+ body: JSON.stringify({
7495
+ app_id: opts.appId,
7496
+ intent_archetype: opts.archetype,
7497
+ incumbent_model: incumbentModel,
7498
+ candidate_model: opts.candidateModel,
7499
+ trigger_source: opts.triggerSource ?? "manual",
7500
+ judge_model: judgeModel,
7501
+ n_cases: result.nCases,
7502
+ wins,
7503
+ ties,
7504
+ losses,
7505
+ floor_violations: result.floorViolations,
7506
+ floor_detail: floorDetail,
7507
+ win_or_tie_ratio: winOrTieRatio,
7508
+ latency_ratio: latencyRatio,
7509
+ verdict,
7510
+ win_or_tie_threshold: threshold,
7511
+ notes: notes.join(" | ") || null
7512
+ })
7513
+ });
7514
+ if (!runRes.ok) {
7515
+ throw new Error(
7516
+ `golden-eval: run-row write failed (${runRes.status}): ${await runRes.text().catch(() => "<no body>")}`
7517
+ );
7518
+ }
7519
+ const runRows = await runRes.json();
7520
+ result.runId = runRows[0]?.id;
7521
+ const caseRows = cases.filter((c) => !c.excludedReason).map((c) => {
7522
+ const row = goldenRows.find((g) => g.id === c.goldenIrId);
7523
+ const turn = typeof row?.ir.currentTurn?.content === "string" ? row.ir.currentTurn.content : "";
7524
+ return {
7525
+ app_id: opts.appId,
7526
+ intent_archetype: opts.archetype,
7527
+ family: tryGetProfile(opts.candidateModel)?.family ?? "unknown",
7528
+ candidate_model: opts.candidateModel,
7529
+ current_model: incumbentModel,
7530
+ prompt_hash: hashForGolden(turn),
7531
+ current_response: c.incumbent?.text.slice(0, 500) ?? null,
7532
+ candidate_response: c.candidate?.text.slice(0, 500) ?? null,
7533
+ judge_verdict: c.floorViolations.length > 0 ? null : c.verdict,
7534
+ judge_rationale: c.floorViolations.length > 0 ? `hard-floor violation: ${c.floorViolations.join(",")}` : c.judgeRationale ?? null,
7535
+ judge_model: judgeModel,
7536
+ tokens_current_in: c.incumbent?.tokensIn ?? null,
7537
+ tokens_current_out: c.incumbent?.tokensOut ?? null,
7538
+ tokens_candidate_in: c.candidate?.tokensIn ?? null,
7539
+ tokens_candidate_out: c.candidate?.tokensOut ?? null,
7540
+ latency_current_ms: c.incumbent?.latencyMs ?? null,
7541
+ latency_candidate_ms: c.candidate?.latencyMs ?? null,
7542
+ prompt_fidelity: 1,
7543
+ replay_source: "golden-replay",
7544
+ outcome: c.floorViolations.includes("candidate_error") ? "candidate_error" : "completed",
7545
+ // migration-032 taxonomy: error_class only on candidate_error rows;
7546
+ // schema-floor detail rides in judge_rationale + the run's floor_detail.
7547
+ error_class: c.floorViolations.includes("candidate_error") ? c.errorClass ?? null : null,
7548
+ golden_run_id: result.runId ?? null,
7549
+ golden_ir_id: c.goldenIrId
7550
+ };
7551
+ });
7552
+ if (caseRows.length > 0) {
7553
+ const casesRes = await fetchFn(rest("probe_outcomes"), {
7554
+ method: "POST",
7555
+ headers: { ...restHeaders, "Content-Type": "application/json", Prefer: "return=minimal" },
7556
+ body: JSON.stringify(caseRows)
7557
+ });
7558
+ if (!casesRes.ok) {
7559
+ notes.push(
7560
+ `case-row write failed (${casesRes.status}): ${await casesRes.text().catch(() => "<no body>")}`
7561
+ );
7562
+ }
7563
+ }
7564
+ const latestRes = await fetchFn(
7565
+ rest(
7566
+ `compile_outcomes?app_id=eq.${encodeURIComponent(opts.appId)}&select=id&order=id.desc&limit=1`
7567
+ ),
7568
+ { headers: restHeaders }
7569
+ );
7570
+ const latest = latestRes.ok ? await latestRes.json() : [];
7571
+ const latestOutcomeId = latest[0]?.id;
7572
+ if (latestOutcomeId !== void 0) {
7573
+ const costLine = costIncumbentUsd !== null && costCandidateUsd !== null ? ` Eval cost basis: incumbent $${costIncumbentUsd.toFixed(4)} vs candidate $${costCandidateUsd.toFixed(4)} across the set.` : "";
7574
+ const message = `Golden-set eval (run #${result.runId}): ${opts.candidateModel} vs ${incumbentModel} on ${opts.appId}/${opts.archetype} \u2014 verdict ${verdict.toUpperCase()}. ${wins}W/${ties}T/${losses}L over ${result.nCases} real workload case(s), wins-or-ties ${(100 * (winOrTieRatio ?? 0)).toFixed(0)}% (threshold ${(100 * threshold).toFixed(0)}%), ${result.floorViolations} hard-floor violation(s), latency ratio ${latencyRatio?.toFixed(2) ?? "n/a"}.` + costLine;
7575
+ const suggestion = verdict === "promote-ready" ? `Candidate passed the non-inferiority rule on your real workload. To promote: node v2/scripts/promote-model.mjs --model ${opts.candidateModel} (or ask kgauto-Cairn). Evidence: kgauto_golden_eval_runs #${result.runId} + probe_outcomes golden_run_id=${result.runId}.` : `Candidate did NOT clear the non-inferiority rule \u2014 no action needed; the incumbent stays. Evidence rows: golden_run_id=${result.runId}.`;
7576
+ const advRes = await fetchFn(rest("compile_outcome_advisories"), {
7577
+ method: "POST",
7578
+ headers: { ...restHeaders, "Content-Type": "application/json", Prefer: "return=minimal" },
7579
+ body: JSON.stringify({
7580
+ outcome_id: latestOutcomeId,
7581
+ code: "golden-eval-verdict",
7582
+ level: "info",
7583
+ recommendation_type: "model-swap",
7584
+ message,
7585
+ suggestion
7586
+ })
7587
+ });
7588
+ if (advRes.ok) {
7589
+ result.advisoryOutcomeId = latestOutcomeId;
7590
+ await fetchFn(rest(`kgauto_golden_eval_runs?id=eq.${result.runId}`), {
7591
+ method: "PATCH",
7592
+ headers: { ...restHeaders, "Content-Type": "application/json", Prefer: "return=minimal" },
7593
+ body: JSON.stringify({ advisory_outcome_id: latestOutcomeId })
7594
+ }).catch(() => {
7595
+ });
7596
+ } else {
7597
+ notes.push(`advisory write failed (${advRes.status})`);
7598
+ }
7599
+ } else {
7600
+ notes.push("no compile_outcomes row for app \u2014 evidence advisory skipped (view needs a real outcome_id)");
7601
+ }
7602
+ return result;
7603
+ }
7604
+
6939
7605
  // src/brain-proxy.ts
6940
7606
  var SEGMENT_TO_TABLE = {
6941
7607
  outcomes: "compile_outcomes",
6942
7608
  compile_outcome_advisories: "compile_outcome_advisories",
6943
7609
  compile_outcome_quality: "compile_outcome_quality",
6944
- probe_outcomes: "probe_outcomes"
7610
+ probe_outcomes: "probe_outcomes",
7611
+ // alpha.62 (eval spine): golden-set capture. Only receives rows when the
7612
+ // consumer has explicitly opted in via KGAUTO_GOLDEN_CAPTURE — the segment
7613
+ // existing here does not by itself store anything.
7614
+ golden_irs: "kgauto_golden_irs"
6945
7615
  };
6946
7616
  var KNOWN_SEGMENTS = Object.keys(SEGMENT_TO_TABLE);
6947
7617
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -7099,7 +7769,7 @@ function createBrainForwardRoutes(config) {
7099
7769
  }
7100
7770
 
7101
7771
  // src/version.ts
7102
- var LIBRARY_VERSION = "2.0.0-alpha.61";
7772
+ var LIBRARY_VERSION = "2.0.0-alpha.63";
7103
7773
 
7104
7774
  // src/key-health.ts
7105
7775
  var JSON_HEADERS2 = { "Content-Type": "application/json" };
@@ -7722,6 +8392,7 @@ function compile2(ir, opts) {
7722
8392
  DIALECT_VERSION,
7723
8393
  FamilyResolutionError,
7724
8394
  INTENT_ARCHETYPES,
8395
+ JUDGE_RUBRICS,
7725
8396
  LATENCY_TIER_MS,
7726
8397
  LIBRARY_VERSION,
7727
8398
  MEASURED_GROUNDING_MIN_N,
@@ -7737,10 +8408,14 @@ function compile2(ir, opts) {
7737
8408
  bucketContext,
7738
8409
  bucketHistory,
7739
8410
  bucketToolCount,
8411
+ buildGoldenIrRow,
7740
8412
  buildLLMJudge,
8413
+ buildPairwiseJudgePrompt,
7741
8414
  buildShadowProbeRow,
7742
8415
  call,
8416
+ captureGoldenIr,
7743
8417
  clearBrain,
8418
+ combineOrderSwappedVerdicts,
7744
8419
  compile,
7745
8420
  compileForAISDKv6,
7746
8421
  configureBrain,
@@ -7786,19 +8461,27 @@ function compile2(ir, opts) {
7786
8461
  markAdvisoryResolved,
7787
8462
  markExclusionFindingHandled,
7788
8463
  markPromoteReadyHandled,
8464
+ parseGoldenCaptureRate,
8465
+ parseJudgeVerdict,
7789
8466
  peekBrainDeadLetter,
7790
8467
  probeShadow,
7791
8468
  profileToRow,
7792
8469
  profilesByProvider,
7793
8470
  readBrainReadEnv,
7794
8471
  record,
8472
+ recordGoldenIr,
7795
8473
  recordOutcome,
7796
8474
  recordShadowProbe,
8475
+ renderIrForJudge,
7797
8476
  resetTokenizer,
7798
8477
  resolveConventionsForProfile,
8478
+ resolveGoldenCaptureRate,
7799
8479
  resolvePricingAt,
7800
8480
  resolveProviderKey,
8481
+ rubricFor,
7801
8482
  runAdvisor,
8483
+ runGoldenEval,
7802
8484
  setTokenizer,
8485
+ shouldCaptureGolden,
7803
8486
  tryGetProfile
7804
8487
  });