@vostride/agent-qa-eval-local 0.0.0-stage → 0.2.1

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,753 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/reader.ts
21
+ var reader_exports = {};
22
+ __export(reader_exports, {
23
+ openCorpusReader: () => openCorpusReader
24
+ });
25
+ module.exports = __toCommonJS(reader_exports);
26
+
27
+ // src/corpus-reader.ts
28
+ var import_agent_qa_eval9 = require("@vostride/agent-qa-eval");
29
+
30
+ // src/committed-corpus-source.ts
31
+ var import_node_fs12 = require("fs");
32
+ var import_node_path12 = require("path");
33
+ var import_agent_qa_eval8 = require("@vostride/agent-qa-eval");
34
+ var import_agent_qa_schema8 = require("@vostride/agent-qa-schema");
35
+ var import_zod6 = require("zod");
36
+
37
+ // src/cassette-loader.ts
38
+ var import_node_fs3 = require("fs");
39
+ var import_node_path3 = require("path");
40
+ var import_agent_qa_eval2 = require("@vostride/agent-qa-eval");
41
+
42
+ // src/artifact-source.ts
43
+ var import_node_fs = require("fs");
44
+ var import_node_path = require("path");
45
+ var import_agent_qa_runner_local = require("@vostride/agent-qa-runner-local");
46
+ var BLOB_SHA_RE = /^[0-9a-f]{64}$/;
47
+ var DirArtifactSource = class {
48
+ dir;
49
+ constructor(config) {
50
+ this.dir = config.dir;
51
+ }
52
+ getBlob(sha) {
53
+ if (!BLOB_SHA_RE.test(sha)) return void 0;
54
+ try {
55
+ return new Uint8Array((0, import_node_fs.readFileSync)((0, import_node_path.join)(this.dir, sha)));
56
+ } catch (error) {
57
+ if (error.code === "ENOENT") return void 0;
58
+ throw error;
59
+ }
60
+ }
61
+ };
62
+
63
+ // src/cassette-store.ts
64
+ var import_node_crypto = require("crypto");
65
+ var import_node_fs2 = require("fs");
66
+ var import_node_path2 = require("path");
67
+ var import_agent_qa_eval = require("@vostride/agent-qa-eval");
68
+ var import_agent_qa_schema = require("@vostride/agent-qa-schema");
69
+ var CASSETTE_FILE = "cassette.json";
70
+ var BLOBS_SUBDIR = "blobs";
71
+
72
+ // src/cassette-loader.ts
73
+ function refused(cassetteId, reason, detail) {
74
+ return { kind: "refused", refusal: { kind: "integrity-refusal", cassetteId, reason, detail } };
75
+ }
76
+ function recoverCassetteId(document, fallback) {
77
+ if (typeof document === "object" && document !== null) {
78
+ const id = document.id;
79
+ if (typeof id === "string" && id.length > 0) return id;
80
+ }
81
+ return fallback;
82
+ }
83
+ function loadCassetteBundle(bundleDir) {
84
+ const fallbackId = (0, import_node_path3.basename)(bundleDir);
85
+ const cassettePath = (0, import_node_path3.join)(bundleDir, CASSETTE_FILE);
86
+ let raw;
87
+ try {
88
+ raw = (0, import_node_fs3.readFileSync)(cassettePath, "utf8");
89
+ } catch (error) {
90
+ return refused(
91
+ fallbackId,
92
+ "parse-failed",
93
+ `Failed to read ${cassettePath}: ${error.message}`
94
+ );
95
+ }
96
+ let document;
97
+ try {
98
+ document = JSON.parse(raw);
99
+ } catch (error) {
100
+ return refused(
101
+ fallbackId,
102
+ "parse-failed",
103
+ `Invalid cassette JSON at ${cassettePath}: ${error.message}`
104
+ );
105
+ }
106
+ let cassette;
107
+ try {
108
+ cassette = (0, import_agent_qa_eval2.guardCassette)(document);
109
+ } catch (error) {
110
+ return refused(recoverCassetteId(document, fallbackId), "guard-failed", error.message);
111
+ }
112
+ const artifacts = new DirArtifactSource({ dir: (0, import_node_path3.join)(bundleDir, BLOBS_SUBDIR) });
113
+ return { kind: "loaded", cassette, artifacts };
114
+ }
115
+
116
+ // src/committed-root-store.ts
117
+ var import_node_crypto2 = require("crypto");
118
+ var import_node_fs4 = require("fs");
119
+ var import_node_path4 = require("path");
120
+ var import_agent_qa_schema2 = require("@vostride/agent-qa-schema");
121
+ var COMMITTED_CASSETTES_DIR = "cassettes";
122
+ var COMMITTED_CORPUS_DIR = "corpus";
123
+ var COMMITTED_LABELS_DIR = "labels";
124
+ function sluggedIdSegments(cassetteId) {
125
+ return cassetteId.split("/").map((segment) => (0, import_agent_qa_schema2.slugBranch)(segment));
126
+ }
127
+ function sluggedJsonLeaf(cassetteId) {
128
+ const segments = sluggedIdSegments(cassetteId);
129
+ const last = segments.pop() ?? "default";
130
+ return [...segments, `${last}.json`];
131
+ }
132
+ function committedLabelPath(product, cassetteId) {
133
+ return [COMMITTED_LABELS_DIR, (0, import_agent_qa_schema2.slugBranch)(product), ...sluggedJsonLeaf(cassetteId)].join("/");
134
+ }
135
+
136
+ // src/replay-read.ts
137
+ var import_node_fs7 = require("fs");
138
+ var import_node_path7 = require("path");
139
+ var import_agent_qa_eval3 = require("@vostride/agent-qa-eval");
140
+
141
+ // src/replay-record-store.ts
142
+ var import_node_fs5 = require("fs");
143
+ var import_node_path5 = require("path");
144
+ var import_agent_qa_schema3 = require("@vostride/agent-qa-schema");
145
+
146
+ // src/score-store.ts
147
+ var import_node_fs6 = require("fs");
148
+ var import_node_path6 = require("path");
149
+ var import_agent_qa_schema4 = require("@vostride/agent-qa-schema");
150
+
151
+ // src/replay-read.ts
152
+ function listMarkerDirs(root, markerFile) {
153
+ const found = [];
154
+ function walk(dir) {
155
+ let entries;
156
+ try {
157
+ entries = (0, import_node_fs7.readdirSync)(dir, { withFileTypes: true });
158
+ } catch {
159
+ return;
160
+ }
161
+ if (entries.some((entry) => entry.isFile() && entry.name === markerFile)) found.push(dir);
162
+ for (const entry of entries) {
163
+ if (entry.isDirectory()) walk((0, import_node_path7.join)(dir, entry.name));
164
+ }
165
+ }
166
+ walk(root);
167
+ return found.sort();
168
+ }
169
+ function listCassetteBundleDirs(cassettesRoot) {
170
+ return listMarkerDirs(cassettesRoot, CASSETTE_FILE);
171
+ }
172
+
173
+ // src/mark-ledger.ts
174
+ var import_node_fs9 = require("fs");
175
+ var import_node_path9 = require("path");
176
+ var import_agent_qa_eval4 = require("@vostride/agent-qa-eval");
177
+ var import_agent_qa_runner_local2 = require("@vostride/agent-qa-runner-local");
178
+ var import_agent_qa_schema5 = require("@vostride/agent-qa-schema");
179
+ var import_zod2 = require("zod");
180
+
181
+ // src/mark-lock.ts
182
+ var import_node_crypto3 = require("crypto");
183
+ var import_node_fs8 = require("fs");
184
+ var import_node_path8 = require("path");
185
+ var import_zod = require("zod");
186
+ var ownerSchema = import_zod.z.object({
187
+ schemaVersion: import_zod.z.literal(2),
188
+ kind: import_zod.z.literal("mark-ledger-lock"),
189
+ pid: import_zod.z.number().int().positive(),
190
+ token: import_zod.z.uuid(),
191
+ runId: import_zod.z.string().min(1)
192
+ }).strict();
193
+
194
+ // src/mark-ledger.ts
195
+ var MARK_INTENT_STAGES = ["prepared", "evidence", "applied"];
196
+ var intentSchema = import_zod2.z.object({
197
+ schemaVersion: import_zod2.z.literal(2),
198
+ mark: import_agent_qa_schema5.MarkReceiptSchema,
199
+ stage: import_zod2.z.enum(MARK_INTENT_STAGES),
200
+ operationId: import_zod2.z.uuid(),
201
+ plan: import_agent_qa_schema5.ImprovementPlanSchema.optional()
202
+ }).strict().superRefine((intent, ctx) => {
203
+ if (intent.stage === "applied" && intent.mark.disposition.kind === "drafted") {
204
+ ctx.addIssue({ code: "custom", path: ["mark", "disposition"], message: "a mark applies its fix; it never files a draft" });
205
+ }
206
+ });
207
+
208
+ // src/calibration-source.ts
209
+ var import_node_fs10 = require("fs");
210
+ var import_node_path10 = require("path");
211
+ var import_zod3 = require("zod");
212
+ var import_agent_qa_eval5 = require("@vostride/agent-qa-eval");
213
+ var import_agent_qa_schema6 = require("@vostride/agent-qa-schema");
214
+ var LABEL_CALIBRATION_PATH = "labels/calibration.json";
215
+ var LABEL_CALIBRATION_SCHEMA_VERSION = 2;
216
+ var count = import_zod3.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
217
+ var unit = import_zod3.z.number().finite().min(0).max(1);
218
+ var digest = import_zod3.z.string().regex(/^[0-9a-f]{64}$/);
219
+ var noisy = import_zod3.z.union([
220
+ import_zod3.z.object({ status: import_zod3.z.literal("uncalibrated"), n: count, n_gold: count }).strict(),
221
+ import_zod3.z.object({
222
+ status: import_zod3.z.literal("calibrated"),
223
+ n: count,
224
+ n_gold: count,
225
+ precision: unit,
226
+ wilson95: import_zod3.z.object({ lower: unit, upper: unit, halfWidth: unit }).strict().refine((v) => v.lower <= v.upper)
227
+ }).strict()
228
+ ]);
229
+ var gold = import_zod3.z.object({ n_gold: count, precision: import_zod3.z.literal("by-construction") }).strict();
230
+ var prior = import_zod3.z.object({ alpha: import_zod3.z.number().finite().min(0), beta: import_zod3.z.number().finite().min(0) }).strict().refine((v) => Number.isFinite(v.alpha + v.beta) && v.alpha + v.beta > 0);
231
+ var rate = import_zod3.z.object({ numerator: count, denominator: count, rate: unit.optional() }).strict().refine((v) => v.numerator <= v.denominator && (v.denominator === 0 ? v.rate === void 0 : v.rate === v.numerator / v.denominator));
232
+ var accuracy = import_zod3.z.object({ n: count, correct: count, accuracy: unit.optional() }).strict().refine((v) => v.correct <= v.n && (v.n === 0 ? v.accuracy === void 0 : v.accuracy === v.correct / v.n));
233
+ var artifactSchema = import_zod3.z.object({
234
+ schemaVersion: import_zod3.z.literal(LABEL_CALIBRATION_SCHEMA_VERSION),
235
+ generationId: digest,
236
+ evidenceDigest: digest,
237
+ corpusDigest: digest,
238
+ goldSetDigest: digest,
239
+ minGold: import_zod3.z.object({ value: count.min(2), source: import_zod3.z.enum(["default", "cli"]) }).strict(),
240
+ channels: import_zod3.z.object({ "recorded-verdict": noisy, "self-heal-pair": noisy, "user-mark": gold, "overturned-verdict": gold }).strict(),
241
+ priors: import_zod3.z.object({ "agent-verified": prior.optional(), "agent-observed": prior.optional() }).strict(),
242
+ unchangedOrigins: import_zod3.z.tuple([import_zod3.z.literal("user"), import_zod3.z.literal("import")]),
243
+ verifierFalsePassRate: rate,
244
+ verifierFalseFailRate: rate,
245
+ rootCauseClassifierAccuracy: import_zod3.z.object({ "analyze-run": accuracy, "deterministic-classifier": accuracy }).strict(),
246
+ rootCauseClassifierGrain: import_zod3.z.literal("member/producer:app_bug-binary"),
247
+ skippedCounts: import_zod3.z.object({ "missing-source": count.optional(), "invalid-gold": count.optional(), "conflicting-truth": count.optional(), "missing-verdict": count.optional(), "missing-pairing": count.optional(), "conflicting-observation": count.optional() }).strict(),
248
+ targetRevisions: import_zod3.z.array(import_zod3.z.object({ cassetteId: import_zod3.z.string().min(1), revisionId: digest }).strict())
249
+ }).strict();
250
+ function assertCalibrationPath(root, path) {
251
+ const base = (0, import_node_path10.resolve)(root), full = (0, import_node_path10.resolve)(path), rel = (0, import_node_path10.relative)(base, full);
252
+ if (rel === ".." || rel.startsWith("../") || rel.startsWith("/")) throw new Error("invalid calibration path");
253
+ let cursor = full;
254
+ while (true) {
255
+ try {
256
+ if ((0, import_node_fs10.lstatSync)(cursor).isSymbolicLink()) throw new Error("invalid calibration path");
257
+ } catch (error) {
258
+ if (error.code !== "ENOENT") throw error;
259
+ }
260
+ if (cursor === base) break;
261
+ const parent = (0, import_node_path10.dirname)(cursor);
262
+ if (parent === cursor) break;
263
+ cursor = parent;
264
+ }
265
+ }
266
+ function calibrationGenerationId(body) {
267
+ return (0, import_agent_qa_schema6.sha256hex)((0, import_agent_qa_eval5.canonicalJson)(body));
268
+ }
269
+ function guardLabelCalibration(value) {
270
+ const parsed = artifactSchema.safeParse(value);
271
+ if (!parsed.success) return void 0;
272
+ const artifact = parsed.data;
273
+ const { generationId, ...body } = artifact;
274
+ if (calibrationGenerationId(body) !== generationId) return void 0;
275
+ let previous;
276
+ for (const target of artifact.targetRevisions) {
277
+ if (previous !== void 0 && previous >= target.cassetteId) return void 0;
278
+ previous = target.cassetteId;
279
+ }
280
+ for (const [channel, origin] of [["recorded-verdict", "agent-verified"], ["self-heal-pair", "agent-observed"]]) {
281
+ const row = artifact.channels[channel], emitted = artifact.priors[origin];
282
+ if (row.n !== row.n_gold || row.status === "calibrated" !== row.n >= artifact.minGold.value) return void 0;
283
+ if (row.status === "uncalibrated") {
284
+ if (emitted !== void 0) return void 0;
285
+ } else {
286
+ const mass = import_agent_qa_schema6.ORIGIN_PRIORS[origin].alpha + import_agent_qa_schema6.ORIGIN_PRIORS[origin].beta;
287
+ if (!emitted || emitted.alpha !== row.precision * mass || emitted.beta !== (1 - row.precision) * mass) return void 0;
288
+ }
289
+ }
290
+ return artifact;
291
+ }
292
+ function readLabelCalibration(committedRoot) {
293
+ const marker = (0, import_node_path10.join)(committedRoot, LABEL_CALIBRATION_PATH);
294
+ let targetCassetteIds;
295
+ try {
296
+ let walk2 = function(directory) {
297
+ assertCalibrationPath(committedRoot, directory);
298
+ for (const entry of (0, import_node_fs10.readdirSync)(directory, { withFileTypes: true })) {
299
+ const path = (0, import_node_path10.join)(directory, entry.name);
300
+ if (entry.isDirectory()) {
301
+ walk2(path);
302
+ continue;
303
+ }
304
+ if (!entry.isFile() || !entry.name.endsWith(".json") || path === marker) continue;
305
+ let parsed;
306
+ try {
307
+ parsed = (0, import_agent_qa_eval5.parseStandaloneLabelRecord)(JSON.parse((0, import_node_fs10.readFileSync)(path, "utf8")));
308
+ } catch {
309
+ continue;
310
+ }
311
+ if (!parsed.ok) continue;
312
+ const record = parsed.record, product = (0, import_node_path10.relative)((0, import_node_path10.join)(committedRoot, "labels"), path).split("/")[0];
313
+ const expected = (0, import_node_path10.join)(committedRoot, committedLabelPath(product, record.cassetteId)).replace(/\.json$/, record.revision ? `--revision-${record.revision.id}.json` : ".json");
314
+ if (expected !== path) continue;
315
+ const id = record.revision?.id ?? (0, import_agent_qa_eval5.deriveLabelRevisionId)(record);
316
+ if (records.has(id)) throw new Error("duplicate label identity");
317
+ records.set(id, record);
318
+ }
319
+ };
320
+ var walk = walk2;
321
+ assertCalibrationPath(committedRoot, marker);
322
+ try {
323
+ (0, import_node_fs10.lstatSync)(marker);
324
+ } catch (error) {
325
+ if (error.code === "ENOENT") return { kind: "absent" };
326
+ throw error;
327
+ }
328
+ const artifact = guardLabelCalibration(JSON.parse((0, import_node_fs10.readFileSync)(marker, "utf8")));
329
+ if (!artifact) return { kind: "refused", reason: "invalid label calibration artifact" };
330
+ targetCassetteIds = artifact.targetRevisions.map((target) => target.cassetteId);
331
+ const records = /* @__PURE__ */ new Map();
332
+ walk2((0, import_node_path10.join)(committedRoot, "labels"));
333
+ const authorizedRevisionIds = /* @__PURE__ */ new Set();
334
+ for (const target of artifact.targetRevisions) {
335
+ const chain = [], visited = /* @__PURE__ */ new Set(), generations = /* @__PURE__ */ new Set();
336
+ let id = target.revisionId;
337
+ while (id !== void 0) {
338
+ const record = records.get(id);
339
+ if (!record || record.cassetteId !== target.cassetteId || visited.has(id)) throw new Error("incomplete label chain");
340
+ visited.add(id);
341
+ chain.push(record);
342
+ if (record.revision?.generationId) generations.add(record.revision.generationId);
343
+ id = record.revision?.predecessorId;
344
+ }
345
+ const selected = (0, import_agent_qa_eval5.selectEffectiveLabels)(chain, { committedGenerationIds: generations });
346
+ const terminal = selected.effective.get(target.cassetteId);
347
+ if (selected.refusals.length || !terminal || (terminal.revision?.id ?? (0, import_agent_qa_eval5.deriveLabelRevisionId)(terminal)) !== target.revisionId) throw new Error("invalid label chain");
348
+ for (const id2 of visited) authorizedRevisionIds.add(id2);
349
+ }
350
+ return { kind: "loaded", artifact, authorizedRevisionIds };
351
+ } catch {
352
+ return { kind: "refused", reason: "label calibration or target history unavailable", targetCassetteIds };
353
+ }
354
+ }
355
+
356
+ // src/report-metadata-guard.ts
357
+ var import_zod4 = require("zod");
358
+ var import_agent_qa_eval6 = require("@vostride/agent-qa-eval");
359
+ var count2 = import_zod4.z.number().int().nonnegative().safe();
360
+ var amount = import_zod4.z.number().finite().nonnegative();
361
+ var unit2 = import_zod4.z.number().finite().min(0).max(1);
362
+ var rate2 = import_zod4.z.object({ numerator: count2, denominator: count2, rate: unit2.optional() }).passthrough().refine((row) => row.numerator <= row.denominator && (row.denominator === 0 ? row.rate === void 0 : row.rate === row.numerator / row.denominator));
363
+ var recovery = import_zod4.z.object({
364
+ weightSum: import_zod4.z.number().finite().nonnegative(),
365
+ pairsWithoutWeight: count2,
366
+ weightedAccuracy: unit2.optional(),
367
+ selfHealPairCount: count2,
368
+ recoveredPositiveCount: count2,
369
+ eligiblePositiveCount: count2,
370
+ recoveryAccuracy: unit2.optional(),
371
+ negativeDecisionCount: count2,
372
+ negativeFullMatchCount: count2
373
+ }).passthrough();
374
+ var cell = import_zod4.z.object({
375
+ firstAttemptDecisionAccuracy: rate2,
376
+ verifierFalsePassRate: rate2,
377
+ recovery,
378
+ perDecisionCost: import_zod4.z.object({
379
+ decisionCount: count2,
380
+ promptTokens: amount,
381
+ completionTokens: amount,
382
+ totalTokens: amount,
383
+ durationMs: amount
384
+ }).passthrough()
385
+ }).passthrough();
386
+ var closedCounts = (values) => import_zod4.z.record(import_zod4.z.enum(values), count2);
387
+ var openCounts = import_zod4.z.record(import_zod4.z.string(), count2);
388
+ var generationMix = import_zod4.z.object({
389
+ total: count2,
390
+ metadataUnavailable: count2,
391
+ byProvenance: closedCounts(import_agent_qa_eval6.GENERATOR_PROVENANCES),
392
+ byKind: closedCounts(import_agent_qa_eval6.GENERATOR_KINDS),
393
+ byMutator: closedCounts(import_agent_qa_eval6.ADVERSARIAL_MUTATORS),
394
+ byTableVersion: openCounts,
395
+ tableHashesByVersion: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.array(import_zod4.z.string())),
396
+ byPromptVersion: openCounts,
397
+ byAuthoringModel: openCounts,
398
+ byAuthoringFamily: openCounts
399
+ }).strict();
400
+ var current = import_zod4.z.object({
401
+ // Additive-optional: absent is the pre-422 shape and stays admissible forever.
402
+ adversarialGenerationMix: generationMix.optional(),
403
+ headline: import_zod4.z.object({ verifierFalsePassRate: rate2 }).passthrough(),
404
+ recovery,
405
+ calibration: import_zod4.z.discriminatedUnion("status", [
406
+ import_zod4.z.object({ status: import_zod4.z.literal("uncalibrated"), n_gold: count2.optional(), verifierFalsePassRate: rate2.optional() }).passthrough(),
407
+ import_zod4.z.object({ status: import_zod4.z.literal("calibrated"), n_gold: count2, verifierFalsePassRate: rate2 }).passthrough()
408
+ ]),
409
+ perSplit: import_zod4.z.object({
410
+ natural: cell,
411
+ "held-out": import_zod4.z.object({ shared: cell, private: cell }).passthrough(),
412
+ adversarial: cell,
413
+ unassignedCount: count2
414
+ }).passthrough()
415
+ }).passthrough();
416
+
417
+ // src/report-store.ts
418
+ var import_node_fs11 = require("fs");
419
+ var import_node_path11 = require("path");
420
+ var import_agent_qa_eval7 = require("@vostride/agent-qa-eval");
421
+ var import_agent_qa_schema7 = require("@vostride/agent-qa-schema");
422
+ var import_zod5 = require("zod");
423
+ var calibrationCount = import_zod5.z.number().int().nonnegative().safe();
424
+ var calibrationUnit = import_zod5.z.number().finite().min(0).max(1);
425
+ var copiedInterval = import_zod5.z.object({
426
+ lower: calibrationUnit,
427
+ upper: calibrationUnit,
428
+ halfWidth: calibrationUnit.max(0.5)
429
+ }).strict().refine((value) => value.lower <= value.upper && value.upper - value.lower <= 2 * value.halfWidth + Number.EPSILON * 4);
430
+ var consistentAgreement = (n, agreement) => agreement === Math.round(n * agreement) / n;
431
+ var copiedMember = import_zod5.z.object({
432
+ judgeModelId: import_zod5.z.string(),
433
+ n: calibrationCount,
434
+ agreement: calibrationUnit.optional(),
435
+ wilson95: copiedInterval.optional()
436
+ }).strict().refine((value) => value.n === 0 ? value.agreement === void 0 && value.wilson95 === void 0 : value.agreement !== void 0 && value.wilson95 !== void 0 && consistentAgreement(value.n, value.agreement));
437
+ var copiedCalibration = import_zod5.z.discriminatedUnion("status", [
438
+ import_zod5.z.object({
439
+ status: import_zod5.z.literal("calibrated"),
440
+ n: calibrationCount.min(2),
441
+ pooledAgreement: calibrationUnit,
442
+ wilson95: copiedInterval,
443
+ perMember: import_zod5.z.array(copiedMember).min(2).max(3)
444
+ }).strict().refine((value) => consistentAgreement(value.n, value.pooledAgreement)),
445
+ import_zod5.z.object({
446
+ status: import_zod5.z.literal("uncalibrated"),
447
+ n: calibrationCount,
448
+ provenance: import_zod5.z.literal("unavailable").optional()
449
+ }).strict().refine((value) => value.provenance === void 0 || value.n === 0),
450
+ import_zod5.z.object({
451
+ status: import_zod5.z.literal("capability-gap"),
452
+ reason: import_zod5.z.enum(["panel-not-configured", "no-credential", "single-family-host"])
453
+ }).strict()
454
+ ]);
455
+ var reportJudgeSchema = import_agent_qa_eval7.judgeIdentitySchema.safeExtend({ calibration: copiedCalibration.optional() }).refine((judge) => {
456
+ const calibration = judge.calibration;
457
+ if (calibration === void 0) return true;
458
+ if (judge.panelSize === void 0 || judge.members === void 0) return false;
459
+ if (calibration.status !== "calibrated") return true;
460
+ const memberIds = calibration.perMember.map((member) => member.judgeModelId).sort();
461
+ return calibration.perMember.length === judge.members.length && memberIds.every((id, index) => id === judge.members[index].judgeModelId);
462
+ }, "calibration requires the complete recorded composite identity");
463
+ var stagedReportSchema = import_zod5.z.object({
464
+ batchKey: import_zod5.z.string().min(1),
465
+ matcherVersion: import_zod5.z.number().int().nonnegative(),
466
+ headline: import_zod5.z.object({
467
+ perDecisionCost: import_zod5.z.object({ decisionCount: import_zod5.z.number() }).passthrough()
468
+ }).passthrough(),
469
+ // Optional historical provenance remains optional; malformed mixed identities must never
470
+ // reach the comparator's renderer as though its judge-id list were a string array.
471
+ judgeIdentity: import_zod5.z.literal("mixed").optional(),
472
+ mixedJudgeModelIds: import_zod5.z.array(import_zod5.z.string()).optional(),
473
+ judge: reportJudgeSchema.optional()
474
+ }).passthrough().refine((report) => report.judgeIdentity !== "mixed" || report.judge === void 0);
475
+ var replayGenerationSchema = import_zod5.z.object({
476
+ seed: import_zod5.z.number().int().safe(),
477
+ records: import_zod5.z.array(
478
+ import_zod5.z.object({
479
+ cassetteId: import_zod5.z.string().min(1),
480
+ replayDigest: import_zod5.z.string().regex(/^[a-f0-9]{64}$/),
481
+ scoreDigest: import_zod5.z.string().regex(/^[a-f0-9]{64}$/).nullable()
482
+ }).strict()
483
+ )
484
+ }).strict();
485
+ var publicationSchema = import_zod5.z.object({
486
+ schemaVersion: import_zod5.z.literal(2),
487
+ reportDigest: import_zod5.z.string().regex(/^[a-f0-9]{64}$/),
488
+ decisionsDigest: import_zod5.z.string().regex(/^[a-f0-9]{64}$/).nullable(),
489
+ replayGeneration: replayGenerationSchema.optional()
490
+ }).strict();
491
+
492
+ // src/committed-corpus-source.ts
493
+ var reportSchema = import_zod6.z.object({
494
+ batchKey: import_zod6.z.string(),
495
+ matcherVersion: import_zod6.z.number(),
496
+ judgeIdentity: import_zod6.z.literal("mixed").optional(),
497
+ mixedJudgeModelIds: import_zod6.z.array(import_zod6.z.string()).optional(),
498
+ headline: import_zod6.z.object({ perDecisionCost: import_zod6.z.object({ decisionCount: import_zod6.z.number() }).passthrough() }).passthrough(),
499
+ honesty: import_zod6.z.object({
500
+ unscorableIdentityCounts: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.number()),
501
+ refusalCounts: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.number())
502
+ }).passthrough(),
503
+ judge: reportJudgeSchema.optional()
504
+ }).passthrough().refine((report) => report.judgeIdentity !== "mixed" || report.judge === void 0);
505
+ var baselinePointerSchema = import_zod6.z.object({
506
+ schemaVersion: import_zod6.z.literal(import_agent_qa_eval8.BASELINE_POINTER_SCHEMA_VERSION),
507
+ profileKey: import_zod6.z.string(),
508
+ batchKey: import_zod6.z.string(),
509
+ fingerprint: import_zod6.z.string(),
510
+ corpusDigest: import_zod6.z.string()
511
+ }).passthrough();
512
+ function listDirNames(dir) {
513
+ try {
514
+ return (0, import_node_fs12.readdirSync)(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
515
+ } catch {
516
+ return [];
517
+ }
518
+ }
519
+ function listJsonFiles(dir) {
520
+ const found = [];
521
+ function walk(current2) {
522
+ let entries;
523
+ try {
524
+ entries = (0, import_node_fs12.readdirSync)(current2, { withFileTypes: true });
525
+ } catch {
526
+ return;
527
+ }
528
+ for (const entry of entries) {
529
+ const path = (0, import_node_path12.join)(current2, entry.name);
530
+ if (entry.isDirectory()) walk(path);
531
+ else if (entry.isFile() && entry.name.endsWith(".json")) found.push(path);
532
+ }
533
+ }
534
+ walk(dir);
535
+ return found.sort();
536
+ }
537
+ function readJson(path) {
538
+ let raw;
539
+ try {
540
+ raw = (0, import_node_fs12.readFileSync)(path, "utf8");
541
+ } catch (error) {
542
+ return { ok: false, reason: `unreadable: ${error.message}` };
543
+ }
544
+ try {
545
+ return { ok: true, value: JSON.parse(raw) };
546
+ } catch (error) {
547
+ return { ok: false, reason: `invalid JSON: ${error.message}` };
548
+ }
549
+ }
550
+ function bumpCounter(counter, key) {
551
+ counter[key] = (counter[key] ?? 0) + 1;
552
+ }
553
+ function blobsPresent(bundleDir) {
554
+ const blobsDir = (0, import_node_path12.join)(bundleDir, BLOBS_SUBDIR);
555
+ if (!(0, import_node_fs12.existsSync)(blobsDir)) return false;
556
+ try {
557
+ return (0, import_node_fs12.readdirSync)(blobsDir).length > 0;
558
+ } catch {
559
+ return false;
560
+ }
561
+ }
562
+ function readCommittedCorpus(committedRoot, calibrationRead) {
563
+ const notices = [];
564
+ const refusals = [];
565
+ const entries = [];
566
+ const schemaVersionsSeen = {};
567
+ const labelsById = /* @__PURE__ */ new Map();
568
+ const labelHistory = [];
569
+ const excludedLabelIds = /* @__PURE__ */ new Set();
570
+ const cassettesById = /* @__PURE__ */ new Map();
571
+ const blobPresentById = /* @__PURE__ */ new Map();
572
+ if (!(0, import_node_fs12.existsSync)(committedRoot)) {
573
+ notices.push(`committed root absent: ${committedRoot}`);
574
+ return {
575
+ snapshot: { entries, labelsById, cassettesById, blobPresentById, labelHistory, excludedLabelIds },
576
+ productsSeen: [],
577
+ notices,
578
+ refusals,
579
+ schemaVersionsSeen
580
+ };
581
+ }
582
+ const corpusRoot = (0, import_node_path12.join)(committedRoot, COMMITTED_CORPUS_DIR);
583
+ const productsSeen = listDirNames(corpusRoot);
584
+ for (const product of productsSeen) {
585
+ for (const path of listJsonFiles((0, import_node_path12.join)(corpusRoot, product))) {
586
+ const read = readJson(path);
587
+ if (!read.ok) {
588
+ refusals.push({ path, reason: read.reason });
589
+ continue;
590
+ }
591
+ const parsed = (0, import_agent_qa_eval8.parseCorpusEntry)(read.value);
592
+ if (!parsed.ok) {
593
+ refusals.push({ path, reason: `corpus entry rejected: ${parsed.issues}` });
594
+ continue;
595
+ }
596
+ if (parsed.entry.product !== product) {
597
+ notices.push(
598
+ `corpus dir '${product}' holds an entry declaring product '${parsed.entry.product}' (${parsed.entry.cassetteId}); the entry field is authoritative`
599
+ );
600
+ }
601
+ entries.push(parsed.entry);
602
+ bumpCounter(schemaVersionsSeen, String(parsed.schemaVersion));
603
+ }
604
+ }
605
+ const labelsRoot = (0, import_node_path12.join)(committedRoot, COMMITTED_LABELS_DIR);
606
+ const labelOwners = /* @__PURE__ */ new Map();
607
+ const idsByBasePath = /* @__PURE__ */ new Map();
608
+ for (const entry of entries) {
609
+ const owners = labelOwners.get(entry.cassetteId) ?? /* @__PURE__ */ new Set();
610
+ owners.add((0, import_agent_qa_schema8.slugBranch)(entry.product));
611
+ labelOwners.set(entry.cassetteId, owners);
612
+ const path = (0, import_node_path12.join)(committedRoot, committedLabelPath(entry.product, entry.cassetteId));
613
+ const ids = idsByBasePath.get(path) ?? /* @__PURE__ */ new Set();
614
+ ids.add(entry.cassetteId);
615
+ idsByBasePath.set(path, ids);
616
+ }
617
+ const readInvalidIds = /* @__PURE__ */ new Set();
618
+ const validHistory = [];
619
+ for (const product of listDirNames(labelsRoot)) {
620
+ for (const path of listJsonFiles((0, import_node_path12.join)(labelsRoot, product))) {
621
+ const basePath = path.replace(/--revision-[^/]*\.json$/, ".json");
622
+ const pathIds = idsByBasePath.get(basePath) ?? /* @__PURE__ */ new Set();
623
+ const refuse = (reason, cassetteId) => {
624
+ refusals.push({ path, reason });
625
+ for (const id of pathIds) readInvalidIds.add(id);
626
+ if (cassetteId !== void 0) readInvalidIds.add(cassetteId);
627
+ };
628
+ const read = readJson(path);
629
+ if (!read.ok) {
630
+ refuse("label record unreadable or invalid JSON");
631
+ continue;
632
+ }
633
+ labelHistory.push(read.value);
634
+ const parsed = (0, import_agent_qa_eval8.parseStandaloneLabelRecord)(read.value);
635
+ if (!parsed.ok) {
636
+ const claimedId = typeof read.value === "object" && read.value !== null && "cassetteId" in read.value && typeof read.value.cassetteId === "string" ? read.value.cassetteId : void 0;
637
+ refuse(`label record rejected: ${parsed.issues}`, claimedId);
638
+ continue;
639
+ }
640
+ const record = parsed.record;
641
+ const expectedBase = (0, import_node_path12.join)(committedRoot, committedLabelPath(product, record.cassetteId));
642
+ const expectedPath = record.revision === void 0 ? expectedBase : expectedBase.replace(/\.json$/, `--revision-${record.revision.id}.json`);
643
+ const owners = labelOwners.get(record.cassetteId);
644
+ if (path !== expectedPath || owners !== void 0 && (owners.size !== 1 || !owners.has(product))) {
645
+ refuse("label path or product ownership mismatch", record.cassetteId);
646
+ continue;
647
+ }
648
+ validHistory.push(record);
649
+ }
650
+ }
651
+ const calibration = calibrationRead ?? readLabelCalibration(committedRoot);
652
+ const authorized = calibration.kind === "loaded" ? calibration.authorizedRevisionIds : /* @__PURE__ */ new Set();
653
+ const eligibleHistory = validHistory.filter((record) => record.revision?.generationId === void 0 || authorized.has(record.revision.id));
654
+ const generations = new Set(eligibleHistory.flatMap((record) => record.revision?.generationId ? [record.revision.generationId] : []));
655
+ if (calibration.kind === "refused") {
656
+ refusals.push({ path: (0, import_node_path12.join)(labelsRoot, "calibration.json"), reason: calibration.reason });
657
+ for (const id of calibration.targetCassetteIds ?? []) readInvalidIds.add(id);
658
+ for (const record of validHistory) if (record.revision?.generationId) readInvalidIds.add(record.cassetteId);
659
+ }
660
+ const selected = (0, import_agent_qa_eval8.selectEffectiveLabels)(eligibleHistory, { committedGenerationIds: generations });
661
+ for (const [id, label] of selected.effective) {
662
+ if (!readInvalidIds.has(id)) labelsById.set(id, label);
663
+ }
664
+ for (const id of [...readInvalidIds, ...selected.excludedLabelIds]) excludedLabelIds.add(id);
665
+ for (const refusal of selected.refusals) {
666
+ refusals.push({ path: labelsRoot, reason: `label history rejected: ${refusal.reason}` });
667
+ }
668
+ for (const bundleDir of listCassetteBundleDirs((0, import_node_path12.join)(committedRoot, COMMITTED_CASSETTES_DIR))) {
669
+ const load = loadCassetteBundle(bundleDir);
670
+ if (load.kind === "refused") {
671
+ refusals.push({
672
+ path: (0, import_node_path12.join)(bundleDir, "cassette.json"),
673
+ reason: `${load.refusal.reason}: ${load.refusal.detail}`
674
+ });
675
+ continue;
676
+ }
677
+ if (load.cassette.granularity !== "leaf") {
678
+ notices.push(`skipped non-leaf cassette bundle: ${bundleDir}`);
679
+ continue;
680
+ }
681
+ cassettesById.set(load.cassette.id, load.cassette);
682
+ blobPresentById.set(load.cassette.id, blobsPresent(bundleDir));
683
+ }
684
+ entries.sort(
685
+ (first, second) => first.cassetteId < second.cassetteId ? -1 : first.cassetteId > second.cassetteId ? 1 : 0
686
+ );
687
+ return {
688
+ corpusEntriesById: new Map(entries.map((entry) => [entry.cassetteId, entry])),
689
+ calibration: calibration.kind === "loaded" ? {
690
+ status: calibration.artifact.channels["recorded-verdict"].status,
691
+ n_gold: calibration.artifact.channels["recorded-verdict"].n_gold,
692
+ verifierFalsePassRate: calibration.artifact.verifierFalsePassRate
693
+ } : { status: "uncalibrated" },
694
+ snapshot: {
695
+ entries: entries.filter((entry) => !excludedLabelIds.has(entry.cassetteId)),
696
+ labelsById,
697
+ cassettesById,
698
+ blobPresentById,
699
+ labelHistory,
700
+ excludedLabelIds
701
+ },
702
+ productsSeen,
703
+ notices,
704
+ refusals,
705
+ schemaVersionsSeen
706
+ };
707
+ }
708
+
709
+ // src/corpus-reader.ts
710
+ function openCorpusReader(committedRoot) {
711
+ let slice;
712
+ function load() {
713
+ if (slice === void 0) {
714
+ const read = readCommittedCorpus(committedRoot);
715
+ const visible = read.snapshot.entries.filter(
716
+ (entry) => (0, import_agent_qa_eval9.isProposerVisibleEntry)(entry)
717
+ );
718
+ slice = {
719
+ visible,
720
+ visibleIds: new Set(visible.map((entry) => entry.cassetteId)),
721
+ cassettesById: read.snapshot.cassettesById,
722
+ labelsById: read.snapshot.labelsById
723
+ };
724
+ }
725
+ return slice;
726
+ }
727
+ return {
728
+ listEntries(product) {
729
+ const { visible } = load();
730
+ if (product === void 0) return visible;
731
+ return visible.filter((entry) => entry.product === product);
732
+ },
733
+ loadCassette(cassetteId) {
734
+ const { visibleIds, cassettesById } = load();
735
+ if (!visibleIds.has(cassetteId)) return { kind: "not-found" };
736
+ const cassette = cassettesById.get(cassetteId);
737
+ if (cassette === void 0) return { kind: "not-found" };
738
+ return { kind: "loaded", cassette };
739
+ },
740
+ loadLabel(cassetteId) {
741
+ const { visibleIds, labelsById } = load();
742
+ if (!visibleIds.has(cassetteId)) return { kind: "not-found" };
743
+ const record = labelsById.get(cassetteId);
744
+ if (record === void 0) return { kind: "not-found" };
745
+ return { kind: "loaded", record };
746
+ }
747
+ };
748
+ }
749
+ // Annotate the CommonJS export names for ESM import in node:
750
+ 0 && (module.exports = {
751
+ openCorpusReader
752
+ });
753
+ //# sourceMappingURL=reader.cjs.map