@tangle-network/agent-eval 0.161.0 → 0.163.2
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 +51 -0
- package/dist/{active-curriculum-CD5TU2yW.js → active-curriculum-OjIWgrUJ.js} +2 -2
- package/dist/{active-curriculum-CD5TU2yW.js.map → active-curriculum-OjIWgrUJ.js.map} +1 -1
- package/dist/analyst/index.d.ts +2 -2
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +3 -3
- package/dist/{baseline-BhPRQBVn.js → baseline-BC-eBZ7U.js} +2 -2
- package/dist/{baseline-BhPRQBVn.js.map → baseline-BC-eBZ7U.js.map} +1 -1
- package/dist/{benchmark-command-BVtaq_ve.js → benchmark-command-CF-4GEWZ.js} +9 -8
- package/dist/benchmark-command-CF-4GEWZ.js.map +1 -0
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +3 -3
- package/dist/builder-eval/index.d.ts.map +1 -1
- package/dist/builder-eval/index.js +22 -8
- package/dist/builder-eval/index.js.map +1 -1
- package/dist/campaign/index.js +8 -8
- package/dist/{campaign-BSmOwskD.js → campaign-DQZmc2Dq.js} +12 -12
- package/dist/{campaign-BSmOwskD.js.map → campaign-DQZmc2Dq.js.map} +1 -1
- package/dist/{chat-json-call-6g5sJobJ.js → chat-json-call-5Jxna-aV.js} +2 -2
- package/dist/{chat-json-call-6g5sJobJ.js.map → chat-json-call-5Jxna-aV.js.map} +1 -1
- package/dist/cli.js +3 -3
- package/dist/contract/index.js +7 -7
- package/dist/{counterfactual-D_VWavVm.js → counterfactual-Bjq1mlUu.js} +2 -2
- package/dist/{counterfactual-D_VWavVm.js.map → counterfactual-Bjq1mlUu.js.map} +1 -1
- package/dist/{define-agent-eval-h-s-sI-v.js → define-agent-eval-D08pWIJb.js} +13 -13
- package/dist/{define-agent-eval-h-s-sI-v.js.map → define-agent-eval-D08pWIJb.js.map} +1 -1
- package/dist/{descriptive-jDOuI6mz.js → descriptive-1V17A-qa.js} +2 -2
- package/dist/{descriptive-jDOuI6mz.js.map → descriptive-1V17A-qa.js.map} +1 -1
- package/dist/{dspy-rlm-engine-DptEII26.js → dspy-rlm-engine-DhA9qKIm.js} +2 -2
- package/dist/{dspy-rlm-engine-DptEII26.js.map → dspy-rlm-engine-DhA9qKIm.js.map} +1 -1
- package/dist/emitter-D_jYSGRd.d.ts.map +1 -1
- package/dist/{emitter-BpYFQPj4.js → emitter-DeQHiDMm.js} +13 -6
- package/dist/emitter-DeQHiDMm.js.map +1 -0
- package/dist/{eval-campaign-BsXWL2-2.js → eval-campaign-BfohKmzx.js} +3 -3
- package/dist/{eval-campaign-BsXWL2-2.js.map → eval-campaign-BfohKmzx.js.map} +1 -1
- package/dist/experiment/index.js +8 -8
- package/dist/{experiment-tracker-Ym6rEQT1.js → experiment-tracker-BKEumQug.js} +2 -2
- package/dist/{experiment-tracker-Ym6rEQT1.js.map → experiment-tracker-BKEumQug.js.map} +1 -1
- package/dist/{external-optimizer-process-WosTBChy.js → external-optimizer-process-BFmh36vW.js} +2 -2
- package/dist/{external-optimizer-process-WosTBChy.js.map → external-optimizer-process-BFmh36vW.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BIWbHpgD.js → external-optimizer-subprocess-CqLMW3nh.js} +2 -2
- package/dist/{external-optimizer-subprocess-BIWbHpgD.js.map → external-optimizer-subprocess-CqLMW3nh.js.map} +1 -1
- package/dist/fuzz.d.ts +1 -2
- package/dist/fuzz.d.ts.map +1 -1
- package/dist/fuzz.js +4 -10
- package/dist/fuzz.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +26 -26
- package/dist/index.js.map +1 -1
- package/dist/{internal-BDHPCnjk.js → internal-BMFSR8Ns.js} +3 -19
- package/dist/internal-BMFSR8Ns.js.map +1 -0
- package/dist/{judge-calibration-zZjLz8hr.js → judge-calibration-BnpVKtnb.js} +3 -13
- package/dist/judge-calibration-BnpVKtnb.js.map +1 -0
- package/dist/judge-calibration-C5CbMYce.d.ts.map +1 -1
- package/dist/{llm-client-hgDieDNN.js → llm-client-BFMRpmqb.js} +8 -11
- package/dist/llm-client-BFMRpmqb.js.map +1 -0
- package/dist/{llm-judge-BhasIPFT.js → llm-judge-Du7WQPh7.js} +7 -7
- package/dist/{llm-judge-BhasIPFT.js.map → llm-judge-Du7WQPh7.js.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -1
- package/dist/meta-eval/index.d.ts.map +1 -1
- package/dist/meta-eval/index.js +14 -22
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{paired-arms-D-XRF_fy.js → paired-arms-D4aeIHUy.js} +3 -3
- package/dist/{paired-arms-D-XRF_fy.js.map → paired-arms-D4aeIHUy.js.map} +1 -1
- package/dist/{paired-tests-BHIhYVdu.js → paired-tests-C8iCsioC.js} +3 -3
- package/dist/{paired-tests-BHIhYVdu.js.map → paired-tests-C8iCsioC.js.map} +1 -1
- package/dist/pipelines/index.d.ts +3 -2
- package/dist/pipelines/index.d.ts.map +1 -1
- package/dist/pipelines/index.js +4 -19
- package/dist/pipelines/index.js.map +1 -1
- package/dist/{power-and-mde-CHIrXJll.js → power-and-mde-B8F2RdcD.js} +3 -3
- package/dist/{power-and-mde-CHIrXJll.js.map → power-and-mde-B8F2RdcD.js.map} +1 -1
- package/dist/{power-preflight-DEw-uC7q.js → power-preflight-CFXm0Vjo.js} +3 -3
- package/dist/{power-preflight-DEw-uC7q.js.map → power-preflight-CFXm0Vjo.js.map} +1 -1
- package/dist/{produced-state-DZ89riy5.js → produced-state-Be0BK3RN.js} +3 -3
- package/dist/{produced-state-DZ89riy5.js.map → produced-state-Be0BK3RN.js.map} +1 -1
- package/dist/{promotion-policy-xzA40Evo.js → promotion-policy-LY9mVQ7W.js} +3 -3
- package/dist/{promotion-policy-xzA40Evo.js.map → promotion-policy-LY9mVQ7W.js.map} +1 -1
- package/dist/{query-DxPYqpmT.d.ts → query-CwnHlu5p.d.ts} +19 -2
- package/dist/query-CwnHlu5p.d.ts.map +1 -0
- package/dist/{query-CHmMP42p.js → query-_5g6re3_.js} +44 -2
- package/dist/query-_5g6re3_.js.map +1 -0
- package/dist/random-Dn5fPWkt.js +21 -0
- package/dist/random-Dn5fPWkt.js.map +1 -0
- package/dist/record-id-DUgsK5qp.js +17 -0
- package/dist/record-id-DUgsK5qp.js.map +1 -0
- package/dist/{release-confidence-DKfD2RYU.js → release-confidence-nGDJiiwc.js} +2 -2
- package/dist/{release-confidence-DKfD2RYU.js.map → release-confidence-nGDJiiwc.js.map} +1 -1
- package/dist/reporting.js +6 -6
- package/dist/{reward-hacking-t4lB1yt8.js → reward-hacking-O5zKDANP.js} +2 -2
- package/dist/{reward-hacking-t4lB1yt8.js.map → reward-hacking-O5zKDANP.js.map} +1 -1
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +9 -15
- package/dist/rl.js.map +1 -1
- package/dist/{rubric-predictive-validity-CK8SCOg-.js → rubric-predictive-validity-2D5Gw9z9.js} +3 -3
- package/dist/{rubric-predictive-validity-CK8SCOg-.js.map → rubric-predictive-validity-2D5Gw9z9.js.map} +1 -1
- package/dist/{semantic-concept-judge-BSkKKHeq.js → semantic-concept-judge-BsDMOwJr.js} +2 -2
- package/dist/{semantic-concept-judge-BSkKKHeq.js.map → semantic-concept-judge-BsDMOwJr.js.map} +1 -1
- package/dist/{sequential-rYW-Ophm.js → sequential-BLMbdrD7.js} +3 -3
- package/dist/{sequential-rYW-Ophm.js.map → sequential-BLMbdrD7.js.map} +1 -1
- package/dist/{server-BtFd4uzB.js → server-BjYiJHoJ.js} +2 -2
- package/dist/{server-BtFd4uzB.js.map → server-BjYiJHoJ.js.map} +1 -1
- package/dist/{skillopt-optimization-method-DbaekMcn.js → skillopt-optimization-method-UArRo-nr.js} +6 -6
- package/dist/{skillopt-optimization-method-DbaekMcn.js.map → skillopt-optimization-method-UArRo-nr.js.map} +1 -1
- package/dist/{store-tool-spans-Dlh9vkFK.js → store-tool-spans-BVga3c37.js} +21 -17
- package/dist/store-tool-spans-BVga3c37.js.map +1 -0
- package/dist/store-tool-spans-DPUG7UUY.d.ts.map +1 -1
- package/dist/{student-t-CvBq2mve.js → student-t-BA-Uy51p.js} +2 -2
- package/dist/{student-t-CvBq2mve.js.map → student-t-BA-Uy51p.js.map} +1 -1
- package/dist/{summary-report-BI5hUtvK.js → summary-report-BXeQ5Ues.js} +6 -6
- package/dist/{summary-report-BI5hUtvK.js.map → summary-report-BXeQ5Ues.js.map} +1 -1
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{tool-waste-BqzmVdJk.js → tool-waste-8BQiUc8K.js} +4 -4
- package/dist/{tool-waste-BqzmVdJk.js.map → tool-waste-8BQiUc8K.js.map} +1 -1
- package/dist/{tool-waste-Dro0gJi3.d.ts → tool-waste-CKc7bYIg.d.ts} +2 -2
- package/dist/{tool-waste-Dro0gJi3.d.ts.map → tool-waste-CKc7bYIg.d.ts.map} +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +2 -2
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +8 -17
- package/dist/traces.js.map +1 -1
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +3 -13
- package/dist/trajectory-replay/index.js.map +1 -1
- package/dist/{types-BPb2Kf_C2.d.ts → types-BPb2Kf_C.d.ts} +1 -1
- package/dist/types-BPb2Kf_C.d.ts.map +1 -0
- package/dist/types-Bfk0uxRj.d.ts.map +1 -1
- package/dist/wire/index.js +1 -1
- package/package.json +2 -2
- package/dist/benchmark-command-BVtaq_ve.js.map +0 -1
- package/dist/emitter-BpYFQPj4.js.map +0 -1
- package/dist/internal-BDHPCnjk.js.map +0 -1
- package/dist/judge-calibration-zZjLz8hr.js.map +0 -1
- package/dist/llm-client-hgDieDNN.js.map +0 -1
- package/dist/query-CHmMP42p.js.map +0 -1
- package/dist/query-DxPYqpmT.d.ts.map +0 -1
- package/dist/store-tool-spans-Dlh9vkFK.js.map +0 -1
- package/dist/types-BPb2Kf_C2.d.ts.map +0 -1
|
@@ -7,7 +7,8 @@ import { a as rubricPredictiveValidity, i as RubricRanking, n as RubricPredictiv
|
|
|
7
7
|
//#region src/meta-eval/correlation-study.d.ts
|
|
8
8
|
interface EvalMetricSpec {
|
|
9
9
|
id: string;
|
|
10
|
-
/** Extract a scalar from a run
|
|
10
|
+
/** Extract a scalar from a run. Omit it and `id` must name one of
|
|
11
|
+
* `RUN_METRICS`; any other `id` is refused. */
|
|
11
12
|
extract?: (run: Run, store: TraceStore) => Promise<number | null>;
|
|
12
13
|
}
|
|
13
14
|
interface OutcomePair {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/meta-eval/correlation-study.ts","../../src/meta-eval/calibration.ts","../../src/meta-eval/sentinel.ts"],"mappings":";;;;;;;UAkBiB;EACf
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/meta-eval/correlation-study.ts","../../src/meta-eval/calibration.ts","../../src/meta-eval/sentinel.ts"],"mappings":";;;;;;;UAkBiB;EACf;;;EAGA,WAAW,KAAK,KAAK,OAAO,eAAe;;UAG5B;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;EAEA;IAAe;IAAe;;;EAE9B;;UAGe;EACf,OAAO;EACP;EACA;;UAGe;;EAEf;;EAEA,gBAAgB;;EAEhB;;EAEA;;;EAGA;;iBAGoB,iBACpB,YAAY,YACZ,cAAc,cACd,aAAa,kBACb,8BACA,UAAS,0BACR,QAAQ;;;UCtDM;EACf;EACA;EACA;EACA;EACA;;EAEA;;UAGe;EACf;EACA;EACA;EACA,MAAM;;EAEN;;EAEA;;UAGe;EACf;;EAEA;;EAEA;IAAU;IAAY;;;UAGP;EACf;EACA;;iBAGoB,iBACpB,YAAY,YACZ,cAAc,cACd,YAAY,gBACZ,uBACA,UAAS,qBACR,QAAQ;;;cCDL;KAEM,6BAA6B;UAExB;;EAEf;;EAEA;;EAEA;;UAGe;;EAEf;EACA;;EAEA;;;;;;;EAOA,SAAS;;;UAIM;EACf;EACA;EACA;;;iBAcc,yBAAyB,UAAU,kBAAkB;;;;;;iBAiCrD,wBACd,QAAQ,oBAAoB,6BAC5B,MAAM,eACL;;;;;;;;iBAmBa,sBACd,QAAQ,wBAAwB,qBAChC,MAAM,eACL;UAYc;;EAEf;;;;;;;;;iBAUc,wBACd,QAAQ,kBACR,QAAQ,cACR,MAAM,cACN,UAAS,qBACR;UA4Cc;EACf,OAAO,UAAU,mBAAmB;;EAEpC,QAAQ,mBAAmB,QAAQ;;iBAGrB,sBAAsB,UAAS,qBAA0B;;;;;;;iBAqBzD,kBAAkB,eAAe;UA0ChC;;EAEf;;EAEA;;EAEA;;EAEA;;UAGe;;EAEf;EACA,aAAa;;EAEb,cAAc;;UAGC;EACf;EACA,QAAQ;;EAER,OAAO;;EAEP;;EAEA;;EAEA;EACA;EACA;;UAGe;EACf,UAAU;EACV;EACA;;;;;;;EAOA;;iBAKc,oBACd,SAAS,oBACT,MAAM,uBACL;UA6Gc;EACf;EACA;;;;;;;;;;iBAWc,gBAAgB,QAAQ,iBAAiB"}
|
package/dist/meta-eval/index.js
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { s as ValidationError } from "../errors-Dngq5h35.js";
|
|
2
|
-
import { i as makeRng } from "../internal-
|
|
3
|
-
import { a as spearmanR, r as pearsonR } from "../descriptive-
|
|
4
|
-
import {
|
|
2
|
+
import { i as makeRng } from "../internal-BMFSR8Ns.js";
|
|
3
|
+
import { a as spearmanR, r as pearsonR } from "../descriptive-1V17A-qa.js";
|
|
4
|
+
import { u as runMetricExtractor } from "../query-_5g6re3_.js";
|
|
5
5
|
import { t as analyzeSeries } from "../series-convergence-CjO2QdRW.js";
|
|
6
|
-
import { t as rubricPredictiveValidity } from "../rubric-predictive-validity-
|
|
6
|
+
import { t as rubricPredictiveValidity } from "../rubric-predictive-validity-2D5Gw9z9.js";
|
|
7
7
|
import { n as InMemoryOutcomeStore, t as FileSystemOutcomeStore } from "../outcome-store-ChBKlTd_.js";
|
|
8
8
|
//#region src/meta-eval/calibration.ts
|
|
9
|
+
/**
|
|
10
|
+
* Calibration curve — binned "if eval says X, what does reality show?"
|
|
11
|
+
*
|
|
12
|
+
* Companion to correlationStudy. Raw correlation is a single number;
|
|
13
|
+
* the calibration curve shows *where* the eval is well-calibrated vs
|
|
14
|
+
* overconfident / underconfident. Buckets the eval metric, computes
|
|
15
|
+
* mean outcome per bucket, reports expected-calibration-error (ECE).
|
|
16
|
+
*/
|
|
9
17
|
async function calibrationCurve(traceStore, outcomeStore, evalMetric, outcomeMetric, options = {}) {
|
|
10
18
|
const runs = await traceStore.listRuns();
|
|
11
19
|
const outcomes = await outcomeStore.list();
|
|
@@ -15,7 +23,7 @@ async function calibrationCurve(traceStore, outcomeStore, evalMetric, outcomeMet
|
|
|
15
23
|
arr.push(o);
|
|
16
24
|
byRun.set(o.runId, arr);
|
|
17
25
|
}
|
|
18
|
-
const extract = evalMetric.extract ??
|
|
26
|
+
const extract = evalMetric.extract ?? runMetricExtractor(evalMetric.id);
|
|
19
27
|
const pairs = [];
|
|
20
28
|
for (const run of runs) {
|
|
21
29
|
const os = byRun.get(run.runId);
|
|
@@ -92,9 +100,6 @@ function toBin(chunk, lower, upper) {
|
|
|
92
100
|
function mean(xs) {
|
|
93
101
|
return xs.reduce((a, b) => a + b, 0) / xs.length;
|
|
94
102
|
}
|
|
95
|
-
function defaultExtract$1(metric) {
|
|
96
|
-
return async (run) => run.outcome?.score ?? (metric === "pass" ? run.outcome?.pass === true ? 1 : 0 : null);
|
|
97
|
-
}
|
|
98
103
|
//#endregion
|
|
99
104
|
//#region src/meta-eval/correlation-study.ts
|
|
100
105
|
/**
|
|
@@ -139,7 +144,7 @@ async function correlationStudy(traceStore, outcomeStore, evalMetrics, outcomeMe
|
|
|
139
144
|
continue;
|
|
140
145
|
}
|
|
141
146
|
for (const em of evalMetrics) {
|
|
142
|
-
const x = await (em.extract ??
|
|
147
|
+
const x = await (em.extract ?? runMetricExtractor(em.id))(run, traceStore);
|
|
143
148
|
if (x === null || !Number.isFinite(x)) continue;
|
|
144
149
|
for (const om of outcomeMetricNames) {
|
|
145
150
|
const values = eligible.map((o) => o.metrics[om]).filter((v) => typeof v === "number" && Number.isFinite(v));
|
|
@@ -220,19 +225,6 @@ function bootstrapPearsonCi(xs, ys, iterations, seed) {
|
|
|
220
225
|
upper: rs[Math.min(rs.length - 1, Math.floor(.975 * rs.length))]
|
|
221
226
|
};
|
|
222
227
|
}
|
|
223
|
-
function defaultExtract(metric) {
|
|
224
|
-
return async (run, store) => {
|
|
225
|
-
switch (metric) {
|
|
226
|
-
case "score":
|
|
227
|
-
case "overallScore": return run.outcome?.score ?? null;
|
|
228
|
-
case "pass": return run.outcome?.pass === true ? 1 : 0;
|
|
229
|
-
case "durationMs": return run.endedAt && run.startedAt ? run.endedAt - run.startedAt : null;
|
|
230
|
-
case "costUsd": return aggregateLlm(await llmSpans(store, run.runId)).costUsd;
|
|
231
|
-
case "inputTokens": return aggregateLlm(await llmSpans(store, run.runId)).inputTokens;
|
|
232
|
-
default: return null;
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
228
|
//#endregion
|
|
237
229
|
//#region src/meta-eval/sentinel.ts
|
|
238
230
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["defaultExtract"],"sources":["../../src/meta-eval/calibration.ts","../../src/meta-eval/correlation-study.ts","../../src/meta-eval/sentinel.ts"],"sourcesContent":["/**\n * Calibration curve — binned \"if eval says X, what does reality show?\"\n *\n * Companion to correlationStudy. Raw correlation is a single number;\n * the calibration curve shows *where* the eval is well-calibrated vs\n * overconfident / underconfident. Buckets the eval metric, computes\n * mean outcome per bucket, reports expected-calibration-error (ECE).\n */\n\nimport type { Run } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport type { EvalMetricSpec } from './correlation-study'\nimport type { DeploymentOutcome, OutcomeStore } from './outcome-store'\n\nexport interface CalibrationBin {\n lower: number\n upper: number\n n: number\n evalMean: number\n outcomeMean: number\n /** |outcomeMean − evalMean|; contributes to ECE weighted by n/total. */\n gap: number\n}\n\nexport interface CalibrationReport {\n evalMetric: string\n outcomeMetric: string\n n: number\n bins: CalibrationBin[]\n /** Expected Calibration Error — Σ (n_i/N) × |outcomeMean_i − evalMean_i|. */\n ece: number\n /** Max bin gap — upper bound on miscalibration. */\n maxGap: number\n}\n\nexport interface CalibrationOptions {\n bins?: number\n /** Equal-width (fixed bin edges) or equal-frequency (quantile bins). */\n binning?: 'equal-width' | 'equal-frequency'\n /** Clip eval values to [lo, hi] before binning. */\n range?: { lo: number; hi: number }\n}\n\nexport interface CalibrationPair {\n evalScore: number\n outcome: number\n}\n\nexport async function calibrationCurve(\n traceStore: TraceStore,\n outcomeStore: OutcomeStore,\n evalMetric: EvalMetricSpec,\n outcomeMetric: string,\n options: CalibrationOptions = {},\n): Promise<CalibrationReport | null> {\n const runs = await traceStore.listRuns()\n const outcomes = await outcomeStore.list()\n const byRun = new Map<string, DeploymentOutcome[]>()\n for (const o of outcomes) {\n const arr = byRun.get(o.runId) ?? []\n arr.push(o)\n byRun.set(o.runId, arr)\n }\n\n const extract = evalMetric.extract ?? defaultExtract(evalMetric.id)\n const pairs: Array<{ x: number; y: number }> = []\n for (const run of runs) {\n const os = byRun.get(run.runId)\n if (!os?.length) continue\n const x = await extract(run, traceStore)\n if (x === null || !Number.isFinite(x)) continue\n const latest = [...os].sort((a, b) => b.capturedAt - a.capturedAt)[0]!\n const y = latest.metrics[outcomeMetric]\n if (typeof y !== 'number' || !Number.isFinite(y)) continue\n pairs.push({ x, y })\n }\n if (pairs.length < 2) return null\n\n return calibrationFromPairs(\n pairs.map((p) => ({ evalScore: p.x, outcome: p.y })),\n evalMetric.id,\n outcomeMetric,\n options,\n )\n}\n\nfunction calibrationFromPairs(\n inputPairs: CalibrationPair[],\n evalMetric: string,\n outcomeMetric: string,\n options: CalibrationOptions = {},\n): CalibrationReport | null {\n const pairs = inputPairs.filter(\n (pair) => Number.isFinite(pair.evalScore) && Number.isFinite(pair.outcome),\n )\n if (pairs.length < 2) return null\n\n const numBins = options.bins ?? 10\n const binning = options.binning ?? 'equal-width'\n const xs = pairs.map((p) => p.evalScore)\n const lo = options.range?.lo ?? Math.min(...xs)\n const hi = options.range?.hi ?? Math.max(...xs)\n\n const bins: CalibrationBin[] = []\n if (binning === 'equal-frequency') {\n const sorted = [...pairs].sort((a, b) => a.evalScore - b.evalScore)\n const perBin = Math.max(1, Math.floor(sorted.length / numBins))\n for (let i = 0; i < sorted.length; i += perBin) {\n const chunk = sorted.slice(i, i + perBin)\n if (chunk.length === 0) continue\n bins.push(toBin(chunk))\n }\n } else {\n const width = (hi - lo) / numBins\n if (width === 0) return null\n for (let i = 0; i < numBins; i++) {\n const binLo = lo + i * width\n const binHi = i === numBins - 1 ? hi + 1e-9 : lo + (i + 1) * width\n const chunk = pairs.filter((p) => p.evalScore >= binLo && p.evalScore < binHi)\n if (chunk.length === 0) continue\n bins.push(toBin(chunk, binLo, binHi))\n }\n }\n\n const total = bins.reduce((a, b) => a + b.n, 0)\n const ece = bins.reduce((a, b) => a + (b.n / total) * b.gap, 0)\n const maxGap = bins.reduce((a, b) => Math.max(a, b.gap), 0)\n\n return { evalMetric, outcomeMetric, n: pairs.length, bins, ece, maxGap }\n}\n\nfunction toBin(chunk: CalibrationPair[], lower?: number, upper?: number): CalibrationBin {\n const xs = chunk.map((c) => c.evalScore)\n const ys = chunk.map((c) => c.outcome)\n const evalMean = mean(xs)\n const outcomeMean = mean(ys)\n return {\n lower: lower ?? Math.min(...xs),\n upper: upper ?? Math.max(...xs),\n n: chunk.length,\n evalMean,\n outcomeMean,\n gap: Math.abs(outcomeMean - evalMean),\n }\n}\n\nfunction mean(xs: number[]): number {\n return xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\nfunction defaultExtract(metric: string): (run: Run, store: TraceStore) => Promise<number | null> {\n return async (run) =>\n run.outcome?.score ?? (metric === 'pass' ? (run.outcome?.pass === true ? 1 : 0) : null)\n}\n","/**\n * Correlation study — \"does our eval score predict real-world outcomes?\"\n *\n * This is the load-bearing signal. Takes a TraceStore + OutcomeStore,\n * joins on runId, computes Pearson + Spearman + bootstrap CI for every\n * (evalMetric, outcomeMetric) pair the caller declares.\n *\n * Without this number the framework is ornamental. With it and r > 0.6\n * the framework is a moat — no other agent-eval tool publishes one.\n */\n\nimport { pearsonR, spearmanR } from '../statistics'\nimport { makeRng } from '../statistics/internal'\nimport { aggregateLlm, llmSpans } from '../trace/query'\nimport type { Run } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport type { DeploymentOutcome, OutcomeFilter, OutcomeStore } from './outcome-store'\n\nexport interface EvalMetricSpec {\n id: string\n /** Extract a scalar from a run (defaults cover score/pass/durationMs/costUsd/tokens). */\n extract?: (run: Run, store: TraceStore) => Promise<number | null>\n}\n\nexport interface OutcomePair {\n evalMetric: string\n outcomeMetric: string\n}\n\nexport interface CorrelationResult {\n evalMetric: string\n outcomeMetric: string\n n: number\n pearson: number\n spearman: number\n /** 95% bootstrap CI for Pearson. */\n pearsonCi95: { lower: number; upper: number }\n /** Rough verdict: 'strong' ≥ 0.7, 'moderate' ≥ 0.4, else 'weak'. */\n verdict: 'strong' | 'moderate' | 'weak'\n}\n\nexport interface CorrelationStudyResult {\n pairs: CorrelationResult[]\n joinedSamples: number\n skippedRuns: number\n}\n\nexport interface CorrelationStudyOptions {\n /** Only join outcomes captured within this window after run.startedAt. */\n maxCaptureLagMs?: number\n /** Restrict to a subset of outcomes (cohort, region, source). */\n outcomeFilter?: OutcomeFilter\n /** Which outcome per run to use when multiple exist. Default 'latest'. */\n reduction?: 'latest' | 'mean' | 'max'\n /** Bootstrap iterations for the CI. Default 500. */\n bootstrapIterations?: number\n /** Seed for the bootstrap resampler. Absent, the seed is derived from the\n * paired observations, so the same study reproduces the same interval. */\n seed?: number\n}\n\nexport async function correlationStudy(\n traceStore: TraceStore,\n outcomeStore: OutcomeStore,\n evalMetrics: EvalMetricSpec[],\n outcomeMetricNames: string[],\n options: CorrelationStudyOptions = {},\n): Promise<CorrelationStudyResult> {\n const runs = await traceStore.listRuns()\n const outcomes = await outcomeStore.list(options.outcomeFilter)\n const outcomesByRun = new Map<string, DeploymentOutcome[]>()\n for (const o of outcomes) {\n const arr = outcomesByRun.get(o.runId) ?? []\n arr.push(o)\n outcomesByRun.set(o.runId, arr)\n }\n\n const reduction = options.reduction ?? 'latest'\n const maxLag = options.maxCaptureLagMs ?? Infinity\n\n const pairs: Array<{ evalMetric: string; outcomeMetric: string; xs: number[]; ys: number[] }> = []\n for (const em of evalMetrics) {\n for (const om of outcomeMetricNames) {\n pairs.push({ evalMetric: em.id, outcomeMetric: om, xs: [], ys: [] })\n }\n }\n\n let joined = 0\n let skipped = 0\n for (const run of runs) {\n const os = outcomesByRun.get(run.runId)\n if (!os || os.length === 0) {\n skipped++\n continue\n }\n const eligible = os.filter((o) => o.capturedAt - run.startedAt <= maxLag)\n if (eligible.length === 0) {\n skipped++\n continue\n }\n\n for (const em of evalMetrics) {\n const extract = em.extract ?? defaultExtract(em.id)\n const x = await extract(run, traceStore)\n if (x === null || !Number.isFinite(x)) continue\n\n for (const om of outcomeMetricNames) {\n const values = eligible\n .map((o) => o.metrics[om])\n .filter((v): v is number => typeof v === 'number' && Number.isFinite(v))\n if (values.length === 0) continue\n const y = reduce(values, reduction, eligible)\n if (y === null) continue\n const pair = pairs.find((p) => p.evalMetric === em.id && p.outcomeMetric === om)!\n pair.xs.push(x)\n pair.ys.push(y)\n }\n }\n joined++\n }\n\n const results: CorrelationResult[] = pairs\n .filter((p) => p.xs.length >= 3)\n .map((p) => {\n const pearson = pearsonR(p.xs, p.ys)\n const spearman = spearmanR(p.xs, p.ys)\n const pearsonCi95 = bootstrapPearsonCi(\n p.xs,\n p.ys,\n options.bootstrapIterations ?? 500,\n options.seed,\n )\n const verdict: CorrelationResult['verdict'] =\n Math.abs(pearson) >= 0.7 ? 'strong' : Math.abs(pearson) >= 0.4 ? 'moderate' : 'weak'\n return {\n evalMetric: p.evalMetric,\n outcomeMetric: p.outcomeMetric,\n n: p.xs.length,\n pearson,\n spearman,\n pearsonCi95,\n verdict,\n }\n })\n\n return { pairs: results, joinedSamples: joined, skippedRuns: skipped }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction reduce(\n values: number[],\n kind: 'latest' | 'mean' | 'max',\n outcomes: DeploymentOutcome[],\n): number | null {\n if (values.length === 0) return null\n if (kind === 'mean') return values.reduce((a, b) => a + b, 0) / values.length\n if (kind === 'max') return Math.max(...values)\n // 'latest': pick the outcome captured last, then lookup its metric\n const latest = [...outcomes].sort((a, b) => b.capturedAt - a.capturedAt)[0]\n if (!latest) return null\n const latestKey = Object.keys(latest.metrics)[0]\n const v = latestKey !== undefined ? latest.metrics[latestKey] : undefined\n // For 'latest' we already have `values` aligned; use the last-captured one\n const paired = outcomes\n .map((o) => {\n const k = Object.keys(o.metrics)[0]\n return {\n at: o.capturedAt,\n v: k !== undefined ? values.find((x) => o.metrics[k] === x) : undefined,\n }\n })\n .filter((p) => p.v !== undefined)\n if (paired.length === 0) return v ?? null\n return paired.sort((a, b) => b.at - a.at)[0]?.v ?? null\n}\n\nfunction bootstrapPearsonCi(\n xs: number[],\n ys: number[],\n iterations: number,\n seed: number | undefined,\n): { lower: number; upper: number } {\n const n = xs.length\n if (n < 3) return { lower: NaN, upper: NaN }\n const rng = makeRng(seed, xs, ys)\n const rs: number[] = []\n for (let b = 0; b < iterations; b++) {\n const rx: number[] = new Array(n)\n const ry: number[] = new Array(n)\n for (let i = 0; i < n; i++) {\n const idx = Math.floor(rng() * n)\n rx[i] = xs[idx]!\n ry[i] = ys[idx]!\n }\n const r = pearsonR(rx, ry)\n if (Number.isFinite(r)) rs.push(r)\n }\n rs.sort((a, b) => a - b)\n if (rs.length === 0) return { lower: NaN, upper: NaN }\n return {\n lower: rs[Math.floor(0.025 * rs.length)]!,\n upper: rs[Math.min(rs.length - 1, Math.floor(0.975 * rs.length))]!,\n }\n}\n\nfunction defaultExtract(metric: string): (run: Run, store: TraceStore) => Promise<number | null> {\n return async (run, store) => {\n switch (metric) {\n case 'score':\n case 'overallScore':\n return run.outcome?.score ?? null\n case 'pass':\n return run.outcome?.pass === true ? 1 : 0\n case 'durationMs':\n return run.endedAt && run.startedAt ? run.endedAt - run.startedAt : null\n case 'costUsd': {\n const llm = await llmSpans(store, run.runId)\n return aggregateLlm(llm).costUsd\n }\n case 'inputTokens': {\n const llm = await llmSpans(store, run.runId)\n return aggregateLlm(llm).inputTokens\n }\n default:\n return null\n }\n }\n}\n","/**\n * Judge sentinel — eval trustworthiness as a continuously measured,\n * alarmed trend.\n *\n * Judges are models; models change underneath us; calibration decays.\n * This module composes three existing instruments into one loop:\n *\n * snapshot — adapters turn real instrument outputs (`calibrateJudge` /\n * `calibrateJudgeContinuous`, `corpusInterRaterAgreement` /\n * `continuousAgreement`, a rerun sentinel golden set) into\n * `SentinelSnapshot`s\n * series — `analyzeSeries` (src/series-convergence) classifies each\n * judge×metric history as stabilized / drifting / noisy\n * alarm — `judgeSentinelReport` turns trends + thresholds into named\n * alarms; `evalHealthStamp` is the tiny object a campaign\n * attaches to its verdicts\n *\n * Alarm conditions:\n * - convergence state `drifting-down` on any tracked metric\n * - irr below `minIrr`\n * - calibrationKappa / sentinelPassRate dropped vs the series baseline\n * beyond `maxKappaDrop` / `maxSentinelDrop`\n * - judge model changed with no post-change golden-grounded snapshot\n * (the silent-upgrade trap: judges agreeing with each other after a\n * model swap proves nothing — only re-measuring against gold does)\n * - newest snapshot older than `staleAfterDays` relative to `asOf`\n *\n * Wire-in: run the snapshot adapters from a post-campaign hook or a\n * nightly job, append to a `SentinelStore`, then compute\n * `judgeSentinelReport(await store.history(), { asOf })` with `asOf` =\n * the campaign timestamp. Attach `evalHealthStamp(report)` to campaign\n * verdicts: an alarmed sentinel means every downstream verdict carries\n * an integrity warning until the judge is recalibrated.\n *\n * The module is clock-free — every timestamp (`at`, `asOf`) is\n * caller-supplied ISO-8601, so reports are reproducible.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n CalibrationResult,\n CandidateScore,\n ContinuousAgreement,\n ContinuousCalibrationResult,\n GoldenItem,\n} from '../judge-calibration'\nimport {\n analyzeSeries,\n type SeriesConvergenceOptions,\n type SeriesConvergenceResult,\n} from '../series-convergence'\nimport type { CorpusAgreementReport } from '../statistics'\n\nconst SENTINEL_METRIC_NAMES = ['irr', 'calibrationKappa', 'sentinelPassRate'] as const\n\nexport type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number]\n\nexport interface SentinelMetrics {\n /** Inter-rater reliability — ICC(2,1) from agreement instruments. */\n irr?: number\n /** Weighted κ vs the human golden set (`calibrateJudge*`). */\n calibrationKappa?: number\n /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */\n sentinelPassRate?: number\n}\n\nexport interface SentinelSnapshot {\n /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */\n at: string\n judgeId: string\n /** Exact model identity behind the judge (pin the full version string). */\n judgeModel: string\n /**\n * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a\n * model-change marker — it records the new `judgeModel` immediately and\n * the silent-upgrade alarm stays raised until a golden-grounded snapshot\n * (calibrationKappa or sentinelPassRate) follows.\n */\n metrics: SentinelMetrics\n}\n\n/** Identity + timestamp the caller supplies alongside an instrument output. */\nexport interface SnapshotMeta {\n at: string\n judgeId: string\n judgeModel: string\n}\n\nfunction parseIso(value: string, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-sentinel: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\n/** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */\nexport function validateSentinelSnapshot(snapshot: SentinelSnapshot, source = 'snapshot'): void {\n parseIso(snapshot.at, `${source}.at`)\n if (typeof snapshot.judgeId !== 'string' || snapshot.judgeId.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeId must be a non-empty string`)\n }\n if (typeof snapshot.judgeModel !== 'string' || snapshot.judgeModel.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeModel must be a non-empty string`)\n }\n if (snapshot.metrics === null || typeof snapshot.metrics !== 'object') {\n throw new ValidationError(`judge-sentinel: ${source}.metrics must be an object (may be empty)`)\n }\n for (const [key, value] of Object.entries(snapshot.metrics)) {\n if (!(SENTINEL_METRIC_NAMES as readonly string[]).includes(key)) {\n // A typo'd key would silently never trend — reject instead.\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics carries unknown key \"${key}\" — known: ${SENTINEL_METRIC_NAMES.join(', ')}`,\n )\n }\n if (value !== undefined && !Number.isFinite(value)) {\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics.${key} is not a finite number: ${String(value)}`,\n )\n }\n }\n}\n\n// ── Snapshot adapters — real instrument output → SentinelSnapshot ───\n\n/**\n * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the\n * un-rounded continuous κ_w when the report carries one (integer κ\n * discards information for [0,1] judges).\n */\nexport function snapshotFromCalibration(\n report: CalibrationResult | ContinuousCalibrationResult,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const kappa = 'weightedKappaContinuous' in report ? report.weightedKappaContinuous : report.kappa\n if (!Number.isFinite(kappa)) {\n throw new ValidationError(\n `snapshotFromCalibration: κ is not finite (n=${report.n}) — calibrate against ≥2 joined golden items before snapshotting`,\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { calibrationKappa: kappa } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n/**\n * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`\n * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability\n * coefficient both instruments compute. For ensemble-level agreement,\n * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its\n * composition (e.g. a joined list of member model strings).\n */\nexport function snapshotFromAgreement(\n report: CorpusAgreementReport | ContinuousAgreement,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const irr = 'overallIcc' in report ? report.overallIcc : report.icc\n if (!Number.isFinite(irr)) {\n throw new ValidationError(\n 'snapshotFromAgreement: ICC is not finite — agreement needs ≥2 raters and ≥2 complete items',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { irr } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\nexport interface SentinelSetOptions {\n /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */\n tolerance?: number\n}\n\n/**\n * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the\n * judge was originally calibrated on, re-scored periodically. Pass rate =\n * fraction of joined items where the judge stays within `tolerance` of the\n * human score. Items the judge didn't score are excluded from the\n * denominator; zero joined items is an error, not a 0% pass rate.\n */\nexport function snapshotFromSentinelSet(\n scores: CandidateScore[],\n golden: GoldenItem[],\n meta: SnapshotMeta,\n options: SentinelSetOptions = {},\n): SentinelSnapshot {\n const tolerance = options.tolerance ?? 0.1\n if (!Number.isFinite(tolerance) || tolerance < 0) {\n throw new ValidationError(\n `snapshotFromSentinelSet: tolerance must be a finite number ≥ 0, got ${tolerance}`,\n )\n }\n const goldenById = new Map<string, number>()\n for (const item of golden) {\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: golden item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (goldenById.has(item.itemId)) {\n throw new ValidationError(`snapshotFromSentinelSet: duplicate golden itemId \"${item.itemId}\"`)\n }\n goldenById.set(item.itemId, item.humanScore)\n }\n let joined = 0\n let passed = 0\n for (const s of scores) {\n const human = goldenById.get(s.itemId)\n if (human === undefined) continue\n if (!Number.isFinite(s.score)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: judge score for item \"${s.itemId}\" is not finite`,\n )\n }\n joined++\n if (Math.abs(s.score - human) <= tolerance) passed++\n }\n if (joined === 0) {\n throw new ValidationError(\n 'snapshotFromSentinelSet: no judge scores joined the golden set — itemIds mismatch or empty sentinel run',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { sentinelPassRate: passed / joined } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n// ── Persistence ──────────────────────────────────────────────────────\n\nexport interface SentinelStore {\n append(snapshot: SentinelSnapshot): Promise<void>\n /** All snapshots (optionally for one judge), in append order. */\n history(judgeId?: string): Promise<SentinelSnapshot[]>\n}\n\nexport function inMemorySentinelStore(initial: SentinelSnapshot[] = []): SentinelStore {\n for (const s of initial) validateSentinelSnapshot(s)\n const items = initial.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n items.push({ ...snapshot, metrics: { ...snapshot.metrics } })\n },\n async history(judgeId) {\n const all = items.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return judgeId === undefined ? all : all.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n/**\n * JSONL store — one snapshot per line, appended atomically per call.\n * A corrupt or shape-invalid line is a loud error naming the file and\n * line number: a sentinel history that silently drops records would\n * defeat the drift detection it exists to provide.\n */\nexport function fileSentinelStore(path: string): SentinelStore {\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n const fs = await import('node:fs/promises')\n const pathMod = await import('node:path')\n await fs.mkdir(pathMod.dirname(path), { recursive: true })\n await fs.appendFile(path, `${JSON.stringify(snapshot)}\\n`, 'utf8')\n },\n async history(judgeId) {\n const fs = await import('node:fs/promises')\n let raw: string\n try {\n raw = await fs.readFile(path, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw err\n }\n const lines = raw.split('\\n')\n const snapshots: SentinelSnapshot[] = []\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n if (line.trim().length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `judge-sentinel: store at ${path} has a corrupt JSONL line ${i + 1}: ${(err as Error).message}`,\n )\n }\n const snapshot = parsed as SentinelSnapshot\n validateSentinelSnapshot(snapshot, `${path}:${i + 1}`)\n snapshots.push(snapshot)\n }\n return judgeId === undefined ? snapshots : snapshots.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n// ── Trend report ─────────────────────────────────────────────────────\n\nexport interface SentinelThresholds {\n /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */\n minIrr?: number\n /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */\n maxKappaDrop?: number\n /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */\n maxSentinelDrop?: number\n /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */\n staleAfterDays?: number\n}\n\nexport interface JudgeSentinelOptions {\n /** Caller-supplied ISO timestamp staleness is measured against. */\n asOf: string\n thresholds?: SentinelThresholds\n /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */\n convergence?: SeriesConvergenceOptions\n}\n\nexport interface SentinelTrend {\n judgeId: string\n metric: SentinelMetricName\n /** Verbatim `analyzeSeries` state for this judge×metric history. */\n state: SeriesConvergenceResult['state']\n /** Newest value in the series. */\n current: number\n /** Oldest value in the series — the reference the drop thresholds compare against. */\n baseline: number\n /** current − baseline (signed; negative = decayed). */\n drift: number\n alarmed: boolean\n reason?: string\n}\n\nexport interface SentinelReport {\n perJudge: SentinelTrend[]\n alarms: string[]\n healthy: boolean\n /**\n * `judgeId:metric` pairs with too few snapshots for the convergence\n * machine. Named, not counted — a blind spot you can't see is a blind\n * spot you won't fix. Floor/drop checks still apply to thin series, so\n * insufficient history alone never masks an alarm.\n */\n insufficientHistory: string[]\n}\n\nconst MS_PER_DAY = 86_400_000\n\nexport function judgeSentinelReport(\n history: SentinelSnapshot[],\n opts: JudgeSentinelOptions,\n): SentinelReport {\n const asOfMs = parseIso(opts.asOf, 'asOf')\n const minIrr = opts.thresholds?.minIrr ?? 0.6\n const maxKappaDrop = opts.thresholds?.maxKappaDrop ?? 0.15\n const maxSentinelDrop = opts.thresholds?.maxSentinelDrop ?? 0.1\n const staleAfterDays = opts.thresholds?.staleAfterDays ?? 30\n\n const byJudge = new Map<string, Array<SentinelSnapshot & { atMs: number }>>()\n for (const snapshot of history) {\n validateSentinelSnapshot(snapshot)\n const atMs = parseIso(snapshot.at, `snapshot.at (judge \"${snapshot.judgeId}\")`)\n const arr = byJudge.get(snapshot.judgeId) ?? []\n arr.push({ ...snapshot, atMs })\n byJudge.set(snapshot.judgeId, arr)\n }\n\n const perJudge: SentinelTrend[] = []\n const alarms: string[] = []\n const insufficientHistory: string[] = []\n\n for (const judgeId of [...byJudge.keys()].sort()) {\n const snaps = byJudge.get(judgeId)!.sort((a, b) => a.atMs - b.atMs)\n const newest = snaps[snaps.length - 1]!\n\n const ageDays = (asOfMs - newest.atMs) / MS_PER_DAY\n if (ageDays > staleAfterDays) {\n alarms.push(\n `judge \"${judgeId}\": stale — newest snapshot ${newest.at} is ${ageDays.toFixed(1)}d old vs asOf (limit ${staleAfterDays}d)`,\n )\n }\n\n // Silent-upgrade trap: only the latest model change matters for current\n // trust, and only golden-grounded metrics clear it — irr alone proves\n // judges still agree with each other, not that they're still right.\n let changeIdx = -1\n for (let i = 1; i < snaps.length; i++) {\n if (snaps[i]!.judgeModel !== snaps[i - 1]!.judgeModel) changeIdx = i\n }\n if (changeIdx >= 0) {\n const recalibrated = snaps\n .slice(changeIdx)\n .some(\n (s) =>\n Number.isFinite(s.metrics.calibrationKappa) ||\n Number.isFinite(s.metrics.sentinelPassRate),\n )\n if (!recalibrated) {\n alarms.push(\n `judge \"${judgeId}\": model changed \"${snaps[changeIdx - 1]!.judgeModel}\" → \"${snaps[changeIdx]!.judgeModel}\" at ${snaps[changeIdx]!.at} with no post-change calibration snapshot — silent-upgrade trap; rerun calibrateJudge or the sentinel set against the new model`,\n )\n }\n }\n\n for (const metric of SENTINEL_METRIC_NAMES) {\n const values = snaps\n .filter((s) => typeof s.metrics[metric] === 'number')\n .map((s) => s.metrics[metric]!)\n if (values.length === 0) continue\n\n const convergence = analyzeSeries(values, opts.convergence)\n if (convergence.state === 'insufficient-data')\n insufficientHistory.push(`${judgeId}:${metric}`)\n\n const current = values[values.length - 1]!\n const baseline = values[0]!\n const drift = current - baseline\n const reasons: string[] = []\n if (convergence.state === 'drifting-down') {\n reasons.push(\n `convergence state drifting-down (tail run ${convergence.tailRun}, window mean ${convergence.windowMean.toFixed(3)})`,\n )\n }\n if (metric === 'irr' && current < minIrr) {\n reasons.push(`irr ${current.toFixed(3)} below floor ${minIrr}`)\n }\n if (metric === 'calibrationKappa' && baseline - current > maxKappaDrop) {\n reasons.push(\n `calibrationKappa dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxKappaDrop})`,\n )\n }\n if (metric === 'sentinelPassRate' && baseline - current > maxSentinelDrop) {\n reasons.push(\n `sentinelPassRate dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxSentinelDrop})`,\n )\n }\n\n const alarmed = reasons.length > 0\n const trend: SentinelTrend = {\n judgeId,\n metric,\n state: convergence.state,\n current,\n baseline,\n drift,\n alarmed,\n }\n if (alarmed) {\n trend.reason = reasons.join('; ')\n alarms.push(`judge \"${judgeId}\" ${metric}: ${trend.reason}`)\n }\n perJudge.push(trend)\n }\n }\n\n return { perJudge, alarms, healthy: alarms.length === 0, insufficientHistory }\n}\n\n// ── Verdict stamp ────────────────────────────────────────────────────\n\nexport interface EvalHealthStamp {\n healthy: boolean\n alarms: string[]\n}\n\n/**\n * The object a campaign attaches to its verdicts. Compute it from the\n * sentinel report in a post-campaign hook (or a nightly job feeding the\n * next day's campaigns) and store it alongside the verdict payload.\n * `healthy: false` means the judges that produced those verdicts have an\n * unresolved drift / decay / silent-upgrade / staleness alarm — treat the\n * verdicts as carrying an integrity warning until recalibration clears it.\n */\nexport function evalHealthStamp(report: SentinelReport): EvalHealthStamp {\n return { healthy: report.healthy, alarms: [...report.alarms] }\n}\n"],"mappings":";;;;;;;;AAgDA,eAAsB,iBACpB,YACA,cACA,YACA,eACA,UAA8B,CAAC,GACI;CACnC,MAAM,OAAO,MAAM,WAAW,SAAS;CACvC,MAAM,WAAW,MAAM,aAAa,KAAK;CACzC,MAAM,wBAAQ,IAAI,IAAiC;CACnD,KAAK,MAAM,KAAK,UAAU;EACxB,MAAM,MAAM,MAAM,IAAI,EAAE,KAAK,KAAK,CAAC;EACnC,IAAI,KAAK,CAAC;EACV,MAAM,IAAI,EAAE,OAAO,GAAG;CACxB;CAEA,MAAM,UAAU,WAAW,WAAWA,iBAAe,WAAW,EAAE;CAClE,MAAM,QAAyC,CAAC;CAChD,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,KAAK,MAAM,IAAI,IAAI,KAAK;EAC9B,IAAI,CAAC,IAAI,QAAQ;EACjB,MAAM,IAAI,MAAM,QAAQ,KAAK,UAAU;EACvC,IAAI,MAAM,QAAQ,CAAC,OAAO,SAAS,CAAC,GAAG;EAEvC,MAAM,IADS,CAAC,GAAG,EAAE,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU,CAAC,CAAC,EACnD,CAAC,QAAQ;EACzB,IAAI,OAAO,MAAM,YAAY,CAAC,OAAO,SAAS,CAAC,GAAG;EAClD,MAAM,KAAK;GAAE;GAAG;EAAE,CAAC;CACrB;CACA,IAAI,MAAM,SAAS,GAAG,OAAO;CAE7B,OAAO,qBACL,MAAM,KAAK,OAAO;EAAE,WAAW,EAAE;EAAG,SAAS,EAAE;CAAE,EAAE,GACnD,WAAW,IACX,eACA,OACF;AACF;AAEA,SAAS,qBACP,YACA,YACA,eACA,UAA8B,CAAC,GACL;CAC1B,MAAM,QAAQ,WAAW,QACtB,SAAS,OAAO,SAAS,KAAK,SAAS,KAAK,OAAO,SAAS,KAAK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,QAAQ,CAAC,EAAE,iBAAiB,SAAS,QAAQ,CAAC,EAAE,UAAU,aAAa,EAC1H;GAEF,IAAI,WAAW,sBAAsB,WAAW,UAAU,iBACxD,QAAQ,KACN,6BAA6B,WAAW,QAAA,CAAS,QAAQ,CAAC,EAAE,iBAAiB,SAAS,QAAQ,CAAC,EAAE,UAAU,gBAAgB,EAC7H;GAGF,MAAM,UAAU,QAAQ,SAAS;GACjC,MAAM,QAAuB;IAC3B;IACA;IACA,OAAO,YAAY;IACnB;IACA;IACA;IACA;GACF;GACA,IAAI,SAAS;IACX,MAAM,SAAS,QAAQ,KAAK,IAAI;IAChC,OAAO,KAAK,UAAU,QAAQ,IAAI,OAAO,IAAI,MAAM,QAAQ;GAC7D;GACA,SAAS,KAAK,KAAK;EACrB;CACF;CAEA,OAAO;EAAE;EAAU;EAAQ,SAAS,OAAO,WAAW;EAAG;CAAoB;AAC/E;;;;;;;;;AAiBA,SAAgB,gBAAgB,QAAyC;CACvE,OAAO;EAAE,SAAS,OAAO;EAAS,QAAQ,CAAC,GAAG,OAAO,MAAM;CAAE;AAC/D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/meta-eval/calibration.ts","../../src/meta-eval/correlation-study.ts","../../src/meta-eval/sentinel.ts"],"sourcesContent":["/**\n * Calibration curve — binned \"if eval says X, what does reality show?\"\n *\n * Companion to correlationStudy. Raw correlation is a single number;\n * the calibration curve shows *where* the eval is well-calibrated vs\n * overconfident / underconfident. Buckets the eval metric, computes\n * mean outcome per bucket, reports expected-calibration-error (ECE).\n */\n\nimport { runMetricExtractor } from '../trace/query'\nimport type { TraceStore } from '../trace/store'\nimport type { EvalMetricSpec } from './correlation-study'\nimport type { DeploymentOutcome, OutcomeStore } from './outcome-store'\n\nexport interface CalibrationBin {\n lower: number\n upper: number\n n: number\n evalMean: number\n outcomeMean: number\n /** |outcomeMean − evalMean|; contributes to ECE weighted by n/total. */\n gap: number\n}\n\nexport interface CalibrationReport {\n evalMetric: string\n outcomeMetric: string\n n: number\n bins: CalibrationBin[]\n /** Expected Calibration Error — Σ (n_i/N) × |outcomeMean_i − evalMean_i|. */\n ece: number\n /** Max bin gap — upper bound on miscalibration. */\n maxGap: number\n}\n\nexport interface CalibrationOptions {\n bins?: number\n /** Equal-width (fixed bin edges) or equal-frequency (quantile bins). */\n binning?: 'equal-width' | 'equal-frequency'\n /** Clip eval values to [lo, hi] before binning. */\n range?: { lo: number; hi: number }\n}\n\nexport interface CalibrationPair {\n evalScore: number\n outcome: number\n}\n\nexport async function calibrationCurve(\n traceStore: TraceStore,\n outcomeStore: OutcomeStore,\n evalMetric: EvalMetricSpec,\n outcomeMetric: string,\n options: CalibrationOptions = {},\n): Promise<CalibrationReport | null> {\n const runs = await traceStore.listRuns()\n const outcomes = await outcomeStore.list()\n const byRun = new Map<string, DeploymentOutcome[]>()\n for (const o of outcomes) {\n const arr = byRun.get(o.runId) ?? []\n arr.push(o)\n byRun.set(o.runId, arr)\n }\n\n const extract = evalMetric.extract ?? runMetricExtractor(evalMetric.id)\n const pairs: Array<{ x: number; y: number }> = []\n for (const run of runs) {\n const os = byRun.get(run.runId)\n if (!os?.length) continue\n const x = await extract(run, traceStore)\n if (x === null || !Number.isFinite(x)) continue\n const latest = [...os].sort((a, b) => b.capturedAt - a.capturedAt)[0]!\n const y = latest.metrics[outcomeMetric]\n if (typeof y !== 'number' || !Number.isFinite(y)) continue\n pairs.push({ x, y })\n }\n if (pairs.length < 2) return null\n\n return calibrationFromPairs(\n pairs.map((p) => ({ evalScore: p.x, outcome: p.y })),\n evalMetric.id,\n outcomeMetric,\n options,\n )\n}\n\nfunction calibrationFromPairs(\n inputPairs: CalibrationPair[],\n evalMetric: string,\n outcomeMetric: string,\n options: CalibrationOptions = {},\n): CalibrationReport | null {\n const pairs = inputPairs.filter(\n (pair) => Number.isFinite(pair.evalScore) && Number.isFinite(pair.outcome),\n )\n if (pairs.length < 2) return null\n\n const numBins = options.bins ?? 10\n const binning = options.binning ?? 'equal-width'\n const xs = pairs.map((p) => p.evalScore)\n const lo = options.range?.lo ?? Math.min(...xs)\n const hi = options.range?.hi ?? Math.max(...xs)\n\n const bins: CalibrationBin[] = []\n if (binning === 'equal-frequency') {\n const sorted = [...pairs].sort((a, b) => a.evalScore - b.evalScore)\n const perBin = Math.max(1, Math.floor(sorted.length / numBins))\n for (let i = 0; i < sorted.length; i += perBin) {\n const chunk = sorted.slice(i, i + perBin)\n if (chunk.length === 0) continue\n bins.push(toBin(chunk))\n }\n } else {\n const width = (hi - lo) / numBins\n if (width === 0) return null\n for (let i = 0; i < numBins; i++) {\n const binLo = lo + i * width\n const binHi = i === numBins - 1 ? hi + 1e-9 : lo + (i + 1) * width\n const chunk = pairs.filter((p) => p.evalScore >= binLo && p.evalScore < binHi)\n if (chunk.length === 0) continue\n bins.push(toBin(chunk, binLo, binHi))\n }\n }\n\n const total = bins.reduce((a, b) => a + b.n, 0)\n const ece = bins.reduce((a, b) => a + (b.n / total) * b.gap, 0)\n const maxGap = bins.reduce((a, b) => Math.max(a, b.gap), 0)\n\n return { evalMetric, outcomeMetric, n: pairs.length, bins, ece, maxGap }\n}\n\nfunction toBin(chunk: CalibrationPair[], lower?: number, upper?: number): CalibrationBin {\n const xs = chunk.map((c) => c.evalScore)\n const ys = chunk.map((c) => c.outcome)\n const evalMean = mean(xs)\n const outcomeMean = mean(ys)\n return {\n lower: lower ?? Math.min(...xs),\n upper: upper ?? Math.max(...xs),\n n: chunk.length,\n evalMean,\n outcomeMean,\n gap: Math.abs(outcomeMean - evalMean),\n }\n}\n\nfunction mean(xs: number[]): number {\n return xs.reduce((a, b) => a + b, 0) / xs.length\n}\n","/**\n * Correlation study — \"does our eval score predict real-world outcomes?\"\n *\n * This is the load-bearing signal. Takes a TraceStore + OutcomeStore,\n * joins on runId, computes Pearson + Spearman + bootstrap CI for every\n * (evalMetric, outcomeMetric) pair the caller declares.\n *\n * Without this number the framework is ornamental. With it and r > 0.6\n * the framework is a moat — no other agent-eval tool publishes one.\n */\n\nimport { pearsonR, spearmanR } from '../statistics'\nimport { makeRng } from '../statistics/internal'\nimport { runMetricExtractor } from '../trace/query'\nimport type { Run } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport type { DeploymentOutcome, OutcomeFilter, OutcomeStore } from './outcome-store'\n\nexport interface EvalMetricSpec {\n id: string\n /** Extract a scalar from a run. Omit it and `id` must name one of\n * `RUN_METRICS`; any other `id` is refused. */\n extract?: (run: Run, store: TraceStore) => Promise<number | null>\n}\n\nexport interface OutcomePair {\n evalMetric: string\n outcomeMetric: string\n}\n\nexport interface CorrelationResult {\n evalMetric: string\n outcomeMetric: string\n n: number\n pearson: number\n spearman: number\n /** 95% bootstrap CI for Pearson. */\n pearsonCi95: { lower: number; upper: number }\n /** Rough verdict: 'strong' ≥ 0.7, 'moderate' ≥ 0.4, else 'weak'. */\n verdict: 'strong' | 'moderate' | 'weak'\n}\n\nexport interface CorrelationStudyResult {\n pairs: CorrelationResult[]\n joinedSamples: number\n skippedRuns: number\n}\n\nexport interface CorrelationStudyOptions {\n /** Only join outcomes captured within this window after run.startedAt. */\n maxCaptureLagMs?: number\n /** Restrict to a subset of outcomes (cohort, region, source). */\n outcomeFilter?: OutcomeFilter\n /** Which outcome per run to use when multiple exist. Default 'latest'. */\n reduction?: 'latest' | 'mean' | 'max'\n /** Bootstrap iterations for the CI. Default 500. */\n bootstrapIterations?: number\n /** Seed for the bootstrap resampler. Absent, the seed is derived from the\n * paired observations, so the same study reproduces the same interval. */\n seed?: number\n}\n\nexport async function correlationStudy(\n traceStore: TraceStore,\n outcomeStore: OutcomeStore,\n evalMetrics: EvalMetricSpec[],\n outcomeMetricNames: string[],\n options: CorrelationStudyOptions = {},\n): Promise<CorrelationStudyResult> {\n const runs = await traceStore.listRuns()\n const outcomes = await outcomeStore.list(options.outcomeFilter)\n const outcomesByRun = new Map<string, DeploymentOutcome[]>()\n for (const o of outcomes) {\n const arr = outcomesByRun.get(o.runId) ?? []\n arr.push(o)\n outcomesByRun.set(o.runId, arr)\n }\n\n const reduction = options.reduction ?? 'latest'\n const maxLag = options.maxCaptureLagMs ?? Infinity\n\n const pairs: Array<{ evalMetric: string; outcomeMetric: string; xs: number[]; ys: number[] }> = []\n for (const em of evalMetrics) {\n for (const om of outcomeMetricNames) {\n pairs.push({ evalMetric: em.id, outcomeMetric: om, xs: [], ys: [] })\n }\n }\n\n let joined = 0\n let skipped = 0\n for (const run of runs) {\n const os = outcomesByRun.get(run.runId)\n if (!os || os.length === 0) {\n skipped++\n continue\n }\n const eligible = os.filter((o) => o.capturedAt - run.startedAt <= maxLag)\n if (eligible.length === 0) {\n skipped++\n continue\n }\n\n for (const em of evalMetrics) {\n const extract = em.extract ?? runMetricExtractor(em.id)\n const x = await extract(run, traceStore)\n if (x === null || !Number.isFinite(x)) continue\n\n for (const om of outcomeMetricNames) {\n const values = eligible\n .map((o) => o.metrics[om])\n .filter((v): v is number => typeof v === 'number' && Number.isFinite(v))\n if (values.length === 0) continue\n const y = reduce(values, reduction, eligible)\n if (y === null) continue\n const pair = pairs.find((p) => p.evalMetric === em.id && p.outcomeMetric === om)!\n pair.xs.push(x)\n pair.ys.push(y)\n }\n }\n joined++\n }\n\n const results: CorrelationResult[] = pairs\n .filter((p) => p.xs.length >= 3)\n .map((p) => {\n const pearson = pearsonR(p.xs, p.ys)\n const spearman = spearmanR(p.xs, p.ys)\n const pearsonCi95 = bootstrapPearsonCi(\n p.xs,\n p.ys,\n options.bootstrapIterations ?? 500,\n options.seed,\n )\n const verdict: CorrelationResult['verdict'] =\n Math.abs(pearson) >= 0.7 ? 'strong' : Math.abs(pearson) >= 0.4 ? 'moderate' : 'weak'\n return {\n evalMetric: p.evalMetric,\n outcomeMetric: p.outcomeMetric,\n n: p.xs.length,\n pearson,\n spearman,\n pearsonCi95,\n verdict,\n }\n })\n\n return { pairs: results, joinedSamples: joined, skippedRuns: skipped }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\nfunction reduce(\n values: number[],\n kind: 'latest' | 'mean' | 'max',\n outcomes: DeploymentOutcome[],\n): number | null {\n if (values.length === 0) return null\n if (kind === 'mean') return values.reduce((a, b) => a + b, 0) / values.length\n if (kind === 'max') return Math.max(...values)\n // 'latest': pick the outcome captured last, then lookup its metric\n const latest = [...outcomes].sort((a, b) => b.capturedAt - a.capturedAt)[0]\n if (!latest) return null\n const latestKey = Object.keys(latest.metrics)[0]\n const v = latestKey !== undefined ? latest.metrics[latestKey] : undefined\n // For 'latest' we already have `values` aligned; use the last-captured one\n const paired = outcomes\n .map((o) => {\n const k = Object.keys(o.metrics)[0]\n return {\n at: o.capturedAt,\n v: k !== undefined ? values.find((x) => o.metrics[k] === x) : undefined,\n }\n })\n .filter((p) => p.v !== undefined)\n if (paired.length === 0) return v ?? null\n return paired.sort((a, b) => b.at - a.at)[0]?.v ?? null\n}\n\nfunction bootstrapPearsonCi(\n xs: number[],\n ys: number[],\n iterations: number,\n seed: number | undefined,\n): { lower: number; upper: number } {\n const n = xs.length\n if (n < 3) return { lower: NaN, upper: NaN }\n const rng = makeRng(seed, xs, ys)\n const rs: number[] = []\n for (let b = 0; b < iterations; b++) {\n const rx: number[] = new Array(n)\n const ry: number[] = new Array(n)\n for (let i = 0; i < n; i++) {\n const idx = Math.floor(rng() * n)\n rx[i] = xs[idx]!\n ry[i] = ys[idx]!\n }\n const r = pearsonR(rx, ry)\n if (Number.isFinite(r)) rs.push(r)\n }\n rs.sort((a, b) => a - b)\n if (rs.length === 0) return { lower: NaN, upper: NaN }\n return {\n lower: rs[Math.floor(0.025 * rs.length)]!,\n upper: rs[Math.min(rs.length - 1, Math.floor(0.975 * rs.length))]!,\n }\n}\n","/**\n * Judge sentinel — eval trustworthiness as a continuously measured,\n * alarmed trend.\n *\n * Judges are models; models change underneath us; calibration decays.\n * This module composes three existing instruments into one loop:\n *\n * snapshot — adapters turn real instrument outputs (`calibrateJudge` /\n * `calibrateJudgeContinuous`, `corpusInterRaterAgreement` /\n * `continuousAgreement`, a rerun sentinel golden set) into\n * `SentinelSnapshot`s\n * series — `analyzeSeries` (src/series-convergence) classifies each\n * judge×metric history as stabilized / drifting / noisy\n * alarm — `judgeSentinelReport` turns trends + thresholds into named\n * alarms; `evalHealthStamp` is the tiny object a campaign\n * attaches to its verdicts\n *\n * Alarm conditions:\n * - convergence state `drifting-down` on any tracked metric\n * - irr below `minIrr`\n * - calibrationKappa / sentinelPassRate dropped vs the series baseline\n * beyond `maxKappaDrop` / `maxSentinelDrop`\n * - judge model changed with no post-change golden-grounded snapshot\n * (the silent-upgrade trap: judges agreeing with each other after a\n * model swap proves nothing — only re-measuring against gold does)\n * - newest snapshot older than `staleAfterDays` relative to `asOf`\n *\n * Wire-in: run the snapshot adapters from a post-campaign hook or a\n * nightly job, append to a `SentinelStore`, then compute\n * `judgeSentinelReport(await store.history(), { asOf })` with `asOf` =\n * the campaign timestamp. Attach `evalHealthStamp(report)` to campaign\n * verdicts: an alarmed sentinel means every downstream verdict carries\n * an integrity warning until the judge is recalibrated.\n *\n * The module is clock-free — every timestamp (`at`, `asOf`) is\n * caller-supplied ISO-8601, so reports are reproducible.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n CalibrationResult,\n CandidateScore,\n ContinuousAgreement,\n ContinuousCalibrationResult,\n GoldenItem,\n} from '../judge-calibration'\nimport {\n analyzeSeries,\n type SeriesConvergenceOptions,\n type SeriesConvergenceResult,\n} from '../series-convergence'\nimport type { CorpusAgreementReport } from '../statistics'\n\nconst SENTINEL_METRIC_NAMES = ['irr', 'calibrationKappa', 'sentinelPassRate'] as const\n\nexport type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number]\n\nexport interface SentinelMetrics {\n /** Inter-rater reliability — ICC(2,1) from agreement instruments. */\n irr?: number\n /** Weighted κ vs the human golden set (`calibrateJudge*`). */\n calibrationKappa?: number\n /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */\n sentinelPassRate?: number\n}\n\nexport interface SentinelSnapshot {\n /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */\n at: string\n judgeId: string\n /** Exact model identity behind the judge (pin the full version string). */\n judgeModel: string\n /**\n * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a\n * model-change marker — it records the new `judgeModel` immediately and\n * the silent-upgrade alarm stays raised until a golden-grounded snapshot\n * (calibrationKappa or sentinelPassRate) follows.\n */\n metrics: SentinelMetrics\n}\n\n/** Identity + timestamp the caller supplies alongside an instrument output. */\nexport interface SnapshotMeta {\n at: string\n judgeId: string\n judgeModel: string\n}\n\nfunction parseIso(value: string, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-sentinel: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\n/** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */\nexport function validateSentinelSnapshot(snapshot: SentinelSnapshot, source = 'snapshot'): void {\n parseIso(snapshot.at, `${source}.at`)\n if (typeof snapshot.judgeId !== 'string' || snapshot.judgeId.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeId must be a non-empty string`)\n }\n if (typeof snapshot.judgeModel !== 'string' || snapshot.judgeModel.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeModel must be a non-empty string`)\n }\n if (snapshot.metrics === null || typeof snapshot.metrics !== 'object') {\n throw new ValidationError(`judge-sentinel: ${source}.metrics must be an object (may be empty)`)\n }\n for (const [key, value] of Object.entries(snapshot.metrics)) {\n if (!(SENTINEL_METRIC_NAMES as readonly string[]).includes(key)) {\n // A typo'd key would silently never trend — reject instead.\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics carries unknown key \"${key}\" — known: ${SENTINEL_METRIC_NAMES.join(', ')}`,\n )\n }\n if (value !== undefined && !Number.isFinite(value)) {\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics.${key} is not a finite number: ${String(value)}`,\n )\n }\n }\n}\n\n// ── Snapshot adapters — real instrument output → SentinelSnapshot ───\n\n/**\n * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the\n * un-rounded continuous κ_w when the report carries one (integer κ\n * discards information for [0,1] judges).\n */\nexport function snapshotFromCalibration(\n report: CalibrationResult | ContinuousCalibrationResult,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const kappa = 'weightedKappaContinuous' in report ? report.weightedKappaContinuous : report.kappa\n if (!Number.isFinite(kappa)) {\n throw new ValidationError(\n `snapshotFromCalibration: κ is not finite (n=${report.n}) — calibrate against ≥2 joined golden items before snapshotting`,\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { calibrationKappa: kappa } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n/**\n * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`\n * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability\n * coefficient both instruments compute. For ensemble-level agreement,\n * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its\n * composition (e.g. a joined list of member model strings).\n */\nexport function snapshotFromAgreement(\n report: CorpusAgreementReport | ContinuousAgreement,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const irr = 'overallIcc' in report ? report.overallIcc : report.icc\n if (!Number.isFinite(irr)) {\n throw new ValidationError(\n 'snapshotFromAgreement: ICC is not finite — agreement needs ≥2 raters and ≥2 complete items',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { irr } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\nexport interface SentinelSetOptions {\n /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */\n tolerance?: number\n}\n\n/**\n * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the\n * judge was originally calibrated on, re-scored periodically. Pass rate =\n * fraction of joined items where the judge stays within `tolerance` of the\n * human score. Items the judge didn't score are excluded from the\n * denominator; zero joined items is an error, not a 0% pass rate.\n */\nexport function snapshotFromSentinelSet(\n scores: CandidateScore[],\n golden: GoldenItem[],\n meta: SnapshotMeta,\n options: SentinelSetOptions = {},\n): SentinelSnapshot {\n const tolerance = options.tolerance ?? 0.1\n if (!Number.isFinite(tolerance) || tolerance < 0) {\n throw new ValidationError(\n `snapshotFromSentinelSet: tolerance must be a finite number ≥ 0, got ${tolerance}`,\n )\n }\n const goldenById = new Map<string, number>()\n for (const item of golden) {\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: golden item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (goldenById.has(item.itemId)) {\n throw new ValidationError(`snapshotFromSentinelSet: duplicate golden itemId \"${item.itemId}\"`)\n }\n goldenById.set(item.itemId, item.humanScore)\n }\n let joined = 0\n let passed = 0\n for (const s of scores) {\n const human = goldenById.get(s.itemId)\n if (human === undefined) continue\n if (!Number.isFinite(s.score)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: judge score for item \"${s.itemId}\" is not finite`,\n )\n }\n joined++\n if (Math.abs(s.score - human) <= tolerance) passed++\n }\n if (joined === 0) {\n throw new ValidationError(\n 'snapshotFromSentinelSet: no judge scores joined the golden set — itemIds mismatch or empty sentinel run',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { sentinelPassRate: passed / joined } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n// ── Persistence ──────────────────────────────────────────────────────\n\nexport interface SentinelStore {\n append(snapshot: SentinelSnapshot): Promise<void>\n /** All snapshots (optionally for one judge), in append order. */\n history(judgeId?: string): Promise<SentinelSnapshot[]>\n}\n\nexport function inMemorySentinelStore(initial: SentinelSnapshot[] = []): SentinelStore {\n for (const s of initial) validateSentinelSnapshot(s)\n const items = initial.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n items.push({ ...snapshot, metrics: { ...snapshot.metrics } })\n },\n async history(judgeId) {\n const all = items.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return judgeId === undefined ? all : all.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n/**\n * JSONL store — one snapshot per line, appended atomically per call.\n * A corrupt or shape-invalid line is a loud error naming the file and\n * line number: a sentinel history that silently drops records would\n * defeat the drift detection it exists to provide.\n */\nexport function fileSentinelStore(path: string): SentinelStore {\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n const fs = await import('node:fs/promises')\n const pathMod = await import('node:path')\n await fs.mkdir(pathMod.dirname(path), { recursive: true })\n await fs.appendFile(path, `${JSON.stringify(snapshot)}\\n`, 'utf8')\n },\n async history(judgeId) {\n const fs = await import('node:fs/promises')\n let raw: string\n try {\n raw = await fs.readFile(path, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw err\n }\n const lines = raw.split('\\n')\n const snapshots: SentinelSnapshot[] = []\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n if (line.trim().length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `judge-sentinel: store at ${path} has a corrupt JSONL line ${i + 1}: ${(err as Error).message}`,\n )\n }\n const snapshot = parsed as SentinelSnapshot\n validateSentinelSnapshot(snapshot, `${path}:${i + 1}`)\n snapshots.push(snapshot)\n }\n return judgeId === undefined ? snapshots : snapshots.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n// ── Trend report ─────────────────────────────────────────────────────\n\nexport interface SentinelThresholds {\n /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */\n minIrr?: number\n /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */\n maxKappaDrop?: number\n /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */\n maxSentinelDrop?: number\n /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */\n staleAfterDays?: number\n}\n\nexport interface JudgeSentinelOptions {\n /** Caller-supplied ISO timestamp staleness is measured against. */\n asOf: string\n thresholds?: SentinelThresholds\n /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */\n convergence?: SeriesConvergenceOptions\n}\n\nexport interface SentinelTrend {\n judgeId: string\n metric: SentinelMetricName\n /** Verbatim `analyzeSeries` state for this judge×metric history. */\n state: SeriesConvergenceResult['state']\n /** Newest value in the series. */\n current: number\n /** Oldest value in the series — the reference the drop thresholds compare against. */\n baseline: number\n /** current − baseline (signed; negative = decayed). */\n drift: number\n alarmed: boolean\n reason?: string\n}\n\nexport interface SentinelReport {\n perJudge: SentinelTrend[]\n alarms: string[]\n healthy: boolean\n /**\n * `judgeId:metric` pairs with too few snapshots for the convergence\n * machine. Named, not counted — a blind spot you can't see is a blind\n * spot you won't fix. Floor/drop checks still apply to thin series, so\n * insufficient history alone never masks an alarm.\n */\n insufficientHistory: string[]\n}\n\nconst MS_PER_DAY = 86_400_000\n\nexport function judgeSentinelReport(\n history: SentinelSnapshot[],\n opts: JudgeSentinelOptions,\n): SentinelReport {\n const asOfMs = parseIso(opts.asOf, 'asOf')\n const minIrr = opts.thresholds?.minIrr ?? 0.6\n const maxKappaDrop = opts.thresholds?.maxKappaDrop ?? 0.15\n const maxSentinelDrop = opts.thresholds?.maxSentinelDrop ?? 0.1\n const staleAfterDays = opts.thresholds?.staleAfterDays ?? 30\n\n const byJudge = new Map<string, Array<SentinelSnapshot & { atMs: number }>>()\n for (const snapshot of history) {\n validateSentinelSnapshot(snapshot)\n const atMs = parseIso(snapshot.at, `snapshot.at (judge \"${snapshot.judgeId}\")`)\n const arr = byJudge.get(snapshot.judgeId) ?? []\n arr.push({ ...snapshot, atMs })\n byJudge.set(snapshot.judgeId, arr)\n }\n\n const perJudge: SentinelTrend[] = []\n const alarms: string[] = []\n const insufficientHistory: string[] = []\n\n for (const judgeId of [...byJudge.keys()].sort()) {\n const snaps = byJudge.get(judgeId)!.sort((a, b) => a.atMs - b.atMs)\n const newest = snaps[snaps.length - 1]!\n\n const ageDays = (asOfMs - newest.atMs) / MS_PER_DAY\n if (ageDays > staleAfterDays) {\n alarms.push(\n `judge \"${judgeId}\": stale — newest snapshot ${newest.at} is ${ageDays.toFixed(1)}d old vs asOf (limit ${staleAfterDays}d)`,\n )\n }\n\n // Silent-upgrade trap: only the latest model change matters for current\n // trust, and only golden-grounded metrics clear it — irr alone proves\n // judges still agree with each other, not that they're still right.\n let changeIdx = -1\n for (let i = 1; i < snaps.length; i++) {\n if (snaps[i]!.judgeModel !== snaps[i - 1]!.judgeModel) changeIdx = i\n }\n if (changeIdx >= 0) {\n const recalibrated = snaps\n .slice(changeIdx)\n .some(\n (s) =>\n Number.isFinite(s.metrics.calibrationKappa) ||\n Number.isFinite(s.metrics.sentinelPassRate),\n )\n if (!recalibrated) {\n alarms.push(\n `judge \"${judgeId}\": model changed \"${snaps[changeIdx - 1]!.judgeModel}\" → \"${snaps[changeIdx]!.judgeModel}\" at ${snaps[changeIdx]!.at} with no post-change calibration snapshot — silent-upgrade trap; rerun calibrateJudge or the sentinel set against the new model`,\n )\n }\n }\n\n for (const metric of SENTINEL_METRIC_NAMES) {\n const values = snaps\n .filter((s) => typeof s.metrics[metric] === 'number')\n .map((s) => s.metrics[metric]!)\n if (values.length === 0) continue\n\n const convergence = analyzeSeries(values, opts.convergence)\n if (convergence.state === 'insufficient-data')\n insufficientHistory.push(`${judgeId}:${metric}`)\n\n const current = values[values.length - 1]!\n const baseline = values[0]!\n const drift = current - baseline\n const reasons: string[] = []\n if (convergence.state === 'drifting-down') {\n reasons.push(\n `convergence state drifting-down (tail run ${convergence.tailRun}, window mean ${convergence.windowMean.toFixed(3)})`,\n )\n }\n if (metric === 'irr' && current < minIrr) {\n reasons.push(`irr ${current.toFixed(3)} below floor ${minIrr}`)\n }\n if (metric === 'calibrationKappa' && baseline - current > maxKappaDrop) {\n reasons.push(\n `calibrationKappa dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxKappaDrop})`,\n )\n }\n if (metric === 'sentinelPassRate' && baseline - current > maxSentinelDrop) {\n reasons.push(\n `sentinelPassRate dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxSentinelDrop})`,\n )\n }\n\n const alarmed = reasons.length > 0\n const trend: SentinelTrend = {\n judgeId,\n metric,\n state: convergence.state,\n current,\n baseline,\n drift,\n alarmed,\n }\n if (alarmed) {\n trend.reason = reasons.join('; ')\n alarms.push(`judge \"${judgeId}\" ${metric}: ${trend.reason}`)\n }\n perJudge.push(trend)\n }\n }\n\n return { perJudge, alarms, healthy: alarms.length === 0, insufficientHistory }\n}\n\n// ── Verdict stamp ────────────────────────────────────────────────────\n\nexport interface EvalHealthStamp {\n healthy: boolean\n alarms: string[]\n}\n\n/**\n * The object a campaign attaches to its verdicts. Compute it from the\n * sentinel report in a post-campaign hook (or a nightly job feeding the\n * next day's campaigns) and store it alongside the verdict payload.\n * `healthy: false` means the judges that produced those verdicts have an\n * unresolved drift / decay / silent-upgrade / staleness alarm — treat the\n * verdicts as carrying an integrity warning until recalibration clears it.\n */\nexport function evalHealthStamp(report: SentinelReport): EvalHealthStamp {\n return { healthy: report.healthy, alarms: [...report.alarms] }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgDA,eAAsB,iBACpB,YACA,cACA,YACA,eACA,UAA8B,CAAC,GACI;CACnC,MAAM,OAAO,MAAM,WAAW,SAAS;CACvC,MAAM,WAAW,MAAM,aAAa,KAAK;CACzC,MAAM,wBAAQ,IAAI,IAAiC;CACnD,KAAK,MAAM,KAAK,UAAU;EACxB,MAAM,MAAM,MAAM,IAAI,EAAE,KAAK,KAAK,CAAC;EACnC,IAAI,KAAK,CAAC;EACV,MAAM,IAAI,EAAE,OAAO,GAAG;CACxB;CAEA,MAAM,UAAU,WAAW,WAAW,mBAAmB,WAAW,EAAE;CACtE,MAAM,QAAyC,CAAC;CAChD,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,KAAK,MAAM,IAAI,IAAI,KAAK;EAC9B,IAAI,CAAC,IAAI,QAAQ;EACjB,MAAM,IAAI,MAAM,QAAQ,KAAK,U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W,QAAA,CAAS,QAAQ,CAAC,EAAE,iBAAiB,SAAS,QAAQ,CAAC,EAAE,UAAU,aAAa,EAC1H;GAEF,IAAI,WAAW,sBAAsB,WAAW,UAAU,iBACxD,QAAQ,KACN,6BAA6B,WAAW,QAAA,CAAS,QAAQ,CAAC,EAAE,iBAAiB,SAAS,QAAQ,CAAC,EAAE,UAAU,gBAAgB,EAC7H;GAGF,MAAM,UAAU,QAAQ,SAAS;GACjC,MAAM,QAAuB;IAC3B;IACA;IACA,OAAO,YAAY;IACnB;IACA;IACA;IACA;GACF;GACA,IAAI,SAAS;IACX,MAAM,SAAS,QAAQ,KAAK,IAAI;IAChC,OAAO,KAAK,UAAU,QAAQ,IAAI,OAAO,IAAI,MAAM,QAAQ;GAC7D;GACA,SAAS,KAAK,KAAK;EACrB;CACF;CAEA,OAAO;EAAE;EAAU;EAAQ,SAAS,OAAO,WAAW;EAAG;CAAoB;AAC/E;;;;;;;;;AAiBA,SAAgB,gBAAgB,QAAyC;CACvE,OAAO;EAAE,SAAS,OAAO;EAAS,QAAQ,CAAC,GAAG,OAAO,MAAM;CAAE;AAC/D"}
|
package/dist/openapi.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"openapi": "3.1.0",
|
|
3
3
|
"info": {
|
|
4
4
|
"title": "@tangle-network/agent-eval — wire protocol",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.163.2",
|
|
6
6
|
"description": "HTTP and stdio RPC interface to agent-eval. The TypeScript runtime is the source of truth; this spec is the contract that cross-language clients (Python, Rust, Go) generate from.\n\nWire-protocol version: 1.0.0. Bumps on breaking changes to request/response schemas.",
|
|
7
7
|
"contact": {
|
|
8
8
|
"name": "Tangle Network",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-Dngq5h35.js";
|
|
2
|
-
import { i as makeRng, l as
|
|
3
|
-
import { r as pairedBootstrap } from "./paired-tests-
|
|
2
|
+
import { c as lnGamma, i as makeRng, l as regularizedIncompleteBeta, o as symmetricTwoSampleSeed, r as binomialSignTwoSided, s as zQuantile, t as assertFiniteSample } from "./internal-BMFSR8Ns.js";
|
|
3
|
+
import { r as pairedBootstrap } from "./paired-tests-C8iCsioC.js";
|
|
4
4
|
//#region src/statistics/paired-binary.ts
|
|
5
5
|
/**
|
|
6
6
|
* Wilson score interval for a binomial proportion. Correct at small n and near
|
|
@@ -1042,4 +1042,4 @@ function metricValue(row, name) {
|
|
|
1042
1042
|
//#endregion
|
|
1043
1043
|
export { passAtK as _, MANN_WHITNEY_EXACT_MAX_STATES as a, mannWhitneyU as c, isBinaryOutcomeVector as d, mcnemar as f, pairedRiskDifferenceScore as g, pairedRiskDifferenceExact as h, DEFAULT_PERMUTATIONS as i, wilcoxonSignedRank as l, pairedRiskDifference as m, pairArms as n, MANN_WHITNEY_EXACT_MAX_WORK as o, pairedBinaryScale as p, pairRunRecords as r, WILCOXON_EXACT_MAX_N as s, comparePairedArms as t, normalCdf as u, wilson as v };
|
|
1044
1044
|
|
|
1045
|
-
//# sourceMappingURL=paired-arms-
|
|
1045
|
+
//# sourceMappingURL=paired-arms-D4aeIHUy.js.map
|