@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 @@
1
+ {"version":3,"sources":["../src/adversarial-composition.ts","../src/adversarial-state.ts","../src/committed-root-store.ts","../src/cassette-store.ts","../src/corpus-reader.ts","../src/committed-corpus-source.ts","../src/cassette-loader.ts","../src/artifact-source.ts","../src/replay-read.ts","../src/replay-record-store.ts","../src/score-store.ts","../src/mark-ledger.ts","../src/mark-lock.ts","../src/calibration-source.ts","../src/report-metadata-guard.ts","../src/report-store.ts","../src/gate2-composition.ts","../src/replay-sweep.ts","../src/replay-composition.ts","../src/judge-binding.ts","../src/replay-batch-assembly.ts","../src/seeding-composition.ts","../src/replay-gate-composition.ts","../src/baseline-cache-read.ts","../src/baseline-cache-guards.ts","../src/judge-calibration-composition.ts","../src/judge-calibration-evidence-source.ts","../src/judge-calibration-source.ts","../src/calibration-composition.ts","../src/calibration-evidence-source.ts","../src/label-evidence-source.ts","../src/golden-composition.ts","../src/census-committing.ts","../src/handoff-source.ts","../src/aa-floor-composition.ts","../src/committed-corpus-admission.ts","../src/noise-floor-writer.ts","../src/measured-floor-read.ts","../src/release-gate-composition.ts","../src/report-committing.ts","../src/baseline-pointer.ts","../src/gate-posture-composition.ts"],"sourcesContent":["// 2026-09-11, 422 D-01/D-02/D-03/D-06/D-07/D-08: the adversarial staging and admission\n// composition — the 418 D-21 feedback idiom (gate2-composition.ts) pointed at generated\n// cassettes instead of observed ones.\n//\n// Authority law (D-01): NOTHING here commits on its own. `stageAdversarialProposal` derives\n// concrete bytes and publishes them as LOCAL AUDIT DATA under\n// `.agent-qa/eval/adversarial/<product>/<batchDigest>`; `refreshAdversarialSplit` is the only\n// function that touches the committed root, and its sole production caller is the explicit\n// `eval adversarial --admit --batch <digest>` branch. An operator reviews real\n// injection-shaped text before it can enter a git-tracked root.\n//\n// Content law (441 D-15, GAP3-D1): staged and admitted cases are committed as authored, and the\n// operator's review of the exact bytes is the gate. The one check is the declared mask: admission\n// never rewrites reviewed bytes, so a staged case that still holds a declared value raw is refused\n// by the seeding writer and reported as an `unmasked-declared-value` staging skip.\n//\n// Exact-byte law (D-02): the reviewed manifest pins the sha256 of each staged document, and\n// the batch digest is a function of those pins. Admission re-reads the staged bytes, re-hashes\n// them against the manifest, re-derives the digest from the manifest's own case list, and\n// requires the operator's `--batch` digest to equal both — so recomputing a manifest after an\n// edit is not admission authority, it is a mismatch. Nothing is re-generated at admission: a\n// regenerated label or a fresh timestamp would mean the operator reviewed other bytes.\n//\n// Blob law: referenced blob bytes are VALIDATED by content address against the seed's\n// committed blobs and are never copied into staging. They are copied into the committed root\n// only at admission, by the one sanctioned seeding writer, under the derived cassette's own\n// path — which is what makes a fresh reader's blob closure resolvable.\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\n\nimport {\n ADVERSARIAL_INAPPLICABILITIES,\n ADVERSARIAL_MUTATORS,\n ADVERSARIAL_PROMPT_VERSION,\n ADVERSARIAL_TABLE_HASH,\n ADVERSARIAL_TABLE_VERSION,\n ADVERSARIAL_TABLES,\n GENERATOR_KINDS,\n PROBE_GENERATOR_KINDS,\n buildProbeRequest,\n canonicalJson,\n committedFileText,\n deriveAdversarialCassetteId,\n deriveProbeCassette,\n deriveRunSlug,\n generateAdversarialVariants,\n guardCassette,\n guardCorpusEntry,\n isProbeGeneratorKind,\n parseStandaloneLabelRecord,\n type AdversarialCapSource,\n type AdversarialCorpusEntry,\n type AdversarialMutator,\n type AdversarialSeed,\n type AdversarialSeedSkip,\n type AuthoringModel,\n type CorpusGenerator,\n type ExtractedBlob,\n type ExtractedCassette,\n type GeneratorKind,\n type LeafCassette,\n type NoProbeModelGap,\n type ProbeAuthorPort,\n type ProbeGeneratorKind,\n type ProbeInapplicability,\n type ProbeRefusal,\n type ProbeText,\n type SeedingPlan,\n type StandaloneLabelRecord,\n} from '@vostride/agent-qa-eval'\nimport { slugBranch, type MaskFn } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport {\n ADVERSARIAL_PROBE_SCHEMA_VERSION,\n ADVERSARIAL_STATE_SCHEMA_VERSION,\n adversarialRefreshRecordDigest,\n adversarialTupleKey,\n completeProbeCall,\n derivedAdversarialCassetteIds,\n probeReservationOf,\n publishAdversarialRefreshRecord,\n readAdversarialRefreshRecords,\n readProbeAttempt,\n reserveProbeCall,\n resolveAdversarialSeedCap,\n settledAdversarialTupleIndex,\n type AdversarialRefreshRecord,\n type AdversarialRefreshTuple,\n type AdversarialSeedCap,\n type ProbeCompletion,\n type ProbeReservationKey,\n} from './adversarial-state.js'\nimport { committedBlobPath, committedCassettePath, committedCorpusPath, committedLabelPath } from './committed-root-store.js'\nimport { openCorpusReader } from './corpus-reader.js'\nimport { readCommittedCorpus } from './committed-corpus-source.js'\nimport { readCommittedCorpusDigest } from './gate2-composition.js'\nimport { requireCorpusMask, seedCommittedCorpus, type SeedingBatchReport } from './seeding-composition.js'\n\n/** Local staging root for reviewable adversarial batches (D-01, beside `eval/feedback`). */\nexport const ADVERSARIAL_STAGING_SUBDIR = 'eval/adversarial'\n\n/** The reviewed manifest's file name inside a staged batch directory. */\nexport const ADVERSARIAL_MANIFEST_FILE = 'manifest.json'\n\nconst LOWER_HEX_64 = /^[0-9a-f]{64}$/\nconst digestField = z.string().regex(LOWER_HEX_64)\n\n/**\n * The SEED's label identity as it stood when the batch was reviewed (D-06).\n *\n * This is the pin that a recomputed manifest cannot launder. Every other pin here describes\n * STAGED bytes, so an operator who edits a staged document and regenerates the manifest gets\n * a self-consistent manifest — with a different digest, which is already refused. This one is\n * checked against the seed's COMMITTED label at admission, so a derived record whose\n * provenance, channel or tier was rewritten to something the seed never had is refused even\n * if every staged pin agrees with itself.\n */\nexport interface AdversarialSeedProvenancePin {\n runId: string\n capturedAtOrdinal: number\n sourceChannel: string\n tier: string\n}\n\n/**\n * One reviewed case, pinned by content address (D-02).\n *\n * TWO DERIVATION PATHS, TWO PROVENANCE SHAPES (D-05/D-11). A table-drawn variant names\n * `mutator` + `tableEntryId`; an LLM-authored probe names `promptVersion` and neither of the\n * other two, because no frozen table drew its text. The pair is mutually exclusive and\n * `listStagedAdversarial` refuses a case that carries both or neither — a manifest case whose\n * provenance cannot be true is exactly what a refusal is for.\n *\n * The author's model id is deliberately NOT pinned here. It is already on the corpus entry,\n * whose bytes the manifest pins.\n */\nexport interface AdversarialBatchManifestCase {\n cassetteId: string\n seedCassetteId: string\n /** Table path only: the mutation family. Absent on a probe. */\n mutator?: AdversarialMutator\n kind: GeneratorKind\n /** Table path only. Disclosure of the drawn table entry; not part of the derived identity (D-08). */\n tableEntryId?: string\n /** Probe path only: the frozen prompt generation the text was authored under (D-11). */\n promptVersion?: number\n cassetteTextHash: string\n labelTextHash: string\n entryTextHash: string\n /** The ORIGINAL label identity the clone must still carry (D-06). */\n seedProvenance: AdversarialSeedProvenancePin\n /** The derived cassette's blob closure, validated against the seed's committed bytes. */\n blobShas: readonly string[]\n}\n\n/** The reviewed batch: what an operator admits with `--batch <digest>` (D-01/D-02). */\nexport interface AdversarialBatchManifest {\n schemaVersion: 2\n product: string\n /** sha256 over the pinned case list; equals the staging directory name. */\n batchDigest: string\n tableVersion: number\n tableHash: string\n /** Disclosure only — deliberately OUTSIDE the digest so re-staging is idempotent. */\n stagedAt: string\n cases: readonly AdversarialBatchManifestCase[]\n}\n\nconst manifestCaseSchema = z.object({\n cassetteId: z.string().min(1),\n seedCassetteId: z.string().min(1),\n mutator: z.enum(ADVERSARIAL_MUTATORS).optional(),\n kind: z.enum(GENERATOR_KINDS),\n tableEntryId: z.string().min(1).optional(),\n promptVersion: z.number().int().nonnegative().optional(),\n cassetteTextHash: digestField,\n labelTextHash: digestField,\n entryTextHash: digestField,\n seedProvenance: z.object({\n runId: z.string().min(1),\n capturedAtOrdinal: z.number().int().nonnegative(),\n sourceChannel: z.string().min(1),\n tier: z.string().min(1),\n }).strict(),\n blobShas: z.array(digestField),\n}).strict()\n\nconst manifestSchema = z.object({\n schemaVersion: z.literal(2),\n product: z.string().min(1),\n batchDigest: digestField,\n tableVersion: z.number().int().nonnegative(),\n tableHash: digestField,\n stagedAt: z.iso.datetime(),\n cases: z.array(manifestCaseSchema).min(1),\n}).strict()\n\n/** A per-detector refusal row. Nothing produces one since 441-42 (D-15); the field stays empty. */\nexport interface AdversarialRefusal {\n cassetteId: string\n seedCassetteId: string\n generator: GeneratorKind\n detector: string\n action: 'block' | 'redact'\n}\n\n/**\n * A refusal a previous refresh recorded. Nothing produces one since 441-53 (D-15): the refresh\n * record no longer holds a refused tuple, so the field stays empty.\n */\nexport interface AdversarialSettledRefusal {\n seedCassetteId: string\n mutator: AdversarialMutator\n detector?: string\n}\n\n/** Everything that stopped a derived case short of publication for a non-policy reason. */\nexport interface AdversarialStagingSkip {\n cassetteId: string\n seedCassetteId: string\n reason:\n | 'blob-unresolvable'\n | 'blob-hash-mismatch'\n | 'text-hash-mismatch'\n | 'manifest-digest-mismatch'\n | 'path-identity-mismatch'\n | 'seed-label-unavailable'\n | 'seed-provenance-mismatch'\n /** This id is already committed with DIFFERENT bytes. History wins; nothing is overwritten. */\n | 'committed-conflict'\n /** 441 GAP3-D1: a reviewed string still holds a declared value raw; the writer refused it. */\n | 'unmasked-declared-value'\n}\n\n// ---------------------------------------------------------------------------\n// The AUTHORED half (D-09/D-10/D-11): bounded provider spend, accounted for.\n// ---------------------------------------------------------------------------\n\n/**\n * Recorded default cap on PROVIDER CALLS one refresh may make (D-04/D-10).\n *\n * The rationale, stated rather than tuned: a refresh authors at most one probe per\n * `(seed, kind, promptVersion)` tuple, and the two frozen probe kinds over two seeds is four\n * requested generations. It is deliberately INDEPENDENT of\n * `ADVERSARIAL_DEFAULT_MAX_SEEDS_PER_REFRESH` — eight deterministic seeds cost nothing but CPU,\n * while four authored probes cost four provider calls that no later run can recover. Two\n * budgets, because the two halves are bounded for two different reasons.\n *\n * It counts CALLS and not tokens. A provider that reports no usage yields zero tokens\n * (422-05), which UNDER-states spend; an unreported token must never be readable as \"free\", so\n * the budget is denominated in the one quantity this layer always knows exactly.\n */\nexport const ADVERSARIAL_DEFAULT_MAX_PROBE_CALLS = 4\n\n/**\n * The resolved probe-call cap and where the operator set it (the seed-cap idiom).\n *\n * 2026-09-12, 422-22: `source` names the NEUTRAL `AdversarialCapSource` for the same reason the\n * seed cap does — this value is recorded beside every refresh, and a second storage-side spelling\n * of a persisted vocabulary is a second list to keep in step with the first.\n */\nexport interface AdversarialProbeCallCap {\n value: number\n source: AdversarialCapSource\n}\n\n/**\n * What a refresh SPENT at a provider.\n *\n * `modelCalls` is the authoritative number and is counted at RESERVATION time, not at answer\n * time: a call that was announced and never answered still cost whatever it cost, and counting\n * only answers would let an interrupted refresh under-report its bill. Token counts are carried\n * exactly as the provider reported them and are never inferred.\n */\nexport interface AdversarialSpend {\n modelCalls: number\n promptTokens: number\n completionTokens: number\n /**\n * Whether every call counted above reported its token usage.\n *\n * `false` is a statement, not a warning: a call that was announced and never answered, or one\n * that failed, has UNKNOWN tokens, and the alternative to saying so is reporting `0` — which\n * makes a real charge indistinguishable from a free one. It is exactly the reason the budget\n * is denominated in calls rather than in tokens.\n */\n usageKnown: boolean\n}\n\n/**\n * Why a `(seed, kind, promptVersion)` tuple yielded no authored probe.\n *\n * The first members are the pure contract's own seed law, re-reported verbatim so a staging\n * report speaks ONE vocabulary about table families and probes alike. The last two are this\n * layer's: a tuple already decided by a previous refresh, and a tuple this refresh's call\n * budget deferred to the next one.\n */\nexport type AdversarialProbeSkipReason =\n | ProbeInapplicability\n | 'tuple-already-decided'\n /**\n * A durable reservation exists with no completion: a previous run announced this call and\n * never recorded an answer. It is CHARGED and it is NOT re-authored — re-asking would buy the\n * same question twice — and it is its own reason precisely because \"asked and lost\" is a\n * different fact from \"asked and answered\" and from \"never asked\".\n */\n | 'tuple-interrupted'\n | 'probe-cap-exceeded'\n /** Paid output belongs to a different author or prompt; never implicitly re-author it. */\n | 'probe-reservation-mismatch'\n /** Re-derivation must recover the identity already recorded with the paid response. */\n | 'probe-completion-identity-mismatch'\n\n/** An honest row for every probe tuple that produced no case. */\nexport interface AdversarialProbeSkip {\n seedCassetteId: string\n kind: ProbeGeneratorKind\n promptVersion: number\n reason: AdversarialProbeSkipReason\n}\n\n/**\n * An authored RESPONSE the pure contract refused.\n *\n * It says the model's answer was not a usable probe — too long, not a name, folded back onto the\n * recorded identity. It names no text either, for the same reason.\n */\nexport interface AdversarialProbeRefusal {\n seedCassetteId: string\n kind: ProbeGeneratorKind\n promptVersion: number\n reason: ProbeRefusal\n}\n\nexport interface StageAdversarialProposalInput {\n agentQaRoot: string\n committedRoot: string\n product: string\n mutators?: readonly AdversarialMutator[]\n /** D-04: the per-refresh NOVEL-seed cap; absent resolves to the recorded default. */\n maxSeeds?: number\n /** Where `maxSeeds` came from, recorded beside the refresh. Absent with a value means 'flag'. */\n maxSeedsSource?: Exclude<AdversarialCapSource, 'default'>\n /**\n * D-10: the bound author, or nothing.\n *\n * A PORT and never a model: this package constructs no provider client and sees no profile,\n * credential or provider name. Absent means this refresh authors nothing at all — the frozen\n * families still derive, because a host with no eligible author is not a host with no\n * adversarial corpus.\n */\n probeAuthor?: ProbeAuthorPort\n /** D-11: the identity every authored entry stamps. Required with `probeAuthor`. */\n authoringModel?: AuthoringModel\n /** D-09: the host's capability gap, reported on the batch when there is no author. */\n noProbeModel?: NoProbeModelGap\n /** D-04/D-10: the per-refresh provider-CALL cap; absent resolves to the recorded default. */\n maxProbeCalls?: number\n /** Where `maxProbeCalls` came from. Absent with a value means 'flag'. */\n maxProbeCallsSource?: Exclude<AdversarialCapSource, 'default'>\n /** Derive, publish nothing — neither staged bytes nor a settle record. */\n dryRun?: boolean\n}\n\nexport interface StagedAdversarialCase {\n cassetteId: string\n seedCassetteId: string\n /** Table path only. */\n mutator?: AdversarialMutator\n kind: GeneratorKind\n /** Table path only. */\n tableEntryId?: string\n /** Probe path only: the frozen prompt generation this text was authored under (D-11). */\n promptVersion?: number\n}\n\nexport interface StageAdversarialProposalResult {\n kind: 'staged' | 'unchanged' | 'dry-run' | 'nothing-derived'\n product: string\n batchDigest?: string\n dir?: string\n staged: readonly StagedAdversarialCase[]\n refusals: readonly AdversarialRefusal[]\n skips: readonly AdversarialSeedSkip[]\n stagingSkips: readonly AdversarialStagingSkip[]\n seedsConsidered: number\n seedsDeferred: number\n tableVersion: number\n tableHash: string\n /**\n * D-04: the committed root's GATE posture, not the reader's length.\n *\n * `openCorpusReader` answers an absent, unmarked or unreadable root with an empty list —\n * byte-identical to a healthy root that genuinely holds no visible entry. Only the gate's own\n * digest read establishes the root, and a refresh that cannot establish it settles nothing:\n * a settle record written against silence is evidence manufactured from an outage.\n */\n rootPosture: 'available' | 'unavailable'\n /** The corpus digest this refresh read its seeds from; absent when the posture is unavailable. */\n sourceDigest?: string\n /** The resolved cap and its source, recorded beside every refresh. */\n cap: AdversarialSeedCap\n /** NOVEL eligible seeds, counted BEFORE the cap; `seedsDeferred` is the overflow. */\n eligibleSeeds: number\n /** The durable refresh record this refresh published, if it published one. */\n stateRecordDigest?: string\n /** Always empty since 441-53 (D-15). */\n settledRefusals: readonly AdversarialSettledRefusal[]\n /**\n * D-09: why this host authored no probes.\n *\n * ABSENT means the capability was never consulted (an admission, or a caller that declined to\n * resolve credentials) — which is a different fact from \"consulted, and there is no author\".\n * Collapsing the two would let a host that never asked read as a host that has nothing.\n */\n noProbeModel?: NoProbeModelGap\n /** The identity that authored this refresh's probes; absent when none were authored. */\n authoringModel?: AuthoringModel\n /** The resolved provider-call cap and its source, recorded beside every refresh. */\n probeCap: AdversarialProbeCallCap\n /** What this refresh actually spent at a provider. */\n spend: AdversarialSpend\n /** Every probe tuple that produced no case, and why. */\n probeSkips: readonly AdversarialProbeSkip[]\n /** Authored responses the pure contract refused. */\n probeRefusals: readonly AdversarialProbeRefusal[]\n /**\n * Calls a PREVIOUS run announced and never recorded an answer for, still charged against\n * their tuples. Reported separately from `spend.modelCalls`, which counts only what THIS\n * refresh asked: folding them together would claim this run made a call it did not.\n */\n interruptedProbeCalls: number\n}\n\n/** A staged batch loaded back from disk with its bytes verified against the manifest pins. */\nexport interface StagedAdversarialBatch {\n dir: string\n manifest: AdversarialBatchManifest\n retirement?: AdversarialRetirementRecord\n cases: readonly {\n manifest: AdversarialBatchManifestCase\n caseDir: string\n cassette: LeafCassette\n labelRecord: StandaloneLabelRecord\n corpusEntry: AdversarialCorpusEntry\n /** The EXACT reviewed bytes; admission never re-serializes from the parsed objects. */\n texts: { cassette: string; label: string; entry: string }\n }[]\n}\n\nexport interface RefreshAdversarialSplitInput {\n agentQaRoot: string\n committedRoot: string\n product: string\n /** The reviewed batch digest the operator named; exact, never \"the latest\". */\n batchDigest: string\n dryRun?: boolean\n /** Snapshot host receipts only after validation, under lifecycle ownership, before writes. */\n beforeWrites?: () => void\n /**\n * Runs after ONE case's bytes have landed and been byte-verified.\n *\n * An observation and fault-injection seam. Admission is the only place in this composition\n * where an interruption can leave the committed root part-way through a reviewed batch, and\n * \"a case that landed stays landed\" is not a claim anything could check without a way to\n * interrupt it between cases. A throw here is treated exactly like a real IO failure.\n */\n afterCaseCommitted?: (cassetteId: string) => void\n /** 441 GAP3-D1: the workspace's declared-secret mask, passed to the seeding writer. Required. */\n mask: MaskFn\n}\n\n/**\n * The outcome of ONE operator admission (D-01..D-04).\n *\n * Four counts, deliberately not three. `admitted` are cases whose bytes this run committed;\n * `unchanged` are reviewed cases already present BYTE-IDENTICALLY, which move no digest and\n * must not be double-counted as admissions; `refusals` is always empty (441 D-15); `remaining` are\n * reviewed members that have not landed — the number that makes a partial admission legible\n * as one. Collapsing any pair of them is how an interrupted run comes to read as a complete one.\n */\nexport interface AdversarialAdmissionResult {\n kind: 'admitted' | 'partial' | 'dry-run' | 'refused'\n reason?:\n | 'batch-not-found'\n | 'staging-integrity'\n | 'corpus-unavailable'\n | 'admission-refused'\n | 'admission-interrupted'\n product: string\n batchDigest: string\n /** Cases whose bytes THIS run committed. */\n admitted: readonly StagedAdversarialCase[]\n /** Reviewed cases already committed byte-identically; the digest does not move for these. */\n unchanged: readonly StagedAdversarialCase[]\n refusals: readonly AdversarialRefusal[]\n /** Reviewed members that have not landed — zero on a complete admission. */\n remaining: readonly StagedAdversarialCase[]\n stagingSkips: readonly AdversarialStagingSkip[]\n previousCorpusDigest?: string\n nextCorpusDigest?: string\n writesStarted: boolean\n retirement?: AdversarialRetirementResult\n lifecycleBusy?: { lockPath: string }\n}\n\nconst retirementSchema = z.object({\n schemaVersion: z.literal(2), product: z.string().min(1), batchDigest: digestField,\n manifestSha256: digestField, reviewedCaseIds: z.array(z.string().min(1)).min(1),\n alreadyCommittedCaseIds: z.array(z.string().min(1)),\n}).strict()\ntype AdversarialRetirementRecord = z.infer<typeof retirementSchema>\n\nexport interface RetireStagedAdversarialBatchInput {\n agentQaRoot: string\n committedRoot: string\n product: string\n batchDigest: string\n}\n\n/** A decision over retained reviewed bytes, never an admission outcome. */\nexport interface AdversarialRetirementResult {\n retired: true\n alreadyRetired: boolean\n product: string\n batchDigest: string\n manifestSha256: string\n retainedBatchDir: string\n retirementRecordPath: string\n reviewedCaseIds: readonly string[]\n alreadyCommittedCaseIds: readonly string[]\n remainingCaseIds: readonly string[]\n}\n\nexport class AdversarialLifecycleBusyError extends Error {\n constructor(readonly lockPath: string) {\n super(`Adversarial batch lifecycle is busy or ownership is uncertain at ${lockPath}; retry after its owner finishes. Do not remove the lock.`)\n this.name = 'AdversarialLifecycleBusyError'\n }\n}\n\nfunction validateBatchIdentity(product: string, digest: string): void {\n if (!product || slugBranch(product) !== product) throw new TypeError('adversarial product must be an exact safe product slug')\n if (!LOWER_HEX_64.test(digest)) throw new TypeError('adversarial batch must be an exact lowercase SHA256 digest')\n}\n\nconst lifecycleOwnerSchema = z.object({ schemaVersion: z.literal(2),\n product: z.string().min(1), batchDigest: digestField,\n pid: z.number().int().positive(), token: z.uuid(),\n}).strict()\ntype LifecycleOwner = z.infer<typeof lifecycleOwnerSchema>\n\nfunction syncLifecycleDirectory(dir: string): void {\n const fd = openSync(dir, 'r')\n try { fsyncSync(fd) } finally { closeSync(fd) }\n}\n\nfunction lifecycleLockPath(input: { agentQaRoot: string; product: string; batchDigest: string }): string {\n validateBatchIdentity(input.product, input.batchDigest)\n if (!lstatSync(input.agentQaRoot).isDirectory()) throw new TypeError('unsafe adversarial root')\n const productDir = adversarialProductDir(input.agentQaRoot, input.product)\n requireDirectories(productDir)\n return join(productDir, `.pending-lifecycle-${input.batchDigest}`)\n}\n\nfunction readLifecycleOwner(lock: string, identity: Pick<LifecycleOwner, 'product' | 'batchDigest'>): LifecycleOwner | undefined {\n try {\n if (!lstatSync(lock).isDirectory() || readdirSync(lock).join() !== 'owner.json') return undefined\n const parsed = lifecycleOwnerSchema.safeParse(JSON.parse(readStagedFile(lock, 'owner.json')))\n return parsed.success && parsed.data.product === identity.product && parsed.data.batchDigest === identity.batchDigest\n ? parsed.data : undefined\n } catch { return undefined }\n}\n\nfunction lifecycleOwnerDead(pid: number): boolean {\n try { process.kill(pid, 0); return false }\n catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH' }\n}\n\n/** Nonblocking mark-lock protocol: keep nonempty dead-generation tombstones to fence ABA. */\nfunction acquireLifecycleLock(lock: string, identity: Pick<LifecycleOwner, 'product' | 'batchDigest'>): () => void {\n const owner: LifecycleOwner = { schemaVersion: 2, product: identity.product,\n batchDigest: identity.batchDigest, pid: process.pid, token: randomUUID() }\n const candidate = `${lock}.candidate-${owner.token}`\n mkdirSync(candidate)\n let acquired = false\n try {\n const fd = openSync(join(candidate, 'owner.json'), 'wx', 0o600)\n try { writeFileSync(fd, committedFileText(owner)); fsyncSync(fd) } finally { closeSync(fd) }\n syncLifecycleDirectory(candidate)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n try { mkdirSync(lock) }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const current = readLifecycleOwner(lock, identity)\n if (current === undefined || !lifecycleOwnerDead(current.pid)) throw new AdversarialLifecycleBusyError(lock)\n try {\n // Never remove this tombstone: a delayed reclaimer cannot replace a nonempty G\n // with a newer H after a competing reclaimer already moved G here.\n renameSync(lock, `${lock}.dead-${current.token}`)\n syncLifecycleDirectory(dirname(lock))\n continue\n } catch { throw new AdversarialLifecycleBusyError(lock) }\n }\n renameSync(join(candidate, 'owner.json'), join(lock, 'owner.json'))\n syncLifecycleDirectory(lock)\n syncLifecycleDirectory(dirname(lock))\n acquired = true\n break\n }\n if (!acquired) throw new AdversarialLifecycleBusyError(lock)\n } finally {\n rmSync(candidate, { recursive: true, force: true })\n }\n return () => {\n if (readLifecycleOwner(lock, identity)?.token !== owner.token) throw new AdversarialLifecycleBusyError(lock)\n const released = `${lock}.released-${owner.token}`\n renameSync(lock, released)\n syncLifecycleDirectory(dirname(lock))\n rmSync(released, { recursive: true })\n syncLifecycleDirectory(dirname(lock))\n }\n}\n\nfunction retirementResult(batch: StagedAdversarialBatch, record: AdversarialRetirementRecord, alreadyRetired: boolean): AdversarialRetirementResult {\n const committed = new Set(record.alreadyCommittedCaseIds)\n return { retired: true, alreadyRetired, product: record.product, batchDigest: record.batchDigest,\n manifestSha256: record.manifestSha256, retainedBatchDir: batch.dir,\n retirementRecordPath: join(batch.dir, 'retirement.json'), reviewedCaseIds: record.reviewedCaseIds,\n alreadyCommittedCaseIds: record.alreadyCommittedCaseIds,\n remainingCaseIds: record.reviewedCaseIds.filter(id => !committed.has(id)) }\n}\n\nfunction readRetirement(batch: StagedAdversarialBatch): AdversarialRetirementRecord | undefined {\n if (!pathPresent(join(batch.dir, 'retirement.json'))) return undefined\n const text = readStagedFile(batch.dir, 'retirement.json')\n const record = retirementSchema.parse(JSON.parse(text))\n const ids = batch.manifest.cases.map(row => row.cassetteId)\n const committed = new Set(record.alreadyCommittedCaseIds)\n if (record.product !== batch.manifest.product || record.batchDigest !== batch.manifest.batchDigest\n || record.manifestSha256 !== textHash(readStagedFile(batch.dir, ADVERSARIAL_MANIFEST_FILE))\n || JSON.stringify(record.reviewedCaseIds) !== JSON.stringify(ids)\n || JSON.stringify(record.alreadyCommittedCaseIds) !== JSON.stringify(ids.filter(id => committed.has(id)))\n || text !== committedFileText(record)) throw new TypeError('adversarial retirement record conflicts with reviewed bytes')\n return record\n}\n\n/** Retain the reviewed batch and publish its operator decision once, under admission's lock. */\nexport function retireStagedAdversarialBatch(input: RetireStagedAdversarialBatchInput): AdversarialRetirementResult {\n const lock = lifecycleLockPath(input)\n const release = acquireLifecycleLock(lock, input)\n try {\n const batch = listStagedAdversarial({ ...input, includeRetired: true })[0]\n if (batch === undefined) throw new TypeError('adversarial reviewed batch not found; name its exact product and digest')\n const digest = readCommittedCorpusDigest({ committedRoot: input.committedRoot })\n if (digest.kind !== 'digest') throw new TypeError('adversarial committed corpus unavailable; cannot establish already committed cases')\n if (!lstatSync(input.committedRoot).isDirectory()) throw new TypeError('unsafe adversarial committed root')\n const committedRoot = realpathSync(input.committedRoot)\n const alreadyCommittedCaseIds: string[] = []\n for (const row of batch.cases) {\n let present = 0\n for (const [path, text] of [\n [committedCassettePath(input.product, row.cassette.id), row.texts.cassette],\n [committedLabelPath(input.product, row.cassette.id), row.texts.label],\n [committedCorpusPath(input.product, row.cassette.id), row.texts.entry],\n ] as const) {\n const file = join(committedRoot, path)\n requireDirectories(dirname(file))\n if (!pathPresent(file)) continue\n if (!lstatSync(file).isFile() || readFileSync(file, 'utf8') !== text) throw new TypeError('adversarial committed case conflicts with reviewed bytes')\n present += 1\n }\n if (present !== 0 && present !== 3) throw new TypeError('adversarial committed case is incomplete')\n if (present === 3) alreadyCommittedCaseIds.push(row.cassette.id)\n }\n const record: AdversarialRetirementRecord = { schemaVersion: 2, product: input.product,\n batchDigest: input.batchDigest, manifestSha256: textHash(readStagedFile(batch.dir, ADVERSARIAL_MANIFEST_FILE)),\n reviewedCaseIds: batch.manifest.cases.map(row => row.cassetteId), alreadyCommittedCaseIds }\n if (batch.retirement !== undefined) {\n if (committedFileText(record) !== committedFileText(batch.retirement)) throw new TypeError('adversarial retirement committed-case identity changed')\n return retirementResult(batch, batch.retirement, true)\n }\n const temporary = join(batch.dir, `.pending-retirement-${randomUUID()}`)\n let ownedTemporary = false\n try {\n const fd = openSync(temporary, 'wx', 0o600)\n ownedTemporary = true\n try { writeFileSync(fd, committedFileText(record)); fsyncSync(fd) } finally { closeSync(fd) }\n linkSync(temporary, join(batch.dir, 'retirement.json'))\n syncLifecycleDirectory(batch.dir)\n } finally {\n if (ownedTemporary) rmSync(temporary, { force: true })\n }\n return retirementResult(batch, record, false)\n } finally { release() }\n}\n\n/** 422-01's spelling of the same result, retained for its existing callers. */\nexport type RefreshAdversarialSplitResult = AdversarialAdmissionResult\n\n// ---------------------------------------------------------------------------\n// Guarded local IO (the gate2 staging posture, verbatim in spirit).\n// ---------------------------------------------------------------------------\n\nfunction pathPresent(path: string): boolean {\n try {\n lstatSync(path)\n return true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n}\n\n/** Refuse links and wrong-kind ancestors rather than following audit paths out of their root. */\nfunction requireDirectories(path: string): void {\n const absolute = resolve(path)\n const parent = dirname(absolute)\n if (parent !== absolute) requireDirectories(parent)\n if (pathPresent(absolute) && !lstatSync(absolute).isDirectory()) {\n throw new TypeError('unsafe adversarial staging directory')\n }\n}\n\nfunction directoryNames(path: string): string[] {\n requireDirectories(path)\n if (!pathPresent(path)) return []\n return readdirSync(path, { withFileTypes: true })\n .map(entry => {\n if (!entry.isDirectory()) throw new TypeError('unexpected adversarial staging path')\n return entry.name\n })\n .sort()\n}\n\n/** A staged document is only readable as a REGULAR file inside its own case directory. */\nfunction readStagedFile(caseDir: string, name: string): string {\n requireDirectories(caseDir)\n const file = join(caseDir, name)\n if (!pathPresent(file) || !lstatSync(file).isFile()) {\n throw new TypeError('unsafe adversarial staging file')\n }\n return readFileSync(file, 'utf8')\n}\n\nfunction textHash(text: string): string {\n return createHash('sha256').update(text, 'utf8').digest('hex')\n}\n\n/** The four label facts D-06 forbids a derivation from changing. */\nfunction seedProvenancePin(record: StandaloneLabelRecord): AdversarialSeedProvenancePin {\n return {\n runId: record.provenance.runId,\n capturedAtOrdinal: record.provenance.capturedAtOrdinal,\n sourceChannel: record.label.sourceChannel,\n tier: record.label.tier,\n }\n}\n\nfunction samePin(left: AdversarialSeedProvenancePin, right: AdversarialSeedProvenancePin): boolean {\n return (\n left.runId === right.runId &&\n left.capturedAtOrdinal === right.capturedAtOrdinal &&\n left.sourceChannel === right.sourceChannel &&\n left.tier === right.tier\n )\n}\n\n/**\n * Narrow a recorded `detail` back to the generator's closed inapplicability vocabulary.\n *\n * A record written by an older build may carry a member this build does not know. That is not a\n * reason to drop the row — it is a reason not to re-report it as a vocabulary term the caller\n * would then switch on. Such a row falls back to `already-derived`, which is true of every\n * settled tuple by construction: its id is decided for this generation.\n */\nfunction isInapplicability(value: string | undefined): value is AdversarialSeedSkip['reason'] {\n return value !== undefined && (ADVERSARIAL_INAPPLICABILITIES as readonly string[]).includes(value)\n}\n\nfunction adversarialProductDir(agentQaRoot: string, product: string): string {\n return join(realpathSync(agentQaRoot), ADVERSARIAL_STAGING_SUBDIR, slugBranch(product))\n}\n\nfunction caseDirName(index: number): string {\n return `case-${String(index).padStart(4, '0')}`\n}\n\n/**\n * The batch digest (D-02). `stagedAt` is deliberately absent: two refreshes that derive the\n * same cases must address the same directory, so re-staging is an idempotent no-op rather\n * than an unbounded pile of near-identical batches.\n */\nexport function computeAdversarialBatchDigest(\n product: string,\n cases: readonly AdversarialBatchManifestCase[],\n): string {\n return createHash('sha256')\n .update(\n canonicalJson({\n schemaVersion: 2,\n product,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n tableHash: ADVERSARIAL_TABLE_HASH,\n cases,\n }),\n 'utf8',\n )\n .digest('hex')\n}\n\n/**\n * Resolve the per-refresh provider-call cap (D-04/D-10).\n *\n * Every rejected boundary is rejected LOUDLY, exactly as the seed cap is: zero, negative,\n * fractional, nonfinite and beyond-safe-integer budgets are a TypeError rather than a silent\n * fallback. A budget that quietly becomes four because the operator typed `0` is a budget the\n * operator does not have — and here the silent version would buy provider calls they refused.\n */\nexport function resolveAdversarialProbeCallCap(input: {\n value?: number\n source?: Exclude<AdversarialCapSource, 'default'>\n}): AdversarialProbeCallCap {\n if (input.value === undefined) {\n return { value: ADVERSARIAL_DEFAULT_MAX_PROBE_CALLS, source: 'default' }\n }\n if (!Number.isSafeInteger(input.value) || input.value < 1) {\n throw new TypeError('adversarial probe call cap must be a positive safe integer')\n }\n return { value: input.value, source: input.source ?? 'flag' }\n}\n\n/**\n * D-11's idempotence key: `(seed, kind, promptVersion)` and NOTHING else.\n *\n * Not the authored text — that is part of the derived IDENTITY, so keying on it would make\n * every answer a new tuple and no refresh could ever recognise that it had already asked. Not\n * the author either: a second host with a second model must not buy a second copy of a probe\n * this corpus already holds. A future `promptVersion` IS a new tuple, deliberately — different\n * instructions are a different case, not a duplicate.\n */\nexport function adversarialProbeTupleKey(\n seedCassetteId: string,\n kind: ProbeGeneratorKind,\n promptVersion: number,\n): string {\n // U+001F, the `adversarialTupleKey` separator: no cassette id, kind or version can contain\n // it, so `(a, bc)` and `(ab, c)` can never collide into one key.\n return [seedCassetteId, kind, String(promptVersion)].join('\\u001F')\n}\n\n/**\n * Resolve the derived cassette's blob closure from the SEED's committed blobs, by content\n * address. Nothing is copied here; the bytes are proof that the closure is admissible.\n */\nfunction resolveSeedBlobs(\n committedRoot: string,\n product: string,\n seedCassetteId: string,\n shas: readonly string[],\n): { blobs: ExtractedBlob[] } | { skipReason: AdversarialStagingSkip['reason'] } {\n const blobs: ExtractedBlob[] = []\n for (const sha of shas) {\n if (!LOWER_HEX_64.test(sha)) return { skipReason: 'blob-hash-mismatch' }\n const file = join(committedRoot, committedBlobPath(product, seedCassetteId, sha))\n let bytes: Buffer\n try {\n if (!lstatSync(file).isFile()) return { skipReason: 'blob-unresolvable' }\n bytes = readFileSync(file)\n } catch {\n return { skipReason: 'blob-unresolvable' }\n }\n if (createHash('sha256').update(bytes).digest('hex') !== sha) {\n return { skipReason: 'blob-hash-mismatch' }\n }\n blobs.push({ sha, bytes })\n }\n return { blobs }\n}\n\n// ---------------------------------------------------------------------------\n// Stage (D-01/D-02): derive concrete bytes, scan them, publish LOCAL audit data.\n// ---------------------------------------------------------------------------\n\n/**\n * Derive and stage one reviewable adversarial batch for a product.\n *\n * Seeds come from a FRESH `/reader` snapshot of the committed root, so a private held-out\n * entry is structurally unreachable — the proposer's door is the same door this uses.\n * Nothing under the committed root is written, read-modified, or re-digested.\n */\nexport async function stageAdversarialProposal(\n input: StageAdversarialProposalInput,\n): Promise<StageAdversarialProposalResult> {\n // D-04: resolved BEFORE any read, so an invalid cap is a loud refusal rather than a refresh\n // that silently ran under the default. The provider budget resolves in the same breath and\n // for the sharper version of the same reason: an invalid one must not buy a single call.\n const cap = resolveAdversarialSeedCap({\n ...(input.maxSeeds === undefined ? {} : { value: input.maxSeeds }),\n ...(input.maxSeedsSource === undefined ? {} : { source: input.maxSeedsSource }),\n })\n const probeCap = resolveAdversarialProbeCallCap({\n ...(input.maxProbeCalls === undefined ? {} : { value: input.maxProbeCalls }),\n ...(input.maxProbeCallsSource === undefined ? {} : { source: input.maxProbeCallsSource }),\n })\n const spend: AdversarialSpend = {\n modelCalls: 0, promptTokens: 0, completionTokens: 0, usageKnown: true,\n }\n const probeSkips: AdversarialProbeSkip[] = []\n const probeRefusals: AdversarialProbeRefusal[] = []\n let interruptedProbeCalls = 0\n const probeDisclosure = {\n ...(input.noProbeModel === undefined ? {} : { noProbeModel: input.noProbeModel }),\n probeCap,\n spend,\n probeSkips,\n probeRefusals,\n }\n const empty: Omit<StageAdversarialProposalResult, 'kind'> = {\n product: input.product,\n staged: [],\n refusals: [],\n skips: [],\n stagingSkips: [],\n seedsConsidered: 0,\n seedsDeferred: 0,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n tableHash: ADVERSARIAL_TABLE_HASH,\n rootPosture: 'unavailable',\n cap,\n eligibleSeeds: 0,\n settledRefusals: [],\n ...probeDisclosure,\n interruptedProbeCalls: 0,\n }\n // The gate's own read, not the reader's length: an unmarked or refusing root reads empty\n // through the proposer port and must not be mistaken for a healthy corpus with nothing in it.\n const posture = readCommittedCorpusDigest({ committedRoot: input.committedRoot })\n if (posture.kind !== 'digest') return { ...empty, kind: 'nothing-derived' }\n const sourceDigest = posture.corpusDigest\n\n const reader = openCorpusReader(input.committedRoot)\n const entries = reader.listEntries(input.product)\n const candidates: AdversarialSeed[] = []\n const existingCassetteIds = new Set<string>()\n /**\n * D-11: every `(seed, kind, promptVersion)` tuple this corpus has already ASKED about.\n *\n * Read from COMMITTED bytes and from STAGED bytes, before a single call is made. This is the\n * one set that makes a re-run free: a derived cassette id cannot serve here, because a probe's\n * id is a function of the text the model happened to return, so there is no id to look up\n * until after the money is spent. The tuple is the only thing knowable in advance.\n */\n const decidedProbeTuples = new Set<string>()\n const rememberProbeTuple = (generator: CorpusGenerator | undefined): void => {\n if (generator === undefined || generator.promptVersion === undefined) return\n if (!isProbeGeneratorKind(generator.kind)) return\n decidedProbeTuples.add(\n adversarialProbeTupleKey(generator.seedCassetteId, generator.kind, generator.promptVersion),\n )\n }\n for (const entry of entries) {\n existingCassetteIds.add(entry.cassetteId)\n if (entry.split === 'adversarial') rememberProbeTuple(entry.generator)\n if (entry.split !== 'natural') continue\n const cassette = reader.loadCassette(entry.cassetteId)\n if (cassette.kind !== 'loaded' || cassette.cassette.granularity !== 'leaf') continue\n const label = reader.loadLabel(entry.cassetteId)\n candidates.push({\n cassette: cassette.cassette,\n entry,\n ...(label.kind === 'loaded' ? { label: label.record } : {}),\n })\n }\n // Anything already staged is also already derived: D-04's idempotence key spans both.\n for (const batch of listStagedAdversarial({ agentQaRoot: input.agentQaRoot, product: input.product, includeRetired: true })) {\n for (const staged of batch.manifest.cases) {\n existingCassetteIds.add(staged.cassetteId)\n if (staged.promptVersion !== undefined && isProbeGeneratorKind(staged.kind)) {\n decidedProbeTuples.add(\n adversarialProbeTupleKey(staged.seedCassetteId, staged.kind, staged.promptVersion),\n )\n }\n }\n }\n // ...and so is anything a previous refresh recorded, under ANY generation (D-08).\n const records = readAdversarialRefreshRecords({\n agentQaRoot: input.agentQaRoot,\n product: input.product,\n })\n for (const id of derivedAdversarialCassetteIds(records)) existingCassetteIds.add(id)\n const settled = settledAdversarialTupleIndex(records, {\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n })\n\n // The seed-level filter the cap depends on. A seed whose every requested tuple is already\n // decided — derived or explicitly inapplicable — is NOT novel, and letting it into the\n // generator would spend a cap slot to re-reach a conclusion already on disk. That is the\n // starvation this plan exists to remove: without it the leading seeds are re-selected forever\n // and the seeds behind them are never reached.\n //\n // A dropped seed is DISCLOSED, never silently forgotten: an empty batch with no rows cannot\n // be told apart from a refresh that never ran. Derived and inapplicable settlements re-report\n // through the generator's own closed vocabulary.\n const requested = ADVERSARIAL_MUTATORS.filter(\n mutator => input.mutators === undefined || input.mutators.includes(mutator),\n )\n const settledSkips: AdversarialSeedSkip[] = []\n const seeds = candidates.filter(seed => {\n const decided: { mutator: AdversarialMutator; tuple?: AdversarialRefreshTuple }[] = []\n let novel = false\n for (const mutator of requested) {\n const tuple = settled.get(adversarialTupleKey(seed.cassette.id, mutator))\n if (tuple !== undefined) {\n decided.push({ mutator, tuple })\n continue\n }\n const derivedId = deriveAdversarialCassetteId({\n seedCassetteId: seed.cassette.id,\n kind: ADVERSARIAL_TABLES[mutator].kind,\n mutator,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n })\n if (existingCassetteIds.has(derivedId)) {\n decided.push({ mutator })\n continue\n }\n novel = true\n }\n if (novel) return true\n for (const row of decided) {\n settledSkips.push({\n seedCassetteId: seed.cassette.id,\n mutator: row.mutator,\n reason:\n row.tuple?.outcome === 'inapplicable' && isInapplicability(row.tuple.detail)\n ? row.tuple.detail\n : 'already-derived',\n })\n }\n return false\n })\n\n const generated = generateAdversarialVariants({\n product: input.product,\n seeds,\n existingCassetteIds,\n ...(input.mutators === undefined ? {} : { mutators: input.mutators }),\n maxSeeds: cap.value,\n })\n // Novel eligible seeds, counted before the cap: the generator only defers a seed that passed\n // its own eligibility check, so considered + deferred is exactly that population.\n const eligibleSeeds = generated.seedsConsidered + generated.seedsDeferred\n\n const stagingSkips: AdversarialStagingSkip[] = []\n const tuples: AdversarialRefreshTuple[] = []\n const publishable: {\n manifestCase: AdversarialBatchManifestCase\n texts: { cassette: string; label: string; entry: string }\n }[] = []\n\n // A family the generator explicitly could not act on is a COMPLETED decision for this\n // generation, so it settles. `cap-exceeded` is a deferral and `already-derived` is a decision\n // taken earlier — neither is work this refresh did, and recording either would manufacture a\n // settlement. Seed-level rows carry no mutator and settle nothing: an ineligible seed can\n // become eligible when its corpus entry changes.\n for (const outcome of generated.outcomes) {\n if (outcome.kind !== 'inapplicable') continue\n if (outcome.mutator === undefined) continue\n if (outcome.reason === 'cap-exceeded' || outcome.reason === 'already-derived') continue\n tuples.push({\n seedCassetteId: outcome.seedCassetteId,\n mutator: outcome.mutator,\n cassetteId: deriveAdversarialCassetteId({\n seedCassetteId: outcome.seedCassetteId,\n kind: ADVERSARIAL_TABLES[outcome.mutator].kind,\n mutator: outcome.mutator,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n }),\n outcome: 'inapplicable',\n detail: outcome.reason,\n })\n }\n\n for (const variant of generated.variants) {\n const texts = {\n cassette: committedFileText(variant.cassette),\n label: committedFileText(variant.labelRecord),\n entry: committedFileText(variant.corpusEntry),\n }\n const resolved = resolveSeedBlobs(\n input.committedRoot,\n input.product,\n variant.seedCassetteId,\n variant.blobShas,\n )\n if ('skipReason' in resolved) {\n // Deliberately NOT settled: an unresolvable blob is an operational failure that a repaired\n // root fixes. Settling it would turn a transient disk problem into a permanent exclusion.\n stagingSkips.push({\n cassetteId: variant.cassette.id,\n seedCassetteId: variant.seedCassetteId,\n reason: resolved.skipReason,\n })\n continue\n }\n tuples.push({\n seedCassetteId: variant.seedCassetteId,\n mutator: variant.mutator,\n cassetteId: variant.cassette.id,\n outcome: 'derived',\n })\n publishable.push({\n manifestCase: {\n cassetteId: variant.cassette.id,\n seedCassetteId: variant.seedCassetteId,\n mutator: variant.mutator,\n kind: variant.generator.kind,\n tableEntryId: variant.tableEntryId,\n cassetteTextHash: textHash(texts.cassette),\n labelTextHash: textHash(texts.label),\n entryTextHash: textHash(texts.entry),\n seedProvenance: seedProvenancePin(variant.labelRecord),\n blobShas: [...variant.blobShas],\n },\n texts,\n })\n }\n\n // -------------------------------------------------------------------------\n // The AUTHORED half (D-09/D-10/D-11). Everything above this line is pure and\n // recomputable; nothing below it is.\n //\n // WHY THE PROBE BUDGET IS NOT THE SEED CAP. A probe tuple is keyed by\n // `(seed, kind, promptVersion)` and a table tuple by `(seed, mutator)` under a table\n // generation — different keys about different work. Gating probes behind the deterministic\n // seed filter would make a seed whose eleven families are all settled permanently unreachable\n // to a NEW prompt generation, which is exactly the starvation 422-03 removed one level up. So\n // the probe phase walks every eligible candidate in id order and is bounded by its own budget.\n //\n // ORDER INSIDE THE LOOP IS THE CONTRACT. A decided tuple costs nothing; an inapplicable seed\n // costs nothing; only a tuple that WOULD be authored can hit the cap. Checking the budget\n // first would spend rows of `probe-cap-exceeded` on seeds that were never going to be asked.\n // -------------------------------------------------------------------------\n let authoringModel: AuthoringModel | undefined\n if (input.probeAuthor !== undefined && input.authoringModel !== undefined) {\n authoringModel = input.authoringModel\n const probeSeeds = [...candidates].sort((left, right) =>\n left.cassette.id < right.cassette.id ? -1 : left.cassette.id > right.cassette.id ? 1 : 0,\n )\n for (const seed of probeSeeds) {\n for (const kind of PROBE_GENERATOR_KINDS) {\n const promptVersion = ADVERSARIAL_PROMPT_VERSION\n const row = { seedCassetteId: seed.cassette.id, kind, promptVersion }\n if (decidedProbeTuples.has(adversarialProbeTupleKey(seed.cassette.id, kind, promptVersion))) {\n probeSkips.push({ ...row, reason: 'tuple-already-decided' })\n continue\n }\n const request = buildProbeRequest({ seed, kind, authoringModel })\n if (typeof request === 'string') {\n probeSkips.push({ ...row, reason: request })\n continue\n }\n const reservationKey: ProbeReservationKey = {\n product: input.product,\n seedCassetteId: seed.cassette.id,\n kind,\n promptVersion,\n }\n // WHAT THE DURABLE STORE ALREADY KNOWS, BEFORE ANY BUDGET IS SPENT.\n //\n // A COMPLETED `derived` attempt is re-derivable for free: the text is the only part of a\n // probe that is not a pure function of its inputs, so with the text on disk the case can\n // be rebuilt exactly. That is what makes the window between the call and the publication\n // recoverable at all — recomputation alone would have to buy the answer again.\n //\n // An INTERRUPTED attempt is charged and stays charged. Re-authoring it would buy one\n // question twice, and there is no way to know whether the lost response was ever\n // generated; the honest move is to report it and leave the window closed.\n const attempt = readProbeAttempt({ agentQaRoot: input.agentQaRoot, key: reservationKey })\n let response: ProbeText | undefined\n if (attempt.kind === 'interrupted') {\n interruptedProbeCalls += 1\n probeSkips.push({ ...row, reason: 'tuple-interrupted' })\n continue\n }\n if (attempt.kind === 'completed') {\n const expected = probeReservationOf(reservationKey, {\n promptHash: request.promptHash,\n author: request.authoringModel,\n })\n if (\n attempt.reservation.authorDigest !== expected.authorDigest ||\n attempt.reservation.authorFamily !== expected.authorFamily ||\n attempt.reservation.promptHash !== expected.promptHash\n ) {\n // Only closed reasons leave this boundary: model IDs may contain credentials.\n // The paid record stays untouched and this tuple never falls through to author().\n probeSkips.push({ ...row, reason: 'probe-reservation-mismatch' })\n continue\n }\n const completion = attempt.completion\n if (completion.outcome !== 'derived' || completion.text === undefined) {\n probeSkips.push({ ...row, reason: 'tuple-already-decided' })\n continue\n }\n // The TEXT is what makes a completed attempt re-derivable; the token counts are a\n // disclosure about a call this refresh is not making. A recorded answer whose\n // provider reported no usage is still a perfectly good answer, so absence here\n // rebuilds as absence rather than disqualifying the tuple.\n response = {\n text: completion.text,\n usage: {\n ...(completion.promptTokens === undefined\n ? {}\n : { promptTokens: completion.promptTokens }),\n ...(completion.completionTokens === undefined\n ? {}\n : { completionTokens: completion.completionTokens }),\n },\n }\n } else {\n if (spend.modelCalls >= probeCap.value) {\n probeSkips.push({ ...row, reason: 'probe-cap-exceeded' })\n continue\n }\n // THE ALLOWANCE IS MADE DURABLE FIRST, AND THE COUNT MOVES WITH IT. A run that dies\n // inside `author` paid for whatever it paid for; counting only answers would let an\n // interruption under-report its own bill, and a budget that can be under-reported is\n // not a budget. `reserveProbeCall` is exclusive, so a concurrent owner observes this\n // reservation rather than opening a second call for the same tuple.\n const reserved = reserveProbeCall({\n agentQaRoot: input.agentQaRoot,\n reservation: probeReservationOf(reservationKey, {\n promptHash: request.promptHash,\n author: authoringModel,\n }),\n })\n if (reserved.kind === 'already-claimed') {\n interruptedProbeCalls += 1\n probeSkips.push({ ...row, reason: 'tuple-interrupted' })\n continue\n }\n spend.modelCalls += 1\n decidedProbeTuples.add(adversarialProbeTupleKey(seed.cassette.id, kind, promptVersion))\n try {\n response = await input.probeAuthor.author(request)\n } catch {\n // The provider failed, or the port refused. The call is an ANSWER — control came\n // back — so the outcome is durable and the tuple is consumed for this prompt\n // generation. Its tokens are UNKNOWN and are left absent rather than written as\n // zero; the exception text is never carried, because it can name a model or a\n // credential.\n completeProbeCall({\n agentQaRoot: input.agentQaRoot,\n key: reservationKey,\n completion: { schemaVersion: ADVERSARIAL_PROBE_SCHEMA_VERSION, outcome: 'error' },\n })\n spend.usageKnown = false\n probeSkips.push({ ...row, reason: 'tuple-already-decided' })\n continue\n }\n // ABSENT is not zero. A call that answered without reporting usage makes the\n // running totals incomplete, and the honest move is to say the totals are unknown\n // rather than to add a fabricated zero to them.\n if (\n response.usage.promptTokens === undefined ||\n response.usage.completionTokens === undefined\n ) {\n spend.usageKnown = false\n } else {\n spend.promptTokens += response.usage.promptTokens\n spend.completionTokens += response.usage.completionTokens\n }\n }\n const derivation = deriveProbeCassette({\n seed,\n request,\n response,\n product: input.product,\n })\n if (derivation.outcome === 'refused') {\n recordProbeOutcome(input.agentQaRoot, attempt, reservationKey, {\n schemaVersion: ADVERSARIAL_PROBE_SCHEMA_VERSION, outcome: 'invalid', detail: derivation.reason,\n })\n probeRefusals.push({ ...row, reason: derivation.reason })\n continue\n }\n const probe = derivation.probe\n if (attempt.kind === 'completed' && attempt.completion.cassetteId !== probe.cassette.id) {\n probeSkips.push({ ...row, reason: 'probe-completion-identity-mismatch' })\n continue\n }\n const texts = {\n cassette: committedFileText(probe.cassette),\n label: committedFileText(probe.labelRecord),\n entry: committedFileText(probe.corpusEntry),\n }\n // The durable output, written ONCE, and written BEFORE any operational skip below it.\n // A later refresh that finds it re-derives this exact case with no call at all, which\n // is what makes the crash between the answer and the reviewed batch a recoverable one\n // rather than a second bill. The text is the only non-recomputable part of a probe, so\n // it is recorded the instant it is known to be good: leaving it unrecorded while an\n // unresolvable blob sends the loop to `continue` would strand the reservation with no\n // completion, which the next refresh reads as `interrupted` — turning a transient disk\n // problem into a permanent exclusion AND discarding an answer already paid for. The\n // deterministic half refuses to settle that same condition for the weaker reason.\n recordProbeOutcome(input.agentQaRoot, attempt, reservationKey, {\n schemaVersion: ADVERSARIAL_PROBE_SCHEMA_VERSION,\n outcome: 'derived',\n text: probe.text,\n cassetteId: probe.cassette.id,\n // Written only when the provider reported them, so `completionUsageKnown` reads a\n // real fact off the record instead of returning `true` unconditionally.\n ...(probe.usage.promptTokens === undefined\n ? {}\n : { promptTokens: probe.usage.promptTokens }),\n ...(probe.usage.completionTokens === undefined\n ? {}\n : { completionTokens: probe.usage.completionTokens }),\n })\n const probeBlobs = resolveSeedBlobs(\n input.committedRoot,\n input.product,\n probe.seedCassetteId,\n probe.blobShas,\n )\n if ('skipReason' in probeBlobs) {\n // Deliberately NOT settled, on the deterministic half's rule: a repaired root\n // re-derives this case for free from the answer recorded above.\n stagingSkips.push({\n cassetteId: probe.cassette.id,\n seedCassetteId: probe.seedCassetteId,\n reason: probeBlobs.skipReason,\n })\n continue\n }\n publishable.push({\n manifestCase: {\n cassetteId: probe.cassette.id,\n seedCassetteId: probe.seedCassetteId,\n kind: probe.kind,\n promptVersion,\n cassetteTextHash: textHash(texts.cassette),\n labelTextHash: textHash(texts.label),\n entryTextHash: textHash(texts.entry),\n seedProvenance: seedProvenancePin(probe.labelRecord),\n blobShas: [...probe.blobShas],\n },\n texts,\n })\n }\n }\n }\n\n // One deterministic order for the manifest, the directory layout and the digest.\n publishable.sort((left, right) =>\n left.manifestCase.cassetteId < right.manifestCase.cassetteId\n ? -1\n : left.manifestCase.cassetteId > right.manifestCase.cassetteId\n ? 1\n : 0,\n )\n\n // Immutable batch membership: every seed this refresh actually SELECTED, ascending. A seed\n // the cap deferred, or one that was ineligible, emits a single mutator-less row and is not a\n // member — so a retry after an interruption reconstructs the same membership from the same\n // corpus rather than drifting onto a different eight.\n const seedIds = [\n ...new Set(\n generated.outcomes.flatMap(outcome =>\n outcome.mutator === undefined ? [] : [outcome.seedCassetteId],\n ),\n ),\n ].sort()\n\n const record: AdversarialRefreshRecord = {\n schemaVersion: ADVERSARIAL_STATE_SCHEMA_VERSION,\n product: input.product,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n sourceDigest,\n cap,\n eligibleSeeds,\n excessSeeds: generated.seedsDeferred,\n seedIds,\n tuples: [...tuples].sort((left, right) =>\n left.cassetteId < right.cassetteId ? -1 : left.cassetteId > right.cassetteId ? 1 : 0,\n ),\n }\n\n const base: Omit<StageAdversarialProposalResult, 'kind'> = {\n product: input.product,\n staged: publishable.map(row => stagedCaseOf(row.manifestCase)),\n refusals: [],\n skips: [...settledSkips, ...generated.skips],\n stagingSkips,\n seedsConsidered: generated.seedsConsidered,\n seedsDeferred: generated.seedsDeferred,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n tableHash: ADVERSARIAL_TABLE_HASH,\n rootPosture: 'available',\n sourceDigest,\n cap,\n eligibleSeeds,\n settledRefusals: [],\n ...probeDisclosure,\n interruptedProbeCalls,\n ...(authoringModel === undefined ? {} : { authoringModel }),\n }\n\n /**\n * Settle what this refresh decided. A DRY RUN settles nothing — it published no bytes, so\n * claiming its conclusions would let a preview silently retire seeds. An empty tuple list\n * settles nothing either: there is no decision to record.\n */\n function settle(): { stateRecordDigest?: string } {\n if (input.dryRun === true || record.tuples.length === 0) return {}\n publishAdversarialRefreshRecord({ agentQaRoot: input.agentQaRoot, record })\n return { stateRecordDigest: adversarialRefreshRecordDigest(record) }\n }\n\n if (publishable.length === 0) return { ...base, kind: 'nothing-derived', ...settle() }\n\n const cases = publishable.map(row => row.manifestCase)\n const batchDigest = computeAdversarialBatchDigest(input.product, cases)\n const productDir = adversarialProductDir(input.agentQaRoot, input.product)\n const dir = join(productDir, batchDigest)\n function existingBatchOutcome(): StageAdversarialProposalResult {\n const existing = listStagedAdversarial({ agentQaRoot: input.agentQaRoot,\n product: input.product, batchDigest, includeRetired: true })[0]\n if (existing?.retirement !== undefined) return { ...base, kind: 'nothing-derived', staged: [], ...settle() }\n return { ...base, kind: 'unchanged', batchDigest, dir, ...settle() }\n }\n if (pathPresent(dir)) return existingBatchOutcome()\n if (input.dryRun === true) return { ...base, kind: 'dry-run', batchDigest, dir }\n\n requireDirectories(productDir)\n // An already-published batch still settles: the previous run may have been interrupted\n // between the staging rename and its record, and the decisions are the same either way.\n if (pathPresent(dir)) return existingBatchOutcome()\n\n const manifest: AdversarialBatchManifest = {\n schemaVersion: 2,\n product: input.product,\n batchDigest,\n tableVersion: ADVERSARIAL_TABLE_VERSION,\n tableHash: ADVERSARIAL_TABLE_HASH,\n stagedAt: new Date().toISOString(),\n cases,\n }\n\n let temporary: string | undefined\n try {\n mkdirSync(productDir, { recursive: true })\n temporary = mkdtempSync(join(productDir, '.pending-'))\n writeFileSync(join(temporary, ADVERSARIAL_MANIFEST_FILE), committedFileText(manifest), { flag: 'wx' })\n for (const [index, row] of publishable.entries()) {\n const caseDir = join(temporary, caseDirName(index))\n mkdirSync(caseDir)\n writeFileSync(join(caseDir, 'cassette.json'), row.texts.cassette, { flag: 'wx' })\n writeFileSync(join(caseDir, 'label.json'), row.texts.label, { flag: 'wx' })\n writeFileSync(join(caseDir, 'entry.json'), row.texts.entry, { flag: 'wx' })\n }\n // Publish once, fully validated. An existing published batch is nonempty and cannot be\n // replaced by rename; a competitor is reported as 'unchanged', never as a fresh stage.\n if (pathPresent(dir)) return existingBatchOutcome()\n renameSync(temporary, dir)\n temporary = undefined\n // Settle AFTER the bytes are published: an interruption before this point leaves nothing\n // settled and the retry re-derives the same batch, which is the recoverable order.\n return { ...base, kind: 'staged', batchDigest, dir, ...settle() }\n } finally {\n if (temporary !== undefined) rmSync(temporary, { recursive: true, force: true })\n }\n}\n\n// ---------------------------------------------------------------------------\n// List (D-02): read staged batches back with every pin re-checked.\n// ---------------------------------------------------------------------------\n\n/**\n * Load staged batches, verifying identity at every level: the directory name IS the manifest\n * digest, the digest recomputed from the manifest's own case list equals it, and each staged\n * document re-hashes to its pinned value. A structural violation throws — a tampered batch is\n * never handed back as if it were reviewable.\n */\nexport function listStagedAdversarial(input: {\n agentQaRoot: string\n product?: string\n batchDigest?: string\n includeRetired?: boolean\n}): StagedAdversarialBatch[] {\n if (input.product !== undefined && (!input.product || slugBranch(input.product) !== input.product)) throw new TypeError('adversarial product must be an exact safe product slug')\n if (input.batchDigest !== undefined && !LOWER_HEX_64.test(input.batchDigest)) throw new TypeError('adversarial batch must be an exact lowercase SHA256 digest')\n if (!pathPresent(input.agentQaRoot)) return []\n if (!lstatSync(input.agentQaRoot).isDirectory()) throw new TypeError('unsafe adversarial root')\n const root = join(realpathSync(input.agentQaRoot), ADVERSARIAL_STAGING_SUBDIR)\n const products = input.product === undefined ? directoryNames(root) : [slugBranch(input.product)]\n const batches: StagedAdversarialBatch[] = []\n for (const productSlug of products) {\n const productDir = join(root, productSlug)\n if (!pathPresent(productDir)) continue\n for (const batchDigest of directoryNames(productDir)) {\n if (batchDigest.startsWith('.pending-')) continue\n if (input.batchDigest !== undefined && input.batchDigest !== batchDigest) continue\n const dir = join(productDir, batchDigest)\n requireDirectories(dir)\n // Inspect the whole retained audit tree without following links, including entries\n // outside the manifest's document paths. Unreviewed links cannot ride a valid marker.\n for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {\n if (!entry.isFile() && !entry.isDirectory()) throw new TypeError('unsafe or unexpected adversarial batch entry')\n }\n const manifest = manifestSchema.parse(\n JSON.parse(readStagedFile(dir, ADVERSARIAL_MANIFEST_FILE)),\n ) as AdversarialBatchManifest\n if (slugBranch(manifest.product) !== productSlug || manifest.batchDigest !== batchDigest) {\n throw new TypeError('adversarial staging path identity mismatch')\n }\n if (input.product !== undefined && input.product !== manifest.product) {\n throw new TypeError('adversarial staging path identity mismatch')\n }\n if (computeAdversarialBatchDigest(manifest.product, manifest.cases) !== manifest.batchDigest) {\n throw new TypeError('adversarial manifest digest mismatch')\n }\n if (new Set(manifest.cases.map(row => row.cassetteId)).size !== manifest.cases.length) throw new TypeError('duplicate adversarial reviewed case identity')\n const cases: StagedAdversarialBatch['cases'] = manifest.cases.map((manifestCase, index) => {\n const caseDir = join(dir, caseDirName(index))\n const texts = {\n cassette: readStagedFile(caseDir, 'cassette.json'),\n label: readStagedFile(caseDir, 'label.json'),\n entry: readStagedFile(caseDir, 'entry.json'),\n }\n if (\n textHash(texts.cassette) !== manifestCase.cassetteTextHash ||\n textHash(texts.label) !== manifestCase.labelTextHash ||\n textHash(texts.entry) !== manifestCase.entryTextHash\n ) {\n throw new TypeError('adversarial staged text hash mismatch')\n }\n const cassette = guardCassette(JSON.parse(texts.cassette))\n if (cassette.granularity !== 'leaf' || cassette.id !== manifestCase.cassetteId) {\n throw new TypeError('adversarial staged cassette identity mismatch')\n }\n const parsedLabel = parseStandaloneLabelRecord(JSON.parse(texts.label))\n if (!parsedLabel.ok || parsedLabel.record.cassetteId !== manifestCase.cassetteId) {\n throw new TypeError('adversarial staged label rejected')\n }\n const corpusEntry = guardCorpusEntry(JSON.parse(texts.entry))\n if (corpusEntry.split !== 'adversarial' || corpusEntry.cassetteId !== manifestCase.cassetteId) {\n throw new TypeError('adversarial staged entry identity mismatch')\n }\n if (\n corpusEntry.generator.seedCassetteId !== manifestCase.seedCassetteId ||\n corpusEntry.generator.kind !== manifestCase.kind ||\n corpusEntry.generator.mutator !== manifestCase.mutator\n ) {\n throw new TypeError('adversarial staged provenance mismatch')\n }\n // D-05/D-11: a manifest case names ONE derivation path. A table case that also claims a\n // prompt version, or a probe case that also claims a mutation family, is provenance that\n // cannot be true — and the reviewed batch is exactly where that must be caught, because\n // admission copies these bytes into a git-tracked root.\n if (manifestCase.promptVersion === undefined) {\n if (manifestCase.mutator === undefined || manifestCase.tableEntryId === undefined) {\n throw new TypeError('adversarial staged provenance mismatch')\n }\n } else {\n if (\n manifestCase.mutator !== undefined ||\n manifestCase.tableEntryId !== undefined ||\n !isProbeGeneratorKind(manifestCase.kind) ||\n corpusEntry.generator.promptVersion !== manifestCase.promptVersion ||\n corpusEntry.generator.authoringModel === undefined\n ) {\n throw new TypeError('adversarial staged provenance mismatch')\n }\n }\n return { manifest: manifestCase, caseDir, cassette, labelRecord: parsedLabel.record, corpusEntry, texts }\n })\n const batch: StagedAdversarialBatch = { dir, manifest, cases }\n const retirement = readRetirement(batch)\n if (retirement !== undefined) batch.retirement = retirement\n if (retirement === undefined || input.includeRetired === true) batches.push(batch)\n }\n }\n return batches\n}\n\n// ---------------------------------------------------------------------------\n// Admit (D-01): the ONLY writer of adversarial entries into the committed root.\n// ---------------------------------------------------------------------------\n\n/**\n * Commit ONE reviewed batch, named by its digest.\n *\n * The order is deliberate: integrity first (nothing is trusted because it is on disk), then\n * blob resolution, then the one sanctioned seeding writer, then a byte-verification of what\n * actually landed. Only a case whose committed bytes equal the reviewed bytes counts as\n * admitted; the reviewed bytes are committed as authored (441 D-15), and the writer refuses a\n * case that still holds a declared value raw under the required mask (441 GAP3-D1), which this\n * reports as an `unmasked-declared-value` staging skip. No other content check runs.\n */\nexport function refreshAdversarialSplit(\n input: RefreshAdversarialSplitInput,\n): RefreshAdversarialSplitResult {\n requireCorpusMask(input.mask, 'refreshAdversarialSplit')\n const base = { product: input.product, batchDigest: input.batchDigest, admitted: [], unchanged: [],\n refusals: [], remaining: [], stagingSkips: [], writesStarted: false, kind: 'refused' as const }\n if (!LOWER_HEX_64.test(input.batchDigest)) return { ...base, reason: 'batch-not-found' }\n let release: (() => void) | undefined\n try {\n validateBatchIdentity(input.product, input.batchDigest)\n if (!pathPresent(input.agentQaRoot)) return { ...base, reason: 'batch-not-found' }\n const lock = lifecycleLockPath(input)\n if (!pathPresent(dirname(lock))) return { ...base, reason: 'batch-not-found' }\n if (input.dryRun === true) {\n if (pathPresent(lock)) throw new AdversarialLifecycleBusyError(lock)\n } else release = acquireLifecycleLock(lock, input)\n } catch (error) {\n if (error instanceof AdversarialLifecycleBusyError) return { ...base, reason: 'admission-refused', lifecycleBusy: { lockPath: error.lockPath } }\n if (error instanceof TypeError || error instanceof z.ZodError || error instanceof SyntaxError) return { ...base, reason: 'staging-integrity' }\n throw error\n }\n try {\n return refreshAdversarialSplitOwned(input)\n } finally { release?.() }\n}\n\nfunction refreshAdversarialSplitOwned(input: RefreshAdversarialSplitInput): RefreshAdversarialSplitResult {\n const base = {\n product: input.product,\n batchDigest: input.batchDigest,\n admitted: [] as StagedAdversarialCase[],\n unchanged: [] as StagedAdversarialCase[],\n refusals: [] as AdversarialRefusal[],\n remaining: [] as StagedAdversarialCase[],\n stagingSkips: [] as AdversarialStagingSkip[],\n writesStarted: false,\n }\n if (!LOWER_HEX_64.test(input.batchDigest)) {\n return { ...base, kind: 'refused', reason: 'batch-not-found' }\n }\n let batch: StagedAdversarialBatch | undefined\n try {\n batch = listStagedAdversarial({\n agentQaRoot: input.agentQaRoot,\n product: input.product,\n batchDigest: input.batchDigest,\n includeRetired: true,\n })[0]\n } catch (error) {\n // A tampered batch is an integrity refusal, not an operational failure — and it happens\n // BEFORE any committed byte is read for writing, so the corpus digest cannot have moved.\n // An UNRELATED IO failure (an unreadable staging dir, a permissions error) is NOT laundered\n // into a refusal: it propagates as the typed operational failure it is, because reporting\n // \"this batch is tampered\" when the disk was merely unreadable would be a false accusation.\n if (!(error instanceof TypeError) && !(error instanceof z.ZodError) && !(error instanceof SyntaxError)) {\n throw error\n }\n return {\n ...base,\n kind: 'refused',\n reason: 'staging-integrity',\n }\n }\n if (batch === undefined) {\n return { ...base, kind: 'refused', reason: 'batch-not-found' }\n }\n if (batch.retirement !== undefined) {\n const retirement = retirementResult(batch, batch.retirement, true)\n const committed = new Set(retirement.alreadyCommittedCaseIds)\n return { ...base, kind: 'refused', reason: 'admission-refused', retirement,\n unchanged: batch.cases.filter(row => committed.has(row.cassette.id)).map(row => stagedCaseOf(row.manifest)),\n remaining: batch.cases.filter(row => !committed.has(row.cassette.id)).map(row => stagedCaseOf(row.manifest)) }\n }\n const previous = readCommittedCorpusDigest({ committedRoot: input.committedRoot })\n if (previous.kind !== 'digest') return { ...base, kind: 'refused', reason: 'corpus-unavailable' }\n\n const stagingSkips: AdversarialStagingSkip[] = []\n const unchanged: StagedAdversarialCase[] = []\n const admissible: {\n manifestCase: AdversarialBatchManifestCase\n cassette: LeafCassette\n labelRecord: StandaloneLabelRecord\n corpusEntry: AdversarialCorpusEntry\n texts: { cassette: string; label: string; entry: string }\n blobs: ExtractedBlob[]\n }[] = []\n\n // ONE fresh reader snapshot for the whole admission: the seed labels it answers with are\n // COMMITTED bytes, which is what makes the provenance pin unforgeable from staging.\n const committedReader = openCorpusReader(input.committedRoot)\n\n for (const staged of batch.cases) {\n // D-06 against committed truth: the clone must still carry the SEED's run, build ordinal,\n // channel and tier — both as reviewed (the manifest pin) and as the root records them now.\n const seedLabel = committedReader.loadLabel(staged.manifest.seedCassetteId)\n if (seedLabel.kind !== 'loaded') {\n stagingSkips.push({\n cassetteId: staged.manifest.cassetteId,\n seedCassetteId: staged.manifest.seedCassetteId,\n reason: 'seed-label-unavailable',\n })\n continue\n }\n const derivedPin = seedProvenancePin(staged.labelRecord)\n if (\n !samePin(derivedPin, staged.manifest.seedProvenance) ||\n !samePin(derivedPin, seedProvenancePin(seedLabel.record)) ||\n staged.labelRecord.derivedFrom?.seedCassetteId !== staged.manifest.seedCassetteId\n ) {\n stagingSkips.push({\n cassetteId: staged.manifest.cassetteId,\n seedCassetteId: staged.manifest.seedCassetteId,\n reason: 'seed-provenance-mismatch',\n })\n continue\n }\n // Exact-byte admission: the bytes about to be committed must re-serialize identically\n // from the parsed documents, or the reviewed text and the committed text are not one\n // thing. This is what makes \"the operator reviewed THESE bytes\" a checkable claim.\n if (\n committedFileText(staged.cassette) !== staged.texts.cassette ||\n committedFileText(staged.labelRecord) !== staged.texts.label ||\n committedFileText(staged.corpusEntry) !== staged.texts.entry\n ) {\n stagingSkips.push({\n cassetteId: staged.manifest.cassetteId,\n seedCassetteId: staged.manifest.seedCassetteId,\n reason: 'text-hash-mismatch',\n })\n continue\n }\n const resolved = resolveSeedBlobs(\n input.committedRoot,\n input.product,\n staged.manifest.seedCassetteId,\n staged.manifest.blobShas,\n )\n if ('skipReason' in resolved) {\n stagingSkips.push({\n cassetteId: staged.manifest.cassetteId,\n seedCassetteId: staged.manifest.seedCassetteId,\n reason: resolved.skipReason,\n })\n continue\n }\n // D-04/D-08 against what is ALREADY committed. Three cases, and only the third is work:\n // byte-identical is `unchanged` (an interrupted run's survivor, or a duplicate admission —\n // the digest does not move for it); conflicting bytes are refused, because deciding which\n // of two versions of one id is right is not an admission's call and history wins; absent\n // is the case this run commits.\n const present = committedState(input.committedRoot, input.product, staged.manifest.cassetteId, staged.texts)\n if (present === 'conflict') {\n stagingSkips.push({\n cassetteId: staged.manifest.cassetteId,\n seedCassetteId: staged.manifest.seedCassetteId,\n reason: 'committed-conflict',\n })\n continue\n }\n if (present === 'identical') {\n unchanged.push(stagedCaseOf(staged.manifest))\n continue\n }\n admissible.push({\n manifestCase: staged.manifest,\n cassette: staged.cassette,\n labelRecord: staged.labelRecord,\n corpusEntry: staged.corpusEntry,\n texts: staged.texts,\n blobs: resolved.blobs,\n })\n }\n\n const result: AdversarialAdmissionResult = {\n ...base,\n kind: 'admitted',\n unchanged,\n stagingSkips,\n previousCorpusDigest: previous.corpusDigest,\n }\n const reviewed = batch.cases.map(row => stagedCaseOf(row.manifest))\n const notLanded = (landed: readonly StagedAdversarialCase[]): StagedAdversarialCase[] => {\n const done = new Set(landed.map(row => row.cassetteId))\n return reviewed.filter(row => !done.has(row.cassetteId))\n }\n\n if (input.dryRun === true) {\n // A preview reports what WOULD be committed and what is already there, and writes nothing.\n return {\n ...result,\n kind: 'dry-run',\n admitted: admissible.map(row => stagedCaseOf(row.manifestCase)),\n remaining: notLanded([...unchanged, ...admissible.map(row => stagedCaseOf(row.manifestCase))]),\n }\n }\n if (admissible.length === 0) {\n // Nothing to write. Already-complete is an ADMISSION whose digest simply does not move;\n // nothing admissible and nothing unchanged is a refusal.\n const complete = unchanged.length === reviewed.length && reviewed.length > 0\n if (complete) cleanupCompletedAdmissionBatch(batch.dir)\n return {\n ...result,\n kind: complete ? 'admitted' : 'refused',\n ...(complete ? {} : { reason: 'admission-refused' as const }),\n remaining: notLanded(unchanged),\n nextCorpusDigest: previous.corpusDigest,\n }\n }\n\n // Commit ONE case at a time. The batch was preflighted in full above, so every case reached\n // here was already judged admissible — which is what makes stopping between them safe: an\n // interruption leaves committed bytes that a retry recognises as `unchanged`, never a\n // half-written case and never a case nobody checked.\n const admitted: StagedAdversarialCase[] = []\n let interrupted = false\n input.beforeWrites?.()\n result.writesStarted = true\n for (const row of admissible) {\n const runId = row.corpusEntry.run_links.runId\n const plan: SeedingPlan = {\n product: input.product,\n runId,\n runSlug: deriveRunSlug(runId),\n cases: [\n {\n cassetteId: row.cassette.id,\n labelRecord: row.labelRecord,\n corpusEntry: row.corpusEntry,\n },\n ],\n pairSkips: [],\n silverExclusions: [],\n pairCounts: { total: 0, sameState: 0, differingState: 0 },\n proceduresExcludedCount: 0,\n }\n const cassettes: ExtractedCassette[] = [{ cassette: row.cassette, blobs: row.blobs }]\n let report: SeedingBatchReport['reports'][number] | undefined\n try {\n report = seedCommittedCorpus({\n batches: [{ plan, cassettes }],\n committedRoot: input.committedRoot,\n mask: input.mask,\n }).reports[0]\n } catch {\n report = undefined\n }\n if (report === undefined || report.refusals.length > 0) {\n stagingSkips.push({\n cassetteId: row.cassette.id,\n seedCassetteId: row.manifestCase.seedCassetteId,\n reason: report?.refusals.some(refusal => refusal.kind === 'unmasked-declared-value') === true\n ? 'unmasked-declared-value'\n : report?.refusals.some(refusal => refusal.kind === 'write-conflict') === true\n ? 'committed-conflict'\n : 'text-hash-mismatch',\n })\n continue\n }\n // Neither aggregate counts nor the absence of an exception is evidence: verify the bytes.\n if (committedState(input.committedRoot, input.product, row.cassette.id, row.texts) !== 'identical'\n || !blobsCommitted(input.committedRoot, input.product, row.cassette.id, row.blobs)) {\n stagingSkips.push({\n cassetteId: row.cassette.id,\n seedCassetteId: row.manifestCase.seedCassetteId,\n reason: 'text-hash-mismatch',\n })\n continue\n }\n admitted.push(stagedCaseOf(row.manifestCase))\n try {\n input.afterCaseCommitted?.(row.cassette.id)\n } catch {\n // A real interruption at exactly this point: the case above is committed and stays so.\n interrupted = true\n break\n }\n }\n\n const landed = [...admitted, ...unchanged]\n const remaining = notLanded(landed)\n // Retire the reviewed batch only when every member landed AND this run finished its own\n // bookkeeping. A partial batch — or one whose run was interrupted after the last case —\n // stays on disk so the operator resumes THAT manifest rather than deriving a different one.\n const complete = remaining.length === 0 && !interrupted\n if (complete) cleanupCompletedAdmissionBatch(batch.dir)\n\n const next = readCommittedCorpusDigest({ committedRoot: input.committedRoot })\n const kind: AdversarialAdmissionResult['kind'] =\n complete ? 'admitted' : admitted.length > 0 ? 'partial' : 'refused'\n return {\n ...result,\n kind,\n // An interruption and a refusal are different facts about an incomplete batch: one stopped,\n // the other was told no. Reporting either as the other misdirects the operator's next move.\n ...(complete\n ? {}\n : { reason: interrupted ? ('admission-interrupted' as const) : ('admission-refused' as const) }),\n admitted,\n unchanged,\n remaining,\n stagingSkips,\n writesStarted: true,\n ...(next.kind === 'digest' ? { nextCorpusDigest: next.corpusDigest } : {}),\n }\n}\n\n/**\n * Whether this id is ALREADY committed, and whether its bytes are the reviewed ones.\n *\n * `absent` only when all three documents are missing: a root holding one of them is a partial\n * write, not an empty slot, and calling it absent would let an admission write over the rest.\n */\nfunction committedState(\n committedRoot: string,\n product: string,\n cassetteId: string,\n texts: { cassette: string; label: string; entry: string },\n): 'absent' | 'identical' | 'conflict' {\n const files: [string, string][] = [\n [join(committedRoot, committedCassettePath(product, cassetteId)), texts.cassette],\n [join(committedRoot, committedLabelPath(product, cassetteId)), texts.label],\n [join(committedRoot, committedCorpusPath(product, cassetteId)), texts.entry],\n ]\n let present = 0\n let equal = 0\n for (const [file, expected] of files) {\n let actual: string\n try {\n actual = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n present += 1\n if (actual === expected) equal += 1\n }\n if (present === 0) return 'absent'\n return equal === files.length ? 'identical' : 'conflict'\n}\n\n/** The derived cassette's own committed blob closure, byte-compared. */\nfunction blobsCommitted(\n committedRoot: string,\n product: string,\n cassetteId: string,\n blobs: readonly ExtractedBlob[],\n): boolean {\n try {\n return blobs.every(blob =>\n readFileSync(join(committedRoot, committedBlobPath(product, cassetteId, blob.sha))).equals(\n Buffer.from(blob.bytes),\n ),\n )\n } catch {\n return false\n }\n}\n\n/**\n * Write a completion for a call THIS refresh made, and never for one it only read back.\n *\n * A tuple whose completion was already on disk is being re-derived for free; writing a second\n * completion for it would be a write-once conflict over bytes that are already true.\n */\nfunction recordProbeOutcome(\n agentQaRoot: string,\n attempt: { kind: string },\n key: ProbeReservationKey,\n completion: ProbeCompletion,\n): void {\n if (attempt.kind === 'completed') return\n completeProbeCall({ agentQaRoot, key, completion })\n}\n\n/** Cleanup is not un-admission: the bytes are already verified in the committed root. */\nfunction cleanupCompletedAdmissionBatch(dir: string): void {\n try {\n rmSync(dir, { recursive: true })\n } catch {\n // A staging directory that cannot be removed is an operator annoyance, not a failed admission.\n }\n}\n\nfunction stagedCaseOf(manifestCase: AdversarialBatchManifestCase): StagedAdversarialCase {\n return {\n cassetteId: manifestCase.cassetteId,\n seedCassetteId: manifestCase.seedCassetteId,\n kind: manifestCase.kind,\n ...(manifestCase.mutator === undefined ? {} : { mutator: manifestCase.mutator }),\n ...(manifestCase.tableEntryId === undefined ? {} : { tableEntryId: manifestCase.tableEntryId }),\n ...(manifestCase.promptVersion === undefined ? {} : { promptVersion: manifestCase.promptVersion }),\n }\n}\n\n/** Re-exported for callers that only need the derived provenance shape. */\nexport type { CorpusGenerator }\n","// 2026-09-11, 422 D-04/D-08: the durable adversarial refresh record — what a capped refresh\n// already decided, so the next one does not spend its cap deciding it again.\n//\n// The problem this store exists to solve. A refresh is capped (D-04) because eleven frozen\n// families over a grown corpus produce more cases than any operator reviews. A cap alone,\n// however, starves the corpus: the seeds are selected in one deterministic order, so unless\n// something on disk records that a leading seed is DONE, the same leading seeds are re-selected\n// every time and the seeds behind them are never reached. Staged and committed cassette ids\n// cover the seeds that produced a variant. They say nothing about the ones that produced an\n// inapplicability — and those are exactly the seeds that would monopolise the cap forever,\n// because they leave no trace to skip.\n//\n// The key (D-08). A completed `(seed, mutator)` tuple is settled for the table GENERATION it was\n// decided under, and for nothing else: a `tableVersion` bump is a NEW generation. Its ids are\n// different ids, so its tuples are open again — and it retires nothing:\n// `derivedAdversarialCassetteIds` spans every generation, so an id committed under generation 1\n// is never re-derived beneath a later one. Since 441-53 (D-15) no guardrail policy scopes a\n// tuple; a record written before then carries a policy digest and is read as malformed (D-20).\n//\n// Publication (S3, canary-run-state). A record is named by its own content digest and linked\n// into place write-once, with the file and its directory fsynced. Two refreshes racing over one\n// unchanged corpus derive the same ids and settle the same tuples, so they publish the SAME\n// bytes under the SAME name — an idempotent no-op rather than two competing histories. Different\n// bytes under one name is a conflict and throws; this record is the audit trail a later refresh\n// trusts, so overwriting it silently would let a bad write erase the reason a seed was skipped.\n//\n// Deliberately absent: a timestamp. `stagedAt` sits outside the batch digest for the same reason\n// (422-01) — a clock reading inside the canonical bytes would make two identical concurrent\n// refreshes conflict, which is precisely the collision this write-once shape exists to absorb.\n// A record's time is its file mtime and its commit, not a field the content address depends on.\n\nimport { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'\nimport { createHash, randomUUID } from 'node:crypto'\nimport { dirname, join, resolve } from 'node:path'\n\nimport {\n ADVERSARIAL_CAP_SOURCES,\n ADVERSARIAL_DEFAULT_MAX_SEEDS_PER_REFRESH,\n ADVERSARIAL_MUTATORS,\n PROBE_GENERATOR_KINDS,\n canonicalJson,\n probeReservationStatus,\n type AdversarialCapSource,\n type AdversarialMutator,\n type ProbeGeneratorKind,\n} from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\n/**\n * Durable refresh state lives BESIDE the staging tree, never inside it: a staged batch\n * directory is reviewable data an operator may delete after admitting or rejecting it, and the\n * record of what was already decided must outlive that.\n */\nexport const ADVERSARIAL_STATE_SUBDIR = 'eval/adversarial-state'\n\nexport const ADVERSARIAL_STATE_SCHEMA_VERSION = 2\n\n/**\n * The separator the settled-tuple key joins on — the `adversarialDrawKey` idiom. No cassette id\n * and no mutator can contain U+001F, so `(a, bc)` and `(ab, c)` can never collide into one key.\n */\nconst TUPLE_KEY_SEPARATOR = '\\u001F'\n\nconst LOWER_HEX_64 = /^[0-9a-f]{64}$/\nconst digestField = z.string().regex(LOWER_HEX_64)\n\n/**\n * What a completed `(seed, mutator)` tuple resolved to.\n *\n * Both are COMPLETED work. `derived` produced reviewable bytes; `inapplicable` is the\n * generator's own typed statement that the family cannot act on this seed. A tuple that is\n * merely DEFERRED (`cap-exceeded`) or that was already settled earlier (`already-derived`) is not\n * an outcome and never lands here — recording either would settle work nobody did.\n */\nexport type AdversarialTupleOutcome = 'derived' | 'inapplicable'\n\nexport interface AdversarialRefreshTuple {\n seedCassetteId: string\n mutator: AdversarialMutator\n /** The derived id this tuple addresses — stable across outcomes, because it is a function of the generation, not of the result (D-08). */\n cassetteId: string\n outcome: AdversarialTupleOutcome\n /** The inapplicability reason for `inapplicable`; absent for `derived`. */\n detail?: string\n}\n\n/**\n * The resolved cap and where the operator set it — recorded so a refresh can explain itself.\n *\n * 2026-09-12, 422-22: `source` names the NEUTRAL vocabulary rather than re-spelling it. This\n * record is persisted, and a storage-side copy of a persisted vocabulary is a second list to keep\n * in step with the first — which is how one of them ends up admitting an origin the other refuses.\n */\nexport interface AdversarialSeedCap {\n value: number\n source: AdversarialCapSource\n}\n\nexport interface AdversarialRefreshRecord {\n schemaVersion: typeof ADVERSARIAL_STATE_SCHEMA_VERSION\n product: string\n /** The frozen table generation these outcomes were decided under. */\n tableVersion: number\n /** The committed corpus digest this refresh read its seeds from. */\n sourceDigest: string\n cap: AdversarialSeedCap\n /** Novel eligible seeds counted BEFORE the cap was applied. */\n eligibleSeeds: number\n /** Novel eligible seeds the cap deferred to a later refresh. */\n excessSeeds: number\n /** Immutable batch membership: the seed ids this refresh selected, ascending. */\n seedIds: readonly string[]\n tuples: readonly AdversarialRefreshTuple[]\n}\n\nconst tupleSchema = z.object({\n seedCassetteId: z.string().min(1),\n mutator: z.enum(ADVERSARIAL_MUTATORS),\n cassetteId: z.string().min(1),\n outcome: z.enum(['derived', 'inapplicable']),\n detail: z.string().min(1).optional(),\n}).strict()\n\nconst recordSchema = z.object({\n schemaVersion: z.literal(ADVERSARIAL_STATE_SCHEMA_VERSION),\n product: z.string().min(1),\n tableVersion: z.number().int().nonnegative(),\n sourceDigest: digestField,\n cap: z.object({\n value: z.number().int().positive(),\n source: z.enum(ADVERSARIAL_CAP_SOURCES),\n }).strict(),\n eligibleSeeds: z.number().int().nonnegative(),\n excessSeeds: z.number().int().nonnegative(),\n seedIds: z.array(z.string().min(1)),\n tuples: z.array(tupleSchema),\n}).strict()\n\n/** The record's own content address — its file name, and the whole of its identity. */\nexport function adversarialRefreshRecordDigest(record: AdversarialRefreshRecord): string {\n return createHash('sha256').update(canonicalJson(record), 'utf8').digest('hex')\n}\n\n/** The settled-tuple key. Public so a caller can build the same key it will be checked against. */\nexport function adversarialTupleKey(seedCassetteId: string, mutator: AdversarialMutator): string {\n return `${seedCassetteId}${TUPLE_KEY_SEPARATOR}${mutator}`\n}\n\n/**\n * Resolve the per-refresh seed cap (D-04).\n *\n * Every rejected boundary is rejected LOUDLY: zero, negative, fractional, nonfinite and\n * beyond-safe-integer caps are a TypeError rather than a silent fallback to the default. A cap\n * that quietly becomes 8 because the operator typed `0` is a cap the operator does not have.\n */\nexport function resolveAdversarialSeedCap(input: {\n value?: number\n source?: Exclude<AdversarialCapSource, 'default'>\n}): AdversarialSeedCap {\n if (input.value === undefined) {\n return { value: ADVERSARIAL_DEFAULT_MAX_SEEDS_PER_REFRESH, source: 'default' }\n }\n if (!Number.isSafeInteger(input.value) || input.value < 1) {\n throw new TypeError('adversarial seed cap must be a positive safe integer')\n }\n return { value: input.value, source: input.source ?? 'flag' }\n}\n\n// ---------------------------------------------------------------------------\n// Guarded local IO (the staging composition's posture, on this store's own tree).\n// ---------------------------------------------------------------------------\n\nfunction pathPresent(path: string): boolean {\n try {\n lstatSync(path)\n return true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n}\n\n/** Refuse links and wrong-kind ancestors rather than following a state path out of its root. */\nfunction requireDirectories(path: string): void {\n const absolute = resolve(path)\n const parent = dirname(absolute)\n if (parent !== absolute) requireDirectories(parent)\n if (pathPresent(absolute) && !lstatSync(absolute).isDirectory()) {\n throw new TypeError('unsafe adversarial state directory')\n }\n}\n\n/**\n * The product's state directory under a REAL root.\n *\n * `realpathSync` matches the staging composition's posture and is not cosmetic: the\n * ancestor-kind walk below refuses any non-directory component, and on macOS `/tmp` is itself a\n * symlink — an unresolved path would make every host whose root sits under a linked ancestor\n * look unsafe.\n */\nfunction productStateDir(agentQaRoot: string, product: string): string {\n return join(realpathSync(agentQaRoot), ADVERSARIAL_STATE_SUBDIR, slugBranch(product))\n}\n\nfunction recordText(record: AdversarialRefreshRecord): string {\n return `${canonicalJson(record)}\\n`\n}\n\n/**\n * Every published refresh record for one product, in file-name order.\n *\n * An absent tree is an empty history, not a failure — the first refresh on a host has no state\n * and must not be told the store is broken. A record that fails the strict schema (one written\n * before Phase 441 carries a policy digest) is absent too: D-20 migrates nothing (441-64, CR-C02).\n * Unparseable bytes, and a record that parses but whose digest name or product does not match,\n * are still failures.\n */\nexport function readAdversarialRefreshRecords(input: {\n agentQaRoot: string\n product: string\n}): AdversarialRefreshRecord[] {\n if (!pathPresent(input.agentQaRoot)) return []\n const dir = productStateDir(input.agentQaRoot, input.product)\n requireDirectories(dir)\n if (!pathPresent(dir)) return []\n const names = readdirSync(dir, { withFileTypes: true })\n .filter(entry => {\n if (entry.name.startsWith('.')) return false\n if (!entry.isFile()) throw new TypeError('unexpected adversarial state path')\n return entry.name.endsWith('.json')\n })\n .map(entry => entry.name)\n .sort()\n return names.flatMap(name => {\n const parsed = recordSchema.safeParse(JSON.parse(readFileSync(join(dir, name), 'utf8')))\n if (!parsed.success) return []\n const record = parsed.data as AdversarialRefreshRecord\n if (`${adversarialRefreshRecordDigest(record)}.json` !== name) {\n throw new TypeError('adversarial refresh record identity mismatch')\n }\n if (slugBranch(record.product) !== slugBranch(input.product)) {\n throw new TypeError('adversarial refresh record product mismatch')\n }\n return [record]\n })\n}\n\n/**\n * Publish one refresh record write-once, under its own content address.\n *\n * `unchanged` means the identical record was already published — the concurrent-refresh case,\n * and the re-run-over-an-unchanged-corpus case. Anything else under that name is a conflict.\n */\nexport function publishAdversarialRefreshRecord(input: {\n agentQaRoot: string\n record: AdversarialRefreshRecord\n}): 'published' | 'unchanged' {\n const record = recordSchema.parse(input.record) as AdversarialRefreshRecord\n mkdirSync(input.agentQaRoot, { recursive: true })\n const dir = productStateDir(input.agentQaRoot, record.product)\n requireDirectories(dir)\n mkdirSync(dir, { recursive: true })\n const file = join(dir, `${adversarialRefreshRecordDigest(record)}.json`)\n const text = recordText(record)\n const temporary = join(dir, `.${randomUUID()}.tmp`)\n try {\n writeFileSync(temporary, text, { flag: 'wx', mode: 0o600 })\n const fd = openSync(temporary, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n let published: 'published' | 'unchanged' = 'published'\n try {\n linkSync(temporary, file)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n if (readFileSync(file, 'utf8') !== text) {\n throw new Error('adversarial refresh record conflict')\n }\n published = 'unchanged'\n }\n const directory = openSync(dir, 'r')\n try {\n fsyncSync(directory)\n } finally {\n closeSync(directory)\n }\n return published\n } finally {\n rmSync(temporary, { force: true })\n }\n}\n\n/**\n * The `(seed, mutator)` tuples already decided under THIS generation.\n *\n * A refresh skips these, which is what lets its cap reach the seeds behind them. Scoping by the\n * generation is the whole contract: a new generation does not inherit a decision that was not\n * made about it.\n */\nexport function settledAdversarialTuples(\n records: readonly AdversarialRefreshRecord[],\n scope: { tableVersion: number },\n): ReadonlySet<string> {\n return new Set(settledAdversarialTupleIndex(records, scope).keys())\n}\n\n/**\n * The same scoped settlement, keyed so a caller can say WHY a tuple was skipped.\n *\n * A refresh that silently drops a settled seed reports an empty batch with no explanation,\n * which is the disclosure regression a bounded refresh must not introduce: the operator has to\n * be able to tell \"nothing new applies\" from \"nothing ran\".\n */\nexport function settledAdversarialTupleIndex(\n records: readonly AdversarialRefreshRecord[],\n scope: { tableVersion: number },\n): ReadonlyMap<string, AdversarialRefreshTuple> {\n const settled = new Map<string, AdversarialRefreshTuple>()\n for (const record of records) {\n if (record.tableVersion !== scope.tableVersion) continue\n for (const tuple of record.tuples) {\n settled.set(adversarialTupleKey(tuple.seedCassetteId, tuple.mutator), tuple)\n }\n }\n return settled\n}\n\n/**\n * Every id this product has EVER derived, across all generations.\n *\n * Unscoped on purpose (D-08): a generation bump creates new ids beside the old, and the old\n * ones are committed history. Re-deriving one would address bytes that already exist, so this\n * set only ever grows.\n */\nexport function derivedAdversarialCassetteIds(\n records: readonly AdversarialRefreshRecord[],\n): ReadonlySet<string> {\n const ids = new Set<string>()\n for (const record of records) {\n for (const tuple of record.tuples) {\n if (tuple.outcome === 'derived') ids.add(tuple.cassetteId)\n }\n }\n return ids\n}\n\n// ---------------------------------------------------------------------------\n// 422 D-04/D-11: the PROBE RESERVATION store — an ask that is durable before it is asked.\n//\n// WHY THIS IS A SECOND STORE AND NOT AN ARM OF THE RECORD ABOVE. `AdversarialRefreshRecord` is\n// named by its own content digest, which is exactly what lets two concurrent refreshes over one\n// unchanged corpus publish the same bytes instead of fighting. A reservation cannot work that\n// way: its content is a claim about work that has NOT happened yet, so the outcome is unknown at\n// the moment the name would have to be computed, and content-addressing a row whose content\n// changes is a contradiction. 422-03 recorded that its record \"will need a reservation arm\"; the\n// truthful answer is that it needs a SIBLING, and the property that makes the record good is\n// precisely the property that stops it from carrying one.\n//\n// THREE STATES, ENCODED STRUCTURALLY. `unattempted` is no reservation. `completed` is a\n// reservation plus a completion. `interrupted` is a reservation with NO completion — and it is\n// derived rather than written, because the one thing a dying process cannot do is record that it\n// died. A status field would have to be updated by the very code that failed to run.\n//\n// WHAT A RESERVATION MAY SAY. Its KEY is `(product, seed, kind, promptVersion)` and nothing else\n// (D-11): not the returned text, which does not exist yet, and not the author, because a second\n// host with a second model must not buy a second copy of a probe this corpus already holds. Its\n// BODY names the author by DIGEST and family rather than by raw model id — a configured model id\n// can itself embed a credential (422-05).\n// ---------------------------------------------------------------------------\n\n/**\n * Probe reservations live beside the refresh-state tree, never inside a staged batch: a batch is\n * reviewable data an operator may delete, and the record of what was already PAID FOR must\n * outlive that even more emphatically than the record of what was already decided.\n */\nexport const ADVERSARIAL_PROBE_SUBDIR = 'eval/adversarial-probes'\n\nexport const ADVERSARIAL_PROBE_SCHEMA_VERSION = 2\n\n/** D-11's idempotence key, as durable fields. */\nexport interface ProbeReservationKey {\n product: string\n seedCassetteId: string\n kind: ProbeGeneratorKind\n promptVersion: number\n}\n\n/** The row written BEFORE a provider is contacted. Its existence is the charge. */\nexport interface ProbeReservation extends ProbeReservationKey {\n schemaVersion: typeof ADVERSARIAL_PROBE_SCHEMA_VERSION\n /** The frozen prompt hash the request was rendered from. */\n promptHash: string\n /** sha256 of the configured model id — never the id, which can embed a credential. */\n authorDigest: string\n /** The resolved provider family, which cannot. */\n authorFamily: string\n}\n\n/**\n * What a provider call resolved to.\n *\n * All four are ANSWERS — the port returned control. `derived` carries the authored text so a\n * later refresh can re-derive the same case for free; `refused` is a policy block recorded\n * before 441-42 and only read back now, `invalid` an\n * answer the pure contract rejected, and `error` a call that failed. None of the last three\n * carries text: a refused surface is data, not a diagnostic.\n */\nexport type ProbeCompletionOutcome = 'derived' | 'refused' | 'invalid' | 'error'\n\nexport interface ProbeCompletion {\n schemaVersion: typeof ADVERSARIAL_PROBE_SCHEMA_VERSION\n outcome: ProbeCompletionOutcome\n /** Present only on `derived`: the authored text and the id it produced. */\n text?: string\n cassetteId?: string\n /** Reported spend, present only when the provider reported it. ABSENT is not zero. */\n promptTokens?: number\n completionTokens?: number\n /** The firing detector or the refusal reason; never the refused text. */\n detail?: string\n}\n\n/**\n * The store's answer about one tuple.\n *\n * `usageKnown` is on every arm and is never inferred from a zero: an interrupted attempt and a\n * failed one both have unknown tokens, and reporting them as `0` would make a real charge read\n * as a free one.\n */\nexport type ProbeAttemptState =\n | { kind: 'unattempted'; usageKnown: false }\n | { kind: 'interrupted'; reservation: ProbeReservation; usageKnown: false }\n | { kind: 'completed'; reservation: ProbeReservation; completion: ProbeCompletion; usageKnown: boolean }\n\n/** Build the durable reservation for one tuple. Pure; the author is reduced to a digest here. */\nexport function probeReservationOf(\n key: ProbeReservationKey,\n input: { promptHash: string; author: { id: string; family: string } },\n): ProbeReservation {\n return {\n schemaVersion: ADVERSARIAL_PROBE_SCHEMA_VERSION,\n ...key,\n promptHash: input.promptHash,\n authorDigest: createHash('sha256').update(input.author.id, 'utf8').digest('hex'),\n authorFamily: input.author.family,\n }\n}\n\nconst probeReservationSchema = z.object({\n schemaVersion: z.literal(ADVERSARIAL_PROBE_SCHEMA_VERSION),\n product: z.string().min(1),\n seedCassetteId: z.string().min(1),\n kind: z.enum(PROBE_GENERATOR_KINDS),\n promptVersion: z.number().int().nonnegative(),\n promptHash: digestField,\n authorDigest: digestField,\n authorFamily: z.string().min(1),\n}).strict()\n\nconst probeCompletionSchema = z.object({\n schemaVersion: z.literal(ADVERSARIAL_PROBE_SCHEMA_VERSION),\n outcome: z.enum(['derived', 'refused', 'invalid', 'error']),\n text: z.string().min(1).optional(),\n cassetteId: z.string().min(1).optional(),\n promptTokens: z.number().int().nonnegative().optional(),\n completionTokens: z.number().int().nonnegative().optional(),\n detail: z.string().min(1).optional(),\n}).strict()\n\n/** The tuple's address on disk. NOT content-addressed: this names the QUESTION, not the answer. */\nfunction probeTupleDigest(key: ProbeReservationKey): string {\n return createHash('sha256')\n .update(\n canonicalJson({\n product: key.product,\n seedCassetteId: key.seedCassetteId,\n kind: key.kind,\n promptVersion: key.promptVersion,\n }),\n 'utf8',\n )\n .digest('hex')\n}\n\nfunction probeStateDir(agentQaRoot: string, product: string): string {\n return join(realpathSync(agentQaRoot), ADVERSARIAL_PROBE_SUBDIR, slugBranch(product))\n}\n\nfunction reservationFileName(key: ProbeReservationKey): string {\n return `${probeTupleDigest(key)}.reservation.json`\n}\n\nfunction completionFileName(key: ProbeReservationKey): string {\n return `${probeTupleDigest(key)}.completion.json`\n}\n\n/** Write `text` at `file` exactly once, fsynced, with its directory fsynced behind it. */\nfunction linkOnce(dir: string, file: string, text: string): 'published' | 'exists' {\n mkdirSync(dir, { recursive: true })\n const temporary = join(dir, `.${randomUUID()}.tmp`)\n try {\n writeFileSync(temporary, text, { flag: 'wx', mode: 0o600 })\n const fd = openSync(temporary, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n let outcome: 'published' | 'exists' = 'published'\n try {\n linkSync(temporary, file)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n outcome = 'exists'\n }\n const directory = openSync(dir, 'r')\n try {\n fsyncSync(directory)\n } finally {\n closeSync(directory)\n }\n return outcome\n } finally {\n rmSync(temporary, { force: true })\n }\n}\n\nfunction readJsonIfPresent(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\n/**\n * Whether a completion's tokens are actually KNOWN.\n *\n * `derived`, `refused` and `invalid` all came back from a provider that reported usage, so both\n * counts are present. `error` never does. The predicate reads the FIELDS rather than the outcome\n * word, so a completion that somehow lacks them is reported as unknown rather than as zero.\n */\nfunction completionUsageKnown(completion: ProbeCompletion): boolean {\n return completion.promptTokens !== undefined && completion.completionTokens !== undefined\n}\n\nfunction attemptStateFrom(dir: string, key: ProbeReservationKey): ProbeAttemptState {\n const rawReservation = readJsonIfPresent(join(dir, reservationFileName(key)))\n if (rawReservation === undefined) return { kind: 'unattempted', usageKnown: false }\n const reservation = probeReservationSchema.parse(rawReservation) as ProbeReservation\n const rawCompletion = readJsonIfPresent(join(dir, completionFileName(key)))\n // THE DERIVATION THAT MATTERS. A reservation with no completion is `interrupted`, and it is\n // read that way rather than written that way because the one thing a dying process cannot do\n // is record that it died. A status field would have to be updated by the code that failed.\n //\n // 2026-09-12, 422-22: the derivation itself is the NEUTRAL `probeReservationStatus`, and the arm\n // takes its name from the word that function returned — so this reader's arm names and the\n // staging report's status words are one vocabulary rather than the same three facts spelled\n // twice. A rename on either side stops compiling here.\n const status = probeReservationStatus({\n reservationRecorded: true,\n completionRecorded: rawCompletion !== undefined,\n })\n if (status === 'interrupted') return { kind: status, reservation, usageKnown: false }\n const completion = probeCompletionSchema.parse(rawCompletion) as ProbeCompletion\n return { kind: 'completed', reservation, completion, usageKnown: completionUsageKnown(completion) }\n}\n\n/** What the durable store says about ONE tuple. An absent tree is an empty history, not a failure. */\nexport function readProbeAttempt(input: {\n agentQaRoot: string\n key: ProbeReservationKey\n}): ProbeAttemptState {\n if (!pathPresent(input.agentQaRoot)) return { kind: 'unattempted', usageKnown: false }\n const dir = probeStateDir(input.agentQaRoot, input.key.product)\n requireDirectories(dir)\n if (!pathPresent(dir)) return { kind: 'unattempted', usageKnown: false }\n return attemptStateFrom(dir, input.key)\n}\n\n/**\n * Every attempt this product has on disk, in tuple-digest order.\n *\n * The disclosure surface: a report that wants to say \"these calls were made and this one is\n * still unanswered\" reads it here. A PRESENT but malformed row is a failure, never silently\n * dropped — this is the evidence a later refresh declines to spend on.\n */\nexport function readProbeAttempts(input: {\n agentQaRoot: string\n product: string\n}): ProbeAttemptState[] {\n if (!pathPresent(input.agentQaRoot)) return []\n const dir = probeStateDir(input.agentQaRoot, input.product)\n requireDirectories(dir)\n if (!pathPresent(dir)) return []\n const reservations = readdirSync(dir, { withFileTypes: true })\n .filter(entry => {\n if (entry.name.startsWith('.')) return false\n if (!entry.isFile()) throw new TypeError('unexpected adversarial probe state path')\n return entry.name.endsWith('.reservation.json')\n })\n .map(entry => entry.name)\n .sort()\n return reservations.map(name => {\n const reservation = probeReservationSchema.parse(\n JSON.parse(readFileSync(join(dir, name), 'utf8')),\n ) as ProbeReservation\n if (reservationFileName(reservation) !== name) {\n throw new TypeError('adversarial probe reservation identity mismatch')\n }\n if (slugBranch(reservation.product) !== slugBranch(input.product)) {\n throw new TypeError('adversarial probe reservation product mismatch')\n }\n return attemptStateFrom(dir, reservation)\n })\n}\n\n/**\n * Claim the allowance for ONE tuple, exclusively, BEFORE anything reaches a provider.\n *\n * `already-claimed` is not an error and is not a retry: it is the answer a concurrent owner —\n * or a later run over the same disk — must get, together with the reservation that actually\n * exists. Unlike the refresh record above this one is NOT content-addressed, so differing bytes\n * under one name are not a conflict: two hosts with two authors asking the same question is\n * exactly the race this arbitrates, and the first claim wins outright.\n */\nexport function reserveProbeCall(input: {\n agentQaRoot: string\n reservation: ProbeReservation\n}): { kind: 'claimed' | 'already-claimed'; state: ProbeAttemptState } {\n const reservation = probeReservationSchema.parse(input.reservation) as ProbeReservation\n mkdirSync(input.agentQaRoot, { recursive: true })\n const dir = probeStateDir(input.agentQaRoot, reservation.product)\n requireDirectories(dir)\n const file = join(dir, reservationFileName(reservation))\n const outcome = linkOnce(dir, file, `${canonicalJson(reservation)}\\n`)\n return {\n kind: outcome === 'published' ? 'claimed' : 'already-claimed',\n state: attemptStateFrom(dir, reservation),\n }\n}\n\n/**\n * Record what ONE reserved call resolved to, write-once.\n *\n * Two refusals, both deliberate. A completion for a tuple nothing reserved is refused, because\n * it would show an answer nobody was ever charged for. A SECOND, different completion for one\n * tuple is refused, because the completion is the reason a tuple is closed and overwriting it\n * would erase why — the same law the refresh record keeps, for the same reason. An identical\n * re-write is `unchanged`: a retry that recomputes the same answer is a no-op, not a conflict.\n */\nexport function completeProbeCall(input: {\n agentQaRoot: string\n key: ProbeReservationKey\n completion: ProbeCompletion\n}): 'published' | 'unchanged' {\n const completion = probeCompletionSchema.parse(input.completion) as ProbeCompletion\n if (!pathPresent(input.agentQaRoot)) {\n throw new TypeError('adversarial probe completion without a reservation')\n }\n const dir = probeStateDir(input.agentQaRoot, input.key.product)\n requireDirectories(dir)\n if (!pathPresent(join(dir, reservationFileName(input.key)))) {\n throw new TypeError('adversarial probe completion without a reservation')\n }\n const file = join(dir, completionFileName(input.key))\n const text = `${canonicalJson(completion)}\\n`\n if (linkOnce(dir, file, text) === 'published') return 'published'\n if (readFileSync(file, 'utf8') !== text) {\n throw new Error('adversarial probe completion conflict')\n }\n return 'unchanged'\n}\n","// Write-once committed eval-root store (Phase 371, ROOT-01/D-15/D-17).\n//\n// Owns the physical committed root: cassettes/ · corpus/ · labels/ · contracts/ · reports/,\n// product-partitioned, scaffolded on first seed with a .gitignore whose one rule covers\n// every blobs/ dir at any depth plus a schemaVersion root marker (D-15). Every text write\n// is write-once: a byte-identical re-write is a silent 'unchanged' no-op, the same path\n// with differing bytes is a typed 'write-conflict' refusal — never an overwrite, never a\n// delete (D-17). The ONLY mutations in this file are recursive mkdir and create-new-file\n// writes; the staging store's dir-recreate posture is deliberately inverted here.\n//\n// Boundary: text reaching this store has passed the committed-egress checkpoint upstream\n// (the seeding composition helper checks BEFORE handing text over) — the store enforces\n// write-once and layout, never content policy. Blob bytes bypass the text checkpoint and\n// land only under ignore-covered blobs/ dirs after sha-format + byte-hash verification.\n//\n// Every id-derived path segment passes schema's security-reviewed slugBranch sanitizer\n// (T-368-10 posture): a crafted cassette id cannot escape the committed root.\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\n\nimport type { ExtractedBlob } from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nimport { BLOBS_SUBDIR, CASSETTE_FILE } from './cassette-store.js'\n\nexport const COMMITTED_CASSETTES_DIR = 'cassettes'\nexport const COMMITTED_CORPUS_DIR = 'corpus'\nexport const COMMITTED_LABELS_DIR = 'labels'\nexport const COMMITTED_CONTRACTS_DIR = 'contracts'\nexport const COMMITTED_REPORTS_DIR = 'reports'\n/** 414 D-02: one committed file per excluded run, product-partitioned. */\nexport const COMMITTED_EXCLUSIONS_DIR = 'exclusions'\n/** 414 D-05: the file-name prefix that makes a partition manifest findable under contracts/. */\nexport const PARTITION_MANIFEST_FILE_PREFIX = 'partition-'\n/** 413 D-19: baseline pointers live one level under reports/, beside the batchKey dirs. */\nexport const COMMITTED_BASELINES_SUBDIR = 'baselines'\n/** 413 D-15: the corpus census lives one level under reports/, beside the batchKey dirs. */\nexport const COMMITTED_CENSUS_SUBDIR = 'census'\n/** 415 D-04: one floor artefact per profile, beside the baseline-pointer set. */\nexport const COMMITTED_NOISE_FLOOR_SUBDIR = 'noise-floor'\n\nexport const COMMITTED_ROOT_MARKER_FILE = 'eval-root.json'\nexport const COMMITTED_ROOT_SCHEMA_VERSION = 2\n\n/** Scaffolded ignore content: one rule covering every blobs/ dir at any depth (D-15). */\nexport const COMMITTED_GITIGNORE_TEXT =\n '# agent-qa committed eval root: binary blob bytes stay untracked (D-15/L12).\\n**/blobs/\\n'\n\nconst BLOB_SHA_RE = /^[0-9a-f]{64}$/\n\nexport interface CommittedRootStoreConfig {\n /**\n * Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the Phase 372\n * CLI. Deliberately NO default: nothing may silently resolve into a workdir (OQ-2).\n */\n committedRoot: string\n}\n\nexport type CommittedWriteOutcome =\n | { kind: 'written' }\n | { kind: 'unchanged' }\n | { kind: 'write-conflict'; path: string }\n\nexport function buildRootMarkerValue(): { schemaVersion: number } {\n return { schemaVersion: COMMITTED_ROOT_SCHEMA_VERSION }\n}\n\nfunction sluggedIdSegments(cassetteId: string): string[] {\n return cassetteId.split('/').map(segment => slugBranch(segment))\n}\n\nfunction sluggedJsonLeaf(cassetteId: string): string[] {\n const segments = sluggedIdSegments(cassetteId)\n const last = segments.pop() ?? 'default'\n return [...segments, `${last}.json`]\n}\n\nexport function committedCassettePath(product: string, cassetteId: string): string {\n return [\n COMMITTED_CASSETTES_DIR,\n slugBranch(product),\n ...sluggedIdSegments(cassetteId),\n CASSETTE_FILE,\n ].join('/')\n}\n\nexport function committedBlobPath(product: string, cassetteId: string, sha: string): string {\n return [\n COMMITTED_CASSETTES_DIR,\n slugBranch(product),\n ...sluggedIdSegments(cassetteId),\n BLOBS_SUBDIR,\n slugBranch(sha),\n ].join('/')\n}\n\nexport function committedLabelPath(product: string, cassetteId: string): string {\n return [COMMITTED_LABELS_DIR, slugBranch(product), ...sluggedJsonLeaf(cassetteId)].join('/')\n}\n\n/** Preserve validated cassette path segments; suffix only the JSON leaf, never slug the whole ID. */\nexport function committedLabelRevisionPath(product: string, cassetteId: string, revisionId: string): string {\n if (!BLOB_SHA_RE.test(revisionId) || !cassetteId.split('/').every(segment =>\n segment.length > 0 && segment !== '.' && segment !== '..' && slugBranch(segment) === segment)) {\n throw new TypeError('invalid label revision path')\n }\n return committedLabelPath(product, cassetteId).replace(/\\.json$/, `--revision-${revisionId}.json`)\n}\n\nexport function committedCorpusPath(product: string, cassetteId: string): string {\n return [COMMITTED_CORPUS_DIR, slugBranch(product), ...sluggedJsonLeaf(cassetteId)].join('/')\n}\n\nexport function committedContractPath(fileName: string): string {\n return [COMMITTED_CONTRACTS_DIR, slugBranch(fileName)].join('/')\n}\n\n/**\n * Phase 372 D-13: the baseline report commits beside the corpus/contracts that produced it —\n * one dir per batchKey, so a changed corpus (⇒ changed key) gets a fresh dir under write-once\n * while an identical regen byte-compares 'unchanged'. Every segment slugged (T-368-10).\n */\nexport function committedReportPath(batchKey: string, fileName: string): string {\n return [COMMITTED_REPORTS_DIR, slugBranch(batchKey), slugBranch(fileName)].join('/')\n}\n\n/**\n * Phase 413 D-15: the census commits one dir per CORPUS DIGEST, the reports/<batchKey>/ shape\n * applied to the population rather than to a replay batch — a grown corpus hashes to a fresh\n * digest and therefore gets a fresh dir under write-once, while re-running the census over an\n * unchanged corpus byte-compares 'unchanged' and is an idempotent no-op. Every segment slugged,\n * so a crafted digest cannot escape the committed root (T-368-10 / T-413-18).\n */\nexport function committedCensusPath(corpusDigest: string, fileName: string): string {\n return [\n COMMITTED_REPORTS_DIR,\n COMMITTED_CENSUS_SUBDIR,\n slugBranch(corpusDigest),\n slugBranch(fileName),\n ].join('/')\n}\n\n/**\n * Phase 413 D-19: baseline designation is a committed pointer, one file per profile key, so\n * moving a baseline is a reviewed git edit of that file rather than a silent overwrite. The\n * key is a single path segment and every segment is slugged (T-368-10).\n */\nexport function committedBaselinePointerPath(profileKey: string): string {\n return [COMMITTED_REPORTS_DIR, COMMITTED_BASELINES_SUBDIR, `${slugBranch(profileKey)}.json`].join(\n '/',\n )\n}\n\n/** 415 D-04: the entire profile key is one slugged segment, never a batch report dir. */\nexport function committedNoiseFloorPath(profileKey: string): string {\n return [COMMITTED_REPORTS_DIR, COMMITTED_NOISE_FLOOR_SUBDIR, `${slugBranch(profileKey)}.json`].join('/')\n}\n\n/**\n * Phase 414 D-05: one partition manifest per product, under contracts/ rather than beside the\n * entries it governs. Two reasons. (1) The recursive corpus/ walk parses every *.json it finds,\n * so a manifest under corpus/ would be handed to the corpus-entry guard and refused as a corpus\n * entry — putting it under contracts/ means the walk never sees it (T-414-20). (2) contracts/ is\n * already where this root keeps its reviewed constitution documents, and a manifest IS one: a\n * change to its salt or fractions re-partitions a committed corpus, so it lands as a reviewed git\n * edit and a named migration, never a silent rewrite. Every segment slugged (T-368-10).\n */\nexport function committedPartitionManifestPath(product: string): string {\n return committedContractPath(`${PARTITION_MANIFEST_FILE_PREFIX}${slugBranch(product)}.json`)\n}\n\n/**\n * Phase 414 D-02: one committed file per excluded run, so corpus membership becomes a function of\n * a committed list rather than a fact about whoever ran the growth campaign. 413 dropped excluded\n * runs before anything was committed and they left no trace; a record per run lets the census\n * count what never arrived and 422's curator ask why a run is missing. Every segment slugged, so a\n * crafted product or runSlug cannot escape the committed root (T-368-10 / T-414-16).\n */\nexport function committedExclusionPath(product: string, runSlug: string): string {\n return [COMMITTED_EXCLUSIONS_DIR, slugBranch(product), `${slugBranch(runSlug)}.json`].join('/')\n}\n\nfunction byteSha(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex')\n}\n\nexport class FsCommittedRootStore {\n private readonly committedRoot: string\n\n constructor(config: CommittedRootStoreConfig) {\n this.committedRoot = config.committedRoot\n }\n\n /**\n * Scaffold the committed root deterministically: the blobs-covering .gitignore plus the\n * schemaVersion root marker (D-15). Both texts arrive as ALREADY-CHECKED strings from\n * the seeding composition helper — the store never imports the guardrail. Re-scaffolding\n * an intact root yields two 'unchanged' outcomes and mutates nothing.\n */\n scaffold(\n checkedGitignoreText: string,\n checkedRootMarkerText: string,\n ): { gitignore: CommittedWriteOutcome; rootMarker: CommittedWriteOutcome } {\n return {\n gitignore: this.writeText('.gitignore', checkedGitignoreText),\n rootMarker: this.writeText(COMMITTED_ROOT_MARKER_FILE, checkedRootMarkerText),\n }\n }\n\n /** The write-once comparison WITHOUT any mkdir or write — pure read + compare. */\n previewText(relPath: string, text: string): 'absent' | 'identical' | 'conflict' {\n const file = join(this.committedRoot, relPath)\n if (!existsSync(file)) return 'absent'\n return readFileSync(file, 'utf8') === text ? 'identical' : 'conflict'\n }\n\n /** Write-once text: read-compare-refuse, never overwrite (D-17). */\n writeText(relPath: string, text: string): CommittedWriteOutcome {\n const file = join(this.committedRoot, relPath)\n if (existsSync(file)) {\n return readFileSync(file, 'utf8') === text\n ? { kind: 'unchanged' }\n : { kind: 'write-conflict', path: relPath }\n }\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, text, 'utf8')\n return { kind: 'written' }\n }\n\n /**\n * Write-once blob bytes, confined to ignore-covered blobs/ dirs. The sha must match the\n * lowercase 64-hex content-address format, the byte hash must equal it, and the target\n * path must be `.../blobs/<sha>` — any verification failure is a typed refusal, so\n * corrupt bytes never land under an untrue content address (T-371-11).\n */\n writeBlob(relBlobPath: string, blob: ExtractedBlob): CommittedWriteOutcome {\n if (!BLOB_SHA_RE.test(blob.sha)) return { kind: 'write-conflict', path: relBlobPath }\n if (byteSha(blob.bytes) !== blob.sha) return { kind: 'write-conflict', path: relBlobPath }\n if (basename(relBlobPath) !== blob.sha || basename(dirname(relBlobPath)) !== BLOBS_SUBDIR) {\n return { kind: 'write-conflict', path: relBlobPath }\n }\n const file = join(this.committedRoot, relBlobPath)\n if (existsSync(file)) {\n return readFileSync(file).equals(Buffer.from(blob.bytes))\n ? { kind: 'unchanged' }\n : { kind: 'write-conflict', path: relBlobPath }\n }\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, blob.bytes)\n return { kind: 'written' }\n }\n}\n","// Filesystem cassette bundle store (Phase 367, D-05/D-06/D-07).\n//\n// Owns the storageImplementation write leg behind eval's in-memory ExtractedCassette contract.\n// Each deterministic bundle is recreated in full before publication:\n//\n// <output-root>/<slugged cassette id segments>/\n// ├── cassette.json\n// └── blobs/<verified lowercase 64-hex sha>\n//\n// Every id segment delegates to schema's security-reviewed slugBranch sanitizer. Blob names are\n// validated and their bytes are hashed with node:crypto before path use; corrupt copy-in degrades\n// completeness loudly instead of publishing bytes under an untrue content address.\n\nimport { createHash } from 'node:crypto'\nimport { mkdirSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n guardCassette,\n type Cassette,\n type ExtractedCassette,\n type ExtractedBlob,\n} from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nexport const CASSETTE_FILE = 'cassette.json'\nexport const BLOBS_SUBDIR = 'blobs'\nexport const DEFAULT_EVAL_CASSETTES_SUBDIR = 'eval/cassettes'\n\nconst BLOB_SHA_RE = /^[0-9a-f]{64}$/\n\nexport interface FsCassetteStoreConfig {\n /** Runtime root (normally the workdir's `.agent-qa` directory). */\n root: string\n /** Optional retargeted root used by later committed-corpus composition. */\n outputDir?: string\n}\n\nexport interface WrittenCassette {\n id: string\n dir: string\n writtenBlobShas: string[]\n corruptBlobShas: string[]\n}\n\nfunction byteSha(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex')\n}\n\nfunction addUnique(values: string[], value: string): void {\n if (!values.includes(value)) values.push(value)\n}\n\nfunction withMissingBlobs(cassette: Cassette, missingShas: readonly string[]): Cassette {\n if (missingShas.length === 0) return cassette\n const combined = [...(cassette.completeness.missingBlobShas ?? [])]\n for (const sha of missingShas) addUnique(combined, sha)\n return {\n ...cassette,\n completeness: {\n ...cassette.completeness,\n status: 'evidence-incomplete',\n missingBlobShas: combined,\n },\n }\n}\n\nexport class FsCassetteStore {\n private readonly outputRoot: string\n\n constructor(config: FsCassetteStoreConfig) {\n this.outputRoot = config.outputDir ?? join(config.root, DEFAULT_EVAL_CASSETTES_SUBDIR)\n }\n\n write(extracted: ExtractedCassette): WrittenCassette {\n const sourceCassette = guardCassette(extracted.cassette)\n const dir = join(\n this.outputRoot,\n ...sourceCassette.id.split('/').map(segment => slugBranch(segment)),\n )\n rmSync(dir, { recursive: true, force: true })\n mkdirSync(dir, { recursive: true })\n\n const verifiedBlobs: ExtractedBlob[] = []\n const writtenBlobShas: string[] = []\n const corruptBlobShas: string[] = []\n const copyInMissingShas: string[] = []\n\n for (const blob of extracted.blobs) {\n if (!BLOB_SHA_RE.test(blob.sha)) {\n addUnique(corruptBlobShas, blob.sha)\n continue\n }\n if (byteSha(blob.bytes) !== blob.sha) {\n addUnique(corruptBlobShas, blob.sha)\n addUnique(copyInMissingShas, blob.sha)\n continue\n }\n if (!writtenBlobShas.includes(blob.sha)) {\n verifiedBlobs.push(blob)\n writtenBlobShas.push(blob.sha)\n }\n }\n\n if (verifiedBlobs.length > 0) {\n const blobsDir = join(dir, BLOBS_SUBDIR)\n mkdirSync(blobsDir, { recursive: true })\n for (const blob of verifiedBlobs) writeFileSync(join(blobsDir, blob.sha), blob.bytes)\n }\n\n const cassette = guardCassette(withMissingBlobs(sourceCassette, copyInMissingShas))\n writeFileSync(join(dir, CASSETTE_FILE), `${JSON.stringify(cassette, null, 2)}\\n`, 'utf8')\n\n return {\n id: cassette.id,\n dir,\n writtenBlobShas,\n corruptBlobShas,\n }\n }\n}\n","/**\n * The proposer's ONLY read over the committed corpus (414 D-18 / D-19 / D-20, ROOT-10).\n *\n * The corpus is a train / validation / test partition. `natural` is the optimise set the\n * proposer may read and learn from; held-out `shared` is a VISIBLE validation set — readable,\n * still gated on; held-out `private` is the unseen test set. A measurement the thing being\n * measured can read is not a measurement, so the private arm is unreachable from here: not\n * listable, not loadable, not countable.\n *\n * Existence non-leak (D-19, the anti-pattern this module exists to make impossible): a private\n * cassetteId answers with the SAME `{ kind: 'not-found' }` an id that was never committed gets.\n * There is deliberately no `not-visible` arm — an arm that distinguishes the two tells the\n * proposer the id exists, which is the whole of what the private set withholds. For the same\n * reason there is no count method, no `listProducts`, and no visibility parameter: each of those\n * is a channel through which the size or the shape of the unseen set could be inferred.\n *\n * Refusals and notices from the underlying read are NOT exposed. A refused committed file is an\n * operator's problem, not the proposer's, and the paths it names are root-shaped information.\n *\n * Composition law (eval-local's ownership contract): this module reads and FILTERS. The\n * visibility predicate itself (`isProposerVisibleEntry`) lives in eval core beside the type it\n * narrows, so the filter here and the never-bar in `__tests__/reader.test-d.ts` are talking\n * about one definition rather than two that could drift.\n *\n * D-18 declined a physically separate private root, so the pin is at the PORT and at the TYPE:\n * `packages/eval-local/src/reader.ts` publishes exactly this function, `validate:arch` holds\n * every non-cli importer to that subpath, and three cells RED if a private-returning export or\n * method is added.\n */\n\nimport { isProposerVisibleEntry } from '@vostride/agent-qa-eval'\nimport type {\n LeafCassette,\n ProposerVisibleCorpusEntry,\n StandaloneLabelRecord,\n} from '@vostride/agent-qa-eval'\n\nimport { readCommittedCorpus } from './committed-corpus-source.js'\n\nexport type { ProposerVisibleCorpusEntry } from '@vostride/agent-qa-eval'\n\n/**\n * The two-arm answer every load gives. `not-found` is TOTAL: it covers an id that does not\n * exist, an id whose bytes are unreadable, and an id the proposer may not see — deliberately\n * indistinguishable (D-19).\n */\nexport type CorpusReaderLoad<TLoaded> = ({ kind: 'loaded' } & TLoaded) | { kind: 'not-found' }\n\n/** A visible entry's cassette bundle, or nothing. */\nexport type CorpusCassetteLoad = CorpusReaderLoad<{ cassette: LeafCassette }>\n\n/** A visible entry's standalone label record, or nothing. */\nexport type CorpusLabelLoad = CorpusReaderLoad<{ record: StandaloneLabelRecord }>\n\n/**\n * The port. EXACTLY three methods — every addition is a widening of what a proposer may learn\n * about the measurement it is being scored against, so the set is pinned by name in three places.\n */\nexport interface CorpusReader {\n /** Every proposer-visible entry, cassetteId ascending; optionally one product's slice. */\n listEntries(product?: string): readonly ProposerVisibleCorpusEntry[]\n /** The cassette bundle for a VISIBLE entry; `not-found` for anything else. */\n loadCassette(cassetteId: string): CorpusCassetteLoad\n /** The label record for a VISIBLE entry; `not-found` for anything else. */\n loadLabel(cassetteId: string): CorpusLabelLoad\n}\n\ninterface VisibleSlice {\n visible: readonly ProposerVisibleCorpusEntry[]\n visibleIds: ReadonlySet<string>\n cassettesById: ReadonlyMap<string, LeafCassette>\n labelsById: ReadonlyMap<string, StandaloneLabelRecord>\n}\n\n/**\n * Open a read port over the committed root at `committedRoot`.\n *\n * The root is read ONCE, lazily on first use, and the visible slice is kept: a port whose answers\n * changed mid-session would let a proposer watch the corpus move. An absent or unreadable root is\n * an empty port — `listEntries()` is `[]` and every load is `not-found` — never a throw, matching\n * the read leg's own posture for a hand-editable, git-tracked document.\n */\nexport function openCorpusReader(committedRoot: string): CorpusReader {\n let slice: VisibleSlice | undefined\n\n function load(): VisibleSlice {\n if (slice === undefined) {\n const read = readCommittedCorpus(committedRoot)\n const visible = read.snapshot.entries.filter((entry): entry is ProposerVisibleCorpusEntry =>\n isProposerVisibleEntry(entry),\n )\n slice = {\n visible,\n visibleIds: new Set(visible.map((entry) => entry.cassetteId)),\n cassettesById: read.snapshot.cassettesById,\n labelsById: read.snapshot.labelsById,\n }\n }\n return slice\n }\n\n return {\n listEntries(product?: string): readonly ProposerVisibleCorpusEntry[] {\n const { visible } = load()\n if (product === undefined) return visible\n return visible.filter((entry) => entry.product === product)\n },\n\n loadCassette(cassetteId: string): CorpusCassetteLoad {\n const { visibleIds, cassettesById } = load()\n if (!visibleIds.has(cassetteId)) return { kind: 'not-found' }\n const cassette = cassettesById.get(cassetteId)\n if (cassette === undefined) return { kind: 'not-found' }\n return { kind: 'loaded', cassette }\n },\n\n loadLabel(cassetteId: string): CorpusLabelLoad {\n const { visibleIds, labelsById } = load()\n if (!visibleIds.has(cassetteId)) return { kind: 'not-found' }\n const record = labelsById.get(cassetteId)\n if (record === undefined) return { kind: 'not-found' }\n return { kind: 'loaded', record }\n },\n }\n}\n","// The committed-root READ leg (413 D-14/D-08, RESEARCH F6) — the inverse of seedCommittedCorpus.\n//\n// Composition law (the eval-local ownership rule): every eval filesystem read lives here and the\n// derivation lives in eval core. This module loads corpus entries, label records, cassette\n// bundles and local blob presence off disk and hands eval core the CommittedCorpusSnapshot its\n// pure census folds. It computes nothing.\n//\n// Refusal posture (mirrors cassette-loader.ts): a committed root is a cross-machine,\n// hand-editable, git-tracked document, so NO content failure throws. An unreadable file,\n// unparseable JSON, or a guard rejection becomes a typed refusal row and the surrounding read\n// survives; an absent root is an empty snapshot with a notice, never an error. Blob presence is\n// reported rather than required — `**/blobs/` is gitignored, so a freshly cloned root legitimately\n// carries zero blobs (F6) and the census prints `blobs present locally: n/N`.\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport type { Dirent } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n activeMarkedCorpusEntries,\n BASELINE_POINTER_SCHEMA_VERSION,\n guardDecisionVectorsDocument,\n guardNoiseFloorArtefact,\n parseCorpusEntry,\n parseStandaloneLabelRecord,\n selectEffectiveLabels,\n partitionManifestSchema,\n runExclusionRecordSchema,\n} from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\nimport type {\n CommittedCorpusSnapshot,\n CorpusEntry,\n DecisionVectorsDocument,\n EvalBatchReport,\n LeafCassette,\n NoiseFloorArtefact,\n PartitionManifest,\n RunExclusionRecord,\n StandaloneLabelRecord,\n} from '@vostride/agent-qa-eval'\nimport { z } from 'zod'\n\nimport { loadCassetteBundle } from './cassette-loader.js'\nimport { BLOBS_SUBDIR } from './cassette-store.js'\nimport {\n COMMITTED_CASSETTES_DIR,\n COMMITTED_CONTRACTS_DIR,\n COMMITTED_CORPUS_DIR,\n COMMITTED_EXCLUSIONS_DIR,\n COMMITTED_LABELS_DIR,\n COMMITTED_NOISE_FLOOR_SUBDIR,\n COMMITTED_REPORTS_DIR,\n PARTITION_MANIFEST_FILE_PREFIX,\n committedPartitionManifestPath,\n committedLabelPath,\n committedReportPath,\n} from './committed-root-store.js'\nimport { listCassetteBundleDirs } from './replay-read.js'\nimport { FsMarkLedger } from './mark-ledger.js'\nimport { readLabelCalibration, type LabelCalibrationRead } from './calibration-source.js'\nimport { reportMetadataKind } from './report-metadata-guard.js'\nimport { reportJudgeSchema } from './report-store.js'\n\n/** Gate-side effective view; raw committed history and the proposer reader remain unchanged. */\nexport function readActiveCommittedCorpus(committedRoot: string, agentQaRoot: string, calibrationRead?: LabelCalibrationRead): CommittedCorpusRead {\n const read = readCommittedCorpus(committedRoot, calibrationRead)\n const runs = new Set([...read.snapshot.labelsById.values()].filter(label =>\n label.provenance.sourceCassetteId !== undefined).map(label => label.provenance.runId))\n const marks = []\n const refusals = [...read.refusals]\n for (const runId of runs) {\n try { marks.push(...new FsMarkLedger({ root: agentQaRoot, runId }).latestPerAddress()) }\n catch { refusals.push({ path: agentQaRoot, reason: 'mark ledger unreadable; active gold unavailable' }) }\n }\n const entries = activeMarkedCorpusEntries(read.snapshot, marks)\n const activeIds = new Set(entries.map(entry => entry.cassetteId))\n return { ...read, refusals, snapshot: { ...read.snapshot, entries },\n retiredMarkedCassetteIds: new Set(read.snapshot.entries.filter(entry => !activeIds.has(entry.cassetteId)).map(entry => entry.cassetteId)),\n notices: [...read.notices, ...(entries.length === read.snapshot.entries.length ? []\n : [`${read.snapshot.entries.length - entries.length} historical or incomplete marked cases excluded`])] }\n}\n\n/** Census, baseline pointers and per-profile floors are not batch reports (415 D-04). */\nconst RESERVED_REPORT_DIRS = new Set(['census', 'baselines', 'noise-floor', 'judge-calibration'])\n\nconst reportSchema = z\n .object({\n batchKey: z.string(),\n matcherVersion: z.number(),\n judgeIdentity: z.literal('mixed').optional(),\n mixedJudgeModelIds: z.array(z.string()).optional(),\n headline: z\n .object({ perDecisionCost: z.object({ decisionCount: z.number() }).passthrough() })\n .passthrough(),\n honesty: z\n .object({\n unscorableIdentityCounts: z.record(z.string(), z.number()),\n refusalCounts: z.record(z.string(), z.number()),\n })\n .passthrough(),\n judge: reportJudgeSchema.optional(),\n })\n .passthrough().refine(report => report.judgeIdentity !== 'mixed' || report.judge === undefined)\n\nconst baselinePointerSchema = z\n .object({\n schemaVersion: z.literal(BASELINE_POINTER_SCHEMA_VERSION),\n profileKey: z.string(),\n batchKey: z.string(),\n fingerprint: z.string(),\n corpusDigest: z.string(),\n })\n .passthrough()\n\n/** One unreadable or unadmittable committed file, attributable by path (D-08). */\nexport interface CommittedReadRefusal {\n path: string\n reason: string\n}\n\n/** The loaded committed root: eval core's snapshot plus everything the read learned about it. */\nexport interface CommittedCorpusRead {\n /** Guarded ownership including scoring-excluded history, for incurred-cost reports. */\n corpusEntriesById?: ReadonlyMap<string, CorpusEntry>\n calibration?: EvalBatchReport['calibration']\n retiredMarkedCassetteIds?: ReadonlySet<string>\n snapshot: CommittedCorpusSnapshot\n productsSeen: readonly string[]\n notices: string[]\n refusals: readonly CommittedReadRefusal[]\n /**\n * How many committed files declared each schemaVersion, keyed by the declared version as a\n * string. An absent version key means zero files declared it.\n */\n schemaVersionsSeen: Record<string, number>\n}\n\n/** Every committed partition manifest under contracts/, and what the read refused (D-05). */\nexport interface PartitionManifestRead {\n manifests: readonly PartitionManifest[]\n notices: string[]\n refusals: readonly CommittedReadRefusal[]\n}\n\n/** Every committed run-exclusion record under exclusions/, and what the read refused (D-02). */\nexport interface RunExclusionRead {\n exclusions: readonly RunExclusionRecord[]\n refusals: readonly CommittedReadRefusal[]\n}\n\n/** One committed batch report keyed by its own dir name. */\nexport interface CommittedReportEntry {\n batchKey: string\n report: EvalBatchReport\n path: string\n}\n\n/** One committed per-profile baseline designation (D-19). */\nexport interface BaselinePointerEntry {\n schemaVersion: typeof BASELINE_POINTER_SCHEMA_VERSION\n profileKey: string\n batchKey: string\n fingerprint: string\n corpusDigest: string\n path: string\n}\n\nexport interface NoiseFloorArtefactEntry {\n profileKey: string\n artefact: NoiseFloorArtefact\n path: string\n}\n\nexport type CommittedDecisionVectorsLoad =\n | { kind: 'loaded'; document: DecisionVectorsDocument; path: string }\n | { kind: 'absent'; path: string }\n | { kind: 'refused'; refusal: CommittedReadRefusal }\n\nexport type ResolveMinimumGateSetOutcome =\n | { kind: 'resolved'; minimumGateSet: number; path: string }\n | { kind: 'no-floor' }\n | { kind: 'no-value'; path: string }\n\n/** Read only the per-profile files; the former literal reports/noise-floor.json is invalid. */\nexport function listNoiseFloorArtefacts(committedRoot: string): {\n artefacts: NoiseFloorArtefactEntry[]\n refusals: CommittedReadRefusal[]\n} {\n const reportsRoot = join(committedRoot, COMMITTED_REPORTS_DIR)\n const floorRoot = join(reportsRoot, COMMITTED_NOISE_FLOOR_SUBDIR)\n const artefacts: NoiseFloorArtefactEntry[] = []\n const refusals: CommittedReadRefusal[] = []\n const strayPath = join(reportsRoot, 'noise-floor.json')\n if (existsSync(strayPath)) {\n refusals.push({ path: strayPath, reason: 'noise floor must live under reports/noise-floor/<profile-key>.json' })\n }\n let entries: Dirent[]\n try {\n entries = readdirSync(floorRoot, { withFileTypes: true })\n } catch {\n return { artefacts, refusals }\n }\n for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {\n if (!entry.isFile() || !entry.name.endsWith('.json')) continue\n const path = join(floorRoot, entry.name)\n const read = readJson(path)\n if (!read.ok) {\n refusals.push({ path, reason: read.reason })\n continue\n }\n const guarded = guardNoiseFloorArtefact(read.value)\n if (guarded.kind === 'rejected') {\n refusals.push({ path, reason: `noise floor rejected: ${guarded.reason}` })\n continue\n }\n artefacts.push({ profileKey: guarded.artefact.profileKey, artefact: guarded.artefact, path })\n }\n artefacts.sort((a, b) => a.profileKey < b.profileKey ? -1 : a.profileKey > b.profileKey ? 1 : 0)\n return { artefacts, refusals }\n}\n\nexport function readCommittedDecisionVectors(\n committedRoot: string,\n batchKey: string,\n): CommittedDecisionVectorsLoad {\n const path = join(committedRoot, committedReportPath(batchKey, 'decisions.json'))\n if (!existsSync(path)) return { kind: 'absent', path }\n const read = readJson(path)\n if (!read.ok) return { kind: 'refused', refusal: { path, reason: read.reason } }\n const guarded = guardDecisionVectorsDocument(read.value)\n if (guarded.kind === 'rejected') {\n return { kind: 'refused', refusal: { path, reason: `decisions rejected: ${guarded.reason}` } }\n }\n if (guarded.document.batchKey !== batchKey) {\n return { kind: 'refused', refusal: { path, reason: 'decisions batchKey does not match the requested batchKey' } }\n }\n return { kind: 'loaded', document: guarded.document, path }\n}\n\n/** 414 D-15 → 417 handoff: resolve the measured integer without changing the pure posture port. */\nexport function resolveMinimumGateSet(input: {\n committedRoot: string\n profileKey: string\n}): ResolveMinimumGateSetOutcome {\n const entry = listNoiseFloorArtefacts(input.committedRoot).artefacts.find(\n candidate => candidate.profileKey === input.profileKey,\n )\n if (entry === undefined) return { kind: 'no-floor' }\n const minimumGateSet = entry.artefact.minimumGateSet.value\n if (minimumGateSet === undefined) return { kind: 'no-value', path: entry.path }\n return { kind: 'resolved', minimumGateSet, path: entry.path }\n}\n\nfunction listDirNames(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort()\n } catch {\n return []\n }\n}\n\n/** Every `*.json` file under dir at any depth, sorted; ENOENT is an empty list. */\nfunction listJsonFiles(dir: string): string[] {\n const found: string[] = []\n\n function walk(current: string): void {\n let entries: Dirent[]\n try {\n entries = readdirSync(current, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n const path = join(current, entry.name)\n if (entry.isDirectory()) walk(path)\n else if (entry.isFile() && entry.name.endsWith('.json')) found.push(path)\n }\n }\n\n walk(dir)\n return found.sort()\n}\n\nfunction readJson(path: string): { ok: true; value: unknown } | { ok: false; reason: string } {\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (error) {\n return { ok: false, reason: `unreadable: ${(error as NodeJS.ErrnoException).message}` }\n }\n try {\n return { ok: true, value: JSON.parse(raw) }\n } catch (error) {\n return { ok: false, reason: `invalid JSON: ${(error as Error).message}` }\n }\n}\n\nfunction issueText(error: z.ZodError): string {\n return error.issues\n .map(\n (issue) => `${issue.path.length === 0 ? '<root>' : issue.path.join('.')}: ${issue.message}`,\n )\n .join('; ')\n}\n\n/** Every `*.json` file directly under dir (no recursion), sorted; ENOENT is an empty list. */\nfunction listJsonFilesShallow(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))\n .map((entry) => entry.name)\n .sort()\n } catch {\n return []\n }\n}\n\nfunction bumpCounter(counter: Record<string, number>, key: string): void {\n counter[key] = (counter[key] ?? 0) + 1\n}\n\n/** A blobs/ dir counts as present only when it exists AND holds at least one file (F6). */\nfunction blobsPresent(bundleDir: string): boolean {\n const blobsDir = join(bundleDir, BLOBS_SUBDIR)\n if (!existsSync(blobsDir)) return false\n try {\n return readdirSync(blobsDir).length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Load the committed root at `committedRoot` into the snapshot eval core's `deriveCensus` folds.\n * Never throws for content: every parse or guard failure lands in `refusals`, and a missing root\n * yields an empty snapshot with a notice naming it.\n */\nexport function readCommittedCorpus(committedRoot: string, calibrationRead?: LabelCalibrationRead): CommittedCorpusRead {\n const notices: string[] = []\n const refusals: CommittedReadRefusal[] = []\n const entries: CorpusEntry[] = []\n const schemaVersionsSeen: Record<string, number> = {}\n const labelsById = new Map<string, StandaloneLabelRecord>()\n const labelHistory: unknown[] = []\n const excludedLabelIds = new Set<string>()\n const cassettesById = new Map<string, LeafCassette>()\n const blobPresentById = new Map<string, boolean>()\n\n if (!existsSync(committedRoot)) {\n notices.push(`committed root absent: ${committedRoot}`)\n return {\n snapshot: { entries, labelsById, cassettesById, blobPresentById, labelHistory, excludedLabelIds },\n productsSeen: [],\n notices,\n refusals,\n schemaVersionsSeen,\n }\n }\n\n const corpusRoot = join(committedRoot, COMMITTED_CORPUS_DIR)\n const productsSeen = listDirNames(corpusRoot)\n\n for (const product of productsSeen) {\n for (const path of listJsonFiles(join(corpusRoot, product))) {\n const read = readJson(path)\n if (!read.ok) {\n refusals.push({ path, reason: read.reason })\n continue\n }\n // The one guard in eval core, not a second zod shape here.\n const parsed = parseCorpusEntry(read.value)\n if (!parsed.ok) {\n refusals.push({ path, reason: `corpus entry rejected: ${parsed.issues}` })\n continue\n }\n if (parsed.entry.product !== product) {\n notices.push(\n `corpus dir '${product}' holds an entry declaring product '${parsed.entry.product}' (${parsed.entry.cassetteId}); the entry field is authoritative`,\n )\n }\n entries.push(parsed.entry)\n bumpCounter(schemaVersionsSeen, String(parsed.schemaVersion))\n }\n }\n\n const labelsRoot = join(committedRoot, COMMITTED_LABELS_DIR)\n const labelOwners = new Map<string, Set<string>>()\n const idsByBasePath = new Map<string, Set<string>>()\n for (const entry of entries) {\n const owners = labelOwners.get(entry.cassetteId) ?? new Set<string>()\n owners.add(slugBranch(entry.product))\n labelOwners.set(entry.cassetteId, owners)\n const path = join(committedRoot, committedLabelPath(entry.product, entry.cassetteId))\n const ids = idsByBasePath.get(path) ?? new Set<string>()\n ids.add(entry.cassetteId)\n idsByBasePath.set(path, ids)\n }\n const readInvalidIds = new Set<string>()\n const validHistory: StandaloneLabelRecord[] = []\n for (const product of listDirNames(labelsRoot)) {\n for (const path of listJsonFiles(join(labelsRoot, product))) {\n const basePath = path.replace(/--revision-[^/]*\\.json$/, '.json')\n const pathIds = idsByBasePath.get(basePath) ?? new Set<string>()\n const refuse = (reason: string, cassetteId?: string) => {\n refusals.push({ path, reason })\n for (const id of pathIds) readInvalidIds.add(id)\n if (cassetteId !== undefined) readInvalidIds.add(cassetteId)\n }\n const read = readJson(path)\n if (!read.ok) {\n refuse('label record unreadable or invalid JSON')\n continue\n }\n labelHistory.push(read.value)\n const parsed = parseStandaloneLabelRecord(read.value)\n if (!parsed.ok) {\n const claimedId = typeof read.value === 'object' && read.value !== null && 'cassetteId' in read.value && typeof read.value.cassetteId === 'string' ? read.value.cassetteId : undefined\n refuse(`label record rejected: ${parsed.issues}`, claimedId)\n continue\n }\n const record = parsed.record\n const expectedBase = join(committedRoot, committedLabelPath(product, record.cassetteId))\n const expectedPath = record.revision === undefined ? expectedBase\n : expectedBase.replace(/\\.json$/, `--revision-${record.revision.id}.json`)\n const owners = labelOwners.get(record.cassetteId)\n if (path !== expectedPath || (owners !== undefined && (owners.size !== 1 || !owners.has(product)))) {\n refuse('label path or product ownership mismatch', record.cassetteId)\n continue\n }\n validHistory.push(record)\n }\n }\n // Generation-bearing refreshes stay invisible until the guarded publication loader\n // explicitly authorizes their marker. Seed/base revisions require no marker.\n const calibration = calibrationRead ?? readLabelCalibration(committedRoot)\n const authorized = calibration.kind === 'loaded' ? calibration.authorizedRevisionIds : new Set<string>()\n const eligibleHistory = validHistory.filter(record => record.revision?.generationId === undefined || authorized.has(record.revision.id))\n const generations = new Set(eligibleHistory.flatMap(record => record.revision?.generationId ? [record.revision.generationId] : []))\n if (calibration.kind === 'refused') {\n refusals.push({ path: join(labelsRoot, 'calibration.json'), reason: calibration.reason })\n for (const id of calibration.targetCassetteIds ?? []) readInvalidIds.add(id)\n for (const record of validHistory) if (record.revision?.generationId) readInvalidIds.add(record.cassetteId)\n }\n const selected = selectEffectiveLabels(eligibleHistory, { committedGenerationIds: generations })\n for (const [id, label] of selected.effective) {\n if (!readInvalidIds.has(id)) labelsById.set(id, label)\n }\n for (const id of [...readInvalidIds, ...selected.excludedLabelIds]) excludedLabelIds.add(id)\n for (const refusal of selected.refusals) {\n refusals.push({ path: labelsRoot, reason: `label history rejected: ${refusal.reason}` })\n }\n\n for (const bundleDir of listCassetteBundleDirs(join(committedRoot, COMMITTED_CASSETTES_DIR))) {\n const load = loadCassetteBundle(bundleDir)\n if (load.kind === 'refused') {\n refusals.push({\n path: join(bundleDir, 'cassette.json'),\n reason: `${load.refusal.reason}: ${load.refusal.detail}`,\n })\n continue\n }\n if (load.cassette.granularity !== 'leaf') {\n notices.push(`skipped non-leaf cassette bundle: ${bundleDir}`)\n continue\n }\n cassettesById.set(load.cassette.id, load.cassette)\n blobPresentById.set(load.cassette.id, blobsPresent(bundleDir))\n }\n\n entries.sort((first, second) =>\n first.cassetteId < second.cassetteId ? -1 : first.cassetteId > second.cassetteId ? 1 : 0,\n )\n\n return {\n corpusEntriesById: new Map(entries.map(entry => [entry.cassetteId, entry])),\n calibration: calibration.kind === 'loaded' ? {\n status: calibration.artifact.channels['recorded-verdict'].status,\n n_gold: calibration.artifact.channels['recorded-verdict'].n_gold,\n verifierFalsePassRate: calibration.artifact.verifierFalsePassRate,\n } : { status: 'uncalibrated' },\n snapshot: { entries: entries.filter(entry => !excludedLabelIds.has(entry.cassetteId)),\n labelsById, cassettesById, blobPresentById, labelHistory, excludedLabelIds },\n productsSeen,\n notices,\n refusals,\n schemaVersionsSeen,\n }\n}\n\n/**\n * Load every committed partition manifest under `contracts/` (414 D-05).\n *\n * Manifests are found by file-name prefix, not by parsing every contract: the dir also holds the\n * D-04 matcher and judge constitution projections, and asking the manifest guard about those would\n * manufacture refusals for documents that are not manifests. An absent `contracts/` is an empty\n * list with no refusal — a root that has never been partitioned is a legitimate root.\n */\nexport function readPartitionManifests(committedRoot: string): PartitionManifestRead {\n const contractsRoot = join(committedRoot, COMMITTED_CONTRACTS_DIR)\n const manifests: PartitionManifest[] = []\n const notices: string[] = []\n const refusals: CommittedReadRefusal[] = []\n\n for (const name of listJsonFilesShallow(contractsRoot)) {\n if (!name.startsWith(PARTITION_MANIFEST_FILE_PREFIX)) continue\n const path = join(contractsRoot, name)\n const read = readJson(path)\n if (!read.ok) {\n refusals.push({ path, reason: read.reason })\n continue\n }\n const parsed = partitionManifestSchema.safeParse(read.value)\n if (!parsed.success) {\n refusals.push({ path, reason: `partition manifest rejected: ${issueText(parsed.error)}` })\n continue\n }\n const expected = committedPartitionManifestPath(parsed.data.product)\n if (expected !== `${COMMITTED_CONTRACTS_DIR}/${name}`) {\n notices.push(\n `partition manifest '${name}' declares product '${parsed.data.product}', whose committed path is '${expected}'; the manifest field is authoritative`,\n )\n }\n manifests.push(parsed.data)\n }\n\n manifests.sort((first, second) =>\n first.product < second.product ? -1 : first.product > second.product ? 1 : 0,\n )\n return { manifests, notices, refusals }\n}\n\n/**\n * Load every committed run-exclusion record under `exclusions/<product>/` (414 D-02).\n *\n * Same posture as the corpus walk: a committed root is hand-editable, so an unparseable or\n * unadmittable record is a refusal row naming its path, never a throw. An absent `exclusions/`\n * dir is an empty list with no refusal — a root with nothing excluded is the common case.\n */\nexport function readRunExclusions(committedRoot: string): RunExclusionRead {\n const exclusionsRoot = join(committedRoot, COMMITTED_EXCLUSIONS_DIR)\n const exclusions: RunExclusionRecord[] = []\n const refusals: CommittedReadRefusal[] = []\n\n for (const product of listDirNames(exclusionsRoot)) {\n for (const path of listJsonFiles(join(exclusionsRoot, product))) {\n const read = readJson(path)\n if (!read.ok) {\n refusals.push({ path, reason: read.reason })\n continue\n }\n const parsed = runExclusionRecordSchema.safeParse(read.value)\n if (!parsed.success) {\n refusals.push({ path, reason: `run exclusion rejected: ${issueText(parsed.error)}` })\n continue\n }\n exclusions.push(parsed.data)\n }\n }\n\n return { exclusions, refusals }\n}\n\n/**\n * List every committed batch report under `reports/`, one per batchKey dir. The reserved `census/`\n * and `baselines/`, `noise-floor/`, `judge-calibration/` dirs are not batch reports.\n */\nexport function listCommittedReports(committedRoot: string): {\n reports: CommittedReportEntry[]\n refusals: CommittedReadRefusal[]\n} {\n const reportsRoot = join(committedRoot, COMMITTED_REPORTS_DIR)\n const reports: CommittedReportEntry[] = []\n const refusals: CommittedReadRefusal[] = []\n\n for (const name of listDirNames(reportsRoot)) {\n if (RESERVED_REPORT_DIRS.has(name)) continue\n const path = join(reportsRoot, name, 'report.json')\n if (!existsSync(path)) {\n refusals.push({ path, reason: 'report.json absent' })\n continue\n }\n const read = readJson(path)\n if (!read.ok) {\n refusals.push({ path, reason: read.reason })\n continue\n }\n const parsed = reportSchema.safeParse(read.value)\n if (!parsed.success) {\n refusals.push({ path, reason: `report rejected: ${issueText(parsed.error)}` })\n continue\n }\n if (reportMetadataKind(read.value) === 'invalid') {\n refusals.push({ path, reason: 'report label metadata incomplete or malformed' })\n continue\n }\n reports.push({ batchKey: name, report: parsed.data as unknown as EvalBatchReport, path })\n }\n\n reports.sort((first, second) =>\n first.batchKey < second.batchKey ? -1 : first.batchKey > second.batchKey ? 1 : 0,\n )\n return { reports, refusals }\n}\n\n/** List every committed per-profile baseline pointer under `reports/baselines/`, sorted (D-19). */\nexport function listBaselinePointers(committedRoot: string): {\n pointers: BaselinePointerEntry[]\n refusals: CommittedReadRefusal[]\n} {\n const baselinesRoot = join(committedRoot, COMMITTED_REPORTS_DIR, 'baselines')\n const pointers: BaselinePointerEntry[] = []\n const refusals: CommittedReadRefusal[] = []\n\n let names: string[]\n try {\n names = readdirSync(baselinesRoot).sort()\n } catch {\n return { pointers, refusals }\n }\n\n for (const name of names) {\n if (!name.endsWith('.json')) continue\n const path = join(baselinesRoot, name)\n if (!statSync(path).isFile()) continue\n const read = readJson(path)\n if (!read.ok) {\n refusals.push({ path, reason: read.reason })\n continue\n }\n const parsed = baselinePointerSchema.safeParse(read.value)\n if (!parsed.success) {\n refusals.push({ path, reason: `baseline pointer rejected: ${issueText(parsed.error)}` })\n continue\n }\n pointers.push({\n schemaVersion: parsed.data.schemaVersion,\n profileKey: parsed.data.profileKey,\n batchKey: parsed.data.batchKey,\n fingerprint: parsed.data.fingerprint,\n corpusDigest: parsed.data.corpusDigest,\n path,\n })\n }\n\n pointers.sort((first, second) =>\n first.profileKey < second.profileKey ? -1 : first.profileKey > second.profileKey ? 1 : 0,\n )\n return { pointers, refusals }\n}\n","// Filesystem cassette bundle loader (Phase 368, D-08 / RPLY-02).\n//\n// Inverts FsCassetteStore's write leg: reads `cassette.json`, version-gates + structurally validates\n// it through guardCassette (the V5 input-validation control), and binds a DirArtifactSource over the\n// bundle's `blobs/` directory. A cassette bundle is an untrusted, hand-editable, cross-machine\n// document, so every failure — an unreadable/missing file, unparseable JSON, or a guard rejection —\n// becomes a typed ReplayRefusal instead of a throw. The cassette is never partially loaded and never\n// replayed on refusal; the refusal surfaces in reports and the surrounding batch always survives.\n\nimport { readFileSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nimport {\n guardCassette,\n type ArtifactSource,\n type Cassette,\n type ReplayRefusal,\n} from '@vostride/agent-qa-eval'\n\nimport { DirArtifactSource } from './artifact-source.js'\nimport { BLOBS_SUBDIR, CASSETTE_FILE } from './cassette-store.js'\n\n/** The discriminated bundle-load outcome: a guarded cassette + its blob source, or a typed refusal. */\nexport type CassetteBundleLoad =\n | { kind: 'loaded'; cassette: Cassette; artifacts: ArtifactSource }\n | { kind: 'refused'; refusal: ReplayRefusal }\n\nfunction refused(\n cassetteId: string,\n reason: ReplayRefusal['reason'],\n detail: string,\n): CassetteBundleLoad {\n return { kind: 'refused', refusal: { kind: 'integrity-refusal', cassetteId, reason, detail } }\n}\n\n// Recover the recorded id from a parsed-but-rejected document so the refusal is attributable; falls\n// back to the bundle directory basename when the id is unrecoverable (unparseable / absent / non-string).\nfunction recoverCassetteId(document: unknown, fallback: string): string {\n if (typeof document === 'object' && document !== null) {\n const id = (document as Record<string, unknown>).id\n if (typeof id === 'string' && id.length > 0) return id\n }\n return fallback\n}\n\n/**\n * Load a cassette bundle directory into a guarded Cassette + DirArtifactSource over its blobs.\n * Never throws for a malformed bundle — read/parse failures map to a 'parse-failed' refusal and\n * guard rejections (version or structural) map to 'guard-failed', each carrying the underlying\n * message in `detail` (D-08).\n */\nexport function loadCassetteBundle(bundleDir: string): CassetteBundleLoad {\n const fallbackId = basename(bundleDir)\n const cassettePath = join(bundleDir, CASSETTE_FILE)\n\n let raw: string\n try {\n raw = readFileSync(cassettePath, 'utf8')\n } catch (error) {\n return refused(\n fallbackId,\n 'parse-failed',\n `Failed to read ${cassettePath}: ${(error as NodeJS.ErrnoException).message}`,\n )\n }\n\n let document: unknown\n try {\n document = JSON.parse(raw)\n } catch (error) {\n return refused(\n fallbackId,\n 'parse-failed',\n `Invalid cassette JSON at ${cassettePath}: ${(error as Error).message}`,\n )\n }\n\n let cassette: Cassette\n try {\n cassette = guardCassette(document)\n } catch (error) {\n return refused(recoverCassetteId(document, fallbackId), 'guard-failed', (error as Error).message)\n }\n\n const artifacts = new DirArtifactSource({ dir: join(bundleDir, BLOBS_SUBDIR) })\n return { kind: 'loaded', cassette, artifacts }\n}\n","// Filesystem artifact-source implementations for eval extraction (Phase 367, D-02 / Open Q1a).\n//\n// No run directory currently owns a sha-keyed blob store. `absentArtifactSource` states that fact\n// honestly so a present-but-unservable reference becomes evidence-incomplete downstream. The\n// directory-backed implementation is the real copy-in seam for tests and future callers:\n//\n// <dir>/<lowercase 64-hex sha>\n//\n// The sha is validated before any path or filesystem use. A future runner-local blob write leg can\n// bind the same eval port without changing pure extraction logic.\n\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { ArtifactSource } from '@vostride/agent-qa-eval'\nimport { FsEvidenceArtifactStore } from '@vostride/agent-qa-runner-local'\n\nconst BLOB_SHA_RE = /^[0-9a-f]{64}$/\n\nexport const absentArtifactSource: ArtifactSource = {\n getBlob: () => undefined,\n}\n\nexport interface DirArtifactSourceConfig {\n /** Directory containing one file per lowercase 64-hex content sha. */\n dir: string\n}\n\nexport class DirArtifactSource implements ArtifactSource {\n private readonly dir: string\n\n constructor(config: DirArtifactSourceConfig) {\n this.dir = config.dir\n }\n\n getBlob(sha: string): Uint8Array | undefined {\n if (!BLOB_SHA_RE.test(sha)) return undefined\n\n try {\n return new Uint8Array(readFileSync(join(this.dir, sha)))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n }\n}\n\nexport interface FsRunArtifactSourceConfig {\n /** Runtime root the production run store persisted under (e.g. `.agent-qa`). */\n root: string\n /** The run whose sha-keyed screenshot blobs this source reads. */\n runId: string\n}\n\n// Production-shaped read leg over the exact runner-local store that persisted planner screenshots.\n// Run layout, slugging, and sha validation live in FsEvidenceArtifactStore; this adapter only binds\n// eval's neutral ArtifactSource port to that store's read method.\nexport class FsRunArtifactSource implements ArtifactSource {\n private readonly store: FsEvidenceArtifactStore\n\n constructor(config: FsRunArtifactSourceConfig) {\n this.store = new FsEvidenceArtifactStore({ root: config.root, runId: config.runId })\n }\n\n getBlob(sha: string): Uint8Array | undefined {\n return this.store.getBlob(sha)\n }\n}\n","// Phase 372 G2 read legs — the report verb's input integrity layer.\n//\n// Inverts FsReplayRecordStore's and FsScoreStore's write legs: reads `replay.json` / `score.json`\n// back from a staged cassette dir with the exact typed-refusal posture of loadCassetteBundle —\n// staged files are hand-editable, cross-machine documents, so every read/parse failure becomes a\n// typed ReplayRefusal instead of a throw (D-08: refusals are data; the surrounding batch always\n// survives). A missing score.json is typed ABSENCE, not an error: refusal outcomes are never\n// scored, the report verb counts them instead. eval-local serializes/deserializes only (F9) —\n// no scoring or aggregation logic lives here; deep validation stays with eval core's guards.\n\nimport { existsSync, readFileSync, readdirSync, type Dirent } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nimport type { ReplayCassetteOutcome, ReplayRefusal } from '@vostride/agent-qa-eval'\nimport { scoringContextSchema, hasValidScoreJudgeMetadata } from '@vostride/agent-qa-eval'\n\nimport { CASSETTE_FILE } from './cassette-store.js'\nimport { REPLAY_RECORD_FILE } from './replay-record-store.js'\nimport { SCORE_FILE, type ScoreRecord } from './score-store.js'\n\n/** The discriminated replay-record read outcome: a persisted outcome, or a typed refusal. */\nexport type ReplayRecordLoad =\n | { kind: 'loaded'; outcome: ReplayCassetteOutcome }\n | { kind: 'refused'; refusal: ReplayRefusal }\n\n/** The score read outcome: a persisted record, typed absence (never scored), or a typed refusal. */\nexport type ScoreRecordLoad =\n | { kind: 'loaded'; record: ScoreRecord }\n | { kind: 'absent' }\n | { kind: 'refused'; refusal: ReplayRefusal }\n\n// Every refusal is attributed to a cassette id recovered from the dir basename: unlike\n// loadCassetteBundle there is no guard step here (deep validation stays with eval core), so a\n// document is never parsed-but-rejected — read/parse failures are the only refusal paths and the\n// basename is the only recoverable id on them.\nfunction refusal(cassetteId: string, detail: string): ReplayRefusal {\n return { kind: 'integrity-refusal', cassetteId, reason: 'parse-failed', detail }\n}\n\n// The shared read→parse ladder (loadCassetteBundle's posture): every failure is a returned value.\nfunction readDocument(\n path: string,\n fallbackId: string,\n): { kind: 'parsed'; document: unknown } | { kind: 'refused'; refusal: ReplayRefusal } {\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (error) {\n return {\n kind: 'refused',\n refusal: refusal(\n fallbackId,\n `Failed to read ${path}: ${(error as NodeJS.ErrnoException).message}`,\n ),\n }\n }\n\n let document: unknown\n try {\n document = JSON.parse(raw)\n } catch (error) {\n return {\n kind: 'refused',\n refusal: refusal(fallbackId, `Invalid JSON at ${path}: ${(error as Error).message}`),\n }\n }\n\n return { kind: 'parsed', document }\n}\n\n/**\n * Read a persisted ReplayCassetteOutcome back from `<dir>/replay.json`. A replay dir without its\n * marker file is corrupt, not empty — a missing or unreadable file refuses like a parse failure.\n * Never throws; the store serialized the outcome verbatim so the parsed document is it.\n */\nexport function loadReplayRecord(dir: string): ReplayRecordLoad {\n const read = readDocument(join(dir, REPLAY_RECORD_FILE), basename(dir))\n if (read.kind === 'refused') return read\n return { kind: 'loaded', outcome: read.document as ReplayCassetteOutcome }\n}\n\n/**\n * Read a persisted ScoreRecord back from `<dir>/score.json`. Absence is typed and legitimate\n * (refusal outcomes are never scored); an existing-but-unreadable/unparseable file refuses.\n * Never throws.\n */\nexport function loadScoreRecord(dir: string): ScoreRecordLoad {\n const path = join(dir, SCORE_FILE)\n if (!existsSync(path)) return { kind: 'absent' }\n\n const read = readDocument(path, basename(dir))\n if (read.kind === 'refused') return read\n if (!hasValidScoreJudgeMetadata(read.document)) {\n return { kind: 'refused', refusal: refusal(basename(dir), `Invalid score judge metadata at ${path}`) }\n }\n if (typeof read.document === 'object' && read.document !== null && 'scoringContext' in read.document &&\n !scoringContextSchema.safeParse(read.document.scoringContext).success) {\n return { kind: 'refused', refusal: refusal(basename(dir), `Invalid scoring context at ${path}`) }\n }\n return { kind: 'loaded', record: read.document as ScoreRecord }\n}\n\n// Recursive walk collecting every directory that directly contains the marker file. Cassette ids\n// are multi-segment slugged paths, so staged dirs nest at arbitrary depth — the walk must recurse,\n// not glob one level. The root read is ENOENT-safe (a missing root is an empty sweep, D-02) and\n// the result is sorted lexicographically before returning: deterministic sweep order, no\n// readdir-ordering leaks (the eval determinism law).\nfunction listMarkerDirs(root: string, markerFile: string): string[] {\n const found: string[] = []\n\n function walk(dir: string): void {\n let entries: Dirent[]\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n if (entries.some(entry => entry.isFile() && entry.name === markerFile)) found.push(dir)\n for (const entry of entries) {\n if (entry.isDirectory()) walk(join(dir, entry.name))\n }\n }\n\n walk(root)\n return found.sort()\n}\n\n/** Enumerate every staged replay-record dir (contains replay.json) under the replays root, sorted. */\nexport function listReplayRecordDirs(replaysRoot: string): string[] {\n return listMarkerDirs(replaysRoot, REPLAY_RECORD_FILE)\n}\n\n/** Enumerate every staged cassette-bundle dir (contains cassette.json) under the cassettes root, sorted. */\nexport function listCassetteBundleDirs(cassettesRoot: string): string[] {\n return listMarkerDirs(cassettesRoot, CASSETTE_FILE)\n}\n","// Filesystem replay-record store (Phase 368, D-12).\n//\n// Persists each per-cassette replay outcome — a ReplayResult or a typed ReplayRefusal (refusals are\n// records too, never silent; Phase 372's baseline reader consumes them) — under an uncommitted\n// runtime staging root beside `eval/cassettes`:\n//\n// <output-root>/<slugged cassette id segments>/replay.json\n//\n// The store mirrors FsCassetteStore's posture exactly: every id segment delegates to schema's\n// security-reviewed slugBranch sanitizer (path-traversal control, T-368-10), and each record is\n// recreated in full (rm + mkdir) before writing so a re-run leaves no stale files behind (idempotent\n// overwrite). The write is deterministic: the same outcome yields the same path and the same bytes —\n// no timestamps or random ids are minted here; timing data already lives inside the outcome from the\n// engine clock. Records land ONLY under this output root — never knowledge dirs or committed trees;\n// the committed corpus root is Phase 371's leg. Records are written as handed over (441 D-15).\n\nimport { mkdirSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { ReplayCassetteOutcome } from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nexport const DEFAULT_EVAL_REPLAYS_SUBDIR = 'eval/replays'\nexport const REPLAY_RECORD_FILE = 'replay.json'\n\nexport interface FsReplayRecordStoreConfig {\n /** Runtime root (normally the workdir's `.agent-qa` directory). */\n root: string\n /** Optional retargeted root used by later committed-corpus composition. */\n outputDir?: string\n /** Actual producer seed; embedded in the bytes bound by the run publication. */\n executionSeed?: number\n}\n\nexport interface WrittenReplayRecord {\n cassetteId: string\n dir: string\n file: string\n}\n\nexport class FsReplayRecordStore {\n private readonly outputRoot: string\n private readonly executionSeed?: number\n\n constructor(config: FsReplayRecordStoreConfig) {\n this.outputRoot = config.outputDir ?? join(config.root, DEFAULT_EVAL_REPLAYS_SUBDIR)\n this.executionSeed = config.executionSeed\n }\n\n save(outcome: ReplayCassetteOutcome): WrittenReplayRecord {\n const dir = join(\n this.outputRoot,\n ...outcome.cassetteId.split('/').map((segment) => slugBranch(segment)),\n )\n rmSync(dir, { recursive: true, force: true })\n mkdirSync(dir, { recursive: true })\n\n const file = join(dir, REPLAY_RECORD_FILE)\n const record =\n this.executionSeed === undefined ? outcome : { ...outcome, executionSeed: this.executionSeed }\n writeFileSync(file, `${JSON.stringify(record, null, 2)}\\n`, 'utf8')\n\n return { cassetteId: outcome.cassetteId, dir, file }\n }\n}\n","// Filesystem score store (Phase 369, D-13).\n//\n// Persists one cassette's matcher verdict — the CassetteScore plus its per-decision D-16 diffs —\n// as `score.json` BESIDE the replay record, in the exact same slugged cassette dir\n// FsReplayRecordStore derives (same output root, same slugBranch-per-segment derivation,\n// T-368-10 path-traversal control):\n//\n// <output-root>/<slugged cassette id segments>/score.json\n//\n// Pitfall-5 deviation from the record store's posture: FsReplayRecordStore recreates its dir in\n// full (rm + mkdir) so a re-run leaves no stale files — copying that here would wipe the sibling\n// replay.json. Score writes are therefore FILE-scoped (mkdir-if-missing + overwrite the one file,\n// never rmSync the dir), and the sanctioned composition orders record-save BEFORE score-save so\n// the record store's dir-recreate can never destroy a fresher score (OQ-2). Bytes stay\n// deterministic: same record ⇒ same path, same bytes — no timestamps or random ids minted here.\n//\n// eval-local serializes only (F9): every score and diff arrives fully computed from eval core\n// (scoreCassetteReplay / buildDecisionDiff); no scoring logic of any kind lives in this file.\n\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { CassetteScore, DecisionDiff, JudgeIdentityBlock, ScoringContext } from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nimport { DEFAULT_EVAL_REPLAYS_SUBDIR } from './replay-record-store.js'\n\nexport const SCORE_FILE = 'score.json'\n\n/** The persisted per-cassette score document — computed entirely in eval core (F9). */\nexport interface ScoreRecord {\n cassetteId: string\n /** The matcher constitution that minted the score (attribution stamp). */\n matcherVersion: number\n score: CassetteScore\n diffs: readonly DecisionDiff[]\n /**\n * D-16 score-side reproducibility receipt: the full identity of the judge that produced any\n * stamp on this score — judge model id, resolved family, judgeVersion, threshold. Computed\n * entirely by eval-core adjudication and serialized verbatim here (F9: eval-local never\n * computes, only writes). Typed-absent when no judge walk ran, keeping 369 records\n * byte-compatible. The cassette's reserved tier4JudgeId is Phase 371 label territory —\n * the scorer never writes back into the measurement.\n */\n judge?: JudgeIdentityBlock\n scoringContext?: ScoringContext\n}\n\nexport interface FsScoreStoreConfig {\n /** Runtime root (normally the workdir's `.agent-qa` directory). */\n root: string\n /** Optional retargeted root used by later committed-corpus composition. */\n outputDir?: string\n}\n\nexport interface WrittenScoreRecord {\n cassetteId: string\n dir: string\n file: string\n}\n\nexport class FsScoreStore {\n private readonly outputRoot: string\n\n constructor(config: FsScoreStoreConfig) {\n // SAME subdir as the record store — the score sits beside its replay.json.\n this.outputRoot = config.outputDir ?? join(config.root, DEFAULT_EVAL_REPLAYS_SUBDIR)\n }\n\n save(record: ScoreRecord): WrittenScoreRecord {\n const dir = join(\n this.outputRoot,\n ...record.cassetteId.split('/').map(segment => slugBranch(segment)),\n )\n // File-scoped write (Pitfall 5): no rmSync dir-recreate — that would wipe the sibling\n // replay.json. Idempotent overwrite of the one file only.\n mkdirSync(dir, { recursive: true })\n\n const file = join(dir, SCORE_FILE)\n writeFileSync(file, `${JSON.stringify(record, null, 2)}\\n`, 'utf8')\n\n return { cassetteId: record.cassetteId, dir, file }\n }\n}\n","import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { canonicalJson } from '@vostride/agent-qa-eval'\nimport { HANDOFF_FILE, RUNS_SUBDIR, slugBranch } from '@vostride/agent-qa-runner-local'\nimport { ImprovementPlanSchema, MarkReceiptSchema, markAddressKey, type MarkAddress, type MarkReceipt } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\nimport { acquireMarkLock } from './mark-lock.js'\n\nexport const MARKS_LEDGER_FILE = 'marks.jsonl'\nexport const MARKS_LEDGER_LOCK_FILE = 'marks.jsonl.lock'\n/** A run's one unfinished mark, beside its ledger. */\nexport const MARK_INTENT_FILE = 'mark-intent.json'\n/**\n * 2026-09-30, 432-09 (D-04/D-11): the resumable mark. `operationId` is the stable identity every\n * effect of this mark carries (the knowledge change id derives from it), so a retry at any stage\n * lands the same fix once. `applied` is the last stage: the fix is published and the receipt is\n * next, and only the receipt remains to be written. The applied change itself rides the mark's\n * own disposition, so there is one record of what changed.\n */\nexport const MARK_INTENT_STAGES = ['prepared', 'evidence', 'applied'] as const\nconst intentSchema = z.object({\n schemaVersion: z.literal(2), mark: MarkReceiptSchema,\n stage: z.enum(MARK_INTENT_STAGES),\n operationId: z.uuid(),\n plan: ImprovementPlanSchema.optional(),\n}).strict().superRefine((intent, ctx) => {\n if (intent.stage === 'applied' && intent.mark.disposition.kind === 'drafted') {\n ctx.addIssue({ code: 'custom', path: ['mark', 'disposition'], message: 'a mark applies its fix; it never files a draft' })\n }\n})\nexport type MarkIntent = z.infer<typeof intentSchema>\n\nfunction atomicPublish(path: string, text: string): void {\n const staged = `${path}.pending`\n const fd = openSync(staged, 'w', 0o600)\n try { writeFileSync(fd, text); fsyncSync(fd) } finally { closeSync(fd) }\n renameSync(staged, path)\n}\n\nexport class MarkLedgerBusyError extends Error {\n constructor() {\n super('Mark ledger is busy; retry the mark after the current transaction finishes')\n this.name = 'MarkLedgerBusyError'\n }\n}\n\nexport class MarkLedgerCorruptError extends Error {\n constructor(readonly line: number) {\n // Never echo malformed user text or parser diagnostics into a host surface.\n super(`Mark ledger is corrupt at line ${line}`)\n this.name = 'MarkLedgerCorruptError'\n }\n}\n\n/**\n * 2026-10-03 (quick 261003-lgd, Phase 432 review IN-23): the run's unfinished-mark record cannot be\n * resumed, refused by the record's own name. It used to surface as `MarkLedgerCorruptError` at the\n * NEXT ordinal, a line `marks.jsonl` does not have. D-02: nothing is migrated or read further; the\n * message names the file to remove, after which the run can be marked again.\n */\nexport class MarkIntentUnusableError extends Error {\n constructor(\n readonly intentPath: string,\n readonly reason: 'earlier-version' | 'unreadable' | 'mismatched',\n ) {\n const what = reason === 'earlier-version'\n ? 'was written by an earlier agent-qa version, which this version does not read'\n : reason === 'unreadable' ? 'is unreadable' : 'does not match this run\\'s mark ledger'\n // Never echo the record's bytes or parser diagnostics into a host surface.\n super(`The unfinished-mark record ${intentPath} ${what}; nothing was marked. Remove that file, `\n + 'then mark again.')\n this.name = 'MarkIntentUnusableError'\n }\n}\n\n/** Keys only a pre-432 intent carried: a filed proposal, the drafted stage, a stored test draft. */\nfunction isEarlierVersionIntent(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false\n const intent = value as Record<string, unknown>\n return 'proposalUuid' in intent || 'testDraft' in intent || intent['stage'] === 'drafted'\n}\n\n/** The one latest-per-address rule, over receipts a caller has already read once. */\nexport function latestMarkReceiptsPerAddress(receipts: readonly MarkReceipt[]): MarkReceipt[] {\n const latest = new Map<string, MarkReceipt>()\n for (const receipt of receipts) {\n const key = markAddressKey(receipt)\n if ((latest.get(key)?.ordinal ?? 0) < receipt.ordinal) latest.set(key, receipt)\n }\n return [...latest.values()].sort((a, b) =>\n a.testIndex - b.testIndex || (a.stepIndex ?? -1) - (b.stepIndex ?? -1),\n )\n}\n\nexport function latestMarkReceiptFor(\n receipts: readonly MarkReceipt[],\n runId: string,\n address: MarkAddress,\n): MarkReceipt | undefined {\n if (address.runId !== runId) return undefined\n return latestMarkReceiptsPerAddress(receipts).find(receipt => markAddressKey(receipt) === markAddressKey(address)\n && (address.testId === undefined || receipt.testId === address.testId))\n}\n\nexport class MarkLedgerNoRunError extends Error {\n constructor() {\n super('run-not-found: mark ledger requires a completed run handoff')\n this.name = 'MarkLedgerNoRunError'\n }\n}\n\n/** Gate-side runtime ledger. The proposer reader entry never exports this store. */\nexport class FsMarkLedger {\n private readonly dir: string\n private readonly file: string\n private readonly lock: string\n private readonly runId: string\n private readonly runSlug: string\n private inTransaction = false\n private intentValue: MarkIntent | undefined\n\n constructor(config: { root: string; runId: string }) {\n this.runId = config.runId\n this.runSlug = slugBranch(config.runId)\n this.dir = join(config.root, RUNS_SUBDIR, this.runSlug)\n this.file = join(this.dir, MARKS_LEDGER_FILE)\n this.lock = join(this.dir, MARKS_LEDGER_LOCK_FILE)\n }\n\n read(): MarkReceipt[] {\n let text: string\n try {\n text = readFileSync(this.file, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n if (text === '') return []\n const lines = text.split('\\n')\n // A missing terminator may be a torn append; concatenating another receipt would corrupt it.\n if (lines.pop() !== '') throw new MarkLedgerCorruptError(lines.length + 1)\n return lines.map((line, index) => {\n try {\n const receipt = MarkReceiptSchema.parse(JSON.parse(line))\n if (receipt.ordinal !== index + 1 || receipt.runId !== this.runId || receipt.runSlug !== this.runSlug) {\n throw new Error('ledger identity or ordinal mismatch')\n }\n return receipt\n } catch {\n throw new MarkLedgerCorruptError(index + 1)\n }\n })\n }\n\n latestPerAddress(): MarkReceipt[] {\n return latestMarkReceiptsPerAddress(this.read())\n }\n\n latestFor(address: MarkAddress): MarkReceipt | undefined {\n // A foreign address never reads this run's ledger.\n if (address.runId !== this.runId) return undefined\n return latestMarkReceiptFor(this.read(), this.runId, address)\n }\n\n /** Private resumable state is admitted only while this run's existing lock is held. */\n prepareIntent(mark: MarkReceipt, operationId: string): MarkIntent {\n if (!this.inTransaction) throw new Error('mark intent requires the run transaction')\n const prior = this.intentValue\n if (prior !== undefined) {\n const request = (value: MarkReceipt) => ({ runId: value.runId, testIndex: value.testIndex,\n testId: value.testId, stepIndex: value.stepIndex, kind: value.kind, note: value.note,\n correctedExpectation: value.correctedExpectation, correctedAction: value.correctedAction })\n if (canonicalJson(request(prior.mark)) !== canonicalJson(request(mark))) {\n throw new Error('An unfinished mark must be retried with its original address and correction')\n }\n return prior\n }\n return this.checkpointIntent({ schemaVersion: 2, mark, operationId, stage: 'prepared' })\n }\n\n checkpointIntent(value: MarkIntent): MarkIntent {\n if (!this.inTransaction) throw new Error('mark intent requires the run transaction')\n const intent = intentSchema.parse(value)\n if (intent.mark.runId !== this.runId || intent.mark.runSlug !== this.runSlug\n || intent.mark.ordinal !== this.read().length + 1) throw new MarkLedgerCorruptError(intent.mark.ordinal)\n atomicPublish(join(this.dir, MARK_INTENT_FILE), `${canonicalJson(intent)}\\n`)\n this.intentValue = intent\n return intent\n }\n\n async transact(\n fn: (nextOrdinal: number) => Promise<Omit<MarkReceipt, 'ordinal'> | undefined>,\n ): Promise<MarkReceipt | undefined> {\n if (!existsSync(join(this.dir, HANDOFF_FILE))) throw new MarkLedgerNoRunError()\n const release = await acquireMarkLock(this.lock, this.runId, () => new MarkLedgerBusyError())\n try {\n // Freeze and draft inside this callback: the next host sees the entire prior receipt.\n const receipts = this.read()\n const nextOrdinal = receipts.length + 1\n const intentPath = join(this.dir, MARK_INTENT_FILE)\n this.intentValue = undefined\n if (existsSync(intentPath)) {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(intentPath, 'utf8'))\n } catch { throw new MarkIntentUnusableError(intentPath, 'unreadable') }\n const parsed = intentSchema.safeParse(raw)\n if (!parsed.success) {\n throw new MarkIntentUnusableError(intentPath,\n isEarlierVersionIntent(raw) ? 'earlier-version' : 'unreadable')\n }\n const intent = parsed.data\n if (intent.mark.runId !== this.runId || intent.mark.runSlug !== this.runSlug) {\n throw new MarkIntentUnusableError(intentPath, 'mismatched')\n }\n if (intent.mark.ordinal === nextOrdinal) this.intentValue = intent\n else if (canonicalJson(receipts[intent.mark.ordinal - 1]) === canonicalJson(intent.mark)) unlinkSync(intentPath)\n else throw new MarkIntentUnusableError(intentPath, 'mismatched')\n }\n this.inTransaction = true\n const record = await fn(nextOrdinal)\n if (record === undefined) return undefined\n const receipt = MarkReceiptSchema.parse({ ...record, ordinal: nextOrdinal })\n if (receipt.runId !== this.runId || receipt.runSlug !== this.runSlug) {\n throw new Error('mark receipt does not belong to this run ledger')\n }\n if (this.intentValue !== undefined && (this.intentValue.stage !== 'applied'\n || canonicalJson(this.intentValue.mark) !== canonicalJson(receipt))) {\n throw new MarkLedgerCorruptError(nextOrdinal)\n }\n // Preserve the exact historical prefix while atomically publishing the next complete line.\n const before = existsSync(this.file) ? readFileSync(this.file, 'utf8') : ''\n atomicPublish(this.file, `${before}${canonicalJson(receipt)}\\n`)\n if (this.intentValue !== undefined) unlinkSync(intentPath)\n return receipt\n } finally {\n this.inTransaction = false\n this.intentValue = undefined\n release()\n }\n }\n\n append(record: Omit<MarkReceipt, 'ordinal'>): Promise<MarkReceipt | undefined> {\n return this.transact(async () => record)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { z } from 'zod'\n\nconst ownerSchema = z.object({ schemaVersion: z.literal(2), kind: z.literal('mark-ledger-lock'),\n pid: z.number().int().positive(), token: z.uuid(), runId: z.string().min(1) }).strict()\ntype Owner = z.infer<typeof ownerSchema>\n\nfunction syncDirectory(path: string): void {\n const fd = openSync(path, 'r')\n try { fsyncSync(fd) } finally { closeSync(fd) }\n}\n\nfunction readOwner(path: string, runId: string): Owner | undefined {\n try {\n const directory = lstatSync(path)\n if (!directory.isDirectory() || directory.isSymbolicLink()) return undefined\n const ownerFile = join(path, 'owner.json')\n const file = lstatSync(ownerFile)\n if (!file.isFile() || file.isSymbolicLink()) return undefined\n const parsed = ownerSchema.safeParse(JSON.parse(readFileSync(ownerFile, 'utf8')))\n return parsed.success && parsed.data.runId === runId ? parsed.data : undefined\n } catch { return undefined }\n}\n\nfunction positivelyDead(pid: number): boolean {\n try { process.kill(pid, 0); return false }\n catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH' }\n}\n\n/** Complete owner publication; malformed, legacy and uncertain owners are never reaped. */\nexport async function acquireMarkLock(lock: string, runId: string, busy: () => Error): Promise<() => void> {\n const owner: Owner = { schemaVersion: 2, kind: 'mark-ledger-lock', pid: process.pid, token: randomUUID(), runId }\n const candidate = `${lock}.candidate-${owner.token}`\n mkdirSync(candidate)\n const fd = openSync(join(candidate, 'owner.json'), 'wx', 0o600)\n try { writeFileSync(fd, JSON.stringify(owner)); fsyncSync(fd) } finally { closeSync(fd) }\n syncDirectory(candidate)\n const started = Date.now()\n let acquired = false\n try {\n while (!acquired) {\n try {\n // mkdir is create-only even against an empty legacy/partial directory. Publish the\n // complete owner immediately afterward; death in this tiny gap remains busy by law.\n mkdirSync(lock)\n renameSync(join(candidate, 'owner.json'), join(lock, 'owner.json'))\n syncDirectory(lock)\n syncDirectory(dirname(lock))\n rmSync(candidate, { recursive: true })\n acquired = true\n } catch (error) {\n if (!['EEXIST', 'ENOTEMPTY', 'ENOTDIR', 'EISDIR', 'EPERM', 'EACCES'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error\n const current = readOwner(lock, runId)\n if (current !== undefined && positivelyDead(current.pid)) {\n try {\n // Retain this NONEMPTY generation tombstone. A delayed reclaimer of G cannot\n // rename a newer live H over dead-G after another contender already moved G.\n renameSync(lock, `${lock}.dead-${current.token}`)\n syncDirectory(dirname(lock))\n continue\n } catch (recoveryError) {\n if ((recoveryError as NodeJS.ErrnoException).code === 'ENOENT') continue\n if (!['EEXIST', 'ENOTEMPTY', 'ENOTDIR', 'EISDIR', 'EPERM', 'EACCES'].includes((recoveryError as NodeJS.ErrnoException).code ?? '')) throw recoveryError\n }\n }\n const remaining = 10_000 - (Date.now() - started)\n if (remaining <= 0) throw busy()\n await new Promise(resolve => setTimeout(resolve, Math.min(50, remaining)))\n }\n }\n } finally {\n if (!acquired) rmSync(candidate, { recursive: true, force: true })\n }\n return () => {\n if (readOwner(lock, runId)?.token !== owner.token) return\n const released = `${lock}.released-${owner.token}`\n renameSync(lock, released)\n syncDirectory(dirname(lock))\n rmSync(released, { recursive: true })\n syncDirectory(dirname(lock))\n }\n}\n","import { lstatSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\nimport { z } from 'zod'\nimport { canonicalJson, deriveLabelRevisionId, parseStandaloneLabelRecord, selectEffectiveLabels, type LabelCalibrationReport, type StandaloneLabelRecord } from '@vostride/agent-qa-eval'\nimport { ORIGIN_PRIORS, sha256hex } from '@vostride/agent-qa-schema'\nimport { committedLabelPath } from './committed-root-store.js'\n\nexport const LABEL_CALIBRATION_PATH = 'labels/calibration.json'\nexport const LABEL_CALIBRATION_SCHEMA_VERSION = 2\nexport interface LabelCalibrationArtifact extends Omit<LabelCalibrationReport, 'minGold'> {\n schemaVersion: typeof LABEL_CALIBRATION_SCHEMA_VERSION\n minGold: { value: number; source: 'default' | 'cli' }\n evidenceDigest: string\n generationId: string\n targetRevisions: readonly { cassetteId: string; revisionId: string }[]\n}\nexport type LabelCalibrationRead =\n | { kind: 'absent' }\n | { kind: 'refused'; reason: string; targetCassetteIds?: readonly string[] }\n | { kind: 'loaded'; artifact: LabelCalibrationArtifact; authorizedRevisionIds: ReadonlySet<string> }\n\nconst count = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER)\nconst unit = z.number().finite().min(0).max(1)\nconst digest = z.string().regex(/^[0-9a-f]{64}$/)\nconst noisy = z.union([\n z.object({ status: z.literal('uncalibrated'), n: count, n_gold: count }).strict(),\n z.object({ status: z.literal('calibrated'), n: count, n_gold: count, precision: unit,\n wilson95: z.object({ lower: unit, upper: unit, halfWidth: unit }).strict()\n .refine(v => v.lower <= v.upper),\n }).strict(),\n])\nconst gold = z.object({ n_gold: count, precision: z.literal('by-construction') }).strict()\nconst prior = z.object({ alpha: z.number().finite().min(0), beta: z.number().finite().min(0) }).strict()\n .refine(v => Number.isFinite(v.alpha + v.beta) && v.alpha + v.beta > 0)\nconst rate = z.object({ numerator: count, denominator: count, rate: unit.optional() }).strict()\n .refine(v => v.numerator <= v.denominator && (v.denominator === 0 ? v.rate === undefined : v.rate === v.numerator / v.denominator))\nconst accuracy = z.object({ n: count, correct: count, accuracy: unit.optional() }).strict()\n .refine(v => v.correct <= v.n && (v.n === 0 ? v.accuracy === undefined : v.accuracy === v.correct / v.n))\nconst artifactSchema = z.object({\n schemaVersion: z.literal(LABEL_CALIBRATION_SCHEMA_VERSION), generationId: digest, evidenceDigest: digest,\n corpusDigest: digest, goldSetDigest: digest,\n minGold: z.object({ value: count.min(2), source: z.enum(['default', 'cli']) }).strict(),\n channels: z.object({ 'recorded-verdict': noisy, 'self-heal-pair': noisy, 'user-mark': gold, 'overturned-verdict': gold }).strict(),\n priors: z.object({ 'agent-verified': prior.optional(), 'agent-observed': prior.optional() }).strict(),\n unchangedOrigins: z.tuple([z.literal('user'), z.literal('import')]),\n verifierFalsePassRate: rate, verifierFalseFailRate: rate,\n rootCauseClassifierAccuracy: z.object({ 'analyze-run': accuracy, 'deterministic-classifier': accuracy }).strict(),\n rootCauseClassifierGrain: z.literal('member/producer:app_bug-binary'),\n skippedCounts: 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(),\n targetRevisions: z.array(z.object({ cassetteId: z.string().min(1), revisionId: digest }).strict()),\n}).strict()\n\n/** Refuse symlinks at every existing segment, including a dangling leaf; never follow one. */\nexport function assertCalibrationPath(root: string, path: string): void {\n const base = resolve(root), full = resolve(path), rel = relative(base, full)\n if (rel === '..' || rel.startsWith('../') || rel.startsWith('/')) throw new Error('invalid calibration path')\n let cursor = full\n while (true) {\n try { if (lstatSync(cursor).isSymbolicLink()) throw new Error('invalid calibration path') }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error }\n if (cursor === base) break\n const parent = dirname(cursor)\n if (parent === cursor) break\n cursor = parent\n }\n}\n\nexport function calibrationGenerationId(body: Omit<LabelCalibrationArtifact, 'generationId'>): string {\n return sha256hex(canonicalJson(body))\n}\n\n/** Structural checks plus consistency between minimum, measured channels and emitted priors. */\nexport function guardLabelCalibration(value: unknown): LabelCalibrationArtifact | undefined {\n const parsed = artifactSchema.safeParse(value)\n if (!parsed.success) return undefined\n const artifact = parsed.data\n const { generationId, ...body } = artifact\n if (calibrationGenerationId(body) !== generationId) return undefined\n let previous: string | undefined\n for (const target of artifact.targetRevisions) {\n if (previous !== undefined && previous >= target.cassetteId) return undefined\n previous = target.cassetteId\n }\n for (const [channel, origin] of [['recorded-verdict', 'agent-verified'], ['self-heal-pair', 'agent-observed']] as const) {\n const row = artifact.channels[channel], emitted = artifact.priors[origin]\n if (row.n !== row.n_gold || (row.status === 'calibrated') !== (row.n >= artifact.minGold.value)) return undefined\n if (row.status === 'uncalibrated') { if (emitted !== undefined) return undefined }\n else {\n const mass = ORIGIN_PRIORS[origin].alpha + ORIGIN_PRIORS[origin].beta\n if (!emitted || emitted.alpha !== row.precision * mass || emitted.beta !== (1 - row.precision) * mass) return undefined\n }\n }\n return artifact\n}\n\n/** Independent marker loading: never calls the corpus reader and never grants a whole generation. */\nexport function readLabelCalibration(committedRoot: string): LabelCalibrationRead {\n const marker = join(committedRoot, LABEL_CALIBRATION_PATH)\n let targetCassetteIds: string[] | undefined\n try {\n assertCalibrationPath(committedRoot, marker)\n try { lstatSync(marker) } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'absent' }\n throw error\n }\n const artifact = guardLabelCalibration(JSON.parse(readFileSync(marker, 'utf8')))\n if (!artifact) return { kind: 'refused', reason: 'invalid label calibration artifact' }\n targetCassetteIds = artifact.targetRevisions.map(target => target.cassetteId)\n const records = new Map<string, StandaloneLabelRecord>()\n function walk(directory: string): void {\n assertCalibrationPath(committedRoot, directory)\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name)\n if (entry.isDirectory()) { walk(path); continue }\n if (!entry.isFile() || !entry.name.endsWith('.json') || path === marker) continue\n let parsed\n try { parsed = parseStandaloneLabelRecord(JSON.parse(readFileSync(path, 'utf8'))) } catch { continue }\n if (!parsed.ok) continue\n const record = parsed.record, product = relative(join(committedRoot, 'labels'), path).split('/')[0]!\n const expected = join(committedRoot, committedLabelPath(product, record.cassetteId))\n .replace(/\\.json$/, record.revision ? `--revision-${record.revision.id}.json` : '.json')\n if (expected !== path) continue\n const id = record.revision?.id ?? deriveLabelRevisionId(record)\n if (records.has(id)) throw new Error('duplicate label identity')\n records.set(id, record)\n }\n }\n walk(join(committedRoot, 'labels'))\n const authorizedRevisionIds = new Set<string>()\n for (const target of artifact.targetRevisions) {\n const chain: StandaloneLabelRecord[] = [], visited = new Set<string>(), generations = new Set<string>()\n let id: string | undefined = target.revisionId\n while (id !== undefined) {\n const record = records.get(id)\n if (!record || record.cassetteId !== target.cassetteId || visited.has(id)) throw new Error('incomplete label chain')\n visited.add(id); chain.push(record)\n if (record.revision?.generationId) generations.add(record.revision.generationId)\n id = record.revision?.predecessorId\n }\n const selected = selectEffectiveLabels(chain, { committedGenerationIds: generations })\n const terminal = selected.effective.get(target.cassetteId)\n if (selected.refusals.length || !terminal || (terminal.revision?.id ?? deriveLabelRevisionId(terminal)) !== target.revisionId) throw new Error('invalid label chain')\n for (const id of visited) authorizedRevisionIds.add(id)\n }\n return { kind: 'loaded', artifact, authorizedRevisionIds }\n } catch { return { kind: 'refused', reason: 'label calibration or target history unavailable', targetCassetteIds } }\n}\n","import { z } from 'zod'\nimport {\n ADVERSARIAL_MUTATORS,\n GENERATOR_KINDS,\n GENERATOR_PROVENANCES,\n} from '@vostride/agent-qa-eval'\nimport type { EvalBatchReport } from '@vostride/agent-qa-eval'\n\nconst count = z.number().int().nonnegative().safe()\nconst amount = z.number().finite().nonnegative()\nconst unit = z.number().finite().min(0).max(1)\nconst rate = z.object({ numerator: count, denominator: count, rate: unit.optional() })\n .passthrough().refine(row => row.numerator <= row.denominator &&\n (row.denominator === 0 ? row.rate === undefined : row.rate === row.numerator / row.denominator))\nconst recovery = z.object({ weightSum: z.number().finite().nonnegative(),\n pairsWithoutWeight: count, weightedAccuracy: unit.optional(),\n selfHealPairCount: count, recoveredPositiveCount: count, eligiblePositiveCount: count,\n recoveryAccuracy: unit.optional(), negativeDecisionCount: count, negativeFullMatchCount: count,\n}).passthrough()\nconst cell = z.object({ firstAttemptDecisionAccuracy: rate, verifierFalsePassRate: rate,\n recovery, perDecisionCost: z.object({ decisionCount: count, promptTokens: amount,\n completionTokens: amount, totalTokens: amount, durationMs: amount }).passthrough(),\n}).passthrough()\n/**\n * 2026-09-12, 422 D-05/D-08: the stored generation mix, validated STRICTLY and additively.\n *\n * A closed-set group is `z.record` keyed on the shipped vocabulary rather than a free string map,\n * so a mutator or provenance arm read off disk that this build does not know is a REFUSAL and not\n * a value that passes through into a disclosure a reader trusts. The open-set groups (table\n * generation, prompt version, authoring model and family) cannot be enumerated — nobody can list\n * the generations that do not exist — so those keep a string key and validate only their counts.\n */\nconst closedCounts = <T extends string>(values: readonly [T, ...T[]]) =>\n z.record(z.enum(values), count)\nconst openCounts = z.record(z.string(), count)\nconst generationMix = z.object({\n total: count,\n metadataUnavailable: count,\n byProvenance: closedCounts(GENERATOR_PROVENANCES),\n byKind: closedCounts(GENERATOR_KINDS),\n byMutator: closedCounts(ADVERSARIAL_MUTATORS),\n byTableVersion: openCounts,\n tableHashesByVersion: z.record(z.string(), z.array(z.string())),\n byPromptVersion: openCounts,\n byAuthoringModel: openCounts,\n byAuthoringFamily: openCounts,\n}).strict()\n\nconst current = z.object({\n // Additive-optional: absent is the pre-422 shape and stays admissible forever.\n adversarialGenerationMix: generationMix.optional(),\n headline: z.object({ verifierFalsePassRate: rate }).passthrough(),\n recovery,\n calibration: z.discriminatedUnion('status', [\n z.object({ status: z.literal('uncalibrated'), n_gold: count.optional(), verifierFalsePassRate: rate.optional() }).passthrough(),\n z.object({ status: z.literal('calibrated'), n_gold: count, verifierFalsePassRate: rate }).passthrough(),\n ]),\n perSplit: z.object({ natural: cell, 'held-out': z.object({ shared: cell, private: cell }).passthrough(),\n adversarial: cell, unassignedCount: count }).passthrough(),\n}).passthrough()\n\n/** Read boundary only: a partially present addition is never evidence of a legacy format. */\nexport function reportMetadataKind(value: unknown): 'legacy' | 'current' | 'invalid' {\n if (value === null || typeof value !== 'object') return 'invalid'\n const report = value as Record<string, unknown>\n const has = (object: unknown, key: string) => object !== null && typeof object === 'object'\n && Object.hasOwn(object, key)\n // 422: a report carrying the generation mix is certainly not a legacy report, so the mix joins\n // the addition set rather than being ignored — bytes naming it but missing `perSplit` are\n // `invalid`, which is the same \"partially present is never evidence of legacy\" rule as above.\n const additions = has(report, 'calibration') || has(report, 'perSplit')\n || has(report, 'adversarialGenerationMix')\n || has(report.headline, 'verifierFalsePassRate') || has(report.recovery, 'weightSum')\n || has(report.recovery, 'pairsWithoutWeight') || has(report.recovery, 'weightedAccuracy')\n return !additions ? 'legacy' : current.safeParse(value).success ? 'current' : 'invalid'\n}\n\n/**\n * Strip the six named Phase420 additions and 422's generation mix from a fresh comparison view;\n * never saved bytes. The mix joins for exactly the reason the six did: a legacy report predates\n * the field, so leaving it on the candidate would make every legacy report stop reproducing from\n * its own retained records the moment the field shipped.\n */\nexport function legacyReportComparison(report: EvalBatchReport): Record<string, unknown> {\n const {\n calibration: _calibration,\n perSplit: _perSplit,\n adversarialGenerationMix: _generationMix,\n ...historical\n } = report\n const { verifierFalsePassRate: _falsePass, ...headline } = report.headline\n const { weightSum: _weightSum, pairsWithoutWeight: _missing, weightedAccuracy: _weighted, ...recovery } = report.recovery\n return { ...historical, headline, recovery }\n}\n","// Filesystem batch-report store (Phase 369, D-13/D-14).\n//\n// Persists one aggregated EvalBatchReport as its own artifact under the uncommitted runtime\n// staging root:\n//\n// <output-root>/eval/reports/<slugged batchKey>.json\n//\n// The filename derives ONLY from report.batchKey — eval core's deterministic replay-batch key\n// (sha256 over the canonical sorted cassette-id list, D-13) — through schema's slugBranch\n// sanitizer (T-368-10 path-traversal control). No timestamps or random components are minted\n// in the published identity, so a rerun of the same batch replaces the same file and a\n// different batch lands beside it. Bytes are deterministic: same report ⇒ same path, same bytes.\n// 415 D-16 adds an optional .decisions.json sidecar. A staging-only publication manifest\n// binds both file digests before either replacement; interrupted or interleaved generations\n// refuse at the reader. Legacy evidence without a manifest remains readable unchanged.\n//\n// `.agent-qa/eval/reports/` joins `eval/replays/` as UNCOMMITTED runtime staging: committed\n// placement (the corpus root with fail-closed egress) is Phase 371/372's concern; Phase 372's\n// baseline reads reports from exactly this path.\n//\n// eval-local serializes only (F9): the report arrives fully aggregated from eval core's\n// buildEvalReport — no aggregation or scoring logic lives in this file.\n\nimport { mkdirSync, mkdtempSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\n\nimport { guardDecisionVectorsDocument, judgeIdentitySchema } from '@vostride/agent-qa-eval'\nimport type { DecisionVectorsDocument, EvalBatchReport } from '@vostride/agent-qa-eval'\nimport { sha256hex, slugBranch } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\nimport { reportMetadataKind } from './report-metadata-guard.js'\n\nexport const DEFAULT_EVAL_REPORTS_SUBDIR = 'eval/reports'\n\nexport interface FsReportStoreConfig {\n /** Runtime root (normally the workdir's `.agent-qa` directory). */\n root: string\n /** Optional retargeted root used by later committed-corpus composition. */\n outputDir?: string\n}\n\nexport interface WrittenReport {\n batchKey: string\n file: string\n decisionsFile?: string\n}\n\nexport type StagedReportLoad =\n | {\n kind: 'loaded'\n report: EvalBatchReport\n decisions?: DecisionVectorsDocument\n file: string\n replayGeneration?: ReplayGeneration\n }\n | { kind: 'absent'; file: string }\n | { kind: 'refused'; file: string; reason: string }\n\nconst calibrationCount = z.number().int().nonnegative().safe()\nconst calibrationUnit = z.number().finite().min(0).max(1)\nconst copiedInterval = z.object({ lower: calibrationUnit, upper: calibrationUnit,\n halfWidth: calibrationUnit.max(0.5) }).strict().refine(value => value.lower <= value.upper\n && value.upper - value.lower <= 2 * value.halfWidth + Number.EPSILON * 4)\n// Check possible integer agreement counts only; never replace the copied estimate or interval.\nconst consistentAgreement = (n: number, agreement: number) => agreement === Math.round(n * agreement) / n\nconst copiedMember = z.object({ judgeModelId: z.string(), n: calibrationCount,\n agreement: calibrationUnit.optional(), wilson95: copiedInterval.optional() }).strict()\n .refine(value => value.n === 0 ? value.agreement === undefined && value.wilson95 === undefined\n : value.agreement !== undefined && value.wilson95 !== undefined && consistentAgreement(value.n, value.agreement))\nconst copiedCalibration = z.discriminatedUnion('status', [\n z.object({ status: z.literal('calibrated'), n: calibrationCount.min(2),\n pooledAgreement: calibrationUnit, wilson95: copiedInterval,\n perMember: z.array(copiedMember).min(2).max(3) }).strict()\n .refine(value => consistentAgreement(value.n, value.pooledAgreement)),\n z.object({ status: z.literal('uncalibrated'), n: calibrationCount,\n provenance: z.literal('unavailable').optional() }).strict()\n .refine(value => value.provenance === undefined || value.n === 0),\n z.object({ status: z.literal('capability-gap'),\n reason: z.enum(['panel-not-configured', 'no-credential', 'single-family-host']) }).strict(),\n])\n\n/** Independent report admission preserves copied precision and never reads calibration storage. */\nexport const reportJudgeSchema = judgeIdentitySchema.safeExtend({ calibration: copiedCalibration.optional() })\n .refine(judge => {\n const calibration = judge.calibration\n if (calibration === undefined) return true\n if (judge.panelSize === undefined || judge.members === undefined) return false\n if (calibration.status !== 'calibrated') return true\n const memberIds = calibration.perMember.map(member => member.judgeModelId).sort()\n return calibration.perMember.length === judge.members.length\n && memberIds.every((id, index) => id === judge.members![index]!.judgeModelId)\n }, 'calibration requires the complete recorded composite identity')\n\n// A light read boundary, not a format migration. Passthrough at every checked object\n// retains the full report: seed evidence, honesty, judge provenance, costs and future fields.\nconst stagedReportSchema = z.object({\n batchKey: z.string().min(1),\n matcherVersion: z.number().int().nonnegative(),\n headline: z.object({\n perDecisionCost: z.object({ decisionCount: z.number() }).passthrough(),\n }).passthrough(),\n // Optional historical provenance remains optional; malformed mixed identities must never\n // reach the comparator's renderer as though its judge-id list were a string array.\n judgeIdentity: z.literal('mixed').optional(),\n mixedJudgeModelIds: z.array(z.string()).optional(),\n judge: reportJudgeSchema.optional(),\n}).passthrough().refine(report => report.judgeIdentity !== 'mixed' || report.judge === undefined)\n\nconst replayGenerationSchema = z\n .object({\n seed: z.number().int().safe(),\n records: z.array(\n z\n .object({\n cassetteId: z.string().min(1),\n replayDigest: z.string().regex(/^[a-f0-9]{64}$/),\n scoreDigest: z\n .string()\n .regex(/^[a-f0-9]{64}$/)\n .nullable(),\n })\n .strict(),\n ),\n })\n .strict()\nexport type ReplayGeneration = z.infer<typeof replayGenerationSchema>\n\nconst publicationSchema = z.object({\n schemaVersion: z.literal(2),\n reportDigest: z.string().regex(/^[a-f0-9]{64}$/),\n decisionsDigest: z.string().regex(/^[a-f0-9]{64}$/).nullable(),\n replayGeneration: replayGenerationSchema.optional(),\n}).strict()\n\nfunction readOptional(file: string): string | undefined {\n try {\n return readFileSync(file, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\nfunction removeOptional(file: string): void {\n try {\n unlinkSync(file)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n}\n\n/** Probe exactly one directory; callers own the gate-root-first search order. */\nexport function loadStagedReport(\n root: string,\n batchKey: string,\n outputDir?: string,\n): StagedReportLoad {\n const outputRoot = outputDir ?? join(root, DEFAULT_EVAL_REPORTS_SUBDIR)\n const stem = slugBranch(batchKey)\n const file = join(outputRoot, `${stem}.json`)\n const publicationFile = join(outputRoot, `${stem}.publication.json`)\n let publicationText: string | undefined\n try {\n publicationText = readOptional(publicationFile)\n } catch (error) {\n return { kind: 'refused', file: publicationFile, reason: `publication unreadable: ${(error as Error).message}` }\n }\n let reportText: string\n let value: unknown\n try {\n reportText = readFileSync(file, 'utf8')\n value = JSON.parse(reportText)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'absent', file }\n return { kind: 'refused', file, reason: `report unreadable: ${(error as Error).message}` }\n }\n const parsed = stagedReportSchema.safeParse(value)\n if (!parsed.success) {\n return { kind: 'refused', file, reason: `report rejected: ${parsed.error.message}` }\n }\n if (reportMetadataKind(value) === 'invalid') {\n return { kind: 'refused', file, reason: 'report label metadata incomplete or malformed' }\n }\n if (parsed.data.batchKey !== batchKey) {\n return { kind: 'refused', file, reason: 'report batchKey does not match the requested batchKey' }\n }\n const report = parsed.data as unknown as EvalBatchReport\n const decisionsFile = join(outputRoot, `${stem}.decisions.json`)\n let decisionsText: string | undefined\n let decisionsValue: unknown\n try {\n decisionsText = readOptional(decisionsFile)\n decisionsValue = decisionsText === undefined ? undefined : JSON.parse(decisionsText)\n } catch (error) {\n return {\n kind: 'refused', file: decisionsFile,\n reason: `decisions unreadable: ${(error as Error).message}`,\n }\n }\n let decisions: DecisionVectorsDocument | undefined\n if (decisionsValue !== undefined) {\n const guarded = guardDecisionVectorsDocument(decisionsValue)\n if (guarded.kind === 'rejected') {\n return { kind: 'refused', file: decisionsFile, reason: `decisions rejected: ${guarded.reason}` }\n }\n // Plan 09 passes only vectors into the gate; check document identity at this boundary.\n for (const field of ['batchKey', 'matcherVersion'] as const) {\n if (guarded.document[field] !== report[field]) {\n return { kind: 'refused', file: decisionsFile,\n reason: `decisions ${field} does not match the report ${field}` }\n }\n }\n decisions = guarded.document\n }\n // Read the manifest on both sides of the data reads, including the legacy absent case.\n // No newly published generation can be mistaken for an unbound historical pair.\n let replayGeneration: ReplayGeneration | undefined\n try {\n if (readOptional(publicationFile) !== publicationText) {\n return { kind: 'refused', file: publicationFile, reason: 'report publication changed during read' }\n }\n if (publicationText !== undefined) {\n const publication = publicationSchema.parse(JSON.parse(publicationText))\n replayGeneration = publication.replayGeneration\n if (publication.reportDigest !== sha256hex(reportText)) {\n return { kind: 'refused', file, reason: 'report publication digest mismatch' }\n }\n if (publication.decisionsDigest !== (decisionsText === undefined ? null : sha256hex(decisionsText))) {\n return { kind: 'refused', file: decisionsFile, reason: 'decisions publication digest mismatch or incomplete sidecar' }\n }\n }\n } catch (error) {\n return { kind: 'refused', file: publicationFile, reason: `publication rejected: ${(error as Error).message}` }\n }\n return { kind: 'loaded', report, ...(decisions === undefined ? {} : { decisions }), file,\n ...(replayGeneration === undefined ? {} : { replayGeneration }) }\n}\n\nexport class FsReportStore {\n private readonly outputRoot: string\n\n constructor(config: FsReportStoreConfig) {\n this.outputRoot = config.outputDir ?? join(config.root, DEFAULT_EVAL_REPORTS_SUBDIR)\n }\n\n save(report: EvalBatchReport, decisions?: DecisionVectorsDocument, replayGeneration?: ReplayGeneration): WrittenReport {\n if (replayGeneration !== undefined) replayGenerationSchema.parse(replayGeneration)\n if (decisions !== undefined) {\n for (const field of ['batchKey', 'matcherVersion'] as const) {\n if (decisions[field] !== report[field]) {\n throw new TypeError(`decisions ${field} does not match the report ${field}`)\n }\n }\n }\n const file = join(this.outputRoot, `${slugBranch(report.batchKey)}.json`)\n const decisionsFile = join(this.outputRoot, `${slugBranch(report.batchKey)}.decisions.json`)\n const publicationFile = join(this.outputRoot, `${slugBranch(report.batchKey)}.publication.json`)\n const reportText = `${JSON.stringify(report, null, 2)}\\n`\n const decisionsText = decisions === undefined ? undefined : `${JSON.stringify(decisions, null, 2)}\\n`\n const publicationText = `${JSON.stringify({ schemaVersion: 2,\n reportDigest: sha256hex(reportText),\n decisionsDigest: decisionsText === undefined ? null : sha256hex(decisionsText),\n ...(replayGeneration === undefined ? {} : { replayGeneration }),\n }, null, 2)}\\n`\n mkdirSync(dirname(file), { recursive: true })\n // Unique temporary storage keeps concurrent writers from sharing a staging file.\n const temporary = mkdtempSync(join(this.outputRoot, '.publish-'))\n const replace = (target: string, text: string): void => {\n const staged = join(temporary, basename(target))\n try {\n writeFileSync(staged, text, 'utf8')\n renameSync(staged, target)\n } catch (error) {\n const io = error as NodeJS.ErrnoException\n if (typeof io.code !== 'string') throw error\n // The public failed file is the intended publication; retain OS detail and cause.\n throw Object.assign(new Error(io.message, { cause: error }), { code: io.code, path: target })\n }\n }\n try {\n replace(publicationFile, publicationText)\n // Invalidate even when this save supplies new vectors, before replacing the report.\n removeOptional(decisionsFile)\n replace(file, reportText)\n if (decisionsText !== undefined) replace(decisionsFile, decisionsText)\n } finally {\n for (const target of [publicationFile, file, decisionsFile]) {\n removeOptional(join(temporary, basename(target)))\n }\n rmdirSync(temporary)\n }\n return { batchKey: report.batchKey, file, ...(decisions === undefined ? {} : { decisionsFile }) }\n }\n}\n","// 2026-09-07, 418 D-02: the ablation composition. The live decision becomes sample one\n// only here; every fresh model call delegates to runCassetteReplay's safety scope.\nimport { dirname, join, resolve } from 'node:path'\nimport { createHash } from 'node:crypto'\nimport { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport {\n applyBriefDelta,\n buildEvalReport,\n computeCorpusDigest,\n computeDecisionIdentity,\n deriveSampleSeeds,\n assignSplit,\n committedFileText,\n deriveRunSlug,\n extractRunCassettes,\n maskCorpusText,\n projectCorpusEntry,\n projectSilverLabelRecord,\n resolveProductPartition,\n type ExtractedCassette,\n type LeafCassette,\n type SeedingPlan,\n type ReplaySample,\n} from '@vostride/agent-qa-eval'\nimport { BENEFITS, distilledScreenStateDigest, slugBranch, type Benefit, type CrossCheck, type MaskFn } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\nimport { loadCompletedRunHandoff, RUNS_SUBDIR, HANDOFF_FILE } from '@vostride/agent-qa-runner-local'\nimport { FsRunArtifactSource } from './artifact-source.js'\nimport { loadCassetteBundle } from './cassette-loader.js'\nimport { loadCassetteBundles } from './replay-sweep.js'\nimport { cassetteProductPartition } from './replay-batch-assembly.js'\nimport { requireCorpusMask, seedCommittedCorpus, type SeedingRefusal, type SeedingBatchReport } from './seeding-composition.js'\nimport { readCommittedCorpus } from './committed-corpus-source.js'\nimport {\n locateTargetCassettes,\n removalFlipsOutcome,\n resolveActiveRecordRemoval,\n type FailingPathCandidateAuthorization,\n type ReplayBag,\n} from './replay-gate-composition.js'\nimport { runCassetteReplay } from './replay-composition.js'\nimport { FsReplayRecordStore } from './replay-record-store.js'\nimport { FsScoreStore } from './score-store.js'\nimport { loadScoreRecord } from './replay-read.js'\nimport { buildRootMarkerValue, COMMITTED_ROOT_MARKER_FILE, committedCassettePath, committedCorpusPath, committedLabelPath, committedBlobPath } from './committed-root-store.js'\n\nexport const GATE2_AUDIT_SUBDIR = 'eval/gate2'\nexport const GATE2_TARGET_SUBDIR = 'target'\n\n// 2026-09-08, 418 D-21: staging is local audit DATA. Only explicit admission calls the seeder.\nexport const FEEDBACK_STAGING_SUBDIR = 'eval/feedback'\nconst feedbackSchema = z.object({\n schemaVersion: z.literal(2), product: z.string().min(1), stateDigest: z.string().regex(/^[0-9a-f]{64}$/),\n attributedObservationId: z.string().min(1), benefit: z.enum(BENEFITS), candidateId: z.string().min(1),\n runId: z.string().min(1), testId: z.string().min(1), stepIndex: z.number().int().nonnegative(),\n stagedAt: z.iso.datetime(),\n}).strict()\ntype FeedbackMetadata = z.infer<typeof feedbackSchema>\nexport interface StagedFeedbackEntry extends FeedbackMetadata {\n dir: string\n extracted: ExtractedCassette & { cassette: LeafCassette }\n}\nexport interface FeedbackStateInput {\n agentQaRoot: string\n committedRoot: string\n product: string\n stateDigest: string\n}\nexport interface StageFeedbackEntryInput extends FeedbackStateInput {\n target: { runId: string; testId: string; stepIndex: number }\n attributedObservationId: string\n benefit: Benefit\n candidateId: string\n /** 441 GAP3-D1: required. The staged cassette is extracted from the masked run. */\n mask: MaskFn\n}\nexport type StageFeedbackEntryResult =\n | { kind: 'staged'; dir: string }\n | { kind: 'already-staged' | 'not-novel' }\n | { kind: 'target-unavailable' | 'write-conflict' }\n\nfunction feedbackDir(input: Omit<FeedbackStateInput, 'committedRoot'>): string {\n if (!/^[0-9a-f]{64}$/.test(input.stateDigest)) throw new TypeError('invalid feedback state digest')\n return join(realpathSync(input.agentQaRoot), FEEDBACK_STAGING_SUBDIR, slugBranch(input.product), input.stateDigest)\n}\nfunction pathPresent(path: string): boolean {\n try { lstatSync(path); return true } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n}\n/** Refuse links/wrong-kind ancestors rather than following local audit paths out of their root. */\nfunction requireDirectories(path: string): void {\n const absolute = resolve(path)\n const parent = dirname(absolute)\n if (parent !== absolute) requireDirectories(parent)\n if (pathPresent(absolute) && !lstatSync(absolute).isDirectory()) throw new TypeError('unsafe feedback directory')\n}\nfunction directoryNames(path: string): string[] {\n requireDirectories(path)\n if (!pathPresent(path)) return []\n return readdirSync(path, { withFileTypes: true }).map(entry => {\n if (!entry.isDirectory()) throw new TypeError('unexpected feedback path')\n return entry.name\n }).sort()\n}\nexport function isNovelState(input: FeedbackStateInput): boolean {\n const dir = feedbackDir(input)\n requireDirectories(dirname(dir))\n if (pathPresent(dir)) return false\n const { corpus, result } = readDigestSnapshot(input.committedRoot)\n if (result.kind !== 'digest') throw new TypeError('feedback corpus unavailable')\n const bundles = loadCassetteBundles(join(input.committedRoot, 'cassettes'))\n if (Object.keys(bundles.loadRefusals).length > 0) throw new TypeError('feedback cassette unavailable')\n const productIds = new Set(corpus.snapshot.entries.filter(entry => entry.product === input.product).map(entry => entry.cassetteId))\n return !bundles.loaded.some(({ cassette }) => cassette.granularity === 'leaf'\n && (productIds.has(cassette.id) || cassetteProductPartition(cassette) === input.product)\n && distilledScreenStateDigest(cassette.input.stateBefore) === input.stateDigest)\n}\n\nexport async function stageFeedbackEntry(input: StageFeedbackEntryInput): Promise<StageFeedbackEntryResult> {\n requireCorpusMask(input.mask, 'stageFeedbackEntry')\n let temporary: string | undefined\n try {\n const dir = feedbackDir(input)\n requireDirectories(dirname(dir))\n if (pathPresent(dir)) return { kind: 'already-staged' }\n if (!isNovelState(input)) return { kind: 'not-novel' }\n // Reuse the same pure extraction as Gate2, in memory; the old locator's write leg would\n // publish outside this staging directory.\n const handoff = loadCompletedRunHandoff(join(input.agentQaRoot, RUNS_SUBDIR, slugBranch(input.target.runId), HANDOFF_FILE))\n if (handoff.runId !== input.target.runId || resolveProductPartition(handoff.scope) !== input.product\n || handoff.tests.find(test => test.testId === input.target.testId)?.isRerun === true) return { kind: 'target-unavailable' }\n // 441 GAP3-D1: extract from the masked run. The digest comparisons below stay as they are, so a\n // target whose route or element names hold a declared value answers target-unavailable.\n const extraction = extractRunCassettes({ handoff: maskCorpusText(handoff, input.mask),\n artifacts: new FsRunArtifactSource({ root: input.agentQaRoot, runId: handoff.runId }) })\n const matches = extraction.cassettes.filter((entry): entry is ExtractedCassette & { cassette: LeafCassette } =>\n entry.cassette.granularity === 'leaf' && entry.cassette.runId === input.target.runId\n && entry.cassette.input.testId === input.target.testId && entry.cassette.stepIndex === input.target.stepIndex)\n if (matches.length !== 1) return { kind: 'target-unavailable' }\n const extracted = matches[0]!\n if (distilledScreenStateDigest(extracted.cassette.input.stateBefore) !== input.stateDigest) return { kind: 'target-unavailable' }\n const metadata = feedbackSchema.parse({ schemaVersion: 2, product: input.product, stateDigest: input.stateDigest,\n attributedObservationId: input.attributedObservationId, benefit: input.benefit, candidateId: input.candidateId,\n ...input.target, stagedAt: new Date().toISOString() })\n const texts = [committedFileText(extracted.cassette), committedFileText(metadata)]\n for (const blob of extracted.blobs) {\n if (!/^[0-9a-f]{64}$/.test(blob.sha) || createHash('sha256').update(blob.bytes).digest('hex') !== blob.sha) return { kind: 'target-unavailable' }\n }\n mkdirSync(dirname(dir), { recursive: true })\n temporary = mkdtempSync(join(dirname(dir), '.pending-'))\n writeFileSync(join(temporary, 'cassette.json'), texts[0]!, { flag: 'wx' })\n writeFileSync(join(temporary, 'feedback.json'), texts[1]!, { flag: 'wx' })\n if (extracted.blobs.length) mkdirSync(join(temporary, 'blobs'))\n for (const blob of extracted.blobs) writeFileSync(join(temporary, 'blobs', blob.sha), blob.bytes, { flag: 'wx' })\n // Rename only a fully validated bundle. Existing published bundles are nonempty and\n // cannot be replaced by rename; a competitor is reported without a successful stage count.\n if (pathPresent(dir)) return { kind: 'already-staged' }\n renameSync(temporary, dir)\n temporary = undefined\n return { kind: 'staged', dir }\n } catch (error) {\n if (['EEXIST', 'ENOTEMPTY'].includes((error as NodeJS.ErrnoException).code ?? '')) return { kind: 'write-conflict' }\n return { kind: 'target-unavailable' }\n } finally {\n if (temporary !== undefined) rmSync(temporary, { recursive: true, force: true })\n }\n}\n\nexport function listStagedFeedback(input: { agentQaRoot: string; product?: string }): StagedFeedbackEntry[] {\n if (!pathPresent(input.agentQaRoot)) return []\n const root = join(realpathSync(input.agentQaRoot), FEEDBACK_STAGING_SUBDIR)\n const products = input.product === undefined ? directoryNames(root) : [slugBranch(input.product)]\n const entries: StagedFeedbackEntry[] = []\n for (const productSlug of products) for (const stateDigest of directoryNames(join(root, productSlug))) {\n if (stateDigest.startsWith('.pending-')) continue\n const dir = feedbackDir({ agentQaRoot: input.agentQaRoot, product: productSlug, stateDigest })\n for (const name of ['feedback.json', 'cassette.json']) {\n if (!lstatSync(join(dir, name)).isFile()) throw new TypeError('unsafe feedback file')\n }\n const metadata = feedbackSchema.parse(JSON.parse(readFileSync(join(dir, 'feedback.json'), 'utf8')))\n if (slugBranch(metadata.product) !== productSlug || metadata.stateDigest !== stateDigest\n || (input.product !== undefined && input.product !== metadata.product)) throw new TypeError('feedback path identity mismatch')\n const bundle = loadCassetteBundle(dir)\n if (bundle.kind !== 'loaded' || bundle.cassette.granularity !== 'leaf') throw new TypeError('feedback cassette unavailable')\n const cassette = bundle.cassette\n if (cassette.runId !== metadata.runId || cassette.input.testId !== metadata.testId || cassette.stepIndex !== metadata.stepIndex\n || distilledScreenStateDigest(cassette.input.stateBefore) !== stateDigest) throw new TypeError('feedback provenance mismatch')\n const blobs = directoryNamesForBlobs(join(dir, 'blobs'))\n entries.push({ ...metadata, dir, extracted: { cassette, blobs } })\n }\n return entries\n}\nfunction directoryNamesForBlobs(dir: string): ExtractedCassette['blobs'] {\n requireDirectories(dir)\n if (!pathPresent(dir)) return []\n return readdirSync(dir, { withFileTypes: true }).map(entry => {\n if (!entry.isFile() || !/^[0-9a-f]{64}$/.test(entry.name)) throw new TypeError('invalid feedback blob')\n const bytes = readFileSync(join(dir, entry.name))\n if (createHash('sha256').update(bytes).digest('hex') !== entry.name) throw new TypeError('feedback blob mismatch')\n return { sha: entry.name, bytes }\n })\n}\n\nexport interface AdmitStagedFeedbackResult {\n entries: StagedFeedbackEntry[]\n admitted: StagedFeedbackEntry[]\n refusals: (SeedingRefusal & { product: string; runId: string })[]\n previousCorpusDigest: string\n nextCorpusDigest?: string\n writesStarted: boolean\n failures: {\n phase: 'write' | 'cleanup' | 'final-digest'\n reason: 'seeding-unavailable' | 'staging-cleanup-failed' | 'corpus-unavailable'\n cassetteId?: string\n product?: string\n runId?: string\n }[]\n}\nexport async function admitStagedFeedback(input: {\n agentQaRoot: string; committedRoot: string; product?: string; dryRun: boolean\n /** 441 GAP3-D1: required. A staged case still holding a declared value is refused by the writer. */\n mask: MaskFn\n}): Promise<AdmitStagedFeedbackResult> {\n requireCorpusMask(input.mask, 'admitStagedFeedback')\n const previous = readCommittedCorpusDigest(input)\n if (previous.kind !== 'digest') throw new TypeError('feedback corpus unavailable')\n const entries = listStagedFeedback(input)\n const batches = entries.map(entry => {\n const cassette = entry.extracted.cassette\n const plan: SeedingPlan = { product: entry.product, runId: entry.runId, runSlug: deriveRunSlug(entry.runId),\n cases: [{ cassetteId: cassette.id, labelRecord: projectSilverLabelRecord({ cassette, runId: entry.runId }),\n corpusEntry: projectCorpusEntry({ cassette, product: entry.product, runId: entry.runId,\n assignment: assignSplit({ cassetteId: cassette.id, isFeedbackEntry: true }),\n feedback: { attributedObservationId: entry.attributedObservationId, benefit: entry.benefit } }) }],\n pairSkips: [], silverExclusions: [], pairCounts: { total: 0, sameState: 0, differingState: 0 }, proceduresExcludedCount: 0 }\n return { plan, cassettes: [entry.extracted] }\n })\n const result: AdmitStagedFeedbackResult = { entries, admitted: [], refusals: [], previousCorpusDigest: previous.corpusDigest, writesStarted: false, failures: [] }\n if (input.dryRun) return result\n if (entries.length) {\n result.writesStarted = true\n let seeded: SeedingBatchReport | undefined\n try {\n seeded = seedCommittedCorpus({ batches, committedRoot: input.committedRoot, mask: input.mask })\n } catch {\n result.failures.push({ phase: 'write', reason: 'seeding-unavailable' })\n }\n // Even an interrupted bulk writer can have published cases. Verify each case's bytes;\n // neither aggregate counts nor a late exception are evidence of rollback.\n for (const [index, entry] of entries.entries()) {\n const report = seeded?.reports[index]\n result.refusals.push(...(report?.refusals ?? []).map(refusal => ({ ...refusal, product: entry.product, runId: entry.runId })))\n if (report?.refusals.length) continue\n const planCase = batches[index]!.plan.cases[0]!\n const id = entry.extracted.cassette.id\n const textParts = [\n [committedCassettePath(entry.product, id), entry.extracted.cassette],\n [committedCorpusPath(entry.product, id), planCase.corpusEntry],\n [committedLabelPath(entry.product, id), planCase.labelRecord],\n ] as const\n let verified = false\n try {\n verified = textParts.every(([path, value]) => readFileSync(join(input.committedRoot, path), 'utf8') === committedFileText(value))\n && entry.extracted.blobs.every(blob => readFileSync(join(input.committedRoot, committedBlobPath(entry.product, id, blob.sha))).equals(blob.bytes))\n } catch { /* A missing or unreadable part is not admission; retain its staged source. */ }\n if (!verified) {\n result.refusals.push({ cassetteId: id, kind: 'write-conflict', path: committedCorpusPath(entry.product, id), product: entry.product, runId: entry.runId })\n continue\n }\n result.admitted.push(entry)\n try { rmSync(entry.dir, { recursive: true }) } catch {\n result.failures.push({ phase: 'cleanup', reason: 'staging-cleanup-failed',\n cassetteId: id, product: entry.product, runId: entry.runId })\n }\n }\n }\n try {\n const next = readCommittedCorpusDigest(input)\n if (next.kind !== 'digest') throw new TypeError('feedback corpus unavailable')\n result.nextCorpusDigest = next.corpusDigest\n } catch {\n result.failures.push({ phase: 'final-digest', reason: 'corpus-unavailable' })\n }\n return result\n}\n\nexport interface AblateCanaryStepInput {\n agentQaRoot: string\n committedRoot: string\n recordId: string\n target: { runId: string; testId: string; stepIndex: number }\n /** The gate-2 audit sub-tree this ablation writes under. Slugged before it becomes a path. */\n attributedObservationId: string\n k: number\n baseSeed: number\n replay: ReplayBag\n /**\n * 2026-09-12, 422 D-18: WHICH removal rule authorizes this ablation.\n *\n * ABSENT keeps 418's opt-in served-canary flag, which is what every canary caller means and\n * what this function did unconditionally before — so no existing caller changes behaviour. The\n * pre-analysis circularity arbiter passes a D-18 authorization INSTEAD, because its subject is\n * an ORDINARY candidate that was never flagged a canary, and `resolveFailingPathCandidate`\n * recomputes the failing step, the served membership and the brief identity from the run's own\n * bytes before admitting it. The two are a sibling pair rather than one switch: the canary flag\n * is an opt-in and the authorization is positive proof.\n */\n admission?: {\n servedCanary?: true\n failingPathCandidate?: FailingPathCandidateAuthorization\n }\n}\nexport type CommittedCorpusDigestRead =\n | { kind: 'digest'; corpusDigest: string }\n | { kind: 'unavailable'; reason: 'corpus-unreadable'; detail: string }\nexport type AblateCanaryStepResult =\n | {\n kind: 'ablated'\n crossCheck: CrossCheck\n corpusDigest: string\n k: number\n baseSeed: number\n seeds: number[]\n seedHonored: boolean\n spend: { modelCalls: number; screens: number; promptTokens: number; completionTokens: number }\n gate2Dir: string\n notices: string[]\n }\n | {\n kind: 'unavailable'\n reason: 'target-unavailable' | 'brief-line-not-found' | 'no-live-decision' | 'corpus-unreadable'\n detail: string\n }\n\nfunction readDigestSnapshot(committedRoot: string) {\n const corpus = readCommittedCorpus(committedRoot)\n // 418 D-08: the general census reader accepts an absent tree as empty data. A gate\n // citation must establish the root itself, or a broken host could mint an empty digest.\n try {\n const marker = JSON.parse(readFileSync(join(committedRoot, COMMITTED_ROOT_MARKER_FILE), 'utf8'))\n if (marker?.schemaVersion !== buildRootMarkerValue().schemaVersion) {\n throw new Error('invalid eval root marker schemaVersion')\n }\n } catch (error) {\n return { corpus, result: { kind: 'unavailable', reason: 'corpus-unreadable',\n detail: error instanceof Error ? error.message : String(error),\n } as const }\n }\n const result: CommittedCorpusDigestRead =\n corpus.refusals.length > 0\n ? {\n kind: 'unavailable',\n reason: 'corpus-unreadable',\n detail: corpus.refusals.map((row) => `${row.path}: ${row.reason}`).join('\\n'),\n }\n : { kind: 'digest', corpusDigest: computeCorpusDigest(corpus.snapshot.entries) }\n return { corpus, result }\n}\n\n/** D-07: the same committed corpus definition the posture resolver cites, including negatives. */\nexport function readCommittedCorpusDigest(input: {\n committedRoot: string\n}): CommittedCorpusDigestRead {\n return readDigestSnapshot(input.committedRoot).result\n}\n\nexport async function ablateCanaryStep(\n input: AblateCanaryStepInput,\n): Promise<AblateCanaryStepResult> {\n // Validate before extraction or spend, using the canonical odd-k contract.\n deriveSampleSeeds(input.baseSeed, input.k)\n // One resolution, shared by sample one and by every subsequent sample (418 D-02): a second\n // spelling here would let the first arm admit a removal the rest of the cross-check refuses.\n const admission = input.admission ?? { servedCanary: true as const }\n const gate2Dir = join(\n input.agentQaRoot,\n GATE2_AUDIT_SUBDIR,\n slugBranch(input.attributedObservationId),\n )\n const { corpus, result: digest } = readDigestSnapshot(input.committedRoot)\n if (digest.kind === 'unavailable') return digest\n const located = await locateTargetCassettes({\n committedRoot: input.committedRoot,\n agentQaRoot: input.agentQaRoot,\n gate1Dir: gate2Dir,\n corpusEntries: corpus.snapshot.entries,\n target: input.target,\n source: 'handoff',\n })\n if (located.kind === 'unavailable')\n return {\n kind: 'unavailable',\n reason:\n located.detail.reason === 'no live decision at target'\n ? 'no-live-decision'\n : 'target-unavailable',\n detail: JSON.stringify(located.detail),\n }\n // The input identifies a step, not a sub-action. Never guess which decision earned credit.\n if (located.cassettes.length !== 1)\n return {\n kind: 'unavailable',\n reason: 'target-unavailable',\n detail: 'ambiguous live step: multiple recorded decisions',\n }\n const target = located.cassettes[0]!\n const { cassette, artifacts } = target\n // Extraction's sidecar.goldAction is the exact recorded SubActionEvidence.plannedAction.\n const action = cassette.sidecar.goldAction\n if (action === undefined)\n return { kind: 'unavailable', reason: 'no-live-decision', detail: 'recorded planned action absent' }\n const withRecord: ReplaySample = {\n sampleIndex: 0,\n durationMs: 0,\n outcome: {\n kind: 'decision',\n action,\n identity: computeDecisionIdentity(action, cassette.input.stateBefore.elements),\n },\n }\n const removal = resolveActiveRecordRemoval({\n cassette,\n recordId: input.recordId,\n ...(admission.servedCanary === undefined ? {} : { servedCanary: admission.servedCanary }),\n ...(admission.failingPathCandidate === undefined\n ? {}\n : { failingPathCandidate: admission.failingPathCandidate }),\n })\n if (removal.kind === 'unavailable')\n return { kind: 'unavailable', reason: 'brief-line-not-found', detail: removal.reason }\n const outputDir = join(gate2Dir, 'cross-check', 'without', 'sample-0', 'replays')\n let modelCalls = 0\n const firstReplay = await runCassetteReplay({\n ...input.replay,\n cassette: { ...cassette, input: applyBriefDelta(cassette.input, removal.delta) },\n artifacts,\n declaredBriefDelta: removal.delta,\n k: 1,\n seed: input.baseSeed,\n modelCallObservation: {\n onProviderCall: () => {\n modelCalls++\n input.replay.modelCallObservation?.onProviderCall?.()\n },\n },\n recordStore: new FsReplayRecordStore({ root: gate2Dir, outputDir }),\n scoreStore: new FsScoreStore({ root: gate2Dir, outputDir }),\n })\n const firstSample =\n 'granularity' in firstReplay && firstReplay.granularity === 'leaf'\n ? firstReplay.samples[0]\n : undefined\n const withoutRecord: ReplaySample = firstSample ?? {\n sampleIndex: 0,\n durationMs: 0,\n outcome: { kind: 'harness-error', message: 'replay produced no sample' },\n }\n const score = loadScoreRecord(join(outputDir, ...cassette.id.split('/').map(slugBranch)))\n const judgeCost =\n score.kind === 'loaded' && firstSample !== undefined\n ? buildEvalReport([\n { cassetteId: cassette.id, outcome: firstReplay, score: score.record.score },\n ]).honesty.judge.cost\n : { inputTokens: 0, outputTokens: 0 }\n const checked = await removalFlipsOutcome({\n recordId: input.recordId,\n cassettes: [target],\n mode: {\n kind: 'active-record',\n ...(admission.servedCanary === undefined ? {} : { servedCanary: admission.servedCanary }),\n },\n ...(admission.failingPathCandidate === undefined\n ? {}\n : { failingPathCandidate: admission.failingPathCandidate }),\n k: input.k,\n baseSeed: input.baseSeed,\n existing: { withRecord, withoutRecord },\n replay: input.replay,\n gate1Dir: gate2Dir,\n })\n if (\n checked.crossCheck === 'inconclusive' &&\n checked.notices.some((line) => line.startsWith('brief-line-not-found:'))\n )\n return { kind: 'unavailable', reason: 'brief-line-not-found', detail: checked.notices.join('\\n') }\n return {\n kind: 'ablated',\n crossCheck: checked.crossCheck,\n corpusDigest: digest.corpusDigest,\n k: input.k,\n baseSeed: input.baseSeed,\n seeds: checked.seeds,\n seedHonored: checked.seedHonored,\n spend: {\n modelCalls: modelCalls + checked.modelCalls,\n screens: 1 + checked.screens,\n promptTokens:\n (withoutRecord.tokenUsage?.promptTokens ?? 0) + judgeCost.inputTokens + checked.promptTokens,\n completionTokens:\n (withoutRecord.tokenUsage?.completionTokens ?? 0) + judgeCost.outputTokens + checked.completionTokens,\n },\n gate2Dir,\n notices: [\n 'with-record sample 1 is the recorded live decision; its seed was not replayed or verified. seedHonored describes fresh replay samples only.',\n ...checked.notices,\n ...(!checked.seedHonored\n ? ['seedHonored=false: fresh samples measure repeat variance on this provider']\n : []),\n ],\n }\n}\n","import { join } from 'node:path'\nimport type { StandaloneLabelRecord } from '@vostride/agent-qa-eval'\n\nimport type {\n ModelProfile,\n ModelProviderOverrides,\n ResolvedModelAuth,\n} from '@vostride/agent-qa-model'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nimport { loadCassetteBundle, type CassetteBundleLoad } from './cassette-loader.js'\nimport { runCassetteReplay, type RunCassetteReplayInput } from './replay-composition.js'\nimport { listCassetteBundleDirs } from './replay-read.js'\nimport type { FsReplayRecordStore } from './replay-record-store.js'\nimport type { FsScoreStore } from './score-store.js'\n\nexport type LoadedCassetteBundle = Extract<CassetteBundleLoad, { kind: 'loaded' }>\n\n/** Enumerate every bundle once, retaining load refusals as batch counters. */\nexport function loadCassetteBundles(cassettesRoot: string): {\n swept: number\n loaded: LoadedCassetteBundle[]\n loadRefusals: Record<string, number>\n} {\n const bundleDirs = listCassetteBundleDirs(cassettesRoot)\n const loadRefusals: Record<string, number> = {}\n const loaded: LoadedCassetteBundle[] = []\n for (const bundleDir of bundleDirs) {\n const load = loadCassetteBundle(bundleDir)\n if (load.kind === 'refused') {\n bumpCounter(loadRefusals, load.refusal.reason)\n continue\n }\n loaded.push(load)\n }\n return { swept: bundleDirs.length, loaded, loadRefusals }\n}\n\nexport interface SweepCassetteReplaysInput {\n /** Caller-selected order; whole-corpus callers sort by cassette id before sweeping. */\n selected: readonly LoadedCassetteBundle[]\n labelRecords?: ReadonlyMap<string, StandaloneLabelRecord>\n profile: ModelProfile\n auth: ResolvedModelAuth\n modelOverrides?: ModelProviderOverrides\n modelCallObservation?: RunCassetteReplayInput['modelCallObservation']\n clock?: RunCassetteReplayInput['clock']\n k?: number\n seed?: number\n judge?: RunCassetteReplayInput['judge']\n mask: RunCassetteReplayInput['mask']\n recordStore: FsReplayRecordStore\n scoreStore: FsScoreStore\n /** The explicit output root shared by the caller's record and score stores. */\n replaysRoot: string\n onProgress?: (cassetteId: string) => void\n}\n\nexport interface SweepCassetteReplaysResult {\n replayed: number\n replayRefusals: Record<string, number>\n replayedDirs: string[]\n /** Only invocations that returned and persisted this time, including typed refusals. */\n recordedDirs: string[]\n notices: string[]\n}\n\n/**\n * Run the selected batch through the one sanctioned replay composition. Persistence roots\n * come from the caller so repeat runs can retain independent records. Refusals and thrown\n * harness errors remain data; one broken cassette never aborts the rest of the batch.\n */\nexport async function sweepCassetteReplays(\n input: SweepCassetteReplaysInput,\n): Promise<SweepCassetteReplaysResult> {\n const replayRefusals: Record<string, number> = {}\n const replayedDirs: string[] = []\n const recordedDirs: string[] = []\n const notices: string[] = []\n let replayed = 0\n\n for (const entry of input.selected) {\n input.onProgress?.(entry.cassette.id)\n let outcome: Awaited<ReturnType<typeof runCassetteReplay>>\n try {\n outcome = await runCassetteReplay({\n cassette: entry.cassette,\n labelRecord: input.labelRecords?.get(entry.cassette.id),\n artifacts: entry.artifacts,\n profile: input.profile,\n auth: input.auth,\n ...(input.modelOverrides !== undefined ? { modelOverrides: input.modelOverrides } : {}),\n ...(input.modelCallObservation !== undefined ? { modelCallObservation: input.modelCallObservation } : {}),\n ...(input.clock !== undefined ? { clock: input.clock } : {}),\n ...(input.k !== undefined ? { k: input.k } : {}),\n ...(input.seed !== undefined ? { seed: input.seed } : {}),\n ...(input.judge !== undefined ? { judge: input.judge } : {}),\n mask: input.mask,\n recordStore: input.recordStore,\n scoreStore: input.scoreStore,\n })\n } catch (err) {\n bumpCounter(replayRefusals, 'harness-error')\n notices.push(\n `harness error replaying ${entry.cassette.id}: ${err instanceof Error ? err.message : String(err)}`,\n )\n continue\n }\n const recordDir = join(input.replaysRoot, ...entry.cassette.id.split('/').map(segment => slugBranch(segment)))\n recordedDirs.push(recordDir)\n if (!('granularity' in outcome)) {\n bumpCounter(replayRefusals, outcome.reason)\n continue\n }\n replayed++\n replayedDirs.push(recordDir)\n }\n\n return { replayed, replayRefusals, replayedDirs, recordedDirs, notices }\n}\n\nfunction bumpCounter(counters: Record<string, number>, reason: string): void {\n counters[reason] = (counters[reason] ?? 0) + 1\n}\n","// The ONE sanctioned replay-composition helper (Phase 368, D-04/D-05/D-06). This is the single\n// host binding that wires the pure eval-core replay engine to the production runner/model/safety\n// stack — eval-local deliberately becomes the SECOND package (after cli) importing both `model`\n// and `runner`, a contract-visible arch change recorded in ownership-contract.ts. Phase 372's\n// CLI wraps exactly this function.\n//\n// Composition law (RPLY-02):\n// - `createModel` is the ONLY egress path and the ONLY call site here — every replayed prompt\n// rides its pinned-last mask/guardrail middleware (validate:safety enforced). A FRESH\n// ModelProfile copy is built before the call because createModel mutates `profile.capabilities`\n// (RESEARCH Pitfall 8); the handle is shared across samples (RESEARCH A3).\n// - The replay planner runs at temperature 0 via the 366 sampling seam\n// (DeclaredModelProfile.sampling), with a FRESH createTokenAccounting + LLMPlanner per sample\n// (RESEARCH Pitfall 6) — the 368-01 `nonActionTools` ctor seam threads the recorded-exchange\n// server through unmodified production planner code.\n// - Model selection derives ONLY from the caller-supplied profile, never the recorded id (D-03):\n// recorded vs replayed ids are both stamped on the result, neither is enforced.\n// - Every model request is masked with the caller's declared mask (441 D-06).\n\nimport {\n adjudicateCassetteScore,\n assessJudgeEligibility,\n assessPanelEligibility,\n createPanelIdentity,\n buildDecisionDiff,\n computeReplayProfileFingerprint,\n createScoringContext,\n effectiveGold,\n neverEscalate,\n replayCassette,\n scoreCassetteReplay,\n} from '@vostride/agent-qa-eval'\nimport type {\n ArtifactSource,\n Cassette,\n CassetteScore,\n DecisionDiff,\n DeclaredBriefDelta,\n ReplayCassetteInput,\n ReplayCassetteOutcome,\n ReplayClock,\n ReplayEscalationPredicate,\n ReplayPlannerFactory,\n ReplayPlannerHandle,\n ReplayResult,\n SeedPolicy,\n StandaloneLabelRecord,\n ScoringJudgeRequest,\n} from '@vostride/agent-qa-eval'\nimport {\n createModel,\n createTokenAccounting,\n resolveCapabilities,\n} from '@vostride/agent-qa-model'\nimport type {\n ModelCallObservation,\n ModelProfile,\n ModelProviderOverrides,\n ResolvedModelAuth,\n} from '@vostride/agent-qa-model'\nimport { LLMPlanner, buildTools, defaultRegistry } from '@vostride/agent-qa-runner'\nimport type { DeclaredModelProfile, MaskFn, ScreenState } from '@vostride/agent-qa-schema'\n\nimport { bindJudgePanel, bindJudgePort } from './judge-binding.js'\nimport type { JudgeBindingInput } from './judge-binding.js'\nimport type { FsReplayRecordStore } from './replay-record-store.js'\nimport type { FsScoreStore } from './score-store.js'\n\ntype JudgeDeclaration = Omit<JudgeBindingInput, 'mask'>\n\nexport interface RunCassetteReplayInput {\n /** A loaded, guarded cassette (leaf or procedure) — normally from loadCassetteBundle. */\n cassette: Cassette\n /** Authoritative score metadata; never included in replayCassette's planner inputs. */\n labelRecord?: StandaloneLabelRecord\n /** 417 D-01 / 415 D-05: already applied by the caller; the engine reverses it only before hashing. */\n declaredBriefDelta?: DeclaredBriefDelta\n /** Blob source for full-capture screenshot reconstruction (normally a DirArtifactSource). */\n artifacts: ArtifactSource\n /** The currently-configured model profile — the SOLE source of model selection (D-03). */\n profile: ModelProfile\n /** Resolved provider auth for the configured model. */\n auth: ResolvedModelAuth\n /** Optional provider overrides — the captured-boundary stub seam for tests (createModel passthrough). */\n modelOverrides?: ModelProviderOverrides\n /** Whole-run counter shared by planner and judge, including provider retries. */\n modelCallObservation?: ModelCallObservation\n /** Optional deterministic timing port for repeatable measurement fixtures. */\n clock?: ReplayClock\n /** Sample budget (D-10). Defaults to the engine's k=1. */\n k?: number\n /** Optional replay seed applied through the 366 sampling seam when the provider supports it. */\n seed?: number\n /** k-sample escalation seam (D-10). Defaults to the imported neverEscalate — never re-minted. */\n escalationPredicate?: ReplayEscalationPredicate\n /** Optional persistence: when supplied, the outcome is saved after the replay returns (D-12). */\n recordStore?: FsReplayRecordStore\n /**\n * Optional D-13 score persistence: when supplied and the outcome is a ReplayResult (refusals are\n * never scored — reports count them instead), the score + per-decision diffs are computed in\n * eval core and saved AFTER recordStore.save (record-then-score ordering, OQ-2).\n */\n scoreStore?: FsScoreStore\n /**\n * Optional D-06 tier-4 judge bag: an EXPLICIT second ModelProfile plus its auth and stub seam\n * (372's CLI surfaces it as config). No auto-pick from configured models, no fallback scanning —\n * absence is a first-class configuration, in which case every unresolved tie is stamped\n * not-invoked{no-judge-configured} whenever the score leg runs (D-05/D-10).\n * allowSameFamily (owner override of D-10, 2026-07-12): explicit default-off opt-in threaded\n * verbatim into assessJudgeEligibility — it lifts ONLY known-same-family refusal and stamps\n * the D-16 identity block with familyOverride; unknown families stay forbidden.\n */\n judge?: (JudgeDeclaration & { allowSameFamily?: boolean }) |\n { members: readonly JudgeDeclaration[]; allowSameFamily?: boolean }\n mask: MaskFn\n}\n\n/** Persist the declared identity, including a refused panel; singletons retain old bytes. */\nexport function replayJudgeRequest(judge: RunCassetteReplayInput['judge']): ScoringJudgeRequest {\n if (judge === undefined) return null\n if ('members' in judge) {\n if (judge.members.length === 0) return null\n return { judgeModelId: createPanelIdentity(judge.members.map(member => member.profile.model)).judgeModelId,\n allowSameFamily: judge.members.length === 1 && judge.allowSameFamily === true }\n }\n return { judgeModelId: judge.profile.model, allowSameFamily: judge.allowSameFamily === true }\n}\n\n/** The platform the action-tool slice is derived for — the cassette's recorded observation platform. */\nfunction cassettePlatform(cassette: Cassette): ScreenState['platform'] {\n if (cassette.granularity === 'leaf') {\n return cassette.input.stateBefore.platform\n }\n for (const step of cassette.steps) {\n if (step.kind === 'decision') {\n return step.record.input.stateBefore.platform\n }\n }\n return 'web'\n}\n\nfunction isReplayResult(outcome: ReplayCassetteOutcome): outcome is ReplayResult {\n return 'granularity' in outcome\n}\n\n/**\n * The matcher-constitution stamp already minted inside the eval-core score — read for the persisted\n * record's attribution field, never computed here (F9).\n */\nfunction scoreMatcherVersion(score: CassetteScore): number {\n if (score.kind === 'shape-mismatch') return score.matcherVersion\n const entries =\n score.kind === 'leaf' ? [score.entry] : score.kind === 'procedure' ? score.entries : []\n for (const entry of entries) {\n if (entry.kind === 'decision') return entry.score.matcherVersion\n if (entry.kind === 'never-scored') return entry.matcherVersion\n }\n // Unreachable through this composition: refusal outcomes are guarded before scoring, and every\n // extracted cassette carries at least one decision entry.\n throw new Error('cassette score carries no matcher-version stamp')\n}\n\n/**\n * The recorded model identity from the cassette's reproducibility receipt — the D-14 recorded-side\n * eligibility input. Declared identity wins over the provider-resolved id; a procedure reads its\n * first decision record's receipt; absence is typed (the recorded side of the family check is then\n * skipped, D-14 \"when resolvable\").\n */\nfunction recordedReceiptModelId(cassette: Cassette): string | undefined {\n if (cassette.granularity === 'leaf') {\n return cassette.receipt.model.declared?.modelId ?? cassette.receipt.model.resolvedModelId\n }\n for (const step of cassette.steps) {\n if (step.kind === 'decision') {\n return (\n step.record.receipt.model.declared?.modelId ?? step.record.receipt.model.resolvedModelId\n )\n }\n }\n return undefined\n}\n\n/**\n * Orchestrate eval core's buildDecisionDiff over every scored decision entry — joining each entry\n * back to its recorded sidecar/elements and its replayed decision result. Pure plumbing: the diff\n * content itself is computed entirely in eval core (F9).\n */\nfunction decisionDiffs(\n cassette: Cassette,\n outcome: ReplayResult,\n score: CassetteScore,\n): DecisionDiff[] {\n if (score.kind === 'leaf') {\n if (cassette.granularity !== 'leaf' || outcome.granularity !== 'leaf') return []\n const entry = score.entry\n if (entry.kind !== 'decision') return []\n return [\n buildDecisionDiff({\n cassetteId: cassette.id,\n decisionOrdinal: entry.decisionOrdinal,\n sidecar: cassette.sidecar,\n elements: cassette.input.stateBefore.elements,\n result: outcome,\n score: entry.score,\n }),\n ]\n }\n\n if (score.kind !== 'procedure') return []\n if (cassette.granularity !== 'procedure' || outcome.granularity !== 'procedure') return []\n const diffs: DecisionDiff[] = []\n for (const entry of score.entries) {\n if (entry.kind !== 'decision') continue\n const step = outcome.steps.find(\n candidate =>\n candidate.kind === 'decision' &&\n candidate.stepIndex === entry.stepIndex &&\n candidate.decisionOrdinal === entry.decisionOrdinal,\n )\n const record = cassette.steps.find(\n candidate =>\n candidate.kind === 'decision' &&\n candidate.stepIndex === entry.stepIndex &&\n candidate.decisionOrdinal === entry.decisionOrdinal,\n )\n if (step?.kind !== 'decision' || record?.kind !== 'decision') continue\n diffs.push(\n buildDecisionDiff({\n cassetteId: cassette.id,\n ...(entry.stepIndex === undefined ? {} : { stepIndex: entry.stepIndex }),\n decisionOrdinal: entry.decisionOrdinal,\n sidecar: record.record.sidecar,\n elements: record.record.input.stateBefore.elements,\n result: step.result,\n score: entry.score,\n }),\n )\n }\n return diffs\n}\n\n/**\n * Name the resolved temperature-zero replay profile without auth resolution or model creation.\n * D-11: keep these inputs aligned with the single createModel site below. Override names are\n * the injected provider identities; seed values and provider disclosures never enter the key.\n */\nexport function computeReplayProfileFingerprintFor(input: {\n profile: ModelProfile\n seedPolicy: SeedPolicy\n modelOverrides?: ModelProviderOverrides\n}): string {\n const profileCopy: ModelProfile = {\n ...input.profile,\n ...(input.profile.capabilities !== undefined\n ? { capabilities: { ...input.profile.capabilities } }\n : {}),\n }\n const capabilities = resolveCapabilities(profileCopy)\n return computeReplayProfileFingerprint({\n provider: input.profile.provider,\n modelId: input.profile.model,\n temperature: 0,\n seedPolicy: input.seedPolicy,\n capabilities: {\n vision: capabilities.vision,\n ...(capabilities.maxOutput !== undefined ? { maxOutputTokens: capabilities.maxOutput } : {}),\n },\n modelOverrideKeys: Object.keys(input.modelOverrides?.languageModels ?? {}).sort(),\n })\n}\n\n/**\n * Run one loaded cassette through the pure replay engine bound to the production planner/model/\n * safety stack, optionally persisting the typed outcome. The one sanctioned model+runner\n * composition in eval-local (D-04).\n */\nexport async function runCassetteReplay(\n input: RunCassetteReplayInput,\n): Promise<ReplayCassetteOutcome> {\n // Fresh ModelProfile copy: createModel mutates `profile.capabilities` (RESEARCH Pitfall 8), so\n // the caller's object is never touched and the one call site owns its own copy.\n const profileCopy: ModelProfile = {\n ...input.profile,\n ...(input.profile.capabilities !== undefined\n ? { capabilities: { ...input.profile.capabilities } }\n : {}),\n }\n const capabilities = resolveCapabilities(profileCopy)\n\n // Temp-0 declared profile via the 366 sampling seam — model identity comes ONLY from the caller\n // profile (D-03), sampling pins temperature 0 with an optional caller-supplied seed.\n const replayProfile: DeclaredModelProfile = {\n provider: input.profile.provider,\n modelId: input.profile.model,\n vision: capabilities.vision,\n maxOutputTokens: capabilities.maxOutput,\n sampling: { temperature: 0, ...(input.seed !== undefined ? { seed: input.seed } : {}) },\n }\n\n // The ONLY createModel call site and the ONLY egress path. The handle is shared across samples\n // (RESEARCH A3); per-sample freshness is confined to accounting + planner + exchange server.\n // D-11: computeReplayProfileFingerprintFor must read these same resolved profile values.\n const model = createModel(profileCopy, input.auth, input.mask, input.modelOverrides ?? {}, input.modelCallObservation)\n const replayedModel = { provider: input.profile.provider, modelId: input.profile.model }\n\n const plannerFactory: ReplayPlannerFactory = {\n create({ platform, nonActionTools }): ReplayPlannerHandle {\n // Fresh accounting per sample so clamp/degrade + per-sample token cost stay attributable.\n const accounting = createTokenAccounting({\n getCapabilities: () => resolveCapabilities(profileCopy),\n })\n // Fresh unmodified LLMPlanner per sample; the 368-01 nonActionTools ctor seam threads the\n // recorded-exchange server through the real bounded tool-loop.\n const planner = new LLMPlanner(\n model,\n platform,\n undefined,\n undefined,\n accounting,\n replayProfile,\n nonActionTools,\n )\n return {\n plan: (stepText, screenState, context) => planner.plan(stepText, screenState, context),\n model,\n replayedModel,\n }\n },\n }\n\n // The action slice a recorded exchange may never shadow (RESEARCH Open Q2): derived here in the\n // host from buildTools so the engine stays pure. plan() rebuilds the same slice internally.\n const actionToolNames: ReadonlySet<string> = new Set(\n Object.keys(buildTools(defaultRegistry, { platform: cassettePlatform(input.cassette) })),\n )\n\n // Host wall-clock behind the eval-core ReplayClock port (eval core bans host time APIs).\n const clock: ReplayClock = input.clock ?? { now: () => performance.now() }\n\n const engineInput: ReplayCassetteInput = {\n cassette: input.cassette,\n artifacts: input.artifacts,\n plannerFactory,\n actionToolNames,\n clock,\n ...(input.k !== undefined ? { k: input.k } : {}),\n ...(input.declaredBriefDelta !== undefined ? { declaredBriefDelta: input.declaredBriefDelta } : {}),\n escalationPredicate: input.escalationPredicate ?? neverEscalate,\n }\n\n const outcome: ReplayCassetteOutcome = await replayCassette(engineInput)\n\n if (input.recordStore !== undefined) {\n input.recordStore.save(outcome)\n }\n\n // Write ordering is strict and load-bearing (OQ-2/D-05, Pitfall 2): recordStore.save → score\n // (sync, eval core) → adjudicate (async) → diffs over the FINAL score →\n // exactly ONE scoreStore.save. The record store recreates the cassette dir in full (rm + mkdir),\n // so the file-scoped score write MUST land after it — never before — or a re-run would wipe the\n // fresh score.json. Refusals save a record but never a score (they are counted in reports\n // instead). Score, adjudication, and diffs are computed in eval core (F9); this composition\n // only orchestrates and saves.\n if (input.scoreStore !== undefined && isReplayResult(outcome)) {\n const score = scoreCassetteReplay(input.cassette, outcome, input.labelRecord)\n const effective = input.cassette.granularity === 'leaf' ? effectiveGold(input.cassette, input.labelRecord) : undefined\n const scoringCassette = effective?.kind === 'eligible' ? effective.cassette : input.cassette\n\n // D-12/D-14 two-sided family eligibility, assessed ONCE at composition time against BOTH the\n // replayed profile's model and the cassette receipt's recorded identity. Ineligible ⇒ the\n // judge port never binds and the batch proceeds deterministically (soft-but-loud: the refusal\n // is data on every tie's stamp, never a thrown error).\n const recordedModelId = recordedReceiptModelId(input.cassette)\n const declaration = input.judge\n const members = declaration !== undefined && 'members' in declaration ? declaration.members : undefined\n const single = members === undefined ? declaration as (JudgeDeclaration & { allowSameFamily?: boolean }) | undefined\n : members.length === 1 ? { ...members[0], allowSameFamily: declaration?.allowSameFamily } : undefined\n const panel = members !== undefined && members.length > 1 ? members : undefined\n const eligibilityInput = {\n replayedModelId: input.profile.model,\n ...(recordedModelId !== undefined ? { recordedModelId } : {}),\n ...(declaration?.allowSameFamily !== undefined\n ? { allowSameFamily: declaration.allowSameFamily }\n : {}),\n }\n const eligibility = panel === undefined\n ? assessJudgeEligibility({ ...eligibilityInput, judgeModelId: single?.profile.model })\n : assessPanelEligibility({ ...eligibilityInput, memberModelIds: panel.map(member => member.profile.model) })\n const observedBinding = (member: JudgeDeclaration): JudgeBindingInput => {\n const hooks = [...new Set([\n input.modelCallObservation?.onProviderCall,\n member.modelCallObservation?.onProviderCall,\n ].filter(hook => hook !== undefined))]\n return { ...member, mask: input.mask, modelCallObservation: { onProviderCall: () => {\n for (const hook of hooks) {\n try { hook() } catch { /* Observation cannot interrupt another counter or provider call. */ }\n }\n } } }\n }\n const port = !eligibility.eligible ? undefined : panel !== undefined\n ? bindJudgePanel(panel.map(observedBinding))\n : single === undefined ? undefined\n : bindJudgePort(observedBinding(single))\n\n // Adjudication runs UNCONDITIONALLY so every tie is stamped with its disposition even when\n // no port exists (D-06/D-10/D-12); the pure scoreCassetteReplay output itself stays untouched.\n const adjudicated = await adjudicateCassetteScore({\n cassette: scoringCassette,\n outcome,\n score,\n eligibility,\n ...(port !== undefined ? { port } : {}),\n })\n\n input.scoreStore.save({\n cassetteId: input.cassette.id,\n matcherVersion: scoreMatcherVersion(adjudicated.score),\n score: adjudicated.score,\n diffs: decisionDiffs(scoringCassette, outcome, adjudicated.score),\n scoringContext: createScoringContext({ cassette: input.cassette, outcome, labelRecord: input.labelRecord,\n ...adjudicated, judgeRequest: replayJudgeRequest(input.judge) }),\n ...(adjudicated.judge !== undefined ? { judge: adjudicated.judge } : {}),\n })\n }\n\n return outcome\n}\n","// The eval-local JudgePort binding (Phase 370 D-05/D-06, JUDGE-03). The pure eval-core judge\n// module builds every prompt; this binding ONLY transports: one createModel handle (the pinned-last\n// mask/guardrail middleware stack — the sole egress path, exactly like runCassetteReplay's planner\n// leg) executes one generateText + Output.object structured verdict per order-tagged request at\n// temperature 0 with maxRetries 0. Structured-output repair is the model package's middleware job\n// (repair + extract-json in createModel's stack) — no second application-level retry loop exists\n// here (D-08/D-11). The port NEVER throws: unparseable output and provider failure each mint a\n// typed call-error (D-09/D-11). Invoked only from runCassetteReplay's flow (the ownership\n// contract's forbidden provider-invocation clause); 370-07 composes it inside the safety scope.\n\nimport { NoObjectGeneratedError, NoOutputGeneratedError, Output, generateText } from 'ai'\nimport type { SystemModelMessage } from 'ai'\nimport { z } from 'zod'\n\nimport type {\n JudgePanelPort,\n JudgeCallResult,\n JudgePort,\n JudgeTokenUsage,\n} from '@vostride/agent-qa-eval'\nimport { createPanelIdentity } from '@vostride/agent-qa-eval'\nimport { createModel } from '@vostride/agent-qa-model'\nimport type {\n ModelCallObservation,\n ModelProfile,\n ModelProviderOverrides,\n ResolvedModelAuth,\n} from '@vostride/agent-qa-model'\nimport type { MaskFn } from '@vostride/agent-qa-schema'\n\nexport interface JudgeBindingInput {\n /** The judge model profile — a SECOND profile, never the replay planner's (D-12 disjointness). */\n profile: ModelProfile\n /** Resolved provider auth for the judge model. */\n auth: ResolvedModelAuth\n /** Optional provider overrides — the captured-boundary stub seam for tests (createModel passthrough). */\n modelOverrides?: ModelProviderOverrides\n modelCallObservation?: ModelCallObservation\n mask: MaskFn\n}\n\n/** N existing bindings in declaration order, each retaining bindJudgePort's fresh copy. */\nexport function bindJudgePanel(inputs: readonly JudgeBindingInput[]): JudgePanelPort {\n return { judgeModelId: createPanelIdentity(inputs.map(input => input.profile.model)).judgeModelId,\n members: inputs.map(bindJudgePort) }\n}\n\n// The closed D-09 verdict schema: forced explicit-unsure vocabulary + categorical confidence.\n// Output.object validates against it inside generateText; the safeParse below re-checks the\n// resolved output defensively (never trust free text — the verifier's D-06 posture).\nconst verdictSchema = z.object({\n verdict: z.enum(['equivalent', 'different', 'unsure']),\n confidence: z.enum(['high', 'medium', 'low']),\n rationale: z.string(),\n})\n\nconst verdictOutput = Output.object({\n schema: verdictSchema,\n name: 'judge_verdict',\n description: 'Equivalence verdict, confidence category, and rationale for the judged pair',\n})\n\n/**\n * Bind the tier-4 JudgePort over the production createModel recipe: a fresh ModelProfile copy\n * (createModel mutates `profile.capabilities` — RESEARCH Pitfall 8), ONE handle built at bind\n * time and shared across calls, model identity from the caller profile only.\n */\nexport function bindJudgePort(input: JudgeBindingInput): JudgePort {\n const profileCopy: ModelProfile = {\n ...input.profile,\n ...(input.profile.capabilities !== undefined\n ? { capabilities: { ...input.profile.capabilities } }\n : {}),\n }\n // The ONLY createModel call site for the judge leg and its ONLY egress path (JUDGE-03).\n const model = createModel(profileCopy, input.auth, input.mask, input.modelOverrides ?? {}, input.modelCallObservation)\n\n return {\n judgeModelId: input.profile.model,\n async call(request): Promise<JudgeCallResult> {\n try {\n // The judge's byte-stable system tier arrives pre-built from JUDGE_CONFIG — it forms its\n // own cache identity, so the single Anthropic ephemeral breakpoint rides it exactly as\n // the verifier's stable tier does (a transparent no-op on other providers).\n const system: SystemModelMessage[] = [\n {\n role: 'system',\n content: request.system,\n providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } },\n },\n ]\n // temperature 0 through the same mechanism the replay planner rides: passed on the call,\n // stripped by stripUnsupportedParamsMiddleware inside createModel's stack for providers\n // that reject the setting. The prompt is transported verbatim (D-15: templates stay\n // hash-covered pure-side — the binding never assembles or edits prompt content).\n const result = await generateText({\n model,\n maxRetries: 0,\n temperature: 0,\n output: verdictOutput,\n system,\n messages: [{ role: 'user', content: [{ type: 'text', text: request.prompt }] }],\n })\n const parsed = verdictSchema.safeParse(result.output)\n if (!parsed.success) {\n return {\n kind: 'call-error',\n reason: 'unparseable-output',\n detail: 'judge output failed the closed verdict schema',\n }\n }\n const usage: JudgeTokenUsage = {\n calls: 1,\n // Typed-absent token fields: omit what the provider did not report, never zero-fill.\n ...(result.usage.inputTokens !== undefined\n ? { inputTokens: result.usage.inputTokens }\n : {}),\n ...(result.usage.outputTokens !== undefined\n ? { outputTokens: result.usage.outputTokens }\n : {}),\n }\n return {\n kind: 'verdict',\n verdict: parsed.data.verdict,\n confidence: parsed.data.confidence,\n rationale: parsed.data.rationale,\n usage,\n }\n } catch (error: unknown) {\n // generateText parses Output.object EAGERLY: text that is not valid verdict JSON (after\n // the middleware's extract/repair pass) throws NoObjectGeneratedError from the call\n // itself, and a non-stop finish surfaces as NoOutputGeneratedError at output resolution.\n // Both are the model failing to produce a verdict — unparseable-output, not infra.\n if (NoObjectGeneratedError.isInstance(error) || NoOutputGeneratedError.isInstance(error)) {\n return {\n kind: 'call-error',\n reason: 'unparseable-output',\n detail: 'judge output failed the closed verdict schema',\n }\n }\n return {\n kind: 'call-error',\n reason: 'provider-error',\n detail: 'judge provider call failed',\n }\n }\n },\n }\n}\n","import { buildEvalReport, canonicalJson, decisionCorrectnessVectors, judgeIdentitySchema, resolveProductPartition, resolveScoringContext } from '@vostride/agent-qa-eval'\nimport type {\n Cassette,\n CassetteLabelLeg,\n CassetteScore,\n JudgeIdentityBlock,\n ScoredBatchEntry,\n StandaloneLabelRecord,\n ScoringJudgeRequest,\n CorpusEntry,\n EvalBatchReport,\n} from '@vostride/agent-qa-eval'\n\nimport { loadCassetteBundle } from './cassette-loader.js'\nimport type { JudgeCalibrationRead } from './judge-calibration-source.js'\nimport { sha256hex } from '@vostride/agent-qa-schema'\nimport { loadStagedReport, type ReplayGeneration } from './report-store.js'\nimport {\n listCassetteBundleDirs,\n listReplayRecordDirs,\n loadReplayRecord,\n loadScoreRecord,\n} from './replay-read.js'\n\n/**\n * Resolve the product partition from the recorded served-brief scope. Procedures read their\n * first decision record; a cassette with no decision maps to the typed 'default' partition.\n */\nexport function cassetteProductPartition(cassette: Cassette): string {\n if (cassette.granularity === 'leaf') {\n return resolveProductPartition(cassette.input.servedBrief.scope)\n }\n for (const step of cassette.steps) {\n if (step.kind === 'decision') {\n return resolveProductPartition(step.record.input.servedBrief.scope)\n }\n }\n return 'default'\n}\n\n/**\n * Assemble report inputs from the caller's replay root, joining labels and product partitions\n * from cassette bundles. Scores and judge blocks come only from persisted records; every\n * replay remains an entry, including a record that can only be read as a typed refusal.\n */\nexport function assembleScoredBatch(input: {\n replaysRoot: string\n cassettesRoot: string\n source: string\n /** Fresh-run callers supply only completed writes; absence retains the generic disk sweep. */\n recordDirs?: readonly string[]\n /** Committed-corpus ownership is authoritative; generic callers retain scope semantics. */\n productByCassetteId?: ReadonlyMap<string, string>\n /** Latest committed mark generations only; historical bundles remain on disk. */\n eligibleCassetteIds?: ReadonlySet<string>\n labelRecords?: ReadonlyMap<string, StandaloneLabelRecord>\n corpusEntriesById?: ReadonlyMap<string, CorpusEntry>\n excludedLabelIds?: ReadonlySet<string>\n calibration?: EvalBatchReport['calibration']\n expectedJudgeRequest?: ScoringJudgeRequest\n}): {\n entries: ScoredBatchEntry[]\n judgeBlocks: JudgeIdentityBlock[]\n partitionsById: Map<string, string>\n missingBundleCount: number\n notices: string[]\n calibration?: EvalBatchReport['calibration']\n} {\n const { replaysRoot, cassettesRoot, source } = input\n const notices: string[] = []\n\n // Only leaf cassettes carry a label leg; procedures join with partition only.\n const labelsById = new Map<string, CassetteLabelLeg>()\n const cassettesById = new Map<string, Cassette>()\n const partitionsById = new Map<string, string>()\n for (const bundleDir of listCassetteBundleDirs(cassettesRoot)) {\n const load = loadCassetteBundle(bundleDir)\n if (load.kind === 'refused') {\n notices.push(`${source} bundle read refused under ${bundleDir}: ${load.refusal.detail}`)\n continue\n }\n if (input.eligibleCassetteIds !== undefined && !input.eligibleCassetteIds.has(load.cassette.id)\n && !input.excludedLabelIds?.has(load.cassette.id)) continue\n if (load.cassette.granularity === 'leaf') {\n labelsById.set(load.cassette.id, input.labelRecords?.get(load.cassette.id)?.label ?? load.cassette.label)\n }\n cassettesById.set(load.cassette.id, load.cassette)\n const product = input.corpusEntriesById?.get(load.cassette.id)?.product ?? (input.productByCassetteId === undefined\n ? cassetteProductPartition(load.cassette)\n : input.productByCassetteId.get(load.cassette.id))\n if (product === undefined && !input.excludedLabelIds?.has(load.cassette.id)) throw new TypeError(`committed product absent for ${load.cassette.id}`)\n if (product !== undefined) partitionsById.set(load.cassette.id, product)\n }\n\n const entries: ScoredBatchEntry[] = []\n const judgeBlocks: JudgeIdentityBlock[] = []\n let missingBundleCount = 0\n for (const recordDir of input.recordDirs ?? listReplayRecordDirs(replaysRoot)) {\n const load = loadReplayRecord(recordDir)\n const outcome = load.kind === 'loaded' ? load.outcome : load.refusal\n if (load.kind === 'refused') {\n notices.push(`replay record read refused under ${recordDir}: ${load.refusal.detail}`)\n }\n const cassetteId = outcome.cassetteId\n if (input.eligibleCassetteIds !== undefined && !input.eligibleCassetteIds.has(cassetteId)\n && !input.excludedLabelIds?.has(cassetteId)) continue\n\n let score: CassetteScore | undefined\n const scoreLoad = loadScoreRecord(recordDir)\n if (scoreLoad.kind === 'loaded') {\n score = scoreLoad.record.score\n } else if (scoreLoad.kind === 'refused') {\n notices.push(`score read refused under ${recordDir}: ${scoreLoad.refusal.detail}`)\n }\n\n const label = labelsById.get(cassetteId)\n const authoritative = input.labelRecords?.get(cassetteId)\n const scoringExcluded = input.excludedLabelIds?.has(cassetteId) === true\n || authoritative?.quarantine !== undefined\n const corpusEntry = input.corpusEntriesById?.get(cassetteId)\n const cassette = cassettesById.get(cassetteId)\n const resolved = cassette === undefined ? undefined : resolveScoringContext({ cassette, outcome,\n labelRecord: authoritative, scoringExcluded, expectedJudgeRequest: input.expectedJudgeRequest,\n record: scoreLoad.kind === 'loaded' ? scoreLoad.record : undefined })\n if (resolved !== undefined) score = resolved.score\n if (scoringExcluded) score = undefined\n if (!scoringExcluded && scoreLoad.kind === 'loaded' && resolved?.compatible !== false && scoreLoad.record.judge !== undefined) {\n judgeBlocks.push(scoreLoad.record.judge)\n }\n const product = partitionsById.get(cassetteId)\n if (!partitionsById.has(cassetteId)) missingBundleCount++\n const incurredJudgeScore = resolved?.incurredJudgeScore\n ?? (scoringExcluded && scoreLoad.kind === 'loaded' ? scoreLoad.record.score : undefined)\n\n entries.push({\n cassetteId,\n logicalSourceId: authoritative?.provenance.sourceCassetteId ?? cassetteId,\n ...(authoritative?.weight === undefined ? {} : { softWeight: authoritative.weight }),\n ...(scoringExcluded ? { scoringExcluded: true } : {}),\n ...(corpusEntry === undefined ? {} : { split: corpusEntry.split,\n ...(corpusEntry.split !== 'held-out' ? {} : { heldOutVisibility: corpusEntry.heldOutVisibility }),\n // 2026-09-12, 422 D-05/D-11: the generator stamp travels with the split it belongs to,\n // read off the SAME committed entry. An entry this assembler could not resolve carries\n // neither, so the report discloses its generation as unavailable rather than absent.\n ...(corpusEntry.split !== 'adversarial' ? {} : { generator: corpusEntry.generator }) }),\n outcome,\n ...(score !== undefined ? { score } : {}),\n ...(incurredJudgeScore === undefined ? {} : { incurredJudgeScore }),\n ...(label !== undefined ? { label } : {}),\n ...(product !== undefined ? { product } : {}),\n })\n }\n\n return { entries, judgeBlocks, partitionsById, missingBundleCount, notices, calibration: input.calibration }\n}\n\n/** The same report/vector projection serves fresh replay and guarded measured-run recovery. */\nexport function projectAssembledBatch(\n batch: ReturnType<typeof assembleScoredBatch>,\n options: Parameters<typeof buildEvalReport>[3],\n) {\n const { entries, partitionsById } = batch\n // Compare only the score identity contract. Later report disclosure (such as copied\n // calibration) is not part of the identity that produced these decisions.\n const judgeBlocks = batch.judgeBlocks.map(block => judgeIdentitySchema.strip().parse(block))\n if (entries.some(entry => entry.split === undefined)) {\n batch.notices.push('corpus split ownership unknown; entries without corpus metadata are unassigned')\n }\n entries.sort((a, b) => a.cassetteId < b.cassetteId ? -1 : a.cassetteId > b.cassetteId ? 1 : 0)\n let judge: JudgeIdentityBlock | undefined\n let identity: { judgeIdentity: 'mixed'; judgeModelIds: readonly string[] } | undefined\n if (judgeBlocks.length === 0) {\n batch.notices.push('no judge identity on any persisted score record — the report carries no judge block')\n } else if (judgeBlocks.every(block => canonicalJson(block) === canonicalJson(judgeBlocks[0]))) {\n judge = judgeBlocks[0]\n } else {\n identity = { judgeIdentity: 'mixed',\n judgeModelIds: [...new Set(judgeBlocks.map(block => block.judgeModelId))].sort() }\n batch.notices.push('mixed judge identities across persisted score records — the report carries no judge block')\n }\n return {\n report: buildEvalReport(entries, judge, identity, { ...options, calibration: options?.calibration ?? batch.calibration }),\n vectors: decisionCorrectnessVectors(entries, partitionsById),\n notices: batch.notices,\n }\n}\n\n/** Attach disclosure only after the caller has compared persisted score identities. */\nexport function copyJudgeCalibrationToReport(report: EvalBatchReport, read?: JudgeCalibrationRead): void {\n if (report.judgeIdentity === 'mixed' || report.judge?.panelSize === undefined) return\n const artifact = read?.kind === 'loaded' ? read.artifact : undefined\n const calibration: NonNullable<EvalBatchReport['judge']>['calibration'] = !artifact\n ? { status: 'uncalibrated', n: 0, provenance: 'unavailable' }\n : artifact.status === 'capability-gap' ? { status: 'capability-gap', reason: artifact.reason }\n : artifact.status === 'uncalibrated' ? { status: 'uncalibrated', n: artifact.n }\n : { status: 'calibrated', n: artifact.n, pooledAgreement: artifact.pooledAgreement!,\n wilson95: { ...artifact.wilson95! }, perMember: artifact.perMember.map(member => ({\n judgeModelId: member.judgeModelId, n: member.n,\n ...(member.agreement === undefined ? {} : { agreement: member.agreement }),\n ...(member.wilson95 === undefined ? {} : { wilson95: { ...member.wilson95 } }),\n })) }\n report.judge = { ...report.judge, calibration }\n}\n\n/** Existing producer publication must bind the full profile to these exact saved inputs. */\nexport function readReportProfileProof(input: {\n agentQaRoot: string\n replaysRoot: string\n report: EvalBatchReport\n entries: readonly ScoredBatchEntry[]\n fingerprint: string\n corpusDigest: string\n seed?: number\n}): { runIdentity: NonNullable<EvalBatchReport['runIdentity']>; replayGeneration: ReplayGeneration } | undefined {\n // Legacy standalone replays have no full-profile publication. A model ID is insufficient.\n if (input.seed === undefined || input.entries.length === 0) return undefined\n const loaded = loadStagedReport(input.agentQaRoot, input.report.batchKey)\n if (loaded.kind !== 'loaded' || !loaded.replayGeneration) return undefined\n const { report, replayGeneration } = loaded\n if (report.runIdentity?.fingerprint !== input.fingerprint\n || report.runIdentity.corpusDigest !== input.corpusDigest\n || report.matcherVersion !== input.report.matcherVersion\n || report.judgeIdentity === 'mixed'\n || canonicalJson(report.judge && judgeIdentitySchema.strip().parse(report.judge))\n !== canonicalJson(input.report.judge)\n || replayGeneration.seed !== input.seed\n || replayGeneration.records.length !== input.entries.length) return undefined\n const records = listReplayRecordDirs(input.replaysRoot).map(dir => ({\n replay: loadReplayRecord(dir), score: loadScoreRecord(dir),\n }))\n for (const entry of input.entries) {\n const refs = replayGeneration.records.filter(ref => ref.cassetteId === entry.cassetteId)\n const matching = records.filter(row => row.replay.kind === 'loaded' && row.replay.outcome.cassetteId === entry.cassetteId)\n if (refs.length !== 1 || matching.length !== 1) return undefined\n const row = matching[0]!, ref = refs[0]!\n if (row.replay.kind !== 'loaded' || row.score.kind !== 'loaded'\n || canonicalJson(row.replay.outcome) !== canonicalJson(entry.outcome)\n || Reflect.get(row.replay.outcome, 'executionSeed') !== input.seed\n || sha256hex(canonicalJson(row.replay.outcome)) !== ref.replayDigest\n || sha256hex(canonicalJson(row.score.record)) !== ref.scoreDigest) return undefined\n }\n return { runIdentity: report.runIdentity, replayGeneration }\n}\n","// The ONE sanctioned seeding-composition helper (Phase 371, ROOT-02/D-13/D-14/D-15/D-16/D-17) —\n// sibling of runCassetteReplay, same recipe. It EXECUTES a pure eval-core SeedingPlan against the\n// write-once committed root and returns a typed SeedingReport; it never selects, labels, or\n// re-decides (the planner is the only decision-maker, D-16). Phase 372's CLI wraps exactly this\n// function.\n//\n// Composition law (ROOT-02):\n// - Every committed TEXT write — gitignore, root marker, contracts projections, cassette, label\n// record, corpus entry — is committed as authored (441 D-15: no egress check). 441 GAP3-D1: a\n// case's D-18 text (step text, screen state, planned action) is masked with the declared\n// secrets before the case is built (maskCorpusText over the handoff, before extraction), and\n// this writer requires that mask and refuses a case any of whose committed strings it would\n// still change (`unmasked-declared-value`). The declared mask is the only check.\n// - The atomic unit is the CASE: cassette + label record + corpus entry land together or not at\n// all, and a refused case never aborts the batch (D-14).\n// - Write-once (D-17): all of a case's text paths are PREVIEWED against the store before any\n// write; a conflict on ANY file refuses the whole case before anything lands. Byte-identical\n// re-seeding reports 'unchanged' everywhere and mutates nothing.\n// - Blob bytes land only under ignore-covered blobs/ paths after the store's sha-format +\n// byte-hash verification (D-15). A\n// blob verification refusal surfaces as the same typed write-conflict — never silent.\n// - Every committed text is serialized by eval core's committedFileText (the ONE serializer);\n// canonical key order is what makes the byte-compare idempotence hold across re-seeds.\n// - The helper makes ZERO model calls and opens no safety scope.\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n canonicalJson,\n committedFileText,\n contractFileName,\n maskCorpusText,\n projectJudgeConfigContract,\n projectMatcherConfigContract,\n runExclusionCore,\n runExclusionRecordSchema,\n} from '@vostride/agent-qa-eval'\nimport type {\n ExtractedCassette,\n PairSkip,\n PartitionManifest,\n RunExclusionRecord,\n SeedingPlan,\n SilverExclusion,\n} from '@vostride/agent-qa-eval'\nimport type { MaskFn } from '@vostride/agent-qa-schema'\n\nimport {\n COMMITTED_GITIGNORE_TEXT,\n FsCommittedRootStore,\n buildRootMarkerValue,\n committedBlobPath,\n committedCassettePath,\n committedContractPath,\n committedCorpusPath,\n committedExclusionPath,\n committedLabelPath,\n committedPartitionManifestPath,\n} from './committed-root-store.js'\nimport type { CommittedWriteOutcome } from './committed-root-store.js'\n\nexport interface SeedCommittedCorpusInput {\n /** The pure eval-core plan — the ONLY decision-maker; this helper executes it verbatim (D-16). */\n plan: SeedingPlan\n /** The extracted cassettes the plan's cases reference (cassette bytes + verified blobs). */\n cassettes: readonly ExtractedCassette[]\n /** Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the 372 CLI. */\n committedRoot: string\n /** 441 GAP3-D1: the workspace's declared-secret mask. Required; a missing one throws first. */\n mask: MaskFn\n}\n\nexport type SeedingRefusal =\n | { cassetteId: string; kind: 'write-conflict'; path: string }\n | { cassetteId: string; kind: 'missing-cassette' }\n /** A committed string of the case still holds a declared value raw; nothing of it is written. */\n | { cassetteId: string; kind: 'unmasked-declared-value' }\n\n/** 441 GAP3-D1: every committed-corpus entry point requires the mask before anything is read or written. */\nexport function requireCorpusMask(mask: unknown, caller: string): asserts mask is MaskFn {\n if (typeof mask !== 'function') throw new TypeError(`${caller} requires the declared-secret mask`)\n}\n\nfunction holdsUnmaskedDeclaredValue(documents: readonly unknown[], mask: MaskFn): boolean {\n return documents.some(document =>\n committedFileText(maskCorpusText(document, mask, { everyLeaf: true })) !== committedFileText(document))\n}\n\nexport interface SeedingReport {\n supersededOriginalCount: number\n retirementCounts: NonNullable<SeedingPlan['retirementCounts']>\n softEvidence?: SeedingPlan['softEvidence']\n product: string\n runId: string\n committedRoot: string\n /** Cases with at least one newly written file. */\n seededCount: number\n /** Cases whose every file was byte-identical (D-17 idempotent no-op). */\n unchangedCount: number\n /** Typed per-case refusals — write conflicts and missing cassettes. Never silent. */\n refusals: SeedingRefusal[]\n /** Matcher skips, carried verbatim from the plan. */\n pairSkips: PairSkip[]\n /** Sampler exclusions, carried verbatim from the plan. */\n silverExclusions: SilverExclusion[]\n /** Both pair classes counted, carried verbatim from the plan (D-07). */\n pairCounts: { total: number; sameState: number; differingState: number }\n /** Count of 'procedure-granularity' exclusions, carried verbatim from the plan. */\n proceduresExcludedCount: number\n /** Per-contract-file outcome for the D-04 constitution projections. */\n contracts: { fileName: string; outcome: CommittedWriteOutcome['kind'] }[]\n /** D-15 scaffold outcomes for the blobs-covering gitignore and the schemaVersion marker. */\n scaffold: {\n gitignore: CommittedWriteOutcome['kind']\n marker: CommittedWriteOutcome['kind']\n }\n}\n\n/**\n * Execute a SeedingPlan against the committed root: scaffold (D-15), contracts projections\n * (D-04), then each case as an atomic preview-then-write unit (D-14/D-17). Conflicted cases\n * refuse atomically; the batch always runs to completion.\n */\n/** 2026-09-08, 418 D-21: one reviewed invocation may contain several actual product/run plans.\n * The existing per-case sequential writer remains the unit; no whole-root transaction is implied.\n */\nexport interface SeedCommittedCorpusBatchInput extends Omit<SeedCommittedCorpusInput, 'plan' | 'cassettes'> {\n batches: readonly Pick<SeedCommittedCorpusInput, 'plan' | 'cassettes'>[]\n}\nexport interface SeedingBatchReport {\n reports: SeedingReport[]\n}\nexport function seedCommittedCorpus(input: SeedCommittedCorpusBatchInput): SeedingBatchReport\n// Keep the original signature last: existing ReturnType/Parameters consumers retain their contract.\nexport function seedCommittedCorpus(input: SeedCommittedCorpusInput): SeedingReport\nexport function seedCommittedCorpus(input: SeedCommittedCorpusInput | SeedCommittedCorpusBatchInput): SeedingReport | SeedingBatchReport {\n requireCorpusMask(input.mask, 'seedCommittedCorpus')\n // A mask that cannot mask (a key-only session's) throws here, before the scaffold.\n input.mask('')\n if ('batches' in input) {\n return { reports: input.batches.map(batch => executeSeedingPlan({ ...input, ...batch })) }\n }\n return executeSeedingPlan(input)\n}\n\nfunction executeSeedingPlan(input: SeedCommittedCorpusInput): SeedingReport {\n const store = new FsCommittedRootStore({ committedRoot: input.committedRoot })\n\n // (1) Scaffold.\n const scaffoldOutcomes = store.scaffold(COMMITTED_GITIGNORE_TEXT, committedFileText(buildRootMarkerValue()))\n\n // (2) D-04 contracts projections, one file per version.\n const contracts: SeedingReport['contracts'] = []\n for (const projection of [projectMatcherConfigContract(), projectJudgeConfigContract()]) {\n const fileName = contractFileName(projection)\n const outcome = store.writeText(committedContractPath(fileName), committedFileText(projection))\n contracts.push({ fileName, outcome: outcome.kind })\n }\n\n // (3) Per case, in plan order — the atomic unit is cassette + label record + corpus entry.\n const cassettesById = new Map<string, ExtractedCassette>()\n for (const entry of input.cassettes) {\n cassettesById.set(entry.cassette.id, entry)\n }\n\n const product = input.plan.product\n const refusals: SeedingRefusal[] = []\n let seededCount = 0\n let unchangedCount = 0\n let supersededOriginalCount = 0\n\n for (const planCase of input.plan.cases) {\n const cassetteId = planCase.cassetteId\n const extracted = cassettesById.get(cassetteId)\n if (extracted === undefined) {\n refusals.push({ cassetteId, kind: 'missing-cassette' })\n continue\n }\n if (holdsUnmaskedDeclaredValue([extracted.cassette, planCase.labelRecord, planCase.corpusEntry], input.mask)) {\n refusals.push({ cassetteId, kind: 'unmasked-declared-value' })\n continue\n }\n\n const texts: { relPath: string; text: string }[] = [\n { relPath: committedCassettePath(product, cassetteId), text: committedFileText(extracted.cassette) },\n { relPath: planCase.labelRecord.revision === undefined ? committedLabelPath(product, cassetteId)\n : committedLabelPath(product, cassetteId).replace(/\\.json$/, `--revision-${planCase.labelRecord.revision.id}.json`),\n text: committedFileText(planCase.labelRecord) },\n { relPath: committedCorpusPath(product, cassetteId), text: committedFileText(planCase.corpusEntry) },\n ]\n\n // Preview ALL text paths before writing ANY — a conflict on one file refuses the whole\n // case with nothing partial landed (per-case atomicity across D-17 too).\n const conflicting = texts.find(\n (candidate) => store.previewText(candidate.relPath, candidate.text) === 'conflict',\n )\n if (conflicting !== undefined) {\n refusals.push({ cassetteId, kind: 'write-conflict', path: conflicting.relPath })\n continue\n }\n\n const outcomes: CommittedWriteOutcome[] = texts.map((candidate) =>\n store.writeText(candidate.relPath, candidate.text),\n )\n // A writer can race the preview. Do not count partially written text as admission.\n const textConflict = outcomes.find(outcome => outcome.kind === 'write-conflict')\n if (textConflict?.kind === 'write-conflict') {\n refusals.push({ cassetteId, kind: 'write-conflict', path: textConflict.path })\n continue\n }\n // Blob bytes (binary, ignore-covered, D-15): the store verifies sha format + byte hash\n // before landing. A verification refusal is surfaced typed.\n let blobConflictPath: string | undefined\n for (const blob of extracted.blobs) {\n const relBlobPath = committedBlobPath(product, cassetteId, blob.sha)\n const outcome = store.writeBlob(relBlobPath, blob)\n outcomes.push(outcome)\n if (outcome.kind === 'write-conflict' && blobConflictPath === undefined) {\n blobConflictPath = outcome.path\n }\n }\n if (blobConflictPath !== undefined) {\n refusals.push({ cassetteId, kind: 'write-conflict', path: blobConflictPath })\n continue\n }\n\n if (outcomes.some((outcome) => outcome.kind === 'written')) {\n seededCount += 1\n } else {\n unchangedCount += 1\n }\n }\n\n // Label-only siblings retire exact originals without touching their other committed legs.\n for (const revision of input.plan.labelRevisions ?? []) {\n const cassetteId = revision.cassetteId\n if (!revision.revision) throw new Error('label-only seeding operation requires a revision identity')\n if (holdsUnmaskedDeclaredValue([revision], input.mask)) {\n refusals.push({ cassetteId, kind: 'unmasked-declared-value' })\n continue\n }\n const path = committedLabelPath(product, cassetteId)\n .replace(/\\.json$/, `--revision-${revision.revision.id}.json`)\n const text = committedFileText(revision)\n if (store.previewText(path, text) === 'conflict') {\n refusals.push({ cassetteId, kind: 'write-conflict', path })\n continue\n }\n const outcome = store.writeText(path, text)\n if (outcome.kind === 'write-conflict') refusals.push({ cassetteId, kind: 'write-conflict', path: outcome.path })\n else if (outcome.kind === 'written') supersededOriginalCount++\n }\n\n // (4) The report: every skip, refusal, and count visible — never silent (T-371-18).\n return {\n supersededOriginalCount,\n retirementCounts: input.plan.retirementCounts ?? { superseded: 0, missing: 0, conflict: 0 },\n product,\n ...(input.plan.softEvidence ? { softEvidence: input.plan.softEvidence } : {}),\n runId: input.plan.runId,\n committedRoot: input.committedRoot,\n seededCount,\n unchangedCount,\n refusals,\n pairSkips: [...input.plan.pairSkips],\n silverExclusions: [...input.plan.silverExclusions],\n pairCounts: { ...input.plan.pairCounts },\n proceduresExcludedCount: input.plan.proceduresExcludedCount,\n contracts,\n scaffold: {\n gitignore: scaffoldOutcomes.gitignore.kind,\n marker: scaffoldOutcomes.rootMarker.kind,\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// The two committed PARTITION documents (414 D-02/D-05/D-06).\n//\n// Both are the write-once recipe from `baseline-pointer.ts` — preview, then write —\n// with no egress check (441 D-15). They live here because a manifest and an\n// exclusion are seeding-side committed bytes.\n//\n// Neither writer mints a salt. The salt is 32 random bytes minted ONCE per product\n// upstream (the Plan 07 seed verb) and handed here inside an already-guarded\n// manifest — eval-local has no business deciding a partition parameter, and a\n// derived salt would be a public salt.\n// ---------------------------------------------------------------------------\n\n/** Both writers answer with the same outcomes. */\ntype CommittedDocumentOutcome =\n | { kind: 'written' | 'unchanged'; path: string }\n | { kind: 'write-conflict'; path: string }\n\nexport interface WritePartitionManifestInput {\n /** An already-guarded manifest; its `product` names the committed file. */\n manifest: PartitionManifest\n /** Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the CLI. */\n committedRoot: string\n}\n\nexport type WritePartitionManifestOutcome = CommittedDocumentOutcome\n\nexport interface WriteRunExclusionInput {\n /** An already-guarded exclusion record; its product + runSlug name the file. */\n record: RunExclusionRecord\n committedRoot: string\n}\n\nexport type WriteRunExclusionOutcome = CommittedDocumentOutcome\n\n/** Preview-then-write against the write-once store, mapping the outcome (371 D-17). */\nfunction previewThenWrite(\n committedRoot: string,\n relPath: string,\n text: string,\n): CommittedDocumentOutcome {\n const store = new FsCommittedRootStore({ committedRoot })\n if (store.previewText(relPath, text) === 'conflict') {\n return { kind: 'write-conflict', path: relPath }\n }\n const outcome = store.writeText(relPath, text)\n if (outcome.kind === 'write-conflict') return { kind: 'write-conflict', path: outcome.path }\n return { kind: outcome.kind, path: relPath }\n}\n\n/**\n * Commit one product's partition manifest (414 D-05).\n *\n * Write-once is the entire point. The salt and the two fractions decide which split every\n * cassette in the product lands in, so a second manifest whose flags disagree with the committed\n * one is not an update — it silently re-partitions a corpus that has already been gated against.\n * That is refused as a `write-conflict` with the committed bytes untouched; changing a live\n * partition is a reviewed git edit plus a named migration, never a rewrite through this function.\n */\nexport function writePartitionManifest(\n input: WritePartitionManifestInput,\n): WritePartitionManifestOutcome {\n const relPath = committedPartitionManifestPath(input.manifest.product)\n const text = committedFileText(input.manifest)\n\n // Write-once: preview, then write.\n return previewThenWrite(input.committedRoot, relPath, text)\n}\n\n/**\n * Commit one excluded run's record (414 D-02).\n *\n * Identical-regen is decided on `runExclusionCore` — the record WITHOUT its `backfill` block —\n * rather than on the bytes. `backfill` records a LATER act (entries deleted from the root after\n * the fact); the rest of the record is the original exclusion decision. Comparing bytes would\n * make re-recording an unchanged decision beside a newly-added backfill look like a conflicting\n * exclusion, and would equally refuse the mirror case. Anything that differs in the CORE — a\n * different verdict class, a different analysisDigest — still falls through to the write-once\n * preview and refuses.\n */\nexport function writeRunExclusion(input: WriteRunExclusionInput): WriteRunExclusionOutcome {\n const relPath = committedExclusionPath(input.record.product, input.record.runSlug)\n const text = committedFileText(input.record)\n\n // (1) The CORE comparison, before the byte preview.\n const committedFile = join(input.committedRoot, relPath)\n if (existsSync(committedFile)) {\n let existing: unknown\n try {\n existing = JSON.parse(readFileSync(committedFile, 'utf8'))\n } catch {\n // Unparseable committed bytes are not this writer's to repair: fall through to the\n // write-once preview, which refuses them as a conflict naming the path.\n existing = undefined\n }\n const parsed = runExclusionRecordSchema.safeParse(existing)\n if (\n parsed.success &&\n canonicalJson(runExclusionCore(parsed.data)) === canonicalJson(runExclusionCore(input.record))\n ) {\n return { kind: 'unchanged', path: relPath }\n }\n }\n\n // (2) Write-once for everything the core comparison did not settle.\n return previewThenWrite(input.committedRoot, relPath, text)\n}\n","// 2026-09-07, 417: guarded committed reads + the profile cache + pure eval arithmetic.\n// All replay calls delegate to the existing safety-scoped composition. Writes are gate-local.\nimport { join } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { HANDOFF_FILE, RUNS_SUBDIR, loadCompletedRunHandoff } from '@vostride/agent-qa-runner-local'\nimport {\n applyBriefDelta,\n assessJudgeEligibility,\n assessPanelEligibility,\n createPanelIdentity,\n buildEvalReport,\n computeCorpusDigest,\n computeDecisionIdentity,\n decideGate1,\n decisionCorrectnessVectors,\n decisionIdentityKey,\n deriveSampleSeeds,\n extractRunCassettes,\n effectiveGold,\n resolveScoringContext,\n FLOOR_AXES,\n diffArms,\n foldPerAxisScore,\n foldRemovalSamples,\n foldCrossCheckAcrossTargets,\n generalizationDisclosure,\n injectCandidate,\n JUDGE_CONFIG,\n locateBriefLine,\n orderGate1Reasons,\n productFloorRows,\n renderGate1Line,\n selectGateSet,\n toDeclaredBriefDelta,\n type ArmDecision,\n type ScoringJudgeRequest,\n type ArtifactSource,\n type CorpusEntry,\n type DeclaredBriefDelta,\n type DiffedDecision,\n type LeafCassette,\n type ReplayCassetteOutcome,\n type ReplaySample,\n type ReplaySampleOutcome,\n type StandaloneLabelRecord,\n} from '@vostride/agent-qa-eval'\nimport type {\n ModelProfile,\n ModelProviderOverrides,\n ResolvedModelAuth,\n} from '@vostride/agent-qa-model'\nimport {\n computeBriefDigest,\n deriveMemoryOnPathSites,\n failingStepOf,\n GATE_RECEIPT_SCHEMA_VERSION,\n GateReceiptSchema,\n slugBranch,\n stampReceiptDigest,\n type CandidateInjection,\n type CrossCheck,\n type Gate1KSource,\n type Gate1Reason,\n type Gate1Receipt,\n type PerTestOutcome,\n} from '@vostride/agent-qa-schema'\nimport { resolveBaselineCache, type BaselineCacheRow } from './baseline-cache-read.js'\nimport {\n listNoiseFloorArtefacts,\n readActiveCommittedCorpus,\n readPartitionManifests,\n resolveMinimumGateSet,\n type CommittedReadRefusal,\n} from './committed-corpus-source.js'\nimport { loadCassetteBundles } from './replay-sweep.js'\nimport { runCassetteReplay, replayJudgeRequest, type RunCassetteReplayInput } from './replay-composition.js'\nimport { FsReplayRecordStore } from './replay-record-store.js'\nimport { FsScoreStore, type ScoreRecord } from './score-store.js'\nimport { loadScoreRecord } from './replay-read.js'\nimport { loadCassetteBundle } from './cassette-loader.js'\nimport { FsCassetteStore } from './cassette-store.js'\nimport { FsRunArtifactSource } from './artifact-source.js'\n\nexport const GATE1_AUDIT_SUBDIR = 'eval/gate1'\nexport const GATE1_TARGET_SUBDIR = 'target'\n\nexport function judgeIdOf(input: {\n judgeModelId: string\n judgeFamily: string\n judgeVersion: number\n}): string {\n return `${input.judgeModelId}|family=${input.judgeFamily}|judgeVersion=${input.judgeVersion}`\n}\n\n/** A slug locates storage; only the loaded run/step/test establishes target identity. */\nexport async function locateTargetCassettes(input: {\n committedRoot: string\n agentQaRoot: string\n gate1Dir: string\n corpusEntries: readonly CorpusEntry[]\n target: NonNullable<CandidateInjection['target']>\n /** 418 D-02: a live ablation must not substitute a committed/corrected gold record. */\n source?: 'handoff'\n}): Promise<\n | { kind: 'committed' | 'extracted'; cassettes: LeafBundle[]; detail: TargetLocationDetail }\n | { kind: 'unavailable'; detail: TargetLocationDetail }\n> {\n const { target } = input\n const entries = input.corpusEntries.filter((entry) => entry.run_links.runId === target.runId)\n const handoffPath = join(input.agentQaRoot, RUNS_SUBDIR, slugBranch(target.runId), HANDOFF_FILE)\n const detail: TargetLocationDetail = {\n runId: target.runId,\n stepIndex: target.stepIndex,\n corpusEntriesForRun: entries.length,\n handoffPresent: existsSync(handoffPath),\n }\n const matches = (cassette: LeafCassette) =>\n cassette.runId === target.runId &&\n cassette.stepIndex === target.stepIndex &&\n (target.testId === undefined || cassette.input.testId === target.testId)\n const entryIds = new Set(entries.map((entry) => entry.cassetteId))\n const committed: LeafBundle[] = []\n const committedBundles = input.source === 'handoff'\n ? [] : loadCassetteBundles(join(input.committedRoot, 'cassettes')).loaded\n for (const bundle of committedBundles)\n if (\n entryIds.has(bundle.cassette.id) &&\n bundle.cassette.granularity === 'leaf' &&\n matches(bundle.cassette)\n )\n committed.push({ cassette: bundle.cassette, artifacts: bundle.artifacts })\n if (committed.length) return { kind: 'committed', cassettes: committed, detail }\n if (!detail.handoffPresent) return { kind: 'unavailable', detail }\n let extraction: ReturnType<typeof extractRunCassettes>\n try {\n const handoff = loadCompletedRunHandoff(handoffPath)\n if (handoff.runId !== target.runId)\n return { kind: 'unavailable', detail: { ...detail, reason: 'loaded handoff runId mismatch' } }\n extraction = extractRunCassettes({\n handoff,\n artifacts: new FsRunArtifactSource({ root: input.agentQaRoot, runId: handoff.runId }),\n })\n if (\n input.source === 'handoff' &&\n handoff.tests.some((test) =>\n (target.testId === undefined || test.testId === target.testId) &&\n test.steps.some((step) => step.stepIndex === target.stepIndex),\n ) &&\n !extraction.cassettes.some((row) =>\n row.cassette.granularity === 'leaf' && matches(row.cassette),\n )\n )\n return { kind: 'unavailable', detail: { ...detail, reason: 'no live decision at target' } }\n } catch (error) {\n return {\n kind: 'unavailable',\n detail: { ...detail, reason: error instanceof Error ? error.message : String(error) },\n }\n }\n const store = new FsCassetteStore({\n root: input.agentQaRoot,\n outputDir: join(input.gate1Dir, GATE1_TARGET_SUBDIR, 'cassettes'),\n })\n const cassettes: LeafBundle[] = []\n for (const extracted of extraction.cassettes) {\n if (extracted.cassette.granularity !== 'leaf' || !matches(extracted.cassette)) continue\n const bundle = loadCassetteBundle(store.write(extracted).dir)\n if (\n bundle.kind === 'loaded' &&\n bundle.cassette.granularity === 'leaf' &&\n matches(bundle.cassette)\n )\n cassettes.push({ cassette: bundle.cassette, artifacts: bundle.artifacts })\n }\n return cassettes.length\n ? { kind: 'extracted', cassettes, detail }\n : { kind: 'unavailable', detail }\n}\ninterface TargetLocationDetail {\n runId: string\n stepIndex: number\n corpusEntriesForRun: number\n handoffPresent: boolean\n reason?: string\n}\n\n/** The CLI's JSON output uses the same schema-validated DTO as persisted receipts. */\nexport function serializeReplayGateReceipt(receipt: unknown): string {\n return JSON.stringify(GateReceiptSchema.parse(receipt), null, 2)\n}\ntype Planner = {\n profile: ModelProfile\n modelOverrides?: ModelProviderOverrides\n resolveAuth: () => Promise<ResolvedModelAuth>\n}\nexport interface RunReplayGateInput {\n injection: CandidateInjection\n committedRoot: string\n agentQaRoot: string\n identity: {\n plannerModelId: string\n matcherVersion: number\n judgeModelId?: string\n judgeVersion?: number\n judgeMemberModelIds?: readonly string[]\n fingerprint: string\n profileKey: string\n }\n planner: Planner\n judge?: Planner\n /** Complete explicit lazy declaration; Gate 1 evaluates the raw members as a unit. */\n judgeMembers?: readonly Planner[]\n judgeOverrideConfigured: boolean\n k: number\n kSource: Gate1KSource\n maxScreens: number\n baselineSeed: { seed?: number; source: 'flag' | 'config' } | { floorSeeds: readonly number[] }\n /** Effective CLI selection for a copyable, spend-bearing cache recovery command. */\n baselineWarmup?: { configPath: string; judge?: string; judges?: readonly string[] }\n mask: RunCassetteReplayInput['mask']\n producedBy: { opId: string }\n clock?: () => number\n onProgress?: (line: string) => void\n}\nexport type RunReplayGateResult =\n | {\n kind: 'receipt'\n receipt: Gate1Receipt\n lines: string[]\n notices: string[]\n refusals: readonly CommittedReadRefusal[]\n modelCalls: number\n wallClockMs: number\n }\n | { kind: 'refused'; refusal: CommittedReadRefusal; notices: string[] }\ntype LeafBundle = { cassette: LeafCassette; artifacts: ArtifactSource }\ntype Cached = Extract<BaselineCacheRow, { kind: 'cached' }>\nexport type ReplayBag = Pick<\n RunCassetteReplayInput,\n | 'profile'\n | 'auth'\n | 'modelOverrides'\n | 'judge'\n | 'mask'\n | 'modelCallObservation'\n | 'clock'\n>\n\nfunction firstSample(outcome: ReplayCassetteOutcome): ReplaySample | undefined {\n return 'granularity' in outcome && outcome.granularity === 'leaf' ? outcome.samples[0] : undefined\n}\nfunction outcomeOf(sample: ReplaySample | undefined): ReplaySampleOutcome {\n return sample?.outcome ?? { kind: 'harness-error', message: 'replay produced no sample' }\n}\nfunction honored(sample: ReplaySample | undefined): boolean {\n return (\n sample !== undefined &&\n !(sample.unsupportedFeatures ?? []).some((feature) => feature.toLowerCase().includes('seed'))\n )\n}\nfunction arm(\n cassette: LeafCassette,\n replay: ReplayCassetteOutcome,\n score?: ScoreRecord,\n labelRecord?: StandaloneLabelRecord,\n expectedJudgeRequest?: ScoringJudgeRequest,\n): ArmDecision['baseline'] {\n const resolved = resolveScoringContext({ cassette, outcome: replay, record: score, labelRecord, expectedJudgeRequest })\n const vector = decisionCorrectnessVectors([\n { cassetteId: cassette.id, outcome: replay,\n score: resolved.score,\n label: labelRecord?.label ?? cassette.label },\n ])[0]\n return vector === undefined || FLOOR_AXES.every((axis) => vector.axes[axis] === 'not-applicable')\n ? { kind: 'refused', reason: 'no decision vector' }\n : { kind: 'scored', vector, briefSource: vector.briefSource }\n}\nfunction harm(row: DiffedDecision): NonNullable<Gate1Receipt['harmed']>[number] {\n const {\n cassetteId,\n stepIndex,\n decisionOrdinal,\n origin,\n labelTier,\n sourceChannel,\n verdictPresent,\n split,\n heldOutVisibility,\n softWeight,\n } = row\n return {\n cassetteId,\n ...(stepIndex === undefined ? {} : { stepIndex }),\n decisionOrdinal,\n origin,\n ...(labelTier === undefined ? {} : { labelTier }),\n ...(sourceChannel === undefined ? {} : { sourceChannel }),\n verdictPresent,\n ...(split === undefined ? {} : { split }),\n ...(heldOutVisibility === undefined ? {} : { heldOutVisibility }),\n ...(softWeight === undefined ? {} : { softWeight }),\n axes: row.flippedWorse,\n }\n}\n\nexport interface RemovalFlipsOutcomeInput {\n recordId: string\n cassettes: readonly (LeafBundle & {\n labelRecord?: StandaloneLabelRecord\n existing?: { withRecord: ReplaySample; withoutRecord: ReplaySample }\n baseSeed?: number\n seedHonored?: boolean\n })[]\n // 2026-09-07, 418 D-02/reconciliation 8: opt-in served-canary removal only.\n // Ordinary active-record callers retain rule 5; this is not another mode arm.\n mode:\n | { kind: 'injected'; injection: CandidateInjection }\n | { kind: 'active-record'; servedCanary?: true }\n k: number\n baseSeed: number\n existing?: { withRecord: ReplaySample; withoutRecord: ReplaySample }\n replay: ReplayBag\n gate1Dir: string\n /**\n * 2026-09-11, 422 D-18: the ONE way an ORDINARY candidate — served on channel 1 without a\n * canary flag — becomes ablatable. Deliberately a sibling of `mode`, not a third mode arm:\n * the served-canary rule above is an opt-in FLAG, and this is positive PROOF. Absent, the\n * arbiter removes nothing that the active and served-canary rules did not already admit.\n */\n failingPathCandidate?: FailingPathCandidateAuthorization\n}\nexport interface RemovalFlipsOutcomeResult {\n crossCheck: Exclude<CrossCheck, 'not-run'>\n perTarget: { cassetteId: string; crossCheck: Exclude<CrossCheck, 'not-run'> }[]\n seeds: number[]\n seedHonored: boolean\n detail: NonNullable<Gate1Receipt['samples']['detail']>\n modelCalls: number\n screens: number\n promptTokens: number\n completionTokens: number\n notices: string[]\n}\n\n/**\n * 2026-09-11, 422 D-18: the arbiter's authorization to ablate an ORDINARY candidate.\n *\n * Ordinary candidate memory is the user's, and this is the one path in the phase that deletes\n * it from a replayed input. So the authorization carries the run's OWN recorded bytes and\n * DECLARES nothing that code can recompute: which step failed is re-derived with the single\n * exported `failingStepOf` rule, and whether the record was on that step's path is re-read\n * from that step's own served brief with `deriveMemoryOnPathSites`. A caller can therefore\n * name a record and hand over evidence, but it cannot assert either fact.\n */\nexport interface FailingPathCandidateAuthorization {\n /** The record to ablate. Must be the record `removalFlipsOutcome` was asked to remove. */\n readonly recordId: string\n /** The run that recorded {@link perTest}. Must be the target cassette's own run. */\n readonly runId: string\n /** The run's own recorded member outcome — the source of the two recomputed facts above. */\n readonly perTest: PerTestOutcome\n}\n\n/**\n * Three outcomes, never two. `absent` (no authorization was offered) and `refused` (one was,\n * and it did not establish the removal) both leave memory intact, but they are different\n * facts about the caller and the gate reports them apart.\n */\nexport type FailingPathCandidateAdmission =\n | { kind: 'authorized'; stepIndex: number }\n | { kind: 'absent' }\n | { kind: 'refused'; reason: string }\n\n/**\n * Evaluate a D-18 authorization against the decision it claims to authorize. Every refusal\n * names its own cause, because \"removed nothing\" for six different reasons is one fact a\n * reader cannot act on.\n */\nexport function resolveFailingPathCandidate(input: {\n cassette: LeafCassette\n recordId: string\n authorization?: FailingPathCandidateAuthorization\n}): FailingPathCandidateAdmission {\n const authorization = input.authorization\n if (authorization === undefined) return { kind: 'absent' }\n const malformed = { kind: 'refused', reason: 'failing-path authorization is malformed' } as const\n if (typeof authorization !== 'object' || authorization === null) return malformed\n const { recordId, runId, perTest } = authorization\n if (\n typeof recordId !== 'string' ||\n recordId === '' ||\n typeof runId !== 'string' ||\n runId === '' ||\n typeof perTest !== 'object' ||\n perTest === null ||\n typeof perTest.testId !== 'string' ||\n !Array.isArray(perTest.steps) ||\n perTest.steps.some(\n (step) =>\n typeof step !== 'object' ||\n step === null ||\n !Number.isSafeInteger(step.stepIndex) ||\n typeof step.verifierVerdict?.pass !== 'boolean' ||\n !Array.isArray(step.servedBrief?.channel1),\n )\n )\n return malformed\n // Identity first: an authorization for a different record, run or member is not evidence\n // about this decision, however well-formed it is.\n if (recordId !== input.recordId)\n return { kind: 'refused', reason: 'failing-path authorization names another record' }\n if (runId !== input.cassette.runId || perTest.testId !== input.cassette.input.testId)\n return { kind: 'refused', reason: 'failing-path authorization names another run or member' }\n // WHICH step failed is RECOMPUTED with the one exported rule, never declared.\n const failing = failingStepOf(perTest)\n if (failing === undefined)\n return { kind: 'refused', reason: 'failing-path authorization records no step' }\n // `failingStepOf` answers the LAST step when nothing failed (the timeout anchor), so the\n // verdict itself has to be read: a verified-passing step is not a failing path.\n if (failing.verifierVerdict.pass)\n return { kind: 'refused', reason: 'failing-path authorization cites a verified-passing step' }\n if (failing.stepIndex !== input.cassette.stepIndex)\n return {\n kind: 'refused',\n reason: 'failing-path authorization cites a step other than the removal target',\n }\n // Served membership is RE-READ from that step's own brief, with the same derivation the\n // circularity guard uses, so a caller cannot assert that a record was on the path.\n const site = deriveMemoryOnPathSites([failing]).find((row) => row.recordId === input.recordId)\n if (site === undefined)\n return { kind: 'refused', reason: 'failing-path record was not served on the failing step' }\n if (site.trust !== 'candidate')\n return { kind: 'refused', reason: 'failing-path record is not an ordinary candidate' }\n // Last, and the reason the two derivations above mean anything: the brief they read must BE\n // the brief the decision replays. Recomputed, never compared against the stored field — a\n // lookalike assembled from a stale or edited handoff carries the old digest unchanged.\n if (\n computeBriefDigest(failing.servedBrief) !==\n computeBriefDigest(input.cassette.input.servedBrief)\n )\n return {\n kind: 'refused',\n reason: 'failing-path authorization cites a different brief than the replayed decision',\n }\n return { kind: 'authorized', stepIndex: failing.stepIndex }\n}\n\n/** 418 D-02: share the exact removal proof between sample one and subsequent samples.\n * Internal to eval-local; ordinary callers retain the active-record admission rule.\n */\nexport function resolveActiveRecordRemoval(input: {\n cassette: LeafCassette\n recordId: string\n servedCanary?: true\n /** 422 D-18: positive proof for an ordinary candidate; see the interface above. */\n failingPathCandidate?: FailingPathCandidateAuthorization\n}): { kind: 'removed'; delta: DeclaredBriefDelta } | { kind: 'unavailable'; reason: string } {\n const { cassette } = input\n const brief = cassette.input.servedBrief\n const channel1Position = brief.channel1.findIndex((line) => line.id === input.recordId)\n const line = brief.channel1[channel1Position]\n // 422 D-18: a PRESENT authorization that does not establish the removal refuses in its own\n // words, before any admission rule runs — including the active and served-canary rules a\n // broken authorization must never be able to fall back onto.\n const authorized = resolveFailingPathCandidate({\n cassette,\n recordId: input.recordId,\n authorization: input.failingPathCandidate,\n })\n if (authorized.kind === 'refused') return { kind: 'unavailable', reason: authorized.reason }\n if (\n line === undefined ||\n !(\n line.status === 'active' ||\n (input.servedCanary === true && line.status === 'candidate' && line.servedAsCanary === true) ||\n (authorized.kind === 'authorized' && line.status === 'candidate')\n ) ||\n (line.tier !== 'L0' && line.tier !== 'L1' && line.tier !== 'L2')\n )\n return {\n kind: 'unavailable',\n reason:\n line !== undefined && line.status === 'candidate' && authorized.kind === 'absent'\n ? 'candidate removal requires an explicit failing-path authorization'\n : 'active record brief line unavailable',\n }\n const turns = brief.proof?.promptTurns ?? []\n const turn =\n turns.find((row) => row.turnOrdinal === cassette.decisionOrdinal) ??\n (turns.every((row) =>\n row.policyL0 === turns[0]?.policyL0 &&\n row.learnedL1 === turns[0]?.learnedL1 &&\n row.learnedL2 === turns[0]?.learnedL2,\n ) ? turns[0] : undefined)\n if (turn === undefined)\n return { kind: 'unavailable', reason: 'active record requires a reproducible proof turn' }\n const text = turn[\n { L0: 'policyL0', L1: 'learnedL1', L2: 'learnedL2' }[line.tier] as\n 'policyL0' | 'learnedL1' | 'learnedL2'\n ]\n const located = locateBriefLine(text, line, line.tier)\n if (located.kind !== 'located')\n return { kind: 'unavailable', reason: 'active record rendered line is absent or ambiguous' }\n return {\n kind: 'removed',\n delta: {\n kind: 'removed',\n line,\n tier: line.tier,\n renderedLine: text.split('\\n')[located.index]!,\n turnOrdinal: turn.turnOrdinal,\n position: located.index,\n channel1Position,\n },\n }\n}\n\n/** Existing samples count as sample one; every additional sample gets a distinct derived seed. */\nexport async function removalFlipsOutcome(\n input: RemovalFlipsOutcomeInput,\n): Promise<RemovalFlipsOutcomeResult> {\n const result: RemovalFlipsOutcomeResult = {\n crossCheck: 'inconclusive',\n perTarget: [],\n seeds: [input.baseSeed, ...deriveSampleSeeds(input.baseSeed, input.k)],\n seedHonored: true,\n detail: [],\n modelCalls: 0,\n screens: 0,\n promptTokens: 0,\n completionTokens: 0,\n notices: [],\n }\n for (const target of input.cassettes) {\n const { cassette, artifacts } = target\n const effective = effectiveGold(cassette, target.labelRecord)\n if (effective.kind === 'refused') {\n result.notices.push(`gold unavailable: ${cassette.id}: ${effective.reason}`)\n result.perTarget.push({ cassetteId: cassette.id, crossCheck: 'inconclusive' })\n continue\n }\n const baseSeed = target.baseSeed ?? input.baseSeed\n const seeds = [baseSeed, ...deriveSampleSeeds(baseSeed, input.k)]\n const existing = target.existing ?? input.existing\n if (existing === undefined) throw new TypeError('cross-check requires both first samples')\n let withCassette = cassette\n let withoutCassette = cassette\n let withDelta: DeclaredBriefDelta | undefined\n let withoutDelta: DeclaredBriefDelta | undefined\n if (input.mode.kind === 'injected') {\n const planned = toDeclaredBriefDelta(input.mode.injection, cassette)\n if (planned.kind !== 'plan') throw new TypeError(planned.detail)\n withDelta = planned.plan.delta\n withCassette = injectCandidate(cassette, planned.plan)\n } else {\n const removal = resolveActiveRecordRemoval({\n cassette,\n recordId: input.recordId,\n servedCanary: input.mode.servedCanary,\n // Re-checked PER TARGET: the authorization names one decision, so a second cassette\n // gets its own admission and its own refusal rather than riding the first one's.\n failingPathCandidate: input.failingPathCandidate,\n })\n if (removal.kind === 'unavailable') {\n result.notices.push(`brief-line-not-found: ${cassette.id}: ${removal.reason}`)\n result.perTarget.push({ cassetteId: cassette.id, crossCheck: 'inconclusive' })\n continue\n }\n withoutDelta = removal.delta\n withoutCassette = { ...cassette, input: applyBriefDelta(cassette.input, withoutDelta) }\n }\n const gold = computeDecisionIdentity(\n effective.cassette.sidecar.goldAction,\n cassette.input.stateBefore.elements,\n )\n const goldKey = decisionIdentityKey(gold)\n const arms = { withRecord: [existing.withRecord], withoutRecord: [existing.withoutRecord] }\n result.seedHonored &&= target.seedHonored !== false\n for (let index = 1; index < input.k; index++) {\n for (const withRecord of [true, false]) {\n const outputDir = join(\n input.gate1Dir,\n 'cross-check',\n withRecord ? 'with' : 'without',\n `sample-${index}`,\n 'replays',\n )\n const replay = await runCassetteReplay({\n ...input.replay,\n cassette: withRecord ? withCassette : withoutCassette,\n labelRecord: target.labelRecord,\n artifacts,\n declaredBriefDelta: withRecord ? withDelta : withoutDelta,\n k: 1,\n seed: seeds[index]!,\n modelCallObservation: {\n onProviderCall: () => {\n result.modelCalls++\n input.replay.modelCallObservation?.onProviderCall?.()\n },\n },\n recordStore: new FsReplayRecordStore({ root: input.gate1Dir, outputDir }),\n scoreStore: new FsScoreStore({ root: input.gate1Dir, outputDir }),\n })\n const sample = firstSample(replay) ?? {\n sampleIndex: 0,\n outcome: outcomeOf(undefined),\n durationMs: 0,\n }\n arms[withRecord ? 'withRecord' : 'withoutRecord'].push(sample)\n result.screens++\n result.promptTokens += sample.tokenUsage?.promptTokens ?? 0\n result.completionTokens += sample.tokenUsage?.completionTokens ?? 0\n const score = loadScoreRecord(join(outputDir, ...cassette.id.split('/').map(slugBranch)))\n if (score.kind === 'loaded') {\n const cost = buildEvalReport([\n { cassetteId: cassette.id, outcome: replay, score: score.record.score },\n ]).honesty.judge.cost\n result.promptTokens += cost.inputTokens\n result.completionTokens += cost.outputTokens\n }\n }\n }\n for (const withRecord of [true, false])\n for (const [index, sample] of arms[withRecord ? 'withRecord' : 'withoutRecord'].entries()) {\n result.seedHonored &&= honored(sample)\n result.detail.push({\n withRecord,\n seed: seeds[index]!,\n matchesGold:\n sample.outcome.kind === 'decision' &&\n decisionIdentityKey(sample.outcome.identity) === goldKey,\n kind: sample.outcome.kind,\n })\n }\n result.perTarget.push({\n cassetteId: cassette.id,\n crossCheck: foldRemovalSamples({\n withRecord: arms.withRecord.map((sample) => sample.outcome),\n withoutRecord: arms.withoutRecord.map((sample) => sample.outcome),\n gold,\n }),\n })\n }\n result.crossCheck = foldCrossCheckAcrossTargets(result.perTarget.map((row) => row.crossCheck))\n return result\n}\n\nexport async function runReplayGate(input: RunReplayGateInput): Promise<RunReplayGateResult> {\n const notices: string[] = []\n try {\n return await compose(input, notices)\n } catch (error) {\n const io = error as NodeJS.ErrnoException\n if (typeof io?.code !== 'string' || typeof io.path !== 'string') throw error\n return {\n kind: 'refused',\n refusal: { path: io.path, reason: `gate staging failed: ${io.message}` },\n notices,\n }\n }\n}\n\nasync function compose(input: RunReplayGateInput, notices: string[]): Promise<RunReplayGateResult> {\n const { injection, identity } = input\n if (!Number.isSafeInteger(input.k) || input.k < 3 || input.k % 2 === 0)\n throw new TypeError('k must be an odd integer of at least 3')\n if (!Number.isSafeInteger(input.maxScreens) || input.maxScreens < 1)\n throw new TypeError('maxScreens must be a positive safe integer')\n const clock = input.clock ?? Date.now\n const started = clock()\n const corpus = readActiveCommittedCorpus(input.committedRoot, input.agentQaRoot)\n const floors = listNoiseFloorArtefacts(input.committedRoot)\n const partitions = readPartitionManifests(input.committedRoot)\n const refusals = [...corpus.refusals, ...floors.refusals, ...partitions.refusals]\n notices.push(...corpus.notices, ...partitions.notices)\n if (refusals[0]) return { kind: 'refused', refusal: refusals[0], notices }\n const floor = floors.artefacts.find((row) => row.profileKey === identity.profileKey)?.artefact\n const minimum = resolveMinimumGateSet({\n committedRoot: input.committedRoot,\n profileKey: identity.profileKey,\n })\n if (floor === undefined || minimum.kind !== 'resolved')\n return {\n kind: 'refused',\n refusal: { path: input.committedRoot, reason: 'noise floor or minimum gate set unavailable' },\n notices,\n }\n const members = input.judgeMembers ?? (input.judge === undefined ? [] : [input.judge])\n const memberModelIds = members.map(member => member.profile.model)\n const panel = members.length > 1 ? createPanelIdentity(memberModelIds) : undefined\n if (identity.judgeModelId?.startsWith('panel:') && panel === undefined)\n throw new TypeError('Gate 1 composite judge identity requires explicit raw members')\n const declaredJudgeId = members.length === 0 ? identity.judgeModelId\n : createPanelIdentity(memberModelIds).judgeModelId\n if (declaredJudgeId !== identity.judgeModelId ||\n (identity.judgeMemberModelIds !== undefined &&\n JSON.stringify([...identity.judgeMemberModelIds].sort()) !== JSON.stringify([...memberModelIds].sort())))\n throw new TypeError('Gate 1 judge declaration differs from its cache identity')\n const assess = (cassette?: LeafCassette) => {\n const common = { replayedModelId: identity.plannerModelId,\n recordedModelId: cassette?.receipt.model.declared?.modelId ?? cassette?.receipt.model.resolvedModelId }\n return panel === undefined\n ? assessJudgeEligibility({ ...common, judgeModelId: declaredJudgeId })\n : assessPanelEligibility({ ...common, memberModelIds })\n }\n const eligibility = assess()\n let sameFamilyRefused =\n (panel !== undefined || input.judgeOverrideConfigured) &&\n !eligibility.eligible &&\n eligibility.reason === 'no-eligible-judge'\n const emptyFold = foldPerAxisScore([], floor.axes)\n const receipt: Omit<Gate1Receipt, 'receiptDigest'> = {\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION,\n gate: 1,\n candidateId: injection.candidateId,\n producedAtOrdinal: injection.latestOrdinal,\n producedBy: input.producedBy,\n verdict: 'abstain',\n perAxisScore: emptyFold.perAxisScore,\n floorAbsentAxes: emptyFold.floorAbsentAxes,\n population: emptyFold.population,\n corpusVersion: {\n corpusDigest: computeCorpusDigest(corpus.snapshot.entries),\n partitionVersion:\n partitions.manifests.find((row) => row.product === injection.product)?.partitionVersion ??\n (corpus.snapshot.entries.some((row) => row.product === injection.product)\n ? floor.partitionVersion\n : 0),\n gateSetSize: 0,\n excludedCount: 0,\n minimumGateSet: minimum.minimumGateSet,\n },\n noiseFloorRef: { profileKey: floor.profileKey, corpusDigest: floor.corpusDigest },\n samples: { k: input.k, seeds: [], seedHonored: false, modelCalls: 0 },\n crossCheck: 'not-run',\n kSource: input.kSource,\n cap: { maxScreens: input.maxScreens },\n spend: { screens: 0, modelCalls: 0, promptTokens: 0, completionTokens: 0, wallClockMs: 0 },\n judge: {\n eligibility: eligibility.eligible ? 'eligible' : eligibility.reason,\n overrideConfigured: input.judgeOverrideConfigured,\n ...(panel === undefined ? {} : { panelSize: panel.panelSize, members: [...panel.members!] }),\n },\n ...(eligibility.eligible\n ? {\n judgeId: judgeIdOf({ ...eligibility, judgeVersion: JUDGE_CONFIG.judgeVersion }),\n }\n : { degradation: 'replay-diff' }),\n }\n const finish = (): RunReplayGateResult => {\n const stamped = stampReceiptDigest(receipt)\n GateReceiptSchema.parse(stamped)\n return {\n kind: 'receipt',\n receipt: stamped,\n lines: [renderGate1Line(stamped), ...notices],\n notices,\n refusals,\n modelCalls: receipt.spend!.modelCalls,\n wallClockMs: receipt.spend!.wallClockMs,\n }\n }\n const abstain = (reason: Gate1Reason) => {\n receipt.spend!.wallClockMs = Math.max(0, Math.round(clock() - started))\n receipt.reasons = orderGate1Reasons([\n reason,\n ...(sameFamilyRefused ? ['same-family-refused' as const] : []),\n ])\n if (reason === 'tier-not-implemented') receipt.degradation = 'tier-not-implemented'\n return finish()\n }\n if (injection.kind !== 'fact' && injection.kind !== 'caution')\n return abstain('tier-not-implemented')\n const gate = selectGateSet({\n entries: corpus.snapshot.entries,\n product: injection.product,\n candidate: injection.provenance,\n minimumGateSet: minimum.minimumGateSet,\n })\n if (gate.verdict !== 'ok') return abstain(gate.verdict)\n receipt.corpusVersion.gateSetSize = gate.gateEntries.length\n receipt.corpusVersion.excludedCount = gate.excluded.length\n if (injection.target === undefined) return abstain('target-unavailable')\n const loaded = loadCassetteBundles(join(input.committedRoot, 'cassettes')).loaded\n const bundles = new Map<string, LeafBundle>()\n for (const row of loaded)\n if (row.cassette.granularity === 'leaf') {\n if (bundles.has(row.cassette.id))\n return {\n kind: 'refused',\n refusal: { path: input.committedRoot, reason: 'duplicate cassette identity' },\n notices,\n }\n bundles.set(row.cassette.id, { cassette: row.cassette, artifacts: row.artifacts })\n }\n const gate1Dir = join(input.agentQaRoot, GATE1_AUDIT_SUBDIR, slugBranch(injection.candidateId))\n const located = await locateTargetCassettes({\n committedRoot: input.committedRoot,\n agentQaRoot: input.agentQaRoot,\n gate1Dir,\n corpusEntries: corpus.snapshot.entries.filter((row) => row.product === injection.product),\n target: injection.target,\n })\n if (located.kind === 'unavailable') {\n const d = located.detail\n notices.push(\n `target-unavailable: runId=${d.runId} stepIndex=${d.stepIndex} corpusEntriesForRun=${d.corpusEntriesForRun} handoffPresent=${d.handoffPresent}${d.reason === undefined ? '' : ' reason=' + d.reason}`,\n )\n return abstain('target-unavailable')\n }\n // Explicitly excluded corpus history cannot regain scoring eligibility through\n // a local handoff. Genuinely non-corpus target siblings keep their existing path.\n const targets = located.cassettes.filter(({ cassette }) =>\n !corpus.snapshot.excludedLabelIds?.has(cassette.id) &&\n !corpus.retiredMarkedCassetteIds?.has(cassette.id))\n if (targets.length === 0) return abstain('target-unavailable')\n for (const target of targets) bundles.set(target.cassette.id, target)\n const allIds = [\n ...new Set([\n ...gate.gateEntries.map((row) => row.cassetteId),\n ...targets.map((row) => row.cassette.id),\n ]),\n ]\n if (allIds.some((id) => !bundles.has(id)))\n return {\n kind: 'refused',\n refusal: { path: input.committedRoot, reason: 'gate cassette unavailable' },\n notices,\n }\n const seed =\n 'floorSeeds' in input.baselineSeed\n ? (input.baselineSeed.floorSeeds[0] ?? 11)\n : (input.baselineSeed.seed ?? 11)\n const seedSource =\n 'floorSeeds' in input.baselineSeed\n ? input.baselineSeed.floorSeeds[0] === undefined\n ? 'default'\n : 'floor'\n : input.baselineSeed.source\n // Each cached score was judged against its own recorded model as well as the\n // actual replay planner. An ineligible row must carry no eligible judge stamp.\n const assessments = new Map(allIds.map(id => [id, assess(bundles.get(id)!.cassette)]))\n if (panel !== undefined && [...assessments.values()].some(row => !row.eligible)) {\n receipt.judge!.eligibility = 'no-eligible-judge'\n receipt.degradation = 'replay-diff'\n sameFamilyRefused = true\n delete receipt.judgeId\n }\n const resolutions = allIds.map(id => {\n const rowEligibility = assessments.get(id)!\n return resolveBaselineCache({\n agentQaRoot: input.agentQaRoot,\n ...identity,\n ...(rowEligibility.eligible\n ? {\n judgeIdentity: {\n judgeModelId: rowEligibility.judgeModelId,\n judgeVersion: JUDGE_CONFIG.judgeVersion,\n },\n }\n : {}),\n gateRootSeed: seed,\n gateRootSeedSource: seedSource,\n cassettes: [{\n id,\n promptInputHash: bundles.get(id)!.cassette.receipt.promptInputHash,\n }],\n })\n })\n const cache = { rows: resolutions.flatMap(result => result.rows) }\n // D-01 + literal D-06: extraction cannot inherit a committed-profile baseline,\n // even when a stale/colliding directory happens to contain an identically slugged id.\n if (located.kind === 'extracted') {\n const extractedIds = new Set(targets.map((target) => target.cassette.id))\n cache.rows = cache.rows.map((row) =>\n extractedIds.has(row.cassetteId)\n ? {\n kind: 'uncached',\n cassetteId: row.cassetteId,\n reason: 'extracted target has no committed-profile baseline',\n }\n : row,\n )\n for (const id of extractedIds)\n notices.push(\n `target ${id} was extracted from the local handoff and has no committed-profile baseline; seed the run into the corpus, re-run eval gate to warm its baseline, then re-run eval replay-gate`,\n )\n }\n const uncached = cache.rows.filter((row) => row.kind === 'uncached')\n if (uncached.length) {\n const quote = (value: string) => `'${value.replaceAll(\"'\", \"'\\\\''\")}'`\n const config =\n input.baselineWarmup === undefined\n ? ''\n : ` --config ${quote(input.baselineWarmup.configPath)}`\n const judge = (input.baselineWarmup?.judges ??\n (input.baselineWarmup?.judge === undefined ? [] : [input.baselineWarmup.judge]))\n .map(name => ` --judge ${quote(name)}`).join('')\n notices.push(\n `uncached: ${uncached.map((row) => row.cassetteId).join(', ')}`,\n `agent-qa${config} eval gate --seed ${seed}${judge}`,\n 'Baseline warm-up spends planner and configured judge calls; then re-run eval replay-gate.',\n )\n return abstain('baseline-uncached')\n }\n const cacheById = new Map(cache.rows.map((row) => [row.cassetteId, row]))\n const baselineJudgeRequest = declaredJudgeId === undefined ? null : {\n judgeModelId: declaredJudgeId, allowSameFamily: false }\n const baselineArms = new Map(\n cache.rows.map((row) => [\n row.cassetteId,\n row.kind === 'cached'\n ? arm(bundles.get(row.cassetteId)!.cassette, row.replay, row.score, corpus.snapshot.labelsById.get(row.cassetteId), baselineJudgeRequest)\n : { kind: 'refused' as const, reason: row.reason },\n ]),\n )\n const scoredCollateral = gate.gateEntries.filter((row) => {\n const baseline = baselineArms.get(row.cassetteId)\n return baseline?.kind === 'scored'\n })\n if (scoredCollateral.length === 0) return abstain('collateral-unscorable')\n const targetsToCrossCheck = targets.filter(({ cassette }) => {\n const cached = cacheById.get(cassette.id)\n if (cached?.kind !== 'cached') return false\n const baseline = arm(cassette, cached.replay, cached.score, corpus.snapshot.labelsById.get(cassette.id), baselineJudgeRequest)\n return baseline.kind === 'scored' && baseline.vector.axes.headline === 'incorrect'\n }).length\n const scoredTargets = targets.filter(\n (target) => cacheById.get(target.cassette.id)?.kind === 'cached',\n ).length\n const planned = scoredCollateral.length + scoredTargets + 2 * (input.k - 1) * targetsToCrossCheck\n if (planned > input.maxScreens) {\n notices.push(`cap-exceeded: planned=${planned} maxScreens=${input.maxScreens}`)\n return abstain('cap-exceeded')\n }\n const spend = receipt.spend!\n if (input.planner.profile.model !== identity.plannerModelId)\n throw new TypeError('Gate 1 replay planner differs from its cache identity')\n const judgeCanRun = [...assessments.values()].some(row => row.eligible)\n const auth = await input.planner.resolveAuth()\n const judgeBindings = []\n for (const member of members) {\n // Refused declarations still stamp no-eligible-judge, without credentials.\n // Replay rechecks the identical planner/recorded IDs before it can bind a port.\n judgeBindings.push({ profile: member.profile, modelOverrides: member.modelOverrides,\n auth: judgeCanRun ? await member.resolveAuth() : { kind: 'none' as const } })\n }\n const replay: ReplayBag = {\n profile: input.planner.profile,\n auth,\n modelOverrides: input.planner.modelOverrides,\n mask: input.mask,\n modelCallObservation: {\n onProviderCall: () => {\n spend.modelCalls++\n },\n },\n ...(input.clock === undefined ? {} : { clock: { now: input.clock } }),\n ...(members.length > 0\n ? {\n judge: { members: judgeBindings },\n }\n : {}),\n }\n const rows: ArmDecision[] = []\n const candidateSamples = new Map<string, ReplaySample>()\n const targetIds = new Set(targets.map((row) => row.cassette.id))\n let seedHonored = true\n for (const id of allIds) {\n const { cassette, artifacts } = bundles.get(id)!\n const baseline = cacheById.get(id)!\n const entry = corpus.snapshot.entries.find((row) => row.cassetteId === id)\n const labelRecord = corpus.snapshot.labelsById.get(cassette.id)\n const row: ArmDecision = {\n cassetteId: id,\n stepIndex: cassette.stepIndex,\n decisionOrdinal: cassette.decisionOrdinal,\n origin: targetIds.has(id) ? 'target-step' : 'gate-set',\n entry,\n label: labelRecord?.label ?? cassette.label,\n ...(labelRecord?.weight === undefined ? {} : { softWeight: labelRecord.weight.value }),\n baseline: baselineArms.get(id)!,\n candidate: { kind: 'refused', reason: 'baseline refused' },\n }\n rows.push(row)\n if (baseline.kind !== 'cached' || row.baseline.kind !== 'scored') continue\n seedHonored &&= baseline.seedHonored\n const plan = toDeclaredBriefDelta(injection, cassette)\n if (plan.kind !== 'plan') {\n row.candidate = { kind: 'refused', reason: plan.detail }\n continue\n }\n const outputDir = join(gate1Dir, 'candidate-arm', 'replays')\n const candidateCassette = injectCandidate(cassette, plan.plan)\n const candidate = await runCassetteReplay({\n ...replay,\n cassette: candidateCassette,\n labelRecord: corpus.snapshot.labelsById.get(cassette.id),\n artifacts,\n k: 1,\n seed: baseline.seed,\n declaredBriefDelta: plan.plan.delta,\n recordStore: new FsReplayRecordStore({ root: input.agentQaRoot, outputDir }),\n scoreStore: new FsScoreStore({ root: input.agentQaRoot, outputDir }),\n })\n spend.screens++\n const sample = firstSample(candidate)\n if (sample) candidateSamples.set(id, sample)\n seedHonored &&= honored(sample)\n const score = loadScoreRecord(join(outputDir, ...id.split('/').map(slugBranch)))\n row.candidate = arm(candidateCassette, candidate, score.kind === 'loaded' ? score.record : undefined,\n corpus.snapshot.labelsById.get(cassette.id), replayJudgeRequest(replay.judge))\n const cost = buildEvalReport([\n {\n cassetteId: id,\n outcome: candidate,\n score: score.kind === 'loaded' ? score.record.score : undefined,\n },\n ])\n spend.promptTokens += cost.totalCost.promptTokens + cost.honesty.judge.cost.inputTokens\n spend.completionTokens += cost.totalCost.completionTokens + cost.honesty.judge.cost.outputTokens\n }\n const diffed = diffArms(rows)\n const decisionInput = {\n kind: injection.kind,\n sameFamilyRefused,\n targets: diffed.filter((row) => row.origin === 'target-step'),\n collateral: diffed.filter((row) => row.origin === 'gate-set'),\n }\n if (\n !rows.some(\n ({ origin, baseline, candidate }) =>\n origin === 'gate-set' &&\n baseline.kind === 'scored' &&\n candidate.kind === 'scored' &&\n FLOOR_AXES.some(\n (axis) =>\n baseline.vector.axes[axis] !== 'not-applicable' &&\n candidate.vector.axes[axis] !== 'not-applicable',\n ),\n )\n ) {\n const fold = foldPerAxisScore(rows, floor.axes)\n receipt.perAxisScore = fold.perAxisScore\n receipt.floorAbsentAxes = fold.floorAbsentAxes\n receipt.population = fold.population\n receipt.samples.seedHonored = seedHonored\n receipt.samples.modelCalls = spend.modelCalls\n return abstain('collateral-unscorable')\n }\n const probe = decideGate1({ ...decisionInput, crossCheck: 'inconclusive' })\n let crossCheck: CrossCheck = 'not-run'\n const firstBaseline = cacheById.get(targets[0]!.cassette.id)\n const base =\n firstBaseline?.kind === 'cached'\n ? firstBaseline\n : cache.rows.find((row): row is Cached => row.kind === 'cached')!\n receipt.baselineSource = { runRoot: base.root, seed: base.seed, seedSource: base.seedSource }\n receipt.samples = { k: input.k, seeds: [base.seed], seedHonored, modelCalls: spend.modelCalls }\n receipt.samples.detail = targets.flatMap(({ cassette }) => {\n const cached = cacheById.get(cassette.id)\n if (cached?.kind !== 'cached') return []\n const effective = effectiveGold(cassette, corpus.snapshot.labelsById.get(cassette.id))\n if (effective.kind === 'refused') return []\n const goldKey = decisionIdentityKey(\n computeDecisionIdentity(effective.cassette.sidecar.goldAction, cassette.input.stateBefore.elements),\n )\n return [true, false].map((withRecord) => {\n const sample = withRecord ? candidateSamples.get(cassette.id) : firstSample(cached.replay)\n const outcome = outcomeOf(sample)\n return {\n withRecord,\n seed: cached.seed,\n kind: outcome.kind,\n matchesGold:\n outcome.kind === 'decision' && decisionIdentityKey(outcome.identity) === goldKey,\n }\n })\n })\n const fixedTargetIds = new Set(\n decisionInput.targets.filter((row) => row.headline === 'fixed').map((row) => row.cassetteId),\n )\n if (probe.verdict !== 'fail' && fixedTargetIds.size > 0) {\n const result = await removalFlipsOutcome({\n recordId: injection.candidateId,\n mode: { kind: 'injected', injection },\n k: input.k,\n baseSeed: base.seed,\n gate1Dir,\n replay,\n cassettes: targets\n .filter((target) => fixedTargetIds.has(target.cassette.id))\n .map((target) => {\n const cached = cacheById.get(target.cassette.id) as Cached\n return {\n ...target,\n labelRecord: corpus.snapshot.labelsById.get(target.cassette.id),\n baseSeed: cached.seed,\n seedHonored: cached.seedHonored,\n existing: {\n withRecord: candidateSamples.get(target.cassette.id)!,\n withoutRecord: firstSample(cached.replay)!,\n },\n }\n }),\n })\n crossCheck = result.crossCheck\n notices.push(...result.notices)\n spend.screens += result.screens\n spend.promptTokens += result.promptTokens\n spend.completionTokens += result.completionTokens\n receipt.samples = {\n k: input.k,\n seeds: result.seeds,\n seedHonored: seedHonored && result.seedHonored,\n modelCalls: spend.modelCalls,\n detail: result.detail,\n }\n }\n const decision = decideGate1({ ...decisionInput, crossCheck })\n const fold = foldPerAxisScore(rows, floor.axes)\n Object.assign(receipt, {\n perAxisScore: fold.perAxisScore,\n floorAbsentAxes: fold.floorAbsentAxes,\n population: fold.population,\n verdict: decision.verdict,\n reasons: decision.reasons,\n crossCheck: decision.crossCheck,\n harmed: decision.harmed.map(harm),\n unverifiedFlips: decision.unverifiedFlips.map(harm),\n })\n receipt.targets = targets.map(({ cassette }) => {\n const row = rows.find((row) => row.cassetteId === cassette.id)!\n return {\n cassetteId: cassette.id,\n runId: cassette.runId,\n stepIndex: cassette.stepIndex,\n decisionOrdinal: cassette.decisionOrdinal,\n source: located.kind,\n baselineCorrect:\n row.baseline.kind === 'scored' && row.baseline.vector.axes.headline === 'correct',\n candidateCorrect:\n row.candidate.kind === 'scored' && row.candidate.vector.axes.headline === 'correct',\n baselineBriefSource: row.baseline.kind === 'scored' ? row.baseline.briefSource : 'refused',\n candidateBriefSource: row.candidate.kind === 'scored' ? row.candidate.briefSource : 'refused',\n }\n })\n const product = productFloorRows(floor, injection.product)\n if (product !== undefined) receipt.productFloor = product\n receipt.generalization = generalizationDisclosure({\n targets: decisionInput.targets,\n heldOut: decisionInput.collateral.filter((row) => row.split === 'held-out'),\n })\n spend.wallClockMs = Math.max(0, Math.round(clock() - started))\n receipt.samples.modelCalls = spend.modelCalls\n if (!receipt.samples.seedHonored)\n notices.push('seedHonored=false: samples collapse to repeat variance on this provider')\n input.onProgress?.(\n `gate1 candidate=${injection.candidateId}: screens=${spend.screens} modelCalls=${spend.modelCalls} promptTokens=${spend.promptTokens} completionTokens=${spend.completionTokens} wallClock=${spend.wallClockMs}ms seedHonored=${receipt.samples.seedHonored}`,\n )\n return finish()\n}\n","// 2026-09-07, 417 D-05/D-06/D-07: identity-bearing profile run roots (F-02).\n// Read-only cache resolution; a corpus change does not invalidate an individual cassette.\nimport { existsSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { canonicalJson, type ReplayCassetteOutcome } from '@vostride/agent-qa-eval'\nimport { sha256hex, slugBranch } from '@vostride/agent-qa-schema'\nimport { loadReplayRecord, loadScoreRecord } from './replay-read.js'\nimport { loadStagedReport } from './report-store.js'\nimport type { ScoreRecord } from './score-store.js'\nimport { baselineReplaySchema, baselineScoreSchema } from './baseline-cache-guards.js'\n\nexport function listBaselineRunRoots(\n agentQaRoot: string,\n profileKey: string,\n): {\n root: string\n kind: 'gate' | 'floor'\n seed?: number\n}[] {\n const roots: ReturnType<typeof listBaselineRunRoots> = []\n const gate = join(agentQaRoot, 'eval', 'gate', slugBranch(profileKey))\n if (existsSync(gate)) roots.push({ root: gate, kind: 'gate' })\n const floor = join(agentQaRoot, 'eval', 'floor', slugBranch(profileKey))\n if (!existsSync(floor)) return roots\n for (const entry of readdirSync(floor, { withFileTypes: true }).sort((a, b) =>\n a.name.localeCompare(b.name),\n )) {\n const match = /^r\\d+-seed(-?\\d+)$/.exec(entry.name)\n if (entry.isDirectory() && match && Number.isSafeInteger(Number(match[1]))) {\n roots.push({ root: join(floor, entry.name), kind: 'floor', seed: Number(match[1]) })\n }\n }\n return roots\n}\n\nexport type BaselineCacheRow =\n | {\n cassetteId: string\n kind: 'cached'\n root: string\n replay: ReplayCassetteOutcome\n score: ScoreRecord\n seed: number\n seedSource: string\n seedHonored: boolean\n }\n | { cassetteId: string; kind: 'refused'; root: string; reason: string }\n | { cassetteId: string; kind: 'uncached'; reason: string }\nexport interface BaselineCacheResolution {\n rows: BaselineCacheRow[]\n roots: string[]\n}\n\nexport function resolveBaselineCache(input: {\n agentQaRoot: string\n profileKey: string\n fingerprint: string\n matcherVersion: number\n plannerModelId: string\n judgeIdentity?: { judgeModelId: string; judgeVersion: number }\n gateRootSeed: number\n gateRootSeedSource: string\n cassettes: readonly { id: string; promptInputHash: string }[]\n}): BaselineCacheResolution {\n const resolved = new Map<string, BaselineCacheRow>()\n const failures = new Map<string, string>()\n const roots = new Set<string>()\n for (const run of listBaselineRunRoots(input.agentQaRoot, input.profileKey)) {\n const reportsDir = join(run.root, 'reports')\n let names: string[] = []\n try {\n names = readdirSync(reportsDir)\n .filter((name) => /^[^.]+\\.json$/.test(name))\n .sort()\n } catch {\n /* cold root */\n }\n const reports = names.map((name) =>\n loadStagedReport(input.agentQaRoot, name.slice(0, -5), reportsDir),\n )\n const matchingReports = reports.filter(\n (read): read is Extract<typeof read, { kind: 'loaded' }> =>\n read.kind === 'loaded' &&\n read.report.runIdentity?.fingerprint === input.fingerprint &&\n read.report.matcherVersion === input.matcherVersion,\n )\n if (matchingReports.length === 0) {\n const reason = reports.some((read) => read.kind === 'loaded')\n ? 'report fingerprint or matcherVersion mismatch'\n : 'missing or refused replay record report'\n for (const cassette of input.cassettes) failures.set(cassette.id, reason)\n continue\n }\n for (const cassette of input.cassettes) {\n if (resolved.has(cassette.id)) continue\n const miss = (reason: string) => failures.set(cassette.id, reason)\n const dir = join(run.root, 'replays', ...cassette.id.split('/').map(slugBranch))\n const loaded = loadReplayRecord(dir)\n if (loaded.kind !== 'loaded') {\n miss('missing or refused replay record')\n continue\n }\n const replay = loaded.outcome\n if (!baselineReplaySchema.safeParse(replay).success) {\n miss('invalid replay record: malformed leaf samples, refusal, or replay metadata')\n continue\n }\n if (replay.cassetteId !== cassette.id) {\n miss('replay cassetteId mismatch')\n continue\n }\n if ('kind' in replay) {\n resolved.set(cassette.id, {\n cassetteId: cassette.id,\n kind: 'refused',\n root: run.root,\n reason: replay.reason,\n })\n roots.add(run.root)\n continue\n }\n if (replay.granularity !== 'leaf') {\n miss('replay is not a leaf')\n continue\n }\n if (replay.promptDrift?.recordedHash !== cassette.promptInputHash) {\n miss('promptInputHash mismatch: promptDrift.recordedHash differs')\n continue\n }\n if (replay.replayedModel?.modelId !== input.plannerModelId) {\n miss('replayedModel.modelId mismatch')\n continue\n }\n const score = loadScoreRecord(dir)\n if (score.kind !== 'loaded') {\n miss(score.kind === 'refused' ? 'invalid score record: malformed judge metadata or scoring context' : 'missing or refused score record')\n continue\n }\n if (!baselineScoreSchema.safeParse(score.record).success) {\n miss(\n 'invalid score record: malformed score, diffs, judge context, or nested cassetteId/matcherVersion identities',\n )\n continue\n }\n if (score.record.cassetteId !== cassette.id) {\n miss('score cassetteId mismatch')\n continue\n }\n if (score.record.matcherVersion !== input.matcherVersion) {\n miss('score matcherVersion mismatch')\n continue\n }\n if (score.record.scoringContext !== undefined && score.record.scoringContext.replayDigest !==\n sha256hex(canonicalJson({ ...replay, executionSeed: undefined }))) {\n miss('score replayDigest mismatch')\n continue\n }\n const judge = score.record.judge\n if (\n input.judgeIdentity === undefined\n ? judge !== undefined\n : judge?.judgeModelId !== input.judgeIdentity.judgeModelId ||\n judge?.judgeVersion !== input.judgeIdentity.judgeVersion\n ) {\n miss('judge identity mismatch')\n continue\n }\n // A gate root can hold multiple batch reports. Admit against the publication\n // that binds this row, never whichever filename happens to sort first.\n const replayDigest = sha256hex(canonicalJson(replay))\n const scoreDigest = sha256hex(canonicalJson(score.record))\n const report = matchingReports.find((candidate) => {\n const generation = candidate.replayGeneration\n if (generation === undefined)\n return (\n run.kind === 'floor' &&\n (Reflect.get(replay, 'executionSeed') === undefined ||\n Reflect.get(replay, 'executionSeed') === run.seed)\n )\n const matching = generation.records.filter((record) => record.cassetteId === cassette.id)\n const recorded = matching[0]\n return (\n matching.length === 1 &&\n recorded?.replayDigest === replayDigest &&\n recorded.scoreDigest === scoreDigest &&\n Reflect.get(replay, 'executionSeed') === generation.seed &&\n (run.seed === undefined || run.seed === generation.seed)\n )\n })\n if (report === undefined) {\n miss(\n run.kind === 'gate' && matchingReports.every((row) => row.replayGeneration === undefined)\n ? 'gate replay seed is unproven: missing run publication generation'\n : 'replay generation mismatch: seed or record digests differ from run publication',\n )\n continue\n }\n const generation = report.replayGeneration\n resolved.set(cassette.id, {\n cassetteId: cassette.id,\n kind: 'cached',\n root: run.root,\n replay,\n score: score.record,\n seed: generation?.seed ?? run.seed!,\n seedSource: generation === undefined ? 'run-dir' : 'run-publication',\n seedHonored: report.report.seedHonored === true,\n })\n roots.add(run.root)\n }\n }\n return {\n rows: input.cassettes.map(\n (cassette) =>\n resolved.get(cassette.id) ?? {\n cassetteId: cassette.id,\n kind: 'uncached',\n reason: failures.get(cassette.id) ?? 'missing replay record',\n },\n ),\n roots: [...roots],\n }\n}\n","// Admission for the leaf-only baseline cache. Validate without replacing the persisted\n// objects: publication digests must still cover the complete original record values.\nimport { z } from 'zod'\nimport {\n actionWireSchema,\n BRIEF_SOURCES,\n TURN_MATCHES,\n REPLAY_REFUSAL_REASONS,\n projectMatcherConfigContract,\n scoringContextSchema,\n judgeIdentitySchema,\n judgeMemberOutcomeSchema,\n judgeUsageSchema,\n hasValidScoreJudgeMetadata,\n JUDGE_ABSTENTION_CAUSES,\n JUDGE_CONFIG,\n canonicalJson,\n} from '@vostride/agent-qa-eval'\nimport { sha256hex } from '@vostride/agent-qa-schema'\nimport { TIER_ORDER } from '@vostride/agent-qa-safety'\n\nconst integer = z.number().int().nonnegative().safe()\nconst ratio = z.number().min(0).max(1)\nconst hash = z.string().regex(/^[a-f0-9]{64}$/)\nconst identity = z.object({\n opClass: z.string(),\n target: z.object({ role: z.string(), nameNormalized: z.string(), ordinal: integer }).optional(),\n value: z.string().optional(),\n})\nconst model = z.object({ provider: z.string(), modelId: z.string() })\nconst drift = z.object({\n drift: z.boolean(),\n harnessDrift: z.boolean(),\n recordedHash: hash,\n recomputedHash: hash,\n declaredDelta: z.object({ kind: z.enum(['injected', 'removed']), id: z.string() }).optional(),\n})\nconst agreement = z.object({\n k: integer.min(1),\n agreementRate: ratio,\n noConsensus: z.boolean(),\n harnessErrorCount: integer,\n modal: z.object({ identity, count: integer.min(1) }).optional(),\n})\nconst sample = z.object({\n sampleIndex: integer,\n durationMs: z.number().nonnegative(),\n unsupportedFeatures: z.array(z.string()).optional(),\n providerFingerprint: z.string().optional(),\n tokenUsage: z\n .object({ promptTokens: integer, completionTokens: integer, totalTokens: integer })\n .optional(),\n outcome: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('decision'), action: actionWireSchema, identity }),\n z.object({ kind: z.literal('planner-failure'), reason: z.string(), message: z.string() }),\n z.object({\n kind: z.literal('unservable-divergence'),\n tool: z.string(),\n args: z.record(z.string(), z.unknown()),\n }),\n z.object({ kind: z.literal('harness-error'), message: z.string() }),\n ]),\n})\nconst refusal = z.object({\n kind: z.literal('integrity-refusal'),\n granularity: z.never().optional(),\n cassetteId: z.string().min(1),\n reason: z.enum(REPLAY_REFUSAL_REASONS),\n detail: z.string(),\n})\nconst leafReplay = z\n .object({\n kind: z.never().optional(),\n granularity: z.literal('leaf'),\n cassetteId: z.string().min(1),\n samples: z.array(sample).min(1),\n agreement,\n modalDecision: identity.optional(),\n promptDrift: drift,\n briefSource: z.enum(BRIEF_SOURCES),\n turnMatch: z.enum(TURN_MATCHES).optional(),\n replayedModel: model,\n recordedModel: model.optional(),\n totalDurationMs: z.number().nonnegative(),\n unconsumedExchanges: z.array(\n z.object({ tool: z.string(), args: z.record(z.string(), z.unknown()) }),\n ),\n executionSeed: z.number().int().safe().optional(),\n })\n .refine(\n (value) =>\n value.agreement.k === value.samples.length &&\n value.samples.every((row, index) => row.sampleIndex === index) &&\n value.agreement.harnessErrorCount <= value.samples.length &&\n (value.agreement.modal?.count ?? 0) <= value.samples.length,\n 'sample indices and agreement must describe the stored sample array',\n )\n\nexport const baselineReplaySchema = z.union([refusal, leafReplay])\n\nconst matcherConfig = projectMatcherConfigContract().config\nconst identityLevels =\n 'identityLadder' in matcherConfig ? Object.keys(matcherConfig.identityLadder) : []\n\nconst breakdown = z.object({\n tierReached: z.union([z.literal(1), z.literal(2), z.literal(3)]),\n axes: z.object({\n opClass: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('match'), opClass: z.string() }),\n z.object({ kind: z.literal('mismatch'), goldClass: z.string(), candidateClass: z.string() }),\n ]),\n elementIdentity: z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('scored'),\n level: z.enum(identityLevels),\n numeric: ratio,\n tier: z.union([z.literal(2), z.literal(3)]),\n }),\n z.object({\n kind: z.literal('unscorable'),\n cause: z.enum(['no-gold-evidence', 'no-candidate-geometry', 'coordspace-mismatch']),\n }),\n z.object({ kind: z.literal('not-evaluated') }),\n ]),\n value: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('scored'), f1: ratio, band: z.enum(['full', 'mid', 'low']) }),\n z.object({ kind: z.literal('not-evaluated') }),\n z.object({ kind: z.literal('not-applicable') }),\n ]),\n }),\n sideEffect: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('none') }),\n z.object({ kind: z.literal('flagged'), reason: z.string(), riskFamily: z.enum(TIER_ORDER) }),\n ]),\n loop: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('none') }),\n z.object({ kind: z.literal('not-applicable') }),\n z.object({ kind: z.literal('flagged'), priorStepIndex: integer }),\n ]),\n})\nconst confidence = z.enum(['high', 'medium', 'low'])\nconst tieCause = z.enum(['partial-identity', 'value-mid-band', 'no-consensus'])\nconst judgeStamp = z.object({\n judgeId: z.string(),\n judgeVersion: integer,\n usage: judgeUsageSchema.optional(),\n members: z.array(judgeMemberOutcomeSchema).optional(),\n})\nconst decisionScore = z.discriminatedUnion('kind', [\n breakdown.extend({\n kind: z.literal('scored'),\n matcherVersion: integer,\n judgeSettled: judgeStamp\n .extend({\n axis: z.enum(['element-identity', 'value']),\n resolution: z.enum(['equivalent', 'different']),\n cause: tieCause,\n confidence,\n })\n .optional(),\n }),\n z.object({ kind: z.literal('miss-by-failure'), reason: z.string(), matcherVersion: integer }),\n z.object({\n kind: z.literal('unresolved-tie'),\n cause: tieCause,\n partial: breakdown.optional(),\n matcherVersion: integer,\n judgeOutcome: z\n .discriminatedUnion('kind', [\n judgeStamp.extend({\n kind: z.literal('abstained'),\n confidence: confidence.optional(),\n cause: z.enum(JUDGE_ABSTENTION_CAUSES),\n }),\n judgeStamp.extend({\n kind: z.literal('judge-error'),\n reason: z.enum(['provider-error', 'unparseable-output']),\n detail: z.string(),\n }),\n z.object({\n kind: z.literal('not-invoked'),\n reason: z.enum(['no-judge-configured', 'no-eligible-judge']),\n families: z\n .object({\n judge: z.string().optional(),\n replayed: z.string().optional(),\n recorded: z.string().optional(),\n })\n .optional(),\n }),\n ])\n .optional(),\n }),\n])\nconst scoreEntry = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('decision'),\n decisionOrdinal: integer,\n stepIndex: integer.optional(),\n score: decisionScore,\n }),\n z.object({\n kind: z.literal('never-scored'),\n decisionOrdinal: integer,\n stepIndex: integer.optional(),\n reason: z.enum([\n 'all-samples-harness-error',\n 'modal-representative-missing',\n 'missing-cassette-decision',\n 'missing-executable-correction', 'invalid-executable-correction', 'label-identity-mismatch',\n 'stale-scoring-context',\n ]),\n matcherVersion: integer,\n }),\n])\n\nconst baselineScoreShape = z\n .object({\n cassetteId: z.string().min(1),\n matcherVersion: integer,\n score: z.object({ kind: z.literal('leaf'), cassetteId: z.string().min(1), entry: scoreEntry }),\n scoringContext: scoringContextSchema.optional(),\n diffs: z.array(\n z.object({\n kind: z.enum(['scored', 'miss-by-failure', 'unresolved-tie']),\n cassetteId: z.string().min(1),\n decisionOrdinal: integer,\n stepIndex: integer.optional(),\n matcherVersion: integer,\n goldIdentity: identity,\n candidateIdentity: identity.optional(),\n replay: z.object({\n promptDrift: drift,\n agreement,\n replayedModel: model,\n recordedModel: model.optional(),\n }),\n }),\n ),\n judge: judgeIdentitySchema.optional(),\n })\n .refine((record) => {\n const entry = record.score.entry\n return (\n record.score.cassetteId === record.cassetteId &&\n (entry.kind === 'decision' ? entry.score.matcherVersion : entry.matcherVersion) ===\n record.matcherVersion &&\n record.diffs.every(\n (diff) =>\n diff.cassetteId === record.cassetteId &&\n diff.matcherVersion === record.matcherVersion &&\n diff.decisionOrdinal === entry.decisionOrdinal &&\n diff.stepIndex === entry.stepIndex,\n )\n )\n }, 'nested score identities must match the admitted record')\n/** Validate original bytes: shape parsing must not strip additive fields before digest checks. */\nexport const baselineScoreSchema = z.custom<z.infer<typeof baselineScoreShape>>(value =>\n baselineScoreShape.safeParse(value).success && hasValidScoreJudgeMetadata(value))\n .refine(record => {\n const judge = record.judge\n // Historical single/no-judge records remain readable; a panel has always had context.\n if (judge !== undefined && (judge.judgeVersion !== JUDGE_CONFIG.judgeVersion ||\n judge.confidenceThreshold !== JUDGE_CONFIG.confidenceThreshold)) return false\n const context = record.scoringContext\n if (context === undefined) return judge?.panelSize === undefined\n return context.matcherVersion === record.matcherVersion &&\n context.finalScoreDigest === sha256hex(canonicalJson(record.score)) &&\n context.judgeIdentityDigest === sha256hex(canonicalJson(judge ?? null)) &&\n // A configured but ineligible judge can honestly leave no identity stamp.\n (judge === undefined || context.judgeRequest?.judgeModelId === judge.judgeModelId) &&\n (judge?.panelSize === undefined || context.judgeRequest?.allowSameFamily === false)\n }, 'cached score context must bind the current judge, request and final score')\n","import {\n adjudicatePanelComparison, assessPanelEligibility, createPanelIdentity,\n prepareJudgeCalibrationProbe, resolveJudgeCalibrationMinimum,\n summarizeJudgeCalibration,\n type BaselineProfileKeyInput, type JudgeCalibrationProbeObservation,\n type JudgeCalibrationMinimum, type JudgeTargetedCalibrationDisclosure, type UsageAggregator,\n} from '@vostride/agent-qa-eval'\nimport type { ModelProfile } from '@vostride/agent-qa-model'\nimport type { MaskFn } from '@vostride/agent-qa-schema'\nimport { bindJudgePanel, type JudgeBindingInput } from './judge-binding.js'\nimport { loadJudgeCalibrationEvidence } from './judge-calibration-evidence-source.js'\nimport { createJudgeCalibrationArtifact, publishJudgeCalibration, JudgeCalibrationEvidenceError,\n type JudgeCalibrationReadInput, type JudgeCalibrationPublication } from './judge-calibration-source.js'\n\nexport type RunJudgeCalibrationResult = Awaited<ReturnType<typeof runJudgePanelCalibration>>\n | JudgeCalibrationPublication\n | { kind: 'capability-gap'; status: 'capability-gap'; reason: 'panel-not-configured' | 'no-credential' | 'single-family-host';\n minN: number; minNSource: JudgeCalibrationMinimum['source']; n: 0; identity?: JudgeCalibrationReadInput['identity'];\n cost: { callBound: number; usage: { calls: number } }; artifactDisposition: 'not-created';\n judgeTargeted: JudgeTargetedCalibrationDisclosure }\n\n// 441-68 (GAP2-D6): the only paths whose declared type is a closed string-literal union. `[]` is\n// an array element. Top-level `reason` and `artifact.reason` are unions only in the capability-gap\n// arm, so they are added per arm below; everywhere else they are free text.\nconst JUDGE_CALIBRATION_VOCABULARY_PATHS = [\n 'kind', 'status', 'minNSource', 'artifactDisposition',\n 'judgeTargeted.basis', 'judgeTargeted.source', 'judgeTargeted.reason',\n 'entries[].credential', 'entries[].failures[]',\n 'rows[].kind', 'rows[].reason', 'rows[].axis',\n 'artifact.status', 'artifact.minNSource',\n 'artifact.judgeTargeted.basis', 'artifact.judgeTargeted.source', 'artifact.judgeTargeted.reason',\n] as const\n\nexport function maskJudgeCalibrationText<T>(value: T, mask: MaskFn): T {\n const kept = new Set<string>(JUDGE_CALIBRATION_VOCABULARY_PATHS)\n const top = value as { kind?: unknown; artifact?: { status?: unknown } } | null\n if (top?.kind === 'capability-gap') kept.add('reason')\n if (top?.artifact?.status === 'capability-gap') kept.add('artifact.reason')\n return maskJudgeLeaves(value, '', kept, mask) as T\n}\n\nfunction maskJudgeLeaves(value: unknown, path: string, kept: ReadonlySet<string>, mask: MaskFn): unknown {\n if (typeof value === 'string') return kept.has(path) ? value : mask(value)\n if (Array.isArray(value)) return value.map(entry => maskJudgeLeaves(entry, `${path}[]`, kept, mask))\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) =>\n [key, maskJudgeLeaves(entry, path ? `${path}.${key}` : key, kept, mask)]))\n }\n return value\n}\n\n/** Publication routing is separate from the forced probe, so a missing composite does no IO. */\nexport async function runJudgeCalibration(input: {\n commit?: boolean; replace?: boolean\n} & (\n | { kind: 'capability-gap'; reason: 'panel-not-configured' | 'no-credential' | 'single-family-host'; minN: JudgeCalibrationMinimum;\n publication?: JudgeCalibrationReadInput }\n | { kind: 'probe'; probe: RunJudgePanelCalibrationInput }\n)): Promise<RunJudgeCalibrationResult> {\n if (input.replace && !input.commit) return { kind: 'refused' as const, reason: '--replace requires --commit.' }\n if (input.kind === 'capability-gap' && (!input.publication || !input.commit)) return {\n kind: 'capability-gap' as const, status: 'capability-gap' as const, reason: input.reason,\n minN: input.minN.value, minNSource: input.minN.source, n: 0,\n cost: { callBound: 0, usage: { calls: 0 } }, artifactDisposition: 'not-created' as const,\n // This branch opens no committed root, so it has no bait content to report. Saying so is\n // the whole point: a zero here would be a clean bill of health nobody measured.\n judgeTargeted: { basis: 'raw' as const, source: 'unavailable' as const, reason: 'not-read' as const },\n ...(input.publication ? { identity: input.publication.identity } : {}),\n }\n if (input.kind === 'probe' && !input.commit) return runJudgePanelCalibration(input.probe)\n try {\n // 441 GAP3-D2: publication and drift are decided on the raw probe; only the return is masked.\n const preview = input.kind === 'probe' ? await probeJudgePanelCalibration(input.probe) : undefined\n const context: JudgeCalibrationReadInput = input.kind === 'probe'\n ? { ...input.probe, identity: preview!.identity, minN: input.probe.minN ?? resolveJudgeCalibrationMinimum() }\n : input.publication!\n if (input.kind === 'capability-gap' && input.reason === 'panel-not-configured') throw new Error('No composite')\n const artifact = createJudgeCalibrationArtifact(context, preview ?? { status: 'capability-gap',\n reason: input.kind === 'capability-gap' && input.reason === 'single-family-host' ? 'single-family-host' : 'no-credential' })\n // The post-probe reread must prove the snapshot actually measured, not a newer one.\n if (preview && (['profileKey', 'corpusDigest', 'goldSetDigest', 'replayEvidenceDigest', 'evidenceDigest'] as const)\n .some(key => artifact[key] !== preview[key])) return { kind: 'input-drift' as const, reason: 'Judge calibration evidence changed during the probe; retry.' }\n const published = await publishJudgeCalibration({ ...context, artifact, replace: input.replace })\n return input.kind === 'probe' ? maskJudgeCalibrationText(published, input.probe.mask) : published\n } catch (error) { return { kind: 'refused' as const, reason: 'Judge calibration evidence unavailable or invalid; inspect the selected corpus and saved replays.',\n ...(error instanceof JudgeCalibrationEvidenceError ? { skippedCounts: error.skippedCounts } : {}) } }\n}\n\nexport interface RunJudgePanelCalibrationInput {\n committedRoot: string\n agentQaRoot: string\n profile: BaselineProfileKeyInput\n replayProfile: ModelProfile\n members: readonly Omit<JudgeBindingInput, 'mask'>[]\n minN?: JudgeCalibrationMinimum\n replayRunRoots?: readonly string[]\n mask: MaskFn\n}\n\n/** Operator-only forced probe. Credentials and source action content never enter its DTO. */\nexport async function runJudgePanelCalibration(input: RunJudgePanelCalibrationInput) {\n const preview = await probeJudgePanelCalibration(input)\n try {\n return maskJudgeCalibrationText(preview, input.mask)\n } catch {\n throw new Error('Judge calibration probe failed; retry.')\n }\n}\n\nasync function probeJudgePanelCalibration(input: RunJudgePanelCalibrationInput) {\n try {\n if (input.members.length < 2) throw new Error('Explicit panel required')\n // Never manufacture a replacement canonical identity from a secret-bearing ID.\n if ([input.replayProfile.model, ...input.members.map(member => member.profile.model)]\n .some(id => input.mask(id) !== id)) throw new Error('Unsafe model identity')\n return await executeJudgePanelCalibration(input)\n } catch {\n throw new Error('Judge calibration probe failed; retry.')\n }\n}\n\nasync function executeJudgePanelCalibration(input: RunJudgePanelCalibrationInput) {\n const minN = input.minN ?? resolveJudgeCalibrationMinimum()\n resolveJudgeCalibrationMinimum(minN.value)\n if (input.profile.plannerModelId !== input.replayProfile.model) throw new Error('Calibration replay profile mismatch.')\n const identity = createPanelIdentity(input.members.map(member => member.profile.model))\n if (input.profile.judgeModelId !== identity.judgeModelId || input.profile.judgeVersion !== identity.judgeVersion) {\n throw new Error('Calibration panel profile mismatch.')\n }\n const read = loadJudgeCalibrationEvidence(input)\n const observations: JudgeCalibrationProbeObservation[] = []\n const memberModelIds = input.members.map(member => member.profile.model)\n for (const row of read.evidence) {\n // Re-read the admitted receipt, preserving genuine absence and unknown supplied IDs.\n const recordedModelId = row.recordedReceipt.receipt.model.declared?.modelId\n ?? row.recordedReceipt.receipt.model.resolvedModelId\n const eligibility = assessPanelEligibility({ memberModelIds,\n replayedModelId: input.replayProfile.model,\n ...(recordedModelId === undefined ? {} : { recordedModelId }) })\n const common = { decisionId: row.decisionId, replayedModelId: input.replayProfile.model,\n ...(recordedModelId === undefined ? {} : { recordedModelId }), truth: row.truth, eligibility }\n if (!eligibility.eligible) {\n observations.push({ ...common, kind: 'not-invoked', reason: 'no-eligible-judge' })\n continue\n }\n const probe = prepareJudgeCalibrationProbe(row)\n if (!probe) { observations.push({ ...common, kind: 'skipped', reason: 'missing-evidence' }); continue }\n try {\n const usage: UsageAggregator = { calls: 0 }\n const port = bindJudgePanel(input.members.map(member => ({ ...member, mask: input.mask })))\n const outcome = await adjudicatePanelComparison(port, probe.evidence, usage)\n observations.push({ ...common, kind: 'attempted', probe, outcome, usage })\n } catch {\n throw new Error('Judge calibration probe failed; retry.')\n }\n }\n // 422 D-12: RAW disclosure beside the measurement. The bait population is the committed\n // adversarial arm — never this run's gold, which the reader has already kept disjoint from it.\n const summary = summarizeJudgeCalibration({ observations, memberModelIds, minN, selected: read.selected,\n judgeTargeted: { ...(read.adversarialMembers === undefined\n ? { unavailable: 'corpus-unreadable' as const }\n : { members: read.adversarialMembers }),\n observedCassetteIds: read.evidence.map(row => row.goldCassetteId) } })\n return { kind: 'dry-run' as const, ...summary,\n identity, profileKey: read.profileKey,\n corpusDigest: read.corpusDigest, goldSetDigest: read.goldSetDigest,\n replayEvidenceDigest: read.replayEvidenceDigest, evidenceDigest: read.evidenceDigest,\n skippedCounts: read.skippedCounts,\n // Explicit safe projection: no source actions, prompts, auth, or arbitrary provider detail.\n rows: observations.map(row => ({ decisionId: row.decisionId, replayedModelId: row.replayedModelId,\n ...(row.recordedModelId === undefined ? {} : { recordedModelId: row.recordedModelId }),\n kind: row.kind, eligibility: row.eligibility, truth: row.truth,\n ...(row.kind === 'attempted' ? { axis: row.probe.axis, outcome: row.outcome,\n members: row.usage.members, usage: { calls: row.usage.calls,\n ...(row.usage.inputTokens === undefined ? {} : { inputTokens: row.usage.inputTokens }),\n ...(row.usage.outputTokens === undefined ? {} : { outputTokens: row.usage.outputTokens }) } } : { reason: row.reason }) })) }\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n activeMarkedCorpusEntries, canonicalJson, composeBaselineProfileKey, computeDecisionIdentity,\n isUnjudgedPanelRefusal,\n createScoringContext, deriveRunSlug, representativeDecisionSample, resolveJudgeCalibrationTruth,\n resolveProductPartition, selectJudgeCalibrationGold,\n type BaselineProfileKeyInput, type JudgeCalibrationDiagnostics, type JudgeCalibrationEvidence,\n type JudgeCalibrationGold, type JudgeCalibrationSkipReason, type JudgeTargetedCalibrationMember,\n type LeafReplayResult,\n} from '@vostride/agent-qa-eval'\nimport { HANDOFF_FILE, RUNS_SUBDIR, loadCompletedRunHandoff } from '@vostride/agent-qa-runner-local'\nimport { sha256hex, slugBranch, type MarkReceipt } from '@vostride/agent-qa-schema'\nimport { baselineReplaySchema, baselineScoreSchema } from './baseline-cache-guards.js'\nimport { listBaselineRunRoots } from './baseline-cache-read.js'\nimport { assertCalibrationPath } from './calibration-source.js'\nimport { readCommittedCorpus, readRunExclusions } from './committed-corpus-source.js'\nimport { FsMarkLedger, MARKS_LEDGER_FILE } from './mark-ledger.js'\nimport { loadStagedReport } from './report-store.js'\nimport type { ScoreRecord } from './score-store.js'\n\nexport interface LoadJudgeCalibrationEvidenceInput {\n committedRoot: string\n agentQaRoot: string\n profile: BaselineProfileKeyInput\n /** Explicit operator selection when supplied; never choose the newest matching directory. */\n replayRunRoots?: readonly string[]\n}\nexport interface JudgeCalibrationEvidenceRead {\n /** Executable selected gold before saved-replay admission; not a sum of skip diagnostics. */\n selected: number\n evidence: JudgeCalibrationEvidence[]\n skippedCounts: JudgeCalibrationDiagnostics\n corpusDigest: string\n goldSetDigest: string\n replayEvidenceDigest: string\n evidenceDigest: string\n profileKey: string\n selectedInputs: { decisionId: string; goldCassetteId: string; replayFile: string; reportFile: string; replayDigest: string; scoreDigest: string; reportDigest: string }[]\n /**\n * 422 D-12: the committed ADVERSARIAL population — the bait disclosure's source, never gold.\n *\n * ABSENT means this reader could not open the committed corpus at all, which is a different\n * fact from a corpus that holds no adversarial member; an empty array standing in for the\n * former would report a clean zero nobody measured.\n */\n adversarialMembers?: readonly JudgeTargetedCalibrationMember[]\n}\nconst hash = (value: unknown) => sha256hex(canonicalJson(value))\n\n/** Preflight every file a delegated reader might open, including dangling links. */\nfunction inspectTree(root: string, path: string): void {\n assertCalibrationPath(root, path)\n if (!existsSync(path)) return\n for (const entry of readdirSync(path, { withFileTypes: true })) {\n const child = join(path, entry.name)\n assertCalibrationPath(root, child)\n if (entry.isDirectory()) inspectTree(root, child)\n }\n}\n\n/** Operator-only IO. Every action/truth derivation stays in the neutral package. */\nexport function loadJudgeCalibrationEvidence(input: LoadJudgeCalibrationEvidenceInput): JudgeCalibrationEvidenceRead {\n const skippedCounts: JudgeCalibrationDiagnostics = {}\n const skip = (reason: JudgeCalibrationSkipReason) => { skippedCounts[reason] = (skippedCounts[reason] ?? 0) + 1 }\n const result: JudgeCalibrationEvidenceRead = { selected: 0, evidence: [], skippedCounts, corpusDigest: hash([]),\n goldSetDigest: hash([]), replayEvidenceDigest: hash([]), evidenceDigest: hash([]),\n profileKey: composeBaselineProfileKey(input.profile), selectedInputs: [] }\n const finish = () => {\n result.replayEvidenceDigest = hash(result.selectedInputs)\n result.evidenceDigest = hash({ profileKey: result.profileKey, corpusDigest: result.corpusDigest,\n goldSetDigest: result.goldSetDigest, replayEvidenceDigest: result.replayEvidenceDigest,\n evidence: result.evidence, skippedCounts })\n return result\n }\n try { inspectTree(input.committedRoot, input.committedRoot) }\n catch { skip('path-refused'); return finish() }\n const raw = readCommittedCorpus(input.committedRoot)\n // Set the moment the corpus IS readable, and never before: every path above returns with the\n // field still absent, which is what keeps \"could not open\" distinct from \"holds no bait\".\n result.adversarialMembers = raw.snapshot.entries\n .filter(entry => entry.split === 'adversarial')\n .map(entry => ({ cassetteId: entry.cassetteId, generator: entry.generator }))\n for (const _refusal of raw.refusals) skip('corpus-refused')\n const exclusions = readRunExclusions(input.committedRoot)\n if (exclusions.refusals.length) {\n for (const _refusal of exclusions.refusals) skip('corpus-refused')\n return finish()\n }\n const marks: MarkReceipt[] = []\n const excluded = new Set(raw.snapshot.excludedLabelIds)\n for (const exclusion of exclusions.exclusions) {\n for (const [id, cassette] of raw.snapshot.cassettesById) if (cassette.runId === exclusion.runId) excluded.add(id)\n }\n const runIds = [...new Set([...raw.snapshot.labelsById.values()].map(label => label.provenance.runId))].sort()\n for (const runId of runIds) {\n const run = join(input.agentQaRoot, RUNS_SUBDIR, deriveRunSlug(runId))\n const excludeRun = () => {\n for (const [id, cassette] of raw.snapshot.cassettesById) if (cassette.runId === runId) excluded.add(id)\n }\n try {\n assertCalibrationPath(input.agentQaRoot, join(run, MARKS_LEDGER_FILE))\n assertCalibrationPath(input.agentQaRoot, join(run, HANDOFF_FILE))\n } catch { skip('path-refused'); excludeRun(); continue }\n try {\n const ledger = new FsMarkLedger({ root: input.agentQaRoot, runId }).latestPerAddress()\n marks.push(...ledger)\n } catch { skip('marks-unreadable'); excludeRun(); continue }\n try {\n const handoff = loadCompletedRunHandoff(join(run, HANDOFF_FILE))\n if (handoff.runId !== runId || new Set(handoff.tests.map(member => member.testIndex)).size !== handoff.tests.length) throw new Error('foreign handoff')\n for (const [id, cassette] of raw.snapshot.cassettesById) {\n if (cassette.runId !== runId) continue\n const member = handoff.tests.find(row => row.testIndex === cassette.testIndex)\n const steps = member?.steps.filter(step => step.stepIndex === cassette.stepIndex)\n if (!member || member.testId !== cassette.testId || steps?.length !== 1\n || steps[0]!.subActions[cassette.decisionOrdinal] === undefined\n || raw.snapshot.entries.filter(entry => entry.cassetteId === id).some(entry => entry.product !== resolveProductPartition(handoff.scope))) {\n skip('handoff-refused'); excluded.add(id)\n }\n }\n } catch { skip('handoff-refused'); excludeRun() }\n }\n const snapshot = { ...raw.snapshot, entries: activeMarkedCorpusEntries(raw.snapshot, marks), excludedLabelIds: excluded }\n const selection = selectJudgeCalibrationGold({ snapshot, marks })\n result.selected = selection.gold.length\n Object.assign(skippedCounts, selection.skippedCounts)\n result.corpusDigest = selection.corpusDigest\n result.goldSetDigest = selection.goldSetDigest\n let runRoots: readonly string[]\n const coordinates = new Map<string, { index: number; seed?: number }>()\n try {\n // Guard parents before listBaselineRunRoots opens a profile directory.\n for (const kind of ['gate', 'floor']) assertCalibrationPath(input.agentQaRoot,\n join(input.agentQaRoot, 'eval', kind, slugBranch(result.profileKey)))\n runRoots = input.replayRunRoots ?? listBaselineRunRoots(input.agentQaRoot, result.profileKey).map(run => run.root)\n for (const root of runRoots) inspectTree(input.agentQaRoot, root)\n } catch { skip('path-refused'); return finish() }\n if (input.replayRunRoots === undefined) {\n const floor = join(input.agentQaRoot, 'eval', 'floor', slugBranch(result.profileKey))\n const indices = new Set<number>()\n for (const entry of existsSync(floor) ? readdirSync(floor, { withFileTypes: true }) : []) {\n const match = /^r(0|[1-9]\\d*)-seed(0|-?[1-9]\\d*)$/.exec(entry.name)\n const index = Number(match?.[1]), seed = Number(match?.[2])\n if (!entry.isDirectory() || !match || !Number.isSafeInteger(index) || !Number.isSafeInteger(seed) || indices.has(index)) {\n skip('ambiguous-replay'); return finish()\n }\n indices.add(index)\n coordinates.set(join(floor, entry.name), { index, seed })\n }\n coordinates.set(join(input.agentQaRoot, 'eval', 'gate', slugBranch(result.profileKey)), { index: Infinity })\n }\n const publications = [...new Set(runRoots)].sort().flatMap(root => {\n const directory = join(root, 'reports')\n if (!existsSync(directory)) return []\n return readdirSync(directory).filter(name => /^[^.]+\\.json$/.test(name)).sort().map(name => ({\n root, load: loadStagedReport(input.agentQaRoot, name.slice(0, -5), directory),\n }))\n })\n if (input.replayRunRoots === undefined && publications.some(publication => publication.load.kind !== 'loaded')) {\n skip('missing-profile-proof'); return finish()\n }\n for (const gold of selection.gold) {\n const candidates: { root: string; evidence: JudgeCalibrationEvidence; identity: JudgeCalibrationEvidenceRead['selectedInputs'][number] }[] = []\n const failures = new Set<JudgeCalibrationSkipReason>()\n let missingPublishedReplay = false\n for (const root of [...new Set(runRoots)].sort()) {\n const dir = join(root, 'replays', ...gold.goldCassetteId.split('/').map(slugBranch))\n const replayFile = join(dir, 'replay.json'), scoreFile = join(dir, 'score.json')\n let replay: LeafReplayResult, score: ScoreRecord\n try {\n assertCalibrationPath(input.agentQaRoot, replayFile)\n assertCalibrationPath(input.agentQaRoot, scoreFile)\n } catch { failures.add('path-refused'); continue }\n if (!existsSync(replayFile)) {\n const claimed = publications.some(publication => publication.root === root && publication.load.kind === 'loaded'\n && publication.load.replayGeneration?.records.some(row => row.cassetteId === gold.goldCassetteId))\n missingPublishedReplay ||= claimed\n failures.add('missing-replay'); continue\n }\n try {\n const value: unknown = JSON.parse(readFileSync(replayFile, 'utf8'))\n if (!baselineReplaySchema.safeParse(value).success || !value || typeof value !== 'object'\n || !('granularity' in value) || value.granularity !== 'leaf') { failures.add('malformed-replay'); continue }\n replay = value as LeafReplayResult\n } catch { failures.add('malformed-replay'); continue }\n if (replay.cassetteId !== gold.goldCassetteId || replay.replayedModel.modelId !== input.profile.plannerModelId\n || replay.promptDrift.recordedHash !== gold.cassette.receipt.promptInputHash\n || replay.promptDrift.harnessDrift || replay.promptDrift.declaredDelta !== undefined\n || replay.promptDrift.recomputedHash !== gold.cassette.receipt.promptInputHash\n || replay.samples.some(sample => sample.outcome.kind === 'decision' && canonicalJson(sample.outcome.identity)\n !== canonicalJson(computeDecisionIdentity(sample.outcome.action, gold.cassette.input.stateBefore.elements)))) {\n failures.add('foreign-replay'); continue\n }\n if (replay.agreement.noConsensus) { failures.add('ambiguous-replay'); continue }\n const modal = replay.agreement.modal\n const matchingSamples = replay.samples.filter(sample => sample.outcome.kind === 'decision'\n && canonicalJson(sample.outcome.identity) === canonicalJson(modal?.identity))\n if (!modal || modal.count !== matchingSamples.length\n || replay.agreement.agreementRate !== modal.count / replay.samples.length\n || canonicalJson(replay.modalDecision) !== canonicalJson(modal.identity)) {\n failures.add('malformed-replay'); continue\n }\n try {\n const value: unknown = JSON.parse(readFileSync(scoreFile, 'utf8'))\n if (!baselineScoreSchema.safeParse(value).success) { failures.add('stale-replay'); continue }\n score = value as ScoreRecord\n } catch { failures.add('stale-replay'); continue }\n if (!score.scoringContext || score.cassetteId !== gold.goldCassetteId\n || score.matcherVersion !== input.profile.matcherVersion\n || score.score.kind !== 'leaf' || score.score.entry.decisionOrdinal !== gold.cassette.decisionOrdinal\n || (score.score.entry.kind !== 'skipped' && score.score.entry.stepIndex !== undefined && score.score.entry.stepIndex !== gold.cassette.stepIndex)\n || canonicalJson(createScoringContext({ cassette: gold.cassette, labelRecord: gold.labelRecord,\n outcome: replay, score: score.score, judge: score.judge, judgeRequest: score.scoringContext.judgeRequest })) !== canonicalJson(score.scoringContext)) {\n failures.add('stale-replay'); continue\n }\n const replayDigest = hash(replay), scoreDigest = hash(score)\n const unjudgedRefusal = isUnjudgedPanelRefusal({ record: score, profile: input.profile,\n recordedModel: gold.recordedReceipt.receipt.model, replayedModelId: replay.replayedModel.modelId })\n const proofs = publications.filter(publication => publication.root === root && publication.load.kind === 'loaded')\n if (publications.some(publication => publication.root === root && publication.load.kind !== 'loaded')) failures.add('missing-profile-proof')\n let matched = false\n for (const publication of proofs) {\n const loaded = publication.load\n if (loaded.kind !== 'loaded') continue\n const { report, replayGeneration } = loaded\n if (report.runIdentity?.fingerprint !== input.profile.fingerprint\n || report.matcherVersion !== input.profile.matcherVersion || report.judgeIdentity === 'mixed'\n || (!(unjudgedRefusal && report.judge === undefined) &&\n (report.judge?.judgeModelId !== input.profile.judgeModelId || report.judge?.judgeVersion !== input.profile.judgeVersion))\n || (!unjudgedRefusal && (score.judge?.judgeModelId !== input.profile.judgeModelId || score.judge?.judgeVersion !== input.profile.judgeVersion))\n || (input.profile.judgeModelId?.startsWith('panel:') && canonicalJson(score.scoringContext.judgeRequest)\n !== canonicalJson({ judgeModelId: input.profile.judgeModelId, allowSameFamily: false }))) {\n failures.add('foreign-profile'); continue\n }\n if (report.runIdentity.corpusDigest !== result.corpusDigest) { failures.add('stale-replay'); continue }\n if (!replayGeneration) { failures.add('missing-profile-proof'); continue }\n if (coordinates.get(root)?.seed !== undefined && coordinates.get(root)!.seed !== replayGeneration.seed) {\n failures.add('foreign-replay'); continue\n }\n const refs = replayGeneration.records.filter(row => row.cassetteId === gold.goldCassetteId)\n if (refs.length !== 1 || refs[0]!.replayDigest !== replayDigest || refs[0]!.scoreDigest !== scoreDigest\n || Reflect.get(replay, 'executionSeed') !== replayGeneration.seed) { failures.add('stale-replay'); continue }\n const candidate = representativeDecisionSample(replay)\n if (!candidate) { failures.add('missing-candidate'); continue }\n matched = true\n candidates.push({ root, evidence: evidenceRow(gold, candidate, replay, result.profileKey, replayDigest),\n identity: { decisionId: gold.decisionId, goldCassetteId: gold.goldCassetteId, replayFile,\n reportFile: loaded.file, replayDigest, scoreDigest, reportDigest: hash(report) } })\n }\n if (!matched && proofs.length === 0) failures.add('missing-profile-proof')\n }\n // Auto-selection samples the producer's first global schedule slot, never the verdict.\n // Every present row must pass admission; malformed history cannot become a gate fallback.\n if (input.replayRunRoots === undefined) {\n const invalid = [...failures].filter(reason => reason !== 'missing-replay' || missingPublishedReplay)\n if (invalid.length) { for (const reason of invalid.sort()) skip(reason); continue }\n if (new Set(candidates.map(candidate => candidate.root)).size !== candidates.length) {\n skip('ambiguous-replay'); continue\n }\n candidates.sort((a, b) => coordinates.get(a.root)!.index - coordinates.get(b.root)!.index)\n if (candidates.length > 1) candidates.splice(1)\n }\n if (candidates.length !== 1) {\n if (candidates.length > 1) skip('ambiguous-replay')\n else if (failures.size) for (const reason of [...failures].sort()) skip(reason)\n else skip('missing-replay')\n continue\n }\n result.evidence.push(candidates[0]!.evidence)\n result.selectedInputs.push(candidates[0]!.identity)\n }\n return finish()\n}\n\nfunction evidenceRow(gold: JudgeCalibrationGold, candidate: JudgeCalibrationEvidence['candidate'], replay: LeafReplayResult,\n profileKey: string, replayDigest: string): JudgeCalibrationEvidence {\n return { ...gold, candidate, replayedModelId: replay.replayedModel.modelId, profileKey, replayDigest,\n truth: resolveJudgeCalibrationTruth({ gold, candidate }) }\n}\n","import { randomUUID } from 'node:crypto'\nimport { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { z } from 'zod'\nimport { canonicalJson, committedFileText, composeBaselineProfileKey, createPanelIdentity,\n projectJudgeConfigContract, projectJudgeTargetedCalibration, projectMatcherConfigContract, wilsonInterval,\n GENERATOR_KINDS, GENERATOR_PROVENANCES, JUDGE_CALIBRATION_MIN_N,\n JUDGE_TARGETED_CALIBRATION_UNAVAILABLE_REASONS,\n type JudgeCalibrationMinimum, type JudgeCalibrationDiagnostics, type JudgeIdentityBlock,\n} from '@vostride/agent-qa-eval'\nimport { sha256hex, slugBranch } from '@vostride/agent-qa-schema'\nimport { assertCalibrationPath } from './calibration-source.js'\nimport { loadJudgeCalibrationEvidence, type LoadJudgeCalibrationEvidenceInput } from './judge-calibration-evidence-source.js'\nimport { acquireMarkLock } from './mark-lock.js'\n\nexport const JUDGE_CALIBRATION_SCHEMA_VERSION = 2\nexport const JUDGE_CALIBRATION_SUBDIR = 'judge-calibration'\nconst hash = (value: unknown) => sha256hex(canonicalJson(value))\nconst same = (a: unknown, b: unknown) => canonicalJson(a) === canonicalJson(b)\nconst count = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER)\nconst digest = z.string().regex(/^[0-9a-f]{64}$/)\nconst id = z.string().min(1).refine(value => value.trim() === value && !/[\\u0000-\\u001f\\u007f]/.test(value))\nconst unit = z.number().finite().min(0).max(1)\nconst interval = z.object({ lower: unit, upper: unit, halfWidth: unit }).strict()\nconst rateFields = { numerator: count, denominator: count, rate: unit.optional() }\nconst validRate = (v: { numerator: number; denominator: number; rate?: number }) => v.numerator <= v.denominator\n && (v.denominator === 0 ? v.rate === undefined : v.rate === v.numerator / v.denominator)\nconst rate = z.object(rateFields).strict().refine(validRate)\nconst tallyFields = { settled: count, abstained: count, errors: count, n: count,\n numerator: count, denominator: count, agreement: unit.optional(), wilson95: interval.optional() }\nconst tally = z.object(tallyFields).strict()\nconst counts = z.object({ selected: count, admitted: count, eligible: count, attempted: count,\n eligibilityRefused: count, evidenceSkipped: count, truthComparable: count, unresolvedTruth: count }).strict()\nconst cost = z.object({ callBound: count,\n usage: z.object({ calls: count, inputTokens: count.optional(), outputTokens: count.optional() }).strict() }).strict()\nconst profileSchema = z.object({ plannerModelId: id, fingerprint: digest, matcherVersion: count,\n judgeModelId: id, judgeVersion: count }).strict()\nconst identitySchema = z.object({ judgeModelId: id, judgeFamily: z.string(), judgeVersion: count,\n confidenceThreshold: z.literal('high'),\n panelSize: count.min(2).max(3), members: z.array(z.object({ judgeModelId: id, judgeFamily: z.string() }).strict()).min(2).max(3) }).strict()\n/**\n * 422 D-12: the judge-targeted self-authorship subset, ADDITIVE-OPTIONAL and strictly validated.\n *\n * Absent is the pre-422-20 shape and stays admissible forever — an artifact written before the\n * field existed said nothing about bait, and a reader must not turn that silence into a zero.\n * Present is checked by the same closed-vocabulary rule the census mix uses: a provenance arm or\n * generator word from another build is a REFUSAL, not a value to pass into a disclosure.\n */\nconst closedCounts = <T extends string>(values: readonly [T, ...T[]]) => z.record(z.enum(values), count)\nconst authorRow = z.object({ authoringModel: id, authoringFamily: z.string(),\n panelMember: z.boolean(), probeAuthored: count.min(1), judgeTargeted: count }).strict()\nconst judgeTargetedBlock = z.union([\n z.object({ basis: z.literal('raw'), source: z.literal('unavailable'),\n reason: z.enum(JUDGE_TARGETED_CALIBRATION_UNAVAILABLE_REASONS) }).strict(),\n z.object({ basis: z.literal('raw'), source: z.literal('resolved'), total: count,\n metadataUnavailable: count, byProvenance: closedCounts(GENERATOR_PROVENANCES),\n byKind: closedCounts(GENERATOR_KINDS), judgeTargeted: count, selfAuthored: count,\n byAuthoringModel: z.array(authorRow), observedInCalibration: count }).strict(),\n])\nconst common = { schemaVersion: z.literal(JUDGE_CALIBRATION_SCHEMA_VERSION), generationId: digest,\n judgeTargeted: judgeTargetedBlock.optional(),\n profileKey: id, profile: profileSchema, identity: identitySchema, constitutionDigest: digest,\n corpusDigest: digest, goldSetDigest: digest, replayEvidenceDigest: digest, evidenceDigest: digest,\n minN: count.min(2), minNSource: z.enum(['default', 'flag']), selected: count, admitted: count, cost,\n skippedCounts: z.object({ 'missing-executable-correction': count.min(1) }).strict().optional() }\nconst schema = z.union([\n z.object({ ...common, status: z.literal('capability-gap'), reason: z.enum(['no-credential', 'single-family-host']), n: z.literal(0) }).strict(),\n z.object({ ...common, status: z.enum(['calibrated', 'uncalibrated']), n: count,\n counts, pooled: tally, perMember: z.array(z.object({ judgeModelId: id, ...tallyFields }).strict()),\n pooledAgreement: unit.optional(), wilson95: interval.optional(), abstention: rate,\n disagreement: z.object({ ...rateFields, pairs: z.array(z.object({ memberModelIds: z.tuple([id, id]), ...rateFields }).strict().refine(validRate)) }).strict().refine(validRate),\n }).strict(),\n])\nexport type JudgeCalibrationArtifact = z.infer<typeof schema>\nexport interface JudgeCalibrationReadInput extends LoadJudgeCalibrationEvidenceInput {\n identity: JudgeIdentityBlock\n minN: JudgeCalibrationMinimum\n}\nexport type JudgeCalibrationRead = { kind: 'absent' }\n | { kind: 'loaded'; artifact: JudgeCalibrationArtifact }\n | { kind: 'refused'; reason: string }\nexport type JudgeCalibrationPublication = { kind: 'committed' | 'unchanged'; artifact: JudgeCalibrationArtifact; path: string }\n | { kind: 'refused' | 'busy' | 'input-drift' | 'publication-failed'; reason: string }\n | { kind: 'write-conflict'; path: string }\n\n/** Locator only. Admission always checks the complete key and profile separately. */\nexport function judgeCalibrationPath(profileKey: string): string {\n return `reports/${JUDGE_CALIBRATION_SUBDIR}/${slugBranch(profileKey)}.json`\n}\nexport function judgeCalibrationGenerationId(body: unknown): string { return hash(body) }\n\n/** Strict syntax and arithmetic, including independently recomputed Wilson bounds. */\nexport function guardJudgeCalibration(value: unknown): JudgeCalibrationArtifact | undefined {\n try { return guardArtifact(value) } catch { return undefined }\n}\nfunction guardArtifact(value: unknown): JudgeCalibrationArtifact | undefined {\n const parsed = schema.safeParse(value)\n if (!parsed.success) return undefined\n const a = parsed.data, { generationId, ...body } = a\n if (hash(body) !== generationId || a.constitutionDigest !== hash(projectJudgeConfigContract())\n || a.profile.matcherVersion !== projectMatcherConfigContract().version\n || a.profileKey !== composeBaselineProfileKey(a.profile)\n || !same(a.identity, createPanelIdentity(a.identity.members.map(member => member.judgeModelId)))\n || a.profile.judgeModelId !== a.identity.judgeModelId || a.profile.judgeVersion !== a.identity.judgeVersion\n || (a.minNSource === 'default' && a.minN !== JUDGE_CALIBRATION_MIN_N) || a.admitted > a.selected) return undefined\n const subset = a.judgeTargeted\n if (subset?.source === 'resolved') {\n const sum = (counts: Record<string, number>) => Object.values(counts).reduce((n, value) => n + value, 0)\n const authors = subset.byAuthoringModel\n const ids = authors.map(row => row.authoringModel)\n if (sum(subset.byProvenance) + subset.metadataUnavailable !== subset.total\n || sum(subset.byKind) + subset.metadataUnavailable !== subset.total\n || subset.judgeTargeted > Math.min(subset.byProvenance.probe, subset.byKind['judge-targeted'])\n || subset.selfAuthored > subset.judgeTargeted || subset.observedInCalibration > subset.judgeTargeted\n || !same(ids, [...ids].sort()) || new Set(ids).size !== ids.length\n || authors.some(row => row.judgeTargeted > row.probeAuthored)\n || authors.reduce((n, row) => n + row.probeAuthored, 0) !== subset.byProvenance.probe\n || authors.reduce((n, row) => n + row.judgeTargeted, 0) !== subset.judgeTargeted\n || authors.filter(row => row.panelMember).reduce((n, row) => n + row.judgeTargeted, 0) !== subset.selfAuthored) return undefined\n }\n if (a.status === 'capability-gap') return same(a.cost, { callBound: 0, usage: { calls: 0 } }) ? a : undefined\n const c = a.counts, ids = a.identity.members.map(member => member.judgeModelId)\n if (a.n !== a.pooled.n || (a.status === 'calibrated') !== (a.n >= a.minN)\n || c.selected !== a.selected || c.admitted !== a.admitted || c.admitted > c.selected\n || c.eligible + c.eligibilityRefused !== c.admitted || c.attempted > c.eligible\n || c.evidenceSkipped !== c.selected - c.eligibilityRefused - c.attempted\n || c.truthComparable + c.unresolvedTruth !== c.attempted\n || a.cost.callBound !== c.attempted * ids.length * 2 || a.cost.usage.calls !== a.cost.callBound\n || (c.attempted === 0 && (a.cost.usage.inputTokens !== undefined || a.cost.usage.outputTokens !== undefined))\n || !same(a.perMember.map(member => member.judgeModelId).sort(), [...ids].sort())) return undefined\n for (const row of [a.pooled, ...a.perMember]) {\n if (row.settled + row.abstained + row.errors !== c.attempted || row.n > row.settled\n || row.n > c.truthComparable || row.settled - row.n > c.unresolvedTruth\n || row.denominator !== row.n || row.numerator > row.n\n || (row.n === 0 ? row.agreement !== undefined || row.wilson95 !== undefined\n : row.agreement !== row.numerator / row.n || !same(row.wilson95, wilsonInterval(row.numerator, row.n)))) return undefined\n }\n if (!same(a.pooledAgreement, a.pooled.agreement) || !same(a.wilson95, a.pooled.wilson95)\n || a.abstention.numerator !== a.pooled.abstained || a.abstention.denominator !== c.attempted) return undefined\n const expectedPairs = ids.flatMap((left, i) => ids.slice(i + 1).map(right => [left, right].sort().join('\\0'))).sort()\n const pairs = a.disagreement.pairs\n if (!same(pairs.map(pair => [...pair.memberModelIds].sort().join('\\0')).sort(), expectedPairs)\n || pairs.some(pair => {\n const settled = pair.memberModelIds.map(memberId => a.perMember.find(member => member.judgeModelId === memberId)!.settled)\n return pair.denominator > Math.min(...settled)\n || pair.denominator < Math.max(0, settled[0]! + settled[1]! - c.attempted)\n })\n || a.disagreement.numerator !== pairs.reduce((n, pair) => n + pair.numerator, 0)\n || a.disagreement.denominator !== pairs.reduce((n, pair) => n + pair.denominator, 0)) return undefined\n return a\n}\n\nfunction envelope(input: JudgeCalibrationReadInput) {\n const identity = identitySchema.parse(input.identity)\n if (!same(identity, createPanelIdentity(identity.members.map(member => member.judgeModelId)))) throw new Error('invalid identity')\n const { plannerModelId, fingerprint, matcherVersion, judgeModelId, judgeVersion } = input.profile\n const profile = profileSchema.parse({ plannerModelId, fingerprint, matcherVersion, judgeModelId, judgeVersion })\n if (profile.judgeModelId !== identity.judgeModelId || profile.judgeVersion !== identity.judgeVersion\n || (input.profile.judgeMemberModelIds !== undefined && !same(createPanelIdentity(input.profile.judgeMemberModelIds), identity))) throw new Error('foreign identity')\n return { profile, identity, profileKey: composeBaselineProfileKey(profile),\n minN: input.minN.value, minNSource: input.minN.source, constitutionDigest: hash(projectJudgeConfigContract()) }\n}\nexport class JudgeCalibrationEvidenceError extends Error {\n constructor(readonly skippedCounts: JudgeCalibrationDiagnostics) { super('Judge calibration evidence unavailable or refused.') }\n}\nfunction evidenceIdentity(input: JudgeCalibrationReadInput) {\n assertCalibrationPath(input.committedRoot, input.committedRoot)\n if (!lstatSync(input.committedRoot).isDirectory()) throw new Error('committed corpus unavailable')\n const read = loadJudgeCalibrationEvidence(input)\n // This semantic exclusion has no executable action oracle. All admission failures still refuse.\n if (Object.entries(read.skippedCounts).some(([reason, n]) => reason !== 'missing-executable-correction'\n && n !== undefined && n > 0)) throw new JudgeCalibrationEvidenceError(read.skippedCounts)\n const missingCorrection = read.skippedCounts['missing-executable-correction']\n return { corpusDigest: read.corpusDigest, goldSetDigest: read.goldSetDigest,\n replayEvidenceDigest: read.replayEvidenceDigest, evidenceDigest: read.evidenceDigest,\n selected: read.selected, admitted: read.evidence.length,\n // 422 D-12: derived from the SAME read the digests come from, with the same observed-gold\n // population the staged summary uses, so staged and stored cannot disagree.\n judgeTargeted: projectJudgeTargetedCalibration({\n ...(read.adversarialMembers === undefined ? { unavailable: 'corpus-unreadable' as const }\n : { members: read.adversarialMembers }),\n memberModelIds: input.identity.members?.map(member => member.judgeModelId) ?? [],\n observedCassetteIds: read.evidence.map(row => row.goldCassetteId),\n }),\n ...(missingCorrection ? { skippedCounts: { 'missing-executable-correction': missingCorrection } } : {}) }\n}\n\n/** Project only measured summary data; raw rows, credentials and audit paths cannot cross. */\nexport function createJudgeCalibrationArtifact(input: JudgeCalibrationReadInput,\n result: { status: 'capability-gap'; reason: 'no-credential' | 'single-family-host' }\n | ReturnType<typeof import('@vostride/agent-qa-eval').summarizeJudgeCalibration>,\n): JudgeCalibrationArtifact {\n const metrics = result.status === 'capability-gap' ? { ...result, n: 0, cost: { callBound: 0, usage: { calls: 0 } } }\n : { status: result.status, n: result.n, counts: result.counts, pooled: result.pooled,\n perMember: result.perMember, pooledAgreement: result.pooledAgreement, wilson95: result.wilson95,\n abstention: result.abstention, disagreement: result.disagreement, cost: result.cost }\n const body = JSON.parse(JSON.stringify({ schemaVersion: JUDGE_CALIBRATION_SCHEMA_VERSION, ...envelope(input), ...evidenceIdentity(input), ...metrics }))\n const artifact = guardJudgeCalibration(JSON.parse(JSON.stringify({ ...body, generationId: hash(body) })))\n if (!artifact) throw new Error('invalid calibration output')\n return artifact\n}\n\nfunction admitted(input: JudgeCalibrationReadInput, artifact: JudgeCalibrationArtifact): boolean {\n const { skippedCounts, judgeTargeted, ...bound } = { ...envelope(input), ...evidenceIdentity(input) }\n // Absence is evidence too: omitted diagnostics must not admit an invented artifact count.\n return same(artifact.skippedCounts, skippedCounts)\n // 422 D-12: an artifact written before the subset existed carries no block, and that silence\n // stays admissible forever. A block that IS present must be the one this corpus produces —\n // an internally consistent forgery claiming a clean adversarial arm is still a forgery.\n && (artifact.judgeTargeted === undefined || same(artifact.judgeTargeted, judgeTargeted))\n && Object.entries(bound).every(([key, value]) => same(Reflect.get(artifact, key), value))\n}\nfunction checkedText(root: string, path: string): string | undefined {\n assertCalibrationPath(root, path)\n try { if (!lstatSync(path).isFile()) throw new Error('invalid artifact path'); return readFileSync(path, 'utf8') }\n catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error }\n}\nexport function readJudgeCalibration(input: Omit<JudgeCalibrationReadInput, 'minN'> & {\n /** Operators may require an exact minimum; report consumers retain the recorded policy. */\n minN?: JudgeCalibrationMinimum\n}): JudgeCalibrationRead {\n try {\n const expected = envelope({ ...input, minN: input.minN ?? { value: JUDGE_CALIBRATION_MIN_N, source: 'default' } })\n const text = checkedText(input.committedRoot, join(input.committedRoot, judgeCalibrationPath(expected.profileKey)))\n if (text === undefined) return { kind: 'absent' }\n const artifact = guardJudgeCalibration(JSON.parse(text))\n if (!artifact || !admitted({ ...input, minN: input.minN ?? {\n value: artifact.minN, source: artifact.minNSource,\n } }, artifact)) return { kind: 'refused', reason: 'Judge calibration identity or evidence is invalid or stale.' }\n return { kind: 'loaded', artifact }\n } catch { return { kind: 'refused', reason: 'Judge calibration or evidence unavailable; inspect the profile and local corpus.' } }\n}\n\n/** One checked file, with immutable create or explicit atomic replace under the operator lock. */\nexport async function publishJudgeCalibration(input: JudgeCalibrationReadInput & {\n artifact: JudgeCalibrationArtifact; replace?: boolean; onBoundary?: (stage: string) => void;\n}): Promise<JudgeCalibrationPublication> {\n let release: (() => void) | undefined, temp: string | undefined\n try {\n const artifact = guardJudgeCalibration(input.artifact)\n if (!artifact || !admitted(input, artifact)) return { kind: 'refused', reason: 'Judge calibration identity or evidence is invalid or stale.' }\n const path = judgeCalibrationPath(artifact.profileKey), destination = join(input.committedRoot, path)\n const original = checkedText(input.committedRoot, destination)\n const originalInode = original === undefined ? undefined : lstatSync(destination).ino\n // Even replace cannot overwrite a foreign key or corrupted prior artifact.\n if (original !== undefined) {\n const previous = guardJudgeCalibration(JSON.parse(original))\n if (!previous || !same(previous.profile, artifact.profile) || !same(previous.identity, artifact.identity)) {\n return { kind: 'refused', reason: 'Existing judge calibration has an invalid or foreign identity.' }\n }\n }\n const lock = join(input.committedRoot, '.judge-calibration.lock')\n assertCalibrationPath(input.committedRoot, lock)\n mkdirSync(dirname(lock), { recursive: true })\n try { release = await acquireMarkLock(lock, 'judge-calibration', () => new Error('judge-calibration-busy')) }\n catch (error) { if (error instanceof Error && error.message === 'judge-calibration-busy') return { kind: 'busy', reason: 'Another judge calibration publisher holds the operator lock.' }; throw error }\n const inode = lstatSync(lock).ino, owner = checkedText(input.committedRoot, join(lock, 'owner.json'))\n const unchanged = () => {\n try { return lstatSync(lock).ino === inode && checkedText(input.committedRoot, join(lock, 'owner.json')) === owner\n && checkedText(input.committedRoot, destination) === original\n && (originalInode === undefined || lstatSync(destination).ino === originalInode)\n && admitted(input, artifact) } catch { return false }\n }\n input.onBoundary?.('after-lock')\n if (!unchanged()) return { kind: 'input-drift', reason: 'Judge calibration inputs or lock ownership changed; retry.' }\n const text = committedFileText(artifact)\n if (original === text) return { kind: 'unchanged', artifact, path }\n if (original !== undefined && !input.replace) return { kind: 'write-conflict', path }\n assertCalibrationPath(input.committedRoot, destination)\n mkdirSync(dirname(destination), { recursive: true })\n temp = join(dirname(destination), `.judge-calibration-${randomUUID()}.tmp`)\n assertCalibrationPath(input.committedRoot, temp)\n const fd = openSync(temp, 'wx', 0o600)\n try { writeFileSync(fd, text, 'utf8'); fsyncSync(fd) } finally { closeSync(fd) }\n const tempInode = lstatSync(temp).ino\n input.onBoundary?.('before-rename')\n if (!unchanged() || lstatSync(temp).ino !== tempInode || checkedText(input.committedRoot, temp) !== text) return { kind: 'input-drift', reason: 'Judge calibration inputs or destination changed before publication.' }\n assertCalibrationPath(input.committedRoot, destination)\n if (original === undefined) linkSync(temp, destination)\n else renameSync(temp, destination)\n return { kind: 'committed', artifact, path }\n } catch {\n return { kind: 'publication-failed', reason: 'Judge calibration publication interrupted; inspect local inputs and retry.' }\n } finally {\n if (temp) { try { unlinkSync(temp) } catch { /* Renamed or removed by the owner. */ } }\n release?.()\n }\n}\n","import { closeSync, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { calibrateLabels, canonicalJson, collectSoftPopulation, committedFileText, computeCorpusDigest, computeSoftWeight, createLabelRevision, deriveLabelRevisionId, type StandaloneLabelRecord } from '@vostride/agent-qa-eval'\nimport { sha256hex } from '@vostride/agent-qa-schema'\nimport { assertCalibrationPath, calibrationGenerationId, guardLabelCalibration, LABEL_CALIBRATION_PATH, LABEL_CALIBRATION_SCHEMA_VERSION, type LabelCalibrationArtifact } from './calibration-source.js'\nimport { readCommittedCorpus } from './committed-corpus-source.js'\nimport { loadCalibrationEvidence } from './calibration-evidence-source.js'\nimport { loadLabelEvidence } from './label-evidence-source.js'\nimport { committedLabelRevisionPath, FsCommittedRootStore } from './committed-root-store.js'\nimport { acquireMarkLock } from './mark-lock.js'\n\nexport interface RunLabelCalibrationInput {\n committedRoot: string\n agentQaRoot: string\n commit?: boolean\n replace?: boolean\n minGold?: { value: number; source: 'default' | 'cli' }\n /** Synchronous failure injection at actual publication boundaries; never supplied by learners. */\n onBoundary?: (stage: string) => void\n}\nexport type RunLabelCalibrationResult =\n | { kind: 'dry-run' | 'committed' | 'unchanged'; artifact: LabelCalibrationArtifact; refreshedCount: number }\n | { kind: 'refused' | 'busy' | 'input-drift' | 'publication-failed'; reason: string }\n | { kind: 'write-conflict'; path: string }\n\n// Outside label traversal: lock tombstones are runtime ownership, never label history.\nconst LOCK_PATH = '.label-calibration.lock'\nfunction markerText(root: string): string | undefined {\n const path = join(root, LABEL_CALIBRATION_PATH)\n assertCalibrationPath(root, path)\n try { return readFileSync(path, 'utf8') } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\nfunction prepare(input: RunLabelCalibrationInput) {\n if (input.minGold && (!Number.isSafeInteger(input.minGold.value) || input.minGold.value < 2 || !['default', 'cli'].includes(input.minGold.source))) throw new Error('invalid minimum')\n // Validate directory entries before readers can silently skip a symlinked product subtree.\n function checkTree(directory: string): void {\n assertCalibrationPath(input.committedRoot, directory)\n if (!existsSync(directory)) return\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (entry.name === 'blobs') continue\n const path = join(directory, entry.name)\n assertCalibrationPath(input.committedRoot, path)\n if (entry.isDirectory()) checkTree(path)\n }\n }\n for (const name of ['labels', 'corpus', 'cassettes']) checkTree(join(input.committedRoot, name))\n const read = readCommittedCorpus(input.committedRoot)\n if (read.refusals.length) throw new Error('committed corpus refused')\n if (read.snapshot.entries.some(entry => !read.snapshot.labelsById.has(entry.cassetteId)\n || !read.snapshot.cassettesById.has(entry.cassetteId))) throw new Error('incomplete committed corpus')\n const evidence = loadLabelEvidence({ snapshot: read.snapshot, agentQaRoot: input.agentQaRoot })\n if (evidence.refusals.length) throw new Error('complete population unavailable')\n const calibration = loadCalibrationEvidence(input)\n if (Object.entries(calibration.missingEvidenceCounts).some(([key, value]) => value && /refused|unreadable|invalid|path/.test(key))) throw new Error('calibration evidence refused')\n const population = collectSoftPopulation(evidence)\n const report = calibrateLabels({ ...calibration, minGold: input.minGold ? {\n value: input.minGold.value, source: input.minGold.source === 'cli' ? 'flag' : 'default',\n } : undefined })\n const corpusDigest = computeCorpusDigest(read.snapshot.entries)\n const desired: { product: string; record: StandaloneLabelRecord; changed: boolean }[] = []\n for (const [id, current] of [...read.snapshot.labelsById].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {\n if (current.label.tier !== 'near-gold' || current.label.sourceChannel !== 'self-heal-pair' || current.quarantine) continue\n const entries = read.snapshot.entries.filter(entry => entry.cassetteId === id)\n const cassette = read.snapshot.cassettesById.get(id), pairing = current.label.pairing\n if (entries.length !== 1 || !cassette || !pairing) throw new Error('pair identity unavailable')\n const product = entries[0]!.product\n const recoveringId = pairing.relation === 'contrastive-positive' ? id : pairing.pairedCassetteId\n const observation = population.observations.find(row => row.product === product && row.runId === current.provenance.runId\n && row.testIndex === cassette.testIndex && row.stepIndex === cassette.stepIndex\n && row.attempt === (current.provenance.rerun?.attempt ?? 0) && row.recoveringCassetteId === recoveringId)\n if (!observation) throw new Error('pair population unavailable')\n const state = population.observations.filter(row => row.product === product && row.failedScreenStateHash === observation.failedScreenStateHash)\n const wanted = canonicalJson(observation.recoveringAction)\n const weight = computeSoftWeight({ k: state.filter(row => canonicalJson(row.recoveringAction) === wanted).length,\n n: state.length, corpusDigest, evidenceDigest: population.evidenceDigest, recoveringDecision: observation.recoveringDecision })\n const record = createLabelRevision(current, { weight })\n desired.push({ product, record, changed: record !== current })\n }\n const body: Omit<LabelCalibrationArtifact, 'generationId'> = {\n ...report, schemaVersion: LABEL_CALIBRATION_SCHEMA_VERSION,\n minGold: { value: report.minGold.value, source: report.minGold.source === 'flag' ? 'cli' : 'default' },\n evidenceDigest: sha256hex(canonicalJson({ population: population.evidenceDigest,\n observations: calibration.observations, goldSetDigest: report.goldSetDigest, missing: calibration.missingEvidenceCounts })),\n targetRevisions: desired.map(({ record }) => ({ cassetteId: record.cassetteId, revisionId: record.revision?.id ?? deriveLabelRevisionId(record) })),\n }\n const artifact: LabelCalibrationArtifact = { ...body, generationId: calibrationGenerationId(body) }\n if (!guardLabelCalibration(artifact)) throw new Error('invalid calibration output')\n const parts = desired.filter(row => row.changed).map(({ product, record }) => {\n const revision = { ...record, revision: { ...record.revision!, generationId: artifact.generationId } }\n return { relPath: committedLabelRevisionPath(product, record.cassetteId, record.revision!.id), label: `label-revision:${record.cassetteId}`, text: committedFileText(revision) }\n })\n // Drift identity is invocation-local. Generated staged history is deliberately excluded.\n const identity = sha256hex(canonicalJson({ entries: read.snapshot.entries,\n labels: [...read.snapshot.labelsById], cassettes: [...read.snapshot.cassettesById].sort(),\n handoffs: evidence.handoffs, marks: evidence.marks, observations: calibration.observations,\n marker: markerText(input.committedRoot) ?? null }))\n return { artifact, parts, identity, refreshedCount: parts.length }\n}\n\nfunction writeCheckedTemp(root: string, path: string, text: string): void {\n assertCalibrationPath(root, path)\n // An interrupted identical generation may leave this private temporary file behind.\n if (existsSync(path)) {\n if (readFileSync(path, 'utf8') !== text) throw new Error('temporary publication conflict')\n return\n }\n const fd = openSync(path, 'wx', 0o600)\n try { writeFileSync(fd, text, 'utf8'); fsyncSync(fd) } finally { closeSync(fd) }\n}\n\n/** The only explicit operator producer. Immutable revisions precede the one atomic marker swap. */\nexport async function runLabelCalibration(input: RunLabelCalibrationInput): Promise<RunLabelCalibrationResult> {\n if (input.replace && !input.commit) return { kind: 'refused', reason: '--replace requires --commit' }\n let planned: ReturnType<typeof prepare>\n try { planned = prepare(input) } catch { return { kind: 'refused', reason: 'Calibration inputs unavailable or invalid; inspect committed labels and run evidence.' } }\n if (!input.commit) return { kind: 'dry-run', artifact: planned.artifact, refreshedCount: planned.refreshedCount }\n const lock = join(input.committedRoot, LOCK_PATH), marker = join(input.committedRoot, LABEL_CALIBRATION_PATH)\n let release: (() => void) | undefined, lockInode: number | undefined\n const temps: string[] = []\n const unchangedInputs = () => {\n try { return lstatSync(lock).ino === lockInode && prepare(input).identity === planned.identity } catch { return false }\n }\n try {\n assertCalibrationPath(input.committedRoot, lock)\n mkdirSync(dirname(lock), { recursive: true })\n try { release = await acquireMarkLock(lock, 'label-calibration', () => new Error('calibration-busy')) }\n catch (error) { if (error instanceof Error && error.message === 'calibration-busy') return { kind: 'busy', reason: 'Another calibration publisher holds the operator lock.' }; throw error }\n lockInode = lstatSync(lock).ino\n input.onBoundary?.('after-lock')\n if (!unchangedInputs()) return { kind: 'input-drift', reason: 'Calibration inputs changed; retry from the current snapshot.' }\n const artifactPart = { relPath: LABEL_CALIBRATION_PATH, label: 'label-calibration', text: committedFileText(planned.artifact) }\n const parts = [...planned.parts, artifactPart]\n const store = new FsCommittedRootStore(input)\n // Preview every destination before the first revision or marker byte is created.\n const previews = parts.map(part => { assertCalibrationPath(input.committedRoot, join(input.committedRoot, part.relPath)); return store.previewText(part.relPath, part.text) })\n const conflict = parts.find((part, i) => previews[i] === 'conflict' && (part !== artifactPart || !input.replace))\n if (conflict) return { kind: 'write-conflict', path: conflict.relPath }\n if (previews.every(value => value === 'identical')) return { kind: 'unchanged', artifact: planned.artifact, refreshedCount: 0 }\n for (const [i, part] of planned.parts.entries()) {\n input.onBoundary?.(`before-revision:${i}`)\n if (!unchangedInputs()) return { kind: 'input-drift', reason: 'Calibration inputs changed before publication.' }\n const destination = join(input.committedRoot, part.relPath)\n assertCalibrationPath(input.committedRoot, destination)\n if (store.previewText(part.relPath, part.text) === 'identical') continue\n const temp = join(dirname(destination), `.calibration-${planned.artifact.generationId}-${i}.tmp`)\n mkdirSync(dirname(destination), { recursive: true })\n writeCheckedTemp(input.committedRoot, temp, part.text); temps.push(temp)\n // Hard-link publishes a complete file exclusively; an existing path is never overwritten.\n linkSync(temp, destination)\n }\n input.onBoundary?.('before-marker')\n if (!unchangedInputs()) return { kind: 'input-drift', reason: 'Calibration inputs changed before publication.' }\n const temp = join(dirname(marker), `.calibration-${planned.artifact.generationId}.tmp`)\n assertCalibrationPath(input.committedRoot, dirname(marker))\n mkdirSync(dirname(marker), { recursive: true })\n writeCheckedTemp(input.committedRoot, temp, artifactPart.text); temps.push(temp)\n input.onBoundary?.('before-rename')\n if (!unchangedInputs()) return { kind: 'input-drift', reason: 'Calibration inputs changed before publication.' }\n assertCalibrationPath(input.committedRoot, marker)\n renameSync(temp, marker)\n input.onBoundary?.('after-marker')\n return { kind: 'committed', artifact: planned.artifact, refreshedCount: planned.refreshedCount }\n } catch {\n return { kind: 'publication-failed', reason: 'Calibration publication interrupted; a complete generation remains selected. Retry the identical command.' }\n } finally {\n for (const temp of temps) { try { unlinkSync(temp) } catch { /* Already renamed or externally removed. */ } }\n release?.()\n }\n}\n","import { existsSync, readFileSync, readdirSync, realpathSync } from 'node:fs'\nimport { isAbsolute, join, relative, sep } from 'node:path'\nimport { calibrationGoldSetDigest, canonicalJson, deriveRunSlug, resolveProductPartition, type CalibrationObservation, type LabelCalibrationInput } from '@vostride/agent-qa-eval'\nimport { HANDOFF_FILE, RUNS_SUBDIR, loadCompletedRunHandoff } from '@vostride/agent-qa-runner-local'\nimport { ANALYSIS_FILE, admitAnalysisArtifactForRun, guardRunAnalysisArtifact, type CompletedRunHandoff, type MarkReceipt } from '@vostride/agent-qa-schema'\nimport { readActiveCommittedCorpus, readCommittedCorpus } from './committed-corpus-source.js'\nimport { assertCalibrationPath, type LabelCalibrationRead } from './calibration-source.js'\nimport { FsMarkLedger, MARKS_LEDGER_FILE } from './mark-ledger.js'\n\nexport type CalibrationEvidenceMissingReason = 'corpus-refused' | 'invalid-run-link' | 'path-refused'\n | 'marks-missing' | 'marks-unreadable' | 'handoff-missing' | 'handoff-unreadable' | 'handoff-refused'\n | 'source-refused' | 'deterministic-missing' | 'deterministic-refused' | 'analysis-missing'\n | 'analysis-unreadable' | 'analysis-refused' | 'analyze-run-missing'\nexport interface CalibrationEvidenceRead extends LabelCalibrationInput {\n marks: MarkReceipt[]\n observations: CalibrationObservation[]\n missingEvidenceCounts: Partial<Record<CalibrationEvidenceMissingReason, number>>\n}\n\nfunction contained(root: string, path: string): boolean {\n const rel = relative(realpathSync(root), realpathSync(path))\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)\n}\n\n/** Guard persisted observations independently; a winning merged verdict loses producer evidence. */\nexport function loadCalibrationEvidence(input: { committedRoot: string; agentQaRoot: string; calibrationRead?: LabelCalibrationRead }): CalibrationEvidenceRead {\n const missingEvidenceCounts: CalibrationEvidenceRead['missingEvidenceCounts'] = {}\n const missing = (reason: CalibrationEvidenceMissingReason) => {\n missingEvidenceCounts[reason] = (missingEvidenceCounts[reason] ?? 0) + 1\n }\n const raw = readCommittedCorpus(input.committedRoot, input.calibrationRead)\n const links = new Map<string, { products: Set<string>; invalid: boolean }>()\n for (const entry of raw.snapshot.entries) {\n const { runId, runSlug } = entry.run_links\n const link = links.get(runId) ?? { products: new Set<string>(), invalid: false }\n link.products.add(entry.product)\n link.invalid ||= runSlug !== deriveRunSlug(runId)\n links.set(runId, link)\n }\n // Retired gold still locates its sovereign ledger, including newest empty receipts.\n for (const label of raw.snapshot.labelsById.values()) if (!links.has(label.provenance.runId)) {\n links.set(label.provenance.runId, { products: new Set<string>(), invalid: label.provenance.runSlug !== deriveRunSlug(label.provenance.runId) })\n }\n // readActiveCommittedCorpus owns retirement. Preflight its ledger reads before invoking it.\n for (const runId of links.keys()) {\n const path = join(input.agentQaRoot, RUNS_SUBDIR, deriveRunSlug(runId), MARKS_LEDGER_FILE)\n try {\n if (existsSync(path) && !contained(input.agentQaRoot, path)) {\n missing('path-refused')\n return { snapshot: { ...raw.snapshot, entries: [] }, marks: [], observations: [], missingEvidenceCounts }\n }\n } catch {\n missing('marks-unreadable')\n return { snapshot: { ...raw.snapshot, entries: [] }, marks: [], observations: [], missingEvidenceCounts }\n }\n }\n const active = readActiveCommittedCorpus(input.committedRoot, input.agentQaRoot, input.calibrationRead)\n for (const _refusal of active.refusals) missing('corpus-refused')\n const result: CalibrationEvidenceRead = { snapshot: active.snapshot, marks: [], observations: [], missingEvidenceCounts }\n const excluded = new Set(active.snapshot.excludedLabelIds)\n const excludeSources = (runId: string) => {\n for (const [id, label] of active.snapshot.labelsById) if (label.provenance.runId === runId && !label.provenance.sourceCassetteId) excluded.add(id)\n }\n for (const [runId, link] of [...links].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {\n if (link.invalid) { missing('invalid-run-link'); excludeSources(runId); continue }\n const run = join(input.agentQaRoot, RUNS_SUBDIR, deriveRunSlug(runId))\n const ledgerPath = join(run, MARKS_LEDGER_FILE)\n try {\n if (!existsSync(ledgerPath)) missing('marks-missing')\n result.marks.push(...new FsMarkLedger({ root: input.agentQaRoot, runId }).latestPerAddress())\n } catch { missing('marks-unreadable'); excludeSources(runId); continue }\n const handoffPath = join(run, HANDOFF_FILE)\n if (!existsSync(handoffPath)) { missing('handoff-missing'); excludeSources(runId); continue }\n let handoff: CompletedRunHandoff\n try {\n if (!contained(input.agentQaRoot, handoffPath)) { missing('path-refused'); excludeSources(runId); continue }\n handoff = loadCompletedRunHandoff(handoffPath)\n } catch { missing('handoff-unreadable'); excludeSources(runId); continue }\n const indices = handoff.tests.map(member => member.testIndex)\n if (handoff.runId !== runId || !indices.every(index => Number.isSafeInteger(index) && index >= 0)\n || new Set(indices).size !== indices.length\n || [...link.products].some(product => product !== resolveProductPartition(handoff.scope))) {\n missing('handoff-refused'); excludeSources(runId); continue\n }\n for (const [id, cassette] of active.snapshot.cassettesById) {\n if (cassette.runId !== runId) continue\n const member = handoff.tests.find(test => test.testIndex === cassette.testIndex)\n if (!member || member.testId !== cassette.testId || !member.steps.some(step => step.stepIndex === cassette.stepIndex)) {\n missing('source-refused'); excluded.add(id)\n }\n }\n for (const member of handoff.tests) {\n const verdict = member.rootCause\n if (!verdict) { missing('deterministic-missing'); continue }\n if (verdict.producer !== 'deterministic-classifier' || verdict.perTest !== member.testIndex) {\n missing('deterministic-refused'); continue\n }\n result.observations.push({ runId, testIndex: member.testIndex, producer: verdict.producer, class: verdict.class })\n }\n const analysisPath = join(run, ANALYSIS_FILE)\n if (!existsSync(analysisPath)) { missing('analysis-missing'); continue }\n try {\n if (!contained(input.agentQaRoot, analysisPath)) { missing('path-refused'); continue }\n const admission = admitAnalysisArtifactForRun(guardRunAnalysisArtifact(JSON.parse(readFileSync(analysisPath, 'utf8'))), runId)\n if (admission.kind !== 'admitted') { missing('analysis-refused'); continue }\n const authored = new Set<number>()\n for (const verdict of admission.artifact.verdicts) {\n if (verdict.producer !== 'analyze-run' || !indices.includes(verdict.perTest)) { missing('analysis-refused'); continue }\n authored.add(verdict.perTest)\n result.observations.push({ runId, testIndex: verdict.perTest, producer: verdict.producer, class: verdict.class })\n }\n for (const index of indices) if (!authored.has(index)) missing('analyze-run-missing')\n } catch { missing('analysis-unreadable') }\n }\n result.snapshot = { ...active.snapshot, excludedLabelIds: excluded }\n const compare = (a: unknown, b: unknown) => canonicalJson(a) < canonicalJson(b) ? -1 : canonicalJson(a) > canonicalJson(b) ? 1 : 0\n result.marks.sort(compare)\n result.observations.sort(compare)\n return result\n}\n\n/** Guarded diagnostic read using the caller's already validated calibration generation. */\nexport function readCalibrationGoldIdentity(input: {\n committedRoot: string; agentQaRoot: string; calibrationRead: LabelCalibrationRead\n}): { kind: 'loaded'; goldSetDigest: string } | { kind: 'unavailable' } {\n if (input.calibrationRead.kind === 'refused') return { kind: 'unavailable' }\n try {\n assertCalibrationPath(input.committedRoot, input.committedRoot)\n const inspect = (directory: string): void => {\n assertCalibrationPath(input.committedRoot, directory)\n if (!existsSync(directory)) return\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (entry.name === 'blobs') continue\n const path = join(directory, entry.name)\n assertCalibrationPath(input.committedRoot, path)\n if (entry.isDirectory()) inspect(path)\n }\n }\n for (const name of ['labels', 'corpus', 'cassettes']) inspect(join(input.committedRoot, name))\n const evidence = loadCalibrationEvidence(input)\n // Missing/invalid governing evidence cannot certify a current or stale identity.\n const unavailable = Object.entries(evidence.missingEvidenceCounts).some(([reason, n]) =>\n n && !['analysis-missing', 'analyze-run-missing', 'deterministic-missing'].includes(reason))\n if (unavailable) return { kind: 'unavailable' }\n return { kind: 'loaded', goldSetDigest: calibrationGoldSetDigest(evidence) }\n } catch { return { kind: 'unavailable' } }\n}\n","import { existsSync, realpathSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve } from 'node:path'\nimport { canonicalJson, deriveRunSlug, resolveProductPartition, type CommittedCorpusSnapshot } from '@vostride/agent-qa-eval'\nimport { HANDOFF_FILE, RUNS_SUBDIR, loadCompletedRunHandoff } from '@vostride/agent-qa-runner-local'\nimport { guardCompletedRunHandoff, type CompletedRunHandoff, type MarkReceipt } from '@vostride/agent-qa-schema'\nimport { FsMarkLedger, MARKS_LEDGER_FILE } from './mark-ledger.js'\n\nexport interface LoadLabelEvidenceInput {\n snapshot: CommittedCorpusSnapshot\n agentQaRoot: string\n incoming?: CompletedRunHandoff\n}\nexport interface LabelEvidenceRead {\n handoffs: CompletedRunHandoff[]\n marks: MarkReceipt[]\n refusals: { runId: string; reason: 'invalid-run-link' | 'handoff-unavailable' | 'run-identity-mismatch'\n | 'product-mismatch' | 'path-outside-root' | 'conflicting-handoff' | 'marks-unavailable' }[]\n}\n\nfunction contained(root: string, path: string): boolean {\n const rel = relative(realpathSync(root), realpathSync(path))\n return rel !== '..' && !rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`) && !isAbsolute(rel)\n}\n\n/** Load only positively linked runs. A slug locates bytes; the guarded run identity authorizes them. */\nexport function loadLabelEvidence(input: LoadLabelEvidenceInput): LabelEvidenceRead {\n const result: LabelEvidenceRead = { handoffs: [], marks: [], refusals: [] }\n const links = new Map<string, { slug: string; products: Set<string>; invalid: boolean }>()\n for (const entry of input.snapshot.entries) {\n const { runId, runSlug } = entry.run_links\n const link = links.get(runId) ?? { slug: runSlug, products: new Set<string>(), invalid: false }\n link.invalid ||= runSlug !== deriveRunSlug(runId) || link.slug !== runSlug\n link.products.add(entry.product); links.set(runId, link)\n }\n if (input.incoming && !links.has(input.incoming.runId)) {\n links.set(input.incoming.runId, { slug: deriveRunSlug(input.incoming.runId),\n products: new Set([resolveProductPartition(input.incoming.scope)]), invalid: false })\n }\n const loaded = new Map<string, CompletedRunHandoff>()\n const refused = new Set<string>()\n const refuse = (runId: string, reason: LabelEvidenceRead['refusals'][number]['reason']) => {\n result.refusals.push({ runId, reason }); refused.add(runId)\n }\n for (const [runId, link] of links) {\n if (link.invalid) { refuse(runId, 'invalid-run-link'); continue }\n const path = resolve(input.agentQaRoot, RUNS_SUBDIR, link.slug, HANDOFF_FILE)\n try {\n if (!contained(input.agentQaRoot, path)) { refuse(runId, 'path-outside-root'); continue }\n const handoff = loadCompletedRunHandoff(path)\n if (handoff.runId !== runId) { refuse(runId, 'run-identity-mismatch'); continue }\n if (link.products.size !== 1 || !link.products.has(resolveProductPartition(handoff.scope))) {\n refuse(runId, 'product-mismatch'); continue\n }\n loaded.set(runId, handoff)\n } catch { refuse(runId, 'handoff-unavailable') }\n }\n if (input.incoming) {\n const incoming = guardCompletedRunHandoff(input.incoming)\n const existing = loaded.get(incoming.runId)\n if (existing && canonicalJson(existing) !== canonicalJson(incoming)) {\n loaded.delete(incoming.runId); refuse(incoming.runId, 'conflicting-handoff')\n } else if (!refused.has(incoming.runId)) loaded.set(incoming.runId, incoming)\n }\n for (const [runId, handoff] of loaded) {\n result.handoffs.push(handoff)\n const path = join(input.agentQaRoot, RUNS_SUBDIR, deriveRunSlug(runId), MARKS_LEDGER_FILE)\n try {\n if (existsSync(path) && !contained(input.agentQaRoot, path)) { refuse(runId, 'marks-unavailable'); continue }\n result.marks.push(...new FsMarkLedger({ root: input.agentQaRoot, runId }).latestPerAddress())\n } catch { refuse(runId, 'marks-unavailable') }\n }\n result.handoffs.sort((a, b) => a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0)\n return result\n}\n","// Gate-side composition only: extraction, selection and census projection stay in eval core.\n// The shipped writers own every committed byte.\nimport {\n assertBaselineComparator,\n buildGoldenTrajectoryPlan,\n deriveCensus,\n extractRunCassettes,\n markedDecisionCount,\n maskCorpusText,\n renderCensusMarkdown,\n resolveMarkedDecisions,\n} from '@vostride/agent-qa-eval'\nimport type { CompletedRunHandoff, MarkReceipt, MaskFn } from '@vostride/agent-qa-schema'\n\nimport { FsRunArtifactSource } from './artifact-source.js'\nimport { commitCensus } from './census-committing.js'\nimport {\n listBaselinePointers,\n listCommittedReports,\n readCommittedCorpus,\n readPartitionManifests,\n readRunExclusions,\n} from './committed-corpus-source.js'\nimport { requireCorpusMask, seedCommittedCorpus, type SeedingRefusal } from './seeding-composition.js'\n\nexport interface FreezeGoldenTrajectoryInput {\n agentQaRoot: string\n committedRoot: string\n product: string\n mark: MarkReceipt\n handoff: CompletedRunHandoff\n supersedes?: string\n priorGold?: MarkReceipt['gold']\n /** 441 GAP3-D1: the declared mask the run and the mark's correction are frozen under. */\n mask: MaskFn\n}\n\nexport type FreezeOutcome =\n | { kind: 'ambiguous-correction'; decisionCount: number }\n | { kind: 'frozen'; cases: MarkReceipt['gold']; census: 'committed' | 'unchanged' | 'write-conflict' }\n | { kind: 'refused'; refusals: SeedingRefusal[] }\n | { kind: 'step-not-found'; stepCount: number }\n | { kind: 'no-leaf-cassette' }\n\nexport function freezeGoldenTrajectory(input: FreezeGoldenTrajectoryInput): FreezeOutcome {\n requireCorpusMask(input.mask, 'freezeGoldenTrajectory')\n // 441 GAP3-D1: the whole freeze reads the masked run and the masked correction. No later read\n // compares the frozen correction with the stored mark, so masking it moves no identity.\n const handoff = maskCorpusText(input.handoff, input.mask)\n const mark = maskCorpusText(input.mark, input.mask)\n const targets = resolveMarkedDecisions(handoff, mark, mark.kind)\n if ('refusal' in targets) return { kind: 'step-not-found', stepCount: targets.stepCount }\n const decisionCount = markedDecisionCount(handoff, targets)\n if (mark.correctedAction !== undefined && decisionCount !== 1) return { kind: 'ambiguous-correction', decisionCount }\n\n const extracted = extractRunCassettes({\n handoff,\n artifacts: new FsRunArtifactSource({ root: input.agentQaRoot, runId: handoff.runId }),\n })\n const plan = buildGoldenTrajectoryPlan({ ...input, handoff, mark, cassettes: extracted.cassettes })\n if (plan.cases.length === 0) return { kind: 'no-leaf-cassette' }\n if (plan.skipped.length > 0) {\n return { kind: 'refused', refusals: plan.skipped.map(({ cassetteId }) => ({ cassetteId, kind: 'missing-cassette' })) }\n }\n const seeded = seedCommittedCorpus({\n plan: {\n product: plan.product,\n runId: plan.runId,\n runSlug: plan.runSlug,\n cases: plan.cases,\n pairSkips: [],\n silverExclusions: [],\n pairCounts: { total: 0, sameState: 0, differingState: 0 },\n proceduresExcludedCount: 0,\n },\n cassettes: plan.goldCassettes,\n committedRoot: input.committedRoot,\n mask: input.mask,\n })\n if (seeded.refusals.length > 0) return { kind: 'refused', refusals: seeded.refusals }\n\n const read = readCommittedCorpus(input.committedRoot)\n const manifests = readPartitionManifests(input.committedRoot)\n const exclusions = readRunExclusions(input.committedRoot)\n const reports = listCommittedReports(input.committedRoot)\n const pointers = listBaselinePointers(input.committedRoot)\n // Never publish a partial census as the permanent view of a refused committed root.\n if ([read, manifests, exclusions, reports, pointers].some(result => result.refusals.length > 0)) {\n throw new Error('gold census refused: committed root contains unreadable evidence')\n }\n const census = deriveCensus({\n snapshot: read.snapshot,\n schemaVersionsSeen: read.schemaVersionsSeen,\n manifests: manifests.manifests,\n exclusions: exclusions.exclusions,\n reports: reports.reports.map(entry => ({\n report: entry.report,\n comparator: assertBaselineComparator(entry.report),\n designatedBy: pointers.pointers.filter(pointer => pointer.batchKey === entry.batchKey)\n .map(pointer => pointer.profileKey).sort(),\n })),\n })\n const committed = commitCensus({\n census,\n markdown: renderCensusMarkdown(census),\n committedRoot: input.committedRoot,\n })\n return {\n kind: 'frozen',\n cases: plan.cases.map(({ cassetteId, labelRecord }) => {\n const channel = labelRecord.label.sourceChannel\n const sourceCassetteId = labelRecord.provenance.sourceCassetteId\n if ((channel !== 'user-mark' && channel !== 'overturned-verdict') || sourceCassetteId === undefined) {\n throw new Error('gold plan must carry marked source provenance')\n }\n return { cassetteId, sourceCassetteId, channel }\n }),\n census: committed.kind === 'write-conflict' ? 'write-conflict'\n : committed.json === 'unchanged' && committed.markdown === 'unchanged' ? 'unchanged' : 'committed',\n }\n}\n","// The committed-census writer (Phase 413 D-13/D-15/D-16, ROOT-05) — sibling\n// of commitEvalReport, same recipe, keyed on the CORPUS DIGEST instead of a replay batchKey.\n//\n// Why a digest and not a batchKey: the census is a property of the committed corpus, not of a\n// replay batch (D-13). Keying the dir on the digest of the committed entry set makes the two\n// facts that matter free — re-running the census over an unchanged corpus writes byte-identical\n// text and reports 'unchanged' (idempotent no-op, D-15), while a growth commit changes the digest\n// and therefore lands in a fresh dir rather than colliding with the previous census under\n// write-once.\n//\n// Composition law (the 372 D-13 recipe):\n// - Committed bytes are written as given (441 D-15): no content check runs on them.\n// - Write-once (D-17): both relPaths are PREVIEWED before either write, so a conflict on one\n// part leaves even the non-conflicting part unwritten.\n// - census.json is serialized by eval core's committedFileText (the ONE serializer); the\n// markdown's byte-determinism is the renderer's contract — this helper only byte-compares.\n// - ZERO model calls, no safety scope opened.\n\nimport { join } from 'node:path'\n\nimport { committedFileText } from '@vostride/agent-qa-eval'\nimport type { CorpusCensus } from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nimport {\n COMMITTED_CENSUS_SUBDIR,\n COMMITTED_REPORTS_DIR,\n FsCommittedRootStore,\n committedCensusPath,\n} from './committed-root-store.js'\n\nexport const COMMITTED_CENSUS_JSON_FILE = 'census.json'\nexport const COMMITTED_CENSUS_MARKDOWN_FILE = 'census.md'\n\nexport interface CommitCensusInput {\n /** The pure eval-core census DTO — its corpusDigest names the committed dir. */\n census: CorpusCensus\n /** The rendered markdown projection; byte-determinism is the renderer's contract. */\n markdown: string\n /** Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the CLI. */\n committedRoot: string\n}\n\nexport type CommitCensusOutcome =\n | {\n kind: 'committed'\n json: 'written' | 'unchanged'\n markdown: 'written' | 'unchanged'\n censusDir: string\n }\n | { kind: 'write-conflict'; path: string }\n\n/**\n * Commit the census beside the corpus it measures: preview BOTH paths, then write — one\n * atomic unit.\n */\nexport function commitCensus(input: CommitCensusInput): CommitCensusOutcome {\n const store = new FsCommittedRootStore({ committedRoot: input.committedRoot })\n\n const corpusDigest = input.census.corpusDigest\n const parts: { relPath: string; label: string; text: string }[] = [\n {\n relPath: committedCensusPath(corpusDigest, COMMITTED_CENSUS_JSON_FILE),\n label: `census-json:${corpusDigest}`,\n text: committedFileText(input.census),\n },\n {\n relPath: committedCensusPath(corpusDigest, COMMITTED_CENSUS_MARKDOWN_FILE),\n label: `census-markdown:${corpusDigest}`,\n text: input.markdown,\n },\n ]\n\n // (1) Preview BOTH paths before writing EITHER — a conflict on one part leaves even the\n // non-conflicting part unwritten (D-17 atomicity).\n const conflicting = parts.find(\n (part) => store.previewText(part.relPath, part.text) === 'conflict',\n )\n if (conflicting !== undefined) {\n return { kind: 'write-conflict', path: conflicting.relPath }\n }\n\n // (2) Write both; after preview a conflict cannot occur here, but map it defensively.\n const outcomes = parts.map((part) => store.writeText(part.relPath, part.text))\n for (const outcome of outcomes) {\n if (outcome.kind === 'write-conflict') return { kind: 'write-conflict', path: outcome.path }\n }\n\n return {\n kind: 'committed',\n json: outcomes[0]!.kind === 'written' ? 'written' : 'unchanged',\n markdown: outcomes[1]!.kind === 'written' ? 'written' : 'unchanged',\n censusDir: join(\n input.committedRoot,\n COMMITTED_REPORTS_DIR,\n COMMITTED_CENSUS_SUBDIR,\n slugBranch(corpusDigest),\n ),\n }\n}\n","// Filesystem handoff source for eval extraction (Phase 367, D-02).\n//\n// Implements eval's storage-neutral HandoffSource over the one runner-local read leg. The path is\n// composed exclusively from runner-local's exported layout constants and sanitizer:\n//\n// <root>/runs/<slug(runId)>/handoff.json\n//\n// `loadCompletedRunHandoff` remains the sole JSON read + handoff version guard. This adapter owns\n// host path composition without re-deriving either the run-directory layout or version discipline.\n\nimport { join } from 'node:path'\n\nimport type { HandoffSource } from '@vostride/agent-qa-eval'\nimport {\n HANDOFF_FILE,\n RUNS_SUBDIR,\n loadCompletedRunHandoff,\n slugBranch,\n} from '@vostride/agent-qa-runner-local'\nimport type { CompletedRunHandoff } from '@vostride/agent-qa-schema'\n\nexport interface FsHandoffSourceConfig {\n /** Runtime root (for example, the workdir's `.agent-qa` directory). */\n root: string\n /** The run to load; runner-local sanitizes it before path use. */\n runId: string\n}\n\nexport class FsHandoffSource implements HandoffSource {\n private readonly file: string\n\n constructor(config: FsHandoffSourceConfig) {\n this.file = join(config.root, RUNS_SUBDIR, slugBranch(config.runId), HANDOFF_FILE)\n }\n\n load(): CompletedRunHandoff {\n return loadCompletedRunHandoff(this.file)\n }\n}\n","// The ONE whole-corpus run composition in 415: the floor calls it for each repeat and the\n// release gate calls it once. Reports and decisions stay in caller-owned local run roots.\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n composeBaselineProfileKey,\n canonicalJson,\n computeCorpusDigest,\n FLOOR_PROTOCOL_MINIMUM,\n foldNoiseFloorArtefact,\n guardBaselinePointer,\n projectDecisionVectorsDocument,\n} from '@vostride/agent-qa-eval'\nimport type {\n DecisionCorrectnessVector,\n EvalBatchReport,\n ClassifierRepeatability,\n FloorRunInput,\n FloorSplit,\n FoldNoiseFloorInput,\n NoiseFloorArtefact,\n StandaloneLabelRecord,\n CorpusEntry,\n} from '@vostride/agent-qa-eval'\nimport type { ModelProfile, ModelProviderOverrides, ResolvedModelAuth } from '@vostride/agent-qa-model'\nimport { sha256hex, slugBranch } from '@vostride/agent-qa-schema'\n\nimport {\n listBaselinePointers,\n listCommittedReports,\n readActiveCommittedCorpus,\n readPartitionManifests,\n} from './committed-corpus-source.js'\nimport type { CommittedReadRefusal } from './committed-corpus-source.js'\nimport { committedCorpusAdmissionRefusal } from './committed-corpus-admission.js'\nimport { writeNoiseFloorArtefact } from './noise-floor-writer.js'\nimport type { WriteNoiseFloorArtefactOutcome } from './noise-floor-writer.js'\nimport { readMeasuredCostReceipts, readMeasuredFloorRun } from './measured-floor-read.js'\n\nimport { assembleScoredBatch, projectAssembledBatch, copyJudgeCalibrationToReport } from './replay-batch-assembly.js'\nimport { readJudgeCalibration } from './judge-calibration-source.js'\nimport { computeReplayProfileFingerprintFor, replayJudgeRequest } from './replay-composition.js'\nimport type { RunCassetteReplayInput } from './replay-composition.js'\nimport { FsReplayRecordStore } from './replay-record-store.js'\nimport { loadCassetteBundles, sweepCassetteReplays } from './replay-sweep.js'\nimport type { LoadedCassetteBundle, SweepCassetteReplaysResult } from './replay-sweep.js'\nimport { FsReportStore, type ReplayGeneration } from './report-store.js'\nimport { FsScoreStore } from './score-store.js'\n\nexport interface ReplayCorpusOnceInput {\n committedRoot?: string\n selected: readonly LoadedCassetteBundle[]\n /** Bundle-load refusals excluded from selected; never include returned replay refusals. */\n loadRefusals?: Readonly<Partial<EvalBatchReport['honesty']['refusalCounts']>>\n cassettesRoot: string\n agentQaRoot: string\n runRoot: string\n profile: ModelProfile\n auth: ResolvedModelAuth\n modelOverrides?: ModelProviderOverrides\n judge?: RunCassetteReplayInput['judge']\n mask: RunCassetteReplayInput['mask']\n seed: number\n k?: number\n source: string\n /** Digest of the committed snapshot supplying this run, when the caller read one. */\n corpusDigest?: string\n productByCassetteId?: ReadonlyMap<string, string>\n labelRecords?: ReadonlyMap<string, StandaloneLabelRecord>\n corpusEntriesById?: ReadonlyMap<string, CorpusEntry>\n excludedLabelIds?: ReadonlySet<string>\n calibration?: EvalBatchReport['calibration']\n clock?: () => number\n onProgress?: (cassetteId: string) => void\n}\n\nexport interface RunNoiseFloorMeasurementInput {\n committedRoot: string\n cassettesRoot: string\n agentQaRoot: string\n profile: ModelProfile\n auth?: ResolvedModelAuth\n /** Explicit read-only recovery from complete saved runs and the original cost log. */\n fromMeasured?: string\n modelOverrides?: ModelProviderOverrides\n judge?: RunCassetteReplayInput['judge']\n mask: RunCassetteReplayInput['mask']\n profileKeyInputs: {\n plannerModelId: string\n matcherVersion: number\n judgeModelId?: string\n judgeVersion?: number\n }\n seeds: readonly number[]\n repeats: number\n bootstrapSeed: number\n classifierRepeatability?: ClassifierRepeatability\n explanation?: string\n commit: boolean\n clock?: () => number\n onProgress?: (line: string) => void\n}\n\nexport interface RunNoiseFloorMeasurementResult {\n artefact: NoiseFloorArtefact\n profileKey: string\n fingerprint: string\n runRoots: readonly string[]\n committed?: WriteNoiseFloorArtefactOutcome\n notices: string[]\n refusals: readonly CommittedReadRefusal[]\n /** Calls in this invocation, separate from the original observations retained in artefact.cost. */\n recovery?: { costLog: string; modelCalls: 0 }\n}\n\nexport class FloorProtocolError extends Error {\n readonly code = 'FLOOR_PROTOCOL_MINIMUM'\n\n constructor() {\n super(`FLOOR_PROTOCOL_MINIMUM: require at least ${FLOOR_PROTOCOL_MINIMUM.repeats} ` +\n `whole-corpus repeats and ${FLOOR_PROTOCOL_MINIMUM.seeds} distinct integer seeds`)\n this.name = 'FloorProtocolError'\n }\n}\n\n/** Whole-corpus repetitions, then the pure floor fold and the existing write-once checkpoint. */\nexport async function runNoiseFloorMeasurement(\n input: RunNoiseFloorMeasurementInput,\n): Promise<RunNoiseFloorMeasurementResult> {\n const seeds = [...new Set(input.seeds)]\n if (!Number.isSafeInteger(input.repeats) || input.repeats < FLOOR_PROTOCOL_MINIMUM.repeats ||\n seeds.length < FLOOR_PROTOCOL_MINIMUM.seeds || !seeds.every(Number.isSafeInteger)) {\n throw new FloorProtocolError()\n }\n const fingerprint = computeReplayProfileFingerprintFor({\n profile: input.profile, modelOverrides: input.modelOverrides, seedPolicy: 'declared',\n })\n const profileKey = composeBaselineProfileKey({ ...input.profileKeyInputs, fingerprint })\n const corpus = readActiveCommittedCorpus(input.committedRoot, input.agentQaRoot)\n const partitions = readPartitionManifests(input.committedRoot)\n const notices = [...corpus.notices, ...partitions.notices]\n const refusals = [...corpus.refusals, ...partitions.refusals]\n const corpusDigest = computeCorpusDigest(corpus.snapshot.entries)\n const productByCassetteId = new Map(corpus.snapshot.entries.map(entry => [entry.cassetteId, entry.product]))\n const partitionVersions = [...new Set(partitions.manifests.map(manifest => manifest.partitionVersion))]\n const partitionVersion = partitionVersions.length === 1 ? partitionVersions[0]! : 1\n if (partitionVersions.length !== 1) {\n notices.push('partition manifests have no common version; using partitionVersion 1')\n }\n const splitByCassetteId = new Map<string, FloorSplit>()\n const census = new Map<string, { natural: number; heldOutShared: number; heldOutPrivate: number }>()\n for (const entry of corpus.snapshot.entries) {\n let counts = census.get(entry.product)\n if (counts === undefined) {\n counts = { natural: 0, heldOutShared: 0, heldOutPrivate: 0 }\n census.set(entry.product, counts)\n }\n if (entry.split === 'natural') {\n counts.natural++\n splitByCassetteId.set(entry.cassetteId, 'natural')\n } else if (entry.split === 'held-out') {\n if (entry.heldOutVisibility === 'shared') {\n counts.heldOutShared++\n splitByCassetteId.set(entry.cassetteId, 'held-out-shared')\n } else {\n counts.heldOutPrivate++\n splitByCassetteId.set(entry.cassetteId, 'held-out-private')\n }\n }\n }\n const baselineRate = readDesignatedBaselineRate(input, notices, refusals)\n const loaded = loadCassetteBundles(input.cassettesRoot)\n const admission = committedCorpusAdmissionRefusal(input.committedRoot, corpus, loaded)\n ?? partitions.refusals[0]\n if (admission !== undefined) {\n throw new TypeError(`floor requires the complete guarded committed corpus: ${admission.path}: ${admission.reason}`)\n }\n for (const [reason, count] of Object.entries(loaded.loadRefusals)) {\n notices.push(`cassette bundle load refused: ${reason}=${count}`)\n }\n const selected = loaded.loaded.filter(entry => productByCassetteId.has(entry.cassette.id)).sort((a, b) =>\n a.cassette.id < b.cassette.id ? -1 : a.cassette.id > b.cassette.id ? 1 : 0)\n const runSeeds = [...Array<number>(input.repeats).fill(seeds[0]!), ...seeds.slice(1)]\n const receipts = input.fromMeasured === undefined ? undefined : readMeasuredCostReceipts(input.fromMeasured, runSeeds)\n if (receipts !== undefined && refusals.length !== 0) {\n throw new TypeError('measured floor recovery requires the complete guarded committed corpus')\n }\n const runs: FloorRunInput[] = []\n const runRoots: string[] = []\n for (const [index, seed] of runSeeds.entries()) {\n const runRoot = join(input.agentQaRoot, 'eval', 'floor', slugBranch(profileKey), `r${index}-seed${seed}`)\n runRoots.push(runRoot)\n if (receipts !== undefined) {\n const receipt = receipts[index]!\n runs.push(readMeasuredFloorRun({ agentQaRoot: input.agentQaRoot, runRoot,\n cassettesRoot: input.cassettesRoot, fingerprint, corpusDigest,\n plannerModelId: input.profileKeyInputs.plannerModelId,\n matcherVersion: input.profileKeyInputs.matcherVersion, productByCassetteId,\n labelRecords: corpus.snapshot.labelsById, receipt,\n corpusEntriesById: corpus.corpusEntriesById, excludedLabelIds: corpus.snapshot.excludedLabelIds,\n calibration: corpus.calibration,\n expectedJudgeRequest: input.profileKeyInputs.judgeModelId === undefined ? null : {\n judgeModelId: input.profileKeyInputs.judgeModelId, allowSameFamily: input.judge?.allowSameFamily === true } }))\n input.onProgress?.(receipt.line)\n continue\n }\n if (input.auth === undefined) throw new TypeError('fresh floor measurement requires resolved model auth')\n const run = await replayCorpusOnce({\n committedRoot: input.committedRoot,\n selected,\n loadRefusals: loaded.loadRefusals,\n cassettesRoot: input.cassettesRoot,\n agentQaRoot: input.agentQaRoot,\n runRoot,\n profile: input.profile,\n auth: input.auth,\n modelOverrides: input.modelOverrides,\n judge: input.judge,\n mask: input.mask,\n seed,\n k: 1,\n source: 'committed',\n corpusDigest,\n productByCassetteId,\n labelRecords: corpus.snapshot.labelsById,\n corpusEntriesById: corpus.corpusEntriesById, excludedLabelIds: corpus.snapshot.excludedLabelIds,\n calibration: corpus.calibration,\n clock: input.clock,\n onProgress: input.onProgress,\n })\n runs.push({ index, seed, report: run.report, vectors: run.vectors,\n wallClockMs: run.wallClockMs, modelCalls: run.modelCalls })\n notices.push(...run.notices)\n const cost = run.report.totalCost\n const judgeCost = run.report.honesty.judge.cost\n const missingUsage = cost.samplesMissingTokenUsage > 0 || judgeCost.outcomesMissingUsage > 0\n ? ` samplesMissingTokenUsage=${cost.samplesMissingTokenUsage} judgeOutcomesMissingUsage=${judgeCost.outcomesMissingUsage}`\n : ''\n input.onProgress?.(`floor r${index} seed=${seed}: decisions=${run.vectors.length} ` +\n `modelCalls=${run.modelCalls} promptTokens=${cost.promptTokens + judgeCost.inputTokens} ` +\n `completionTokens=${cost.completionTokens + judgeCost.outputTokens} ` +\n `wallClock=${run.wallClockMs}ms seedHonored=${run.report.seedHonored}${missingUsage}`)\n }\n const artefact = foldNoiseFloorArtefact({\n profile: { profileKey, fingerprint, ...input.profileKeyInputs },\n corpusDigest, partitionVersion, seeds, repeats: input.repeats, bootstrapSeed: input.bootstrapSeed,\n runs, splitByCassetteId, censusByProduct: Object.fromEntries(census),\n ...(baselineRate === undefined ? {} : { baselineRate }),\n ...(input.classifierRepeatability === undefined ? {} : { classifierRepeatability: input.classifierRepeatability }),\n ...(input.explanation === undefined ? {} : { explanation: input.explanation }),\n })\n return {\n artefact, profileKey, fingerprint, runRoots, notices, refusals,\n ...(input.fromMeasured === undefined ? {} : { recovery: { costLog: input.fromMeasured, modelCalls: 0 } as const }),\n ...(input.commit ? { committed: writeNoiseFloorArtefact({\n artefact, committedRoot: input.committedRoot,\n }) } : {}),\n }\n}\n\n/** Read actual pointer bodies: the census listing deliberately projects only index fields. */\nfunction readDesignatedBaselineRate(\n input: RunNoiseFloorMeasurementInput,\n notices: string[],\n refusals: CommittedReadRefusal[],\n): FoldNoiseFloorInput['baselineRate'] {\n const pointers = listBaselinePointers(input.committedRoot)\n const reports = listCommittedReports(input.committedRoot)\n refusals.push(...pointers.refusals, ...reports.refusals)\n for (const entry of pointers.pointers) {\n let value: unknown\n try {\n value = JSON.parse(readFileSync(entry.path, 'utf8'))\n } catch (error) {\n refusals.push({ path: entry.path, reason: `baseline pointer unreadable: ${String(error)}` })\n continue\n }\n const guarded = guardBaselinePointer(value)\n if (guarded.kind === 'rejected') {\n refusals.push({ path: entry.path, reason: guarded.reason })\n continue\n }\n const pointer = guarded.pointer\n if (pointer.plannerModelId !== input.profileKeyInputs.plannerModelId) continue\n const found = reports.reports.find(report => report.batchKey === pointer.batchKey)\n if (found === undefined) {\n notices.push(`designated baseline report absent for ${pointer.batchKey}`)\n continue\n }\n if (found.report.batchKey !== pointer.batchKey) {\n refusals.push({ path: found.path, reason: 'report body batchKey does not match designated baseline directory' })\n continue\n }\n const rate = found.report.headline.firstAttemptDecisionAccuracy\n if (rate === undefined || !Number.isSafeInteger(rate.numerator) || !Number.isSafeInteger(rate.denominator) ||\n rate.numerator < 0 || rate.denominator < rate.numerator) {\n refusals.push({ path: found.path, reason: 'baseline decision accuracy counts are invalid' })\n continue\n }\n return { correct: rate.numerator, n: rate.denominator, batchKey: pointer.batchKey }\n }\n notices.push('no usable designated baseline for this planner; minimum gate set uses reference-run rate')\n return undefined\n}\n\nexport interface ReplayCorpusOnceResult {\n report: EvalBatchReport\n vectors: DecisionCorrectnessVector[]\n replaysRoot: string\n reportFile: string\n decisionsFile: string\n sweep: SweepCassetteReplaysResult\n wallClockMs: number\n modelCalls: number\n notices: string[]\n}\n\nexport async function replayCorpusOnce(\n input: ReplayCorpusOnceInput,\n): Promise<ReplayCorpusOnceResult> {\n const replaysRoot = join(input.runRoot, 'replays')\n // Capture THIS writer's values, never reread possibly replaced rows to assign their seed.\n const records = new Map<string, ReplayGeneration['records'][number]>()\n const recordStore = new (class extends FsReplayRecordStore {\n override save(outcome: Parameters<FsReplayRecordStore['save']>[0]) {\n const written = super.save(outcome)\n records.set(outcome.cassetteId, {\n cassetteId: outcome.cassetteId,\n replayDigest: sha256hex(canonicalJson({ ...outcome, executionSeed: input.seed })),\n scoreDigest: null,\n })\n return written\n }\n })({ root: input.agentQaRoot, outputDir: replaysRoot, executionSeed: input.seed })\n const scoreStore = new (class extends FsScoreStore {\n override save(record: Parameters<FsScoreStore['save']>[0]) {\n const written = super.save(record)\n const replay = records.get(record.cassetteId)\n if (replay !== undefined) replay.scoreDigest = sha256hex(canonicalJson(record))\n return written\n }\n })({ root: input.agentQaRoot, outputDir: replaysRoot })\n const clock = input.clock ?? Date.now\n // Capture before replay begins: model creation may resolve capabilities on its own copy.\n const runIdentity = input.corpusDigest === undefined ? undefined : {\n fingerprint: computeReplayProfileFingerprintFor({\n profile: input.profile, modelOverrides: input.modelOverrides, seedPolicy: 'declared',\n }),\n corpusDigest: input.corpusDigest,\n }\n let modelCalls = 0\n const started = clock()\n const sweep = await sweepCassetteReplays({\n selected: input.selected,\n labelRecords: input.labelRecords,\n profile: input.profile,\n auth: input.auth,\n modelOverrides: input.modelOverrides,\n modelCallObservation: { onProviderCall: () => { modelCalls++ } },\n ...(input.clock === undefined ? {} : { clock: { now: input.clock } }),\n k: input.k ?? 1,\n seed: input.seed,\n judge: input.judge,\n mask: input.mask,\n recordStore,\n scoreStore,\n replaysRoot,\n onProgress: input.onProgress,\n })\n const wallClockMs = clock() - started\n // A new store does not empty a directory. Only completed writes from THIS sweep may enter\n // its report, including typed refusals; stale and partially written failed records stay out.\n const batch = assembleScoredBatch({\n replaysRoot,\n cassettesRoot: input.cassettesRoot,\n source: input.source,\n recordDirs: sweep.recordedDirs,\n corpusEntriesById: input.corpusEntriesById, excludedLabelIds: input.excludedLabelIds,\n calibration: input.calibration,\n productByCassetteId: input.productByCassetteId,\n labelRecords: input.labelRecords,\n ...(input.productByCassetteId === undefined ? {} : { eligibleCassetteIds: new Set(input.productByCassetteId.keys()) }),\n expectedJudgeRequest: replayJudgeRequest(input.judge),\n })\n const { report, vectors, notices } = projectAssembledBatch(batch, {\n declaredSeed: input.seed,\n additionalHarnessErrorCount: sweep.replayRefusals['harness-error'] ?? 0,\n ...(input.loadRefusals === undefined ? {} : { additionalRefusalCounts: input.loadRefusals }),\n ...(runIdentity === undefined ? {} : { runIdentity }),\n })\n if (report.judge?.panelSize !== undefined) {\n const read = input.committedRoot === undefined ? undefined : readJudgeCalibration({\n committedRoot: input.committedRoot, agentQaRoot: input.agentQaRoot, identity: report.judge,\n profile: { plannerModelId: input.profile.model, matcherVersion: report.matcherVersion,\n judgeModelId: report.judge.judgeModelId, judgeVersion: report.judge.judgeVersion,\n fingerprint: computeReplayProfileFingerprintFor({ profile: input.profile,\n modelOverrides: input.modelOverrides, seedPolicy: 'declared' }) },\n })\n copyJudgeCalibrationToReport(report, read)\n if (read?.kind !== 'loaded') notices.push('judge calibration unavailable: no matching guarded artifact')\n }\n const staged = new FsReportStore({\n root: input.agentQaRoot,\n outputDir: join(input.runRoot, 'reports'),\n }).save(\n report,\n projectDecisionVectorsDocument({\n batchKey: report.batchKey,\n matcherVersion: report.matcherVersion,\n vectors,\n }),\n { seed: input.seed, records: [...records.values()] },\n )\n if (staged.decisionsFile === undefined) throw new Error('report store did not stage decisions')\n return {\n report, vectors, replaysRoot, reportFile: staged.file, decisionsFile: staged.decisionsFile,\n sweep, wallClockMs, modelCalls, notices: [...sweep.notices, ...notices],\n }\n}\n","import type { CommittedCorpusRead, CommittedReadRefusal } from './committed-corpus-source.js'\nimport type { loadCassetteBundles } from './replay-sweep.js'\n\n/** Admission of the complete committed input precedes replay and any scored-key pairing. */\nexport function committedCorpusAdmissionRefusal(\n committedRoot: string,\n corpus: CommittedCorpusRead,\n loaded: ReturnType<typeof loadCassetteBundles>,\n): CommittedReadRefusal | undefined {\n const refuse = (reason: string, path = committedRoot): CommittedReadRefusal => ({\n path, reason: `committed corpus admission refused: ${reason}`,\n })\n if (corpus.refusals.length > 0) {\n const first = corpus.refusals[0]!\n return refuse(first.reason, first.path)\n }\n const loadFailures = Object.entries(loaded.loadRefusals).filter(([, count]) => count > 0)\n if (loadFailures.length > 0) {\n return refuse(`cassette bundle load refusals: ${loadFailures.map(([reason, count]) => `${reason}=${count}`).join(', ')}`)\n }\n const expected = new Set<string>()\n for (const entry of corpus.snapshot.entries) {\n if (expected.has(entry.cassetteId)) return refuse(`duplicate committed member ${entry.cassetteId}`)\n expected.add(entry.cassetteId)\n }\n if (expected.size === 0) return refuse('no guarded committed members')\n const seen = new Set<string>()\n for (const { cassette } of loaded.loaded) {\n if (corpus.retiredMarkedCassetteIds?.has(cassette.id)) continue\n if (!expected.has(cassette.id)) return refuse(`foreign cassette member ${cassette.id}`)\n if (seen.has(cassette.id)) return refuse(`duplicate cassette member ${cassette.id}`)\n seen.add(cassette.id)\n }\n const missing = [...expected].filter(id => !seen.has(id))\n if (missing.length > 0) return refuse(`missing cassette members: ${missing.join(', ')}`)\n // Blob availability is deliberately not admission: a complete guarded cassette may\n // yield the established missing-blob replay refusal and remain in the report population.\n return undefined\n}\n","// 415 D-04/D-12: per-profile committed floor, using the baseline pointer's\n// refuse → preview → write-once order. The bytes are written as given (441 D-15).\nimport { assertFloorArtefactCommittable, committedFileText } from '@vostride/agent-qa-eval'\nimport type { FloorRefusal, NoiseFloorArtefact } from '@vostride/agent-qa-eval'\n\nimport { FsCommittedRootStore, committedNoiseFloorPath } from './committed-root-store.js'\n\nexport interface WriteNoiseFloorArtefactInput {\n artefact: NoiseFloorArtefact\n committedRoot: string\n}\n\nexport type WriteNoiseFloorArtefactOutcome =\n | { kind: 'written' | 'unchanged'; path: string }\n | { kind: 'refused'; refusal: FloorRefusal }\n | { kind: 'write-conflict'; path: string }\n\nexport function writeNoiseFloorArtefact(\n input: WriteNoiseFloorArtefactInput,\n): WriteNoiseFloorArtefactOutcome {\n const verdict = assertFloorArtefactCommittable(input.artefact)\n if (!verdict.ok) return { kind: 'refused', refusal: verdict.refusal }\n\n const relPath = committedNoiseFloorPath(input.artefact.profileKey)\n const text = committedFileText(input.artefact)\n const store = new FsCommittedRootStore({ committedRoot: input.committedRoot })\n if (store.previewText(relPath, text) === 'conflict') {\n return { kind: 'write-conflict', path: relPath }\n }\n const outcome = store.writeText(relPath, text)\n if (outcome.kind === 'write-conflict') return { kind: 'write-conflict', path: outcome.path }\n return { kind: outcome.kind, path: relPath }\n}\n","// Read-only recovery of complete floor runs. Never rewrites their reports, sidecars or records.\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { canonicalJson, computeBatchKey } from '@vostride/agent-qa-eval'\nimport type { FloorRunInput, StandaloneLabelRecord, ScoringJudgeRequest, CorpusEntry, EvalBatchReport } from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nimport { assembleScoredBatch, projectAssembledBatch } from './replay-batch-assembly.js'\nimport { listReplayRecordDirs, loadReplayRecord, loadScoreRecord } from './replay-read.js'\nimport { loadStagedReport } from './report-store.js'\nimport { reportMetadataKind, legacyReportComparison } from './report-metadata-guard.js'\n\ninterface MeasuredCostReceipt {\n index: number\n seed: number\n decisions: number\n modelCalls: number\n promptTokens: number\n completionTokens: number\n wallClockMs: number\n seedHonored: boolean\n samplesMissingTokenUsage: number\n judgeOutcomesMissingUsage: number\n line: string\n}\n\n/** Cost observations come from the exact retained progress log, never sample-count inference. */\nexport function readMeasuredCostReceipts(path: string, runSeeds: readonly number[]): MeasuredCostReceipt[] {\n const receipts = new Map<number, MeasuredCostReceipt>()\n for (const line of readFileSync(path, 'utf8').split(/\\r?\\n/)) {\n if (!line.startsWith('floor r')) continue\n const match = /^floor r(\\d+) seed=(-?\\d+): decisions=(\\d+) modelCalls=(\\d+) promptTokens=(\\d+) completionTokens=(\\d+) wallClock=(\\d+)ms seedHonored=(true|false)(?: samplesMissingTokenUsage=(\\d+) judgeOutcomesMissingUsage=(\\d+))?$/.exec(line)\n if (match === null) throw new TypeError(`measured floor cost receipt malformed at ${path}`)\n const numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10].map(i => Number(match[i] ?? 0))\n if (!numbers.every(Number.isSafeInteger)) throw new TypeError(`measured floor cost receipt exceeds safe integers at ${path}`)\n const [index, seed, decisions, modelCalls, promptTokens, completionTokens, wallClockMs,\n samplesMissingTokenUsage, judgeOutcomesMissingUsage] = numbers as [number, number, number, number, number, number, number, number, number]\n if (receipts.has(index)) throw new TypeError(`duplicate measured floor receipt r${index} at ${path}`)\n if (runSeeds[index] !== seed) throw new TypeError(`foreign measured floor receipt r${index} seed=${seed} at ${path}`)\n receipts.set(index, { index, seed, decisions, modelCalls, promptTokens, completionTokens, wallClockMs,\n samplesMissingTokenUsage, judgeOutcomesMissingUsage, seedHonored: match[8] === 'true', line })\n }\n if (receipts.size !== runSeeds.length) throw new TypeError(`incomplete measured floor cost receipts at ${path}`)\n return runSeeds.map((_, index) => receipts.get(index)!)\n}\n\nexport function readMeasuredFloorRun(input: {\n agentQaRoot: string\n runRoot: string\n cassettesRoot: string\n fingerprint: string\n corpusDigest: string\n plannerModelId: string\n matcherVersion: number\n productByCassetteId: ReadonlyMap<string, string>\n labelRecords?: ReadonlyMap<string, StandaloneLabelRecord>\n corpusEntriesById?: ReadonlyMap<string, CorpusEntry>\n excludedLabelIds?: ReadonlySet<string>\n calibration?: EvalBatchReport['calibration']\n expectedJudgeRequest?: ScoringJudgeRequest\n receipt: MeasuredCostReceipt\n}): FloorRunInput {\n const { receipt, productByCassetteId } = input\n function refuse(reason: string): never { throw new TypeError(`measured floor r${receipt.index}: ${reason}`) }\n const replaysRoot = join(input.runRoot, 'replays')\n const recordDirs = listReplayRecordDirs(replaysRoot)\n if (recordDirs.length !== productByCassetteId.size) refuse('incomplete replay membership')\n const seen = new Set<string>()\n for (const dir of recordDirs) {\n const loaded = loadReplayRecord(dir)\n if (loaded.kind !== 'loaded') refuse(`unreadable replay at ${dir}`)\n const outcome = loaded.outcome\n if (outcome === null || typeof outcome !== 'object' || typeof outcome.cassetteId !== 'string') {\n refuse(`malformed replay identity at ${dir}`)\n }\n const id = outcome.cassetteId\n if (!productByCassetteId.has(id) || seen.has(id)) refuse(`foreign or duplicate replay ${id}`)\n seen.add(id)\n if (dir !== join(replaysRoot, ...id.split('/').map(segment => slugBranch(segment)))) {\n refuse(`replay identity does not match its path at ${dir}`)\n }\n const score = loadScoreRecord(dir)\n if ('granularity' in outcome) {\n const decisions = outcome.granularity === 'leaf' ? [outcome]\n : outcome.granularity === 'procedure' && Array.isArray(outcome.steps)\n ? outcome.steps.flatMap(step => step.kind === 'decision' ? [step.result] : []) : refuse(`malformed replay ${id}`)\n for (const decision of decisions) {\n if (decision.replayedModel?.modelId !== input.plannerModelId ||\n decision.agreement?.k !== 1 || !Array.isArray(decision.samples) || decision.samples.length !== 1) {\n refuse(`replay model or k=1 protocol differs for ${id}`)\n }\n }\n if (score.kind !== 'loaded' || score.record.cassetteId !== id ||\n score.record.matcherVersion !== input.matcherVersion || score.record.score.cassetteId !== id) {\n refuse(`missing or mismatched score for ${id}`)\n }\n } else if (outcome.kind !== 'integrity-refusal' || score.kind !== 'absent') {\n refuse(`malformed refusal or unexpected score for ${id}`)\n }\n }\n const batchKey = computeBatchKey([...productByCassetteId.keys()])\n const saved = loadStagedReport(input.agentQaRoot, batchKey, join(input.runRoot, 'reports'))\n if (saved.kind !== 'loaded') refuse(`saved report ${saved.kind}: ${saved.file}`)\n if (saved.decisions === undefined) refuse('saved decision sidecar absent')\n const runIdentity = { fingerprint: input.fingerprint, corpusDigest: input.corpusDigest }\n if (canonicalJson(saved.report.runIdentity) !== canonicalJson(runIdentity) ||\n saved.report.matcherVersion !== input.matcherVersion) refuse('saved report identity differs')\n const assemble = (products?: ReadonlyMap<string, string>) => {\n const batch = assembleScoredBatch({ replaysRoot, cassettesRoot: input.cassettesRoot,\n source: 'committed', recordDirs, productByCassetteId: products, expectedJudgeRequest: input.expectedJudgeRequest,\n labelRecords: input.labelRecords, excludedLabelIds: input.excludedLabelIds,\n calibration: input.calibration,\n ...(products === undefined ? {} : { corpusEntriesById: input.corpusEntriesById,\n eligibleCassetteIds: new Set(products.keys()) }) })\n if (batch.missingBundleCount !== 0 || batch.notices.length !== 0) refuse('cassette or score read refused')\n const assembled = projectAssembledBatch(batch, { declaredSeed: receipt.seed, runIdentity })\n // Calibration is historical disclosure, not a value reconstructed from score records.\n // The staged guard already admitted it; preserve it without consulting today's artifact.\n if (saved.report.judge?.calibration !== undefined && assembled.report.judge !== undefined) {\n assembled.report.judge = { ...assembled.report.judge, calibration: saved.report.judge.calibration }\n }\n return assembled\n }\n // Both current committed ownership and the historical scope join are recognized. Every\n // other field must reproduce exactly from retained records before any in-memory correction.\n const corrected = assemble(productByCassetteId)\n const legacy = reportMetadataKind(saved.report) === 'legacy'\n const matches = (candidate: typeof corrected) =>\n canonicalJson(legacy ? legacyReportComparison(candidate.report) : candidate.report) === canonicalJson(saved.report) &&\n canonicalJson(candidate.vectors) === canonicalJson(saved.decisions!.vectors)\n if (!matches(corrected) && (!legacy || !matches(assemble()))) refuse('saved report/decisions do not reproduce from complete records')\n const report = legacy ? saved.report : corrected.report\n const { vectors } = corrected\n const cost = report.totalCost\n const judge = report.honesty.judge.cost\n if (receipt.decisions !== vectors.length || receipt.seedHonored !== report.seedHonored ||\n receipt.promptTokens !== cost.promptTokens + judge.inputTokens ||\n receipt.completionTokens !== cost.completionTokens + judge.outputTokens ||\n receipt.samplesMissingTokenUsage !== cost.samplesMissingTokenUsage ||\n receipt.judgeOutcomesMissingUsage !== judge.outcomesMissingUsage ||\n receipt.modelCalls < cost.sampleCount + judge.calls) refuse('cost receipt differs from saved report evidence')\n return { index: receipt.index, seed: receipt.seed, report, vectors,\n wallClockMs: receipt.wallClockMs, modelCalls: receipt.modelCalls }\n}\n","// Fresh gate replay delegates to replayCorpusOnce → sweepCassetteReplays → runCassetteReplay,\n// retaining its ONE planner createModel site and the existing judge binding.\n// The gate's report and decisions are local audit artifacts, never committed. Committed evidence\n// is read through guarded legs and compared by eval core; no verdict policy is reimplemented here.\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n composeBaselineProfileKey,\n computeCorpusDigest,\n computeGateVerdict,\n guardBaselinePointer,\n renderGateLines,\n} from '@vostride/agent-qa-eval'\nimport type { ComputeGateVerdictInput, EvalBatchReport, GateVerdict } from '@vostride/agent-qa-eval'\nimport type { ModelProfile, ModelProviderOverrides, ResolvedModelAuth } from '@vostride/agent-qa-model'\nimport { slugBranch } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport { replayCorpusOnce } from './aa-floor-composition.js'\nimport {\n listBaselinePointers,\n listCommittedReports,\n listNoiseFloorArtefacts,\n readActiveCommittedCorpus,\n readCommittedDecisionVectors,\n} from './committed-corpus-source.js'\nimport type { CommittedReadRefusal } from './committed-corpus-source.js'\nimport { committedCorpusAdmissionRefusal } from './committed-corpus-admission.js'\nimport {\n committedBaselinePointerPath,\n committedNoiseFloorPath,\n committedReportPath,\n} from './committed-root-store.js'\nimport { computeReplayProfileFingerprintFor } from './replay-composition.js'\nimport type { RunCassetteReplayInput } from './replay-composition.js'\nimport { loadCassetteBundles } from './replay-sweep.js'\nimport { loadStagedReport } from './report-store.js'\n\nexport type ReleaseGateMode =\n | {\n kind: 'fresh'\n profile: ModelProfile\n auth: ResolvedModelAuth\n modelOverrides?: ModelProviderOverrides\n judge?: RunCassetteReplayInput['judge']\n mask: RunCassetteReplayInput['mask']\n seed: number\n cassettesRoot: string\n onProgress?: (line: string) => void\n }\n | {\n kind: 'report'\n batchKey: string\n /** Exactly one report directory; the CLI owns any search order. */\n stagedOutputDir?: string\n profile: ModelProfile\n modelOverrides?: ModelProviderOverrides\n }\n\nexport interface RunReleaseGateInput {\n committedRoot: string\n agentQaRoot: string\n profileKeyInputs: {\n plannerModelId: string\n matcherVersion: number\n judgeModelId?: string\n judgeVersion?: number\n }\n mode: ReleaseGateMode\n clock?: () => number\n}\n\nexport type RunReleaseGateResult =\n | {\n kind: 'verdict'\n verdict: GateVerdict\n lines: string[]\n mode: 'fresh' | 'report'\n profileKey: string\n fingerprint: string\n currentReport: EvalBatchReport\n currentReportFile: string\n /** Actual calls in this invocation, including retries and judge calls; offline is zero. */\n modelCalls: number\n /** Fresh helper replay duration, or offline read/compare duration; never historical cost. */\n wallClockMs: number\n notices: string[]\n refusals: readonly CommittedReadRefusal[]\n }\n | { kind: 'refused'; refusal: CommittedReadRefusal; notices: string[] }\n\nconst runIdentitySchema = z.object({\n fingerprint: z.string().regex(/^[a-f0-9]{64}$/),\n corpusDigest: z.string().regex(/^[a-f0-9]{64}$/),\n}).passthrough()\n\n/** Compose guarded disk evidence with eval core's single comparison law. */\nexport async function runReleaseGate(input: RunReleaseGateInput): Promise<RunReleaseGateResult> {\n const clock = input.clock ?? Date.now\n const started = clock()\n const { mode } = input\n // The gate always declares a seed, matching the floor's policy; seed values do not key profiles.\n const fingerprint = computeReplayProfileFingerprintFor({\n profile: mode.profile, modelOverrides: mode.modelOverrides, seedPolicy: 'declared',\n })\n const expectedProfileKey = composeBaselineProfileKey({ ...input.profileKeyInputs, fingerprint })\n const corpus = readActiveCommittedCorpus(input.committedRoot, input.agentQaRoot)\n const pointers = listBaselinePointers(input.committedRoot)\n const floors = listNoiseFloorArtefacts(input.committedRoot)\n const reports = listCommittedReports(input.committedRoot)\n const notices = [...corpus.notices]\n const refusals = [...corpus.refusals, ...pointers.refusals, ...floors.refusals, ...reports.refusals]\n const corpusDigest = computeCorpusDigest(corpus.snapshot.entries)\n\n // The filename is the designation: a body naming this profile at some other filename is not\n // its pointer.\n const pointerFile = join(input.committedRoot, committedBaselinePointerPath(expectedProfileKey))\n const pointer = readPointer(pointerFile, pointers.pointers.filter(entry =>\n entry.profileKey.startsWith(`planner=${input.profileKeyInputs.plannerModelId}|`)), refusals)\n const floorFile = join(input.committedRoot, committedNoiseFloorPath(expectedProfileKey))\n const floor = floors.artefacts.find(entry => entry.path === floorFile)?.artefact\n let baseline: ComputeGateVerdictInput['baseline']\n if (pointer.kind === 'current') {\n const reportFile = join(input.committedRoot, committedReportPath(pointer.pointer.batchKey, 'report.json'))\n const report = reports.reports.find(entry => entry.path === reportFile)\n const decisions = readCommittedDecisionVectors(input.committedRoot, pointer.pointer.batchKey)\n if (decisions.kind === 'refused') refusals.push(decisions.refusal)\n if (report !== undefined) {\n baseline = { report: report.report,\n ...(decisions.kind === 'loaded' ? { vectors: decisions.document } : {}),\n }\n }\n }\n\n // Only proven foreign profile evidence stops before replay. Absent or rejected pointers,\n // stale corpora, floors and ordinary pairing failures still reach the existing pure gate.\n if (pointer.kind === 'current') {\n const designated = pointer.pointer\n if (designated.profileKey !== expectedProfileKey\n || composeBaselineProfileKey(designated) !== expectedProfileKey) {\n return { kind: 'refused', refusal: { path: pointerFile,\n reason: `baseline profileKey mismatch: designated=${designated.profileKey} expected=${expectedProfileKey}; re-designate this profile's baseline` }, notices }\n }\n if (baseline !== undefined) {\n const report = baseline.report\n const saved = report.runIdentity === undefined ? undefined : runIdentitySchema.safeParse(report.runIdentity)\n if (report.matcherVersion !== designated.matcherVersion\n || report.judge?.judgeModelId !== designated.judgeModelId\n || report.judge?.judgeVersion !== designated.judgeVersion\n || (saved !== undefined && (!saved.success || saved.data.fingerprint !== fingerprint))) {\n return { kind: 'refused', refusal: {\n path: join(input.committedRoot, committedReportPath(designated.batchKey, 'report.json')),\n reason: `baseline report profile identity differs from ${expectedProfileKey}; re-designate this profile's baseline` }, notices }\n }\n }\n }\n\n let current: ComputeGateVerdictInput['current']\n let currentReportFile: string\n let modelCalls = 0\n let freshWallClockMs: number | undefined\n if (mode.kind === 'fresh') {\n const loaded = loadCassetteBundles(mode.cassettesRoot)\n const admission = committedCorpusAdmissionRefusal(input.committedRoot, corpus, loaded)\n if (admission !== undefined) return { kind: 'refused', refusal: admission, notices }\n for (const [reason, count] of Object.entries(loaded.loadRefusals)) {\n notices.push(`cassette bundle load refused: ${reason}=${count}`)\n }\n const eligibleIds = new Set(corpus.snapshot.entries.map(entry => entry.cassetteId))\n const selected = loaded.loaded.filter(entry => eligibleIds.has(entry.cassette.id)).sort((a, b) =>\n a.cassette.id < b.cassette.id ? -1 : a.cassette.id > b.cassette.id ? 1 : 0)\n let run: Awaited<ReturnType<typeof replayCorpusOnce>>\n try {\n run = await replayCorpusOnce({\n committedRoot: input.committedRoot,\n selected,\n loadRefusals: loaded.loadRefusals,\n cassettesRoot: mode.cassettesRoot,\n agentQaRoot: input.agentQaRoot,\n runRoot: join(input.agentQaRoot, 'eval', 'gate', slugBranch(expectedProfileKey)),\n profile: mode.profile,\n auth: mode.auth,\n modelOverrides: mode.modelOverrides,\n judge: mode.judge,\n mask: mode.mask,\n seed: mode.seed,\n k: 1,\n source: 'committed',\n corpusDigest,\n productByCassetteId: new Map(corpus.snapshot.entries.map(entry => [entry.cassetteId, entry.product])),\n labelRecords: corpus.snapshot.labelsById,\n corpusEntriesById: corpus.corpusEntriesById, excludedLabelIds: corpus.snapshot.excludedLabelIds,\n calibration: corpus.calibration,\n clock: input.clock,\n onProgress: mode.onProgress,\n })\n } catch (error) {\n // Per-cassette failures already live in the helper's report. Filesystem failures in\n // final staging retain the OS's exact failed path; caller-contract errors still throw.\n const io = error as NodeJS.ErrnoException\n if (typeof io?.code !== 'string' || typeof io.path !== 'string') throw error\n return { kind: 'refused', refusal: { path: io.path, reason: `gate staging failed: ${io.message}` }, notices }\n }\n current = { report: run.report, vectors: run.vectors, fingerprint, corpusDigest }\n currentReportFile = run.reportFile\n modelCalls = run.modelCalls\n freshWallClockMs = run.wallClockMs\n notices.push(...run.notices)\n const cost = run.report.totalCost\n const judgeCost = run.report.honesty.judge.cost\n const missing = cost.samplesMissingTokenUsage > 0 || judgeCost.outcomesMissingUsage > 0\n ? ` samplesMissingTokenUsage=${cost.samplesMissingTokenUsage} judgeOutcomesMissingUsage=${judgeCost.outcomesMissingUsage}` : ''\n mode.onProgress?.(`gate seed=${mode.seed}: decisions=${run.vectors.length} modelCalls=${modelCalls} ` +\n `promptTokens=${cost.promptTokens + judgeCost.inputTokens} ` +\n `completionTokens=${cost.completionTokens + judgeCost.outputTokens} ` +\n `wallClock=${run.wallClockMs}ms seedHonored=${run.report.seedHonored}${missing}`)\n } else {\n const loaded = loadStagedReport(input.agentQaRoot, mode.batchKey, mode.stagedOutputDir)\n if (loaded.kind !== 'loaded') {\n return { kind: 'refused', refusal: { path: loaded.file,\n reason: loaded.kind === 'absent' ? 'staged report absent' : loaded.reason }, notices }\n }\n currentReportFile = loaded.file\n const vectors = loaded.decisions?.vectors ?? []\n if (loaded.decisions === undefined) {\n notices.push('staged report carries no decisions sidecar — the verdict is inconclusive (no-decision-vector: current); re-run eval report to stage vectors')\n }\n // A report with no vectors cannot compare anyway. Preserve the historical no-vector\n // outcome; any populated offline comparison must establish its actual saved provenance.\n let identity = { fingerprint, corpusDigest }\n if (vectors.length > 0) {\n const saved = runIdentitySchema.safeParse(loaded.report.runIdentity)\n if (!saved.success) {\n return { kind: 'refused', refusal: { path: loaded.file,\n reason: 'staged report runIdentity absent or malformed; re-run eval gate to stage identified evidence' }, notices }\n }\n for (const field of ['fingerprint', 'corpusDigest'] as const) {\n if (saved.data[field] !== identity[field]) {\n return { kind: 'refused', refusal: { path: loaded.file,\n reason: `staged report runIdentity ${field} mismatch: saved=${saved.data[field]} current=${identity[field]}; re-run eval gate` }, notices }\n }\n }\n identity = saved.data\n }\n current = { report: loaded.report, vectors, ...identity }\n }\n const verdict = computeGateVerdict({ expectedProfileKey, pointer, floor, baseline, current })\n return {\n kind: 'verdict', verdict, lines: renderGateLines(verdict), mode: mode.kind,\n profileKey: expectedProfileKey, fingerprint, currentReport: current.report,\n currentReportFile, modelCalls, wallClockMs: freshWallClockMs ?? clock() - started,\n notices, refusals,\n }\n}\n\nfunction readPointer(\n path: string,\n others: readonly { profileKey: string }[],\n refusals: CommittedReadRefusal[],\n): ComputeGateVerdictInput['pointer'] {\n let value: unknown\n try {\n value = JSON.parse(readFileSync(path, 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'absent', others }\n const reason = `baseline pointer unreadable: ${(error as Error).message}`\n if (!refusals.some(refusal => refusal.path === path)) refusals.push({ path, reason })\n return { kind: 'rejected', reason }\n }\n const guarded = guardBaselinePointer(value)\n if (guarded.kind === 'rejected' && !refusals.some(refusal => refusal.path === path)) {\n refusals.push({ path, reason: guarded.reason })\n }\n return guarded\n}\n","// The committed-report writer (Phase 372 D-13, BASE-02) — sibling of seedCommittedCorpus,\n// same recipe. It places the aggregated EvalBatchReport JSON DTO plus its rendered markdown\n// projection, plus optional decisions.json pairing evidence (415 D-16), under\n// reports/<slug(batchKey)>/ inside the committed root.\n//\n// Composition law (ROOT-02 discipline extended):\n// - Committed bytes are written as given (441 D-15): no content check runs on them.\n// - Write-once (D-17): all relPaths are PREVIEWED before any write; a conflict on ANY part\n// refuses the whole report writing nothing. A byte-identical regen reports 'unchanged'\n// everywhere; a changed corpus produces a different batchKey and therefore a fresh dir —\n// the committed baseline can never be silently rewritten (T-372-07).\n// - report.json is serialized by eval core's committedFileText (the ONE serializer); the\n// markdown's byte-determinism is the renderer's contract — this helper only byte-compares.\n// - The helper makes ZERO model calls and opens no safety scope.\n\nimport { join } from 'node:path'\n\nimport { committedFileText } from '@vostride/agent-qa-eval'\nimport type { DecisionVectorsDocument, EvalBatchReport } from '@vostride/agent-qa-eval'\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\nimport {\n COMMITTED_REPORTS_DIR,\n FsCommittedRootStore,\n committedReportPath,\n} from './committed-root-store.js'\n\nexport const COMMITTED_REPORT_JSON_FILE = 'report.json'\nexport const COMMITTED_REPORT_MARKDOWN_FILE = 'report.md'\nexport const COMMITTED_REPORT_DECISIONS_FILE = 'decisions.json'\n\nexport interface CommitEvalReportInput {\n /** The pure eval-core report DTO — batchKey names the committed dir. */\n report: EvalBatchReport\n /** Optional pairing evidence for this same batch and matcher, never a separate channel. */\n decisions?: DecisionVectorsDocument\n /** The rendered markdown projection; byte-determinism is the renderer's contract. */\n markdown: string\n /** Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the 372 CLI. */\n committedRoot: string\n}\n\nexport type CommitEvalReportOutcome =\n | {\n kind: 'committed'\n json: 'written' | 'unchanged'\n markdown: 'written' | 'unchanged'\n decisions?: 'written' | 'unchanged'\n reportDir: string\n }\n | { kind: 'write-conflict'; path: string }\n\n/**\n * Commit the baseline report beside the corpus/contracts that produced it: preview ALL paths,\n * then write — one atomic unit (D-13/D-17).\n */\nexport function commitEvalReport(input: CommitEvalReportInput): CommitEvalReportOutcome {\n // Same-report identity is a caller contract, like the baseline-pointer writer's contract.\n // Check before touching any committed output.\n if (input.decisions !== undefined) {\n for (const field of ['batchKey', 'matcherVersion'] as const) {\n if (input.decisions[field] !== input.report[field]) {\n throw new TypeError(`decisions ${field} does not match the report ${field}`)\n }\n }\n }\n const store = new FsCommittedRootStore({ committedRoot: input.committedRoot })\n\n const batchKey = input.report.batchKey\n const parts: { relPath: string; label: string; text: string }[] = [\n {\n relPath: committedReportPath(batchKey, COMMITTED_REPORT_JSON_FILE),\n label: `report-json:${batchKey}`,\n text: committedFileText(input.report),\n },\n {\n relPath: committedReportPath(batchKey, COMMITTED_REPORT_MARKDOWN_FILE),\n label: `report-markdown:${batchKey}`,\n text: input.markdown,\n },\n ]\n if (input.decisions !== undefined) {\n parts.push({\n relPath: committedReportPath(batchKey, COMMITTED_REPORT_DECISIONS_FILE),\n label: 'report-decisions:' + batchKey,\n text: committedFileText(input.decisions),\n })\n }\n\n // (1) Preview ALL paths before writing ANY — a conflict on one part leaves even the\n // non-conflicting part unwritten (D-17 atomicity).\n const conflicting = parts.find(\n (part) => store.previewText(part.relPath, part.text) === 'conflict',\n )\n if (conflicting !== undefined) {\n return { kind: 'write-conflict', path: conflicting.relPath }\n }\n\n // (2) Write all; after preview a conflict cannot occur here, but map it defensively.\n const outcomes = parts.map((part) => store.writeText(part.relPath, part.text))\n for (const outcome of outcomes) {\n if (outcome.kind === 'write-conflict') return { kind: 'write-conflict', path: outcome.path }\n }\n\n return {\n kind: 'committed',\n json: outcomes[0]!.kind === 'written' ? 'written' : 'unchanged',\n markdown: outcomes[1]!.kind === 'written' ? 'written' : 'unchanged',\n ...(outcomes[2] === undefined ? {} : {\n decisions: outcomes[2].kind === 'written' ? 'written' as const : 'unchanged' as const,\n }),\n reportDir: join(input.committedRoot, COMMITTED_REPORTS_DIR, slugBranch(batchKey)),\n }\n}\n","// The write-once committed baseline-pointer writer (Phase 413 D-19/D-20, ROOT-11) — the\n// report-committing recipe with ONE part, plus a pure refusal gate in front of it.\n//\n// Composition law:\n// - (0) REFUSE FIRST. `assertBaselineComparator` is eval core's ONE predicate (D-20); a report\n// judged under the same-family override is not a gate comparator, so it is refused before\n// any path is resolved and leaves no file.\n// - (1) The pointer bytes are written as given (441 D-15): no content check runs on them.\n// - (2) Write-once (371 D-17): preview then write. A byte-identical re-designation is\n// 'unchanged'; a profile key already pointing at a different batch is a typed\n// 'write-conflict', never an overwrite — MOVING a baseline is a reviewed git edit (D-19).\n// - The pointer body is serialized by eval core's `committedFileText` (the ONE serializer) and\n// carries no wall-clock field, so re-designation byte-compares rather than churning.\n\nimport { assertBaselineComparator, committedFileText } from '@vostride/agent-qa-eval'\nimport type {\n BaselineComparatorRefusal,\n BaselinePointer,\n EvalBatchReport,\n} from '@vostride/agent-qa-eval'\n\nimport { FsCommittedRootStore, committedBaselinePointerPath } from './committed-root-store.js'\n\nexport interface WriteBaselinePointerInput {\n /** The report being designated — its judge provenance decides comparator eligibility. */\n report: EvalBatchReport\n /** The v2 pointer, including fingerprint and corpusDigest; batchKey names the same report. */\n pointer: BaselinePointer\n /** Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the CLI. */\n committedRoot: string\n}\n\nexport type WriteBaselinePointerOutcome =\n | { kind: 'written' | 'unchanged'; path: string }\n | { kind: 'refused'; refusal: BaselineComparatorRefusal }\n | { kind: 'write-conflict'; path: string }\n\n/**\n * Designate a per-profile baseline: refuse-then-preview-then-write.\n *\n * A pointer whose batchKey does not name the designated report is a CALLER bug, not data — the\n * outcome union stays closed for the three honest answers and a mismatch raises instead.\n */\nexport function writeBaselinePointer(\n input: WriteBaselinePointerInput,\n): WriteBaselinePointerOutcome {\n // (0) The ONE predicate, before any path resolution (D-20).\n const verdict = assertBaselineComparator(input.report)\n if (!verdict.ok) return { kind: 'refused', refusal: verdict.refusal }\n\n if (input.pointer.batchKey !== input.report.batchKey) {\n throw new TypeError(\n `baseline pointer batchKey ${input.pointer.batchKey} does not name the designated report ${input.report.batchKey}`,\n )\n }\n\n const relPath = committedBaselinePointerPath(input.pointer.profileKey)\n const text = committedFileText(input.pointer)\n\n // (1) Preview before writing: a key already pointing elsewhere refuses without touching it.\n const store = new FsCommittedRootStore({ committedRoot: input.committedRoot })\n if (store.previewText(relPath, text) === 'conflict') {\n return { kind: 'write-conflict', path: relPath }\n }\n\n // (2) Write-once; a conflict cannot occur after the preview but is mapped defensively.\n const outcome = store.writeText(relPath, text)\n if (outcome.kind === 'write-conflict') return { kind: 'write-conflict', path: outcome.path }\n return { kind: outcome.kind, path: relPath }\n}\n","// GATE-SIDE posture composition (414 D-15, ROOT-10) — the committed-root read leg folded into\n// eval core's pure `readGatePosture`.\n//\n// Composition law, the census-committing shape applied to the gate: every filesystem read lives\n// in eval-local and every derivation lives in eval core. This helper loads the corpus snapshot\n// and the partition manifests off disk and hands both to `readGatePosture`, which computes.\n// Nothing here counts, resolves a scope or judges capability.\n//\n// WHY THE MAIN ENTRY. This is the GATE's view of what could gate, and the gate is not the\n// proposer. Plan 06's `/reader` subpath is the proposer-visible port — it must never see private\n// held-out entries, and D-09 says private entries DO gate. Exporting the posture from `/reader`\n// would hand the proposer a count of the very entries the split exists to hide from it, so this\n// symbol lives on the main entry and the reader port does not re-export it.\n//\n// Refusal posture, inherited from both reads: a committed root is hand-editable, so an\n// unadmittable manifest or corpus entry is a refusal ROW carried out to the caller beside the\n// posture, never a throw and never a silently smaller answer. A refused manifest is a manifest\n// that is not there — the partition echo reports `absent` and the posture still answers.\n\nimport { readGatePosture } from '@vostride/agent-qa-eval'\nimport type {\n CanaryEvidenceSummary,\n GatePosture,\n JudgeCapabilityInput,\n} from '@vostride/agent-qa-eval'\nimport type { ScopeKey } from '@vostride/agent-qa-schema'\n\nimport { dirname, join } from 'node:path'\nimport { readActiveCommittedCorpus, readPartitionManifests } from './committed-corpus-source.js'\nimport type { CommittedReadRefusal } from './committed-corpus-source.js'\n\nexport interface ReadGatePostureForInput {\n /** Explicit absolute committed-root path — `<configDir>/agent-qa-eval` for the CLI. */\n committedRoot: string\n agentQaRoot?: string\n /** The scope being asked about; `resolveProductPartition` is the ONE mapping (D-16). */\n scope: ScopeKey\n /** REQUIRED integer floor, >= 1. No default exists anywhere (D-12). */\n minimumGateSet: number\n /** Complete raw judge declaration and recorded identity; passed intact to the pure fold. */\n judge: JudgeCapabilityInput\n /** Canary evidence as DATA; eval never imports knowledge-local. */\n canary: CanaryEvidenceSummary\n}\n\nexport interface ReadGatePostureForResult {\n posture: GatePosture\n /** Every notice both reads produced, in read order: corpus first, then manifests. */\n notices: string[]\n /** Every refusal both reads produced — never dropped, never merged into a count. */\n refusals: readonly CommittedReadRefusal[]\n}\n\n/**\n * Read the committed root and fold it into the gate posture for one scope.\n *\n * Throws only what `readGatePosture` throws: a `minimumGateSet` that is not a positive integer is\n * a caller bug, not data. Everything the DISK got wrong is a refusal row.\n */\nexport function readGatePostureFor(input: ReadGatePostureForInput): ReadGatePostureForResult {\n const corpus = readActiveCommittedCorpus(input.committedRoot,\n input.agentQaRoot ?? join(dirname(input.committedRoot), '.agent-qa'))\n const manifests = readPartitionManifests(input.committedRoot)\n\n const posture = readGatePosture({\n snapshot: corpus.snapshot,\n manifests: manifests.manifests,\n scope: input.scope,\n minimumGateSet: input.minimumGateSet,\n judge: input.judge,\n canary: input.canary,\n })\n\n return {\n posture,\n notices: [...corpus.notices, ...manifests.notices],\n refusals: [...corpus.refusals, ...manifests.refusals],\n }\n}\n"],"mappings":";AA4BA,SAAS,cAAAA,aAAY,cAAAC,mBAAkB;AACvC,SAAS,aAAAC,YAAW,aAAAC,YAAW,YAAAC,WAAU,aAAAC,YAAW,aAAAC,YAAW,eAAAC,cAAa,YAAAC,WAAU,gBAAAC,gBAAc,eAAAC,cAAa,gBAAAC,eAAc,cAAAC,aAAY,UAAAC,SAAQ,iBAAAC,uBAAqB;AACxK,SAAS,WAAAC,UAAS,QAAAC,QAAM,WAAAC,gBAAe;AAEvC;AAAA,EACE;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAAC;AAAA,EACA,yBAAAC;AAAA,EACA;AAAA,EACA,iBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,iBAAAC;AAAA,EACA;AAAA,EACA,iBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,8BAAAC;AAAA,OAoBK;AACP,SAAS,cAAAC,oBAA+B;AACxC,SAAS,KAAAC,WAAS;;;AC1ClB,SAAS,WAAW,WAAW,UAAU,WAAW,WAAW,UAAU,cAAc,aAAa,cAAc,QAAQ,qBAAqB;AAC/I,SAAS,YAAY,kBAAkB;AACvC,SAAS,SAAS,MAAM,eAAe;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAOX,IAAM,2BAA2B;AAEjC,IAAM,mCAAmC;AAMhD,IAAM,sBAAsB;AAE5B,IAAM,eAAe;AACrB,IAAM,cAAc,EAAE,OAAO,EAAE,MAAM,YAAY;AAmDjD,IAA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UUID","closeSync","fsyncSync","linkSync","lstatSync","mkdirSync","mkdtempSync","openSync","readFileSync","readdirSync","realpathSync","renameSync","rmSync","writeFileSync","dirname","join","resolve","ADVERSARIAL_MUTATORS","GENERATOR_KINDS","PROBE_GENERATOR_KINDS","canonicalJson","committedFileText","deriveRunSlug","guardCassette","parseStandaloneLabelRecord","slugBranch","z","createHash","mkdirSync","readFileSync","writeFileSync","dirname","join","slugBranch","createHash","mkdirSync","rmSync","writeFileSync","join","slugBranch","BLOB_SHA_RE","slugBranch","byteSha","createHash","join","readFileSync","mkdirSync","dirname","writeFileSync","existsSync","readdirSync","readFileSync","join","guardDecisionVectorsDocument","parseStandaloneLabelRecord","selectEffectiveLabels","slugBranch","z","readFileSync","basename","join","guardCassette","readFileSync","join","BLOB_SHA_RE","id","basename","join","readFileSync","guardCassette","existsSync","readFileSync","readdirSync","basename","join","mkdirSync","rmSync","writeFileSync","join","slugBranch","mkdirSync","writeFileSync","join","slugBranch","join","slugBranch","mkdirSync","writeFileSync","readFileSync","join","basename","existsSync","readdirSync","closeSync","existsSync","fsyncSync","openSync","readFileSync","renameSync","writeFileSync","join","canonicalJson","slugBranch","z","randomUUID","closeSync","fsyncSync","lstatSync","mkdirSync","openSync","readFileSync","rmSync","writeFileSync","dirname","join","z","current","resolve","z","openSync","writeFileSync","fsyncSync","closeSync","renameSync","slugBranch","join","readFileSync","prior","canonicalJson","existsSync","lstatSync","readdirSync","readFileSync","dirname","join","resolve","z","canonicalJson","z","resolve","lstatSync","dirname","canonicalJson","join","walk","readdirSync","readFileSync","id","z","ADVERSARIAL_MUTATORS","count","unit","rate","recovery","mkdirSync","readFileSync","renameSync","unlinkSync","writeFileSync","basename","dirname","join","sha256hex","slugBranch","z","z","agreement","id","readFileSync","unlinkSync","join","slugBranch","sha256hex","mkdirSync","dirname","basename","writeFileSync","renameSync","z","join","existsSync","readdirSync","guardDecisionVectorsDocument","current","readFileSync","slugBranch","id","parseStandaloneLabelRecord","selectEffectiveLabels","refusal","dirname","join","resolve","createHash","lstatSync","mkdirSync","mkdtempSync","readdirSync","readFileSync","realpathSync","renameSync","rmSync","writeFileSync","applyBriefDelta","buildEvalReport","computeCorpusDigest","computeDecisionIdentity","deriveSampleSeeds","committedFileText","extractRunCassettes","maskCorpusText","resolveProductPartition","slugBranch","z","loadCompletedRunHandoff","RUNS_SUBDIR","HANDOFF_FILE","join","slugBranch","createPanelIdentity","createModel","z","model","createPanelIdentity","model","createModel","bumpCounter","join","slugBranch","canonicalJson","judgeIdentitySchema","sha256hex","judgeIdentitySchema","identity","canonicalJson","ref","row","sha256hex","existsSync","readFileSync","join","canonicalJson","runExclusionRecordSchema","join","existsSync","readFileSync","runExclusionRecordSchema","canonicalJson","join","existsSync","HANDOFF_FILE","RUNS_SUBDIR","assessJudgeEligibility","assessPanelEligibility","createPanelIdentity","buildEvalReport","decisionCorrectnessVectors","effectiveGold","resolveScoringContext","JUDGE_CONFIG","slugBranch","existsSync","readdirSync","join","canonicalJson","sha256hex","slugBranch","z","projectMatcherConfigContract","scoringContextSchema","judgeIdentitySchema","hasValidScoreJudgeMetadata","canonicalJson","sha256hex","refusal","join","slugBranch","existsSync","readdirSync","sha256hex","canonicalJson","generation","join","RUNS_SUBDIR","slugBranch","HANDOFF_FILE","existsSync","sample","resolveScoringContext","decisionCorrectnessVectors","line","effectiveGold","gold","cost","buildEvalReport","identity","createPanelIdentity","common","assessJudgeEligibility","assessPanelEligibility","JUDGE_CONFIG","id","row","fold","z","join","realpathSync","slugBranch","pathPresent","lstatSync","requireDirectories","resolve","dirname","readdirSync","loadCompletedRunHandoff","RUNS_SUBDIR","HANDOFF_FILE","resolveProductPartition","extractRunCassettes","maskCorpusText","committedFileText","createHash","mkdirSync","mkdtempSync","writeFileSync","renameSync","rmSync","readFileSync","refusal","id","computeCorpusDigest","deriveSampleSeeds","digest","computeDecisionIdentity","applyBriefDelta","firstSample","buildEvalReport","LOWER_HEX_64","digestField","z","ADVERSARIAL_MUTATORS","GENERATOR_KINDS","digest","slugBranch","openSync","fsyncSync","closeSync","lstatSync","requireDirectories","join","identity","readdirSync","randomUUID","mkdirSync","writeFileSync","committedFileText","current","renameSync","dirname","rmSync","id","pathPresent","realpathSync","readFileSync","linkSync","resolve","directoryNames","createHash","canonicalJson","PROBE_GENERATOR_KINDS","mkdtempSync","guardCassette","parseStandaloneLabelRecord","landed","complete","admitted","deriveRunSlug","refusal","assessPanelEligibility","createPanelIdentity","existsSync","readFileSync","readdirSync","join","activeMarkedCorpusEntries","canonicalJson","computeDecisionIdentity","createScoringContext","deriveRunSlug","resolveProductPartition","HANDOFF_FILE","RUNS_SUBDIR","loadCompletedRunHandoff","sha256hex","slugBranch","hash","sha256hex","canonicalJson","existsSync","readdirSync","join","id","RUNS_SUBDIR","deriveRunSlug","HANDOFF_FILE","loadCompletedRunHandoff","resolveProductPartition","activeMarkedCorpusEntries","slugBranch","gold","readFileSync","sample","computeDecisionIdentity","createScoringContext","randomUUID","closeSync","fsyncSync","linkSync","lstatSync","mkdirSync","openSync","readFileSync","renameSync","unlinkSync","writeFileSync","dirname","join","z","canonicalJson","committedFileText","composeBaselineProfileKey","createPanelIdentity","projectJudgeConfigContract","projectMatcherConfigContract","GENERATOR_KINDS","GENERATOR_PROVENANCES","sha256hex","slugBranch","hash","sha256hex","canonicalJson","count","z","digest","unit","rate","closedCounts","GENERATOR_PROVENANCES","GENERATOR_KINDS","slugBranch","projectJudgeConfigContract","projectMatcherConfigContract","composeBaselineProfileKey","createPanelIdentity","counts","value","ids","identity","lstatSync","readFileSync","join","mkdirSync","dirname","committedFileText","randomUUID","openSync","writeFileSync","fsyncSync","closeSync","linkSync","renameSync","unlinkSync","id","identity","createPanelIdentity","assessPanelEligibility","common","closeSync","existsSync","fsyncSync","linkSync","lstatSync","mkdirSync","openSync","readFileSync","readdirSync","renameSync","unlinkSync","writeFileSync","dirname","join","canonicalJson","committedFileText","computeCorpusDigest","deriveLabelRevisionId","sha256hex","existsSync","readFileSync","readdirSync","realpathSync","join","relative","canonicalJson","deriveRunSlug","resolveProductPartition","HANDOFF_FILE","RUNS_SUBDIR","loadCompletedRunHandoff","relative","realpathSync","deriveRunSlug","join","RUNS_SUBDIR","existsSync","id","HANDOFF_FILE","loadCompletedRunHandoff","resolveProductPartition","readFileSync","canonicalJson","readdirSync","existsSync","realpathSync","isAbsolute","join","relative","resolve","canonicalJson","deriveRunSlug","resolveProductPartition","HANDOFF_FILE","RUNS_SUBDIR","loadCompletedRunHandoff","contained","relative","realpathSync","isAbsolute","deriveRunSlug","resolveProductPartition","refused","resolve","RUNS_SUBDIR","HANDOFF_FILE","loadCompletedRunHandoff","canonicalJson","join","existsSync","join","readFileSync","existsSync","readdirSync","computeCorpusDigest","id","current","canonicalJson","sha256hex","deriveLabelRevisionId","committedFileText","identity","openSync","writeFileSync","fsyncSync","closeSync","lstatSync","mkdirSync","dirname","temp","linkSync","renameSync","unlinkSync","extractRunCassettes","maskCorpusText","join","committedFileText","slugBranch","committedFileText","join","slugBranch","maskCorpusText","extractRunCassettes","join","HANDOFF_FILE","RUNS_SUBDIR","loadCompletedRunHandoff","slugBranch","readFileSync","join","composeBaselineProfileKey","canonicalJson","computeCorpusDigest","sha256hex","slugBranch","count","id","committedFileText","committedFileText","readFileSync","join","canonicalJson","slugBranch","readFileSync","join","id","slugBranch","canonicalJson","cost","composeBaselineProfileKey","computeCorpusDigest","counts","count","join","slugBranch","cost","readFileSync","rate","sha256hex","canonicalJson","readFileSync","join","composeBaselineProfileKey","computeCorpusDigest","guardBaselinePointer","slugBranch","z","z","composeBaselineProfileKey","computeCorpusDigest","join","current","count","slugBranch","cost","identity","readFileSync","refusal","guardBaselinePointer","join","committedFileText","slugBranch","committedFileText","join","slugBranch","assertBaselineComparator","committedFileText","assertBaselineComparator","committedFileText","dirname","join","join","dirname"]}