@remnic/bench 9.3.700 → 9.3.702

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1168,6 +1168,43 @@ interface BenchmarkArtifactEnvironment {
1168
1168
  /** Optional CPU architecture (arm64/x64/...). */
1169
1169
  arch?: string;
1170
1170
  }
1171
+ /**
1172
+ * Additive tier metadata (issue #1573). Local-lab regression runs (Tier L)
1173
+ * record `tier: "local"`; frontier leaderboard runs (Tier F) record
1174
+ * `"frontier"`. Omitted on older artifacts — consumers treat absence as
1175
+ * frontier for backwards compatibility (frontier is the historical default).
1176
+ */
1177
+ type BenchmarkArtifactTier = "local" | "frontier";
1178
+ /**
1179
+ * Hardware envelope for a local-lab run (issue #1573). Recorded so a Tier L
1180
+ * number is never conflated with a Tier F number: the GPU, VRAM, and model
1181
+ * quantization pin exactly what produced the result. Optional on all runs;
1182
+ * expected (and audited) on `tier: "local"` artifacts.
1183
+ */
1184
+ interface BenchmarkArtifactHardware {
1185
+ /** Short GPU product id, e.g. "NVIDIA RTX 3090". */
1186
+ gpu: string;
1187
+ /** VRAM in gigabytes (e.g. 24). */
1188
+ vramGb: number;
1189
+ /** Model quantization label, e.g. "Q4_K_M" or "AWQ-int4". */
1190
+ quantization: string;
1191
+ }
1192
+ /**
1193
+ * Cross-tier judge calibration result recorded on local artifacts (issue
1194
+ * #1573 PR3). The Cohen's kappa between the local and frontier judges over a
1195
+ * fixed calibration slice; below `threshold` the local judge is flagged
1196
+ * unreliable for the benchmark and `warning` is set.
1197
+ */
1198
+ interface BenchmarkArtifactJudgeCalibration {
1199
+ /** Cohen's kappa in [-1, 1] between local and frontier judge verdicts. */
1200
+ kappa: number;
1201
+ /** Number of paired judgements the kappa was computed over. */
1202
+ sampleSize: number;
1203
+ /** Kappa threshold below which `warning` is set. */
1204
+ threshold: number;
1205
+ /** True when `kappa < threshold` — local judge unreliable for this benchmark. */
1206
+ warning: boolean;
1207
+ }
1171
1208
  interface BenchmarkArtifactPerTaskScore {
1172
1209
  /** Runner-assigned task ID (stable across reruns). */
1173
1210
  taskId: string;
@@ -1203,6 +1240,24 @@ interface BenchmarkArtifact {
1203
1240
  /** Total wall-clock duration in milliseconds. */
1204
1241
  durationMs: number;
1205
1242
  env: BenchmarkArtifactEnvironment;
1243
+ /**
1244
+ * Two-tier provenance (issue #1573). `"local"` for local-lab regression
1245
+ * runs, `"frontier"` for leaderboard runs. Optional and additive: older
1246
+ * artifacts omit it.
1247
+ */
1248
+ tier?: BenchmarkArtifactTier;
1249
+ /**
1250
+ * Hardware envelope for local-lab runs (issue #1573). Optional; recorded
1251
+ * for `tier: "local"` artifacts so the GPU/VRAM/quantization that produced
1252
+ * a number travel with it.
1253
+ */
1254
+ hardware?: BenchmarkArtifactHardware;
1255
+ /**
1256
+ * Cross-tier judge calibration (issue #1573 PR3). The Cohen's kappa between
1257
+ * the local and frontier judges over the calibration slice; lands in
1258
+ * subsequent local artifacts after `remnic bench judge-calibrate`.
1259
+ */
1260
+ judgeCalibration?: BenchmarkArtifactJudgeCalibration;
1206
1261
  /** Optional explanatory note (e.g. "--limit 100"). Never contains PII. */
1207
1262
  note?: string;
1208
1263
  }
@@ -1219,6 +1274,12 @@ interface BuildBenchmarkArtifactInput {
1219
1274
  categoryFor?: (task: TaskResult) => string | undefined;
1220
1275
  /** Optional free-form note (e.g. `"--limit 100"`). */
1221
1276
  note?: string;
1277
+ /** Optional two-tier provenance tag (issue #1573). */
1278
+ tier?: BenchmarkArtifactTier;
1279
+ /** Optional hardware envelope for local-lab runs (issue #1573). */
1280
+ hardware?: BenchmarkArtifactHardware;
1281
+ /** Optional cross-tier judge calibration result (issue #1573 PR3). */
1282
+ judgeCalibration?: BenchmarkArtifactJudgeCalibration;
1222
1283
  }
1223
1284
  /**
1224
1285
  * Build a `BenchmarkArtifact` from a runner's `BenchmarkResult`.
@@ -2866,6 +2927,219 @@ declare const chatFixture: FixtureGenerator;
2866
2927
  declare const SEALED_PROMPT_REGISTRY: Readonly<Record<string, string>>;
2867
2928
  declare const DEFAULT_ASSISTANT_RUBRIC_ID = "assistant-rubric-v1";
2868
2929
 
2930
+ /**
2931
+ * Cohen's kappa — inter-rater agreement for the cross-tier judge calibration
2932
+ * (issue #1573 PR3).
2933
+ *
2934
+ * The local-lab protocol (#1573) needs a single number that says whether the
2935
+ * cheap local judge agrees with the expensive frontier judge closely enough to
2936
+ * trust it for regression runs. Cohen's kappa is the standard measure: it
2937
+ * corrects raw agreement for the agreement you would see by chance, so a
2938
+ * reported 0.9 on a binary task where both judges say "correct" 95% of the
2939
+ * time is not actually impressive.
2940
+ *
2941
+ * This module is pure: it operates on parallel arrays of category labels and
2942
+ * has no I/O, no globals, and no module-level mutable state (rule 11). The
2943
+ * calibration orchestration that turns numeric judge scores into labels and
2944
+ * drives both judges lives in `./calibration-slice.ts`.
2945
+ */
2946
+ /** A rater-assigned category label. Free-form string (e.g. "correct"). */
2947
+ type JudgeCategory = string;
2948
+ interface CohenKappaResult {
2949
+ /** Cohen's kappa in [-1, 1]. 1 = perfect agreement, 0 = chance, <0 = systematic disagreement. */
2950
+ kappa: number;
2951
+ /** Observed proportional agreement (fraction of identical labels). In [0, 1]. */
2952
+ observedAgreement: number;
2953
+ /** Expected chance agreement given the marginal distributions. In [0, 1]. */
2954
+ expectedAgreement: number;
2955
+ /** Number of paired judgements. */
2956
+ sampleSize: number;
2957
+ /** Distinct category labels seen across both raters (sorted). */
2958
+ categories: readonly JudgeCategory[];
2959
+ }
2960
+ /**
2961
+ * Compute Cohen's kappa from two parallel arrays of category labels.
2962
+ *
2963
+ * Throws when the arrays have mismatched lengths or are empty — kappa on zero
2964
+ * samples is meaningless and callers should surface that as an operator error
2965
+ * rather than a fabricated 0.
2966
+ *
2967
+ * Degenerate case: when every item lands in a single category for both raters,
2968
+ * the chance-agreement denominator collapses to zero. By convention perfect
2969
+ * agreement in that case returns kappa = 1 (the raters agreed on everything;
2970
+ * there just was nothing to distinguish). Imperfect agreement with a zero
2971
+ * denominator is impossible (a single shared category forces agreement), so
2972
+ * the branch is unreachable for well-formed input — but the guard keeps the
2973
+ * function total and returns 0 defensively.
2974
+ */
2975
+ declare function computeCohensKappa(raterA: readonly JudgeCategory[], raterB: readonly JudgeCategory[]): CohenKappaResult;
2976
+ /** Default correct/incorrect decision threshold for a 0..1 judge score. */
2977
+ declare const DEFAULT_JUDGE_BINARIZATION_THRESHOLD = 0.5;
2978
+ /**
2979
+ * Map a numeric judge score to a binary "correct"/"incorrect" category label.
2980
+ * Scores ≥ threshold → "correct"; otherwise "incorrect". Non-finite scores
2981
+ * (NaN/Infinity from a broken judge) are bucketed as "incorrect" so a single
2982
+ * bad verdict does not crash calibration — they still count as disagreement
2983
+ * against a finite frontier verdict.
2984
+ */
2985
+ declare function binarizeJudgeScore(score: number, threshold?: number): JudgeCategory;
2986
+
2987
+ /**
2988
+ * Cross-tier judge calibration — issue #1573 PR3.
2989
+ *
2990
+ * The two-tier protocol (#1573) trusts local-judge numbers for regression only
2991
+ * when the local judge agrees with the frontier judge closely enough. This
2992
+ * module owns three things:
2993
+ *
2994
+ * 1. A deterministic, content-free calibration slice — a reproducible
2995
+ * selection of question ids per benchmark. The slice is "committed" in
2996
+ * the sense that the selection algorithm is fixed and content-free
2997
+ * (rule: no dataset content in repo per docs/benchmarks.md ethics): the
2998
+ * same universe of question ids always yields the same slice, so two
2999
+ * operators running the same dataset compare the same questions.
3000
+ * 2. `runJudgeCalibration` — runs both judges over the slice's cached
3001
+ * answers, bins each verdict to a category, and reports Cohen's kappa.
3002
+ * 3. The kappa threshold + warning that downstream local artifacts carry
3003
+ * (see the `judgeCalibration` field on `BenchmarkArtifact`).
3004
+ *
3005
+ * The module is I/O-free except for the judge calls the caller injects; it has
3006
+ * no module-level mutable state (rule 11) and never interpolates model/answer
3007
+ * text into shell strings (rule 10).
3008
+ */
3009
+
3010
+ /**
3011
+ * Judge identities recorded alongside a persisted calibration so a later run
3012
+ * can verify the kappa was computed for the SAME judge pair (issue #1573 PR3,
3013
+ * codex P2 review). Without this binding, a run that swaps the local-lab
3014
+ * manifest or the frontier judge would inherit a stale kappa computed for a
3015
+ * different pair.
3016
+ */
3017
+ interface JudgeCalibrationIdentities {
3018
+ localJudgeProvider: string;
3019
+ localJudgeModel: string;
3020
+ frontierJudgeProvider: string;
3021
+ frontierJudgeModel: string;
3022
+ }
3023
+ /**
3024
+ * The full persisted calibration record as loaded from disk: the artifact
3025
+ * subset plus the (optional) judge identities that produced it. Identities
3026
+ * are optional because state files written before they existed still load —
3027
+ * the attach path treats absent identities as "unbound, attach anyway" to
3028
+ * preserve backwards compatibility.
3029
+ */
3030
+ type LoadedJudgeCalibrationState = BenchmarkArtifactJudgeCalibration & Partial<JudgeCalibrationIdentities>;
3031
+ /**
3032
+ * Fixed slice size per benchmark. The issue specifies a 50-question slice; a
3033
+ * benchmark with fewer available questions uses all of them.
3034
+ */
3035
+ declare const CALIBRATION_SLICE_SIZE = 50;
3036
+ /**
3037
+ * Minimum number of completed tasks a stored result must have to be a valid
3038
+ * calibration source (codex P2 review). A `--limit 1` full run produces
3039
+ * `mode === "full"` with a single task, yielding a degenerate one-sample κ
3040
+ * (often 1.0). Below this floor, Cohen's kappa is statistically meaningless.
3041
+ * Benchmarks with fewer total questions are unaffected — the slice uses all
3042
+ * available tasks, but a capped run of a larger benchmark is rejected.
3043
+ */
3044
+ declare const MIN_CALIBRATION_SOURCE_TASKS = 10;
3045
+ /**
3046
+ * Kappa below this triggers a loud "local judge unreliable for this
3047
+ * benchmark" warning in the report and on the artifact. 0.7 is the
3048
+ * conventional "substantial agreement" cut-off (Landis & Koch 1977).
3049
+ */
3050
+ declare const JUDGE_CALIBRATION_KAPPA_THRESHOLD = 0.7;
3051
+ /** A cached answer the calibration runs both judges over. */
3052
+ interface CalibrationAnswer {
3053
+ /** Stable question id (matches `BenchmarkArtifactPerTaskScore.taskId`). */
3054
+ questionId: string;
3055
+ /** The prompt/question text the responder was asked. */
3056
+ question: string;
3057
+ /** The responder's produced answer text. */
3058
+ predicted: string;
3059
+ /** The reference / gold answer text. */
3060
+ expected: string;
3061
+ }
3062
+ /** Per-question verdict pair produced while running calibration. */
3063
+ interface CalibrationVerdictPair {
3064
+ questionId: string;
3065
+ localCategory: JudgeCategory;
3066
+ frontierCategory: JudgeCategory;
3067
+ }
3068
+ interface RunJudgeCalibrationOptions {
3069
+ /** Benchmark id the calibration is scoped to (recorded in the result). */
3070
+ benchmarkId: string;
3071
+ /** The cheap local-lab judge (Tier L). */
3072
+ localJudge: BenchJudge;
3073
+ /** The expensive frontier judge (Tier F) — the gold standard. */
3074
+ frontierJudge: BenchJudge;
3075
+ /** Cached answers to judge; the slice is selected from these by question id. */
3076
+ answers: readonly CalibrationAnswer[];
3077
+ /**
3078
+ * Maps a numeric judge score to a category label. Defaults to
3079
+ * `binarizeJudgeScore` (correct/incorrect at 0.5). Both judges share one
3080
+ * binning function so they are compared on the same scale.
3081
+ */
3082
+ binScore?: (score: number) => JudgeCategory;
3083
+ /** Override the slice size (default 50; mainly for tests). */
3084
+ sliceSize?: number;
3085
+ /** Override the warning threshold (default 0.7). */
3086
+ threshold?: number;
3087
+ }
3088
+ interface JudgeCalibrationResult extends CohenKappaResult {
3089
+ benchmarkId: string;
3090
+ /** Question ids that made up the calibrated slice. */
3091
+ sliceQuestionIds: readonly string[];
3092
+ /** Configured warning threshold. */
3093
+ threshold: number;
3094
+ /** True when `kappa < threshold` — local judge is unreliable for this benchmark. */
3095
+ warning: boolean;
3096
+ /** Per-question verdict pairs, in slice order. */
3097
+ verdicts: readonly CalibrationVerdictPair[];
3098
+ }
3099
+ /**
3100
+ * Select the calibration slice from a universe of question ids.
3101
+ *
3102
+ * The selection is deterministic and content-free: ids are ordered by the
3103
+ * hex digest of `sha256(id)` and the first `size` are taken. This commits the
3104
+ * slice to a fixed algorithm rather than a hardcoded id list (which we cannot
3105
+ * ship without the dataset). Same universe → same slice, every time, across
3106
+ * operators and reruns — so the slice is reproducible and comparable.
3107
+ */
3108
+ declare function selectCalibrationSlice(questionIds: readonly string[], size?: number): string[];
3109
+ /**
3110
+ * Run both judges over the calibration slice and report Cohen's kappa.
3111
+ *
3112
+ * For each answer in the slice the local and frontier judges each score
3113
+ * `(question, predicted, expected)`; each numeric score is binned to a
3114
+ * category (default: correct/incorrect) and the two parallel category arrays
3115
+ * feed `computeCohensKappa`. The result is exactly the value that lands in
3116
+ * subsequent local artifacts' `judgeCalibration.kappa`.
3117
+ */
3118
+ declare function runJudgeCalibration(options: RunJudgeCalibrationOptions): Promise<JudgeCalibrationResult>;
3119
+ /**
3120
+ * Persist a calibration result so subsequent local artifacts can carry the
3121
+ * kappa (issue #1573 done-when: "a kappa number that lands in subsequent
3122
+ * local artifacts"). The state is a single JSON file per benchmark under
3123
+ * `<calibrationDir>/<benchmarkId>.json`, written atomically via temp-write-
3124
+ * then-rename (cursor review: a direct writeFile can leave truncated JSON on
3125
+ * crash, which loadJudgeCalibrationState would silently drop as a miss).
3126
+ *
3127
+ * Only the artifact-relevant subset (`BenchmarkArtifactJudgeCalibration`) is
3128
+ * persisted — never the per-question verdicts or answer text (repo ethics +
3129
+ * rule 10: nothing interpolated into shell). Optional `identities` record the
3130
+ * judge pair that produced the kappa so a later run can refuse a stale kappa
3131
+ * for a different pair (codex P2 review); omitted on pre-binding state files.
3132
+ */
3133
+ declare function writeJudgeCalibrationState(result: JudgeCalibrationResult, calibrationDir: string, identities?: JudgeCalibrationIdentities): Promise<string>;
3134
+ /**
3135
+ * Load a previously persisted calibration result for a benchmark. Returns
3136
+ * `undefined` when no calibration has been run yet (the run path treats
3137
+ * absence as "no calibration recorded" and omits `judgeCalibration` from
3138
+ * the artifact). A corrupt/unparseable file is a miss returning `undefined`,
3139
+ * never a crash (rule 34) — the operator re-runs `judge-calibrate`.
3140
+ */
3141
+ declare function loadJudgeCalibrationState(benchmarkId: string, calibrationDir: string): Promise<LoadedJudgeCalibrationState | undefined>;
3142
+
2869
3143
  /**
2870
3144
  * Shared runner scaffolding for the Assistant bench tier.
2871
3145
  *
@@ -3558,4 +3832,4 @@ interface MitigatedTargetConfig {
3558
3832
  */
3559
3833
  declare function createMitigatedTarget(config: MitigatedTargetConfig): ExtractionAttackTarget;
3560
3834
 
3561
- export { AMA_BENCH_DIAGNOSTIC_VARIANTS, ASSISTANT_AGENT_CONFIG_KEY, ASSISTANT_JUDGE_CONFIG_KEY, ASSISTANT_MEETING_PREP_SCENARIOS, ASSISTANT_MEETING_PREP_SMOKE_SCENARIOS, ASSISTANT_MORNING_BRIEF_SCENARIOS, ASSISTANT_MORNING_BRIEF_SMOKE_SCENARIOS, ASSISTANT_NEXT_BEST_ACTION_SCENARIOS, ASSISTANT_NEXT_BEST_ACTION_SMOKE_SCENARIOS, ASSISTANT_RUBRIC_DIMENSIONS, ASSISTANT_RUBRIC_ID_KEY, ASSISTANT_SEEDS_CONFIG_KEY, ASSISTANT_SPOT_CHECK_DIR_KEY, ASSISTANT_SYNTHESIS_SCENARIOS, ASSISTANT_SYNTHESIS_SMOKE_SCENARIOS, type AbstentionRetrievalCase, type AggregateMetrics, type AmaBenchDiagnosticAdapterOptions, type AmaBenchDiagnosticAnswererMode, type AmaBenchDiagnosticBreakdown, type AmaBenchDiagnosticMatrixArtifact, type AmaBenchDiagnosticRecallMode, type AmaBenchDiagnosticRunContext, type AmaBenchDiagnosticTaskEvidence, type AmaBenchDiagnosticTaskRow, type AmaBenchDiagnosticVariant, type AmaBenchDiagnosticVariantSummary, type AnthropicProviderConfig, type AssistantAgent, type AssistantMemoryFact, type AssistantMemoryGraph, type AssistantRubricDimension, type AssistantRubricScores, type AssistantRunnerOptions, type AssistantScenario, type AssistantStance, type AttackRecallOptions, type AttackRetrievalHit, type AttackerMode, BENCHMARK_ARTIFACT_SCHEMA_VERSION, BENCHMARK_INTEGRITY_META_SCHEMA, BENCHMARK_REPRO_MANIFEST_FILENAME, BENCHMARK_REPRO_MANIFEST_SCHEMA_VERSION, BENCHMARK_RESULT_SCHEMA, BENCHMARK_SPLIT_TYPES, type BaselineRow, type BaselineScenario, type BeamDatasetPreview, type BenchConfig, type BenchJudge, type BenchJudgeResult, type BenchMemoryAdapter, type BenchModelSource, type BenchReasoningEffort, type BenchRecallOptions, type BenchResponder, type BenchResponse, type BenchRuntimeProfile, type BenchTier, type BenchmarkArtifact, type BenchmarkArtifactEnvironment, type BenchmarkArtifactPerTaskScore, type BenchmarkArtifactSystem, type BenchmarkCategory, type BenchmarkDefinition, type BenchmarkIntegrityMeta, type BenchmarkMeta, type BenchmarkMode, type BenchmarkReport, type BenchmarkReproManifest, type BenchmarkReproManifestDataset, type BenchmarkReproManifestFile, type BenchmarkReproManifestResult, type BenchmarkResult, type BenchmarkSplitType, type BenchmarkStatus, type BenchmarkSuiteResult, type BenchmarkTier, type BuildBenchmarkArtifactInput, type BuildBenchmarkPublishFeedOptions, type BuildBenchmarkReproManifestOptions, type BuiltInProvider, CANARY_FIXED_RECALL, CANARY_SCORE_FLOOR, type CanaryAdapterOptions, type CanaryFloorCheck, type CodexCliProviderConfig, type ComparisonMetricDelta, type ComparisonResult, type CompletionOpts, type CompletionResult, type ConfidenceInterval, type ContaminationCheckResult, type ContaminationEntry, type ContaminationManifest, type CustomBenchmarkScoring, type CustomBenchmarkSpec, type CustomBenchmarkTask, DEFAULT_ABLATION_BOOTSTRAP_SEED, DEFAULT_ASSISTANT_RUBRIC_ID, DEFAULT_BASELINE_SCENARIOS, type DatasetSource, type DiscoveredModel, EMPTY_CONTAMINATION_MANIFEST, type EffectSizeInterpretation, type EffectSizeSummary, type ExplainResult, type ExtractedEntity, type ExtractedLink, type ExtractedPage, type ExtractionAttackOptions, type ExtractionAttackResult, type ExtractionAttackTarget, type FixtureGenerator, type FixtureOutput, type FixtureVariant, type GeneratedFile, type GoldEntity, type GoldEntityType, type GoldGraph, type GoldLink, type GoldPage, type HarnessRng, INTEGRITY_CIPHER_ALGORITHM, INTEGRITY_HASH_ALGORITHM, INTEGRITY_META_FIELDS, type IngestionBenchAdapter, type IngestionLog, LOCAL_LAB_PROVIDER_KINDS, LOCOMO_DATASET_FILENAMES, LONG_MEM_EVAL_DATASET_FILENAMES, type LeaderboardArtifactWrite, type LlmJudge, type LlmProvider, type LoadDatasetOptions, type LoadSealedQrelsOptions, type LoadedDataset, type LocalLabManifest, type LocalLabManifestNotes, type LocalLabPhase, type LocalLabPhaseDescriptor, type LocalLabPhaseExecute, type LocalLabPhaseName, type LocalLabPhaseOutcome, LocalLabPreflightError, type LocalLabPreflightFailure, type LocalLabPreflightInput, type LocalLabPreflightOptions, type LocalLabPreflightResult, type LocalLabPreflightSuccess, type LocalLabProviderKind, type LocalLabRoleConfig, type LocalLlmProviderConfig, MEMORY_EVAL_DIMENSIONS, MEMORY_EVAL_PUBLIC_LINE, MITIGATED_BASELINE_SCENARIOS, type MemoryEvalCategory, type MemoryEvalDimension, type MemoryEvalDimensionId, type MemoryEvalMetric, type MemoryGraph, type MemoryStats, type MemorySystem, type Message, type MetricAggregate, type MitigatedBaselineConfig, type MitigatedTargetConfig, type MultipleChoiceQuestion, OTHER_NAMESPACE_MEMORIES, type OllamaProviderConfig, type OpenAiCompatibleProviderConfig, PROCEDURAL_REAL_SCENARIOS, PROCEDURAL_REAL_SCENARIOS_SMOKE, PUBLISHED_BENCHMARK_ARTIFACT_IDS, type PersonalizationRetrievalCase, type PreflightDiscoveredModel, type ProceduralAblationArtifact, type ProceduralAblationPerCase, type ProceduralAblationScenario, type ProceduralRealScenario, type ProceduralRealScenarioCategory, type ProviderBaseConfig, type ProviderConfig, type ProviderDiscoveryResult, type ProviderFactoryConfig, type PublishSkipReason, type PublishSkipRecord, type PublishedBenchmarkFeed, type PublishedBenchmarkFeedEntry, type PublishedBenchmarkId, REQUIRED_FRONTMATTER_FIELDS, type RecallMetrics, type RecoveredMemory, type RegressionDetail, type RegressionGateResult, type RemnicAdapterOptions, type ResolveBenchRuntimeProfileOptions, type ResolvedBenchRuntimeProfile, type ResolvedLocalLabProfile, type ResolvedLocalLabRole, type ResolvedRunBenchmarkOptions, type RotatedChoices, type RunBenchmarkOptions, type RunProceduralAblationCliArgs, type RunProceduralAblationOptions, type RunSequentialPhasesOptions, SCHEMA_TIER_FIXTURE, SCHEMA_TIER_SMOKE_FIXTURE, SEALED_PROMPT_REGISTRY, SYNTHETIC_MEMORIES, type SanitizedDiagnosticProvider, type SavedBaseline, type SchemaTierCorpus, type SchemaTierFixture, type SchemaTierName, type SchemaTierPage, type SchemaTierPageFrontmatter, type SealedArtifact, type SealedJudgeDecision, type SealedJudgeInput, type SealedQrelsArtifact, type SealedQrelsHandle, type SealedRubric, type SearchResult, type SeededMemory, type SeededRng, type SequentialPhaseHooks, type SpotCheckLogger, type StatisticalReport, type StructuredJudge, type SyntheticEmailIngestionAdapterOptions, type SyntheticTargetOptions, type TaskResult, type TaskTokenUsage, type TemporalRetrievalCase, type TierDetail, type TimelineEntry, type TokenUsage, type WriteBenchmarkArtifactResult, addContaminationEntry, aggregateTaskScores, answerBenchmarkQuestion, assertCanaryUnderFloor, assertIntegrityMetaPresent, assertPublishableIntegrity, assertSha256Hex, assistantMeetingPrepDefinition, assistantMorningBriefDefinition, assistantNextBestActionDefinition, assistantSynthesisDefinition, backlinkF1, bootstrapMeanConfidenceInterval, buildAmaBenchDiagnosticMatrixArtifact, buildAmaBenchDiagnosticVariantSummary, buildAmaBenchLeaderboardRows, buildBenchmarkArtifact, buildBenchmarkArtifactFilename, buildBenchmarkPublishFeed, buildBenchmarkReproManifest, buildBenchmarkRunSeeds, buildJudgePayload, buildOracleTrajectoryRecall, buildSchemaTierFixture, buildSchemaTierSmokeFixture, calendarFixture, canonicalJsonStringify, chatFixture, checkDatasetContamination, checkRegression, clampScore, cohensD, compareResults, computeSealHash, containsAnswer, createSeededRng as createAdamSeededRng, createAmaBenchDiagnosticAdapter, createAnthropicProvider, createCanaryAdapter, createCodexCliProvider, createDeterministicSpotCheckLogger, createGatewayResponder, createLightweightAdapter, createLiteLlmProvider, createLocalLlmProvider, createMitigatedTarget, createOllamaProvider, createOpenAiCompatibleProvider, createSeededRandom as createProceduralAblationSeededRandom, createProvider, createProviderBackedAmaBenchRecommendedJudge, createProviderBackedJudge, createProviderBackedResponder, createProviderBackedStructuredJudge, createRemnicAdapter, createResponderFromProvider, createSeededRng$1 as createSeededRng, createSpotCheckFileLogger, createStructuredJudgeFromProvider, createSyntheticEmailIngestionAdapter, createSyntheticTarget, createTimeoutGuardedAdapter, defaultBenchmarkBaselineDir, defaultBenchmarkPublishPath, deleteBenchmarkResults, discoverAllProviders, discoveryEndpointFor, emailFixture, entityRecall, exactMatch, extractMarkdownSectionsByTitle, f1Score, fixtureToAblationScenarios, formatHandoffNote, formatMissingDatasetError, generateReport, getBenchmark, getBenchmarkLowerIsBetter, getMemoryEvalDimension, getRemnicVersion, hashBenchmarkArtifact, hashBytes, hashCanonicalJson, hashString, integrityMetaIsComplete, interpretEffectSize, isAmaBenchUnknownLikeAnswer, isContaminationEntry, isContaminationManifest, isSealedQrelsArtifact, isSha256Hex, linkMatches, listBenchmarkBaselines, listBenchmarkResults, listBenchmarks, listMemoryEvalBenchmarkIds, listMemoryEvalDimensions, llmJudgeScore, llmJudgeScoreDetailed, loadAblationFixture, loadBaseline, loadBeamDatasetPreview, loadBenchmarkArtifact, loadBenchmarkBaseline, loadBenchmarkResult, loadCustomBenchmarkFile, loadLoCoMo10, loadLocalLabManifest, loadLongMemEvalS, loadSealKeyFromEnv, loadSealedQrels, loadSealedRubric, matchEntity, mergeContaminationManifests, openSeal, orchestrateBenchmarkRuns, pairedDeltaConfidenceInterval, parseBenchmarkArtifact, parseCustomBenchmark, parseLocalLabManifest, parseRubricResponse, parseSealedQrels, precisionAtK, preflightLocalLabRole, projectFolderFixture, recallAtK, redactBenchmarkResultSecrets, renderBaselineMarkdown, renderBenchmarkResultExport, renderMemorySummaryForJudge, renderMemoryViewForAgent, resolveAssistantAgent, resolveAssistantRubricId, resolveAssistantSeeds, resolveAssistantSpotCheckDir, resolveBenchRuntimeProfile, resolveBenchmarkPhaseTimeoutMs, resolveBenchmarkProgressLogging, resolveBenchmarkResultReference, resolveBenchmarkRunCount, resolveLocalLabProfile, resolveLocalLabRole, resolveStructuredJudge, rotateDistractors, rougeL, runAssistantBenchmark, runAssistantMeetingPrepBenchmark, runAssistantMorningBriefBenchmark, runAssistantNextBestActionBenchmark, runAssistantSynthesisBenchmark, runBaseline, runBenchSuite, runBenchmark, runCustomBenchmarkFile, runExplain, runExtractionAttack, runMitigatedBaseline, runProceduralAblation, runProceduralAblationCli, runSealedJudge, runSequentialPhases, safeHexEqual, saveBaseline, saveBenchmarkBaseline, schemaCompleteness, sealPayload, selectAmaBenchDiagnosticVariants, selectFixtureVariant, serializeBenchmarkArtifact, serializeJsonl, serializeSealedQrels, shuffleTasks, timed, verifyRubricDigest, writeBenchmarkArtifact, writeBenchmarkPublishFeed, writeBenchmarkReproManifest, writeBenchmarkResult, writeLeaderboardArtifactsForResult, zeroScores };
3835
+ export { AMA_BENCH_DIAGNOSTIC_VARIANTS, ASSISTANT_AGENT_CONFIG_KEY, ASSISTANT_JUDGE_CONFIG_KEY, ASSISTANT_MEETING_PREP_SCENARIOS, ASSISTANT_MEETING_PREP_SMOKE_SCENARIOS, ASSISTANT_MORNING_BRIEF_SCENARIOS, ASSISTANT_MORNING_BRIEF_SMOKE_SCENARIOS, ASSISTANT_NEXT_BEST_ACTION_SCENARIOS, ASSISTANT_NEXT_BEST_ACTION_SMOKE_SCENARIOS, ASSISTANT_RUBRIC_DIMENSIONS, ASSISTANT_RUBRIC_ID_KEY, ASSISTANT_SEEDS_CONFIG_KEY, ASSISTANT_SPOT_CHECK_DIR_KEY, ASSISTANT_SYNTHESIS_SCENARIOS, ASSISTANT_SYNTHESIS_SMOKE_SCENARIOS, type AbstentionRetrievalCase, type AggregateMetrics, type AmaBenchDiagnosticAdapterOptions, type AmaBenchDiagnosticAnswererMode, type AmaBenchDiagnosticBreakdown, type AmaBenchDiagnosticMatrixArtifact, type AmaBenchDiagnosticRecallMode, type AmaBenchDiagnosticRunContext, type AmaBenchDiagnosticTaskEvidence, type AmaBenchDiagnosticTaskRow, type AmaBenchDiagnosticVariant, type AmaBenchDiagnosticVariantSummary, type AnthropicProviderConfig, type AssistantAgent, type AssistantMemoryFact, type AssistantMemoryGraph, type AssistantRubricDimension, type AssistantRubricScores, type AssistantRunnerOptions, type AssistantScenario, type AssistantStance, type AttackRecallOptions, type AttackRetrievalHit, type AttackerMode, BENCHMARK_ARTIFACT_SCHEMA_VERSION, BENCHMARK_INTEGRITY_META_SCHEMA, BENCHMARK_REPRO_MANIFEST_FILENAME, BENCHMARK_REPRO_MANIFEST_SCHEMA_VERSION, BENCHMARK_RESULT_SCHEMA, BENCHMARK_SPLIT_TYPES, type BaselineRow, type BaselineScenario, type BeamDatasetPreview, type BenchConfig, type BenchJudge, type BenchJudgeResult, type BenchMemoryAdapter, type BenchModelSource, type BenchReasoningEffort, type BenchRecallOptions, type BenchResponder, type BenchResponse, type BenchRuntimeProfile, type BenchTier, type BenchmarkArtifact, type BenchmarkArtifactEnvironment, type BenchmarkArtifactHardware, type BenchmarkArtifactJudgeCalibration, type BenchmarkArtifactPerTaskScore, type BenchmarkArtifactSystem, type BenchmarkArtifactTier, type BenchmarkCategory, type BenchmarkDefinition, type BenchmarkIntegrityMeta, type BenchmarkMeta, type BenchmarkMode, type BenchmarkReport, type BenchmarkReproManifest, type BenchmarkReproManifestDataset, type BenchmarkReproManifestFile, type BenchmarkReproManifestResult, type BenchmarkResult, type BenchmarkSplitType, type BenchmarkStatus, type BenchmarkSuiteResult, type BenchmarkTier, type BuildBenchmarkArtifactInput, type BuildBenchmarkPublishFeedOptions, type BuildBenchmarkReproManifestOptions, type BuiltInProvider, CALIBRATION_SLICE_SIZE, CANARY_FIXED_RECALL, CANARY_SCORE_FLOOR, type CalibrationAnswer, type CalibrationVerdictPair, type CanaryAdapterOptions, type CanaryFloorCheck, type CodexCliProviderConfig, type CohenKappaResult, type ComparisonMetricDelta, type ComparisonResult, type CompletionOpts, type CompletionResult, type ConfidenceInterval, type ContaminationCheckResult, type ContaminationEntry, type ContaminationManifest, type CustomBenchmarkScoring, type CustomBenchmarkSpec, type CustomBenchmarkTask, DEFAULT_ABLATION_BOOTSTRAP_SEED, DEFAULT_ASSISTANT_RUBRIC_ID, DEFAULT_BASELINE_SCENARIOS, DEFAULT_JUDGE_BINARIZATION_THRESHOLD, type DatasetSource, type DiscoveredModel, EMPTY_CONTAMINATION_MANIFEST, type EffectSizeInterpretation, type EffectSizeSummary, type ExplainResult, type ExtractedEntity, type ExtractedLink, type ExtractedPage, type ExtractionAttackOptions, type ExtractionAttackResult, type ExtractionAttackTarget, type FixtureGenerator, type FixtureOutput, type FixtureVariant, type GeneratedFile, type GoldEntity, type GoldEntityType, type GoldGraph, type GoldLink, type GoldPage, type HarnessRng, INTEGRITY_CIPHER_ALGORITHM, INTEGRITY_HASH_ALGORITHM, INTEGRITY_META_FIELDS, type IngestionBenchAdapter, type IngestionLog, JUDGE_CALIBRATION_KAPPA_THRESHOLD, type JudgeCalibrationIdentities, type JudgeCalibrationResult, type JudgeCategory, LOCAL_LAB_PROVIDER_KINDS, LOCOMO_DATASET_FILENAMES, LONG_MEM_EVAL_DATASET_FILENAMES, type LeaderboardArtifactWrite, type LlmJudge, type LlmProvider, type LoadDatasetOptions, type LoadSealedQrelsOptions, type LoadedDataset, type LoadedJudgeCalibrationState, type LocalLabManifest, type LocalLabManifestNotes, type LocalLabPhase, type LocalLabPhaseDescriptor, type LocalLabPhaseExecute, type LocalLabPhaseName, type LocalLabPhaseOutcome, LocalLabPreflightError, type LocalLabPreflightFailure, type LocalLabPreflightInput, type LocalLabPreflightOptions, type LocalLabPreflightResult, type LocalLabPreflightSuccess, type LocalLabProviderKind, type LocalLabRoleConfig, type LocalLlmProviderConfig, MEMORY_EVAL_DIMENSIONS, MEMORY_EVAL_PUBLIC_LINE, MIN_CALIBRATION_SOURCE_TASKS, MITIGATED_BASELINE_SCENARIOS, type MemoryEvalCategory, type MemoryEvalDimension, type MemoryEvalDimensionId, type MemoryEvalMetric, type MemoryGraph, type MemoryStats, type MemorySystem, type Message, type MetricAggregate, type MitigatedBaselineConfig, type MitigatedTargetConfig, type MultipleChoiceQuestion, OTHER_NAMESPACE_MEMORIES, type OllamaProviderConfig, type OpenAiCompatibleProviderConfig, PROCEDURAL_REAL_SCENARIOS, PROCEDURAL_REAL_SCENARIOS_SMOKE, PUBLISHED_BENCHMARK_ARTIFACT_IDS, type PersonalizationRetrievalCase, type PreflightDiscoveredModel, type ProceduralAblationArtifact, type ProceduralAblationPerCase, type ProceduralAblationScenario, type ProceduralRealScenario, type ProceduralRealScenarioCategory, type ProviderBaseConfig, type ProviderConfig, type ProviderDiscoveryResult, type ProviderFactoryConfig, type PublishSkipReason, type PublishSkipRecord, type PublishedBenchmarkFeed, type PublishedBenchmarkFeedEntry, type PublishedBenchmarkId, REQUIRED_FRONTMATTER_FIELDS, type RecallMetrics, type RecoveredMemory, type RegressionDetail, type RegressionGateResult, type RemnicAdapterOptions, type ResolveBenchRuntimeProfileOptions, type ResolvedBenchRuntimeProfile, type ResolvedLocalLabProfile, type ResolvedLocalLabRole, type ResolvedRunBenchmarkOptions, type RotatedChoices, type RunBenchmarkOptions, type RunJudgeCalibrationOptions, type RunProceduralAblationCliArgs, type RunProceduralAblationOptions, type RunSequentialPhasesOptions, SCHEMA_TIER_FIXTURE, SCHEMA_TIER_SMOKE_FIXTURE, SEALED_PROMPT_REGISTRY, SYNTHETIC_MEMORIES, type SanitizedDiagnosticProvider, type SavedBaseline, type SchemaTierCorpus, type SchemaTierFixture, type SchemaTierName, type SchemaTierPage, type SchemaTierPageFrontmatter, type SealedArtifact, type SealedJudgeDecision, type SealedJudgeInput, type SealedQrelsArtifact, type SealedQrelsHandle, type SealedRubric, type SearchResult, type SeededMemory, type SeededRng, type SequentialPhaseHooks, type SpotCheckLogger, type StatisticalReport, type StructuredJudge, type SyntheticEmailIngestionAdapterOptions, type SyntheticTargetOptions, type TaskResult, type TaskTokenUsage, type TemporalRetrievalCase, type TierDetail, type TimelineEntry, type TokenUsage, type WriteBenchmarkArtifactResult, addContaminationEntry, aggregateTaskScores, answerBenchmarkQuestion, assertCanaryUnderFloor, assertIntegrityMetaPresent, assertPublishableIntegrity, assertSha256Hex, assistantMeetingPrepDefinition, assistantMorningBriefDefinition, assistantNextBestActionDefinition, assistantSynthesisDefinition, backlinkF1, binarizeJudgeScore, bootstrapMeanConfidenceInterval, buildAmaBenchDiagnosticMatrixArtifact, buildAmaBenchDiagnosticVariantSummary, buildAmaBenchLeaderboardRows, buildBenchmarkArtifact, buildBenchmarkArtifactFilename, buildBenchmarkPublishFeed, buildBenchmarkReproManifest, buildBenchmarkRunSeeds, buildJudgePayload, buildOracleTrajectoryRecall, buildSchemaTierFixture, buildSchemaTierSmokeFixture, calendarFixture, canonicalJsonStringify, chatFixture, checkDatasetContamination, checkRegression, clampScore, cohensD, compareResults, computeCohensKappa, computeSealHash, containsAnswer, createSeededRng as createAdamSeededRng, createAmaBenchDiagnosticAdapter, createAnthropicProvider, createCanaryAdapter, createCodexCliProvider, createDeterministicSpotCheckLogger, createGatewayResponder, createLightweightAdapter, createLiteLlmProvider, createLocalLlmProvider, createMitigatedTarget, createOllamaProvider, createOpenAiCompatibleProvider, createSeededRandom as createProceduralAblationSeededRandom, createProvider, createProviderBackedAmaBenchRecommendedJudge, createProviderBackedJudge, createProviderBackedResponder, createProviderBackedStructuredJudge, createRemnicAdapter, createResponderFromProvider, createSeededRng$1 as createSeededRng, createSpotCheckFileLogger, createStructuredJudgeFromProvider, createSyntheticEmailIngestionAdapter, createSyntheticTarget, createTimeoutGuardedAdapter, defaultBenchmarkBaselineDir, defaultBenchmarkPublishPath, deleteBenchmarkResults, discoverAllProviders, discoveryEndpointFor, emailFixture, entityRecall, exactMatch, extractMarkdownSectionsByTitle, f1Score, fixtureToAblationScenarios, formatHandoffNote, formatMissingDatasetError, generateReport, getBenchmark, getBenchmarkLowerIsBetter, getMemoryEvalDimension, getRemnicVersion, hashBenchmarkArtifact, hashBytes, hashCanonicalJson, hashString, integrityMetaIsComplete, interpretEffectSize, isAmaBenchUnknownLikeAnswer, isContaminationEntry, isContaminationManifest, isSealedQrelsArtifact, isSha256Hex, linkMatches, listBenchmarkBaselines, listBenchmarkResults, listBenchmarks, listMemoryEvalBenchmarkIds, listMemoryEvalDimensions, llmJudgeScore, llmJudgeScoreDetailed, loadAblationFixture, loadBaseline, loadBeamDatasetPreview, loadBenchmarkArtifact, loadBenchmarkBaseline, loadBenchmarkResult, loadCustomBenchmarkFile, loadJudgeCalibrationState, loadLoCoMo10, loadLocalLabManifest, loadLongMemEvalS, loadSealKeyFromEnv, loadSealedQrels, loadSealedRubric, matchEntity, mergeContaminationManifests, openSeal, orchestrateBenchmarkRuns, pairedDeltaConfidenceInterval, parseBenchmarkArtifact, parseCustomBenchmark, parseLocalLabManifest, parseRubricResponse, parseSealedQrels, precisionAtK, preflightLocalLabRole, projectFolderFixture, recallAtK, redactBenchmarkResultSecrets, renderBaselineMarkdown, renderBenchmarkResultExport, renderMemorySummaryForJudge, renderMemoryViewForAgent, resolveAssistantAgent, resolveAssistantRubricId, resolveAssistantSeeds, resolveAssistantSpotCheckDir, resolveBenchRuntimeProfile, resolveBenchmarkPhaseTimeoutMs, resolveBenchmarkProgressLogging, resolveBenchmarkResultReference, resolveBenchmarkRunCount, resolveLocalLabProfile, resolveLocalLabRole, resolveStructuredJudge, rotateDistractors, rougeL, runAssistantBenchmark, runAssistantMeetingPrepBenchmark, runAssistantMorningBriefBenchmark, runAssistantNextBestActionBenchmark, runAssistantSynthesisBenchmark, runBaseline, runBenchSuite, runBenchmark, runCustomBenchmarkFile, runExplain, runExtractionAttack, runJudgeCalibration, runMitigatedBaseline, runProceduralAblation, runProceduralAblationCli, runSealedJudge, runSequentialPhases, safeHexEqual, saveBaseline, saveBenchmarkBaseline, schemaCompleteness, sealPayload, selectAmaBenchDiagnosticVariants, selectCalibrationSlice, selectFixtureVariant, serializeBenchmarkArtifact, serializeJsonl, serializeSealedQrels, shuffleTasks, timed, verifyRubricDigest, writeBenchmarkArtifact, writeBenchmarkPublishFeed, writeBenchmarkReproManifest, writeBenchmarkResult, writeJudgeCalibrationState, writeLeaderboardArtifactsForResult, zeroScores };
package/dist/index.js CHANGED
@@ -5729,6 +5729,10 @@ function buildBenchmarkArtifact(input) {
5729
5729
  const startedAt = new Date(startedMs).toISOString();
5730
5730
  const finishedAt = new Date(finishedMs).toISOString();
5731
5731
  const durationMs = Math.max(0, finishedMs - startedMs);
5732
+ const resultCalibration = readJudgeCalibrationFromBenchmarkOptions(
5733
+ result.config.benchmarkOptions?.judgeCalibration
5734
+ );
5735
+ const judgeCalibration = input.judgeCalibration ?? resultCalibration;
5732
5736
  return {
5733
5737
  schemaVersion: BENCHMARK_ARTIFACT_SCHEMA_VERSION,
5734
5738
  benchmarkId: input.benchmarkId,
@@ -5750,9 +5754,26 @@ function buildBenchmarkArtifact(input) {
5750
5754
  os: result.environment.os,
5751
5755
  ...result.environment.hardware ? { arch: result.environment.hardware } : {}
5752
5756
  },
5753
- ...input.note !== void 0 ? { note: input.note } : {}
5757
+ ...input.note !== void 0 ? { note: input.note } : {},
5758
+ ...input.tier !== void 0 ? { tier: input.tier } : {},
5759
+ ...input.hardware !== void 0 ? { hardware: input.hardware } : {},
5760
+ ...judgeCalibration !== void 0 ? { judgeCalibration } : {}
5754
5761
  };
5755
5762
  }
5763
+ function readJudgeCalibrationFromBenchmarkOptions(value) {
5764
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5765
+ return void 0;
5766
+ }
5767
+ const record = value;
5768
+ const kappa = record.kappa;
5769
+ const sampleSize = record.sampleSize;
5770
+ const threshold = record.threshold;
5771
+ const warning = record.warning;
5772
+ if (typeof kappa !== "number" || !Number.isFinite(kappa) || typeof sampleSize !== "number" || !Number.isFinite(sampleSize) || typeof threshold !== "number" || !Number.isFinite(threshold) || typeof warning !== "boolean") {
5773
+ return void 0;
5774
+ }
5775
+ return { kappa, sampleSize, threshold, warning };
5776
+ }
5756
5777
  function buildBenchmarkArtifactFilename(artifact) {
5757
5778
  const date = sanitizeSegment(artifact.startedAt.slice(0, 10));
5758
5779
  const sha = sanitizeSegment((artifact.system.gitSha || "unknown").slice(0, 7));
@@ -5818,6 +5839,27 @@ function parseBenchmarkArtifact(raw) {
5818
5839
  requireString(env, "os");
5819
5840
  requireOptionalString(env, "arch", "env.arch");
5820
5841
  requireOptionalString(record, "note", "note");
5842
+ if (record.tier !== void 0 && record.tier !== "local" && record.tier !== "frontier") {
5843
+ throw new Error(
5844
+ `BenchmarkArtifact tier must be "local" or "frontier" when provided; got ${String(record.tier)}.`
5845
+ );
5846
+ }
5847
+ if (record.hardware !== void 0) {
5848
+ const hardware = requireObject(record, "hardware");
5849
+ requireString(hardware, "gpu");
5850
+ requireNumber(hardware, "vramGb");
5851
+ requireString(hardware, "quantization");
5852
+ }
5853
+ if (record.judgeCalibration !== void 0) {
5854
+ const calibration = requireObject(record, "judgeCalibration");
5855
+ requireNumber(calibration, "kappa");
5856
+ requireNumber(calibration, "sampleSize");
5857
+ requireNumber(calibration, "threshold");
5858
+ const warning = calibration.warning;
5859
+ if (typeof warning !== "boolean") {
5860
+ throw new Error(`BenchmarkArtifact judgeCalibration.warning must be a boolean; got ${String(warning)}.`);
5861
+ }
5862
+ }
5821
5863
  const metrics = requireObject(record, "metrics");
5822
5864
  for (const [key, value] of Object.entries(metrics)) {
5823
5865
  if (typeof value !== "number" || !Number.isFinite(value)) {
@@ -32037,10 +32079,236 @@ var chatFixture = {
32037
32079
  }
32038
32080
  };
32039
32081
 
32082
+ // src/judges/calibration-slice.ts
32083
+ import { createHash as createHash10, randomBytes as randomBytes3 } from "crypto";
32084
+ import { mkdir as mkdir16, readFile as readFile21, rename as rename3, unlink as unlink3, writeFile as writeFile15 } from "fs/promises";
32085
+ import path34 from "path";
32086
+
32087
+ // src/judges/cohen-kappa.ts
32088
+ function computeCohensKappa(raterA, raterB) {
32089
+ if (raterA.length !== raterB.length) {
32090
+ throw new Error(
32091
+ `computeCohensKappa: rater arrays must have equal length; got ${raterA.length} and ${raterB.length}.`
32092
+ );
32093
+ }
32094
+ const sampleSize = raterA.length;
32095
+ if (sampleSize === 0) {
32096
+ throw new Error("computeCohensKappa: cannot compute kappa over zero paired judgements.");
32097
+ }
32098
+ const countA = /* @__PURE__ */ new Map();
32099
+ const countB = /* @__PURE__ */ new Map();
32100
+ let observedAgreements = 0;
32101
+ for (let index = 0; index < sampleSize; index += 1) {
32102
+ const labelA = raterA[index];
32103
+ const labelB = raterB[index];
32104
+ if (labelA === labelB) {
32105
+ observedAgreements += 1;
32106
+ }
32107
+ countA.set(labelA, (countA.get(labelA) ?? 0) + 1);
32108
+ countB.set(labelB, (countB.get(labelB) ?? 0) + 1);
32109
+ }
32110
+ const categories = /* @__PURE__ */ new Set([...countA.keys(), ...countB.keys()]);
32111
+ const observedAgreement = observedAgreements / sampleSize;
32112
+ let expectedAgreement = 0;
32113
+ for (const category of categories) {
32114
+ const probA = (countA.get(category) ?? 0) / sampleSize;
32115
+ const probB = (countB.get(category) ?? 0) / sampleSize;
32116
+ expectedAgreement += probA * probB;
32117
+ }
32118
+ const denominator = 1 - expectedAgreement;
32119
+ let kappa;
32120
+ if (denominator === 0) {
32121
+ kappa = observedAgreement === 1 ? 1 : 0;
32122
+ } else {
32123
+ kappa = (observedAgreement - expectedAgreement) / denominator;
32124
+ }
32125
+ return {
32126
+ kappa,
32127
+ observedAgreement,
32128
+ expectedAgreement,
32129
+ sampleSize,
32130
+ categories: [...categories].sort()
32131
+ };
32132
+ }
32133
+ var DEFAULT_JUDGE_BINARIZATION_THRESHOLD = 0.5;
32134
+ function binarizeJudgeScore(score, threshold = DEFAULT_JUDGE_BINARIZATION_THRESHOLD) {
32135
+ if (typeof score !== "number" || !Number.isFinite(score)) {
32136
+ return "incorrect";
32137
+ }
32138
+ return score >= threshold ? "correct" : "incorrect";
32139
+ }
32140
+
32141
+ // src/judges/calibration-slice.ts
32142
+ var CALIBRATION_SLICE_SIZE = 50;
32143
+ var MIN_CALIBRATION_SOURCE_TASKS = 10;
32144
+ var JUDGE_CALIBRATION_KAPPA_THRESHOLD = 0.7;
32145
+ function selectCalibrationSlice(questionIds, size = CALIBRATION_SLICE_SIZE) {
32146
+ if (!Number.isInteger(size) || size <= 0) {
32147
+ throw new Error(`selectCalibrationSlice: size must be a positive integer; got ${String(size)}.`);
32148
+ }
32149
+ const seen = /* @__PURE__ */ new Set();
32150
+ const unique = [];
32151
+ for (const id of questionIds) {
32152
+ if (typeof id !== "string" || id.length === 0) {
32153
+ throw new Error(`selectCalibrationSlice: question ids must be non-empty strings; got ${String(id)}.`);
32154
+ }
32155
+ if (!seen.has(id)) {
32156
+ seen.add(id);
32157
+ unique.push(id);
32158
+ }
32159
+ }
32160
+ return unique.map((id) => ({ id, digest: createHash10("sha256").update(id, "utf8").digest("hex") })).sort((a, b) => a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0).slice(0, Math.min(size, unique.length)).map((entry) => entry.id);
32161
+ }
32162
+ async function runJudgeCalibration(options) {
32163
+ const binScore = options.binScore ?? ((score) => binarizeJudgeScore(score));
32164
+ const threshold = options.threshold ?? JUDGE_CALIBRATION_KAPPA_THRESHOLD;
32165
+ const sliceSize = options.sliceSize ?? CALIBRATION_SLICE_SIZE;
32166
+ const sliceIds = selectCalibrationSlice(
32167
+ options.answers.map((answer) => answer.questionId),
32168
+ sliceSize
32169
+ );
32170
+ const sliceIdSet = new Set(sliceIds);
32171
+ const answerById = /* @__PURE__ */ new Map();
32172
+ for (const answer of options.answers) {
32173
+ if (sliceIdSet.has(answer.questionId) && !answerById.has(answer.questionId)) {
32174
+ answerById.set(answer.questionId, answer);
32175
+ }
32176
+ }
32177
+ const sliceAnswers = sliceIds.map((id) => answerById.get(id)).filter((answer) => answer !== void 0);
32178
+ const localLabels = [];
32179
+ const frontierLabels = [];
32180
+ const verdicts = [];
32181
+ for (const answer of sliceAnswers) {
32182
+ const localScore = await options.localJudge.score(
32183
+ answer.question,
32184
+ answer.predicted,
32185
+ answer.expected
32186
+ );
32187
+ const frontierScore = await options.frontierJudge.score(
32188
+ answer.question,
32189
+ answer.predicted,
32190
+ answer.expected
32191
+ );
32192
+ const localCategory = binScore(localScore);
32193
+ const frontierCategory = binScore(frontierScore);
32194
+ localLabels.push(localCategory);
32195
+ frontierLabels.push(frontierCategory);
32196
+ verdicts.push({
32197
+ questionId: answer.questionId,
32198
+ localCategory,
32199
+ frontierCategory
32200
+ });
32201
+ }
32202
+ const kappaResult = computeCohensKappa(localLabels, frontierLabels);
32203
+ const warning = kappaResult.kappa < threshold;
32204
+ return {
32205
+ ...kappaResult,
32206
+ benchmarkId: options.benchmarkId,
32207
+ sliceQuestionIds: sliceIds,
32208
+ threshold,
32209
+ warning,
32210
+ verdicts
32211
+ };
32212
+ }
32213
+ async function writeJudgeCalibrationState(result, calibrationDir, identities) {
32214
+ await mkdir16(calibrationDir, { recursive: true });
32215
+ const state = {
32216
+ kappa: result.kappa,
32217
+ sampleSize: result.sampleSize,
32218
+ threshold: result.threshold,
32219
+ warning: result.warning,
32220
+ ...identities ? identities : {}
32221
+ };
32222
+ const filePath = path34.join(calibrationDir, `${sanitizeCalibrationSegment(result.benchmarkId)}.json`);
32223
+ const tempPath = `${filePath}.${randomBytes3(6).toString("hex")}.tmp`;
32224
+ await writeFile15(tempPath, `${JSON.stringify(state, null, 2)}
32225
+ `, "utf8");
32226
+ try {
32227
+ await rename3(tempPath, filePath);
32228
+ } catch (error) {
32229
+ await unlink3(tempPath).catch(() => void 0);
32230
+ throw error;
32231
+ }
32232
+ return filePath;
32233
+ }
32234
+ async function loadJudgeCalibrationState(benchmarkId, calibrationDir) {
32235
+ const filePath = path34.join(calibrationDir, `${sanitizeCalibrationSegment(benchmarkId)}.json`);
32236
+ let raw;
32237
+ try {
32238
+ raw = await readFile21(filePath, "utf8");
32239
+ } catch {
32240
+ return void 0;
32241
+ }
32242
+ let parsed;
32243
+ try {
32244
+ parsed = JSON.parse(raw);
32245
+ } catch {
32246
+ return void 0;
32247
+ }
32248
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
32249
+ return void 0;
32250
+ }
32251
+ const record = parsed;
32252
+ const kappa = record.kappa;
32253
+ const sampleSize = record.sampleSize;
32254
+ const threshold = record.threshold;
32255
+ const warning = record.warning;
32256
+ if (typeof kappa !== "number" || !Number.isFinite(kappa) || typeof sampleSize !== "number" || !Number.isFinite(sampleSize) || typeof threshold !== "number" || !Number.isFinite(threshold) || typeof warning !== "boolean") {
32257
+ return void 0;
32258
+ }
32259
+ const loaded = { kappa, sampleSize, threshold, warning };
32260
+ const identityKeys = [
32261
+ "localJudgeProvider",
32262
+ "localJudgeModel",
32263
+ "frontierJudgeProvider",
32264
+ "frontierJudgeModel"
32265
+ ];
32266
+ const identityValues = identityKeys.map((key) => record[key]);
32267
+ if (identityValues.some((value) => value !== void 0)) {
32268
+ if (identityValues.every((value) => typeof value === "string")) {
32269
+ Object.assign(
32270
+ loaded,
32271
+ Object.fromEntries(identityKeys.map((key, index) => [key, identityValues[index]]))
32272
+ );
32273
+ }
32274
+ }
32275
+ return loaded;
32276
+ }
32277
+ function sanitizeCalibrationSegment(value) {
32278
+ const lowered = value.trim().toLowerCase();
32279
+ const chars = [];
32280
+ let prevWasSeparator = false;
32281
+ for (const ch of lowered) {
32282
+ const code = ch.charCodeAt(0);
32283
+ const isAllowed = code >= 97 && code <= 122 || // a-z
32284
+ code >= 48 && code <= 57 || // 0-9
32285
+ code === 95 || // _
32286
+ code === 45;
32287
+ if (isAllowed) {
32288
+ const isSeparator = ch === "-";
32289
+ if (isSeparator && prevWasSeparator) {
32290
+ continue;
32291
+ }
32292
+ chars.push(ch);
32293
+ prevWasSeparator = isSeparator;
32294
+ } else if (!prevWasSeparator && chars.length > 0) {
32295
+ chars.push("-");
32296
+ prevWasSeparator = true;
32297
+ }
32298
+ }
32299
+ while (chars.length > 0 && chars[0] === "-") {
32300
+ chars.shift();
32301
+ }
32302
+ while (chars.length > 0 && chars[chars.length - 1] === "-") {
32303
+ chars.pop();
32304
+ }
32305
+ return chars.length > 0 ? chars.join("") : "unknown";
32306
+ }
32307
+
32040
32308
  // src/benchmarks/remnic/procedural-recall/ablation.ts
32041
- import { mkdir as mkdir16, mkdtemp as mkdtemp11, rm as rm13, writeFile as writeFile15, readFile as readFile21 } from "fs/promises";
32309
+ import { mkdir as mkdir17, mkdtemp as mkdtemp11, rm as rm13, writeFile as writeFile16, readFile as readFile22 } from "fs/promises";
32042
32310
  import os9 from "os";
32043
- import path34 from "path";
32311
+ import path35 from "path";
32044
32312
  import {
32045
32313
  StorageManager as StorageManager3,
32046
32314
  parseConfig as parseConfig5,
@@ -32071,7 +32339,7 @@ async function runSide(scenarios, proceduralEnabled) {
32071
32339
  const observed = [];
32072
32340
  for (const scenario of scenarios) {
32073
32341
  const dir = await mkdtemp11(
32074
- path34.join(os9.tmpdir(), "remnic-bench-proc-ablation-")
32342
+ path35.join(os9.tmpdir(), "remnic-bench-proc-ablation-")
32075
32343
  );
32076
32344
  try {
32077
32345
  const storage = new StorageManager3(dir);
@@ -32086,7 +32354,7 @@ ${body}`,
32086
32354
  );
32087
32355
  const config = parseConfig5({
32088
32356
  memoryDir: dir,
32089
- workspaceDir: path34.join(dir, "ws"),
32357
+ workspaceDir: path35.join(dir, "ws"),
32090
32358
  openaiApiKey: "bench-key",
32091
32359
  procedural: {
32092
32360
  enabled: proceduralEnabled,
@@ -32161,7 +32429,7 @@ async function runProceduralAblation(options) {
32161
32429
  };
32162
32430
  }
32163
32431
  async function loadAblationFixture(fixturePath) {
32164
- const raw = await readFile21(fixturePath, "utf8");
32432
+ const raw = await readFile22(fixturePath, "utf8");
32165
32433
  let parsed;
32166
32434
  try {
32167
32435
  parsed = JSON.parse(raw);
@@ -32257,9 +32525,9 @@ async function runProceduralAblationCli(args) {
32257
32525
  random: args.random,
32258
32526
  seed: args.seed
32259
32527
  });
32260
- const outDir = path34.dirname(path34.resolve(args.outPath));
32261
- await mkdir16(outDir, { recursive: true });
32262
- await writeFile15(args.outPath, JSON.stringify(artifact, null, 2) + "\n", "utf8");
32528
+ const outDir = path35.dirname(path35.resolve(args.outPath));
32529
+ await mkdir17(outDir, { recursive: true });
32530
+ await writeFile16(args.outPath, JSON.stringify(artifact, null, 2) + "\n", "utf8");
32263
32531
  return artifact;
32264
32532
  }
32265
32533
 
@@ -33344,21 +33612,25 @@ export {
33344
33612
  BENCHMARK_REPRO_MANIFEST_SCHEMA_VERSION,
33345
33613
  BENCHMARK_RESULT_SCHEMA,
33346
33614
  BENCHMARK_SPLIT_TYPES,
33615
+ CALIBRATION_SLICE_SIZE,
33347
33616
  CANARY_FIXED_RECALL,
33348
33617
  CANARY_SCORE_FLOOR,
33349
33618
  DEFAULT_ABLATION_BOOTSTRAP_SEED,
33350
33619
  DEFAULT_ASSISTANT_RUBRIC_ID,
33351
33620
  DEFAULT_BASELINE_SCENARIOS,
33621
+ DEFAULT_JUDGE_BINARIZATION_THRESHOLD,
33352
33622
  EMPTY_CONTAMINATION_MANIFEST,
33353
33623
  INTEGRITY_CIPHER_ALGORITHM,
33354
33624
  INTEGRITY_HASH_ALGORITHM,
33355
33625
  INTEGRITY_META_FIELDS,
33626
+ JUDGE_CALIBRATION_KAPPA_THRESHOLD,
33356
33627
  LOCAL_LAB_PROVIDER_KINDS,
33357
33628
  LOCOMO_DATASET_FILENAMES,
33358
33629
  LONG_MEM_EVAL_DATASET_FILENAMES,
33359
33630
  LocalLabPreflightError,
33360
33631
  MEMORY_EVAL_DIMENSIONS,
33361
33632
  MEMORY_EVAL_PUBLIC_LINE,
33633
+ MIN_CALIBRATION_SOURCE_TASKS,
33362
33634
  MITIGATED_BASELINE_SCENARIOS,
33363
33635
  OTHER_NAMESPACE_MEMORIES,
33364
33636
  PROCEDURAL_REAL_SCENARIOS,
@@ -33381,6 +33653,7 @@ export {
33381
33653
  assistantNextBestActionDefinition,
33382
33654
  assistantSynthesisDefinition,
33383
33655
  backlinkF1,
33656
+ binarizeJudgeScore,
33384
33657
  bootstrapMeanConfidenceInterval,
33385
33658
  buildAmaBenchDiagnosticMatrixArtifact,
33386
33659
  buildAmaBenchDiagnosticVariantSummary,
@@ -33402,6 +33675,7 @@ export {
33402
33675
  clampScore,
33403
33676
  cohensD,
33404
33677
  compareResults,
33678
+ computeCohensKappa,
33405
33679
  computeSealHash,
33406
33680
  containsAnswer,
33407
33681
  createSeededRng2 as createAdamSeededRng,
@@ -33475,6 +33749,7 @@ export {
33475
33749
  loadBenchmarkBaseline,
33476
33750
  loadBenchmarkResult,
33477
33751
  loadCustomBenchmarkFile,
33752
+ loadJudgeCalibrationState,
33478
33753
  loadLoCoMo10,
33479
33754
  loadLocalLabManifest,
33480
33755
  loadLongMemEvalS,
@@ -33525,6 +33800,7 @@ export {
33525
33800
  runCustomBenchmarkFile,
33526
33801
  runExplain,
33527
33802
  runExtractionAttack,
33803
+ runJudgeCalibration,
33528
33804
  runMitigatedBaseline,
33529
33805
  runProceduralAblation,
33530
33806
  runProceduralAblationCli,
@@ -33536,6 +33812,7 @@ export {
33536
33812
  schemaCompleteness,
33537
33813
  sealPayload,
33538
33814
  selectAmaBenchDiagnosticVariants,
33815
+ selectCalibrationSlice,
33539
33816
  selectFixtureVariant,
33540
33817
  serializeBenchmarkArtifact,
33541
33818
  serializeJsonl,
@@ -33547,6 +33824,7 @@ export {
33547
33824
  writeBenchmarkPublishFeed,
33548
33825
  writeBenchmarkReproManifest,
33549
33826
  writeBenchmarkResult,
33827
+ writeJudgeCalibrationState,
33550
33828
  writeLeaderboardArtifactsForResult,
33551
33829
  zeroScores
33552
33830
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remnic/bench",
3
- "version": "9.3.700",
3
+ "version": "9.3.702",
4
4
  "description": "Retrieval latency ladder benchmarks + CI regression gates for @remnic/core",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "hyparquet": "^1.25.7",
38
38
  "yaml": "^2.4.2",
39
- "@remnic/core": "^9.3.700"
39
+ "@remnic/core": "^9.3.702"
40
40
  },
41
41
  "devDependencies": {
42
42
  "tsup": "^8.5.1",