@tangle-network/agent-eval 0.203.2 → 0.203.4

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"judge-gate-B1qYnkpi.js","names":["parseIso"],"sources":["../src/series-convergence.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 * Judge sentinel — eval trustworthiness as a continuously measured,\n * alarmed trend.\n *\n * Judges are models; models change underneath us; calibration decays.\n * This module composes three existing instruments into one loop:\n *\n * snapshot — adapters turn real instrument outputs (`calibrateJudge` /\n * `calibrateJudgeContinuous`, `corpusInterRaterAgreement` /\n * `continuousAgreement`, a rerun sentinel golden set) into\n * `SentinelSnapshot`s\n * series — `analyzeSeries` (src/series-convergence) classifies each\n * judge×metric history as stabilized / drifting / noisy\n * alarm — `judgeSentinelReport` turns trends + thresholds into named\n * alarms; `evalHealthStamp` is the tiny object a campaign\n * attaches to its verdicts\n *\n * Alarm conditions:\n * - convergence state `drifting-down` on any tracked metric\n * - irr below `minIrr`\n * - calibrationKappa / sentinelPassRate dropped vs the series baseline\n * beyond `maxKappaDrop` / `maxSentinelDrop`\n * - judge model changed with no post-change golden-grounded snapshot\n * (the silent-upgrade trap: judges agreeing with each other after a\n * model swap proves nothing — only re-measuring against gold does)\n * - newest snapshot older than `staleAfterDays` relative to `asOf`\n *\n * Wire-in: run the snapshot adapters from a post-campaign hook or a\n * nightly job, append to a `SentinelStore`, then compute\n * `judgeSentinelReport(await store.history(), { asOf })` with `asOf` =\n * the campaign timestamp. Attach `evalHealthStamp(report)` to campaign\n * verdicts: an alarmed sentinel means every downstream verdict carries\n * an integrity warning until the judge is recalibrated.\n *\n * The module is clock-free — every timestamp (`at`, `asOf`) is\n * caller-supplied ISO-8601, so reports are reproducible.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n CalibrationResult,\n CandidateScore,\n ContinuousAgreement,\n ContinuousCalibrationResult,\n GoldenItem,\n} from '../judge-calibration'\nimport {\n analyzeSeries,\n type SeriesConvergenceOptions,\n type SeriesConvergenceResult,\n} from '../series-convergence'\nimport type { CorpusAgreementReport } from '../statistics'\n\nconst SENTINEL_METRIC_NAMES = ['irr', 'calibrationKappa', 'sentinelPassRate'] as const\n\nexport type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number]\n\nexport interface SentinelMetrics {\n /** Inter-rater reliability — ICC(2,1) from agreement instruments. */\n irr?: number\n /** Weighted κ vs the human golden set (`calibrateJudge*`). */\n calibrationKappa?: number\n /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */\n sentinelPassRate?: number\n}\n\nexport interface SentinelSnapshot {\n /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */\n at: string\n judgeId: string\n /** Exact model identity behind the judge (pin the full version string). */\n judgeModel: string\n /**\n * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a\n * model-change marker — it records the new `judgeModel` immediately and\n * the silent-upgrade alarm stays raised until a golden-grounded snapshot\n * (calibrationKappa or sentinelPassRate) follows.\n */\n metrics: SentinelMetrics\n}\n\n/** Identity + timestamp the caller supplies alongside an instrument output. */\nexport interface SnapshotMeta {\n at: string\n judgeId: string\n judgeModel: string\n}\n\nfunction parseIso(value: string, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-sentinel: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\n/** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */\nexport function validateSentinelSnapshot(snapshot: SentinelSnapshot, source = 'snapshot'): void {\n parseIso(snapshot.at, `${source}.at`)\n if (typeof snapshot.judgeId !== 'string' || snapshot.judgeId.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeId must be a non-empty string`)\n }\n if (typeof snapshot.judgeModel !== 'string' || snapshot.judgeModel.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeModel must be a non-empty string`)\n }\n if (snapshot.metrics === null || typeof snapshot.metrics !== 'object') {\n throw new ValidationError(`judge-sentinel: ${source}.metrics must be an object (may be empty)`)\n }\n for (const [key, value] of Object.entries(snapshot.metrics)) {\n if (!(SENTINEL_METRIC_NAMES as readonly string[]).includes(key)) {\n // A typo'd key would silently never trend — reject instead.\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics carries unknown key \"${key}\" — known: ${SENTINEL_METRIC_NAMES.join(', ')}`,\n )\n }\n if (value !== undefined && !Number.isFinite(value)) {\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics.${key} is not a finite number: ${String(value)}`,\n )\n }\n }\n}\n\n// ── Snapshot adapters — real instrument output → SentinelSnapshot ───\n\n/**\n * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the\n * un-rounded continuous κ_w when the report carries one (integer κ\n * discards information for [0,1] judges).\n */\nexport function snapshotFromCalibration(\n report: CalibrationResult | ContinuousCalibrationResult,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const kappa = 'weightedKappaContinuous' in report ? report.weightedKappaContinuous : report.kappa\n if (!Number.isFinite(kappa)) {\n throw new ValidationError(\n `snapshotFromCalibration: κ is not finite (n=${report.n}) — calibrate against ≥2 joined golden items before snapshotting`,\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { calibrationKappa: kappa } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n/**\n * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`\n * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability\n * coefficient both instruments compute. For ensemble-level agreement,\n * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its\n * composition (e.g. a joined list of member model strings).\n */\nexport function snapshotFromAgreement(\n report: CorpusAgreementReport | ContinuousAgreement,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const irr = 'overallIcc' in report ? report.overallIcc : report.icc\n if (!Number.isFinite(irr)) {\n throw new ValidationError(\n 'snapshotFromAgreement: ICC is not finite — agreement needs ≥2 raters and ≥2 complete items',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { irr } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\nexport interface SentinelSetOptions {\n /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */\n tolerance?: number\n}\n\n/**\n * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the\n * judge was originally calibrated on, re-scored periodically. Pass rate =\n * fraction of joined items where the judge stays within `tolerance` of the\n * human score. Items the judge didn't score are excluded from the\n * denominator; zero joined items is an error, not a 0% pass rate.\n */\nexport function snapshotFromSentinelSet(\n scores: CandidateScore[],\n golden: GoldenItem[],\n meta: SnapshotMeta,\n options: SentinelSetOptions = {},\n): SentinelSnapshot {\n const tolerance = options.tolerance ?? 0.1\n if (!Number.isFinite(tolerance) || tolerance < 0) {\n throw new ValidationError(\n `snapshotFromSentinelSet: tolerance must be a finite number ≥ 0, got ${tolerance}`,\n )\n }\n const goldenById = new Map<string, number>()\n for (const item of golden) {\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: golden item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (goldenById.has(item.itemId)) {\n throw new ValidationError(`snapshotFromSentinelSet: duplicate golden itemId \"${item.itemId}\"`)\n }\n goldenById.set(item.itemId, item.humanScore)\n }\n let joined = 0\n let passed = 0\n for (const s of scores) {\n const human = goldenById.get(s.itemId)\n if (human === undefined) continue\n if (!Number.isFinite(s.score)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: judge score for item \"${s.itemId}\" is not finite`,\n )\n }\n joined++\n if (Math.abs(s.score - human) <= tolerance) passed++\n }\n if (joined === 0) {\n throw new ValidationError(\n 'snapshotFromSentinelSet: no judge scores joined the golden set — itemIds mismatch or empty sentinel run',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { sentinelPassRate: passed / joined } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n// ── Persistence ──────────────────────────────────────────────────────\n\nexport interface SentinelStore {\n append(snapshot: SentinelSnapshot): Promise<void>\n /** All snapshots (optionally for one judge), in append order. */\n history(judgeId?: string): Promise<SentinelSnapshot[]>\n}\n\nexport function inMemorySentinelStore(initial: SentinelSnapshot[] = []): SentinelStore {\n for (const s of initial) validateSentinelSnapshot(s)\n const items = initial.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n items.push({ ...snapshot, metrics: { ...snapshot.metrics } })\n },\n async history(judgeId) {\n const all = items.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return judgeId === undefined ? all : all.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n/**\n * JSONL store — one snapshot per line, appended atomically per call.\n * A corrupt or shape-invalid line is a loud error naming the file and\n * line number: a sentinel history that silently drops records would\n * defeat the drift detection it exists to provide.\n */\nexport function fileSentinelStore(path: string): SentinelStore {\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n const fs = await import('node:fs/promises')\n const pathMod = await import('node:path')\n await fs.mkdir(pathMod.dirname(path), { recursive: true })\n await fs.appendFile(path, `${JSON.stringify(snapshot)}\\n`, 'utf8')\n },\n async history(judgeId) {\n const fs = await import('node:fs/promises')\n let raw: string\n try {\n raw = await fs.readFile(path, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw err\n }\n const lines = raw.split('\\n')\n const snapshots: SentinelSnapshot[] = []\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n if (line.trim().length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `judge-sentinel: store at ${path} has a corrupt JSONL line ${i + 1}: ${(err as Error).message}`,\n )\n }\n const snapshot = parsed as SentinelSnapshot\n validateSentinelSnapshot(snapshot, `${path}:${i + 1}`)\n snapshots.push(snapshot)\n }\n return judgeId === undefined ? snapshots : snapshots.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n// ── Trend report ─────────────────────────────────────────────────────\n\nexport interface SentinelThresholds {\n /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */\n minIrr?: number\n /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */\n maxKappaDrop?: number\n /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */\n maxSentinelDrop?: number\n /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */\n staleAfterDays?: number\n}\n\nexport interface JudgeSentinelOptions {\n /** Caller-supplied ISO timestamp staleness is measured against. */\n asOf: string\n thresholds?: SentinelThresholds\n /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */\n convergence?: SeriesConvergenceOptions\n}\n\nexport interface SentinelTrend {\n judgeId: string\n metric: SentinelMetricName\n /** Verbatim `analyzeSeries` state for this judge×metric history. */\n state: SeriesConvergenceResult['state']\n /** Newest value in the series. */\n current: number\n /** Oldest value in the series — the reference the drop thresholds compare against. */\n baseline: number\n /** current − baseline (signed; negative = decayed). */\n drift: number\n alarmed: boolean\n reason?: string\n}\n\nexport interface SentinelReport {\n perJudge: SentinelTrend[]\n alarms: string[]\n healthy: boolean\n /**\n * `judgeId:metric` pairs with too few snapshots for the convergence\n * machine. Named, not counted — a blind spot you can't see is a blind\n * spot you won't fix. Floor/drop checks still apply to thin series, so\n * insufficient history alone never masks an alarm.\n */\n insufficientHistory: string[]\n}\n\nconst MS_PER_DAY = 86_400_000\n\nexport function judgeSentinelReport(\n history: SentinelSnapshot[],\n opts: JudgeSentinelOptions,\n): SentinelReport {\n const asOfMs = parseIso(opts.asOf, 'asOf')\n const minIrr = opts.thresholds?.minIrr ?? 0.6\n const maxKappaDrop = opts.thresholds?.maxKappaDrop ?? 0.15\n const maxSentinelDrop = opts.thresholds?.maxSentinelDrop ?? 0.1\n const staleAfterDays = opts.thresholds?.staleAfterDays ?? 30\n\n const byJudge = new Map<string, Array<SentinelSnapshot & { atMs: number }>>()\n for (const snapshot of history) {\n validateSentinelSnapshot(snapshot)\n const atMs = parseIso(snapshot.at, `snapshot.at (judge \"${snapshot.judgeId}\")`)\n const arr = byJudge.get(snapshot.judgeId) ?? []\n arr.push({ ...snapshot, atMs })\n byJudge.set(snapshot.judgeId, arr)\n }\n\n const perJudge: SentinelTrend[] = []\n const alarms: string[] = []\n const insufficientHistory: string[] = []\n\n for (const judgeId of [...byJudge.keys()].sort()) {\n const snaps = byJudge.get(judgeId)!.sort((a, b) => a.atMs - b.atMs)\n const newest = snaps[snaps.length - 1]!\n\n const ageDays = (asOfMs - newest.atMs) / MS_PER_DAY\n if (ageDays > staleAfterDays) {\n alarms.push(\n `judge \"${judgeId}\": stale — newest snapshot ${newest.at} is ${ageDays.toFixed(1)}d old vs asOf (limit ${staleAfterDays}d)`,\n )\n }\n\n // Silent-upgrade trap: only the latest model change matters for current\n // trust, and only golden-grounded metrics clear it — irr alone proves\n // judges still agree with each other, not that they're still right.\n let changeIdx = -1\n for (let i = 1; i < snaps.length; i++) {\n if (snaps[i]!.judgeModel !== snaps[i - 1]!.judgeModel) changeIdx = i\n }\n if (changeIdx >= 0) {\n const recalibrated = snaps\n .slice(changeIdx)\n .some(\n (s) =>\n Number.isFinite(s.metrics.calibrationKappa) ||\n Number.isFinite(s.metrics.sentinelPassRate),\n )\n if (!recalibrated) {\n alarms.push(\n `judge \"${judgeId}\": model changed \"${snaps[changeIdx - 1]!.judgeModel}\" → \"${snaps[changeIdx]!.judgeModel}\" at ${snaps[changeIdx]!.at} with no post-change calibration snapshot — silent-upgrade trap; rerun calibrateJudge or the sentinel set against the new model`,\n )\n }\n }\n\n for (const metric of SENTINEL_METRIC_NAMES) {\n const values = snaps\n .filter((s) => typeof s.metrics[metric] === 'number')\n .map((s) => s.metrics[metric]!)\n if (values.length === 0) continue\n\n const convergence = analyzeSeries(values, opts.convergence)\n if (convergence.state === 'insufficient-data')\n insufficientHistory.push(`${judgeId}:${metric}`)\n\n const current = values[values.length - 1]!\n const baseline = values[0]!\n const drift = current - baseline\n const reasons: string[] = []\n if (convergence.state === 'drifting-down') {\n reasons.push(\n `convergence state drifting-down (tail run ${convergence.tailRun}, window mean ${convergence.windowMean.toFixed(3)})`,\n )\n }\n if (metric === 'irr' && current < minIrr) {\n reasons.push(`irr ${current.toFixed(3)} below floor ${minIrr}`)\n }\n if (metric === 'calibrationKappa' && baseline - current > maxKappaDrop) {\n reasons.push(\n `calibrationKappa dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxKappaDrop})`,\n )\n }\n if (metric === 'sentinelPassRate' && baseline - current > maxSentinelDrop) {\n reasons.push(\n `sentinelPassRate dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxSentinelDrop})`,\n )\n }\n\n const alarmed = reasons.length > 0\n const trend: SentinelTrend = {\n judgeId,\n metric,\n state: convergence.state,\n current,\n baseline,\n drift,\n alarmed,\n }\n if (alarmed) {\n trend.reason = reasons.join('; ')\n alarms.push(`judge \"${judgeId}\" ${metric}: ${trend.reason}`)\n }\n perJudge.push(trend)\n }\n }\n\n return { perJudge, alarms, healthy: alarms.length === 0, insufficientHistory }\n}\n\n// ── Verdict stamp ────────────────────────────────────────────────────\n\nexport interface EvalHealthStamp {\n healthy: boolean\n alarms: string[]\n}\n\n/**\n * The object a campaign attaches to its verdicts. Compute it from the\n * sentinel report in a post-campaign hook (or a nightly job feeding the\n * next day's campaigns) and store it alongside the verdict payload.\n * `healthy: false` means the judges that produced those verdicts have an\n * unresolved drift / decay / silent-upgrade / staleness alarm — treat the\n * verdicts as carrying an integrity warning until recalibration clears it.\n */\nexport function evalHealthStamp(report: SentinelReport): EvalHealthStamp {\n return { healthy: report.healthy, alarms: [...report.alarms] }\n}\n","/**\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'\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,CA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Q;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"}
@@ -0,0 +1,454 @@
1
+ import { a as JudgeError } from "./errors-DEE6u6ot.js";
2
+ import { u as JudgeScore } from "./types-DLxe96rp.js";
3
+ import { a as ContinuousCalibrationResult, i as ContinuousAgreementOptions, n as CandidateScore, o as GoldenItem, r as ContinuousAgreement, t as CalibrationResult } from "./judge-calibration-DFtEMlde.js";
4
+ import { a as ComputedInterval } from "./ast-hI-vjW6J.js";
5
+ //#region src/statistics/agreement-irr.d.ts
6
+ /**
7
+ * Inter-rater reliability — Krippendorff's α under the squared-difference
8
+ * metric, pooled across dimensions.
9
+ *
10
+ * Each inner array is one judge's scores. Items are matched by position
11
+ * WITHIN a dimension: the k-th score a judge supplies carrying dimension
12
+ * `d` is item k of `d`, and the ratings compared against each other are
13
+ * the ones different judges gave to the same item. Every judge that scores
14
+ * a dimension at all must supply the same number of scores for it —
15
+ * ragged input cannot be aligned into items and throws rather than
16
+ * comparing mismatched items.
17
+ *
18
+ * α = 1 − D_observed / D_expected: D_observed averages the squared
19
+ * difference over within-item judge pairs, D_expected over every pair of
20
+ * ratings irrespective of item. α = 1 is perfect agreement, 0 is chance,
21
+ * negative is systematic disagreement.
22
+ */
23
+ declare function interRaterReliability(judgeScores: JudgeScore[][]): number;
24
+ interface CorpusScoreRecord {
25
+ /** Stable identifier for the rated item (scenario, span, turn, …). */
26
+ itemId: string;
27
+ /** Identifier for the judge that produced this score. */
28
+ judgeName: string;
29
+ /** Dimension name (matches `JudgeScore.dimension`). */
30
+ dimension: string;
31
+ /** Numeric score; must be finite. */
32
+ score: number;
33
+ }
34
+ interface CorpusAgreementPerDimension extends ContinuousAgreement {
35
+ dimension: string;
36
+ /** Item IDs that contributed to this dimension's matrix (every judge scored them). */
37
+ itemIds: string[];
38
+ /** Judge IDs that contributed to this dimension's matrix. */
39
+ judgeIds: string[];
40
+ }
41
+ interface CorpusAgreementReport {
42
+ /** Per-dimension ICC(2,1) + κ_w + Pearson + Spearman + bootstrap CIs. */
43
+ perDimension: CorpusAgreementPerDimension[];
44
+ /** Mean ICC across dimensions (NaN if no dimension yielded a finite ICC). */
45
+ overallIcc: number;
46
+ /** Mean weighted κ across dimensions (NaN if none finite). */
47
+ overallWeightedKappa: number;
48
+ /** Dimensions evaluated (sorted). */
49
+ dimensions: string[];
50
+ /** Judges seen across the corpus (sorted). */
51
+ judgeIds: string[];
52
+ }
53
+ interface CorpusAgreementOptions extends ContinuousAgreementOptions {
54
+ /**
55
+ * Restrict the audit to these dimensions. Default = every dimension
56
+ * that appears in the input. A dimension named here but absent from
57
+ * the input throws — silent omission would corrupt the overall metric.
58
+ */
59
+ dimensions?: string[];
60
+ /**
61
+ * Restrict the audit to these judges. Default = every judge that
62
+ * appears in the input. A judge named here but absent from a
63
+ * dimension throws (see "fail loud" below).
64
+ */
65
+ judges?: string[];
66
+ }
67
+ /**
68
+ * Corpus-wide inter-rater agreement across N items × M judges × D dimensions.
69
+ *
70
+ * For each dimension, builds the [n_items][n_judges] matrix of scores
71
+ * (keeping only items every judge rated on that dimension), then runs
72
+ * `continuousAgreement` to get ICC(2,1), κ_w, Pearson, Spearman, and
73
+ * bootstrap CIs. Reports a pooled mean across dimensions as a single
74
+ * "is this judge panel reliable on this corpus?" number.
75
+ *
76
+ * Fail-loud contract:
77
+ * - Empty input throws.
78
+ * - Fewer than 2 judges or fewer than 2 items per dimension throws.
79
+ * - A judge present in some dimensions but with zero scored items on
80
+ * another dimension throws (would silently shrink the matrix).
81
+ * - Duplicate (itemId, judgeName, dimension) records throw.
82
+ */
83
+ declare function corpusInterRaterAgreement(records: CorpusScoreRecord[], opts?: CorpusAgreementOptions): CorpusAgreementReport;
84
+ /**
85
+ * Convenience adapter for `JudgeScore[]` data keyed externally by item.
86
+ *
87
+ * Use when you have per-item arrays of `JudgeScore[]` (e.g. one
88
+ * `ScenarioResult.judgeScores` per scenario) and want corpus-wide
89
+ * agreement without manually flattening. `itemId` must be unique per
90
+ * row of `itemsScores`.
91
+ */
92
+ declare function corpusInterRaterAgreementFromJudgeScores(itemsScores: Array<{
93
+ itemId: string;
94
+ scores: JudgeScore[];
95
+ }>, opts?: CorpusAgreementOptions): CorpusAgreementReport;
96
+ //#endregion
97
+ //#region src/series-convergence.d.ts
98
+ /**
99
+ * Series convergence — detects whether a sequence of scalar measurements
100
+ * is stabilizing, drifting, or noisy. It reads drift *across* runs, e.g.
101
+ * "are my nightly eval scores stabilizing?".
102
+ *
103
+ * Three signals:
104
+ * - stabilized: last K values have low variance (< epsilon) — done
105
+ * - drifting: recent trend is monotonic and beyond noise — regressing or improving
106
+ * - noisy: neither — keep iterating, but flag as untrustworthy for gating
107
+ */
108
+ interface SeriesConvergenceOptions {
109
+ /** Window size for "recent" analysis (default 5). */
110
+ window?: number;
111
+ /** Coefficient-of-variation threshold below which the window is stabilized (default 0.05 = 5%). */
112
+ stableCv?: number;
113
+ /** Minimum monotone run length to call drift (default 3). */
114
+ driftRun?: number;
115
+ }
116
+ interface SeriesConvergenceResult {
117
+ state: 'stabilized' | 'drifting-up' | 'drifting-down' | 'noisy' | 'insufficient-data';
118
+ windowMean: number;
119
+ windowCv: number;
120
+ /** Longest monotonic run at the tail of the series (positive for up, negative for down). */
121
+ tailRun: number;
122
+ /** True when n ≥ window AND windowCv ≤ stableCv. */
123
+ stable: boolean;
124
+ }
125
+ declare function analyzeSeries(values: number[], options?: SeriesConvergenceOptions): SeriesConvergenceResult;
126
+ //#endregion
127
+ //#region src/meta-eval/sentinel.d.ts
128
+ declare const SENTINEL_METRIC_NAMES: readonly ['irr', 'calibrationKappa', 'sentinelPassRate'];
129
+ type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number];
130
+ interface SentinelMetrics {
131
+ /** Inter-rater reliability — ICC(2,1) from agreement instruments. */
132
+ irr?: number;
133
+ /** Weighted κ vs the human golden set (`calibrateJudge*`). */
134
+ calibrationKappa?: number;
135
+ /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */
136
+ sentinelPassRate?: number;
137
+ }
138
+ interface SentinelSnapshot {
139
+ /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */
140
+ at: string;
141
+ judgeId: string;
142
+ /** Exact model identity behind the judge (pin the full version string). */
143
+ judgeModel: string;
144
+ /**
145
+ * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a
146
+ * model-change marker — it records the new `judgeModel` immediately and
147
+ * the silent-upgrade alarm stays raised until a golden-grounded snapshot
148
+ * (calibrationKappa or sentinelPassRate) follows.
149
+ */
150
+ metrics: SentinelMetrics;
151
+ }
152
+ /** Identity + timestamp the caller supplies alongside an instrument output. */
153
+ interface SnapshotMeta {
154
+ at: string;
155
+ judgeId: string;
156
+ judgeModel: string;
157
+ }
158
+ /** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */
159
+ declare function validateSentinelSnapshot(snapshot: SentinelSnapshot, source?: string): void;
160
+ /**
161
+ * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the
162
+ * un-rounded continuous κ_w when the report carries one (integer κ
163
+ * discards information for [0,1] judges).
164
+ */
165
+ declare function snapshotFromCalibration(report: CalibrationResult | ContinuousCalibrationResult, meta: SnapshotMeta): SentinelSnapshot;
166
+ /**
167
+ * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`
168
+ * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability
169
+ * coefficient both instruments compute. For ensemble-level agreement,
170
+ * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its
171
+ * composition (e.g. a joined list of member model strings).
172
+ */
173
+ declare function snapshotFromAgreement(report: CorpusAgreementReport | ContinuousAgreement, meta: SnapshotMeta): SentinelSnapshot;
174
+ interface SentinelSetOptions {
175
+ /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */
176
+ tolerance?: number;
177
+ }
178
+ /**
179
+ * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the
180
+ * judge was originally calibrated on, re-scored periodically. Pass rate =
181
+ * fraction of joined items where the judge stays within `tolerance` of the
182
+ * human score. Items the judge didn't score are excluded from the
183
+ * denominator; zero joined items is an error, not a 0% pass rate.
184
+ */
185
+ declare function snapshotFromSentinelSet(scores: CandidateScore[], golden: GoldenItem[], meta: SnapshotMeta, options?: SentinelSetOptions): SentinelSnapshot;
186
+ interface SentinelStore {
187
+ append(snapshot: SentinelSnapshot): Promise<void>;
188
+ /** All snapshots (optionally for one judge), in append order. */
189
+ history(judgeId?: string): Promise<SentinelSnapshot[]>;
190
+ }
191
+ declare function inMemorySentinelStore(initial?: SentinelSnapshot[]): SentinelStore;
192
+ /**
193
+ * JSONL store — one snapshot per line, appended atomically per call.
194
+ * A corrupt or shape-invalid line is a loud error naming the file and
195
+ * line number: a sentinel history that silently drops records would
196
+ * defeat the drift detection it exists to provide.
197
+ */
198
+ declare function fileSentinelStore(path: string): SentinelStore;
199
+ interface SentinelThresholds {
200
+ /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */
201
+ minIrr?: number;
202
+ /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */
203
+ maxKappaDrop?: number;
204
+ /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */
205
+ maxSentinelDrop?: number;
206
+ /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */
207
+ staleAfterDays?: number;
208
+ }
209
+ interface JudgeSentinelOptions {
210
+ /** Caller-supplied ISO timestamp staleness is measured against. */
211
+ asOf: string;
212
+ thresholds?: SentinelThresholds;
213
+ /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */
214
+ convergence?: SeriesConvergenceOptions;
215
+ }
216
+ interface SentinelTrend {
217
+ judgeId: string;
218
+ metric: SentinelMetricName;
219
+ /** Verbatim `analyzeSeries` state for this judge×metric history. */
220
+ state: SeriesConvergenceResult['state'];
221
+ /** Newest value in the series. */
222
+ current: number;
223
+ /** Oldest value in the series — the reference the drop thresholds compare against. */
224
+ baseline: number;
225
+ /** current − baseline (signed; negative = decayed). */
226
+ drift: number;
227
+ alarmed: boolean;
228
+ reason?: string;
229
+ }
230
+ interface SentinelReport {
231
+ perJudge: SentinelTrend[];
232
+ alarms: string[];
233
+ healthy: boolean;
234
+ /**
235
+ * `judgeId:metric` pairs with too few snapshots for the convergence
236
+ * machine. Named, not counted — a blind spot you can't see is a blind
237
+ * spot you won't fix. Floor/drop checks still apply to thin series, so
238
+ * insufficient history alone never masks an alarm.
239
+ */
240
+ insufficientHistory: string[];
241
+ }
242
+ declare function judgeSentinelReport(history: SentinelSnapshot[], opts: JudgeSentinelOptions): SentinelReport;
243
+ interface EvalHealthStamp {
244
+ healthy: boolean;
245
+ alarms: string[];
246
+ }
247
+ /**
248
+ * The object a campaign attaches to its verdicts. Compute it from the
249
+ * sentinel report in a post-campaign hook (or a nightly job feeding the
250
+ * next day's campaigns) and store it alongside the verdict payload.
251
+ * `healthy: false` means the judges that produced those verdicts have an
252
+ * unresolved drift / decay / silent-upgrade / staleness alarm — treat the
253
+ * verdicts as carrying an integrity warning until recalibration clears it.
254
+ */
255
+ declare function evalHealthStamp(report: SentinelReport): EvalHealthStamp;
256
+ //#endregion
257
+ //#region src/meta-eval/judge-gate.d.ts
258
+ type OwnerVerdict = 'pass' | 'fail';
259
+ /** One item the owner decided, with where that decision is recorded. */
260
+ interface CalibrationExample {
261
+ /** Stable id of the decided item; a judge run names it in `exampleId`. */
262
+ id: string;
263
+ verdict: OwnerVerdict;
264
+ /** The person whose verdict this is. Never a model. */
265
+ labeledBy: string;
266
+ /** ISO-8601 time the verdict was given. */
267
+ labeledAt: string;
268
+ /** Where the verdict is recorded, e.g. `gtm:asset_decision:<id>`. */
269
+ source: string;
270
+ /** What the owner judged (an image digest, a run id), so a replay judges the same thing. */
271
+ evidenceRef?: string;
272
+ note?: string;
273
+ }
274
+ interface JudgeCalibrationSet {
275
+ judgeId: string;
276
+ /** Whose verdicts the judge stands in for. */
277
+ owner: string;
278
+ examples: readonly CalibrationExample[];
279
+ }
280
+ /**
281
+ * Validate a calibration set and return a normalized copy ordered by example
282
+ * id. Every verdict needs its person, time and source; ids are unique.
283
+ */
284
+ declare function registerCalibrationSet(set: JudgeCalibrationSet): JudgeCalibrationSet;
285
+ interface CalibrationMerge {
286
+ set: JudgeCalibrationSet;
287
+ /** Ids that joined the set. */
288
+ added: string[];
289
+ /** Ids whose verdict a later decision replaced. */
290
+ superseded: string[];
291
+ /** Ids whose incoming verdict was already recorded, or older than the recorded one. */
292
+ unchanged: string[];
293
+ }
294
+ /**
295
+ * Join new owner verdicts to a set. A verdict already recorded from the same
296
+ * source is unchanged, so ingestion can rerun. A later verdict on an item
297
+ * replaces an earlier one: the owner changed their mind, and the set keeps
298
+ * what they decided last.
299
+ */
300
+ declare function addCalibrationVerdicts(set: JudgeCalibrationSet, verdicts: readonly CalibrationExample[]): CalibrationMerge;
301
+ /** One gate decision the judge made on a calibration example. */
302
+ interface JudgeRun {
303
+ exampleId: string;
304
+ /** The judge's decision after its own sample aggregation (median, majority). */
305
+ verdict: OwnerVerdict;
306
+ /** The per-sample verdicts behind that decision, when the judge samples. */
307
+ samples?: readonly OwnerVerdict[];
308
+ }
309
+ interface JudgeRunMeta {
310
+ judgeId: string;
311
+ /** Exact model identity, or `deterministic` for a grader without one. */
312
+ judgeModel: string;
313
+ rubricVersion: string;
314
+ measuredAt: string;
315
+ }
316
+ interface JudgeConfusion {
317
+ /** Judge pass, owner pass. */
318
+ truePass: number;
319
+ /** Judge fail, owner fail. */
320
+ trueFail: number;
321
+ /** Judge pass, owner fail: the judge let through what the owner rejected. */
322
+ falsePass: number;
323
+ /** Judge fail, owner pass: the judge blocked what the owner accepted. */
324
+ falseFail: number;
325
+ }
326
+ interface JudgeExampleAgreement {
327
+ id: string;
328
+ verdict: OwnerVerdict;
329
+ runs: number;
330
+ /** Share of runs that passed. */
331
+ passRate: number;
332
+ /** Share of runs that reached the owner's verdict. */
333
+ agreement: number;
334
+ }
335
+ interface JudgeAgreement extends JudgeRunMeta {
336
+ owner: string;
337
+ /** Examples in the calibration set. */
338
+ examples: number;
339
+ /** Examples the judge ran on at least once. */
340
+ judged: number;
341
+ /** Judged examples per owner verdict. */
342
+ judgedByVerdict: Record<OwnerVerdict, number>;
343
+ runs: number;
344
+ /** Runs that reached the owner's verdict, over all runs; null with no runs. */
345
+ accuracy: number | null;
346
+ /**
347
+ * Exact (Clopper-Pearson) 95% interval for the share of judged examples on
348
+ * which every run reached the owner's verdict. Examples, not runs, are the
349
+ * independent units.
350
+ */
351
+ exampleAccuracy: {
352
+ agreed: number;
353
+ judged: number;
354
+ interval: ComputedInterval;
355
+ } | null;
356
+ /**
357
+ * Cohen's κ between the judge and the owner over runs. Null when undefined:
358
+ * no runs, or both sides used a single verdict.
359
+ */
360
+ kappa: number | null;
361
+ /** Runs that failed what the owner passed, over runs on owner passes; null with none. A veto judge is held to this. */
362
+ falseFailRate: number | null;
363
+ /** Runs that failed what the owner failed, over runs on owner fails; null with none. */
364
+ catchRate: number | null;
365
+ confusion: JudgeConfusion;
366
+ variance: {
367
+ /** Mean over judged examples of p(1 − p), p the example's run pass rate. 0 = no run changed its mind. */
368
+ betweenRuns: number | null;
369
+ /** Mean over runs that reported samples of p(1 − p) across those samples; null when none did. */
370
+ withinRun: number | null;
371
+ /** Examples whose runs disagree with each other. */
372
+ unstable: string[];
373
+ };
374
+ /** Examples with at least one run against the owner, least agreement first. */
375
+ disagreements: JudgeExampleAgreement[];
376
+ /** Examples without any run. */
377
+ unjudged: string[];
378
+ }
379
+ /**
380
+ * Agreement between a judge's runs and the owner's verdicts on one
381
+ * calibration set. A run that names an example outside the set is an error:
382
+ * a silently dropped run would overstate agreement.
383
+ */
384
+ declare function measureJudgeAgreement(set: JudgeCalibrationSet, runs: readonly JudgeRun[], meta: JudgeRunMeta): JudgeAgreement;
385
+ interface JudgeGatePolicy {
386
+ /**
387
+ * `verdict`: the judge passes and blocks, so accuracy and κ must hold.
388
+ * `veto`: it only blocks, so its false-fail rate on owner passes must hold.
389
+ */
390
+ decides: 'verdict' | 'veto';
391
+ /** Judged examples required before the judge may gate; for a veto judge, owner passes. */
392
+ minExamples: number;
393
+ /** Judged examples required of each owner verdict, so κ is defined. */
394
+ minPerVerdict: number;
395
+ /** Floor on run accuracy. */
396
+ minAccuracy: number;
397
+ /** Floor on Cohen's κ. */
398
+ minKappa: number;
399
+ /** Ceiling on a veto judge's false-fail rate. */
400
+ maxFalseFailRate: number;
401
+ /** A report older than this (days, vs `asOf`) no longer calibrates the judge. */
402
+ maxAgeDays: number;
403
+ /** Drift thresholds forwarded to `judgeSentinelReport` over the history. */
404
+ drift?: SentinelThresholds;
405
+ }
406
+ declare const DEFAULT_JUDGE_GATE_POLICY: Readonly<JudgeGatePolicy>;
407
+ type JudgeGateStatus = 'calibrated' | 'uncalibrated' | 'below-threshold' | 'drifted';
408
+ interface JudgeGateDecision {
409
+ judgeId: string;
410
+ judgeModel: string;
411
+ rubricVersion: string;
412
+ /** True only for `calibrated`. */
413
+ mayGate: boolean;
414
+ status: JudgeGateStatus;
415
+ /** Why the judge may not gate; empty when it may. */
416
+ reasons: string[];
417
+ agreement: JudgeAgreement | null;
418
+ policy: JudgeGatePolicy;
419
+ }
420
+ interface JudgeGateInput {
421
+ judgeId: string;
422
+ /** The model the judge runs now. */
423
+ judgeModel: string;
424
+ /** The rubric the judge runs now. */
425
+ rubricVersion: string;
426
+ /** The latest calibration report; null when the judge was never measured. */
427
+ agreement: JudgeAgreement | null;
428
+ asOf: string;
429
+ /** Sentinel snapshots for this judge, oldest first or in any order. */
430
+ history?: readonly SentinelSnapshot[];
431
+ policy?: Partial<JudgeGatePolicy>;
432
+ }
433
+ /** Whether a judge may gate now, and every reason it may not. */
434
+ declare function judgeGateDecision(input: JudgeGateInput): JudgeGateDecision;
435
+ /** Thrown by `assertJudgeMayGate`; carries the refused decision. */
436
+ declare class JudgeGateRefusedError extends JudgeError {
437
+ readonly decision: JudgeGateDecision;
438
+ constructor(decision: JudgeGateDecision);
439
+ }
440
+ /** Throw unless the decision lets the judge gate. */
441
+ declare function assertJudgeMayGate(decision: JudgeGateDecision): void;
442
+ /**
443
+ * The sentinel snapshot for one calibration run. A deciding judge records
444
+ * accuracy as `sentinelPassRate` and κ as `calibrationKappa` when it is
445
+ * defined; a veto judge records the share of owner passes it let through as
446
+ * `sentinelPassRate`. Append it to the judge's `SentinelStore`; the gate reads
447
+ * drift from that history.
448
+ */
449
+ declare function snapshotFromJudgeAgreement(agreement: JudgeAgreement, options?: {
450
+ decides?: JudgeGatePolicy['decides'];
451
+ }): SentinelSnapshot;
452
+ //#endregion
453
+ export { SentinelThresholds as A, validateSentinelSnapshot as B, JudgeSentinelOptions as C, SentinelSetOptions as D, SentinelReport as E, inMemorySentinelStore as F, CorpusAgreementPerDimension as G, SeriesConvergenceResult as H, judgeSentinelReport as I, corpusInterRaterAgreement as J, CorpusAgreementReport as K, snapshotFromAgreement as L, SnapshotMeta as M, evalHealthStamp as N, SentinelSnapshot as O, fileSentinelStore as P, snapshotFromCalibration as R, EvalHealthStamp as S, SentinelMetrics as T, analyzeSeries as U, SeriesConvergenceOptions as V, CorpusAgreementOptions as W, interRaterReliability as X, corpusInterRaterAgreementFromJudgeScores as Y, assertJudgeMayGate as _, JudgeCalibrationSet as a, registerCalibrationSet as b, JudgeGateDecision as c, JudgeGateRefusedError as d, JudgeGateStatus as f, addCalibrationVerdicts as g, OwnerVerdict as h, JudgeAgreement as i, SentinelTrend as j, SentinelStore as k, JudgeGateInput as l, JudgeRunMeta as m, CalibrationMerge as n, JudgeConfusion as o, JudgeRun as p, CorpusScoreRecord as q, DEFAULT_JUDGE_GATE_POLICY as r, JudgeExampleAgreement as s, CalibrationExample as t, JudgeGatePolicy as u, judgeGateDecision as v, SentinelMetricName as w, snapshotFromJudgeAgreement as x, measureJudgeAgreement as y, snapshotFromSentinelSet as z };
454
+ //# sourceMappingURL=judge-gate-BuQd7sSm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"judge-gate-BuQd7sSm.d.ts","names":[],"sources":["../src/statistics/agreement-irr.ts","../src/series-convergence.ts","../src/meta-eval/sentinel.ts","../src/meta-eval/judge-gate.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAyBgB,sBAAsB,aAAa;UA0ElC;;EAEf;;EAEA;;EAEA;;EAEA;;UAGe,oCAAoC;EACnD;;EAEA;;EAEA;;UAGe;;EAEf,cAAc;;EAEd;;EAEA;;EAEA;;EAEA;;UAGe,+BAA+B;;;;;;EAM9C;;;;;;EAMA;;;;;;;;;;;;;;;;;;iBAmBc,0BACd,SAAS,qBACT,OAAM,yBACL;;;;;;;;;iBA0Ha,yCACd,aAAa;EAAQ;EAAgB,QAAQ;IAC7C,OAAM,yBACL;;;;;;;;;;;;;UCvRc;;EAEf;;EAEA;;EAEA;;UAGe;EACf;EACA;EACA;;EAEA;;EAEA;;iBAGc,cACd,kBACA,UAAS,2BACR;;;cCoBG;KAEM,6BAA6B;UAExB;;EAEf;;EAEA;;EAEA;;UAGe;;EAEf;EACA;;EAEA;;;;;;;EAOA,SAAS;;;UAIM;EACf;EACA;EACA;;;iBAcc,yBAAyB,UAAU,kBAAkB;;;;;;iBAiCrD,wBACd,QAAQ,oBAAoB,6BAC5B,MAAM,eACL;;;;;;;;iBAmBa,sBACd,QAAQ,wBAAwB,qBAChC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