@tangle-network/agent-eval 0.86.0 → 0.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/dist/adapters/http.d.ts +3 -3
  3. package/dist/adapters/langchain.d.ts +3 -3
  4. package/dist/adapters/otel.d.ts +6 -6
  5. package/dist/adversarial-DIVcDoI_.d.ts +88 -0
  6. package/dist/analyst/index.d.ts +11 -10
  7. package/dist/analyst/index.js +13 -8
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/analyze-runs-DwCEkpO_.d.ts +81 -0
  10. package/dist/belief-state/index.d.ts +4 -4
  11. package/dist/belief-state/index.js +1 -1
  12. package/dist/benchmarks/index.d.ts +3 -3
  13. package/dist/campaign/index.d.ts +165 -18
  14. package/dist/campaign/index.js +289 -14
  15. package/dist/campaign/index.js.map +1 -1
  16. package/dist/chunk-45EEMHTC.js +35 -0
  17. package/dist/chunk-45EEMHTC.js.map +1 -0
  18. package/dist/{chunk-FZWAFVAA.js → chunk-4FBZZIYD.js} +2 -2
  19. package/dist/{chunk-YV7J7X5N.js → chunk-5HRORJQY.js} +22 -12
  20. package/dist/chunk-5HRORJQY.js.map +1 -0
  21. package/dist/{chunk-OTYQPHPL.js → chunk-6SOJM3VR.js} +5 -5
  22. package/dist/chunk-BOD4O7OF.js +40 -0
  23. package/dist/chunk-BOD4O7OF.js.map +1 -0
  24. package/dist/{chunk-Z7VFTS2J.js → chunk-CY6U5S3X.js} +2 -2
  25. package/dist/{chunk-VIDQF3F5.js → chunk-D3V5B42D.js} +5 -34
  26. package/dist/chunk-D3V5B42D.js.map +1 -0
  27. package/dist/{chunk-YGYXHNAQ.js → chunk-FIUKOSWI.js} +21 -8
  28. package/dist/chunk-FIUKOSWI.js.map +1 -0
  29. package/dist/{chunk-WJL2NJXN.js → chunk-GSH6QNNS.js} +2 -2
  30. package/dist/{chunk-RBNA5AZT.js → chunk-L3JOU6XM.js} +2 -2
  31. package/dist/{chunk-IDVBLYCY.js → chunk-LMZQ2Z4U.js} +56 -2
  32. package/dist/{chunk-IDVBLYCY.js.map → chunk-LMZQ2Z4U.js.map} +1 -1
  33. package/dist/{chunk-VUINJM5M.js → chunk-QAY5UIJO.js} +2 -193
  34. package/dist/chunk-QAY5UIJO.js.map +1 -0
  35. package/dist/{chunk-P2J6SOXT.js → chunk-QG2OVF2D.js} +5 -3
  36. package/dist/{chunk-P2J6SOXT.js.map → chunk-QG2OVF2D.js.map} +1 -1
  37. package/dist/chunk-REVYNR6C.js +100 -0
  38. package/dist/chunk-REVYNR6C.js.map +1 -0
  39. package/dist/chunk-STGVSCDH.js +202 -0
  40. package/dist/chunk-STGVSCDH.js.map +1 -0
  41. package/dist/{chunk-ZZ2HOPME.js → chunk-TWS7AZEY.js} +2 -2
  42. package/dist/chunk-UHMJT4T7.js +200 -0
  43. package/dist/chunk-UHMJT4T7.js.map +1 -0
  44. package/dist/chunk-UMMZHCPB.js +190 -0
  45. package/dist/chunk-UMMZHCPB.js.map +1 -0
  46. package/dist/chunk-VZSRQ272.js +149 -0
  47. package/dist/chunk-VZSRQ272.js.map +1 -0
  48. package/dist/{chunk-L5G7OUKD.js → chunk-XY4DDNEG.js} +8 -190
  49. package/dist/chunk-XY4DDNEG.js.map +1 -0
  50. package/dist/chunk-Y47J2LJ3.js +859 -0
  51. package/dist/chunk-Y47J2LJ3.js.map +1 -0
  52. package/dist/{chunk-BABOZOSN.js → chunk-ZFIBGEOL.js} +3 -3
  53. package/dist/chunk-ZFIBGEOL.js.map +1 -0
  54. package/dist/{code-agent-session-BRXmavYv.d.ts → code-agent-session-BO8nCnv3.d.ts} +1 -1
  55. package/dist/contract/index.d.ts +24 -95
  56. package/dist/contract/index.js +25 -764
  57. package/dist/contract/index.js.map +1 -1
  58. package/dist/{control-GeE8OhpN.d.ts → control-_Qb7skHX.d.ts} +2 -2
  59. package/dist/control.d.ts +5 -5
  60. package/dist/corpus-BoR-041R.d.ts +560 -0
  61. package/dist/cost-ledger-DuSqlw5B.d.ts +113 -0
  62. package/dist/counterfactual-Dwibr5IW.d.ts +85 -0
  63. package/dist/{dataset-B2kL-fSM.d.ts → dataset-BbGkaN2I.d.ts} +1 -1
  64. package/dist/{registry-DrEQ3Luj.d.ts → default-registry-zoGHUQEH.d.ts} +29 -2
  65. package/dist/diagnose.d.ts +251 -0
  66. package/dist/diagnose.js +381 -0
  67. package/dist/diagnose.js.map +1 -0
  68. package/dist/{errors-Dwqw-T_m.d.ts → errors-CzMUYo7b.d.ts} +1 -1
  69. package/dist/{feedback-trajectory-B3rErRsh.d.ts → feedback-trajectory-D9OVLrg9.d.ts} +1 -1
  70. package/dist/fuzz.d.ts +484 -0
  71. package/dist/fuzz.js +613 -0
  72. package/dist/fuzz.js.map +1 -0
  73. package/dist/governance/index.d.ts +4 -4
  74. package/dist/hosted/index.d.ts +6 -6
  75. package/dist/{index-DE3RXAXD.d.ts → index-Bx3gZ8xl.d.ts} +1 -1
  76. package/dist/index.d.ts +718 -455
  77. package/dist/index.js +1604 -793
  78. package/dist/index.js.map +1 -1
  79. package/dist/{insight-report-3ADTfClO.d.ts → insight-report-BBwvOh6x.d.ts} +2 -2
  80. package/dist/{integrity-CJzrpUua.d.ts → integrity-VJ9A7aST.d.ts} +1 -1
  81. package/dist/{judge-calibration-DilmB3Ml.d.ts → judge-calibration-0p2QcWNE.d.ts} +1 -1
  82. package/dist/{kind-factory-CVecZZG_.d.ts → kind-factory-5b7xXXOr.d.ts} +2 -2
  83. package/dist/{llm-client-CuUg2Mn3.d.ts → llm-client-BeEcAokY.d.ts} +1 -1
  84. package/dist/matrix/index.d.ts +2 -2
  85. package/dist/meta-eval/index.d.ts +177 -3
  86. package/dist/meta-eval/index.js +260 -1
  87. package/dist/meta-eval/index.js.map +1 -1
  88. package/dist/{multi-layer-verifier-DlWCXuxL.d.ts → multi-layer-verifier-DUZXrPDA.d.ts} +7 -1
  89. package/dist/multishot/index.d.ts +25 -11
  90. package/dist/multishot/index.js +36 -7
  91. package/dist/multishot/index.js.map +1 -1
  92. package/dist/openapi.json +1 -1
  93. package/dist/perf/index.d.ts +123 -0
  94. package/dist/perf/index.js +18 -0
  95. package/dist/pipelines/index.js +2 -2
  96. package/dist/{agent-profile-D0PBIWlV.d.ts → pre-registration-DELOEJ8v.d.ts} +144 -4
  97. package/dist/{provenance-DPpNIOJD.d.ts → provenance-LnqRT0sS.d.ts} +5 -5
  98. package/dist/{red-team-DW9Ca_tj.d.ts → red-team-BXHil6c8.d.ts} +1 -1
  99. package/dist/{release-report-hlNtD12q.d.ts → release-report-euXIV_Sk.d.ts} +3 -3
  100. package/dist/reporting.d.ts +8 -8
  101. package/dist/reporting.js +3 -3
  102. package/dist/{researcher-BLPHBbNV.d.ts → researcher-DE6Gpnb4.d.ts} +4 -4
  103. package/dist/rl.d.ts +194 -656
  104. package/dist/rl.js +231 -149
  105. package/dist/rl.js.map +1 -1
  106. package/dist/{rubric-predictive-validity-CnEl9Jc8.d.ts → rubric-predictive-validity-Cy_W-hWZ.d.ts} +1 -1
  107. package/dist/{run-campaign-4Y5V5CN3.js → run-campaign-RDGAM5KJ.js} +3 -3
  108. package/dist/run-campaign-RDGAM5KJ.js.map +1 -0
  109. package/dist/{run-improvement-loop-CNqQckTj.d.ts → run-improvement-loop-5z_l5zDz.d.ts} +2 -2
  110. package/dist/{run-record-De9VarXR.d.ts → run-record-e7vj1uZQ.d.ts} +1 -1
  111. package/dist/{runtime-trajectory-BLRiaifm.d.ts → runtime-trajectory-BDgfGZSr.d.ts} +1 -1
  112. package/dist/{semantic-concept-judge-DIEgr_6v.d.ts → semantic-concept-judge-Dn8Z6KEG.d.ts} +5 -31
  113. package/dist/series-convergence-D5OWMBg6.d.ts +33 -0
  114. package/dist/{statistics-CnC1FMbx.d.ts → statistics-C7PozGrZ.d.ts} +71 -2
  115. package/dist/{summary-report-Db0dDSWP.d.ts → summary-report-DGmUucwQ.d.ts} +1 -1
  116. package/dist/traces.d.ts +3 -3
  117. package/dist/traces.js +8 -6
  118. package/dist/{types-Cu3u_x59.d.ts → types-2VVIL04s.d.ts} +2 -2
  119. package/dist/{types-D7lLRYe9.d.ts → types-BU-7W85F.d.ts} +21 -1
  120. package/dist/{types-CqPax19X.d.ts → types-mn5Aqk7x.d.ts} +1 -1
  121. package/dist/{verdict-CeEgtjyI.d.ts → verdict-C9MlYujm.d.ts} +3 -0
  122. package/dist/wire/index.d.ts +3 -3
  123. package/dist/workflow/index.d.ts +12 -11
  124. package/dist/workflow/index.js +1 -1
  125. package/package.json +16 -1
  126. package/dist/chunk-BABOZOSN.js.map +0 -1
  127. package/dist/chunk-L5G7OUKD.js.map +0 -1
  128. package/dist/chunk-SHTXZ4O2.js +0 -113
  129. package/dist/chunk-SHTXZ4O2.js.map +0 -1
  130. package/dist/chunk-VIDQF3F5.js.map +0 -1
  131. package/dist/chunk-VUINJM5M.js.map +0 -1
  132. package/dist/chunk-YGYXHNAQ.js.map +0 -1
  133. package/dist/chunk-YV7J7X5N.js.map +0 -1
  134. /package/dist/{chunk-FZWAFVAA.js.map → chunk-4FBZZIYD.js.map} +0 -0
  135. /package/dist/{chunk-OTYQPHPL.js.map → chunk-6SOJM3VR.js.map} +0 -0
  136. /package/dist/{chunk-Z7VFTS2J.js.map → chunk-CY6U5S3X.js.map} +0 -0
  137. /package/dist/{chunk-WJL2NJXN.js.map → chunk-GSH6QNNS.js.map} +0 -0
  138. /package/dist/{chunk-RBNA5AZT.js.map → chunk-L3JOU6XM.js.map} +0 -0
  139. /package/dist/{chunk-ZZ2HOPME.js.map → chunk-TWS7AZEY.js.map} +0 -0
  140. /package/dist/{run-campaign-4Y5V5CN3.js.map → perf/index.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import { G as GainDistributionBin, P as ParetoFigureSpec } from './summary-report-Db0dDSWP.js';
2
- import { a as ContinuousAgreement } from './judge-calibration-DilmB3Ml.js';
1
+ import { G as GainDistributionBin, P as ParetoFigureSpec } from './summary-report-DGmUucwQ.js';
2
+ import { C as ContinuousAgreement } from './judge-calibration-0p2QcWNE.js';
3
3
 
4
4
  /**
5
5
  * # InsightReport — the rigorous decision packet for any set of agent runs.
@@ -1,4 +1,4 @@
1
- import { C as CaptureIntegrityError } from './errors-Dwqw-T_m.js';
1
+ import { C as CaptureIntegrityError } from './errors-CzMUYo7b.js';
2
2
  import { R as RawProviderSink } from './raw-provider-sink-C46HDghv.js';
3
3
  import { T as TraceStore } from './store-CKUAgsJz.js';
4
4
 
@@ -139,4 +139,4 @@ interface ContinuousCalibrationResult extends CalibrationResult {
139
139
  */
140
140
  declare function calibrateJudgeContinuous(golden: GoldenItem[], candidate: CandidateScore[], opts?: ContinuousAgreementOptions): ContinuousCalibrationResult;
141
141
 
142
- export { type ContinuousAgreementOptions as C, type GoldenItem as G, type PositionalBiasResult as P, type SelfPreferenceResult as S, type VerbosityBiasResult as V, type ContinuousAgreement as a, type CalibrationResult as b, type CandidateScore as c, type ContinuousCalibrationResult as d, calibrateJudge as e, calibrateJudgeContinuous as f, continuousAgreement as g, positionalBias as p, selfPreference as s, verbosityBias as v };
142
+ export { type ContinuousAgreement as C, type GoldenItem as G, type PositionalBiasResult as P, type SelfPreferenceResult as S, type VerbosityBiasResult as V, type CalibrationResult as a, type ContinuousCalibrationResult as b, type CandidateScore as c, type ContinuousAgreementOptions as d, calibrateJudge as e, calibrateJudgeContinuous as f, continuousAgreement as g, positionalBias as p, selfPreference as s, verbosityBias as v };
@@ -1,7 +1,7 @@
1
1
  import { AxAIService, AxFunction } from '@ax-llm/ax';
2
2
  import { T as TraceAnalysisStore } from './store-C1YxJDEK.js';
3
3
  import { z } from 'zod';
4
- import { g as AnalystCost, a as AnalystContext, A as Analyst } from './types-Cu3u_x59.js';
4
+ import { g as AnalystCost, a as AnalystContext, A as Analyst } from './types-2VVIL04s.js';
5
5
 
6
6
  /**
7
7
  * Typed Ax output for analyst findings.
@@ -169,4 +169,4 @@ declare function createTraceAnalystKind(spec: TraceAnalystKindSpec, opts: Create
169
169
  */
170
170
  declare function renderPriorFindings(prior: AnalystContext['priorFindings']): string;
171
171
 
172
- export { ANALYST_SEVERITIES as A, type CreateTraceAnalystKindOpts as C, RAW_FINDING_SCHEMA_PROMPT as R, type TraceAnalystGolden as T, type RawAnalystFinding as a, RawAnalystFindingSchema as b, type TraceAnalystKindSpec as c, createTraceAnalystKind as d, parseRawFinding as p, renderPriorFindings as r };
172
+ export { ANALYST_SEVERITIES as A, type CreateTraceAnalystKindOpts as C, RAW_FINDING_SCHEMA_PROMPT as R, type TraceAnalystKindSpec as T, type RawAnalystFinding as a, RawAnalystFindingSchema as b, type TraceAnalystGolden as c, createTraceAnalystKind as d, parseRawFinding as p, renderPriorFindings as r };
@@ -1,4 +1,4 @@
1
- import { A as AgentEvalError, C as CaptureIntegrityError } from './errors-Dwqw-T_m.js';
1
+ import { A as AgentEvalError, C as CaptureIntegrityError } from './errors-CzMUYo7b.js';
2
2
  import { R as RawProviderSink, P as ProviderRedactor } from './raw-provider-sink-C46HDghv.js';
3
3
 
4
4
  /**
@@ -1,5 +1,5 @@
1
- import { M as MatrixResult, a as MatrixAxis, A as AxisSummary, b as MatrixCell, C as CellResult, R as RunAgentMatrixOptions } from '../types-CqPax19X.js';
2
- export { D as DefaultVerdict } from '../verdict-CeEgtjyI.js';
1
+ import { M as MatrixResult, a as MatrixAxis, A as AxisSummary, b as MatrixCell, C as CellResult, R as RunAgentMatrixOptions } from '../types-mn5Aqk7x.js';
2
+ export { D as DefaultVerdict } from '../verdict-C9MlYujm.js';
3
3
 
4
4
  /**
5
5
  * Per-axis aggregation of cell runs into `AxisSummary` rows.
@@ -1,7 +1,181 @@
1
1
  export { C as CalibrationBin, a as CalibrationOptions, b as CalibrationPair, c as CalibrationReport, d as CorrelationResult, e as CorrelationStudyOptions, f as CorrelationStudyResult, E as EvalMetricSpec, O as OutcomePair, g as calibrationCurve, h as calibrationFromPairs, i as correlationStudy } from '../calibration-Cpr3WaX3.js';
2
2
  export { D as DeploymentOutcome, F as FileSystemOutcomeStore, a as FileSystemOutcomeStoreOptions, I as InMemoryOutcomeStore, O as OutcomeFilter, b as OutcomeStore } from '../outcome-store-rnXLEqSn.js';
3
- export { R as RubricOutcomePair, a as RubricPredictiveValidityInput, b as RubricPredictiveValidityReport, c as RubricRanking, r as rubricPredictiveValidity } from '../rubric-predictive-validity-CnEl9Jc8.js';
3
+ export { R as RubricOutcomePair, a as RubricPredictiveValidityInput, b as RubricPredictiveValidityReport, c as RubricRanking, r as rubricPredictiveValidity } from '../rubric-predictive-validity-Cy_W-hWZ.js';
4
+ import { C as ContinuousAgreement, a as CalibrationResult, b as ContinuousCalibrationResult, c as CandidateScore, G as GoldenItem } from '../judge-calibration-0p2QcWNE.js';
5
+ import { S as SeriesConvergenceOptions, a as SeriesConvergenceResult } from '../series-convergence-D5OWMBg6.js';
6
+ import { C as CorpusAgreementReport } from '../statistics-C7PozGrZ.js';
4
7
  import '../store-CKUAgsJz.js';
5
8
  import '../schema-m0gsnbt3.js';
6
- import '../run-record-De9VarXR.js';
7
- import '../errors-Dwqw-T_m.js';
9
+ import '../run-record-e7vj1uZQ.js';
10
+ import '../errors-CzMUYo7b.js';
11
+ import '../types-Croy5h7V.js';
12
+ import '@tangle-network/tcloud';
13
+
14
+ /**
15
+ * Judge sentinel — eval trustworthiness as a continuously measured,
16
+ * alarmed trend.
17
+ *
18
+ * Judges are models; models change underneath us; calibration decays.
19
+ * This module composes three existing instruments into one loop:
20
+ *
21
+ * snapshot — adapters turn real instrument outputs (`calibrateJudge` /
22
+ * `calibrateJudgeContinuous`, `corpusInterRaterAgreement` /
23
+ * `continuousAgreement`, a rerun sentinel golden set) into
24
+ * `SentinelSnapshot`s
25
+ * series — `analyzeSeries` (src/series-convergence) classifies each
26
+ * judge×metric history as stabilized / drifting / noisy
27
+ * alarm — `judgeSentinelReport` turns trends + thresholds into named
28
+ * alarms; `evalHealthStamp` is the tiny object a campaign
29
+ * attaches to its verdicts
30
+ *
31
+ * Alarm conditions:
32
+ * - convergence state `drifting-down` on any tracked metric
33
+ * - irr below `minIrr`
34
+ * - calibrationKappa / sentinelPassRate dropped vs the series baseline
35
+ * beyond `maxKappaDrop` / `maxSentinelDrop`
36
+ * - judge model changed with no post-change golden-grounded snapshot
37
+ * (the silent-upgrade trap: judges agreeing with each other after a
38
+ * model swap proves nothing — only re-measuring against gold does)
39
+ * - newest snapshot older than `staleAfterDays` relative to `asOf`
40
+ *
41
+ * Wire-in: run the snapshot adapters from a post-campaign hook or a
42
+ * nightly job, append to a `SentinelStore`, then compute
43
+ * `judgeSentinelReport(await store.history(), { asOf })` with `asOf` =
44
+ * the campaign timestamp. Attach `evalHealthStamp(report)` to campaign
45
+ * verdicts: an alarmed sentinel means every downstream verdict carries
46
+ * an integrity warning until the judge is recalibrated.
47
+ *
48
+ * The module is clock-free — every timestamp (`at`, `asOf`) is
49
+ * caller-supplied ISO-8601, so reports are reproducible.
50
+ */
51
+
52
+ declare const SENTINEL_METRIC_NAMES: readonly ["irr", "calibrationKappa", "sentinelPassRate"];
53
+ type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number];
54
+ interface SentinelMetrics {
55
+ /** Inter-rater reliability — ICC(2,1) from agreement instruments. */
56
+ irr?: number;
57
+ /** Weighted κ vs the human golden set (`calibrateJudge*`). */
58
+ calibrationKappa?: number;
59
+ /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */
60
+ sentinelPassRate?: number;
61
+ }
62
+ interface SentinelSnapshot {
63
+ /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */
64
+ at: string;
65
+ judgeId: string;
66
+ /** Exact model identity behind the judge (pin the full version string). */
67
+ judgeModel: string;
68
+ /**
69
+ * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a
70
+ * model-change marker — it records the new `judgeModel` immediately and
71
+ * the silent-upgrade alarm stays raised until a golden-grounded snapshot
72
+ * (calibrationKappa or sentinelPassRate) follows.
73
+ */
74
+ metrics: SentinelMetrics;
75
+ }
76
+ /** Identity + timestamp the caller supplies alongside an instrument output. */
77
+ interface SnapshotMeta {
78
+ at: string;
79
+ judgeId: string;
80
+ judgeModel: string;
81
+ }
82
+ /** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */
83
+ declare function validateSentinelSnapshot(snapshot: SentinelSnapshot, source?: string): void;
84
+ /**
85
+ * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the
86
+ * un-rounded continuous κ_w when the report carries one (integer κ
87
+ * discards information for [0,1] judges).
88
+ */
89
+ declare function snapshotFromCalibration(report: CalibrationResult | ContinuousCalibrationResult, meta: SnapshotMeta): SentinelSnapshot;
90
+ /**
91
+ * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`
92
+ * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability
93
+ * coefficient both instruments compute. For ensemble-level agreement,
94
+ * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its
95
+ * composition (e.g. a joined list of member model strings).
96
+ */
97
+ declare function snapshotFromAgreement(report: CorpusAgreementReport | ContinuousAgreement, meta: SnapshotMeta): SentinelSnapshot;
98
+ interface SentinelSetOptions {
99
+ /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */
100
+ tolerance?: number;
101
+ }
102
+ /**
103
+ * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the
104
+ * judge was originally calibrated on, re-scored periodically. Pass rate =
105
+ * fraction of joined items where the judge stays within `tolerance` of the
106
+ * human score. Items the judge didn't score are excluded from the
107
+ * denominator; zero joined items is an error, not a 0% pass rate.
108
+ */
109
+ declare function snapshotFromSentinelSet(scores: CandidateScore[], golden: GoldenItem[], meta: SnapshotMeta, options?: SentinelSetOptions): SentinelSnapshot;
110
+ interface SentinelStore {
111
+ append(snapshot: SentinelSnapshot): Promise<void>;
112
+ /** All snapshots (optionally for one judge), in append order. */
113
+ history(judgeId?: string): Promise<SentinelSnapshot[]>;
114
+ }
115
+ declare function inMemorySentinelStore(initial?: SentinelSnapshot[]): SentinelStore;
116
+ /**
117
+ * JSONL store — one snapshot per line, appended atomically per call.
118
+ * A corrupt or shape-invalid line is a loud error naming the file and
119
+ * line number: a sentinel history that silently drops records would
120
+ * defeat the drift detection it exists to provide.
121
+ */
122
+ declare function fileSentinelStore(path: string): SentinelStore;
123
+ interface SentinelThresholds {
124
+ /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */
125
+ minIrr?: number;
126
+ /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */
127
+ maxKappaDrop?: number;
128
+ /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */
129
+ maxSentinelDrop?: number;
130
+ /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */
131
+ staleAfterDays?: number;
132
+ }
133
+ interface JudgeSentinelOptions {
134
+ /** Caller-supplied ISO timestamp staleness is measured against. */
135
+ asOf: string;
136
+ thresholds?: SentinelThresholds;
137
+ /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */
138
+ convergence?: SeriesConvergenceOptions;
139
+ }
140
+ interface SentinelTrend {
141
+ judgeId: string;
142
+ metric: SentinelMetricName;
143
+ /** Verbatim `analyzeSeries` state for this judge×metric history. */
144
+ state: SeriesConvergenceResult['state'];
145
+ /** Newest value in the series. */
146
+ current: number;
147
+ /** Oldest value in the series — the reference the drop thresholds compare against. */
148
+ baseline: number;
149
+ /** current − baseline (signed; negative = decayed). */
150
+ drift: number;
151
+ alarmed: boolean;
152
+ reason?: string;
153
+ }
154
+ interface SentinelReport {
155
+ perJudge: SentinelTrend[];
156
+ alarms: string[];
157
+ healthy: boolean;
158
+ /**
159
+ * `judgeId:metric` pairs with too few snapshots for the convergence
160
+ * machine. Named, not counted — a blind spot you can't see is a blind
161
+ * spot you won't fix. Floor/drop checks still apply to thin series, so
162
+ * insufficient history alone never masks an alarm.
163
+ */
164
+ insufficientHistory: string[];
165
+ }
166
+ declare function judgeSentinelReport(history: SentinelSnapshot[], opts: JudgeSentinelOptions): SentinelReport;
167
+ interface EvalHealthStamp {
168
+ healthy: boolean;
169
+ alarms: string[];
170
+ }
171
+ /**
172
+ * The object a campaign attaches to its verdicts. Compute it from the
173
+ * sentinel report in a post-campaign hook (or a nightly job feeding the
174
+ * next day's campaigns) and store it alongside the verdict payload.
175
+ * `healthy: false` means the judges that produced those verdicts have an
176
+ * unresolved drift / decay / silent-upgrade / staleness alarm — treat the
177
+ * verdicts as carrying an integrity warning until recalibration clears it.
178
+ */
179
+ declare function evalHealthStamp(report: SentinelReport): EvalHealthStamp;
180
+
181
+ export { type EvalHealthStamp, type JudgeSentinelOptions, SENTINEL_METRIC_NAMES, type SentinelMetricName, type SentinelMetrics, type SentinelReport, type SentinelSetOptions, type SentinelSnapshot, type SentinelStore, type SentinelThresholds, type SentinelTrend, type SnapshotMeta, evalHealthStamp, fileSentinelStore, inMemorySentinelStore, judgeSentinelReport, snapshotFromAgreement, snapshotFromCalibration, snapshotFromSentinelSet, validateSentinelSnapshot };
@@ -2,6 +2,9 @@ import {
2
2
  calibrationCurve,
3
3
  calibrationFromPairs
4
4
  } from "../chunk-NPCTHQIO.js";
5
+ import {
6
+ analyzeSeries
7
+ } from "../chunk-BOD4O7OF.js";
5
8
  import {
6
9
  FileSystemOutcomeStore,
7
10
  InMemoryOutcomeStore
@@ -14,6 +17,9 @@ import {
14
17
  llmSpans
15
18
  } from "../chunk-47X6LRCE.js";
16
19
  import "../chunk-5BKGXME7.js";
20
+ import {
21
+ ValidationError
22
+ } from "../chunk-3BFEG2F6.js";
17
23
  import "../chunk-PZ5AY32C.js";
18
24
 
19
25
  // src/meta-eval/correlation-study.ts
@@ -169,12 +175,265 @@ function defaultExtract(metric) {
169
175
  }
170
176
  };
171
177
  }
178
+
179
+ // src/meta-eval/sentinel.ts
180
+ var SENTINEL_METRIC_NAMES = ["irr", "calibrationKappa", "sentinelPassRate"];
181
+ function parseIso(value, label) {
182
+ const ms = typeof value === "string" ? Date.parse(value) : NaN;
183
+ if (!Number.isFinite(ms)) {
184
+ throw new ValidationError(
185
+ `judge-sentinel: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`
186
+ );
187
+ }
188
+ return ms;
189
+ }
190
+ function validateSentinelSnapshot(snapshot, source = "snapshot") {
191
+ parseIso(snapshot.at, `${source}.at`);
192
+ if (typeof snapshot.judgeId !== "string" || snapshot.judgeId.length === 0) {
193
+ throw new ValidationError(`judge-sentinel: ${source}.judgeId must be a non-empty string`);
194
+ }
195
+ if (typeof snapshot.judgeModel !== "string" || snapshot.judgeModel.length === 0) {
196
+ throw new ValidationError(`judge-sentinel: ${source}.judgeModel must be a non-empty string`);
197
+ }
198
+ if (snapshot.metrics === null || typeof snapshot.metrics !== "object") {
199
+ throw new ValidationError(`judge-sentinel: ${source}.metrics must be an object (may be empty)`);
200
+ }
201
+ for (const [key, value] of Object.entries(snapshot.metrics)) {
202
+ if (!SENTINEL_METRIC_NAMES.includes(key)) {
203
+ throw new ValidationError(
204
+ `judge-sentinel: ${source}.metrics carries unknown key "${key}" \u2014 known: ${SENTINEL_METRIC_NAMES.join(", ")}`
205
+ );
206
+ }
207
+ if (value !== void 0 && !Number.isFinite(value)) {
208
+ throw new ValidationError(
209
+ `judge-sentinel: ${source}.metrics.${key} is not a finite number: ${String(value)}`
210
+ );
211
+ }
212
+ }
213
+ }
214
+ function snapshotFromCalibration(report, meta) {
215
+ const kappa = "weightedKappaContinuous" in report ? report.weightedKappaContinuous : report.kappa;
216
+ if (!Number.isFinite(kappa)) {
217
+ throw new ValidationError(
218
+ `snapshotFromCalibration: \u03BA is not finite (n=${report.n}) \u2014 calibrate against \u22652 joined golden items before snapshotting`
219
+ );
220
+ }
221
+ const snapshot = { ...meta, metrics: { calibrationKappa: kappa } };
222
+ validateSentinelSnapshot(snapshot);
223
+ return snapshot;
224
+ }
225
+ function snapshotFromAgreement(report, meta) {
226
+ const irr = "overallIcc" in report ? report.overallIcc : report.icc;
227
+ if (!Number.isFinite(irr)) {
228
+ throw new ValidationError(
229
+ "snapshotFromAgreement: ICC is not finite \u2014 agreement needs \u22652 raters and \u22652 complete items"
230
+ );
231
+ }
232
+ const snapshot = { ...meta, metrics: { irr } };
233
+ validateSentinelSnapshot(snapshot);
234
+ return snapshot;
235
+ }
236
+ function snapshotFromSentinelSet(scores, golden, meta, options = {}) {
237
+ const tolerance = options.tolerance ?? 0.1;
238
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
239
+ throw new ValidationError(
240
+ `snapshotFromSentinelSet: tolerance must be a finite number \u2265 0, got ${tolerance}`
241
+ );
242
+ }
243
+ const goldenById = /* @__PURE__ */ new Map();
244
+ for (const item of golden) {
245
+ if (!Number.isFinite(item.humanScore)) {
246
+ throw new ValidationError(
247
+ `snapshotFromSentinelSet: golden item "${item.itemId}" has a non-finite humanScore`
248
+ );
249
+ }
250
+ if (goldenById.has(item.itemId)) {
251
+ throw new ValidationError(`snapshotFromSentinelSet: duplicate golden itemId "${item.itemId}"`);
252
+ }
253
+ goldenById.set(item.itemId, item.humanScore);
254
+ }
255
+ let joined = 0;
256
+ let passed = 0;
257
+ for (const s of scores) {
258
+ const human = goldenById.get(s.itemId);
259
+ if (human === void 0) continue;
260
+ if (!Number.isFinite(s.score)) {
261
+ throw new ValidationError(
262
+ `snapshotFromSentinelSet: judge score for item "${s.itemId}" is not finite`
263
+ );
264
+ }
265
+ joined++;
266
+ if (Math.abs(s.score - human) <= tolerance) passed++;
267
+ }
268
+ if (joined === 0) {
269
+ throw new ValidationError(
270
+ "snapshotFromSentinelSet: no judge scores joined the golden set \u2014 itemIds mismatch or empty sentinel run"
271
+ );
272
+ }
273
+ const snapshot = { ...meta, metrics: { sentinelPassRate: passed / joined } };
274
+ validateSentinelSnapshot(snapshot);
275
+ return snapshot;
276
+ }
277
+ function inMemorySentinelStore(initial = []) {
278
+ for (const s of initial) validateSentinelSnapshot(s);
279
+ const items = initial.map((s) => ({ ...s, metrics: { ...s.metrics } }));
280
+ return {
281
+ async append(snapshot) {
282
+ validateSentinelSnapshot(snapshot);
283
+ items.push({ ...snapshot, metrics: { ...snapshot.metrics } });
284
+ },
285
+ async history(judgeId) {
286
+ const all = items.map((s) => ({ ...s, metrics: { ...s.metrics } }));
287
+ return judgeId === void 0 ? all : all.filter((s) => s.judgeId === judgeId);
288
+ }
289
+ };
290
+ }
291
+ function fileSentinelStore(path) {
292
+ return {
293
+ async append(snapshot) {
294
+ validateSentinelSnapshot(snapshot);
295
+ const fs = await import("fs/promises");
296
+ const pathMod = await import("path");
297
+ await fs.mkdir(pathMod.dirname(path), { recursive: true });
298
+ await fs.appendFile(path, `${JSON.stringify(snapshot)}
299
+ `, "utf8");
300
+ },
301
+ async history(judgeId) {
302
+ const fs = await import("fs/promises");
303
+ let raw;
304
+ try {
305
+ raw = await fs.readFile(path, "utf8");
306
+ } catch (err) {
307
+ if (err.code === "ENOENT") return [];
308
+ throw err;
309
+ }
310
+ const lines = raw.split("\n");
311
+ const snapshots = [];
312
+ for (let i = 0; i < lines.length; i++) {
313
+ const line = lines[i];
314
+ if (line.trim().length === 0) continue;
315
+ let parsed;
316
+ try {
317
+ parsed = JSON.parse(line);
318
+ } catch (err) {
319
+ throw new ValidationError(
320
+ `judge-sentinel: store at ${path} has a corrupt JSONL line ${i + 1}: ${err.message}`
321
+ );
322
+ }
323
+ const snapshot = parsed;
324
+ validateSentinelSnapshot(snapshot, `${path}:${i + 1}`);
325
+ snapshots.push(snapshot);
326
+ }
327
+ return judgeId === void 0 ? snapshots : snapshots.filter((s) => s.judgeId === judgeId);
328
+ }
329
+ };
330
+ }
331
+ var MS_PER_DAY = 864e5;
332
+ function judgeSentinelReport(history, opts) {
333
+ const asOfMs = parseIso(opts.asOf, "asOf");
334
+ const minIrr = opts.thresholds?.minIrr ?? 0.6;
335
+ const maxKappaDrop = opts.thresholds?.maxKappaDrop ?? 0.15;
336
+ const maxSentinelDrop = opts.thresholds?.maxSentinelDrop ?? 0.1;
337
+ const staleAfterDays = opts.thresholds?.staleAfterDays ?? 30;
338
+ const byJudge = /* @__PURE__ */ new Map();
339
+ for (const snapshot of history) {
340
+ validateSentinelSnapshot(snapshot);
341
+ const atMs = parseIso(snapshot.at, `snapshot.at (judge "${snapshot.judgeId}")`);
342
+ const arr = byJudge.get(snapshot.judgeId) ?? [];
343
+ arr.push({ ...snapshot, atMs });
344
+ byJudge.set(snapshot.judgeId, arr);
345
+ }
346
+ const perJudge = [];
347
+ const alarms = [];
348
+ const insufficientHistory = [];
349
+ for (const judgeId of [...byJudge.keys()].sort()) {
350
+ const snaps = byJudge.get(judgeId).sort((a, b) => a.atMs - b.atMs);
351
+ const newest = snaps[snaps.length - 1];
352
+ const ageDays = (asOfMs - newest.atMs) / MS_PER_DAY;
353
+ if (ageDays > staleAfterDays) {
354
+ alarms.push(
355
+ `judge "${judgeId}": stale \u2014 newest snapshot ${newest.at} is ${ageDays.toFixed(1)}d old vs asOf (limit ${staleAfterDays}d)`
356
+ );
357
+ }
358
+ let changeIdx = -1;
359
+ for (let i = 1; i < snaps.length; i++) {
360
+ if (snaps[i].judgeModel !== snaps[i - 1].judgeModel) changeIdx = i;
361
+ }
362
+ if (changeIdx >= 0) {
363
+ const recalibrated = snaps.slice(changeIdx).some(
364
+ (s) => Number.isFinite(s.metrics.calibrationKappa) || Number.isFinite(s.metrics.sentinelPassRate)
365
+ );
366
+ if (!recalibrated) {
367
+ alarms.push(
368
+ `judge "${judgeId}": model changed "${snaps[changeIdx - 1].judgeModel}" \u2192 "${snaps[changeIdx].judgeModel}" at ${snaps[changeIdx].at} with no post-change calibration snapshot \u2014 silent-upgrade trap; rerun calibrateJudge or the sentinel set against the new model`
369
+ );
370
+ }
371
+ }
372
+ for (const metric of SENTINEL_METRIC_NAMES) {
373
+ const values = snaps.filter((s) => typeof s.metrics[metric] === "number").map((s) => s.metrics[metric]);
374
+ if (values.length === 0) continue;
375
+ const convergence = analyzeSeries(values, opts.convergence);
376
+ if (convergence.state === "insufficient-data")
377
+ insufficientHistory.push(`${judgeId}:${metric}`);
378
+ const current = values[values.length - 1];
379
+ const baseline = values[0];
380
+ const drift = current - baseline;
381
+ const reasons = [];
382
+ if (convergence.state === "drifting-down") {
383
+ reasons.push(
384
+ `convergence state drifting-down (tail run ${convergence.tailRun}, window mean ${convergence.windowMean.toFixed(3)})`
385
+ );
386
+ }
387
+ if (metric === "irr" && current < minIrr) {
388
+ reasons.push(`irr ${current.toFixed(3)} below floor ${minIrr}`);
389
+ }
390
+ if (metric === "calibrationKappa" && baseline - current > maxKappaDrop) {
391
+ reasons.push(
392
+ `calibrationKappa dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxKappaDrop})`
393
+ );
394
+ }
395
+ if (metric === "sentinelPassRate" && baseline - current > maxSentinelDrop) {
396
+ reasons.push(
397
+ `sentinelPassRate dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxSentinelDrop})`
398
+ );
399
+ }
400
+ const alarmed = reasons.length > 0;
401
+ const trend = {
402
+ judgeId,
403
+ metric,
404
+ state: convergence.state,
405
+ current,
406
+ baseline,
407
+ drift,
408
+ alarmed
409
+ };
410
+ if (alarmed) {
411
+ trend.reason = reasons.join("; ");
412
+ alarms.push(`judge "${judgeId}" ${metric}: ${trend.reason}`);
413
+ }
414
+ perJudge.push(trend);
415
+ }
416
+ }
417
+ return { perJudge, alarms, healthy: alarms.length === 0, insufficientHistory };
418
+ }
419
+ function evalHealthStamp(report) {
420
+ return { healthy: report.healthy, alarms: [...report.alarms] };
421
+ }
172
422
  export {
173
423
  FileSystemOutcomeStore,
174
424
  InMemoryOutcomeStore,
425
+ SENTINEL_METRIC_NAMES,
175
426
  calibrationCurve,
176
427
  calibrationFromPairs,
177
428
  correlationStudy,
178
- rubricPredictiveValidity
429
+ evalHealthStamp,
430
+ fileSentinelStore,
431
+ inMemorySentinelStore,
432
+ judgeSentinelReport,
433
+ rubricPredictiveValidity,
434
+ snapshotFromAgreement,
435
+ snapshotFromCalibration,
436
+ snapshotFromSentinelSet,
437
+ validateSentinelSnapshot
179
438
  };
180
439
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/meta-eval/correlation-study.ts"],"sourcesContent":["/**\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 { 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}\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 = pearsonR(ranks(p.xs), ranks(p.ys))\n const pearsonCi95 = bootstrapPearsonCi(p.xs, p.ys, options.bootstrapIterations ?? 500)\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 pearsonR(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length < 2) return NaN\n const mA = a.reduce((s, v) => s + v, 0) / a.length\n const mB = b.reduce((s, v) => s + v, 0) / b.length\n let num = 0,\n dA = 0,\n dB = 0\n for (let i = 0; i < a.length; i++) {\n const da = a[i]! - mA,\n db = b[i]! - mB\n num += da * db\n dA += da * da\n dB += db * db\n }\n if (dA === 0 || dB === 0) return dA === 0 && dB === 0 ? 1 : 0\n return num / Math.sqrt(dA * dB)\n}\n\nfunction ranks(xs: number[]): number[] {\n const indexed = xs.map((v, i) => ({ v, i })).sort((x, y) => x.v - y.v)\n const r = new Array<number>(xs.length)\n for (let i = 0; i < indexed.length; i++) {\n let j = i\n while (j + 1 < indexed.length && indexed[j + 1]!.v === indexed[i]!.v) j++\n const avg = (i + j + 2) / 2\n for (let k = i; k <= j; k++) r[indexed[k]!.i] = avg\n i = j\n }\n return r\n}\n\nfunction bootstrapPearsonCi(\n xs: number[],\n ys: number[],\n iterations: number,\n): { lower: number; upper: number } {\n const n = xs.length\n if (n < 3) return { lower: NaN, upper: NaN }\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(Math.random() * 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"],"mappings":";;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,iBACpB,YACA,cACA,aACA,oBACA,UAAmC,CAAC,GACH;AACjC,QAAM,OAAO,MAAM,WAAW,SAAS;AACvC,QAAM,WAAW,MAAM,aAAa,KAAK,QAAQ,aAAa;AAC9D,QAAM,gBAAgB,oBAAI,IAAiC;AAC3D,aAAW,KAAK,UAAU;AACxB,UAAM,MAAM,cAAc,IAAI,EAAE,KAAK,KAAK,CAAC;AAC3C,QAAI,KAAK,CAAC;AACV,kBAAc,IAAI,EAAE,OAAO,GAAG;AAAA,EA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AO,IAAI,KAAK;AAC3C,eAAO,aAAa,GAAG,EAAE;AAAA,MAC3B;AAAA,MACA,KAAK,eAAe;AAClB,cAAM,MAAM,MAAM,SAAS,OAAO,IAAI,KAAK;AAC3C,eAAO,aAAa,GAAG,EAAE;AAAA,MAC3B;AAAA,MACA;AACE,eAAO;AAAA,IACX;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/meta-eval/correlation-study.ts","../../src/meta-eval/sentinel.ts"],"sourcesContent":["/**\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 { 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}\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 = pearsonR(ranks(p.xs), ranks(p.ys))\n const pearsonCi95 = bootstrapPearsonCi(p.xs, p.ys, options.bootstrapIterations ?? 500)\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 pearsonR(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length < 2) return NaN\n const mA = a.reduce((s, v) => s + v, 0) / a.length\n const mB = b.reduce((s, v) => s + v, 0) / b.length\n let num = 0,\n dA = 0,\n dB = 0\n for (let i = 0; i < a.length; i++) {\n const da = a[i]! - mA,\n db = b[i]! - mB\n num += da * db\n dA += da * da\n dB += db * db\n }\n if (dA === 0 || dB === 0) return dA === 0 && dB === 0 ? 1 : 0\n return num / Math.sqrt(dA * dB)\n}\n\nfunction ranks(xs: number[]): number[] {\n const indexed = xs.map((v, i) => ({ v, i })).sort((x, y) => x.v - y.v)\n const r = new Array<number>(xs.length)\n for (let i = 0; i < indexed.length; i++) {\n let j = i\n while (j + 1 < indexed.length && indexed[j + 1]!.v === indexed[i]!.v) j++\n const avg = (i + j + 2) / 2\n for (let k = i; k <= j; k++) r[indexed[k]!.i] = avg\n i = j\n }\n return r\n}\n\nfunction bootstrapPearsonCi(\n xs: number[],\n ys: number[],\n iterations: number,\n): { lower: number; upper: number } {\n const n = xs.length\n if (n < 3) return { lower: NaN, upper: NaN }\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(Math.random() * 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\nexport const 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":";;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,iBACpB,YACA,cACA,aACA,oBACA,UAAmC,CAAC,GACH;AACjC,QAAM,OAAO,MAAM,WAAW,SAAS;AACvC,QAAM,WAAW,MAAM,aAAa,KAAK,QAAQ,aAAa;AAC9D,QAAM,gBAAgB,oBAAI,IAAiC;AAC3D,aAAW,KAAK,UAAU;AACxB,UAAM,MAAM,cAAc,IAAI,EAAE,KAAK,KAAK,CAAC;AAC3C,QAAI,KAAK,CAAC;AACV,kBAAc,IAAI,EAAE,OAAO,GAAG;AAAA,EAChC;AAEA,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,SAAS,QAAQ,mBAAmB;AAE1C,QAAM,QAA0F,CAAC;AACjG,aAAW,MAAM,aAAa;AAC5B,eAAW,MAAM,oBAAoB;AACnC,YAAM,KAAK,EA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