@tangle-network/agent-eval 0.222.0 → 0.223.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 (80) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/dist/analyst/index.d.ts.map +1 -1
  3. package/dist/analyst/index.js +1 -1
  4. package/dist/{analyze-runs-CTheASYV.js → analyze-runs-Ck68mbgj.js} +7 -9
  5. package/dist/analyze-runs-Ck68mbgj.js.map +1 -0
  6. package/dist/{benchmark-command-jYWR2gya.js → benchmark-command-CH86twZj.js} +32 -37
  7. package/dist/benchmark-command-CH86twZj.js.map +1 -0
  8. package/dist/benchmarks/index.js +3 -3
  9. package/dist/campaign/index.js +9 -9
  10. package/dist/{campaign-ddr1N3yD.js → campaign-DdOgQfp8.js} +14 -19
  11. package/dist/campaign-DdOgQfp8.js.map +1 -0
  12. package/dist/{campaign-evidence-DN8rWuBj.js → campaign-evidence-MjCjkb5a.js} +3 -3
  13. package/dist/{campaign-evidence-DN8rWuBj.js.map → campaign-evidence-MjCjkb5a.js.map} +1 -1
  14. package/dist/cli.js +4 -4
  15. package/dist/contract/index.js +11 -10
  16. package/dist/contract/index.js.map +1 -1
  17. package/dist/{define-agent-eval-BLoP4Lf9.js → define-agent-eval-Cc15qGik.js} +5 -5
  18. package/dist/{define-agent-eval-BLoP4Lf9.js.map → define-agent-eval-Cc15qGik.js.map} +1 -1
  19. package/dist/diagnosis/index.js +1 -1
  20. package/dist/{eval-campaign-Cgixrvf7.js → eval-campaign-C_mNDshv.js} +2 -2
  21. package/dist/{eval-campaign-Cgixrvf7.js.map → eval-campaign-C_mNDshv.js.map} +1 -1
  22. package/dist/experiment/index.js +7 -7
  23. package/dist/index-B7v2QHlD.d.ts.map +1 -1
  24. package/dist/index-DAk2quYu.d.ts.map +1 -1
  25. package/dist/index-aDPVYBIM.d.ts.map +1 -1
  26. package/dist/index.js +13 -12
  27. package/dist/index.js.map +1 -1
  28. package/dist/{judge-gate-C2BCOt-M.js → judge-gate-Di_6bifh.js} +4 -4
  29. package/dist/judge-gate-Di_6bifh.js.map +1 -0
  30. package/dist/{llm-judge-cgbhTKQp.js → llm-judge-D6JtIqiU.js} +9 -9
  31. package/dist/{llm-judge-cgbhTKQp.js.map → llm-judge-D6JtIqiU.js.map} +1 -1
  32. package/dist/mean-BPuUNznQ.js +16 -0
  33. package/dist/mean-BPuUNznQ.js.map +1 -0
  34. package/dist/meta-eval/index.js +1 -1
  35. package/dist/openapi.json +1 -1
  36. package/dist/{paired-arms-D-54hO-k.js → paired-arms-D5H_58e8.js} +2 -2
  37. package/dist/{paired-arms-D-54hO-k.js.map → paired-arms-D5H_58e8.js.map} +1 -1
  38. package/dist/{paired-promotion-decision-FGvHA4p_.js → paired-promotion-decision-BiVumgvM.js} +2 -2
  39. package/dist/{paired-promotion-decision-FGvHA4p_.js.map → paired-promotion-decision-BiVumgvM.js.map} +1 -1
  40. package/dist/{mean-CdDYG-us.js → paired-tests-C2zUqgUW.js} +2 -7
  41. package/dist/paired-tests-C2zUqgUW.js.map +1 -0
  42. package/dist/{pareto-B9udAt2i.js → pareto-7_LEmYGG.js} +4 -3
  43. package/dist/{pareto-B9udAt2i.js.map → pareto-7_LEmYGG.js.map} +1 -1
  44. package/dist/{power-and-mde-ClI6RWw4.js → power-and-mde-CHvyDO_H.js} +2 -2
  45. package/dist/{power-and-mde-ClI6RWw4.js.map → power-and-mde-CHvyDO_H.js.map} +1 -1
  46. package/dist/{promotion-policy-CBYeD4zi.js → promotion-policy-D7B4_jEZ.js} +4 -4
  47. package/dist/{promotion-policy-CBYeD4zi.js.map → promotion-policy-D7B4_jEZ.js.map} +1 -1
  48. package/dist/reporting.js +3 -3
  49. package/dist/{reward-hacking-DZzHZlS1.js → reward-hacking-Bjk3MAjh.js} +7 -9
  50. package/dist/{reward-hacking-DZzHZlS1.js.map → reward-hacking-Bjk3MAjh.js.map} +1 -1
  51. package/dist/reward-hacking-C9hPVT0Q.d.ts.map +1 -1
  52. package/dist/rl.js +6 -6
  53. package/dist/{run-record-CZy4-TnZ.js → run-record-BUm-Jggo.js} +2 -2
  54. package/dist/{run-record-CZy4-TnZ.js.map → run-record-BUm-Jggo.js.map} +1 -1
  55. package/dist/search/index.js +2 -2
  56. package/dist/{search-summary-Ct7SrmVc.js → search-summary-Bt3uuK53.js} +4 -4
  57. package/dist/{search-summary-Ct7SrmVc.js.map → search-summary-Bt3uuK53.js.map} +1 -1
  58. package/dist/{sequential-B1I0tRfL.js → sequential-De7BTAlV.js} +2 -2
  59. package/dist/{sequential-B1I0tRfL.js.map → sequential-De7BTAlV.js.map} +1 -1
  60. package/dist/{skillopt-optimization-method-qB1M554K.js → skillopt-optimization-method-BKFbJEyz.js} +9 -12
  61. package/dist/skillopt-optimization-method-BKFbJEyz.js.map +1 -0
  62. package/dist/{statistical-heldout-TP6ndL0B.js → statistical-heldout-C9hz_AF9.js} +3 -3
  63. package/dist/{statistical-heldout-TP6ndL0B.js.map → statistical-heldout-C9hz_AF9.js.map} +1 -1
  64. package/dist/storyboard/index.d.ts +17 -0
  65. package/dist/storyboard/index.d.ts.map +1 -1
  66. package/dist/storyboard/index.js +154 -107
  67. package/dist/storyboard/index.js.map +1 -1
  68. package/dist/{summary-report-CPfsrLac.js → summary-report-BLnTyQKH.js} +5 -4
  69. package/dist/{summary-report-CPfsrLac.js.map → summary-report-BLnTyQKH.js.map} +1 -1
  70. package/dist/trace-repair/index.js +2 -1
  71. package/dist/trace-repair/index.js.map +1 -1
  72. package/dist/{tree-DrIChF4a.js → tree-DnBkWXun.js} +5 -4
  73. package/dist/{tree-DrIChF4a.js.map → tree-DnBkWXun.js.map} +1 -1
  74. package/package.json +2 -2
  75. package/dist/analyze-runs-CTheASYV.js.map +0 -1
  76. package/dist/benchmark-command-jYWR2gya.js.map +0 -1
  77. package/dist/campaign-ddr1N3yD.js.map +0 -1
  78. package/dist/judge-gate-C2BCOt-M.js.map +0 -1
  79. package/dist/mean-CdDYG-us.js.map +0 -1
  80. package/dist/skillopt-optimization-method-qB1M554K.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"judge-gate-C2BCOt-M.js","names":["parseIso"],"sources":["../src/series-convergence.ts","../src/judge-retry.ts","../src/meta-eval/sentinel.ts","../src/meta-eval/judge-gate.ts"],"sourcesContent":["/**\n * Series convergence — detects whether a sequence of scalar measurements\n * is stabilizing, drifting, or noisy. It reads drift *across* runs, e.g.\n * \"are my nightly eval scores stabilizing?\".\n *\n * Three signals:\n * - stabilized: last K values have low variance (< epsilon) — done\n * - drifting: recent trend is monotonic and beyond noise — regressing or improving\n * - noisy: neither — keep iterating, but flag as untrustworthy for gating\n */\n\nexport interface SeriesConvergenceOptions {\n /** Window size for \"recent\" analysis (default 5). */\n window?: number\n /** Coefficient-of-variation threshold below which the window is stabilized (default 0.05 = 5%). */\n stableCv?: number\n /** Minimum monotone run length to call drift (default 3). */\n driftRun?: number\n}\n\nexport interface SeriesConvergenceResult {\n state: 'stabilized' | 'drifting-up' | 'drifting-down' | 'noisy' | 'insufficient-data'\n windowMean: number\n windowCv: number\n /** Longest monotonic run at the tail of the series (positive for up, negative for down). */\n tailRun: number\n /** True when n ≥ window AND windowCv ≤ stableCv. */\n stable: boolean\n}\n\nexport function analyzeSeries(\n values: number[],\n options: SeriesConvergenceOptions = {},\n): SeriesConvergenceResult {\n const window = options.window ?? 5\n const stableCv = options.stableCv ?? 0.05\n const driftRun = options.driftRun ?? 3\n\n if (values.length < Math.max(2, Math.min(window, 3))) {\n return { state: 'insufficient-data', windowMean: 0, windowCv: 0, tailRun: 0, stable: false }\n }\n\n const tail = values.slice(-window)\n const mean = tail.reduce((a, b) => a + b, 0) / tail.length\n const variance = tail.reduce((acc, v) => acc + (v - mean) ** 2, 0) / tail.length\n const stdDev = Math.sqrt(variance)\n const refMean = Math.abs(mean) > 1e-9 ? Math.abs(mean) : 1\n const cv = stdDev / refMean\n const stable = tail.length >= window && cv <= stableCv\n\n // Tail monotonic run: count how many consecutive strictly-increasing (or decreasing)\n // steps end at the final value.\n let tailRun = 0\n let direction: 1 | -1 | 0 = 0\n for (let i = values.length - 1; i > 0; i--) {\n const delta = values[i]! - values[i - 1]!\n if (delta === 0) break\n const dir = delta > 0 ? 1 : -1\n if (direction === 0) direction = dir\n if (dir !== direction) break\n tailRun += dir\n }\n\n let state: SeriesConvergenceResult['state']\n if (stable) {\n state = 'stabilized'\n } else if (Math.abs(tailRun) >= driftRun) {\n state = tailRun > 0 ? 'drifting-up' : 'drifting-down'\n } else {\n state = 'noisy'\n }\n\n return { state, windowMean: mean, windowCv: cv, tailRun, stable }\n}\n","/**\n * Wrap a single judge LLM call with retry, optional fallback-model\n * rotation, exponential backoff, and a typed `JudgeRetryOutcome`. Callers\n * MUST inspect `succeeded` before using `value`; on failure the library\n * returns `value: null` rather than substituting a default, so a judge\n * abort cannot silently corrupt a downstream composite.\n *\n * Reporting contract: callers ship `TrialResult.judgeSucceeded = succeeded`\n * and `TrialResult.judgeAttempts = attempts` so `aggregateTrialsByMode`\n * with `mode: 'exclude-failed'` drops the trial.\n */\n\nimport { backoffMs, isTransientLlmError } from './llm-client'\n\n/** Retry policy for judge LLM calls. */\nexport interface JudgeRetryPolicy {\n /** Max attempts per model. Default 3 (one initial + two retries). */\n maxAttempts?: number\n /** Per-attempt timeout in ms. Default 300_000. */\n timeoutMs?: number\n /**\n * Models to try, in order. The first model is the primary; subsequent\n * models are fallbacks invoked only when ALL retries on the previous\n * model have been exhausted. Example: `['claude-code/sonnet', 'kimi-code/k2p6']`\n * runs claude-code up to maxAttempts times, then falls back to kimi.\n * If omitted, the caller's judge function controls model selection and\n * the retries apply to that single model.\n */\n models?: readonly string[]\n /** Exponential backoff function, default `attempt → min(500 * 2^attempt, 16_000)`. */\n backoffMs?: (attempt: number) => number\n /**\n * Predicate deciding whether an error should trigger a retry. Defaults to\n * `isTransientLlmError` — the package-wide classifier shared with\n * `callLlm` — which retries aborts/timeouts, network faults, HTTP/2\n * transport faults, and any `LlmCallError` with status in {429,502,503,504}.\n * JSON-parse and schema-rejection errors are NOT retriable (the model\n * needs prompt adjustment, not another shot).\n */\n isRetryable?: (err: unknown) => boolean\n}\n\n/** Outcome of a wrapped judge invocation. */\nexport interface JudgeRetryOutcome<T> {\n /** The judge's returned value when `succeeded === true`. */\n value: T | null\n /** True iff one of the attempts completed without throwing. */\n succeeded: boolean\n /** Total attempts made across all models. */\n attempts: number\n /** Which model the successful attempt used (when succeeded). */\n modelUsed?: string\n /** Last error captured when `succeeded === false`. */\n error?: Error\n /** Per-attempt error log for forensics. */\n attemptErrors: Array<{ attempt: number; model: string; error: string }>\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 3\nconst DEFAULT_TIMEOUT_MS = 300_000\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Wrap a judge call with retry + fallback-model + typed outcome semantics.\n *\n * The `judgeFn` signature is `(model: string, signal: AbortSignal) => Promise<T>`.\n * The signal will be aborted at `timeoutMs`. Callers should pass the signal\n * to their underlying fetch/SDK call so the abort actually fires.\n *\n * Returns a typed outcome — callers MUST inspect `succeeded` before using\n * `value`. The library refuses to default to a silent zero score because a\n * synthetic zero is indistinguishable from a real low score downstream.\n */\nexport async function withJudgeRetry<T>(\n judgeFn: (model: string, signal: AbortSignal) => Promise<T>,\n policy: JudgeRetryPolicy = {},\n): Promise<JudgeRetryOutcome<T>> {\n const maxAttempts = policy.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n const timeoutMs = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const backoff = policy.backoffMs ?? backoffMs\n const isRetryable = policy.isRetryable ?? isTransientLlmError\n const models =\n policy.models && policy.models.length > 0 ? policy.models : [undefined as unknown as string]\n\n let totalAttempts = 0\n const attemptErrors: JudgeRetryOutcome<T>['attemptErrors'] = []\n let lastError: Error | undefined\n\n for (const model of models) {\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n totalAttempts += 1\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(new Error('TimeoutError')), timeoutMs)\n try {\n const value = await judgeFn(model as string, controller.signal)\n clearTimeout(timer)\n return {\n value,\n succeeded: true,\n attempts: totalAttempts,\n modelUsed: model,\n attemptErrors,\n }\n } catch (err) {\n clearTimeout(timer)\n const errObj = err instanceof Error ? err : new Error(String(err))\n lastError = errObj\n attemptErrors.push({\n attempt: totalAttempts,\n model: model ?? '(default)',\n error: errObj.message,\n })\n if (!isRetryable(errObj)) {\n // Non-retriable (e.g., JSON parse, schema rejection): break out of\n // attempts on this model AND skip the fallback rotation — a\n // permanent error here will be permanent on the fallback too.\n return {\n value: null,\n succeeded: false,\n attempts: totalAttempts,\n error: errObj,\n attemptErrors,\n }\n }\n if (attempt < maxAttempts - 1) {\n await sleep(backoff(attempt))\n }\n }\n }\n // Exhausted attempts on this model — fall through to next model in the\n // rotation (if any). The backoff between MODEL rotations is the same\n // as the last per-attempt backoff (already slept above).\n }\n\n return {\n value: null,\n succeeded: false,\n attempts: totalAttempts,\n error: lastError,\n attemptErrors,\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\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","/**\n * Judge calibration gate: a judge may gate only while its measured agreement\n * with its owner's verdicts holds.\n *\n * A judge (a model judge or a deterministic grader) registers a calibration\n * set: items its owner has decided, each verdict with its provenance. A\n * calibration run replays the judge on those items, once or several times, and\n * `measureJudgeAgreement` reports how often it reached the owner's verdict\n * (accuracy, and Cohen's κ for the pass/fail pair), how much its own verdict\n * moves between runs and between samples, and where it disagreed.\n *\n * `judgeGateDecision` turns that report into the one decision a consumer acts\n * on. A judge either decides (`decides: 'verdict'`, the default: it passes and\n * blocks, so it must reach the owner's verdict) or only vetoes\n * (`decides: 'veto'`: a necessary-condition check such as a copy or policy\n * check, which blocks but never passes work on its own; owners also reject\n * for reasons it does not cover, so its error is blocking what they approved).\n * It refuses when the judge has no measured agreement, too few decided\n * items of either verdict, a report measured on a different model or rubric\n * than the one the judge now runs, a report older than the policy allows,\n * agreement below the policy floors, or an alarmed drift history. A refused\n * judge's verdict is advisory: the consumer reports it but does not let it\n * pass or block anything.\n *\n * Drift is the judge sentinel (`./sentinel`): `snapshotFromJudgeAgreement`\n * records accuracy as `sentinelPassRate` and κ as `calibrationKappa`, so each\n * calibration run appends one snapshot to a `SentinelStore` and the gate reads\n * the alarms `judgeSentinelReport` raises over that history.\n *\n * Every timestamp is caller-supplied ISO-8601, so decisions are reproducible.\n */\n\nimport { JudgeError, ValidationError } from '../errors'\nimport { type ComputedInterval, computeInterval } from '../experiment/ast/interval'\nimport {\n judgeSentinelReport,\n type SentinelSnapshot,\n type SentinelThresholds,\n validateSentinelSnapshot,\n} from './sentinel'\n\nexport type OwnerVerdict = 'pass' | 'fail'\n\n/** One item the owner decided, with where that decision is recorded. */\nexport interface CalibrationExample {\n /** Stable id of the decided item; a judge run names it in `exampleId`. */\n id: string\n verdict: OwnerVerdict\n /** The person whose verdict this is. Never a model. */\n labeledBy: string\n /** ISO-8601 time the verdict was given. */\n labeledAt: string\n /** Where the verdict is recorded, e.g. `gtm:asset_decision:<id>`. */\n source: string\n /** What the owner judged (an image digest, a run id), so a replay judges the same thing. */\n evidenceRef?: string\n note?: string\n}\n\nexport interface JudgeCalibrationSet {\n judgeId: string\n /** Whose verdicts the judge stands in for. */\n owner: string\n examples: readonly CalibrationExample[]\n}\n\nfunction parseIso(value: unknown, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : Number.NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-gate: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\nfunction requireText(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`judge-gate: ${label} must be a non-empty string`)\n }\n return value\n}\n\nfunction requireVerdict(value: unknown, label: string): OwnerVerdict {\n if (value !== 'pass' && value !== 'fail') {\n throw new ValidationError(\n `judge-gate: ${label} must be 'pass' or 'fail', got ${JSON.stringify(value)}`,\n )\n }\n return value\n}\n\nfunction checkExample(example: CalibrationExample, label: string): CalibrationExample {\n if (example === null || typeof example !== 'object') {\n throw new ValidationError(`judge-gate: ${label} must be an object`)\n }\n requireText(example.id, `${label}.id`)\n requireVerdict(example.verdict, `${label}.verdict`)\n requireText(example.labeledBy, `${label}.labeledBy`)\n parseIso(example.labeledAt, `${label}.labeledAt`)\n requireText(example.source, `${label}.source`)\n if (example.evidenceRef !== undefined) requireText(example.evidenceRef, `${label}.evidenceRef`)\n const copy: CalibrationExample = {\n id: example.id,\n verdict: example.verdict,\n labeledBy: example.labeledBy,\n labeledAt: example.labeledAt,\n source: example.source,\n }\n if (example.evidenceRef !== undefined) copy.evidenceRef = example.evidenceRef\n if (example.note !== undefined) copy.note = example.note\n return copy\n}\n\n/**\n * Validate a calibration set and return a normalized copy ordered by example\n * id. Every verdict needs its person, time and source; ids are unique.\n */\nexport function registerCalibrationSet(set: JudgeCalibrationSet): JudgeCalibrationSet {\n if (set === null || typeof set !== 'object') {\n throw new ValidationError('judge-gate: calibration set must be an object')\n }\n const judgeId = requireText(set.judgeId, 'calibration set judgeId')\n const owner = requireText(set.owner, `calibration set \"${judgeId}\" owner`)\n if (!Array.isArray(set.examples)) {\n throw new ValidationError(`judge-gate: calibration set \"${judgeId}\" examples must be an array`)\n }\n const seen = new Set<string>()\n const examples = set.examples.map((example, index) => {\n const checked = checkExample(example, `calibration set \"${judgeId}\" example ${index}`)\n if (seen.has(checked.id)) {\n throw new ValidationError(\n `judge-gate: calibration set \"${judgeId}\" has duplicate example id \"${checked.id}\"`,\n )\n }\n seen.add(checked.id)\n return checked\n })\n examples.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n return { judgeId, owner, examples }\n}\n\nexport interface CalibrationMerge {\n set: JudgeCalibrationSet\n /** Ids that joined the set. */\n added: string[]\n /** Ids whose verdict a later decision replaced. */\n superseded: string[]\n /** Ids whose incoming verdict was already recorded, or older than the recorded one. */\n unchanged: string[]\n}\n\n/**\n * Join new owner verdicts to a set. A verdict already recorded from the same\n * source is unchanged, so ingestion can rerun. A later verdict on an item\n * replaces an earlier one: the owner changed their mind, and the set keeps\n * what they decided last.\n */\nexport function addCalibrationVerdicts(\n set: JudgeCalibrationSet,\n verdicts: readonly CalibrationExample[],\n): CalibrationMerge {\n const base = registerCalibrationSet(set)\n const byId = new Map(base.examples.map((example) => [example.id, example]))\n const added: string[] = []\n const superseded: string[] = []\n const unchanged: string[] = []\n for (const [index, verdict] of verdicts.entries()) {\n const incoming = checkExample(verdict, `incoming verdict ${index} for \"${base.judgeId}\"`)\n const current = byId.get(incoming.id)\n if (!current) {\n byId.set(incoming.id, incoming)\n added.push(incoming.id)\n continue\n }\n const sameDecision = current.source === incoming.source && current.verdict === incoming.verdict\n if (\n sameDecision ||\n parseIso(incoming.labeledAt, 'labeledAt') <= parseIso(current.labeledAt, 'labeledAt')\n ) {\n unchanged.push(incoming.id)\n continue\n }\n byId.set(incoming.id, incoming)\n superseded.push(incoming.id)\n }\n return {\n set: registerCalibrationSet({ ...base, examples: [...byId.values()] }),\n added,\n superseded,\n unchanged,\n }\n}\n\n/** One gate decision the judge made on a calibration example. */\nexport interface JudgeRun {\n exampleId: string\n /** The judge's decision after its own sample aggregation (median, majority). */\n verdict: OwnerVerdict\n /** The per-sample verdicts behind that decision, when the judge samples. */\n samples?: readonly OwnerVerdict[]\n}\n\nexport interface JudgeRunMeta {\n judgeId: string\n /** Exact model identity, or `deterministic` for a grader without one. */\n judgeModel: string\n rubricVersion: string\n measuredAt: string\n}\n\nexport interface JudgeConfusion {\n /** Judge pass, owner pass. */\n truePass: number\n /** Judge fail, owner fail. */\n trueFail: number\n /** Judge pass, owner fail: the judge let through what the owner rejected. */\n falsePass: number\n /** Judge fail, owner pass: the judge blocked what the owner accepted. */\n falseFail: number\n}\n\nexport interface JudgeExampleAgreement {\n id: string\n verdict: OwnerVerdict\n runs: number\n /** Share of runs that passed. */\n passRate: number\n /** Share of runs that reached the owner's verdict. */\n agreement: number\n}\n\nexport interface JudgeAgreement extends JudgeRunMeta {\n owner: string\n /** Examples in the calibration set. */\n examples: number\n /** Examples the judge ran on at least once. */\n judged: number\n /** Judged examples per owner verdict. */\n judgedByVerdict: Record<OwnerVerdict, number>\n runs: number\n /** Runs that reached the owner's verdict, over all runs; null with no runs. */\n accuracy: number | null\n /**\n * Exact (Clopper-Pearson) 95% interval for the share of judged examples on\n * which every run reached the owner's verdict. Examples, not runs, are the\n * independent units.\n */\n exampleAccuracy: { agreed: number; judged: number; interval: ComputedInterval } | null\n /**\n * Cohen's κ between the judge and the owner over runs. Null when undefined:\n * no runs, or both sides used a single verdict.\n */\n kappa: number | null\n /** Runs that failed what the owner passed, over runs on owner passes; null with none. A veto judge is held to this. */\n falseFailRate: number | null\n /** Runs that failed what the owner failed, over runs on owner fails; null with none. */\n catchRate: number | null\n confusion: JudgeConfusion\n variance: {\n /** Mean over judged examples of p(1 − p), p the example's run pass rate. 0 = no run changed its mind. */\n betweenRuns: number | null\n /** Mean over runs that reported samples of p(1 − p) across those samples; null when none did. */\n withinRun: number | null\n /** Examples whose runs disagree with each other. */\n unstable: string[]\n }\n /** Examples with at least one run against the owner, least agreement first. */\n disagreements: JudgeExampleAgreement[]\n /** Examples without any run. */\n unjudged: string[]\n}\n\nfunction bernoulliVariance(passes: number, n: number): number {\n const p = passes / n\n return p * (1 - p)\n}\n\n/** Cohen's κ for two raters over a binary pass/fail table. */\nfunction binaryKappa(confusion: JudgeConfusion): number | null {\n const n = confusion.truePass + confusion.trueFail + confusion.falsePass + confusion.falseFail\n if (n === 0) return null\n const observed = (confusion.truePass + confusion.trueFail) / n\n const judgePass = (confusion.truePass + confusion.falsePass) / n\n const ownerPass = (confusion.truePass + confusion.falseFail) / n\n const expected = judgePass * ownerPass + (1 - judgePass) * (1 - ownerPass)\n if (expected === 1) return null\n return (observed - expected) / (1 - expected)\n}\n\n/**\n * Agreement between a judge's runs and the owner's verdicts on one\n * calibration set. A run that names an example outside the set is an error:\n * a silently dropped run would overstate agreement.\n */\nexport function measureJudgeAgreement(\n set: JudgeCalibrationSet,\n runs: readonly JudgeRun[],\n meta: JudgeRunMeta,\n): JudgeAgreement {\n const registered = registerCalibrationSet(set)\n if (meta.judgeId !== registered.judgeId) {\n throw new ValidationError(\n `judge-gate: runs are for judge \"${meta.judgeId}\" but the set belongs to \"${registered.judgeId}\"`,\n )\n }\n requireText(meta.judgeModel, 'judgeModel')\n requireText(meta.rubricVersion, 'rubricVersion')\n parseIso(meta.measuredAt, 'measuredAt')\n const byId = new Map(registered.examples.map((example) => [example.id, example]))\n const runsById = new Map<string, JudgeRun[]>()\n const confusion: JudgeConfusion = { truePass: 0, trueFail: 0, falsePass: 0, falseFail: 0 }\n const withinRun: number[] = []\n for (const [index, run] of runs.entries()) {\n const example = byId.get(run?.exampleId)\n if (!example) {\n throw new ValidationError(\n `judge-gate: run ${index} names example ${JSON.stringify(run?.exampleId)}, which is not in \"${registered.judgeId}\"'s calibration set`,\n )\n }\n const verdict = requireVerdict(run.verdict, `run ${index} verdict`)\n if (run.samples !== undefined) {\n if (!Array.isArray(run.samples) || run.samples.length === 0) {\n throw new ValidationError(`judge-gate: run ${index} samples must be a non-empty array`)\n }\n const samples = run.samples.map((sample, s) =>\n requireVerdict(sample, `run ${index} sample ${s}`),\n )\n withinRun.push(\n bernoulliVariance(samples.filter((sample) => sample === 'pass').length, samples.length),\n )\n }\n const list = runsById.get(example.id) ?? []\n list.push({ ...run, verdict })\n runsById.set(example.id, list)\n if (verdict === 'pass') {\n if (example.verdict === 'pass') confusion.truePass++\n else confusion.falsePass++\n } else if (example.verdict === 'fail') confusion.trueFail++\n else confusion.falseFail++\n }\n\n const perExample: JudgeExampleAgreement[] = []\n const unjudged: string[] = []\n const judgedByVerdict: Record<OwnerVerdict, number> = { pass: 0, fail: 0 }\n for (const example of registered.examples) {\n const list = runsById.get(example.id)\n if (!list) {\n unjudged.push(example.id)\n continue\n }\n judgedByVerdict[example.verdict]++\n const passes = list.filter((run) => run.verdict === 'pass').length\n perExample.push({\n id: example.id,\n verdict: example.verdict,\n runs: list.length,\n passRate: passes / list.length,\n agreement: list.filter((run) => run.verdict === example.verdict).length / list.length,\n })\n }\n\n const total = runs.length\n const agreedRuns = confusion.truePass + confusion.trueFail\n const agreedExamples = perExample.filter((example) => example.agreement === 1).length\n const mean = (values: readonly number[]) =>\n values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length\n return {\n ...meta,\n owner: registered.owner,\n examples: registered.examples.length,\n judged: perExample.length,\n judgedByVerdict,\n runs: total,\n accuracy: total === 0 ? null : agreedRuns / total,\n exampleAccuracy:\n perExample.length === 0\n ? null\n : {\n agreed: agreedExamples,\n judged: perExample.length,\n interval: computeInterval(\n { kind: 'clopper-pearson', level: 0.95 },\n { kind: 'binomial', successes: agreedExamples, trials: perExample.length },\n ),\n },\n kappa: binaryKappa(confusion),\n falseFailRate:\n confusion.truePass + confusion.falseFail === 0\n ? null\n : confusion.falseFail / (confusion.truePass + confusion.falseFail),\n catchRate:\n confusion.trueFail + confusion.falsePass === 0\n ? null\n : confusion.trueFail / (confusion.trueFail + confusion.falsePass),\n confusion,\n variance: {\n betweenRuns: mean(perExample.map((example) => example.passRate * (1 - example.passRate))),\n withinRun: mean(withinRun),\n unstable: perExample\n .filter((example) => example.passRate > 0 && example.passRate < 1)\n .map((example) => example.id),\n },\n disagreements: perExample\n .filter((example) => example.agreement < 1)\n .sort((a, b) => a.agreement - b.agreement || (a.id < b.id ? -1 : 1)),\n unjudged,\n }\n}\n\nexport interface JudgeGatePolicy {\n /**\n * `verdict`: the judge passes and blocks, so accuracy and κ must hold.\n * `veto`: it only blocks, so its false-fail rate on owner passes must hold.\n */\n decides: 'verdict' | 'veto'\n /** Judged examples required before the judge may gate; for a veto judge, owner passes. */\n minExamples: number\n /** Judged examples required of each owner verdict, so κ is defined. */\n minPerVerdict: number\n /** Floor on run accuracy. */\n minAccuracy: number\n /** Floor on Cohen's κ. */\n minKappa: number\n /** Ceiling on a veto judge's false-fail rate. */\n maxFalseFailRate: number\n /** A report older than this (days, vs `asOf`) no longer calibrates the judge. */\n maxAgeDays: number\n /** Drift thresholds forwarded to `judgeSentinelReport` over the history. */\n drift?: SentinelThresholds\n}\n\nexport const DEFAULT_JUDGE_GATE_POLICY: Readonly<JudgeGatePolicy> = Object.freeze({\n decides: 'verdict',\n minExamples: 10,\n minPerVerdict: 1,\n minAccuracy: 0.9,\n minKappa: 0.6,\n maxFalseFailRate: 0.1,\n maxAgeDays: 30,\n})\n\nexport type JudgeGateStatus = 'calibrated' | 'uncalibrated' | 'below-threshold' | 'drifted'\n\nexport interface JudgeGateDecision {\n judgeId: string\n judgeModel: string\n rubricVersion: string\n /** True only for `calibrated`. */\n mayGate: boolean\n status: JudgeGateStatus\n /** Why the judge may not gate; empty when it may. */\n reasons: string[]\n agreement: JudgeAgreement | null\n policy: JudgeGatePolicy\n}\n\nexport interface JudgeGateInput {\n judgeId: string\n /** The model the judge runs now. */\n judgeModel: string\n /** The rubric the judge runs now. */\n rubricVersion: string\n /** The latest calibration report; null when the judge was never measured. */\n agreement: JudgeAgreement | null\n asOf: string\n /** Sentinel snapshots for this judge, oldest first or in any order. */\n history?: readonly SentinelSnapshot[]\n policy?: Partial<JudgeGatePolicy>\n}\n\nconst DAY_MS = 86_400_000\n\nfunction percent(value: number): string {\n return `${(value * 100).toFixed(1)}%`\n}\n\n/** Whether a judge may gate now, and every reason it may not. */\nexport function judgeGateDecision(input: JudgeGateInput): JudgeGateDecision {\n const judgeId = requireText(input.judgeId, 'judgeId')\n const judgeModel = requireText(input.judgeModel, 'judgeModel')\n const rubricVersion = requireText(input.rubricVersion, 'rubricVersion')\n const asOf = parseIso(input.asOf, 'asOf')\n const policy: JudgeGatePolicy = {\n ...DEFAULT_JUDGE_GATE_POLICY,\n ...Object.fromEntries(\n Object.entries(input.policy ?? {}).filter(([, value]) => value !== undefined),\n ),\n }\n if (policy.decides !== 'verdict' && policy.decides !== 'veto') {\n throw new ValidationError(\n `judge-gate: policy.decides must be 'verdict' or 'veto', got ${JSON.stringify(policy.decides)}`,\n )\n }\n const agreement = input.agreement\n const decide = (status: JudgeGateStatus, reasons: string[]): JudgeGateDecision => ({\n judgeId,\n judgeModel,\n rubricVersion,\n mayGate: status === 'calibrated',\n status,\n reasons,\n agreement,\n policy,\n })\n\n if (!agreement) return decide('uncalibrated', ['no measured agreement with owner verdicts'])\n if (agreement.judgeId !== judgeId) {\n throw new ValidationError(\n `judge-gate: agreement belongs to \"${agreement.judgeId}\", not \"${judgeId}\"`,\n )\n }\n\n const uncalibrated: string[] = []\n if (agreement.judgeModel !== judgeModel) {\n uncalibrated.push(\n `agreement was measured on model ${agreement.judgeModel}; the judge now runs ${judgeModel}`,\n )\n }\n if (agreement.rubricVersion !== rubricVersion) {\n uncalibrated.push(\n `agreement was measured on rubric ${agreement.rubricVersion}; the judge now runs ${rubricVersion}`,\n )\n }\n const ageDays = (asOf - parseIso(agreement.measuredAt, 'agreement.measuredAt')) / DAY_MS\n if (ageDays > policy.maxAgeDays) {\n uncalibrated.push(`agreement is ${ageDays.toFixed(1)} days old (limit ${policy.maxAgeDays})`)\n }\n if (policy.decides === 'veto') {\n // Only owner passes can show a veto judge blocking what it should not.\n if (agreement.judgedByVerdict.pass < policy.minExamples) {\n uncalibrated.push(\n `${agreement.judgedByVerdict.pass} judged examples the owner marked pass; a veto judge needs at least ${policy.minExamples}`,\n )\n }\n } else {\n if (agreement.judged < policy.minExamples) {\n uncalibrated.push(\n `${agreement.judged} judged ${agreement.judged === 1 ? 'example' : 'examples'}; at least ${policy.minExamples} required`,\n )\n }\n for (const verdict of ['pass', 'fail'] as const) {\n if (agreement.judgedByVerdict[verdict] < policy.minPerVerdict) {\n uncalibrated.push(\n `${agreement.judgedByVerdict[verdict]} judged examples the owner marked ${verdict}; at least ${policy.minPerVerdict} required`,\n )\n }\n }\n }\n if (uncalibrated.length > 0) return decide('uncalibrated', uncalibrated)\n\n const below: string[] = []\n if (policy.decides === 'veto') {\n if (agreement.falseFailRate === null || agreement.falseFailRate > policy.maxFalseFailRate) {\n below.push(\n `it fails ${agreement.falseFailRate === null ? 'an unmeasured share' : percent(agreement.falseFailRate)} of what the owner passed (limit ${percent(policy.maxFalseFailRate)})`,\n )\n }\n } else if (agreement.accuracy === null || agreement.accuracy < policy.minAccuracy) {\n below.push(\n `accuracy ${agreement.accuracy === null ? 'unmeasured' : percent(agreement.accuracy)} is below ${percent(policy.minAccuracy)}`,\n )\n }\n if (\n policy.decides === 'verdict' &&\n (agreement.kappa === null || agreement.kappa < policy.minKappa)\n ) {\n below.push(\n `kappa ${agreement.kappa === null ? 'undefined' : agreement.kappa.toFixed(2)} is below ${policy.minKappa}`,\n )\n }\n if (below.length > 0) return decide('below-threshold', below)\n\n const history = (input.history ?? []).filter((snapshot) => snapshot.judgeId === judgeId)\n if (history.length > 0) {\n const report = judgeSentinelReport([...history], {\n asOf: input.asOf,\n ...(policy.drift ? { thresholds: policy.drift } : {}),\n })\n if (!report.healthy) return decide('drifted', report.alarms)\n }\n return decide('calibrated', [])\n}\n\n/** Thrown by `assertJudgeMayGate`; carries the refused decision. */\nexport class JudgeGateRefusedError extends JudgeError {\n readonly decision: JudgeGateDecision\n\n constructor(decision: JudgeGateDecision) {\n super(\n `judge \"${decision.judgeId}\" may not gate (${decision.status}): ${decision.reasons.join('; ')}`,\n )\n this.decision = decision\n }\n}\n\n/** Throw unless the decision lets the judge gate. */\nexport function assertJudgeMayGate(decision: JudgeGateDecision): void {\n if (!decision.mayGate) throw new JudgeGateRefusedError(decision)\n}\n\n/**\n * The sentinel snapshot for one calibration run. A deciding judge records\n * accuracy as `sentinelPassRate` and κ as `calibrationKappa` when it is\n * defined; a veto judge records the share of owner passes it let through as\n * `sentinelPassRate`. Append it to the judge's `SentinelStore`; the gate reads\n * drift from that history.\n */\nexport function snapshotFromJudgeAgreement(\n agreement: JudgeAgreement,\n options: { decides?: JudgeGatePolicy['decides'] } = {},\n): SentinelSnapshot {\n const veto = options.decides === 'veto'\n const rate = veto\n ? agreement.falseFailRate === null\n ? null\n : 1 - agreement.falseFailRate\n : agreement.accuracy\n if (rate === null) {\n throw new ValidationError(\n `snapshotFromJudgeAgreement: judge \"${agreement.judgeId}\" has no ${veto ? 'runs on owner passes' : 'runs'} to snapshot`,\n )\n }\n const snapshot: SentinelSnapshot = {\n at: agreement.measuredAt,\n judgeId: agreement.judgeId,\n judgeModel: agreement.judgeModel,\n metrics: {\n sentinelPassRate: rate,\n ...(veto || agreement.kappa === null ? {} : { calibrationKappa: agreement.kappa }),\n },\n }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n"],"mappings":";;;;AA8BA,SAAgB,cACd,QACA,UAAoC,CAAC,GACZ;CACzB,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAW,QAAQ,YAAY;CAErC,IAAI,OAAO,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,CAAC,CAAC,GACjD,OAAO;EAAE,OAAO;EAAqB,YAAY;EAAG,UAAU;EAAG,SAAS;EAAG,QA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CAE5D,MAAM,WAAW,MAAM,WAAW,CAAC,EAAA,CAAG,QAAQ,aAAa,SAAS,YAAY,OAAO;CACvF,IAAI,QAAQ,SAAS,GAAG;EACtB,MAAM,SAAS,oBAAoB,CAAC,GAAG,OAAO,GAAG;GAC/C,MAAM,MAAM;GACZ,GAAI,OAAO,QAAQ,EAAE,YAAY,OAAO,MAAM,IAAI,CAAC;EACrD,CAAC;EACD,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO,WAAW,OAAO,MAAM;CAC7D;CACA,OAAO,OAAO,cAAc,CAAC,CAAC;AAChC;;AAGA,IAAa,wBAAb,cAA2C,WAAW;CACpD;CAEA,YAAY,UAA6B;EACvC,MACE,UAAU,SAAS,QAAQ,kBAAkB,SAAS,OAAO,KAAK,SAAS,QAAQ,KAAK,IAAI,GAC9F;EACA,KAAK,WAAW;CAClB;AACF;;AAGA,SAAgB,mBAAmB,UAAmC;CACpE,IAAI,CAAC,SAAS,SAAS,MAAM,IAAI,sBAAsB,QAAQ;AACjE;;;;;;;;AASA,SAAgB,2BACd,WACA,UAAoD,CAAC,GACnC;CAClB,MAAM,OAAO,QAAQ,YAAY;CACjC,MAAM,OAAO,OACT,UAAU,kBAAkB,OAC1B,OACA,IAAI,UAAU,gBAChB,UAAU;CACd,IAAI,SAAS,MACX,MAAM,IAAI,gBACR,sCAAsC,UAAU,QAAQ,WAAW,OAAO,yBAAyB,OAAO,aAC5G;CAEF,MAAM,WAA6B;EACjC,IAAI,UAAU;EACd,SAAS,UAAU;EACnB,YAAY,UAAU;EACtB,SAAS;GACP,kBAAkB;GAClB,GAAI,QAAQ,UAAU,UAAU,OAAO,CAAC,IAAI,EAAE,kBAAkB,UAAU,MAAM;EAClF;CACF;CACA,yBAAyB,QAAQ;CACjC,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"mean-CdDYG-us.js","names":[],"sources":["../src/math/student-t.ts","../src/statistics/paired-tests.ts","../src/statistics/mean.ts"],"sourcesContent":["import { regularizedIncompleteBeta } from './special-functions'\n\n/**\n * Student-t CDF via the regularized incomplete beta function.\n */\nexport function studentTCdf(t: number, degreesOfFreedom: number): number {\n if (degreesOfFreedom <= 0) return 0.5\n\n const x = degreesOfFreedom / (degreesOfFreedom + t * t)\n const beta = regularizedIncompleteBeta(x, degreesOfFreedom / 2, 0.5)\n return t >= 0 ? 1 - 0.5 * beta : 0.5 * beta\n}\n\n/**\n * Inverse Student-t CDF, solved against {@link studentTCdf}.\n *\n * The CDF is monotone, so bracket expansion followed by bisection is stable\n * across fractional degrees of freedom and does not need a separate\n * approximation with a different error profile.\n */\nexport function studentTQuantile(probability: number, degreesOfFreedom: number): number {\n if (!Number.isFinite(probability) || probability < 0 || probability > 1) {\n throw new RangeError(`studentTQuantile: probability must be in [0,1], got ${probability}`)\n }\n if (!Number.isFinite(degreesOfFreedom) || degreesOfFreedom <= 0) {\n throw new RangeError(\n `studentTQuantile: degreesOfFreedom must be positive and finite, got ${degreesOfFreedom}`,\n )\n }\n if (probability === 0) return Number.NEGATIVE_INFINITY\n if (probability === 1) return Number.POSITIVE_INFINITY\n if (probability === 0.5) return 0\n if (probability < 0.5) return -studentTQuantile(1 - probability, degreesOfFreedom)\n\n let low = 0\n let high = 1\n while (studentTCdf(high, degreesOfFreedom) < probability) high *= 2\n for (let iteration = 0; iteration < 64; iteration++) {\n const middle = (low + high) / 2\n if (studentTCdf(middle, degreesOfFreedom) < probability) low = middle\n else high = middle\n }\n return (low + high) / 2\n}\n","/**\n * Paired significance tests on continuous scores: the paired t-test, the\n * promotion-gate paired bootstrap, the exact sign test, and the package-wide\n * paired-delta decision statistic.\n */\n\nimport { ValidationError } from '../errors'\nimport { studentTCdf } from '../math/student-t'\nimport { assertFiniteSample, binomialHalfUpperTail, makeRng, medianInPlace } from './internal'\n\nexport interface PairedTTestResult {\n /** Null when the statistic is undefined — see {@link pairedTTest}. */\n t: number | null\n df: number\n /** Null exactly when `t` is null. */\n p: number | null\n}\n\n/**\n * Paired t-test — before/after measurements on the SAME items.\n * Pairing removes inter-item variance, giving tighter significance than\n * an unpaired test when comparing prompt v1 vs prompt v2 on identical\n * scenarios.\n *\n * Returns `t = p = null` where the statistic is undefined: fewer than two\n * pairs, or a non-zero constant delta whose observed variance is zero. A\n * constant shift carries no information about the variance it would have to\n * be compared against, so the honest answer is \"undefined\", not `p = 0` —\n * three observations cannot buy absolute certainty. This is the same contract\n * {@link pairedCohensDz} states for the same condition. An all-zero delta is\n * different: it is a measured null, and returns `t = 0, p = 1`.\n */\nexport function pairedTTest(before: number[], after: number[]): PairedTTestResult {\n if (before.length !== after.length) {\n throw new ValidationError(\n `pairedTTest: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n assertFiniteSample('pairedTTest', 'before', before)\n assertFiniteSample('pairedTTest', 'after', after)\n const n = before.length\n if (n < 2) return { t: null, df: 0, p: null }\n\n const diffs = before.map((b, i) => after[i]! - b)\n const mean = diffs.reduce((a, b) => a + b, 0) / n\n const variance = diffs.reduce((acc, d) => acc + (d - mean) ** 2, 0) / (n - 1)\n const se = Math.sqrt(variance / n)\n if (se === 0) {\n return mean === 0 ? { t: 0, df: n - 1, p: 1 } : { t: null, df: n - 1, p: null }\n }\n\n const t = mean / se\n const df = n - 1\n const p = 2 * (1 - studentTCdf(Math.abs(t), df))\n return { t, df, p }\n}\n\n// ── Paired bootstrap (promotion-gate effect size) ────────────────────\n\nexport interface PairedBootstrapResult {\n /** Number of paired observations. */\n n: number\n /** Median of paired deltas (after − before). */\n median: number\n /** Mean of paired deltas. */\n mean: number\n /** Lower bound of the bootstrap CI on the chosen statistic. */\n low: number\n /** Upper bound of the bootstrap CI on the chosen statistic. */\n high: number\n /** Confidence level used (e.g. 0.95). */\n confidence: number\n /** Number of bootstrap resamples used. */\n resamples: number\n /** False below {@link BOOTSTRAP_GATE_MIN_N}. See {@link pairedBootstrap}. */\n gateEligible: boolean\n}\n\n/**\n * Pairs below which a percentile bootstrap interval is descriptive spread only.\n *\n * `P(low > 0)` under a true null, against a nominal 2.5 %, measured over 4000\n * seeded trials: 13.53 % at n = 3, 3.52 % at n = 10, 3.10 % at n = 20 on the\n * median; 13.85 %, 4.90 %, 3.80 % on the mean. This is intrinsic to resampling\n * three points, not an implementation error — scipy's BCa gives 16.0 % on the\n * same n = 3 data — so no change to the estimator moves it. Below this floor\n * the decision belongs to the exact sign test or exact signed-rank test.\n */\nexport const BOOTSTRAP_GATE_MIN_N = 20\n\nexport interface PairedBootstrapOptions {\n /** Confidence level. Default 0.95. */\n confidence?: number\n /** Bootstrap resample count. Default 2000. */\n resamples?: number\n /** Statistic to bootstrap. Default 'median'. */\n statistic?: 'median' | 'mean'\n /** Deterministic seed. If omitted, derived from the deltas so the interval\n * is reproducible regardless. */\n seed?: number\n}\n\n/**\n * Paired bootstrap on (after − before) deltas. Returns a CI on the chosen\n * statistic (median by default); pairs are resampled with replacement. Throws\n * on unequal sample sizes.\n *\n * `low > threshold` carries the stated confidence ONLY at `n ≥\n * {@link BOOTSTRAP_GATE_MIN_N}`, which `gateEligible` reports. Below it the\n * check fires under a true null several times more often than nominal, so the\n * interval is descriptive spread and a promotion must not turn on it.\n */\nexport function pairedBootstrap(\n before: number[],\n after: number[],\n opts: PairedBootstrapOptions = {},\n): PairedBootstrapResult {\n if (before.length !== after.length) {\n throw new Error(`pairedBootstrap: unequal sample sizes (${before.length} vs ${after.length})`)\n }\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const statistic = opts.statistic ?? 'median'\n if (confidence <= 0 || confidence >= 1) {\n throw new Error(`pairedBootstrap: confidence must be in (0,1), got ${confidence}`)\n }\n\n const n = before.length\n const deltas = before.map((b, i) => after[i]! - b)\n const gateEligible = n >= BOOTSTRAP_GATE_MIN_N\n if (n === 0) {\n return { n: 0, median: 0, mean: 0, low: 0, high: 0, confidence, resamples, gateEligible }\n }\n if (n === 1) {\n const d = deltas[0]!\n return { n: 1, median: d, mean: d, low: d, high: d, confidence, resamples, gateEligible }\n }\n\n const rng = makeRng(opts.seed, deltas)\n const samples = new Array<number>(resamples)\n for (let b = 0; b < resamples; b++) {\n if (statistic === 'mean') {\n let sum = 0\n for (let k = 0; k < n; k++) {\n sum += deltas[Math.floor(rng() * n)]!\n }\n samples[b] = sum / n\n } else {\n const acc = new Array<number>(n)\n for (let k = 0; k < n; k++) {\n acc[k] = deltas[Math.floor(rng() * n)]!\n }\n samples[b] = medianInPlace(acc)\n }\n }\n samples.sort((a, b) => a - b)\n\n const alpha = 1 - confidence\n const lowIdx = Math.floor((alpha / 2) * resamples)\n const highIdx = Math.min(resamples - 1, Math.ceil((1 - alpha / 2) * resamples) - 1)\n\n return {\n n,\n median: medianInPlace([...deltas]),\n mean: deltas.reduce((s, x) => s + x, 0) / n,\n low: samples[lowIdx]!,\n high: samples[Math.max(highIdx, lowIdx)]!,\n confidence,\n resamples,\n gateEligible,\n }\n}\n\n/** Pre-registered direction for a one-sided paired sign test. */\nexport type SignTestAlternative = 'greater' | 'less'\n\n/** Exact one-sided sign-test result for paired numeric differences. */\nexport interface PairedSignTestResult {\n /** Total supplied differences, including zero ties. */\n n: number\n /** Strictly positive differences. */\n positive: number\n /** Strictly negative differences. */\n negative: number\n /** Zero differences excluded from the binomial test. */\n ties: number\n /** Non-zero differences used by the binomial test. */\n nNonTies: number\n /** Direction of the pre-registered alternative hypothesis. */\n alternative: SignTestAlternative\n /** Exact one-sided p-value under P(positive) = P(negative) = 0.5. */\n pValue: number\n}\n\n/**\n * Exact one-sided sign test over paired differences.\n *\n * Pass `after[i] - before[i]` for each matched item. `alternative = 'greater'`\n * tests whether positive signs are more likely than negative signs and returns\n * `P(Binomial(nNonTies, 0.5) >= positive)`. `alternative = 'less'` treats\n * negative signs as successes instead. With a continuous difference\n * distribution this is the usual directional median test. Exact zero\n * differences are ties and do not enter the binomial denominator. All-tie and\n * empty inputs return p = 1. Every input difference must be finite, and the\n * direction must be chosen explicitly so a caller cannot select it after\n * seeing the signs.\n */\nexport function pairedSignTest(\n differences: readonly number[],\n alternative: SignTestAlternative,\n): PairedSignTestResult {\n if (alternative !== 'greater' && alternative !== 'less') {\n throw new ValidationError(\n `pairedSignTest: alternative must be 'greater' or 'less', got ${alternative}`,\n )\n }\n\n let positive = 0\n let negative = 0\n let ties = 0\n for (let i = 0; i < differences.length; i++) {\n const difference = differences[i]!\n if (!Number.isFinite(difference)) {\n throw new ValidationError(\n `pairedSignTest: difference at index ${i} must be finite, got ${difference}`,\n )\n }\n if (difference > 0) positive++\n else if (difference < 0) negative++\n else ties++\n }\n\n const nNonTies = positive + negative\n const successes = alternative === 'greater' ? positive : negative\n return {\n n: differences.length,\n positive,\n negative,\n ties,\n nNonTies,\n alternative,\n pValue: binomialHalfUpperTail(successes, nNonTies),\n }\n}\n\n/** Fraction of paired observations whose delta is an exact tie (|after − before|\n * < 1e-9). Throws on unequal sample sizes; 0 pairs ⇒ 0. */\nexport function pairedDeltaTieFraction(\n before: ArrayLike<number>,\n after: ArrayLike<number>,\n): number {\n if (before.length !== after.length) {\n throw new Error(\n `pairedDeltaTieFraction: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n const n = before.length\n if (n === 0) return 0\n let ties = 0\n for (let i = 0; i < n; i++) {\n if (Math.abs(after[i]! - before[i]!) < 1e-9) ties++\n }\n return ties / n\n}\n\n/**\n * The paired-delta statistic a DECISION is computed on, package-wide.\n *\n * The mean paired delta is the estimator that answers the question a promotion\n * gate asks — \"by how much did the candidate move the score\" — in the caller's\n * own units, and it equals the aggregate lift everyone quotes. The MEDIAN\n * answers a different question and loses the answer to this one in every regime\n * eval data actually lands in:\n * - TWO-POINT (pass/fail) outcomes on any encoding: the delta vector lives in\n * {−s, 0, +s} dominated by zeros, so the median and its whole bootstrap CI\n * are pinned at exactly 0 however large the shift. (Decide these on\n * {@link pairedRiskDifferenceExact} instead — same estimand, exact interval.)\n * - TIE-DOMINATED outcomes: at half the pairs tied the sample median is 0 by\n * construction, and `ci.low > threshold` then answers \"no\" forever at a\n * non-negative threshold and \"yes\" forever at a negative one.\n * - LOW-CARDINALITY outcomes, even well below half ties: judge dimensions on\n * integer 0-100, and block scores like {⅔, 1} from averaging pass/fail\n * leaves, put the median on a coarse lattice whose bootstrap percentiles\n * land on atoms. Measured: 26 blocks of 3 pass/fail leaves carrying a real\n * +12.8pp lift, only 23% of pairs tied, gives a median CI of [0, 0.333] —\n * lower bound exactly 0, so a gate at threshold 0 refuses a real lift.\n * That last case is why there is no tie-fraction threshold here: any cutoff on\n * ties leaves the lattice case open on the other side of it.\n *\n * `heldoutSignificance` has defaulted to the mean since #316 for the same\n * reason. The median remains available per call site for callers who\n * specifically want outlier robustness and accept the blindness.\n */\nexport const DECISION_PAIRED_DELTA_STATISTIC: 'mean' = 'mean'\n","/** Arithmetic mean. An empty input has no mean and returns NaN. */\nexport function mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n"],"mappings":";;;;;;AAKA,SAAgB,YAAY,GAAW,kBAAkC;CACvE,IAAI,oBAAoB,GAAG,OAAO;CAElC,MAAM,IAAI,oBAAoB,mBAAmB,IAAI;CACrD,MAAM,OAAO,0BAA0B,GAAG,mBAAmB,GAAG,EAAG;CACnE,OAAO,KAAK,IAAI,IAAI,KAAM,OAAO,KAAM;AACzC;;;;;;;;AASA,SAAgB,iBAAiB,aAAqB,kBAAkC;CACtF,IAAI,CAAC,OAAO,SAAS,WAAW,KAAK,cAAc,KAAK,cAAc,GACpE,MAAM,IAAI,WAAW,uDAAuD,aAAa;CAE3F,IAAI,CAAC,OAAO,SAAS,gBAAgB,KAAK,oBAAoB,GAC5D,MAAM,IAAI,WACR,uEAAuE,kBACzE;CAEF,IAAI,gBAAgB,GAAG,OAAO,OAAO;CACrC,IAAI,gBAAgB,GAAG,OAAO,OAAO;CACrC,IAAI,gBAAgB,IAAK,OAAO;CAChC,IAAI,cAAc,IAAK,OAAO,CAAC,iBAAiB,IAAI,aAAa,gBAAgB;CAEjF,IAAI,MAAM;CACV,IAAI,OAAO;CACX,O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