@vostride/agent-qa-knowledge-local 0.0.1 → 0.2.2

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/curator/curation-snapshot.ts","../src/maintenance-scan.ts","../src/bundle-read.ts","../src/journal/curation-effect-receipt.ts","../src/durable-fs.ts","../src/knowledge-containment.ts","../src/lease/writer-lease.ts","../src/bundle-scan.ts","../src/diff-since.ts","../src/purge-receipt.ts","../src/canary-emit.ts","../src/anchor-schema.ts","../src/queue-transport.ts","../src/addressing/ledger.ts","../src/resolver/resolve.ts","../src/entity-index/entity-index.ts","../src/index-open.ts","../src/sqlite-vec-loadable.ts","../src/entity-index/renderings.ts","../src/resolver/hybrid.ts","../src/retrieve.ts","../src/index-reader.ts","../src/rebuild-marker.ts","../src/retrieval/fts-match.ts","../src/promotion-gate-input.ts","../src/lineage-fold.ts","../src/trust-prior-context.ts","../src/query-helper.ts","../src/retrieval/constants.ts","../src/retrieval/query-class.ts","../src/retrieval/pre-filter.ts","../src/retrieval/expansion.ts","../src/retrieval/fusion.ts","../src/retrieval/legs.ts","../src/embedder-acquire.ts","../src/embed-cache.ts","../src/embedder-floor.ts","../src/embedder-native.ts","../src/model-cache-dir.ts","../src/embedder-worker/worker-registration.ts","../src/retrieval/rerank.ts","../src/retrieval/validity.ts","../src/build-ordinal-read.ts","../src/resolver/constants.ts","../src/list-bundles.ts","../src/memory-status.ts","../src/resolver/memory-source.ts","../src/quarantine/ledger.ts","../src/quarantine/identity.ts","../src/quarantine/detection.ts","../src/projection/run-outcome-constants.ts","../src/projection/fingerprint-window-read.ts","../src/quarantine/operations.ts","../src/lease/under-writer-lease.ts","../src/artifact-copy.ts","../src/bundle-parts.ts","../src/bundle-publish.ts","../src/bundle-publish.test-helper.ts","../src/bundle-append.ts","../src/journal/bundle-mutation.ts","../src/canonical-bundle-state-digests.ts","../src/serving/reader.ts","../src/serving/get-cautions.ts","../src/serving/brief-selection.ts","../src/serving/brief-render.ts","../src/serving/serve-trace.ts","../src/serving/get-procedure.ts","../src/serving/get-run-brief.ts","../src/serving/policy-ladder.ts","../src/serving/authoring-reader.ts","../src/serving/get-authoring-brief.ts","../src/retrieval-rung.ts","../src/index-rebuild.ts","../src/contextual-rendering.ts","../src/graph-derive.ts","../src/projection/run-outcomes.ts","../src/projection/path-present.ts","../src/projection/run-outcome-read.ts","../src/projection/suite-fingerprints.ts","../src/gc.ts","../src/profile-migration.ts","../src/embedder-worker/worker-incarnation.ts","../src/queue/queue-payload.ts","../src/queue/curation-queue.ts","../src/queue/job-state.ts","../src/journal/intent-journal.ts","../src/curator/author-contract.ts","../src/curator/commit.ts","../src/curator/disposition.ts","../src/serving/canary-observation-id.ts","../src/curator/drain.ts","../src/journal/reconcile.ts","../src/curator/fallback.ts","../src/curator/knowledge-store.ts","../src/curator/maintenance.ts","../src/purge.ts","../src/inspect.ts","../src/show-records.ts","../src/show-record.ts","../src/review/propose-review.ts","../src/review/apply-review.ts","../src/policy/materialize.ts","../src/review/forget-receipt-journal.ts","../src/authoring/draft-receipts-store.ts","../src/rollback.ts","../src/gates/canary-posture-facts.ts","../src/feedback/apply-feedback.ts","../src/feedback/floor-prose.ts","../src/feedback/mark-evidence.ts","../src/feedback/mark-evidence-plan.ts"],"sourcesContent":["import {\n canonicalJson, CURATION_BUCKET_PRECEDENCE, CURATION_SNAPSHOT_SCHEMA_VERSION, CurationSnapshotSchema,\n CurationSnapshotChangeSchema, RECORD_CHANGE_SCHEMA_VERSION, survivingOutcomeEvents,\n type CurationSnapshot, type CurationSnapshotChange, type CurationSnapshotRow,\n} from '@vostride/agent-qa-schema'\nimport { enumerateMaintenanceBundleDirs, loadMaintenanceBundle } from '../maintenance-scan.js'\nimport { listCurationEffectReceipts } from '../journal/curation-effect-receipt.js'\nimport { diffSince } from '../diff-since.js'\n\nexport interface ReadCurationEffectsOptions {\n knowledgeRoot: string\n sourceRunId: string\n observationIds?: readonly string[]\n}\n\n/** Read only successful, surviving effects; current status is never classification authority. */\nexport function readCurationEffects(options: ReadCurationEffectsOptions): CurationSnapshotChange[] {\n return readCurationEffectsForRun(options).effects\n}\n\n/**\n * `runLinked` is whether any surviving store change carries this run's id or one of its canary\n * observation ids. An empty effect list means \"nothing committed\" only when it is false; otherwise\n * the receipts were lost and absent must never read as zero.\n */\nexport function readCurationEffectsForRun(\n options: ReadCurationEffectsOptions,\n): { effects: CurationSnapshotChange[]; runLinked: boolean } {\n const receipts = listCurationEffectReceipts(options.knowledgeRoot)\n .filter(row => row.sourceRunId === options.sourceRunId)\n const bundles = enumerateMaintenanceBundleDirs(options.knowledgeRoot).map(entry => ({\n product: entry.product, bundle: loadMaintenanceBundle(entry),\n }))\n const effects: CurationSnapshotChange[] = []\n for (const receipt of receipts) {\n const found = bundles.find(({ product, bundle }) => product === receipt.product\n && bundle.manifest.id === receipt.recordId)\n if (found === undefined) continue\n const surviving = survivingOutcomeEvents(found.bundle.events).some(event =>\n event.curationJobId === receipt.candidateId\n && event.evidenceToken === receipt.evidenceToken\n && event.buildOrdinal === receipt.atOrdinal\n && event.type === (receipt.change === 'added' ? 'confirmed' : receipt.change)\n && (receipt.byRecordId === undefined || (event.type === 'superseded'\n && event.byRecordId === receipt.byRecordId)),\n )\n if (!surviving) continue\n const bucket = receipt.disposition === 'downgraded' ? 'proposed' : receipt.change\n effects.push(CurationSnapshotChangeSchema.parse({ bucket, change: {\n schemaVersion: RECORD_CHANGE_SCHEMA_VERSION, recordId: receipt.recordId, change: receipt.change,\n atOrdinal: receipt.atOrdinal, evidenceToken: receipt.evidenceToken,\n sourceRunId: receipt.sourceRunId, observationId: receipt.observationId,\n ...(receipt.byRecordId === undefined ? {} : { byRecordId: receipt.byRecordId }),\n } }))\n }\n // The maintenance fold already applies canonical replay/retraction identities and\n // promotion receipt attribution. Never infer a curation Add/Confirm from bundle shape.\n const observations = new Set(options.observationIds ?? [])\n let runLinked = false\n for (const change of diffSince({ knowledgeRoot: options.knowledgeRoot, sinceOrdinal: 0 })) {\n const canary = change.observationId !== undefined && observations.has(change.observationId)\n if (canary || change.sourceRunId === options.sourceRunId) runLinked = true\n if ((change.change === 'confirmed' && canary)\n || (change.change === 'promoted' && (canary || change.sourceRunId === options.sourceRunId))) {\n // The caller's emitted observation identities attribute this event to the run,\n // even when the affected bundle originated in an older run.\n effects.push(CurationSnapshotChangeSchema.parse({ bucket: 'confirmed', change: {\n ...change, ...(canary ? { sourceRunId: options.sourceRunId } : {}),\n } }))\n }\n }\n return { effects, runLinked }\n}\n\n/** One affected record, strongest classification, with all historical identities retained. */\nexport function foldCurationSnapshot(effects: readonly CurationSnapshotChange[]): CurationSnapshot {\n const identities = new Map<string, CurationSnapshotChange>()\n for (const value of effects) {\n const entry = CurationSnapshotChangeSchema.parse(value)\n const key = canonicalJson(entry.change)\n const previous = identities.get(key)\n if (previous !== undefined && previous.bucket !== entry.bucket) {\n throw new TypeError('conflicting curation classification')\n }\n identities.set(key, entry)\n }\n const groups = new Map<string, CurationSnapshotChange[]>()\n for (const [, entry] of [...identities].sort(([a], [b]) => a.localeCompare(b))) {\n const group = groups.get(entry.change.recordId) ?? []\n group.push(entry)\n groups.set(entry.change.recordId, group)\n }\n const rows: CurationSnapshotRow[] = [...groups].map(([recordId, changes]) => {\n const bucket = CURATION_BUCKET_PRECEDENCE.find(value => changes.some(e => e.bucket === value))!\n const latest = changes.filter(e => e.bucket === 'superseded')\n .sort((a, b) => b.change.atOrdinal - a.change.atOrdinal)[0]\n return { recordId, bucket, changes,\n ...(latest === undefined ? {} : { byRecordId: latest.change.byRecordId }) }\n })\n for (const row of rows) {\n for (const entry of [...row.changes]) {\n if (entry.bucket !== 'superseded') continue\n const replacement = rows.find(r => r.recordId === entry.change.byRecordId)\n if (replacement === undefined) continue\n // Suppress only Add membership. A separately recorded confirmation remains\n // its own affected unit; never invent it from replay or a diagnostic counter.\n const adds = replacement.changes.filter(e => e.bucket === 'added' && e.change.recordId === replacement.recordId)\n for (const added of adds) {\n if (!row.changes.some(e => canonicalJson(e.change) === canonicalJson(added.change))) row.changes.push(added)\n }\n replacement.changes = replacement.changes.filter(e => !adds.includes(e))\n }\n }\n const retained = rows.filter(row => row.changes.length > 0)\n for (const row of retained) {\n row.bucket = CURATION_BUCKET_PRECEDENCE.find(bucket => row.changes.some(entry =>\n entry.change.recordId === row.recordId && entry.bucket === bucket))!\n }\n const breakdown = { added: 0, confirmed: 0, superseded: 0, deprecated: 0, proposed: 0 }\n for (const row of retained) breakdown[row.bucket]++\n return CurationSnapshotSchema.parse({ schemaVersion: CURATION_SNAPSHOT_SCHEMA_VERSION, rows: retained, breakdown })\n}\n","import { readdirSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { loadBundle, verifyBundleIntegrity, type LoadedBundle } from './bundle-read.js'\nimport type { EnumeratedBundleDir } from './bundle-scan.js'\n\nexport type KnowledgeMaintenanceScanIssue =\n | 'directory-read'\n | 'non-directory-entry'\n | 'bundle-load'\n | 'bundle-integrity'\n | 'receipt-read'\n | 'receipt-invalid'\n\n/** Fail-closed maintenance read error: callers must never render a partial clean-looking view. */\nexport class KnowledgeMaintenanceScanError extends Error {\n override readonly name = 'KnowledgeMaintenanceScanError'\n readonly issue: KnowledgeMaintenanceScanIssue\n readonly path: string\n\n constructor(issue: KnowledgeMaintenanceScanIssue, path: string, detail: string) {\n super(`knowledge maintenance scan incomplete at ${path}: ${detail}`)\n this.issue = issue\n this.path = path\n }\n}\n\nfunction directoryEntries(dir: string, missingIsEmpty: boolean) {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch (error) {\n if (missingIsEmpty && (error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw new KnowledgeMaintenanceScanError(\n 'directory-read',\n dir,\n error instanceof Error ? error.message : String(error),\n )\n }\n}\n\n/** Strict counterpart to the serving scanner: every visible bundle entry must be inspectable. */\nexport function enumerateMaintenanceBundleDirs(knowledgeRoot: string): EnumeratedBundleDir[] {\n const memoryRoot = join(knowledgeRoot, 'memory')\n const products = directoryEntries(memoryRoot, true)\n .filter((entry) => (\n !entry.name.startsWith('.')\n && entry.name !== 'index'\n && entry.name !== 'queue'\n && entry.name !== 'receipts'\n ))\n .sort((left, right) => left.name.localeCompare(right.name))\n\n const found: EnumeratedBundleDir[] = []\n for (const product of products) {\n const productPath = join(memoryRoot, product.name)\n if (!product.isDirectory()) {\n throw new KnowledgeMaintenanceScanError(\n 'non-directory-entry',\n productPath,\n 'product entry is not a canonical directory',\n )\n }\n const bundlesRoot = join(productPath, 'bundles')\n const bundles = directoryEntries(bundlesRoot, true)\n .filter((entry) => !entry.name.startsWith('.'))\n .sort((left, right) => left.name.localeCompare(right.name))\n for (const bundle of bundles) {\n const dir = join(bundlesRoot, bundle.name)\n if (!bundle.isDirectory()) {\n throw new KnowledgeMaintenanceScanError(\n 'non-directory-entry',\n dir,\n 'bundle entry is not a canonical directory',\n )\n }\n found.push({ product: product.name, dir })\n }\n }\n return found\n}\n\nexport function loadMaintenanceBundle(entry: EnumeratedBundleDir): LoadedBundle {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded') {\n const detail = 'reason' in loaded ? `${loaded.kind}: ${loaded.reason}` : loaded.kind\n throw new KnowledgeMaintenanceScanError('bundle-load', entry.dir, detail)\n }\n const integrity = verifyBundleIntegrity(entry.dir)\n if (!integrity.ok) {\n throw new KnowledgeMaintenanceScanError(\n 'bundle-integrity',\n entry.dir,\n integrity.violations.join('; '),\n )\n }\n return loaded.bundle\n}\n","// The D-03 read face is the self-sufficiency oracle for committed bundles and Phase 375's\n// projection source. It strictly parses disk-owned contracts, verifies every committed digest,\n// and composes the schema fold; the LLM never supplies trust, counters, status, or validity.\n// Manifest identity and immutable semantics are re-derived across files rather than trusted.\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nimport {\n BundleOutcomeEventSchema,\n GateLineSchema,\n receiptDigestOf,\n VersionGuardError,\n canonicalJson,\n computeMutableStateHash,\n foldBundleTrust,\n guardArtifactsIndex,\n guardBundleManifest,\n guardBundleProvenance,\n guardBundleRelations,\n measurementBaselineSchema,\n measurementObservationSchema,\n parseRecordMarkdown,\n renderEmbeddingInput,\n verifyManifestIdentity,\n} from '@vostride/agent-qa-schema'\nimport type {\n ArtifactsIndex,\n GateLine,\n BundleManifest,\n BundleOutcomeEvent,\n BundleProvenance,\n BundleRelations,\n DerivedTrustState,\n MeasurementBaseline,\n MeasurementObservation,\n RecordFrontmatter,\n ScreenState,\n TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nexport interface LoadedBundle {\n frontmatter: RecordFrontmatter\n summary: string\n body: string\n manifest: BundleManifest\n provenance: BundleProvenance\n relations: BundleRelations\n events: BundleOutcomeEvent[]\n artifactsIndex: ArtifactsIndex\n screenStates: ScreenState[]\n}\n\nexport type LoadBundleOutcome =\n | { kind: 'loaded'; bundle: LoadedBundle }\n | { kind: 'not-found' }\n | { kind: 'incomplete' }\n | { kind: 'version-error'; reason: string }\n | { kind: 'invalid'; reason: string }\n\nexport interface IntegrityReport {\n ok: boolean\n violations: string[]\n}\n\nconst OUTCOMES_REL_PATH = 'evidence/outcomes.jsonl'\nexport const GATES_REL_PATH = 'evidence/gates.jsonl'\nconst MEASUREMENTS_REL_PATH = 'evidence/measurements.json'\nconst RELATIONS_REL_PATH = 'relations.json'\nconst ARTIFACTS_INDEX_REL_PATH = 'artifacts.index.json'\nconst SNAPSHOT_REL_PATH = /^evidence\\/screenstates\\/step-(\\d+)\\.json$/\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction snapshotPaths(manifest: BundleManifest): string[] {\n return Object.keys(manifest.contentHashes)\n .flatMap((relPath) => {\n const match = SNAPSHOT_REL_PATH.exec(relPath)\n return match === null ? [] : [{ relPath, stepIndex: Number(match[1]) }]\n })\n .sort((left, right) => left.stepIndex - right.stepIndex)\n .map(({ relPath }) => relPath)\n}\n\nfunction parseOutcomeLog(\n text: string,\n setCurrentFile: (file: string) => void,\n): BundleOutcomeEvent[] {\n if (text === '') return []\n if (!text.endsWith('\\n')) {\n throw new SyntaxError(`${OUTCOMES_REL_PATH} must end with a newline`)\n }\n\n return text\n .slice(0, -1)\n .split('\\n')\n .map((line, index) => {\n setCurrentFile(`${OUTCOMES_REL_PATH} line ${index + 1}`)\n return BundleOutcomeEventSchema.parse(JSON.parse(line))\n })\n}\n\nexport interface Measurements {\n baseline: MeasurementBaseline\n observations: MeasurementObservation[]\n}\n\n/**\n * Read D-03's baseline-first append stream. Absence is normal for non-measurement\n * bundles; any present malformed line fails loudly through the strict schemas.\n */\nexport function readMeasurements(bundleDir: string): Measurements | undefined {\n const file = join(bundleDir, MEASUREMENTS_REL_PATH)\n if (!existsSync(file)) return undefined\n\n const text = readFileSync(file, 'utf8')\n if (text === '' || !text.endsWith('\\n')) {\n throw new SyntaxError(`${MEASUREMENTS_REL_PATH} must contain a baseline and end with a newline`)\n }\n const lines = text.slice(0, -1).split('\\n')\n return {\n baseline: measurementBaselineSchema.parse(JSON.parse(lines[0]!)),\n observations: lines.slice(1).map((line) =>\n measurementObservationSchema.parse(JSON.parse(line)),\n ),\n }\n}\n\n/** 416 D-03/D-04: absence is normal; a present receipt must attest this bundle and its bytes. */\nexport function readGateReceipts(bundleDir: string, bundleId: string): GateLine[] | undefined {\n const file = join(bundleDir, GATES_REL_PATH)\n if (!existsSync(file)) return undefined\n const text = readFileSync(file, 'utf8')\n if (text === '' || !text.endsWith('\\n')) {\n throw new SyntaxError(`${GATES_REL_PATH} must contain a receipt and end with a newline`)\n }\n return text.slice(0, -1).split('\\n').map((line, index) => {\n // Parser diagnostics can quote receipt bytes or unrecognized keys. Only\n // fixed categories and the line number may cross the shared read boundary;\n // deliberately retain no raw parser error as a serialized cause.\n const label = `${GATES_REL_PATH} line ${index + 1}`\n let value: unknown\n try { value = JSON.parse(line) } catch {\n throw new SyntaxError(`${label}: invalid JSON`)\n }\n const result = GateLineSchema.safeParse(value)\n if (!result.success) throw new SyntaxError(`${label}: invalid receipt schema`)\n const parsed = result.data\n if (parsed.candidateId !== bundleId) {\n throw new SyntaxError(`${GATES_REL_PATH} line ${index + 1}: foreign candidateId`)\n }\n if (receiptDigestOf(parsed) !== parsed.receiptDigest) {\n throw new SyntaxError(`${GATES_REL_PATH} line ${index + 1}: receiptDigest mismatch`)\n }\n if (canonicalJson(parsed) !== line) {\n throw new SyntaxError(`${GATES_REL_PATH} line ${index + 1}: expected canonical JSON`)\n }\n return parsed\n })\n}\n\nexport function loadBundle(bundleDir: string): LoadBundleOutcome {\n if (basename(bundleDir).startsWith('.')) return { kind: 'not-found' }\n try {\n if (!existsSync(bundleDir) || !statSync(bundleDir).isDirectory()) {\n return { kind: 'not-found' }\n }\n } catch {\n return { kind: 'not-found' }\n }\n\n const manifestPath = join(bundleDir, 'manifest.json')\n if (!existsSync(manifestPath)) return { kind: 'not-found' }\n\n let currentFile = 'manifest.json'\n try {\n const manifest = guardBundleManifest(JSON.parse(readFileSync(manifestPath, 'utf8')))\n if (manifest.complete !== true) return { kind: 'incomplete' }\n\n currentFile = GATES_REL_PATH\n readGateReceipts(bundleDir, manifest.id)\n\n currentFile = 'record.md'\n const record = parseRecordMarkdown(readFileSync(join(bundleDir, currentFile), 'utf8'))\n\n currentFile = 'provenance.json'\n const provenance = guardBundleProvenance(\n JSON.parse(readFileSync(join(bundleDir, currentFile), 'utf8')),\n )\n\n currentFile = RELATIONS_REL_PATH\n const relations = guardBundleRelations(\n JSON.parse(readFileSync(join(bundleDir, currentFile), 'utf8')),\n )\n\n currentFile = ARTIFACTS_INDEX_REL_PATH\n const artifactsIndex = guardArtifactsIndex(\n JSON.parse(readFileSync(join(bundleDir, currentFile), 'utf8')),\n )\n\n currentFile = OUTCOMES_REL_PATH\n const events = parseOutcomeLog(\n readFileSync(join(bundleDir, currentFile), 'utf8'),\n (file) => {\n currentFile = file\n },\n )\n\n const screenStates = snapshotPaths(manifest).map((relPath) => {\n currentFile = relPath\n return JSON.parse(readFileSync(join(bundleDir, relPath), 'utf8')) as ScreenState\n })\n\n return {\n kind: 'loaded',\n bundle: {\n frontmatter: record.frontmatter,\n summary: record.summary,\n body: record.body,\n manifest,\n provenance,\n relations,\n events,\n artifactsIndex,\n screenStates,\n },\n }\n } catch (error) {\n const reason = `${currentFile}: ${errorMessage(error)}`\n return error instanceof VersionGuardError\n ? { kind: 'version-error', reason }\n : { kind: 'invalid', reason }\n }\n}\n\nfunction byteSha(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex')\n}\n\nfunction readDigest(bundleDir: string, relPath: string, violations: string[]): string | null {\n try {\n return byteSha(readFileSync(join(bundleDir, relPath)))\n } catch (error) {\n violations.push(`${relPath}: missing or unreadable (${errorMessage(error)})`)\n return null\n }\n}\n\nfunction verifyManifestBindings(\n bundleDir: string,\n manifest: BundleManifest,\n violations: string[],\n): void {\n try {\n const record = parseRecordMarkdown(readFileSync(join(bundleDir, 'record.md'), 'utf8'))\n const { frontmatter } = record\n\n if (frontmatter.id !== manifest.id) {\n violations.push('record.md: id mismatch with manifest.json')\n }\n if (frontmatter.kind !== manifest.identityCore.kind) {\n violations.push('record.md: kind mismatch with manifest.identityCore')\n }\n if ((frontmatter.subtype ?? null) !== manifest.identityCore.subtype) {\n violations.push('record.md: subtype mismatch with manifest.identityCore')\n }\n if (canonicalJson(frontmatter.scope) !== canonicalJson(manifest.identityCore.scope)) {\n violations.push('record.md: scope mismatch with manifest.identityCore')\n }\n\n const primaryAnchor = frontmatter.anchors[0]?.normalized\n if (\n primaryAnchor === undefined ||\n canonicalJson(primaryAnchor) !== canonicalJson(manifest.identityCore.primaryAnchor)\n ) {\n violations.push('record.md: primary anchor mismatch with manifest.identityCore')\n }\n if (frontmatter.createdAtOrdinal !== manifest.createdAtOrdinal) {\n violations.push('record.md: createdAtOrdinal mismatch with manifest.json')\n }\n if (frontmatter.originClass !== manifest.originClass) {\n violations.push('record.md: originClass mismatch with manifest.json')\n }\n if (frontmatter.evidenceIncomplete !== manifest.evidenceIncomplete) {\n violations.push('record.md: evidenceIncomplete mismatch with manifest.json')\n }\n\n const embeddingInput = renderEmbeddingInput({\n summary: record.summary,\n body: record.body,\n anchors: frontmatter.anchors.map(({ raw }) => raw),\n })\n if (embeddingInput !== manifest.embeddingInput) {\n violations.push('record.md: embeddingInput mismatch with manifest.json')\n }\n } catch (error) {\n violations.push(`record.md: immutable cross-checks unavailable (${errorMessage(error)})`)\n }\n\n try {\n const provenance = guardBundleProvenance(\n JSON.parse(readFileSync(join(bundleDir, 'provenance.json'), 'utf8')),\n )\n if (provenance.originClass !== manifest.originClass) {\n violations.push('provenance.json: originClass mismatch with manifest.json')\n }\n } catch (error) {\n violations.push(\n `provenance.json: immutable cross-checks unavailable (${errorMessage(error)})`,\n )\n }\n}\n\nexport function verifyBundleIntegrity(bundleDir: string): IntegrityReport {\n const violations: string[] = []\n let manifest: BundleManifest\n\n try {\n manifest = guardBundleManifest(\n JSON.parse(readFileSync(join(bundleDir, 'manifest.json'), 'utf8')),\n )\n } catch (error) {\n return {\n ok: false,\n violations: [`manifest.json: invalid or unreadable (${errorMessage(error)})`],\n }\n }\n\n for (const violation of verifyManifestIdentity(manifest)) {\n violations.push(`manifest.json: ${violation}`)\n }\n verifyManifestBindings(bundleDir, manifest, violations)\n\n if (manifest.complete !== true) {\n violations.push('manifest.json: bundle is incomplete')\n }\n\n const actualDigests: Record<string, string> = {}\n for (const [relPath, expectedDigest] of Object.entries(manifest.contentHashes).sort()) {\n const actualDigest = readDigest(bundleDir, relPath, violations)\n if (actualDigest === null) continue\n actualDigests[relPath] = actualDigest\n if (actualDigest !== expectedDigest) {\n violations.push(`${relPath}: content hash mismatch`)\n }\n }\n\n const measurements = actualDigests[MEASUREMENTS_REL_PATH]\n const gates = actualDigests[GATES_REL_PATH]\n const mutableStateHash = computeMutableStateHash({\n outcomes: actualDigests[OUTCOMES_REL_PATH] ?? null,\n relations: actualDigests[RELATIONS_REL_PATH] ?? null,\n artifactsIndex: actualDigests[ARTIFACTS_INDEX_REL_PATH] ?? null,\n ...(measurements === undefined ? {} : { measurements }),\n ...(gates === undefined ? {} : { gates }),\n })\n if (mutableStateHash !== manifest.mutableStateHash) {\n violations.push('manifest.json: mutableStateHash mismatch')\n }\n\n try {\n const artifactsIndex = guardArtifactsIndex(\n JSON.parse(readFileSync(join(bundleDir, ARTIFACTS_INDEX_REL_PATH), 'utf8')),\n )\n for (const artifact of artifactsIndex.artifacts) {\n const artifactPath = join(bundleDir, artifact.relPath)\n if (!existsSync(artifactPath)) {\n violations.push(`${artifact.relPath}: dangling artifact reference`)\n continue\n }\n let bytes: Buffer\n try {\n bytes = readFileSync(artifactPath)\n } catch (error) {\n violations.push(`${artifact.relPath}: unreadable artifact (${errorMessage(error)})`)\n continue\n }\n if (byteSha(bytes) !== artifact.sha) {\n violations.push(`${artifact.relPath}: artifact byte hash mismatch`)\n }\n if (bytes.byteLength !== artifact.bytes) {\n violations.push(`${artifact.relPath}: artifact byte length mismatch`)\n }\n }\n } catch (error) {\n violations.push(`${ARTIFACTS_INDEX_REL_PATH}: invalid or unreadable (${errorMessage(error)})`)\n }\n\n return { ok: violations.length === 0, violations }\n}\n\n/**\n * Phase 375 consumes this exact disk-derived projection seam; no model-produced scalar enters it.\n */\nexport function deriveBundleTrust(loaded: LoadedBundle, priors?: TrustPriorTable): DerivedTrustState {\n return foldBundleTrust(loaded.events, {\n originClass: loaded.provenance.originClass,\n evidenceIncomplete: loaded.manifest.evidenceIncomplete,\n createdAtOrdinal: loaded.manifest.createdAtOrdinal,\n }, priors)\n}\n","/** Durable observations of successful curation effects; never lifecycle or write authority. */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync,\n readdirSync, renameSync, rmSync, writeFileSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join } from 'node:path'\n\nimport { canonicalJson, sha256hex } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport { fsyncDirectory } from '../durable-fs.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport { withCurrentWriterAuthority, type CurrentWriterAuthority } from '../lease/writer-lease.js'\nimport { loadBundle, verifyBundleIntegrity } from '../bundle-read.js'\nimport { BundleTargetResolutionError, resolveProductQualifiedBundleDir } from '../bundle-scan.js'\n\nexport const COMPLETED_EFFECTS_SUBDIR = 'memory/queue/journal/completed-effects'\nconst digest = z.string().regex(/^[0-9a-f]{64}$/)\nconst deltaKind = z.enum(['Add', 'Confirm', 'Supersede', 'Deprecate', 'MintUnknown', 'Noop'])\n\n/** The expected canonical change is recorded before any bundle publication. */\nexport const curationEffectSchema = z.object({\n recordId: z.string().min(1),\n product: z.string().min(1),\n change: z.enum(['added', 'confirmed', 'superseded', 'deprecated']),\n atOrdinal: z.number().int().nonnegative(),\n evidenceToken: z.string().min(1),\n byRecordId: z.string().min(1).optional(),\n}).strict()\nexport type CurationEffect = z.infer<typeof curationEffectSchema>\n\nconst classificationFields = {\n sourceRunId: z.string().min(1),\n observationId: z.string().min(1),\n originalDeltaKind: deltaKind,\n appliedDeltaKind: deltaKind,\n disposition: z.enum(['apply', 'downgraded']),\n downgradeReason: z.string().min(1).optional(),\n}\n\nexport const curationObservationSchema = z.object({\n schemaVersion: z.literal(2),\n ...classificationFields,\n effects: z.array(curationEffectSchema),\n}).strict()\nexport type CurationObservation = z.infer<typeof curationObservationSchema>\n\nexport function effectIdentity(candidateId: string, effect: CurationEffect): string {\n return sha256hex(canonicalJson({\n candidateId: digest.parse(candidateId),\n ...curationEffectSchema.parse(effect),\n }))\n}\n\nexport const curationEffectReceiptSchema = z.object({\n schemaVersion: z.literal(2),\n candidateId: digest,\n effectId: digest,\n ...curationEffectSchema.shape,\n ...classificationFields,\n}).strict().refine((row) => row.effectId === sha256hex(canonicalJson({ candidateId: row.candidateId,\n recordId: row.recordId, product: row.product, change: row.change,\n atOrdinal: row.atOrdinal, evidenceToken: row.evidenceToken,\n ...(row.byRecordId === undefined ? {} : { byRecordId: row.byRecordId }),\n})), 'effect identity mismatch')\nexport type CurationEffectReceipt = z.infer<typeof curationEffectReceiptSchema>\n\nfunction receiptRoot(knowledgeRoot: string): string {\n if (!isAbsolute(knowledgeRoot)) throw new TypeError('knowledgeRoot must be absolute')\n return join(knowledgeRoot, COMPLETED_EFFECTS_SUBDIR)\n}\nfunction receiptName(row: CurationEffectReceipt): string {\n return `${row.candidateId}-${row.effectId}.json`\n}\nfunction parseReceipt(text: string, name: string): CurationEffectReceipt {\n // Do not expose parser values or untrusted keys in diagnostics.\n try {\n const row = curationEffectReceiptSchema.parse(JSON.parse(text))\n if (receiptName(row) === name && text === `${canonicalJson(row)}\\n`) return row\n } catch { /* fixed diagnostic below */ }\n throw new TypeError('invalid curation effect receipt')\n}\n\n/** Strict, deterministic, read-only; absence never creates the journal directory. */\nexport function listCurationEffectReceipts(knowledgeRoot: string): CurationEffectReceipt[] {\n const dir = receiptRoot(knowledgeRoot)\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n // OS metadata and editor files are noise, not receipts: the writer alone mints canonical names,\n // and a canonical-named file with malformed content still refuses in parseReceipt.\n return entries\n .filter((entry) => !entry.name.includes('.tmp-'))\n .filter((entry) => entry.isFile() && /^[0-9a-f]{64}-[0-9a-f]{64}\\.json$/.test(entry.name))\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((entry) => parseReceipt(readFileSync(join(dir, entry.name), 'utf8'), entry.name))\n}\n\nexport interface WriteCurationEffectReceiptOptions {\n knowledgeRoot: string\n authority: CurrentWriterAuthority\n receipt: CurationEffectReceipt\n}\n\n/** @internal Caller already holds the existing root writer authority section. */\nexport function writeCurationEffectReceiptWithinCurrentAuthority(\n opts: WriteCurationEffectReceiptOptions,\n): void {\n const parsed = curationEffectReceiptSchema.safeParse(opts.receipt)\n if (!parsed.success) throw new TypeError('invalid curation effect receipt')\n const row = parsed.data\n const file = join(receiptRoot(opts.knowledgeRoot), receiptName(row))\n assertWithinKnowledgeRoot(opts.knowledgeRoot, dirname(file))\n const text = `${canonicalJson(row)}\\n`\n if (existsSync(file)) {\n const existing = parseReceipt(readFileSync(file, 'utf8'), receiptName(row))\n if (canonicalJson(existing) !== canonicalJson(row)) {\n throw new TypeError('conflicting curation effect receipt')\n }\n return\n }\n mkdirSync(dirname(file), { recursive: true })\n fsyncDirectory(dirname(dirname(file)))\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n fsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\nexport function writeCurationEffectReceipt(opts: WriteCurationEffectReceiptOptions): void {\n withCurrentWriterAuthority(opts.knowledgeRoot, opts.authority, () =>\n writeCurationEffectReceiptWithinCurrentAuthority(opts),\n )\n}\n\n/** Check actual canonical bytes, never index presence or an intended effect alone. */\nexport function isCurationEffectCommitted(\n knowledgeRoot: string,\n candidateId: string,\n effect: CurationEffect,\n): boolean {\n let dir: string\n try {\n dir = resolveProductQualifiedBundleDir({\n knowledgeRoot, product: effect.product, recordId: effect.recordId,\n }).dir\n } catch (error) {\n if (error instanceof BundleTargetResolutionError && error.reason === 'not-found') return false\n throw error\n }\n const loaded = loadBundle(dir)\n if (loaded.kind !== 'loaded' || !verifyBundleIntegrity(dir).ok) return false\n const { bundle } = loaded\n if (effect.change === 'added' && (\n bundle.provenance.mode !== 'run-linked'\n || bundle.provenance.curationJobId !== candidateId\n || bundle.manifest.createdAtOrdinal !== effect.atOrdinal\n )) return false\n return bundle.events.some((event) =>\n event.curationJobId === candidateId\n && event.evidenceToken === effect.evidenceToken\n && event.buildOrdinal === effect.atOrdinal\n && event.type === (effect.change === 'added' ? 'confirmed' : effect.change)\n && (effect.byRecordId === undefined || (event.type === 'superseded' && event.byRecordId === effect.byRecordId)),\n )\n}\n\n/** Shared live/recovery row construction, independent of the recovering writer's epoch. */\nexport function receiptForEffect(\n candidateId: string,\n observation: CurationObservation,\n effect: CurationEffect,\n): CurationEffectReceipt {\n const { effects: _effects, ...classification } = observation\n return curationEffectReceiptSchema.parse({\n ...classification, candidateId, ...effect, effectId: effectIdentity(candidateId, effect),\n })\n}\n","import {\n closeSync,\n fsyncSync,\n openSync,\n readdirSync,\n renameSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\n\ninterface FsyncOperations {\n openSync(path: string, flags: string): number\n fsyncSync(fd: number): void\n closeSync(fd: number): void\n}\n\nconst FSYNC_OPERATIONS: FsyncOperations = { openSync, fsyncSync, closeSync }\n\n/** Hosts may reject directory handles with only these established portability errors. */\nconst UNSUPPORTED_DIRECTORY_FSYNC_CODES = new Set([\n 'EINVAL',\n 'EISDIR',\n 'EPERM',\n 'ENOTSUP',\n])\n\nfunction syncPath(path: string, operations: FsyncOperations): void {\n let fd: number | undefined\n try {\n fd = operations.openSync(path, 'r')\n operations.fsyncSync(fd)\n } finally {\n if (fd !== undefined) operations.closeSync(fd)\n }\n}\n\n/** Flush one regular file; every open, sync, and close failure remains fatal. */\nexport function fsyncFile(path: string): void {\n syncPath(path, FSYNC_OPERATIONS)\n}\n\n/** Flush one directory while tolerating only the queue's closed host-portability allowlist. */\nexport function fsyncDirectory(\n path: string,\n operations: FsyncOperations = FSYNC_OPERATIONS,\n): void {\n try {\n syncPath(path, operations)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === undefined || !UNSUPPORTED_DIRECTORY_FSYNC_CODES.has(code)) throw error\n }\n}\n\nfunction collectTree(\n root: string,\n files: string[],\n directoriesBottomUp: string[],\n): void {\n const entries = readdirSync(root, { withFileTypes: true }).sort((left, right) =>\n left.name.localeCompare(right.name),\n )\n for (const entry of entries) {\n const path = join(root, entry.name)\n if (entry.isFile()) {\n files.push(path)\n continue\n }\n if (entry.isDirectory()) {\n collectTree(path, files, directoriesBottomUp)\n continue\n }\n throw new TypeError(`fsyncTree supports only regular files and directories: ${path}`)\n }\n directoriesBottomUp.push(root)\n}\n\n/** Flush every regular file first, then every directory in deterministic bottom-up order. */\nexport function fsyncTree(root: string): void {\n const files: string[] = []\n const directoriesBottomUp: string[] = []\n collectTree(root, files, directoriesBottomUp)\n for (const file of files) fsyncFile(file)\n for (const directory of directoriesBottomUp) fsyncDirectory(directory)\n}\n\n/** Persist the source-parent entry, rename, then persist the destination-parent entry. */\nexport function durableRename(source: string, destination: string): void {\n fsyncDirectory(dirname(source))\n renameSync(source, destination)\n fsyncDirectory(dirname(destination))\n}\n","/**\n * Containment of knowledge-root writes (261003-lgd CR-01, generalised by 261003-mqc).\n *\n * The knowledge root is a git repository people share and pull, and a tracked symlink is checked\n * out even under an ignored directory, so `memory/`, `memory/queue/`, `memory/index/`, a product\n * directory or `policies/` can point anywhere. Every writer checks the directory it is about to\n * create, write, rename into or delete from before it touches it: each component of that\n * directory that already exists must resolve inside the knowledge root's own real path. A link\n * that stays inside the root is fine; one that leaves it, or resolves nowhere, is refused by name.\n * A component that does not exist yet is created by the writer as a real directory.\n *\n * What this does not close: a local process that swaps a component for a link between this check\n * and the write. The threat this answers is a link committed into the shared repository.\n */\nimport { lstatSync, realpathSync } from 'node:fs'\nimport { isAbsolute, join, relative, sep } from 'node:path'\n\nexport class KnowledgeRootContainmentError extends Error {\n override readonly name = 'KnowledgeRootContainmentError'\n readonly path: string\n readonly resolvedTo: string | undefined\n readonly knowledgeRoot: string\n\n constructor(path: string, resolvedTo: string | undefined, knowledgeRoot: string) {\n const where = resolvedTo === undefined\n ? 'is a link that resolves nowhere'\n : `resolves to ${resolvedTo}`\n super(\n `knowledge write refused: ${path} ${where}, outside the knowledge root `\n + `${knowledgeRoot}. Remove the link ${path} and retry.`,\n )\n this.path = path\n this.resolvedTo = resolvedTo\n this.knowledgeRoot = knowledgeRoot\n }\n}\n\nfunction errnoOf(error: unknown): string {\n return (error as NodeJS.ErrnoException).code ?? ''\n}\n\n/**\n * Refuse, before any write, a directory under the knowledge root that leaves it through a link.\n *\n * `directory` is the directory the caller writes in (or creates, renames into, or deletes from);\n * it must name a path under `knowledgeRoot`.\n */\nexport function assertWithinKnowledgeRoot(knowledgeRoot: string, directory: string): void {\n const rel = relative(knowledgeRoot, directory)\n if (rel === '') return\n if (rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) {\n throw new KnowledgeRootContainmentError(directory, directory, knowledgeRoot)\n }\n let realRoot: string\n try {\n realRoot = realpathSync(knowledgeRoot)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return\n throw error\n }\n let current = knowledgeRoot\n for (const part of rel.split(sep)) {\n current = join(current, part)\n try {\n lstatSync(current)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return\n throw error\n }\n let real: string | undefined\n try {\n real = realpathSync(current)\n } catch (error) {\n if (errnoOf(error) !== 'ENOENT' && errnoOf(error) !== 'ELOOP') throw error\n }\n if (real === undefined || (real !== realRoot && !real.startsWith(`${realRoot}${sep}`))) {\n throw new KnowledgeRootContainmentError(current, real, knowledgeRoot)\n }\n }\n}\n","/**\n * Epoch-fenced writer-role primitives for the gitignored knowledge root.\n *\n * This module never touches the curation queue. Plan 378-05 composes stale-holder requeue and\n * journal reconciliation around these lease decisions. Lease and epoch replacements are each\n * file-fsync'd and atomically renamed so a process kill can expose only old or new bytes.\n */\nimport { spawnSync } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants as fsConstants,\n existsSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmdirSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport type { Dirent, Stats } from 'node:fs'\nimport { basename, dirname, isAbsolute, join } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\nimport { threadId } from 'node:worker_threads'\n\nimport { z } from 'zod'\n\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\n\nexport const LEASE_FILE = '.lease'\nexport const EPOCH_FILE = '.epoch'\n\n/** Provisional writer-heartbeat TTL; retune from operational evidence without adding config. */\nexport const LEASE_HEARTBEAT_TTL_MS = 30_000\n\n/** Bounded mutation-lock takeover; retune from operational evidence without adding config. */\nexport const MUTATION_LOCK_TAKEOVER_MS = 45_000\n\n/** Authority-store filename is pinned; retune only through a data-migration plan. */\nexport const WRITER_AUTHORITY_DB_FILE = '.writer-authority.sqlite'\n\n/**\n * Provisional SQLite contention window; retune from operational evidence without adding config.\n *\n * The takeover deadline remains separate: this short timeout makes each failed write attempt\n * observable so the contender can apply the lease and verified-termination policy.\n */\nexport const MUTATION_LOCK_BUSY_TIMEOUT_MS = 2_000\n\n/**\n * Provisional acquisition deadline; retune from operational evidence without adding config.\n *\n * V-02: the retry loop's only exits used to be facts about the lease and the lock, and a state the\n * phase itself models — an epoch-invalid lease kept fresh by a renewal sidecar while a live owner\n * holds the authority transaction — satisfies none of them. A contender then spins on the caller's\n * main thread forever, which is what `agent-qa daemon` startup and `agent-qa knowledge drain` do.\n *\n * The bound is therefore anchored OUTSIDE that vocabulary: a monotonic clock reading taken at loop\n * entry plus an attempt counter, neither of which any on-disk value can influence. Deliberately\n * greater than MUTATION_LOCK_TAKEOVER_MS so a legitimate escalated takeover still fits inside the\n * budget and the deadline never pre-empts a reclaim that was going to succeed.\n */\nexport const ACQUIRE_WRITER_LEASE_DEADLINE_MS = 60_000\n\n/** Provisional cap on one `ps` incarnation fork; retune from operational evidence without config. */\nconst PROCESS_INCARNATION_PS_TIMEOUT_MS = 1_000\n\n/** Provisional floor for that cap — the bounded overshoot argued for at `psIncarnationCapMs`. */\nconst PROCESS_INCARNATION_PS_FLOOR_MS = 250\n\nconst PROCESS_INCARNATION_PS_PATH = '/bin/ps'\nconst PROCESS_INCARNATION_PS_ENV = Object.freeze({ LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' })\n\nconst MUTATION_LOCK_TERMINATION_POLL_MS = 10\nconst MUTATION_LOCK_TERMINATION_TIMEOUT_MS = 5_000\nconst MUTATION_LOCK_TERMINATION_WAIT = new Int32Array(\n new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),\n)\n\n/**\n * Transient guard serializing the beat's read-check-write with release's read-check-delete.\n *\n * A directory holding exactly one `owner-<token>` file, published whole by renaming a staged\n * directory into place. It lives under `memory/queue/`, which every scaffolded knowledge\n * `.gitignore` already ignores, so neither a guard in use nor one a crash left behind is ever a\n * commit-visible file in a user's knowledge repository (261002-lse follow-up; the user's\n * `.gitignore` is never rewritten, D-22).\n */\nexport const LEASE_GUARD_DIR = 'memory/queue/lease-guard'\n\nconst LEASE_GUARD_OWNER_PREFIX = 'owner-'\n\n/** A guard older than this cannot belong to a live section (each is one read and one write). */\nexport const LEASE_GUARD_STALE_MS = 10_000\n\n/**\n * How long a waiter keeps trying for the guard: deliberately LONGER than the residue bound.\n *\n * 2026-10-03 (quick 261003-lgd, Phase 432 review WR-11): the wait used to reuse the 2 s\n * MUTATION_LOCK_BUSY_TIMEOUT_MS, shorter than the 10 s bound. A guard left by a thread terminated\n * inside its section carries this live process's pid, so only the age bound can judge it residue,\n * and no waiter ever lived long enough to see it cross: every beat and release after a terminated\n * beat worker threw. The bound is kept and the wait made to outlast it, rather than the bound cut\n * below the wait, because a bound short enough to fit a 2 s wait could cut a live section short\n * under heavy load. Measured whole calls (stage, claim, section, release), 400 beats and 100\n * releases at load 4 on 12 cores: beat p50 12 ms, p99 15 ms, max 21 ms; release p50 9 ms, p99\n * 13 ms. Load 126-255 is about 10-21 times oversubscribed, so even a p99 stretched that far stays\n * well under the 10 s bound. Live contention still clears in milliseconds; only a residue costs a\n * waiter up to the bound, once.\n */\nexport const LEASE_GUARD_WAIT_MS = LEASE_GUARD_STALE_MS + 2_000\n\n/** A staging directory lives at most as long as its waiter, so one older than this is a leak. */\nconst LEASE_GUARD_STAGING_STALE_MS = LEASE_GUARD_WAIT_MS + LEASE_GUARD_STALE_MS\n\nconst LEASE_GUARD_STAGING_PREFIX = `${basename(LEASE_GUARD_DIR)}.tmp-`\n\nconst LEASE_GUARD_RESIDUE_PREFIX = `${basename(LEASE_GUARD_DIR)}.residue-`\n\nconst LEASE_GUARD_POLL_MS = 2\n\nconst writerLeaseSchema = z\n .object({\n leaseId: z.string().uuid(),\n pid: z.number().int().positive(),\n epoch: z.number().int().positive(),\n heartbeatAtMs: z.number().int().nonnegative(),\n })\n .strict()\n\nexport type WriterLease = z.infer<typeof writerLeaseSchema>\n\n/** What the contender could observe about the owner it gave up on; never an authority claim. */\nexport interface UnreclaimableMutationLockOwner {\n pid: number\n acquiredAtMs: number\n generationToken: string\n /** False when the row carries no incarnation, which is why escalation could never fire. */\n incarnationAttributed: boolean\n}\n\nexport type AcquireWriterLeaseOutcome =\n | { kind: 'held'; holder: WriterLease }\n | { kind: 'acquired'; leaseId: string; epoch: number; reclaimed?: WriterLease }\n | {\n kind: 'refused'\n reason: 'corrupt-epoch-state'\n error: CorruptEpochStateError\n }\n | {\n /**\n * CR-01 (round 5): the lease file's own sibling of `corrupt-epoch-state`.\n *\n * `code` is the raw errno so an operator sees EACCES rather than a contender that silently\n * spun to its deadline over an authority state nobody can evaluate; `error` keeps this arm\n * inside the union's stated contract that every refusal is rethrowable.\n */\n kind: 'refused'\n reason: 'unreadable-lease-state'\n code: string\n error: UnreadableWriterLeaseStateError\n }\n | {\n kind: 'refused'\n reason: 'mutation-lock-unreclaimable'\n /**\n * Both refusal arms carry a thrown-shaped `error` ON PURPOSE.\n *\n * Every caller of this union already renders `refused` as `[reason]: error.message` or\n * rethrows it, so a new arm that also carries one is surfaced by name at every entry point —\n * including any added later — without a list of call sites to keep in step. Naming the\n * refusal is the requirement; enumerating the callers who must name it is the failure mode\n * this phase keeps rediscovering.\n */\n error: WriterLeaseUnreclaimableError\n attempts: number\n waitedMs: number\n observedOwner?: UnreclaimableMutationLockOwner\n observedLease?: WriterLease\n }\n\nexport interface LeaseOperationOptions {\n knowledgeRoot: string\n leaseId: string\n}\n\n/** Test/chaos seam on the lease-file guard taken by `heartbeatLease` and `releaseLease`. */\nexport interface LeaseGuardHooks {\n /** Fires once, when the guard is first found held by a live section other than this caller's. */\n onLeaseGuardContended?: () => void\n /** Fires each time a guard has been judged residue, before this caller reclaims it. */\n beforeLeaseGuardReclaim?: () => void\n /** Fires inside a reclaim, after its first step and before its last. */\n duringLeaseGuardReclaim?: () => void\n}\n\nexport type HeartbeatLeaseOutcome =\n | { kind: 'heartbeated'; holder: WriterLease }\n | {\n kind: 'refused'\n reason:\n | 'lease-missing'\n | 'lease-malformed'\n /** CR-01: the lease exists and could not be opened — never write over what you cannot read. */\n | 'lease-unreadable'\n | 'lease-id-mismatch'\n | 'stale-epoch'\n | 'corrupt-epoch-state'\n holder?: WriterLease\n observedEpoch?: number\n error?: CorruptEpochStateError\n }\n\nexport type ReleaseLeaseOutcome =\n | { kind: 'released' }\n | {\n kind: 'refused'\n reason: 'lease-missing' | 'lease-malformed' | 'lease-unreadable' | 'lease-id-mismatch'\n holder?: WriterLease\n }\n\nexport interface AssertEpochCurrentOptions {\n knowledgeRoot: string\n epoch: number\n}\n\nexport type AssertEpochCurrentOutcome =\n | { current: true }\n | { current: false; observedEpoch: number }\n\n/** Exact writer identity carried by governed maintenance mutators. */\nexport interface WriterLeaseAuthority extends LeaseOperationOptions {\n epoch: number\n}\n\nexport type WriterAuthorityLostReason =\n | Extract<HeartbeatLeaseOutcome, { kind: 'refused' }>['reason']\n | 'epoch-mismatch-before-heartbeat'\n | 'epoch-mismatch-after-heartbeat'\n | 'mutation-lock-generation-lost'\n\n/** Fail-closed maintenance refusal with the holder and fresh disk epoch attached. */\nexport class WriterAuthorityLostError extends Error {\n override readonly name = 'WriterAuthorityLostError'\n readonly authority: WriterLeaseAuthority\n readonly reason: WriterAuthorityLostReason\n readonly observedEpoch: number\n\n constructor(\n authority: WriterLeaseAuthority,\n reason: WriterAuthorityLostReason,\n observedEpoch: number,\n ) {\n super(\n `writer authority lost (${reason}); held epoch ${authority.epoch}, observed ${observedEpoch}`,\n )\n this.authority = authority\n this.reason = reason\n this.observedEpoch = observedEpoch\n }\n}\n\nexport type CorruptEpochStateReason = 'unreadable' | 'malformed' | 'overflow'\n\n/** Fail-closed authority-state error; callers must never substitute epoch zero for this state. */\nexport class CorruptEpochStateError extends Error {\n override readonly name = 'CorruptEpochStateError'\n readonly path: string\n readonly reason: CorruptEpochStateReason\n readonly rawPreview: string\n\n constructor(path: string, reason: CorruptEpochStateReason, rawPreview: string) {\n super(`writer epoch state is corrupt (${reason}) at ${path}`)\n this.path = path\n this.reason = reason\n this.rawPreview = rawPreview\n }\n}\n\n/**\n * Fail-closed acquisition refusal after the deadline; carries why the wait could not end well.\n *\n * A contender that gives up is reporting a fact about the SYSTEM, not about itself, so the\n * diagnostics travel with the error: the owner it kept losing to, whether that owner was even\n * attributable (an unattributed row can never be escalated against, which is usually the whole\n * story), and the lease it kept reading. `agent-qa daemon` prints this and exits non-zero where it\n * previously hung with no output at all.\n */\nexport class WriterLeaseUnreclaimableError extends Error {\n override readonly name = 'WriterLeaseUnreclaimableError'\n readonly reason = 'mutation-lock-unreclaimable' as const\n readonly attempts: number\n readonly waitedMs: number\n readonly observedOwner?: UnreclaimableMutationLockOwner\n readonly observedLease?: WriterLease\n\n constructor(\n attempts: number,\n waitedMs: number,\n observedOwner?: UnreclaimableMutationLockOwner,\n observedLease?: WriterLease,\n ) {\n super(\n `writer lease acquisition refused (mutation-lock-unreclaimable) after ${attempts} `\n + `attempts over ${Math.round(waitedMs)}ms; `\n + (observedOwner === undefined\n ? 'no mutation-lock owner was readable'\n : `mutation lock held by pid ${observedOwner.pid} (generation `\n + `${observedOwner.generationToken}, incarnation `\n + `${observedOwner.incarnationAttributed ? 'attributed' : 'unattributed'})`)\n + '; '\n + (observedLease === undefined\n ? 'no parseable lease on disk'\n : `lease ${observedLease.leaseId} at epoch ${observedLease.epoch} held by pid `\n + `${observedLease.pid}`),\n )\n this.attempts = attempts\n this.waitedMs = waitedMs\n if (observedOwner !== undefined) this.observedOwner = observedOwner\n if (observedLease !== undefined) this.observedLease = observedLease\n }\n}\n\n/**\n * The lease file's sibling of `CorruptEpochStateError`, for a read that produced no throwable.\n *\n * `readFileSync` threw, but the value that reaches a consumer is a kinded outcome rather than an\n * exception, and `AcquireWriterLeaseOutcome`'s own contract is that EVERY refusal arm carries a\n * thrown-shaped `error` — three call sites rethrow or render it without knowing which arm they\n * hold (`drain.ts:842` among them). A refusal that carried only an errno string would have made\n * that contract a list of call sites to keep in step, which is the failure mode this module keeps\n * rediscovering. Deliberately not re-exported from the package index (IN-04): the refusal is fully\n * legible from `reason`, `code` and `error.message`.\n */\nexport class UnreadableWriterLeaseStateError extends Error {\n override readonly name = 'UnreadableWriterLeaseStateError'\n readonly path: string\n readonly code: string\n\n constructor(path: string, code: string) {\n super(`writer lease state is unreadable (${code}) at ${path}`)\n this.path = path\n this.code = code\n }\n}\n\n/**\n * The authority-file read verdict, and it has four values rather than three.\n *\n * Round-5 CR-01: `unreadable` is the sibling of the epoch read's\n * `CorruptEpochStateError(…, 'unreadable', …)`. A file that EXISTS and could not be opened is a\n * different fact from a file that is not there and from a file whose bytes were read and failed to\n * parse, and the previous three arms had nowhere to put it — so EACCES, EIO, EMFILE and ENFILE all\n * landed on `malformed`, which every consumer reads as \"nobody holds authority\". `code` carries\n * the errno so the refusal that follows can name the cause to an operator.\n */\nexport type ReadWriterLeaseOutcome =\n | { kind: 'absent' }\n | { kind: 'malformed' }\n | { kind: 'unreadable'; code: string }\n | { kind: 'parsed'; lease: WriterLease }\n\nfunction assertAbsoluteKnowledgeRoot(knowledgeRoot: string): void {\n if (!isAbsolute(knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n}\n\nfunction leasePath(knowledgeRoot: string): string {\n return join(knowledgeRoot, LEASE_FILE)\n}\n\nfunction epochPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, EPOCH_FILE)\n}\n\nfunction writerAuthorityDbPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, WRITER_AUTHORITY_DB_FILE)\n}\n\nfunction bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n code !== 'ENOENT' &&\n code !== 'EINVAL' &&\n code !== 'EISDIR' &&\n code !== 'EPERM' &&\n code !== 'ENOTSUP'\n ) {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\ninterface MutationLockOwner {\n pid: number\n acquiredAtMs: number\n generationToken: string\n /** OS-reported start-time token of the process that created this row; absent when unresolvable. */\n incarnation?: string\n}\n\n/**\n * Opaque process-incarnation token for one pid, anchored OUTSIDE any value this module writes.\n *\n * CR-04: a durable row's pid is not an identity. Once the recorded process dies, the kernel is\n * free to hand that number to a stranger, and every later decision keyed on the number alone\n * (above all `SIGKILL`) targets whoever holds it now. The one fact that distinguishes them is\n * assigned by the OS and cannot be forged from inside the store: when the process at that pid\n * started.\n *\n * Linux reads field 22 (`starttime`) of `/proc/<pid>/stat`, counted from the LAST `)` because the\n * `comm` field is parenthesised and may itself contain spaces and parentheses. Other POSIX hosts\n * read `/bin/ps -p <pid> -o lstart=` in the C locale and UTC, so every reader renders one start\n * time as one token. Windows has no equivalent builtin, so it resolves to `undefined` and every\n * incarnation check there fails closed.\n *\n * Returns `undefined` — never throws — whenever the pid cannot be attributed. `undefined` means\n * \"do not signal\", never \"safe to signal\".\n *\n * WR-04: `timeoutMs` bounds the POSIX arm's `ps` fork, which is the last wait beneath the\n * acquisition deadline that used to be able to outlive it — a wedged `ps` never returns, and this\n * resolution sits directly on the pre-signal path. A cap that expires resolves\n * through the SAME funnel every other failure uses (`undefined`), so a timed-out resolution is\n * unverifiable and therefore signal-ineligible. Callers with no budget of their own omit it.\n *\n * 386-32 consumes this same helper for the embedder-worker signal path, so both kill paths speak\n * one incarnation vocabulary.\n */\nexport function resolveProcessIncarnation(\n pid: number,\n timeoutMs?: number,\n psExecutable?: string,\n): string | undefined {\n if (!Number.isSafeInteger(pid) || pid <= 0) return undefined\n try {\n if (process.platform === 'win32') return undefined\n return process.platform === 'linux'\n ? resolveLinuxProcessIncarnation(pid)\n : resolvePosixProcessIncarnation(pid, timeoutMs, psExecutable)\n } catch {\n return undefined\n }\n}\n\nexport function incarnationFormat(token: string): string {\n const separator = token.indexOf(':')\n return separator < 0 ? '' : token.slice(0, separator)\n}\n\nfunction resolveLinuxProcessIncarnation(pid: number): string | undefined {\n let raw: string\n try {\n raw = readFileSync(`/proc/${pid}/stat`, 'utf8')\n } catch {\n return undefined\n }\n const commEnd = raw.lastIndexOf(')')\n if (commEnd < 0) return undefined\n // The first field after `comm` is `state` (field 3), so `starttime` (field 22) sits at index 19.\n const startTime = raw.slice(commEnd + 1).trim().split(/\\s+/)[19]\n return startTime !== undefined && /^\\d+$/.test(startTime)\n ? `proc-starttime:${startTime}`\n : undefined\n}\n\nfunction resolvePosixProcessIncarnation(\n pid: number,\n timeoutMs?: number,\n psExecutable: string = PROCESS_INCARNATION_PS_PATH,\n): string | undefined {\n // 2026-10-16 (442-14, GAP-D1): one rendering for every reader; the caller's PATH, TZ and\n // locale never reach ps.\n const observed = spawnSync(psExecutable, ['-p', String(pid), '-o', 'lstart='], {\n encoding: 'utf8',\n env: PROCESS_INCARNATION_PS_ENV,\n windowsHide: true,\n // `spawnSync` reads 0 as \"no timeout\", so an exhausted budget must never arrive here as 0.\n ...(timeoutMs === undefined ? {} : { timeout: Math.max(1, Math.ceil(timeoutMs)) }),\n })\n if (observed.error !== undefined || observed.status !== 0) return undefined\n const lstart = (observed.stdout ?? '').trim()\n return lstart === '' ? undefined : `ps-lstart-utc:${lstart}`\n}\n\nconst OWN_INCARNATION_UNRESOLVED = Symbol('own-incarnation-unresolved')\n/**\n * Only ever a RESOLVED token or the sentinel — `undefined` is deliberately not representable here.\n *\n * That is the whole of round-5 regression 2 in one type: storing `undefined` made \"the process\n * table did not answer this once\" indistinguishable from \"the process table answered, and the\n * answer is that there is nothing to say\", and the second reading is permanent.\n */\nlet ownIncarnation: string | typeof OWN_INCARNATION_UNRESOLVED = OWN_INCARNATION_UNRESOLVED\n\n/**\n * This process's own incarnation, resolved once SUCCESSFULLY and retried until then.\n *\n * A pid's start time is fixed for the life of the process, and this process is alive by\n * definition, so a resolved value cannot go stale. Memoising it keeps the per-claim cost off the\n * hot mutation path (the POSIX arm shells out to `ps`), and the accepting control in the corpus\n * asserts the hit path still forks exactly once per process.\n *\n * Two things this function's previous comment stated, both of which the call site contradicted:\n *\n * 1. It claimed the fork \"is not spending an escalation budget\". It is. The sole call site is\n * `withMutationLock`, which `acquireWriterLease` enters under `deadlineAtNs`, so a wedged\n * `ps` here spends the acquisition deadline exactly as the pre-signal fork does. WR-04's\n * clamp therefore applies to BOTH forks: `psIncarnationCapMs` degrades to the same flat\n * `PROCESS_INCARNATION_PS_TIMEOUT_MS` when the caller has no budget, so the heartbeat and\n * governed-mutation paths are unchanged, while a budgeted acquisition now caps this fork at\n * `clamp(remaining, FLOOR, TIMEOUT)` like every other wait beneath it.\n * 2. It memoised a MISS. One timed-out fork at startup then wrote `undefined` into the memo for\n * the life of the process, so every `mutation_lock` row that daemon ever wrote carried no\n * incarnation, `verifyMutationLockOwnerIdentity` answered `unverifiable` for all of them, and\n * no contender could ever escalate against it. Degraded liveness forever, from one fork.\n *\n * A miss is now a per-call answer: `undefined` is returned, the sentinel is left in place, and the\n * NEXT claim resolves again. There is no retry loop inside one call (that would spend the budget\n * this change exists to protect), no alternative resolver, and no default token — only a token the\n * OS assigned may replace the sentinel. The observer fires on every attempted resolution, because\n * a retry is a real `ps` fork and the cost being bounded has to stay countable.\n */\nfunction ownProcessIncarnation(escalation: MutationEscalationContext = {}): string | undefined {\n if (ownIncarnation !== OWN_INCARNATION_UNRESOLVED) return ownIncarnation\n const resolved = resolveProcessIncarnation(\n process.pid,\n psIncarnationCapMs(escalation),\n escalation.psExecutable,\n )\n escalation.onIncarnationResolved?.(process.pid)\n if (resolved === undefined) return undefined\n ownIncarnation = resolved\n return resolved\n}\n\nexport interface MutationLockOptions {\n /** Test/chaos seam after the claim is committed and before the held transaction begins. */\n afterMutationLockClaimed?: (generationToken: string) => void\n afterMutationLockAcquired?: () => void\n /** Test/chaos seam inside acquisition, after the epoch rewrite and before lease publication. */\n afterEpochRewrite?: () => void\n mutationLockTakeoverMs?: number\n /**\n * Test-only observation of every process-incarnation resolution the escalation path performs.\n *\n * Purely an observer, never a replacement: the production resolver still runs, so what a test\n * counts is what a daemon pays. It exists because the cost being bounded (a `ps` fork per\n * resolution, on the caller's main thread) is invisible to any assertion about outcomes.\n */\n onProcessIncarnationResolved?: (pid: number) => void\n // Test-only replacement for `/bin/ps`, for a wedged process table; production never sets it.\n psExecutable?: string\n}\n\n/**\n * The caller's remaining budget and observation hooks, threaded down the escalation path.\n *\n * W-05: the escalation is reached from `acquireWriterLease`, which owns a deadline; every wait it\n * performs is therefore spending someone else's time. Passing that fact down — rather than letting\n * each wait consult its own pinned constant — is what makes the deadline a real bound instead of\n * an approximate one. The relationship must hold structurally: the current constants happen to\n * satisfy it arithmetically (45 s takeover + 5 s termination < 60 s deadline), but an assertion\n * that rests on that coincidence would survive any retuning that broke it.\n */\ninterface MutationEscalationContext {\n /** Absolute monotonic instant past which no escalation wait may continue; absent = no budget. */\n readonly deadlineAtNs?: bigint\n readonly onIncarnationResolved?: (pid: number) => void\n readonly psExecutable?: string\n}\n\nexport interface AcquireWriterLeaseOptions extends MutationLockOptions {\n /**\n * Test/chaos seam for the pinned acquisition deadline; production never sets it.\n *\n * The same shape as `mutationLockTakeoverMs` and the heartbeat supervisor's `stopTimeoutMs`: a\n * real unreclaimable wait is 60 s, which no test can afford to sit through, and shortening the\n * window is the only way to reach the refusal branch (D-15 — a seam, never a config key).\n */\n acquireDeadlineMs?: number\n}\n\nexport interface CurrentWriterAuthority {\n leaseId: string\n epoch: number\n}\n\nexport interface CurrentWriterAuthorityHooks extends MutationLockOptions {\n /** Test/chaos seam after the lock-held epoch comparison and before mutation. */\n afterFinalAuthorityCompare?: () => void\n}\n\nclass MutationLockBusyError extends Error {\n override readonly name = 'MutationLockBusyError'\n readonly owner?: MutationLockOwner\n\n constructor(owner?: MutationLockOwner) {\n super('writer lease mutation lock is busy')\n this.owner = owner\n }\n}\n\nclass MutationLockGenerationLostError extends Error {\n override readonly name = 'MutationLockGenerationLostError'\n}\n\nclass LeaseGuardBusyError extends Error {\n override readonly name = 'LeaseGuardBusyError'\n}\n\nfunction mutationLockNowMs(): number {\n return new Date().getTime()\n}\n\n/**\n * Elapsed milliseconds from a `process.hrtime.bigint()` reading, immune to wall-clock movement.\n *\n * The acquisition deadline must not be extendable by anything the contended state can influence,\n * and a wall clock can be stepped backwards by NTP or by a test's own `Date.now` stub. This is the\n * external anchor the bound is measured against.\n */\nfunction monotonicElapsedMs(startedAtNs: bigint): number {\n return Number(process.hrtime.bigint() - startedAtNs) / 1e6\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ESRCH') return false\n if (code === 'EPERM') return true\n throw error\n }\n}\n\nfunction isSqliteBusy(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /database is (?:locked|busy)/i.test((error as Error).message)\n}\n\nfunction openWriterAuthorityDb(knowledgeRoot: string): DatabaseSync {\n mkdirSync(knowledgeRoot, { recursive: true })\n const db = new DatabaseSync(writerAuthorityDbPath(knowledgeRoot), {\n timeout: MUTATION_LOCK_BUSY_TIMEOUT_MS,\n })\n try {\n db.exec('PRAGMA journal_mode = WAL')\n db.exec(`PRAGMA busy_timeout = ${MUTATION_LOCK_BUSY_TIMEOUT_MS}`)\n db.exec(`\n CREATE TABLE IF NOT EXISTS mutation_lock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n generation_token TEXT NOT NULL,\n pid INTEGER NOT NULL CHECK (pid > 0),\n acquired_at_ms INTEGER NOT NULL CHECK (acquired_at_ms >= 0),\n incarnation TEXT\n ) STRICT\n `)\n upgradeMutationLockSchema(db)\n return db\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/**\n * Add the incarnation column to a store created before CR-04 shipped.\n *\n * The authority database is transient lock state, not knowledge, so this needs no data-migration\n * plan: an inherited row keeps a NULL incarnation and is therefore unattributed, which fails the\n * signal check closed. That is the correct reading — nothing on disk can say which process wrote\n * a row that predates the column.\n *\n * W-06: the check and the ALTER are not one transaction and cannot be, because the ALTER is itself\n * the schema change every reader would have to serialize behind. Two daemons starting against one\n * legacy store therefore both decide the column is missing, and the loser's ALTER — which blocks on\n * the winner's write lock and then re-prepares against the new schema — fails with\n * `duplicate column name`. `isSqliteBusy` does not match that message, so it used to escape as a\n * raw SqliteError and kill a starting daemon over a race whose OUTCOME WAS ALREADY CORRECT: the\n * column exists, which is the entire postcondition. Losing this race is success, so it is reported\n * as success. Every other error still propagates.\n */\nfunction upgradeMutationLockSchema(db: DatabaseSync): void {\n const columns = db.prepare(`\n SELECT name FROM pragma_table_info('mutation_lock')\n `).all() as { name: string }[]\n if (columns.some((column) => column.name === 'incarnation')) return\n try {\n db.exec('ALTER TABLE mutation_lock ADD COLUMN incarnation TEXT')\n } catch (error) {\n if (!isDuplicateMutationLockColumn(error)) throw error\n }\n}\n\n/** Classified by message beside `isMissingMutationLockTable`, which node:sqlite likewise untypes. */\nfunction isDuplicateMutationLockColumn(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /duplicate column name/i.test((error as Error).message)\n}\n\nfunction parseMutationLockOwner(value: unknown): MutationLockOwner | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const row = value as Record<string, unknown>\n return typeof row.pid === 'number'\n && Number.isSafeInteger(row.pid)\n && row.pid > 0\n && typeof row.acquired_at_ms === 'number'\n && Number.isSafeInteger(row.acquired_at_ms)\n && row.acquired_at_ms >= 0\n && typeof row.generation_token === 'string'\n && row.generation_token !== ''\n ? {\n pid: row.pid,\n acquiredAtMs: row.acquired_at_ms,\n generationToken: row.generation_token,\n // A row written before the incarnation column existed, or by a claimant that could not\n // resolve its own start time, is deliberately left unattributed rather than guessed at.\n ...(typeof row.incarnation === 'string' && row.incarnation !== ''\n ? { incarnation: row.incarnation }\n : {}),\n }\n : undefined\n}\n\nfunction readMutationLockOwner(db: DatabaseSync): MutationLockOwner | undefined {\n // `SELECT *` so a store that predates the incarnation column still reads through a read-only\n // connection, which has no opportunity to upgrade the schema.\n return parseMutationLockOwner(db.prepare(`\n SELECT * FROM mutation_lock WHERE id = 1\n `).get())\n}\n\n/**\n * Read the committed lock owner as a TYPED ABSENCE, never as a throw.\n *\n * Contract: every reason the owner cannot be read answers `undefined` — absent store, table not\n * created yet, and (WR-05) a store too busy to answer. Both callers already read `undefined` as\n * \"no attributable owner\": the busy-catch in `withMutationLock` puts it on a\n * `MutationLockBusyError`, and the acquisition deadline puts it on the typed\n * `mutation-lock-unreclaimable` refusal. A raw `SqliteError` escaping here therefore reached\n * neither of those promises — it propagated out of `acquireWriterLease` uncaught and killed a\n * starting daemon over contention, which is exactly the state the refusal exists to name.\n * Every other error still propagates.\n */\nfunction readCommittedMutationLockOwner(\n knowledgeRoot: string,\n): MutationLockOwner | undefined {\n try {\n const db = new DatabaseSync(writerAuthorityDbPath(knowledgeRoot), {\n readOnly: true,\n timeout: 0,\n })\n try {\n return readMutationLockOwner(db)\n } finally {\n db.close()\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n // A store file whose `mutation_lock` table does not exist yet reads exactly like an absent\n // store: nobody has committed a claim. This is reachable — `openWriterAuthorityDb` creates\n // the store file before `CREATE TABLE`, so a contender that loses the write lock in that\n // window arrives here and used to crash the daemon with a raw SQL logic error instead of\n // reporting contention.\n if (isMissingMutationLockTable(error)) return undefined\n // A store whose write lock is held by someone else answers nothing about who committed a\n // claim. `timeout: 0` is deliberate — this read is diagnostics on a path that has already\n // decided to refuse, so waiting on it would spend budget to learn a detail.\n if (isSqliteBusy(error)) return undefined\n throw error\n }\n}\n\nfunction isMissingMutationLockTable(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /no such table: mutation_lock/i.test((error as Error).message)\n}\n\nfunction mutationLockGenerationIsCurrent(\n db: DatabaseSync,\n generationToken: string,\n): boolean {\n return readMutationLockOwner(db)?.generationToken === generationToken\n}\n\nfunction compareAndSwapMutationLock(\n db: DatabaseSync,\n expected: MutationLockOwner,\n replacement: MutationLockOwner,\n): boolean {\n const result = db.prepare(`\n UPDATE mutation_lock\n SET generation_token = ?, pid = ?, acquired_at_ms = ?, incarnation = ?\n WHERE id = 1 AND generation_token = ?\n `).run(\n replacement.generationToken,\n replacement.pid,\n replacement.acquiredAtMs,\n replacement.incarnation ?? null,\n expected.generationToken,\n )\n return result.changes === 1\n}\n\n/** What the caller has left of its acquisition budget, or `undefined` when it declared none. */\nfunction remainingEscalationBudgetMs(escalation: MutationEscalationContext): number | undefined {\n if (escalation.deadlineAtNs === undefined) return undefined\n return Math.max(Number(escalation.deadlineAtNs - process.hrtime.bigint()) / 1e6, 0)\n}\n\n/**\n * Poll a signalled owner's disappearance, bounded by the CALLER'S remaining budget (W-05).\n *\n * The wait is synchronous on the caller's main thread, so its cost is charged to whoever asked for\n * the lock. Bounding it by MUTATION_LOCK_TERMINATION_TIMEOUT_MS alone let an acquisition overrun\n * its own deadline by that whole window, and the overrun was not hypothetical: SIGKILL cannot be\n * survived, but a killed child of a process that never returns to its event loop is never reaped,\n * so `kill(pid, 0)` keeps answering \"alive\" indefinitely. A daemon spinning synchronously on its\n * main thread is exactly the V-02 shape this phase reproduced, and its children are exactly those.\n *\n * The bound is therefore the MINIMUM of the pinned window and the time the caller has left. An\n * exhausted budget waits not at all and reports that the exit was NOT confirmed — a refusal to\n * reclaim, never a licence to CAS over an owner whose death was never observed. Elapsed time is\n * measured from `process.hrtime.bigint()` for the same reason the acquisition deadline is: a wall\n * clock can be stepped, and this loop's only exit must not be steppable.\n */\nfunction waitForVerifiedProcessExit(\n pid: number,\n escalation: MutationEscalationContext,\n): boolean {\n const startedAtNs = process.hrtime.bigint()\n const remainingMs = remainingEscalationBudgetMs(escalation)\n const boundMs = remainingMs === undefined\n ? MUTATION_LOCK_TERMINATION_TIMEOUT_MS\n : Math.min(MUTATION_LOCK_TERMINATION_TIMEOUT_MS, remainingMs)\n while (processIsAlive(pid)) {\n if (monotonicElapsedMs(startedAtNs) >= boundMs) return false\n Atomics.wait(\n MUTATION_LOCK_TERMINATION_WAIT,\n 0,\n 0,\n MUTATION_LOCK_TERMINATION_POLL_MS,\n )\n }\n return true\n}\n\ntype MutationLockOwnerIdentity = 'match' | 'mismatch' | 'unverifiable'\n\n/**\n * The `ps` fork's share of the caller's remaining budget (WR-04).\n *\n * The caller's remainder is the ceiling, which is what stops one fork from spending a deadline it\n * does not own. The FLOOR is the part that had to be argued for, because it is the one place this\n * cap can overshoot: an acquisition whose busy-timeout already consumed the whole deadline arrives\n * here with nothing left, and a zero-length cap would mean the identity of a genuinely stale owner\n * can never be re-read at all — turning \"the wait is budgeted\" (W-05) into \"the verified kill is\n * cancelled\", which is a different decision and one 386-40 pinned in the other direction.\n *\n * So the fork always gets one short, PINNED allowance: the overshoot is bounded by that constant\n * rather than by however long a wedged `ps` feels like taking, which is the whole subject of WR-04.\n * A zero-length cap would also be worse than useless mechanically — `spawnSync` reads 0 as \"no\n * timeout\" and would UNBOUND the fork entirely.\n *\n * What the floor does NOT do is buy permission: an expired cap still answers `undefined`, which\n * still answers `unverifiable`, which is still a refusal to signal. No default token, no retry.\n */\nfunction psIncarnationCapMs(escalation: MutationEscalationContext): number {\n const remainingMs = remainingEscalationBudgetMs(escalation)\n return Math.max(PROCESS_INCARNATION_PS_FLOOR_MS, Math.min(\n PROCESS_INCARNATION_PS_TIMEOUT_MS,\n remainingMs ?? PROCESS_INCARNATION_PS_TIMEOUT_MS,\n ))\n}\n\n/**\n * Compare the row's recorded incarnation against the pid's CURRENT occupant.\n *\n * An unattributed row (legacy bytes, or a claimant that could not resolve its own start time) and\n * an unresolvable pid both answer `unverifiable`, which is a refusal to signal — never a licence.\n * WR-04: a pid the process table will not report on INSIDE the caller's budget joins that second\n * class rather than extending the deadline, because the resolution sits on the pre-signal path.\n */\nfunction verifyMutationLockOwnerIdentity(\n owner: MutationLockOwner,\n escalation: MutationEscalationContext,\n): MutationLockOwnerIdentity {\n if (owner.incarnation === undefined) return 'unverifiable'\n const occupant = resolveProcessIncarnation(\n owner.pid,\n psIncarnationCapMs(escalation),\n escalation.psExecutable,\n )\n escalation.onIncarnationResolved?.(owner.pid)\n if (occupant === undefined) return 'unverifiable'\n if (incarnationFormat(occupant) !== incarnationFormat(owner.incarnation)) return 'unverifiable'\n return occupant === owner.incarnation ? 'match' : 'mismatch'\n}\n\n/**\n * CR-04: the generation token authenticates the ROW, not the process now occupying its pid.\n *\n * The pid's current incarnation is therefore re-resolved immediately before the signal, and the\n * three answers are genuinely different outcomes:\n *\n * match the process that created this row is still there — SIGKILL and confirm ESRCH,\n * exactly the Plan 20 verified-termination semantics.\n * mismatch the recorded process is gone and a stranger inherited its pid. A reused pid is\n * EVIDENCE OF DEATH, not a target: report success so the caller's generation\n * re-read and CAS reclaim the row with no signal delivered at all.\n * unverifiable fail closed. Refusing escalation can wedge a contender until the occupant really\n * exits (T-386-31-02); signalling an unattributable pid is local arbitrary-process\n * termination. Only one of those is recoverable.\n */\nfunction terminateExactMutationLockOwner(\n owner: MutationLockOwner,\n escalation: MutationEscalationContext,\n): boolean {\n if (owner.pid === process.pid) return false\n const identity = verifyMutationLockOwnerIdentity(owner, escalation)\n if (identity === 'unverifiable') return false\n if (identity === 'mismatch') return true\n try {\n process.kill(owner.pid, 'SIGKILL')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ESRCH') {\n if (code === 'EPERM') return false\n throw error\n }\n }\n return waitForVerifiedProcessExit(owner.pid, escalation)\n}\n\n/**\n * Escalation ends in SIGKILL, so this consumer names `unknown` AND `unreadable` as refusals.\n *\n * A wrong kill is unrecoverable; a contender that declines to kill is not. `reclaimable` is the\n * only verdict that permits, which means a live holder is escalated against exactly when its lease\n * has genuinely aged out or names a superseded epoch — never because the epoch could not be read,\n * and never because the lease could not be read.\n *\n * CR-01 (round 5): the read arms are an exhaustive ladder rather than a `!== 'parsed'`\n * short-circuit. That short-circuit was a fourth conjunct sitting one line ABOVE the derivation\n * the same round moved the third conjunct INTO, and it permitted the kill for the one input class\n * the derivation exists to refuse. `absent` and `malformed` still permit — a lease file that is\n * missing, or whose bytes were read and are not a lease, is recovery input — but a file that\n * exists and could not be opened is no evidence at all.\n *\n * This veto is the LAST lease guard on the governed-mutation contention path: a contender that\n * enters through `withCurrentWriterAuthority` (a fenced-out writer retrying its commit) claims the\n * mutation lock before it reads any lease, so `acquireWriterLease`'s pre-check never runs for it.\n * That path is what makes this gate reachable, and it is pinned by a corpus case that reddens when\n * the veto is removed (WINDOWS #46).\n */\nfunction leasePermitsEscalation(knowledgeRoot: string, owner: MutationLockOwner): boolean {\n if (!processIsAlive(owner.pid)) return true\n const lease = readWriterLease(knowledgeRoot)\n switch (lease.kind) {\n case 'absent':\n case 'malformed':\n return true\n case 'unreadable':\n return false\n case 'parsed':\n return deriveWriterLeaseFreshness(\n knowledgeRoot,\n lease.lease,\n mutationLockNowMs(),\n ).kind === 'reclaimable'\n }\n}\n\nfunction tryEscalatedMutationLockTakeover(\n db: DatabaseSync,\n knowledgeRoot: string,\n expected: MutationLockOwner,\n replacement: MutationLockOwner,\n takeoverMs: number,\n escalation: MutationEscalationContext,\n): boolean {\n if (mutationLockNowMs() - expected.acquiredAtMs < takeoverMs) return false\n if (!leasePermitsEscalation(knowledgeRoot, expected)) return false\n if (\n processIsAlive(expected.pid)\n && !terminateExactMutationLockOwner(expected, escalation)\n ) {\n return false\n }\n\n const observedAfterTermination = readMutationLockOwner(db)\n if (observedAfterTermination?.generationToken !== expected.generationToken) return false\n try {\n return compareAndSwapMutationLock(db, expected, replacement)\n } catch (error) {\n // A mismatched incarnation reclaims without killing anything, so the write lock can still be\n // held by whoever made the store busy. That is an ordinary retry, not a failure to surface.\n if (isSqliteBusy(error)) return false\n throw error\n }\n}\n\nfunction claimMutationLock(\n db: DatabaseSync,\n knowledgeRoot: string,\n owner: MutationLockOwner,\n takeoverMs: number,\n escalation: MutationEscalationContext,\n): void {\n try {\n const inserted = db.prepare(`\n INSERT INTO mutation_lock (id, generation_token, pid, acquired_at_ms, incarnation)\n VALUES (1, ?, ?, ?, ?)\n ON CONFLICT(id) DO NOTHING\n `).run(\n owner.generationToken,\n owner.pid,\n owner.acquiredAtMs,\n owner.incarnation ?? null,\n )\n if (inserted.changes === 1) return\n } catch (error) {\n if (!isSqliteBusy(error)) throw error\n const current = readMutationLockOwner(db)\n if (\n current !== undefined\n && tryEscalatedMutationLockTakeover(\n db,\n knowledgeRoot,\n current,\n owner,\n takeoverMs,\n escalation,\n )\n ) {\n return\n }\n throw new MutationLockBusyError(current)\n }\n\n const current = readMutationLockOwner(db)\n if (current === undefined) {\n throw new MutationLockBusyError()\n }\n\n const ownerIsDead = !processIsAlive(current.pid)\n const ownerPastDeadline =\n mutationLockNowMs() - current.acquiredAtMs >= takeoverMs\n if (!ownerIsDead && !ownerPastDeadline) {\n throw new MutationLockBusyError(current)\n }\n\n try {\n if (compareAndSwapMutationLock(db, current, owner)) return\n } catch (error) {\n if (!isSqliteBusy(error)) throw error\n if (\n tryEscalatedMutationLockTakeover(\n db,\n knowledgeRoot,\n current,\n owner,\n takeoverMs,\n escalation,\n )\n ) {\n return\n }\n throw new MutationLockBusyError(current)\n }\n throw new MutationLockBusyError(readMutationLockOwner(db))\n}\n\nfunction releaseMutationLock(db: DatabaseSync, generationToken: string): void {\n db.prepare(`\n DELETE FROM mutation_lock\n WHERE id = 1 AND generation_token = ?\n `).run(generationToken)\n}\n\nfunction withMutationLock<T>(\n knowledgeRoot: string,\n mutate: (generationToken: string, db: DatabaseSync) => T,\n options: MutationLockOptions = {},\n /**\n * The caller's acquisition deadline, when it has one.\n *\n * Only `acquireWriterLease` does: a heartbeat or a governed mutation is not racing a bound, so\n * omitting it leaves those paths on the pinned termination window exactly as before.\n */\n deadlineAtNs?: bigint,\n): T {\n const escalation: MutationEscalationContext = {\n ...(deadlineAtNs === undefined ? {} : { deadlineAtNs }),\n ...(options.onProcessIncarnationResolved === undefined\n ? {}\n : { onIncarnationResolved: options.onProcessIncarnationResolved }),\n ...(options.psExecutable === undefined ? {} : { psExecutable: options.psExecutable }),\n }\n let db: DatabaseSync\n try {\n db = openWriterAuthorityDb(knowledgeRoot)\n } catch (error) {\n if (isSqliteBusy(error)) {\n throw new MutationLockBusyError(\n readCommittedMutationLockOwner(knowledgeRoot),\n )\n }\n throw error\n }\n const claimantIncarnation = ownProcessIncarnation(escalation)\n const owner: MutationLockOwner = {\n pid: process.pid,\n acquiredAtMs: mutationLockNowMs(),\n generationToken: randomUUID(),\n // A claimant that cannot prove its own incarnation records none, accepting that its row may\n // then only ever be reclaimed after it really dies. Never a fabricated token.\n ...(claimantIncarnation === undefined ? {} : { incarnation: claimantIncarnation }),\n }\n const takeoverMs = options.mutationLockTakeoverMs ?? MUTATION_LOCK_TAKEOVER_MS\n let claimed = false\n let transactionOpen = false\n try {\n claimMutationLock(db, knowledgeRoot, owner, takeoverMs, escalation)\n claimed = true\n options.afterMutationLockClaimed?.(owner.generationToken)\n try {\n db.exec('BEGIN IMMEDIATE')\n transactionOpen = true\n } catch (error) {\n if (isSqliteBusy(error)) throw new MutationLockBusyError(readMutationLockOwner(db))\n throw error\n }\n\n if (!mutationLockGenerationIsCurrent(db, owner.generationToken)) {\n throw new MutationLockGenerationLostError()\n }\n options.afterMutationLockAcquired?.()\n const result = mutate(owner.generationToken, db)\n db.exec('COMMIT')\n transactionOpen = false\n return result\n } finally {\n if (transactionOpen) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // The original failure is authoritative.\n }\n }\n if (claimed) {\n try {\n releaseMutationLock(db, owner.generationToken)\n } catch {\n // A crashed/contended cleanup leaves a CAS-recoverable row.\n }\n }\n db.close()\n }\n}\n\nfunction sweepStagedEpochsBefore(knowledgeRoot: string, epoch: number): void {\n const memoryRoot = join(knowledgeRoot, 'memory')\n let products: Dirent<string>[]\n try {\n products = readdirSync(memoryRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n\n for (const product of products) {\n if (!product.isDirectory()) continue\n const bundlesDir = join(memoryRoot, product.name, 'bundles')\n const stagingRoot = join(bundlesDir, '.staging')\n let staged: Dirent<string>[]\n try {\n staged = readdirSync(stagingRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue\n throw error\n }\n for (const entry of staged) {\n if (!entry.isDirectory()) continue\n const match = /^\\.staged-epoch-(\\d+)-[A-Za-z0-9._-]+$/.exec(entry.name)\n if (match === null) continue\n const stagedEpoch = Number(match[1])\n if (!Number.isSafeInteger(stagedEpoch) || stagedEpoch >= epoch) continue\n rmSync(join(stagingRoot, entry.name), { recursive: true, force: true })\n }\n if (existsSync(stagingRoot)) bestEffortFsyncDirectory(stagingRoot)\n try {\n rmdirSync(stagingRoot)\n bestEffortFsyncDirectory(bundlesDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n }\n}\n\nfunction atomicRewrite(file: string, text: string): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n bestEffortFsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\nconst leaseGuardOwnerSchema = z\n .object({\n pid: z.number().int().positive(),\n threadId: z.number().int().nonnegative(),\n token: z.string().uuid(),\n claimedAtNs: z.string().regex(/^[0-9]+$/),\n })\n .strict()\n\ntype LeaseGuardOwner = z.infer<typeof leaseGuardOwnerSchema>\n\ntype ObservedLeaseGuard =\n | { kind: 'vacant' }\n | { kind: 'held'; ownerFile: string; owner?: LeaseGuardOwner }\n\nfunction ignoreErrno(run: () => void, codes: readonly string[]): void {\n try {\n run()\n } catch (error) {\n if (!codes.includes((error as NodeJS.ErrnoException).code ?? '')) throw error\n }\n}\n\nfunction errnoOf(error: unknown): string {\n return (error as NodeJS.ErrnoException).code ?? ''\n}\n\n/** `lstat` that answers `undefined` for a missing entry; it never follows a link. */\nfunction lstatOrAbsent(path: string): Stats | undefined {\n try {\n return lstatSync(path)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return undefined\n throw error\n }\n}\n\n/** Move a directory nothing can attribute aside, whole: its entries are never ours to delete. */\nfunction moveLeaseGuardAside(guard: string): void {\n const aside = join(dirname(guard), `${LEASE_GUARD_RESIDUE_PREFIX}${randomUUID()}`)\n ignoreErrno(() => renameSync(guard, aside), ['ENOENT'])\n}\n\n/** Read an owner file without following a link or blocking on a special file. */\nfunction readLeaseGuardOwner(path: string, name: string): LeaseGuardOwner | undefined {\n const fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK)\n let raw: string\n try {\n raw = readFileSync(fd, 'utf8')\n } finally {\n closeSync(fd)\n }\n try {\n const parsed = leaseGuardOwnerSchema.safeParse(JSON.parse(raw))\n return parsed.success && `${LEASE_GUARD_OWNER_PREFIX}${parsed.data.token}` === name\n ? parsed.data\n : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe the guard path without ever reaching through it (CR-01).\n *\n * A guard is only ever a real directory holding one regular `owner-<token>` file. Anything else at\n * the path, a symlink wherever it points or a plain file, is removed as an entry: `unlink` removes\n * a link, never its target. A directory nothing can attribute (entries but no owner, or an owner\n * that is not a regular file) is moved aside whole and its entries are never unlinked; no live\n * guard can look like that, because a guard is only published by renaming a staged directory onto\n * an empty one.\n */\nfunction observeLeaseGuard(guard: string): ObservedLeaseGuard {\n const stat = lstatOrAbsent(guard)\n if (stat === undefined) return { kind: 'vacant' }\n if (!stat.isDirectory()) {\n ignoreErrno(() => unlinkSync(guard), ['ENOENT', 'EISDIR', 'EPERM'])\n return { kind: 'vacant' }\n }\n let names: string[]\n try {\n names = readdirSync(guard)\n } catch (error) {\n // Replaced between the two calls: the next observation judges whatever is there now.\n if (errnoOf(error) === 'ENOENT' || errnoOf(error) === 'ENOTDIR') return { kind: 'vacant' }\n throw error\n }\n if (names.length === 0) {\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n return { kind: 'vacant' }\n }\n const ownerFile = names.filter((name) => name.startsWith(LEASE_GUARD_OWNER_PREFIX)).sort()[0]\n const ownerStat = ownerFile === undefined ? undefined : lstatOrAbsent(join(guard, ownerFile))\n if (ownerFile === undefined || (ownerStat !== undefined && !ownerStat.isFile())) {\n moveLeaseGuardAside(guard)\n return { kind: 'vacant' }\n }\n if (ownerStat === undefined) return { kind: 'vacant' }\n let owner: LeaseGuardOwner | undefined\n try {\n owner = readLeaseGuardOwner(join(guard, ownerFile), ownerFile)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return { kind: 'vacant' }\n if (errnoOf(error) === 'ELOOP') {\n moveLeaseGuardAside(guard)\n return { kind: 'vacant' }\n }\n throw error\n }\n return owner === undefined ? { kind: 'held', ownerFile } : { kind: 'held', ownerFile, owner }\n}\n\n/**\n * Sweep staging directories a holder leaked by dying between staging and claiming (IN-24).\n *\n * A staging directory is exactly one owner file in a real directory, and lives no longer than its\n * waiter, so one is swept only when its owner is residue under that longer bound (or its process\n * is gone). The sweep is the same compare-and-swap as a reclaim: the owner's own name, then\n * `rmdir`. A link, or a directory holding anything else, is left exactly as it is. Housekeeping\n * only: nothing here may fail the section.\n */\nfunction sweepLeakedLeaseGuardStaging(parent: string, ownStaged: string): void {\n let names: string[]\n try {\n names = readdirSync(parent)\n } catch {\n return\n }\n for (const name of names) {\n if (!name.startsWith(LEASE_GUARD_STAGING_PREFIX)) continue\n const dir = join(parent, name)\n if (dir === ownStaged) continue\n try {\n sweepLeakedStagingDirectory(dir)\n } catch {\n // Left for a later sweep.\n }\n }\n}\n\nfunction sweepLeakedStagingDirectory(dir: string): void {\n const stat = lstatOrAbsent(dir)\n if (stat === undefined || !stat.isDirectory()) return\n const entries = readdirSync(dir)\n // Wall clock, not `Date.now()`: the beat's only `Date.now()` is a seam the race cells use.\n const nowMs = mutationLockNowMs()\n if (entries.length === 0) {\n // Staged, not yet written: judged by its own age only.\n if (nowMs - stat.mtimeMs >= LEASE_GUARD_STAGING_STALE_MS) {\n ignoreErrno(() => rmdirSync(dir), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n }\n return\n }\n const ownerFile = entries[0]!\n if (entries.length !== 1 || !ownerFile.startsWith(LEASE_GUARD_OWNER_PREFIX)) return\n const ownerPath = join(dir, ownerFile)\n const ownerStat = lstatOrAbsent(ownerPath)\n if (ownerStat === undefined || !ownerStat.isFile()) return\n const owner = readLeaseGuardOwner(ownerPath, ownerFile)\n // An owner being written can read as nothing yet, so unattributable bytes wait out the bound.\n const residue = owner === undefined\n ? nowMs - ownerStat.mtimeMs >= LEASE_GUARD_STAGING_STALE_MS\n : leaseGuardOwnerIsResidue(owner, LEASE_GUARD_STAGING_STALE_MS)\n if (!residue) return\n ignoreErrno(() => unlinkSync(ownerPath), ['ENOENT'])\n ignoreErrno(() => rmdirSync(dir), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n}\n\n/**\n * True when no live section can still be behind the guard.\n *\n * Unattributable owner bytes are residue. So is a claim from a dead process, one older than the\n * bound (a thread terminated inside its section leaves its live process's pid behind), and one\n * stamped ahead of this monotonic clock, which can only come from a previous boot.\n */\nfunction leaseGuardIsResidue(owner: LeaseGuardOwner | undefined): boolean {\n if (owner === undefined) return true\n return leaseGuardOwnerIsResidue(owner, LEASE_GUARD_STALE_MS)\n}\n\nfunction leaseGuardOwnerIsResidue(owner: LeaseGuardOwner, staleMs: number): boolean {\n const ageMs = Number(process.hrtime.bigint() - BigInt(owner.claimedAtNs)) / 1e6\n if (ageMs < 0 || ageMs >= staleMs) return true\n return owner.pid !== process.pid && !processIsAlive(owner.pid)\n}\n\n/**\n * Reclaim a stale guard by compare-and-swap, never by moving whatever sits at the path.\n *\n * The compare is the owner file's NAME: only the stale owner's own file is unlinked. The swap is\n * `rmdir`, which removes the directory only if that left it empty. A live guard is a different\n * owner name inside a non-empty directory, so a second reclaimer of the same stale owner, however\n * late, removes nothing of it (261002-lse follow-up).\n */\nfunction reclaimLeaseGuard(guard: string, ownerFile: string, hooks: LeaseGuardHooks): void {\n ignoreErrno(() => unlinkSync(join(guard, ownerFile)), ['ENOENT'])\n hooks.duringLeaseGuardReclaim?.()\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n}\n\nfunction releaseLeaseGuard(guard: string, ownerFile: string): void {\n try {\n unlinkSync(join(guard, ownerFile))\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n } catch {\n // Whatever is left is residue, and the age bound reclaims it.\n }\n}\n\n/**\n * Run one lease-file section under the guard shared by `heartbeatLease` and `releaseLease`.\n *\n * Claiming is renaming a staged directory onto the guard path, which succeeds only where no guard\n * or an empty one sits. Governed mutations and acquisitions never take the guard, so a mutation of\n * any length cannot starve the beat (CR-03 stands) and a beat cannot block an acquisition. Waiting\n * is bounded by LEASE_GUARD_WAIT_MS, which outlasts the residue bound so that a guard left by a\n * terminated thread of this process is always reclaimed in time (WR-11); a guard held by an\n * enclosing section on this very thread can never be let go by waiting, so that claim fails at\n * once. Nothing here reaches through a link or out of the knowledge root (CR-01).\n */\nfunction withLeaseGuard<T>(\n knowledgeRoot: string,\n section: () => T,\n hooks: LeaseGuardHooks = {},\n): T {\n const guard = join(knowledgeRoot, LEASE_GUARD_DIR)\n // CR-01: nothing is created, claimed or removed through a chain that leaves the root.\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(guard))\n const claimedAtNs = process.hrtime.bigint()\n const token = randomUUID()\n const ownerFile = `${LEASE_GUARD_OWNER_PREFIX}${token}`\n const raw = `${JSON.stringify({\n pid: process.pid,\n threadId,\n token,\n claimedAtNs: String(claimedAtNs),\n })}\\n`\n const parent = dirname(guard)\n // `memory/queue/` and `memory/` are created only when absent, and removed again only by `rmdir`\n // (so only while empty), keeping a lease round-trip from leaving anything under `memory/`.\n const createdAncestors = [parent, dirname(parent)].filter((dir) => !existsSync(dir))\n const staged = `${guard}.tmp-${randomUUID()}`\n let contended = false\n try {\n try {\n while (true) {\n mkdirSync(parent, { recursive: true })\n try {\n mkdirSync(staged)\n break\n } catch (error) {\n // Another section's cleanup removed the empty parent between the two calls.\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n }\n writeFileSync(join(staged, ownerFile), raw, { encoding: 'utf8', flag: 'wx' })\n while (true) {\n try {\n renameSync(staged, guard)\n break\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOTEMPTY' && code !== 'EEXIST' && code !== 'ENOTDIR') throw error\n }\n const observed = observeLeaseGuard(guard)\n if (observed.kind === 'vacant') continue\n const owner = observed.owner\n if (leaseGuardIsResidue(owner)) {\n hooks.beforeLeaseGuardReclaim?.()\n reclaimLeaseGuard(guard, observed.ownerFile, hooks)\n continue\n }\n if (owner?.pid === process.pid && owner.threadId === threadId) {\n throw new LeaseGuardBusyError(\n 'writer lease guard is held by an enclosing section on this thread',\n )\n }\n if (!contended) {\n contended = true\n hooks.onLeaseGuardContended?.()\n }\n if (monotonicElapsedMs(claimedAtNs) >= LEASE_GUARD_WAIT_MS) {\n throw new LeaseGuardBusyError(\n `writer lease guard stayed held by pid ${owner?.pid ?? 'unknown'} for `\n + `${LEASE_GUARD_WAIT_MS}ms`,\n )\n }\n Atomics.wait(MUTATION_LOCK_TERMINATION_WAIT, 0, 0, LEASE_GUARD_POLL_MS)\n }\n } finally {\n // After a successful claim the staged directory IS the guard, so nothing is left to remove.\n rmSync(staged, { recursive: true, force: true })\n }\n try {\n sweepLeakedLeaseGuardStaging(parent, staged)\n return section()\n } finally {\n releaseLeaseGuard(guard, ownerFile)\n }\n } finally {\n for (const dir of createdAncestors) {\n try {\n rmdirSync(dir)\n } catch {\n // Not empty, already gone, or not ours to judge: left as it is.\n }\n }\n }\n}\n\n/**\n * Read and strictly validate current writer authority without acquiring or refreshing it.\n *\n * CR-01 (round 5): ENOENT is the only read failure that is evidence of absence, and NO read\n * failure is evidence of corruption. This is `readEpoch`'s rule applied to the file it was not\n * applied to — the derivation's own W-01 note says the guard belongs at the READ, so that\n * consumers inherit it rather than each re-deriving it, and this read has three consumers that\n * select SIGKILL, epoch minting and registration deletion from its answer.\n *\n * The `existsSync` fallback that used to sit here is deleted rather than kept beside the errno\n * test: under fd exhaustion it fails for the same reason the open did, so it degraded an EMFILE\n * read from `malformed` to `absent` — the strongest possible statement that nobody holds the\n * lease, produced by the weakest possible evidence.\n */\nexport function readWriterLease(knowledgeRoot: string): ReadWriterLeaseOutcome {\n const file = leasePath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { kind: 'absent' }\n return { kind: 'unreadable', code: code ?? 'unknown-read-error' }\n }\n\n try {\n const parsed = writerLeaseSchema.safeParse(JSON.parse(raw))\n return parsed.success ? { kind: 'parsed', lease: parsed.data } : { kind: 'malformed' }\n } catch {\n return { kind: 'malformed' }\n }\n}\n\nfunction previewEpochState(raw: string): string {\n const preview = raw.slice(0, 64).replaceAll('\\r', '\\\\r').replaceAll('\\n', '\\\\n')\n return preview === '' ? '<empty>' : preview\n}\n\nfunction readEpoch(knowledgeRoot: string): number {\n const file = epochPath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return 0\n throw new CorruptEpochStateError(file, 'unreadable', code ?? 'unknown-read-error')\n }\n const canonical = raw.endsWith('\\n') ? raw.slice(0, -1) : raw\n if (!/^(0|[1-9][0-9]*)$/.test(canonical)) {\n throw new CorruptEpochStateError(file, 'malformed', previewEpochState(raw))\n }\n const epoch = Number(canonical)\n if (!Number.isSafeInteger(epoch)) {\n throw new CorruptEpochStateError(file, 'overflow', previewEpochState(raw))\n }\n return epoch\n}\n\n/** Fresh-read the monotonic disk epoch; only an absent file is pre-acquire epoch zero. */\nexport function readCurrentEpoch(knowledgeRoot: string): number {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n return readEpoch(knowledgeRoot)\n}\n\n/**\n * An epoch-stale write is refused AT THE MUTATION BOUNDARY. Plan 378-10 calls this immediately\n * before the intent-journal write and again immediately before the publish rename; a stale result\n * abandons the in-flight job without mutation. Every call re-reads disk and never caches the epoch.\n */\nexport function assertEpochCurrent(\n opts: AssertEpochCurrentOptions,\n): AssertEpochCurrentOutcome {\n const observedEpoch = readCurrentEpoch(opts.knowledgeRoot)\n return observedEpoch === opts.epoch\n ? { current: true }\n : { current: false, observedEpoch }\n}\n\nfunction nextEpoch(current: number): number {\n if (current === Number.MAX_SAFE_INTEGER) {\n throw new RangeError('writer lease epoch exhausted')\n }\n return current + 1\n}\n\n/** Purely classify a guarded or untrusted lease value against one explicit wall-clock instant. */\nexport function isLeaseStale(lease: unknown, nowMs: number): boolean {\n const parsed = writerLeaseSchema.safeParse(lease)\n if (!parsed.success || !Number.isFinite(nowMs)) return true\n return nowMs - parsed.data.heartbeatAtMs >= LEASE_HEARTBEAT_TTL_MS\n}\n\n/**\n * The one freshness answer, and it has three values rather than two.\n *\n * CR-01: the previous derivation returned a boolean, so every way of failing to READ the epoch\n * collapsed into the same value a genuinely expired lease produces. `readEpoch` raises\n * `CorruptEpochStateError(…, 'unreadable', …)` for EACCES, EIO, EMFILE and ENFILE, not only for\n * corrupt bytes, and fd exhaustion produces both that failure and the daemon identity-handshake\n * failure at once. A live, healthy holder therefore became de-registrable and SIGKILL-eligible on\n * a transient read error.\n *\n * `unknown` is deliberately NOT resolved to either boolean here. Resolving it toward \"fresh\" makes\n * a permanently unreadable epoch an immortal phantom holder no contender can ever reclaim;\n * resolving it toward \"reclaimable\" is the kill this closes. It is returned to the consumers so\n * each of them names what it does with it, and so a fourth consumer added later cannot inherit a\n * default it never chose.\n *\n * W-01: the epoch conjunct lives HERE, in the derivation, not at the consumers. Three surfaces\n * classify recoverability from this verdict — `leasePermitsEscalation`, the acquisition\n * pre-check, and `classifyDaemonRegistration` in the CLI — and a fix applied consumer by consumer\n * is a list that the next surface joins without joining the guard. A lease naming a superseded\n * epoch is recovery input no matter how fresh its bytes are: nobody can still be inside a\n * transaction for an epoch that has already been replaced.\n *\n * WR-04: a crash between the epoch rewrite and the lease rewrite leaves a lease naming the\n * previous epoch. Reporting that lease as held manufactures a phantom holder no TTL sweep ever\n * reclaims, so an epoch-invalid lease is recovery input rather than an answer.\n *\n * The inputs are the disk epoch and the lease value, and nothing else. There is no second\n * freshness channel and no further conjunct: three conjuncts produced three defects.\n */\nexport type WriterLeaseFreshness =\n | { kind: 'fresh' }\n | { kind: 'reclaimable' }\n | { kind: 'unknown'; error: CorruptEpochStateError }\n\nexport function deriveWriterLeaseFreshness(\n knowledgeRoot: string,\n lease: WriterLease,\n nowMs: number,\n): WriterLeaseFreshness {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) return { kind: 'unknown', error }\n throw error\n }\n if (lease.epoch !== observedEpoch) return { kind: 'reclaimable' }\n return isLeaseStale(lease, nowMs) ? { kind: 'reclaimable' } : { kind: 'fresh' }\n}\n\n/** Return a live holder or atomically mint a new, monotonically fenced writer identity. */\nexport function acquireWriterLease(\n knowledgeRoot: string,\n hooks?: AcquireWriterLeaseOptions,\n): AcquireWriterLeaseOutcome {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n const beforeLock = readWriterLease(knowledgeRoot)\n if (beforeLock.kind === 'parsed') {\n // This consumer names `unknown` as the typed refusal it already had for corrupt epoch bytes:\n // an authority state that cannot be read is not a licence to mint a new one.\n const verdict = deriveWriterLeaseFreshness(\n knowledgeRoot,\n beforeLock.lease,\n mutationLockNowMs(),\n )\n if (verdict.kind === 'unknown') {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error: verdict.error }\n }\n if (verdict.kind === 'fresh') return { kind: 'held', holder: beforeLock.lease }\n } else if (beforeLock.kind === 'unreadable') {\n // CR-01: a lease that exists and cannot be opened is not a licence to mint over it. Refusing\n // here is what keeps the loop below — and therefore the escalation surface underneath it —\n // out of reach for this input class entirely.\n return {\n kind: 'refused',\n reason: 'unreadable-lease-state',\n code: beforeLock.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), beforeLock.code),\n }\n } else {\n // With no lease to derive from, the epoch is still read before any acquisition: unreadable or\n // corrupt authority state refuses here exactly as it does through the verdict above.\n try {\n readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error }\n }\n throw error\n }\n }\n\n const deadlineMs = hooks?.acquireDeadlineMs ?? ACQUIRE_WRITER_LEASE_DEADLINE_MS\n const startedAtNs = process.hrtime.bigint()\n /**\n * W-05: the same instant the loop's own exit is measured against, handed to everything that\n * waits beneath it.\n *\n * Escalation waits are spent on this budget, not beside it. Deriving the instant once here and\n * threading it down means no wait can be extended by retuning a constant it happens to sit\n * under, and none of them needs to know what the others cost.\n */\n const deadlineAtNs = startedAtNs + BigInt(Math.round(deadlineMs * 1e6))\n let attempts = 0\n\n while (true) {\n attempts += 1\n try {\n return withMutationLock(knowledgeRoot, () => {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return { kind: 'refused' as const, reason: 'corrupt-epoch-state' as const, error }\n }\n throw error\n }\n const current = readWriterLease(knowledgeRoot)\n const nowMs = Date.now()\n if (current.kind === 'unreadable') {\n // The in-lock repeat of the pre-lock arm: a lease that turned unopenable while this\n // contender waited for the lock is still not evidence that nobody holds it.\n return {\n kind: 'refused' as const,\n reason: 'unreadable-lease-state' as const,\n code: current.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), current.code),\n }\n }\n if (current.kind === 'parsed') {\n const verdict = deriveWriterLeaseFreshness(knowledgeRoot, current.lease, nowMs)\n if (verdict.kind === 'unknown') {\n return {\n kind: 'refused' as const,\n reason: 'corrupt-epoch-state' as const,\n error: verdict.error,\n }\n }\n if (verdict.kind === 'fresh' && current.lease.epoch === observedEpoch) {\n return { kind: 'held', holder: current.lease }\n }\n }\n const reclaimed = current.kind === 'parsed' ? current.lease : undefined\n\n const epoch = nextEpoch(observedEpoch)\n const holder = writerLeaseSchema.parse({\n leaseId: randomUUID(),\n pid: process.pid,\n epoch,\n heartbeatAtMs: nowMs,\n })\n atomicRewrite(epochPath(knowledgeRoot), `${epoch}\\n`)\n hooks?.afterEpochRewrite?.()\n sweepStagedEpochsBefore(knowledgeRoot, epoch)\n atomicRewrite(leasePath(knowledgeRoot), `${JSON.stringify(holder)}\\n`)\n return {\n kind: 'acquired',\n leaseId: holder.leaseId,\n epoch: holder.epoch,\n ...(reclaimed === undefined ? {} : { reclaimed }),\n }\n }, hooks, deadlineAtNs)\n } catch (error) {\n if (!(error instanceof MutationLockBusyError)) throw error\n /**\n * Contention answers 'held' only for an epoch-valid lease. Staleness deliberately does NOT\n * disqualify a holder here: the lock is busy, so the published holder is inside its own\n * serialized section and a stale heartbeat is exactly the fencing case DAEM-09 protects\n * (a paused drainer must be reported as holding, not stolen from). An epoch-mismatched\n * lease is different in kind — nobody can still be inside a transaction for a superseded\n * epoch — so it is recovery input and the loop keeps waiting for the lock.\n *\n * An epoch that cannot be READ is a third case and no longer hides inside the mismatch arm:\n * the contender surfaces the typed refusal by name instead of spinning silently to its\n * deadline over an authority state nobody can evaluate.\n */\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'unreadable') {\n // A lease that cannot be READ is a fourth case here for the same reason an unreadable\n // epoch is a third one: the contender surfaces it by name instead of spinning to its\n // deadline over an authority state nobody can evaluate.\n return {\n kind: 'refused',\n reason: 'unreadable-lease-state',\n code: current.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), current.code),\n }\n }\n if (current.kind === 'parsed') {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (epochError) {\n if (epochError instanceof CorruptEpochStateError) {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error: epochError }\n }\n throw epochError\n }\n if (current.lease.epoch === observedEpoch) {\n return { kind: 'held', holder: current.lease }\n }\n }\n /**\n * The outermost exit, and the only one anchored outside this module's own vocabulary.\n *\n * It is checked AFTER the `held` narrow above, so a contender that could have answered\n * `held` always does; the deadline never converts a good answer into a refusal. It is also\n * strictly larger than MUTATION_LOCK_TAKEOVER_MS, so a reclaim that was going to happen has\n * already had its chance by the time this fires.\n */\n const waitedMs = monotonicElapsedMs(startedAtNs)\n if (waitedMs >= deadlineMs) {\n const observedOwner = readCommittedMutationLockOwner(knowledgeRoot)\n const error = new WriterLeaseUnreclaimableError(\n attempts,\n waitedMs,\n observedOwner === undefined ? undefined : {\n pid: observedOwner.pid,\n acquiredAtMs: observedOwner.acquiredAtMs,\n generationToken: observedOwner.generationToken,\n incarnationAttributed: observedOwner.incarnation !== undefined,\n },\n current.kind === 'parsed' ? current.lease : undefined,\n )\n return {\n kind: 'refused',\n reason: 'mutation-lock-unreclaimable',\n error,\n attempts,\n waitedMs,\n ...(error.observedOwner === undefined ? {} : { observedOwner: error.observedOwner }),\n ...(error.observedLease === undefined ? {} : { observedLease: error.observedLease }),\n }\n }\n Atomics.wait(\n MUTATION_LOCK_TERMINATION_WAIT,\n 0,\n 0,\n MUTATION_LOCK_TERMINATION_POLL_MS,\n )\n }\n }\n}\n\n/**\n * Compare one exact writer authority and run its mutation under the same generation lock.\n * The generation check after the failpoint prevents an expired owner from resuming after a\n * bounded takeover. Mutation implementations must keep irreversible work inside `mutate`.\n */\nexport function withCurrentWriterAuthority<T>(\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n mutate: () => T,\n hooks: CurrentWriterAuthorityHooks = {},\n): T {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n const fullAuthority: WriterLeaseAuthority = { knowledgeRoot, ...authority }\n try {\n return withMutationLock(knowledgeRoot, (generationToken, db) => {\n const observedEpoch = readCurrentEpoch(knowledgeRoot)\n if (observedEpoch !== authority.epoch) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'epoch-mismatch-before-heartbeat',\n observedEpoch,\n )\n }\n /**\n * CR-01: the epoch alone is guessable, and release deliberately never advances it, so an\n * epoch-only guard admits both a fabricated identity and a holder that already released.\n * The lease is therefore read INSIDE the held transaction — the same serialization boundary\n * as the epoch and generation checks — and must match the supplied authority exactly. This\n * is heartbeatLease's presence/id/epoch ladder, applied where mutation actually happens.\n */\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'absent') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-missing', observedEpoch)\n }\n if (current.kind === 'malformed') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-malformed', observedEpoch)\n }\n // CR-01: authority that cannot be re-read inside the transaction is authority that cannot be\n // proven, and this is the fence that keeps a fenced-out writer from committing.\n if (current.kind === 'unreadable') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-unreadable', observedEpoch)\n }\n if (current.lease.leaseId !== authority.leaseId) {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-id-mismatch', observedEpoch)\n }\n if (current.lease.epoch !== authority.epoch) {\n throw new WriterAuthorityLostError(fullAuthority, 'stale-epoch', observedEpoch)\n }\n hooks.afterFinalAuthorityCompare?.()\n if (!mutationLockGenerationIsCurrent(db, generationToken)) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'mutation-lock-generation-lost',\n readCurrentEpoch(knowledgeRoot),\n )\n }\n return mutate()\n }, hooks)\n } catch (error) {\n if (\n error instanceof MutationLockBusyError\n || error instanceof MutationLockGenerationLostError\n ) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'mutation-lock-generation-lost',\n readCurrentEpoch(knowledgeRoot),\n )\n }\n throw error\n }\n}\n\n/**\n * Refresh the matching current-epoch holder without entering the mutation lock.\n *\n * CR-03 dissolves here rather than being worked around. The beat used to share\n * `withMutationLock` with every governed write, and it runs in a worker THREAD, so the daemon's\n * long synchronous mutation on the main thread held the lock while the worker blocked on it: the\n * holder starved its own heartbeat, crossed the TTL and became a takeover target. Writing `.lease`\n * directly means a governed mutation of any length cannot starve the beat at all, so heartbeat\n * independence is structural instead of a fallback that has to be maintained beside the real path.\n *\n * What the lock used to buy was check-then-write atomicity of the identity/epoch ladder below\n * against a concurrent reclaim, and dropping it opens exactly one race: a holder resuming from a\n * >=TTL wedge can land its read-check-write astride a contender's reclaim and clobber the\n * successor's lease. That is contained rather than prevented, and the containment is the epoch\n * fence: a reclaim rewrites `.epoch` strictly BEFORE it publishes its lease, both inside the lock,\n * so any lease clobbered afterwards names a superseded epoch. Every classifier reads it as\n * recovery input, no store write is admitted under it (the epoch fence at the store verbs), and\n * the successor's next authority check surfaces WriterAuthorityLostError, after which a fresh\n * acquisition reclaims at the next epoch. The worst case is one successor bounce in a microsecond\n * window after a 30 s wedge — a liveness hiccup, never minted authority. During the exact schedule\n * this lock-free write exists for (the holder's own mutation in flight) no contender can be\n * mid-reclaim at all, because a reclaim requires the very lock that mutation is holding.\n *\n * 2026-08-01 W-02 re-scope: `MUTATION_LOCK_TAKEOVER_MS` now governs reclaim from DEAD and\n * whole-process-STOPPED owners, which write no beats and cross the TTL. Auto-takeover of a LIVE\n * holder whose beat thread is still ticking is deliberately impossible; a wedged-forever live\n * daemon surfaces at every contender as the typed `mutation-lock-unreclaimable` refusal naming its\n * pid. That is an operator kill rather than an automated one, which is this module's own law: a\n * wrong kill is unrecoverable, a wedged contender is not.\n *\n * Identity is still proven first, and every refusal below leaves `.lease` byte-identical.\n *\n * 2026-10-02 (quick 261002-lse, 432-19 #7): the ladder and the write run under the lease-file\n * guard `releaseLease` also takes. Without it a beat that read before a release wrote after it,\n * and since release deliberately keeps the epoch, the resurrected lease named the CURRENT epoch:\n * the fence above contains a reclaim but not a release, and the next acquire answered `held`.\n * The guard is not the mutation lock, so everything said above about CR-03 still holds.\n */\nexport function heartbeatLease(\n opts: LeaseOperationOptions,\n hooks: LeaseGuardHooks = {},\n): HeartbeatLeaseOutcome {\n assertAbsoluteKnowledgeRoot(opts.knowledgeRoot)\n // Nothing to resurrect and nothing to guard: absence is answered before any guard is staged.\n if (readWriterLease(opts.knowledgeRoot).kind === 'absent') {\n return { kind: 'refused', reason: 'lease-missing' }\n }\n return withLeaseGuard(opts.knowledgeRoot, (): HeartbeatLeaseOutcome => {\n const current = readWriterLease(opts.knowledgeRoot)\n if (current.kind === 'absent') return { kind: 'refused', reason: 'lease-missing' }\n if (current.kind === 'malformed') return { kind: 'refused', reason: 'lease-malformed' }\n // CR-01: a beat that cannot read the lease cannot prove it owns it, so it may not rewrite it.\n if (current.kind === 'unreadable') return { kind: 'refused', reason: 'lease-unreadable' }\n if (current.lease.leaseId !== opts.leaseId) {\n return { kind: 'refused', reason: 'lease-id-mismatch', holder: current.lease }\n }\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(opts.knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return {\n kind: 'refused',\n reason: 'corrupt-epoch-state',\n holder: current.lease,\n error,\n }\n }\n throw error\n }\n if (current.lease.epoch !== observedEpoch) {\n return {\n kind: 'refused',\n reason: 'stale-epoch',\n holder: current.lease,\n observedEpoch,\n }\n }\n\n const holder = writerLeaseSchema.parse({\n ...current.lease,\n heartbeatAtMs: Date.now(),\n })\n atomicRewrite(leasePath(opts.knowledgeRoot), `${JSON.stringify(holder)}\\n`)\n return { kind: 'heartbeated', holder }\n }, hooks)\n}\n\n/**\n * Refresh one exact maintenance writer at a non-mutating boundary.\n *\n * The epoch reads deliberately bracket the heartbeat: the first rejects an already-reclaimed\n * holder, while the second detects a reclaim race after the lease rewrite. The authority-store\n * transaction is released before this function returns, so this is NOT a mutation fence. Any\n * irreversible mutation must instead run inside `withCurrentWriterAuthority`.\n */\nexport function refreshWriterLeaseAuthority(\n authority: WriterLeaseAuthority,\n): WriterLeaseAuthority {\n const beforeHeartbeat = assertEpochCurrent(authority)\n if (!beforeHeartbeat.current) {\n throw new WriterAuthorityLostError(\n authority,\n 'epoch-mismatch-before-heartbeat',\n beforeHeartbeat.observedEpoch,\n )\n }\n\n const heartbeat = heartbeatLease(authority)\n if (heartbeat.kind === 'refused') {\n if (heartbeat.reason === 'corrupt-epoch-state' && heartbeat.error !== undefined) {\n throw heartbeat.error\n }\n throw new WriterAuthorityLostError(\n authority,\n heartbeat.reason,\n readCurrentEpoch(authority.knowledgeRoot),\n )\n }\n\n const afterHeartbeat = assertEpochCurrent(authority)\n if (!afterHeartbeat.current) {\n throw new WriterAuthorityLostError(\n authority,\n 'epoch-mismatch-after-heartbeat',\n afterHeartbeat.observedEpoch,\n )\n }\n\n return authority\n}\n\n/**\n * Remove only the matching lease file; the monotonic epoch is deliberately retained forever.\n *\n * The read and the deletion run under the lease-file guard, taken inside the mutation lock, so a\n * heartbeat in flight finishes before the lease is read and any later beat finds it gone\n * (261002-lse). The guard is always taken second, and the beat never takes the mutation lock, so\n * the two cannot wait on each other.\n */\nexport function releaseLease(\n opts: LeaseOperationOptions,\n hooks: LeaseGuardHooks = {},\n): ReleaseLeaseOutcome {\n assertAbsoluteKnowledgeRoot(opts.knowledgeRoot)\n return withMutationLock(opts.knowledgeRoot, () => {\n const outcome = withLeaseGuard(opts.knowledgeRoot, (): ReleaseLeaseOutcome => {\n const current = readWriterLease(opts.knowledgeRoot)\n if (current.kind === 'absent') return { kind: 'refused', reason: 'lease-missing' }\n if (current.kind === 'malformed') return { kind: 'refused', reason: 'lease-malformed' }\n // CR-01: release is a deletion. An unreadable lease could belong to anybody, including a\n // successor that reclaimed while this caller was away, so it is never removed unseen.\n if (current.kind === 'unreadable') return { kind: 'refused', reason: 'lease-unreadable' }\n if (current.lease.leaseId !== opts.leaseId) {\n return { kind: 'refused', reason: 'lease-id-mismatch', holder: current.lease }\n }\n\n rmSync(leasePath(opts.knowledgeRoot), { force: true })\n return { kind: 'released' }\n }, hooks)\n if (outcome.kind === 'released') bestEffortFsyncDirectory(opts.knowledgeRoot)\n return outcome\n })\n}\n","/**\n * IDX-02's authoritative degraded read leg over committed bundles.\n *\n * The scan is lexical + anchor only. Authority requires loadBundle's strict parse,\n * verifyBundleIntegrity's committed-byte digest and identity checks, and deriveBundleTrust's\n * status and ordinal validity (memory.md §8.2). A parseable payload whose manifest digest no\n * longer matches is not authoritative. Per-bundle digest work is deliberate on this degraded\n * face: correctness outranks scan cost at QA scale. Per 374 D-03, this module consumes those\n * read faces and never re-parses committed bundle files.\n */\nimport { readdirSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nimport { canonicalJson, normalizeAnchor } from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n BundleStatus,\n DerivedTrustState,\n RecordId,\n TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle, verifyBundleIntegrity } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\n\nexport interface KnowledgeHit {\n bundleId: string\n product: string\n kind: LoadedBundle['frontmatter']['kind']\n subtype: string | null\n status: BundleStatus\n trust: number\n validity: DerivedTrustState['validity']\n summary: string\n embeddingInput: string\n}\n\nexport interface ScanBundlesOptions {\n knowledgeRoot: string\n priors?: TrustPriorTable\n text?: string\n anchor?: Anchor\n product?: string\n k?: number\n}\n\nexport interface ScanBundleByIdOptions {\n knowledgeRoot: string\n priors?: TrustPriorTable\n bundleId: string\n}\n\nexport type CanonicalBundleAnchorLookup =\n | {\n kind: 'resolved'\n bundleId: RecordId\n product: string\n anchors: Anchor[]\n }\n | { kind: 'unresolved'; reason: 'not-found' }\n | { kind: 'unresolved'; reason: 'invalid'; detail: string }\n\nexport interface EnumeratedBundleDir {\n product: string\n dir: string\n}\n\nexport interface ProductQualifiedBundleDir extends EnumeratedBundleDir {\n recordId: string\n}\n\nexport class BundleTargetResolutionError extends Error {\n override readonly name = 'BundleTargetResolutionError'\n readonly recordId: string\n readonly product: string | undefined\n readonly reason: 'not-found' | 'ambiguous'\n\n constructor(\n recordId: string,\n product: string | undefined,\n reason: 'not-found' | 'ambiguous',\n ) {\n super(\n product === undefined\n ? `bundle target ${recordId} is ${reason}`\n : `bundle target ${product}/${recordId} is ${reason}`,\n )\n this.recordId = recordId\n this.product = product\n this.reason = reason\n }\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction childDirectories(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n } catch {\n return []\n }\n}\n\n/** Enumerate bundle directories in stable product-then-directory order. */\nexport function enumerateBundleDirs(knowledgeRoot: string): EnumeratedBundleDir[] {\n const memoryDir = join(knowledgeRoot, 'memory')\n const products = childDirectories(memoryDir)\n .filter((product) => !product.startsWith('.') && product !== 'index' && product !== 'queue')\n .sort(compareText)\n\n return products.flatMap((product) => {\n const bundlesDir = join(memoryDir, product, 'bundles')\n return childDirectories(bundlesDir)\n .filter((bundleDir) => !bundleDir.startsWith('.'))\n .sort(compareText)\n .map((bundleDir) => ({ product, dir: join(bundlesDir, bundleDir) }))\n })\n}\n\n/**\n * Extract a record id without assuming the host separator. Native Windows paths appear in\n * production while POSIX fixtures may deliberately exercise them during portability tests.\n */\nexport function bundleDirRecordId(dir: string): string {\n const portable = dir.replaceAll('\\\\', '/')\n return portable.slice(portable.lastIndexOf('/') + 1)\n}\n\n/** Resolve exactly one product-qualified target; record-only ambiguity is never first-match. */\nexport function resolveProductQualifiedBundleDir(input: {\n knowledgeRoot: string\n recordId: string\n product?: string\n}): ProductQualifiedBundleDir {\n const matches = enumerateBundleDirs(input.knowledgeRoot)\n .filter((entry) => (\n bundleDirRecordId(entry.dir) === input.recordId\n && (input.product === undefined || entry.product === input.product)\n ))\n if (matches.length === 0) {\n throw new BundleTargetResolutionError(input.recordId, input.product, 'not-found')\n }\n if (matches.length !== 1) {\n throw new BundleTargetResolutionError(input.recordId, input.product, 'ambiguous')\n }\n return { ...matches[0]!, recordId: input.recordId }\n}\n\n/** The single withdrawn-fact firewall reused by degraded and indexed reader paths. */\nexport function isServable(trust: Pick<DerivedTrustState, 'status' | 'validity'>): boolean {\n return (\n (trust.status === 'active' || trust.status === 'candidate')\n && trust.validity.closedAtOrdinal === undefined\n )\n}\n\nfunction toHit(\n bundle: LoadedBundle,\n trustState: DerivedTrustState,\n product: string,\n): KnowledgeHit {\n return {\n bundleId: bundle.manifest.id,\n product,\n kind: bundle.frontmatter.kind,\n subtype: bundle.frontmatter.subtype ?? null,\n status: trustState.status,\n trust: trustState.trust,\n validity: trustState.validity,\n summary: bundle.summary,\n embeddingInput: bundle.manifest.embeddingInput,\n }\n}\n\n/**\n * D-16 widens the no-dense scan authority to stored normalized anchor forms.\n * Phase 377 generalizes this lexical behavior into the §5.5.8 query helper.\n */\nfunction textMatches(bundle: LoadedBundle, queryTokens: readonly string[]): boolean {\n if (queryTokens.length === 0) return true\n const searchableText = [\n bundle.manifest.embeddingInput,\n bundle.summary,\n ...bundle.frontmatter.anchors.map(({ raw }) => canonicalJson(raw)),\n ...bundle.frontmatter.anchors.map(({ normalized }) => canonicalJson(normalized)),\n ]\n .join('\\n')\n .toLowerCase()\n return queryTokens.every((token) => searchableText.includes(token))\n}\n\n/**\n * D-16's rung-3 fallback lives here because a bundle scan is always vec:none.\n * Phase 377 generalizes the same normalized-name widening into the §5.5.8 query helper.\n */\nfunction anchorMatches(bundle: LoadedBundle, queryAnchor: Anchor | undefined): boolean {\n if (queryAnchor === undefined) return true\n const canonicalQuery = canonicalJson(queryAnchor)\n return bundle.frontmatter.anchors.some(({ normalized }) => {\n if (canonicalJson(normalized) === canonicalQuery) return true\n return normalized.t === 'el'\n && queryAnchor.t === 'el'\n && normalized.role === queryAnchor.role\n && normalized.name === queryAnchor.name\n })\n}\n\nfunction servableHit(dir: EnumeratedBundleDir, priors?: TrustPriorTable): KnowledgeHit | undefined {\n const outcome = loadBundle(dir.dir)\n if (outcome.kind !== 'loaded') return undefined\n if (!verifyBundleIntegrity(dir.dir).ok) return undefined\n const trustState = deriveBundleTrust(outcome.bundle, priors)\n return isServable(trustState)\n ? toHit(outcome.bundle, trustState, dir.product)\n : undefined\n}\n\nfunction scanBundlesWithPosture(\n opts: ScanBundlesOptions,\n servingOnly: boolean,\n): KnowledgeHit[] {\n const queryTokens = (opts.text ?? '')\n .toLowerCase()\n .split(/\\s+/)\n .filter((token) => token !== '')\n const queryAnchor = opts.anchor === undefined\n ? undefined\n : normalizeAnchor(opts.anchor)\n\n const hits: KnowledgeHit[] = []\n for (const entry of enumerateBundleDirs(opts.knowledgeRoot)) {\n if (opts.product !== undefined && entry.product !== opts.product) continue\n const outcome = loadBundle(entry.dir)\n if (outcome.kind !== 'loaded') continue\n if (!verifyBundleIntegrity(entry.dir).ok) continue\n\n const trustState = deriveBundleTrust(outcome.bundle, opts.priors)\n if (servingOnly && !isServable(trustState)) continue\n if (!textMatches(outcome.bundle, queryTokens)) continue\n if (!anchorMatches(outcome.bundle, queryAnchor)) continue\n hits.push(toHit(outcome.bundle, trustState, entry.product))\n }\n\n hits.sort(\n (left, right) => compareText(left.product, right.product)\n || compareText(left.bundleId, right.bundleId),\n )\n return opts.k === undefined\n ? hits\n : hits.slice(0, Math.max(0, Math.floor(opts.k)))\n}\n\nexport function scanBundles(opts: ScanBundlesOptions): KnowledgeHit[] {\n return scanBundlesWithPosture(opts, true)\n}\n\n/** Internal retrieval scan: status and validity are filtered by the composed pipeline. */\nexport function scanBundlesForRetrieval(opts: ScanBundlesOptions): KnowledgeHit[] {\n return scanBundlesWithPosture(opts, false)\n}\n\nexport function scanBundleById(opts: ScanBundleByIdOptions): KnowledgeHit | undefined {\n for (const entry of enumerateBundleDirs(opts.knowledgeRoot)) {\n if (basename(entry.dir) !== opts.bundleId) continue\n const hit = servableHit(entry, opts.priors)\n if (hit !== undefined) return hit\n }\n return undefined\n}\n\n/**\n * Trusted, read-only lookup for post-verdict attribution. Unlike scanBundleById this deliberately\n * ignores serving lifecycle state: a handoff may outlive a candidate's promotion, supersession, or\n * deprecation. Canonical bytes still have to parse and pass the complete integrity oracle.\n */\nexport function readCanonicalBundleAnchors(input: {\n knowledgeRoot: string\n bundleId: RecordId\n}): CanonicalBundleAnchorLookup {\n const found = enumerateBundleDirs(input.knowledgeRoot)\n .find(({ dir }) => basename(dir) === input.bundleId)\n if (found === undefined) return { kind: 'unresolved', reason: 'not-found' }\n\n const loaded = loadBundle(found.dir)\n if (loaded.kind !== 'loaded') {\n return {\n kind: 'unresolved',\n reason: 'invalid',\n detail: `canonical bundle could not be loaded (${loaded.kind})`,\n }\n }\n if (loaded.bundle.manifest.id !== input.bundleId) {\n return {\n kind: 'unresolved',\n reason: 'invalid',\n detail: 'canonical bundle id does not match its directory identity',\n }\n }\n\n const integrity = verifyBundleIntegrity(found.dir)\n if (!integrity.ok) {\n return {\n kind: 'unresolved',\n reason: 'invalid',\n detail: integrity.violations.join('; '),\n }\n }\n\n return {\n kind: 'resolved',\n bundleId: input.bundleId,\n product: found.product,\n anchors: loaded.bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n }\n}\n","import { readFileSync, readdirSync } from 'node:fs'\nimport type { Dirent } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n RECORD_CHANGE_SCHEMA_VERSION,\n RecordChangeSchema,\n survivingOutcomeEvents,\n isPromotionReceipt,\n strongestPromotionPath,\n} from '@vostride/agent-qa-schema'\nimport type {\n BundleOutcomeEvent,\n BundleProvenance,\n RecordChange,\n} from '@vostride/agent-qa-schema'\n\nimport {\n enumerateMaintenanceBundleDirs,\n KnowledgeMaintenanceScanError,\n loadMaintenanceBundle,\n} from './maintenance-scan.js'\nimport {\n guardPurgeReceiptForFile,\n parseCanonicalPurgeReceiptFileName,\n} from './purge-receipt.js'\nimport { readGateReceipts } from './bundle-read.js'\n\nexport interface DiffSinceOptions {\n knowledgeRoot: string\n sinceOrdinal: number\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/**\n * The run this event's curation belongs to, or `undefined` when it is not DERIVABLE (Phase 407,\n * LERN-02 · D-10 as reconciled by 407-01).\n *\n * There is no single \"this run's curation job id\" to join on: a commit stamps\n * `curationJobId = candidateId`, a promotion stamps `promote:<candidateId>`, and a canary outcome\n * stamps a sha-derived observation id. The bundle's own `run-linked` provenance carries BOTH the\n * run and the candidate id those two job spellings are built from, so an event whose job id is one\n * of them was produced by this bundle's own curation and no other.\n *\n * An event carrying a NEIGHBOURING candidate's job id gets nothing. A change attributed to the\n * wrong run is worse than one attributed to no run: a person reading \"this run deprecated that\n * fact\" acts on it.\n */\nfunction linkedRunId(\n event: BundleOutcomeEvent,\n provenance: BundleProvenance,\n): string | undefined {\n if (provenance.mode !== 'run-linked' || provenance.curationJobId === undefined) return undefined\n return event.curationJobId === provenance.curationJobId\n || event.curationJobId === `promote:${provenance.curationJobId}`\n ? provenance.runId\n : undefined\n}\n\n/**\n * The two run links, spread onto every change a surviving event produces.\n *\n * `observationId` is a DIFFERENT axis from `sourceRunId` rather than a fallback for it: a canary\n * outcome is attributed by an id the consumer recomputes from the run's own served tuples, while a\n * commit or promotion is attributed by run id. Absent keys, never nulls — a change written before\n * this field existed and a change for which nothing is derivable must read identically.\n */\nfunction runLinks(\n event: BundleOutcomeEvent,\n provenance: BundleProvenance,\n): { sourceRunId?: string; observationId?: string } {\n const runId = linkedRunId(event, provenance)\n return {\n ...(runId === undefined ? {} : { sourceRunId: runId }),\n ...(event.observationId === undefined ? {} : { observationId: event.observationId }),\n }\n}\n\nfunction directChange(\n recordId: string,\n event: BundleOutcomeEvent,\n provenance: BundleProvenance,\n): RecordChange | undefined {\n switch (event.type) {\n case 'confirmed':\n case 'deprecated':\n case 'promoted':\n return RecordChangeSchema.parse({\n schemaVersion: RECORD_CHANGE_SCHEMA_VERSION,\n recordId,\n change: event.type,\n atOrdinal: event.buildOrdinal,\n evidenceToken: event.evidenceToken,\n ...runLinks(event, provenance),\n })\n case 'superseded':\n return RecordChangeSchema.parse({\n schemaVersion: RECORD_CHANGE_SCHEMA_VERSION,\n recordId,\n change: event.type,\n atOrdinal: event.buildOrdinal,\n evidenceToken: event.evidenceToken,\n byRecordId: event.byRecordId,\n ...runLinks(event, provenance),\n })\n default:\n return undefined\n }\n}\n\nfunction purgeChanges(knowledgeRoot: string, sinceOrdinal: number): RecordChange[] {\n const receiptsDir = join(knowledgeRoot, 'memory', 'receipts')\n let entries: Dirent<string>[]\n try {\n entries = readdirSync(receiptsDir, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw new KnowledgeMaintenanceScanError(\n 'directory-read',\n receiptsDir,\n error instanceof Error ? error.message : String(error),\n )\n }\n\n const changes: RecordChange[] = []\n const identities = new Set<string>()\n const files = entries\n .filter((entry) => (\n entry.name.startsWith('purge-')\n && entry.name.endsWith('.json')\n && !entry.name.endsWith('.intent.json')\n ))\n .sort((left, right) => compareText(left.name, right.name))\n for (const file of files) {\n const path = join(receiptsDir, file.name)\n if (!file.isFile()) {\n throw new KnowledgeMaintenanceScanError(\n 'receipt-invalid',\n path,\n 'canonical receipt entry is not a regular file',\n )\n }\n const name = parseCanonicalPurgeReceiptFileName(file.name)\n if (name === undefined) {\n throw new KnowledgeMaintenanceScanError(\n 'receipt-invalid',\n path,\n 'purge-prefixed JSON does not use a canonical receipt filename',\n )\n }\n const identity = `${name.recordId}:${name.cycle}`\n if (identities.has(identity)) continue\n identities.add(identity)\n\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (error) {\n throw new KnowledgeMaintenanceScanError(\n 'receipt-read',\n path,\n error instanceof Error ? error.message : String(error),\n )\n }\n try {\n const receipt = guardPurgeReceiptForFile(JSON.parse(raw), file.name)\n if (receipt.purgedAtOrdinal <= sinceOrdinal) continue\n changes.push(RecordChangeSchema.parse({\n schemaVersion: RECORD_CHANGE_SCHEMA_VERSION,\n recordId: receipt.purgedRecordId,\n change: 'purged',\n atOrdinal: receipt.purgedAtOrdinal,\n }))\n } catch (error) {\n throw new KnowledgeMaintenanceScanError(\n 'receipt-invalid',\n path,\n error instanceof Error ? error.message : String(error),\n )\n }\n }\n return changes\n}\n\n/** Pure build-ordinal fold over committed bundle outcomes and content-free purge receipts. */\nexport function diffSince(options: DiffSinceOptions): RecordChange[] {\n if (!Number.isInteger(options.sinceOrdinal) || options.sinceOrdinal < 0) {\n throw new TypeError('sinceOrdinal must be a non-negative integer')\n }\n\n const changes: RecordChange[] = []\n for (const entry of enumerateMaintenanceBundleDirs(options.knowledgeRoot)) {\n const bundle = loadMaintenanceBundle(entry)\n const survivingEvents = survivingOutcomeEvents(bundle.events)\n const earliestOrdinal = survivingEvents.reduce(\n (earliest, event) => Math.min(earliest, event.buildOrdinal),\n bundle.manifest.createdAtOrdinal,\n )\n let eventLowerBound = options.sinceOrdinal\n if (earliestOrdinal > options.sinceOrdinal) {\n changes.push(RecordChangeSchema.parse({\n schemaVersion: RECORD_CHANGE_SCHEMA_VERSION,\n recordId: bundle.manifest.id,\n change: 'added',\n atOrdinal: earliestOrdinal,\n // 407-04 (D-10): the appearance of a record IS the run's doing whenever the bundle\n // records one — no `curationJobId` match is needed, because no event produced this\n // change. A standalone bundle names no run and gets no key.\n ...(bundle.provenance.mode === 'run-linked'\n ? { sourceRunId: bundle.provenance.runId }\n : {}),\n }))\n eventLowerBound = earliestOrdinal\n }\n\n for (const event of survivingEvents) {\n if (event.buildOrdinal <= options.sinceOrdinal) continue\n const receipts = event.type === 'promoted' ? readGateReceipts(entry.dir, bundle.manifest.id) ?? [] : []\n const promotion = receipts.filter(isPromotionReceipt)\n .reverse().find(line => line.producedAtOrdinal === event.buildOrdinal)\n // A synchronous mark commit and promotion share an ordinal. Its persisted promotion\n // receipt makes that event distinct from the added row; legacy receipt-less rows retain\n // their historical suppression at the creation ordinal.\n if (event.buildOrdinal <= eventLowerBound && promotion === undefined) continue\n const change = directChange(bundle.manifest.id, event, bundle.provenance)\n if (change !== undefined) {\n const promotionPath = promotion === undefined ? undefined : strongestPromotionPath(receipts)\n changes.push(promotionPath === undefined ? change : RecordChangeSchema.parse({\n ...change, promotionPath, promotionReceiptDigest: promotion!.receiptDigest,\n }))\n }\n }\n }\n\n changes.push(...purgeChanges(options.knowledgeRoot, options.sinceOrdinal))\n return changes.sort((left, right) => (\n compareText(left.recordId, right.recordId)\n || left.atOrdinal - right.atOrdinal\n || compareText(left.change, right.change)\n || compareText(left.evidenceToken ?? '', right.evidenceToken ?? '')\n || compareText(left.byRecordId ?? '', right.byRecordId ?? '')\n ))\n}\n","import { VersionGuardError, createVersionGuard } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nexport const PURGE_RECEIPT_SCHEMA_VERSION = 2\n\n/**\n * Receipt ids are used in a suffix-addressed series, so dots cannot be admitted without making\n * `purge-X.2.json` ambiguous between an id and a cycle number.\n */\nexport const PURGE_SAFE_RECORD_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\nexport const purgeReceiptRelativePathSchema = z.string().refine((value) => {\n if (value === '' || value.startsWith('/') || value.includes('\\\\')) return false\n return value\n .split('/')\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..')\n}, 'expected a knowledge-root-relative committed path')\n\n/**\n * Content-free committed audit receipt shared by the purge writer and read-only maintenance\n * history. Keeping the contract outside purge.ts prevents the reader graph from importing the\n * destructive implementation merely to validate committed receipt bytes.\n */\nexport const PurgeReceiptSchema = z.object({\n schemaVersion: z.literal(PURGE_RECEIPT_SCHEMA_VERSION),\n purgedRecordId: z.string().regex(PURGE_SAFE_RECORD_ID),\n purgedAtOrdinal: z.number().int().nonnegative(),\n initiator: z.string().min(1).refine((value) => value.trim() !== '', 'initiator is required'),\n affectedPaths: z.array(purgeReceiptRelativePathSchema).min(1),\n firstCommittedOrdinal: z.number().int().nonnegative(),\n}).strict()\n\nexport const purgeReceiptSchema = PurgeReceiptSchema\nexport type PurgeReceipt = z.infer<typeof PurgeReceiptSchema>\n\nconst guardPurgeReceiptVersion = createVersionGuard<PurgeReceipt>({\n name: 'PurgeReceipt',\n current: PURGE_RECEIPT_SCHEMA_VERSION,\n migrations: {},\n})\n\nexport function guardPurgeReceipt(value: unknown): PurgeReceipt {\n return PurgeReceiptSchema.parse(guardPurgeReceiptVersion(value))\n}\n\n// Cycle 1 uses the unsuffixed base name; only cycles >= 2 use a numeric suffix.\nconst CANONICAL_PURGE_RECEIPT_FILE =\n /^purge-([A-Za-z0-9][A-Za-z0-9_-]*)(?:\\.([2-9]|[1-9][0-9]+))?\\.json$/u\n\nexport interface CanonicalPurgeReceiptName {\n recordId: string\n cycle: number\n}\n\nexport function parseCanonicalPurgeReceiptFileName(\n fileName: string,\n): CanonicalPurgeReceiptName | undefined {\n const match = CANONICAL_PURGE_RECEIPT_FILE.exec(fileName)\n if (match === null) return undefined\n return {\n recordId: match[1]!,\n cycle: match[2] === undefined ? 1 : Number(match[2]),\n }\n}\n\nexport interface ExpectedPurgeReceiptIdentity {\n recordId: string\n cycle: number\n}\n\n/** Bind structurally valid receipt bytes to both its filename and the requested series slot. */\nexport function guardPurgeReceiptForFile(\n value: unknown,\n fileName: string,\n expected?: ExpectedPurgeReceiptIdentity,\n): PurgeReceipt {\n const identity = parseCanonicalPurgeReceiptFileName(fileName)\n if (identity === undefined) {\n throw new TypeError(`non-canonical purge receipt filename: ${fileName}`)\n }\n if (\n expected !== undefined\n && (identity.recordId !== expected.recordId || identity.cycle !== expected.cycle)\n ) {\n throw new TypeError(\n `purge receipt slot identifies ${identity.recordId} cycle ${identity.cycle}, `\n + `expected ${expected.recordId} cycle ${expected.cycle}`,\n )\n }\n let receipt: PurgeReceipt\n try {\n receipt = guardPurgeReceipt(value)\n } catch (error) {\n if (!(error instanceof VersionGuardError)) throw error\n throw new VersionGuardError(\n `${error.documentName} ${fileName}`,\n error.foundVersion,\n error.supportedVersion,\n )\n }\n if (receipt.purgedRecordId !== identity.recordId) {\n throw new TypeError(\n `purge receipt filename identifies ${identity.recordId}, payload identifies ${receipt.purgedRecordId}`,\n )\n }\n return receipt\n}\n","import { randomUUID } from 'node:crypto'\nimport { mkdirSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { z } from 'zod'\n\nimport {\n canonicalJson,\n CROSS_CHECKS,\n sha256hex,\n type Benefit,\n type CanaryOutcome,\n type StateValidity,\n} from '@vostride/agent-qa-schema'\n\nimport { anchorSchema } from './anchor-schema.js'\nimport { assertWithinKnowledgeRoot } from './knowledge-containment.js'\nimport {\n bestEffortFsyncDirectory,\n durableWrite,\n publishStagedQueueEntry,\n queueStagingRoot,\n queuedCandidateDir,\n queuedRoot,\n removeEmptyDir,\n} from './queue-transport.js'\n\nexport const CANARY_QUEUE_SCHEMA_VERSION = 2\n\n// 2026-09-07, 418 SC1: pin persisted payload.json vocabulary in edited local source.\n// satisfies bounds membership; the test-d never-bars enforce completeness.\n// prettier-ignore\nexport const PAYLOAD_BENEFITS = ['exercised-benefited', 'rode-along', 'exercised-harmed'] as const satisfies readonly Benefit[]\n// prettier-ignore\nexport const PAYLOAD_STATE_VALIDITIES = ['valid', 'stale', 'unknown'] as const satisfies readonly StateValidity[]\n\nconst canaryOutcomePayloadBaseShape = {\n jobKind: z.literal('canary-outcome'),\n candidateId: z.string().min(1),\n runId: z.string().min(1),\n testId: z.string().min(1),\n testIndex: z.number().int().nonnegative(),\n buildOrdinal: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n outcome: z.enum(['positive', 'negative']),\n exercisedAnchor: anchorSchema,\n attribution: z.string(),\n briefDigest: z.string().min(1),\n} as const\n\nconst count = z.number().int().nonnegative()\nconst digest = z.string().regex(/^[0-9a-f]{64}$/)\nexport const canaryOutcomePayloadSchema = z\n .object({\n ...canaryOutcomePayloadBaseShape,\n schemaVersion: z.literal(CANARY_QUEUE_SCHEMA_VERSION),\n benefit: z.enum(PAYLOAD_BENEFITS),\n stateValidity: z.enum(PAYLOAD_STATE_VALIDITIES),\n corpusDigest: digest.optional(),\n observedStateDigest: digest.optional(),\n ablation: z.object({\n crossCheck: z.enum(CROSS_CHECKS),\n k: z.number().int().min(3),\n baseSeed: z.number().int(),\n seeds: z.array(z.number().int()),\n seedHonored: z.boolean(),\n spend: z.object({\n modelCalls: count, screens: count, promptTokens: count, completionTokens: count,\n }).strict(),\n }).strict().optional(),\n })\n .strict()\n\n// Diagnostic wall-clock metadata never participates in durable identity.\nconst diagnosticShape = { emittedAt: z.string().optional() }\nconst canaryOutcomeAddressFieldsSchema = canaryOutcomePayloadSchema.extend(diagnosticShape)\n\nexport type CanaryOutcomePayload = z.infer<typeof canaryOutcomePayloadSchema>\nexport type QueuedCanaryPayloadRead =\n | { kind: 'current'; payload: CanaryOutcomePayload }\n | { kind: 'refused'; issues: string[] }\n\nexport function readQueuedCanaryPayload(value: unknown): QueuedCanaryPayloadRead {\n const parsed = canaryOutcomePayloadSchema.safeParse(value)\n if (!parsed.success) {\n // Queued bytes are untrusted: never echo their values or unknown keys in diagnostics.\n return { kind: 'refused', issues: ['Invalid queued canary payload'] }\n }\n return { kind: 'current', payload: parsed.data }\n}\nexport type CanaryOutcomeAddressFields = z.infer<\n typeof canaryOutcomeAddressFieldsSchema\n>\n\n/** Content-address all attribution authority while excluding diagnostic wall-clock metadata. */\nexport function canaryOutcomeContentAddress(\n fields: CanaryOutcomeAddressFields,\n): string {\n const parsed = canaryOutcomeAddressFieldsSchema.parse(fields)\n const { emittedAt: _diagnostic, ...deterministic } = parsed\n return sha256hex(canonicalJson(deterministic))\n}\n\nexport type EnqueueCanaryOutcome =\n | { kind: 'enqueued'; entryId: string }\n | { kind: 'coalesced'; entryId: string }\n\n/**\n * D-20's one emit pattern: synchronously publish with the same durable staging and rename\n * semantics as a curation drop, so crashes and retries cannot multiply one attributed outcome.\n */\nexport function enqueueCanaryOutcome(\n knowledgeRoot: string,\n outcome: CanaryOutcome,\n): EnqueueCanaryOutcome {\n const payload = canaryOutcomePayloadSchema.parse({\n schemaVersion: CANARY_QUEUE_SCHEMA_VERSION,\n jobKind: 'canary-outcome',\n candidateId: outcome.candidateId,\n runId: outcome.runId,\n testId: outcome.testId,\n testIndex: outcome.testIndex,\n buildOrdinal: outcome.buildOrdinal,\n stepIndex: outcome.stepIndex,\n outcome: outcome.runOutcome,\n benefit: outcome.benefit,\n stateValidity: outcome.stateValidity,\n ...(outcome.corpusDigest === undefined ? {} : { corpusDigest: outcome.corpusDigest }),\n ...(outcome.observedStateDigest === undefined ? {} : { observedStateDigest: outcome.observedStateDigest }),\n ...(outcome.ablation === undefined ? {} : { ablation: outcome.ablation }),\n exercisedAnchor: outcome.exercisedAnchor,\n attribution: outcome.attribution,\n briefDigest: outcome.briefDigest,\n })\n const entryId = canaryOutcomeContentAddress(payload)\n const stagingRoot = queueStagingRoot(knowledgeRoot)\n assertWithinKnowledgeRoot(knowledgeRoot, stagingRoot)\n assertWithinKnowledgeRoot(knowledgeRoot, queuedRoot(knowledgeRoot))\n const stagingDir = join(stagingRoot, randomUUID())\n mkdirSync(stagingDir, { recursive: true })\n try {\n durableWrite(join(stagingDir, 'payload.json'), `${canonicalJson(payload)}\\n`)\n bestEffortFsyncDirectory(stagingDir)\n const published = publishStagedQueueEntry(\n stagingDir,\n queuedCandidateDir(knowledgeRoot, entryId),\n queuedRoot(knowledgeRoot),\n )\n return {\n kind: published === 'published' ? 'enqueued' : 'coalesced',\n entryId,\n }\n } finally {\n rmSync(stagingDir, { recursive: true, force: true })\n removeEmptyDir(stagingRoot)\n }\n}\n","import { z } from 'zod'\n\nimport type { Anchor } from '@vostride/agent-qa-schema'\n\n/** Shared strict validator for normalized and raw knowledge anchors. */\nexport const anchorSchema: z.ZodType<Anchor> = z.discriminatedUnion('t', [\n z.object({ t: z.literal('page'), route: z.string() }).strict(),\n z.object({ t: z.literal('flow'), name: z.string() }).strict(),\n z\n .object({\n t: z.literal('el'),\n role: z.string(),\n name: z.string(),\n ordinal: z.number().int().optional(),\n })\n .strict(),\n z\n .object({\n t: z.literal('platform'),\n platform: z.enum(['web', 'android', 'ios']),\n })\n .strict(),\n z.object({ t: z.literal('selector'), literal: z.string() }).strict(),\n z.object({ t: z.literal('error'), message: z.string() }).strict(),\n])\n","import {\n closeSync,\n existsSync,\n fsyncSync,\n mkdirSync,\n openSync,\n renameSync,\n rmdirSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join } from 'node:path'\n\n/** Gitignored durable curation transport root; provisional until M2 field evidence retunes it. */\nexport const QUEUE_DIR = 'memory/queue'\n/** Pending candidates visible to a drainer. */\nexport const QUEUED_SUBDIR = 'queued'\n/** Lease-partitioned candidates atomically removed from the pending set. */\nexport const CLAIMED_SUBDIR = 'claimed'\n/** Terminally isolated candidates that require operator inspection or repair. */\nexport const QUARANTINED_SUBDIR = 'quarantined'\n/** Durable lifecycle checkpoints keyed by candidate content address. */\nexport const JOBS_SUBDIR = 'jobs'\n/** Provisional fail-closed disk-growth limit for one knowledge scope. */\nexport const QUEUE_MAX_JOBS_PER_SCOPE = 200\n/** Provisional fail-closed candidate emission limit for one source run. */\nexport const QUEUE_MAX_EMITS_PER_RUN = 50\n\nconst SAFE_QUEUE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\nfunction assertAbsoluteKnowledgeRoot(knowledgeRoot: string): void {\n if (!isAbsolute(knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n}\n\nfunction assertQueueSegment(value: string, label: string): void {\n if (!SAFE_QUEUE_SEGMENT.test(value) || value === '.' || value === '..') {\n throw new TypeError(`${label} must be a safe path segment`)\n }\n}\n\nexport function queueRoot(knowledgeRoot: string): string {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n return join(knowledgeRoot, QUEUE_DIR)\n}\n\nexport function queuedRoot(knowledgeRoot: string): string {\n return join(queueRoot(knowledgeRoot), QUEUED_SUBDIR)\n}\n\nexport function claimedRoot(knowledgeRoot: string): string {\n return join(queueRoot(knowledgeRoot), CLAIMED_SUBDIR)\n}\n\nexport function quarantinedRoot(knowledgeRoot: string): string {\n return join(queueRoot(knowledgeRoot), QUARANTINED_SUBDIR)\n}\n\nexport function jobsRoot(knowledgeRoot: string): string {\n return join(queueRoot(knowledgeRoot), JOBS_SUBDIR)\n}\n\nexport function queueStagingRoot(knowledgeRoot: string): string {\n return join(queueRoot(knowledgeRoot), '.staging')\n}\n\nexport function queuedCandidateDir(knowledgeRoot: string, candidateId: string): string {\n assertQueueSegment(candidateId, 'candidateId')\n return join(queuedRoot(knowledgeRoot), candidateId)\n}\n\nexport function claimedLeaseDir(knowledgeRoot: string, leaseId: string): string {\n assertQueueSegment(leaseId, 'leaseId')\n return join(claimedRoot(knowledgeRoot), leaseId)\n}\n\nexport function claimedCandidateDir(\n knowledgeRoot: string,\n leaseId: string,\n candidateId: string,\n): string {\n assertQueueSegment(candidateId, 'candidateId')\n return join(claimedLeaseDir(knowledgeRoot, leaseId), candidateId)\n}\n\nexport function quarantinedCandidateDir(\n knowledgeRoot: string,\n candidateId: string,\n): string {\n assertQueueSegment(candidateId, 'candidateId')\n return join(quarantinedRoot(knowledgeRoot), candidateId)\n}\n\nexport function jobStatePath(knowledgeRoot: string, candidateId: string): string {\n assertQueueSegment(candidateId, 'candidateId')\n return join(jobsRoot(knowledgeRoot), `${candidateId}.state.json`)\n}\n\nexport function removeEmptyDir(dir: string): void {\n try {\n rmdirSync(dir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n}\n\nexport function durableWrite(file: string, bytes: string | Uint8Array): void {\n mkdirSync(dirname(file), { recursive: true })\n const fd = openSync(file, 'wx')\n try {\n writeFileSync(fd, bytes)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\nexport function bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EINVAL' && code !== 'EISDIR' && code !== 'EPERM' && code !== 'ENOTSUP') {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\nexport type PublishStagedQueueEntryOutcome = 'published' | 'coalesced'\n\n/** Publish one fully durable staging directory, coalescing an existing content address. */\nexport function publishStagedQueueEntry(\n stagingDir: string,\n finalDir: string,\n queueDir: string,\n): PublishStagedQueueEntryOutcome {\n mkdirSync(queueDir, { recursive: true })\n try {\n renameSync(stagingDir, finalDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if ((code === 'EEXIST' || code === 'ENOTEMPTY') && existsSync(finalDir)) {\n return 'coalesced'\n }\n throw error\n }\n bestEffortFsyncDirectory(queueDir)\n return 'published'\n}\n","// The addressing ledger (Phase 387, ENTY-01 / D-01 / D-02 / D-03 / D-04).\n//\n// The one DURABLE, never-rebuilt store this phase mints. Everything else 387 builds is a\n// projection that a rebuild heals; this file is not, and the difference is the whole reason\n// it lives in its own database beside `agent-jobs.db` rather than as a table inside the\n// knowledge index. Index tables are rebuildable by law, and rebuilding an ordinal ledger\n// would REASSIGN published addresses — `MEM-001` in a CI log from last month would start\n// pointing at a different memory (D-02).\n//\n// Three laws, and each is enforced by the database rather than by discipline:\n//\n// append-only BEFORE DELETE and BEFORE UPDATE triggers on `addresses` abort. Not a\n// convention about which functions this module exports — a rule that holds\n// against a future call site, an older binary, and someone at a sqlite3\n// prompt. The exported surface is open/mint/lookup, and the triggers are\n// what make that surface's narrowness a property of the data (D-04).\n// never-reuse ordinals come from `MAX(ordinal) + 1` per kind, and since nothing is ever\n// deleted that sequence is strictly increasing forever. `UNIQUE(kind,\n// ordinal)` means a second row could not claim a spent one even if some\n// future code computed the wrong next value.\n// lost race mint is one `BEGIN IMMEDIATE` transaction ending in `ON CONFLICT DO\n// NOTHING` followed by a read-back, so two processes minting the same\n// (kind, machine-id) simultaneously BOTH return the winner's ordinal and\n// neither sees a constraint error (the 385 D-02 idiom).\n//\n// Lease-free, deliberately (D-02). Addressing metadata is not learned knowledge, and the CLI\n// has to be able to mint with no daemon running. Nothing here reads the writer lease, and\n// nothing on a run/test/bundle CREATION path calls it — minting happens only when something\n// SIGHTS an entity (D-01).\n\nimport { mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nimport {\n formatOrdinalShortId,\n formatSlugShortId,\n isSlugAddressedKind,\n} from '@vostride/agent-qa-schema'\nimport type { EntityKind } from '@vostride/agent-qa-schema'\n\n/**\n * Stamped into `PRAGMA user_version` at creation and checked on every open.\n *\n * Stamp and hard-fail, never migrate — the 385 D-04 convention. The milestone ships nothing\n * between its releases, so a ledger written by another build is a development artifact, and\n * migration machinery for it would be code with no user that everything afterwards has to\n * keep working. Note what this does NOT license: the ROWS are permanent regardless. A version\n * refusal tells an operator to move a stale development file aside; it never rewrites one.\n */\nexport const ADDRESSING_LEDGER_USER_VERSION = 2\n\n/**\n * Busy timeout for every connection.\n *\n * D-02's story is \"any process mints, sqlite arbitrates\", which only works if a writer\n * waiting on the write lock retries rather than failing immediately. Matched to the job\n * store's window because the transactions are the same shape and size: retune from observed\n * contention, not from a guess about how many hosts there are.\n */\nexport const ADDRESSING_LEDGER_BUSY_TIMEOUT_MS = 2000\n\n/** The ledger's own file name under the agent-qa root, beside `agent-jobs.db` (D-02). */\nexport const ADDRESSING_LEDGER_DB_FILE = 'entity-addresses.db'\n\n/** A ledger file this build cannot read. Refused before a single schema statement runs. */\nexport class AddressingLedgerSchemaVersionError extends Error {\n constructor(\n readonly path: string,\n readonly expected: number,\n readonly found: number,\n ) {\n super(\n `The addressing ledger at ${path} is stamped schema version ${String(found)}, but this `\n + `build reads version ${String(expected)}. The ledger is never migrated and never `\n + 'rebuilt (D-02/D-04); move the file aside if it is a development artifact.',\n )\n this.name = 'AddressingLedgerSchemaVersionError'\n }\n}\n\n/**\n * An EXPLICITLY recorded target rename (D-03).\n *\n * There is no heuristic rename detection in this file and there must not be. Inferring that\n * two target slugs are \"the same target\" from their spelling, their order of appearance or\n * their contents is a guess, and ENTY-01's never-guess law is not weaker inside the ledger\n * than it is inside the resolver — a wrong link here would silently re-point a published\n * address, which is the exact failure D-02 exists to make impossible.\n */\nexport interface TargetRename {\n readonly fromSlug: string\n readonly toSlug: string\n readonly recordedAt: string\n}\n\n/** A minted address: the durable mapping plus the short-ID it renders as. */\nexport interface EntityAddress {\n readonly kind: EntityKind\n readonly machineId: string\n /** Present for ordinal-addressed kinds; absent for slug-addressed ones (D-03). */\n readonly ordinal?: number\n readonly shortId: string\n readonly mintedAt: string\n}\n\nexport interface AddressingLedger {\n /**\n * Assign this machine id its permanent address, or return the one it already has.\n *\n * Idempotent by construction rather than by a caller-side check: the unique index decides,\n * so two processes calling this at the same instant agree, and a caller that forgot to look\n * first cannot create a second address.\n */\n mint(kind: EntityKind, machineId: string): EntityAddress\n /** The address for a machine id, or `undefined` when it has never been sighted. */\n lookup(kind: EntityKind, machineId: string): EntityAddress | undefined\n /** The address a published short-ID names, or `undefined`. Tier (a)'s whole job. */\n lookupByShortId(shortId: string): EntityAddress | undefined\n /**\n * Every address ever minted, in a fixed order (kind, then short-ID).\n *\n * READ-only, and the append-only law is what makes it worth having: this list only grows, so\n * a caller enumerating it is reading a complete history rather than a snapshot that could\n * have lost rows. The entity index is rebuilt FROM this (D-06) — a projection can only claim\n * to heal if the thing it is rebuilt from can be enumerated in full.\n */\n listAddresses(): EntityAddress[]\n /**\n * Record that a config target was renamed (D-03). See {@link TargetRename} for why this is\n * the only way a link between two slugs ever comes to exist.\n *\n * Both slugs are minted, so both keep their own permanent address: the predecessor keeps\n * the one already sitting in somebody's CI log, and the successor gets its own rather than\n * inheriting one. Recording is idempotent — a repeat is the same fact, not a second one.\n */\n recordTargetRename(fromSlug: string, toSlug: string): TargetRename\n /** The rename recorded FOR this slug, if any. Never the reverse direction. */\n lookupTargetRename(fromSlug: string): TargetRename | undefined\n close(): void\n}\n\nconst SCHEMA_STATEMENTS = [\n `CREATE TABLE IF NOT EXISTS addresses (\n kind TEXT NOT NULL,\n machine_id TEXT NOT NULL,\n -- NULL exactly for slug-addressed kinds. sqlite treats NULLs as distinct in a unique\n -- index, so the (kind, ordinal) constraint below still holds for every ordinal kind\n -- while imposing nothing on TGT rows.\n ordinal INTEGER,\n short_id TEXT NOT NULL,\n minted_at TEXT NOT NULL,\n UNIQUE (kind, machine_id),\n UNIQUE (kind, ordinal),\n UNIQUE (short_id)\n )`,\n // The append-only law, as a database rule rather than as an exported-surface convention.\n // A source assertion about which functions this module exports is only as strong as the\n // next module that opens the same file; these two are not.\n `CREATE TRIGGER IF NOT EXISTS addresses_are_append_only\n BEFORE DELETE ON addresses\n BEGIN\n SELECT RAISE(ABORT, 'the addressing ledger never deletes an address (387 D-04)');\n END`,\n `CREATE TRIGGER IF NOT EXISTS addresses_are_immutable\n BEFORE UPDATE ON addresses\n BEGIN\n SELECT RAISE(ABORT, 'a minted address never changes (387 D-04)');\n END`,\n // Renames live in their OWN table rather than as a nullable column on `addresses`, and the\n // reason is the trigger directly above: a rename is a fact recorded LATER about a row that\n // must never change, so writing it onto the address row would require exactly the statement\n // this ledger forbids. Additive, and the stamped version does not move — nothing between\n // this milestone's releases has written a v1 file, and `IF NOT EXISTS` heals a development\n // one. D-04's never-rebuild law is about ORDINALS, which no statement here touches.\n `CREATE TABLE IF NOT EXISTS target_renames (\n from_slug TEXT NOT NULL PRIMARY KEY,\n to_slug TEXT NOT NULL,\n recorded_at TEXT NOT NULL\n )`,\n] as const\n\nexport interface OpenAddressingLedgerOptions {\n /** Absolute path to the ledger file, typically `<agentQaRoot>/entity-addresses.db`. */\n readonly path: string\n /** ISO-8601 stamp source. Injected so mint times are deterministic under test. */\n readonly now?: () => string\n readonly timeoutMs?: number\n}\n\nfunction toNumber(value: unknown): number {\n return typeof value === 'bigint' ? Number(value) : Number(value)\n}\n\nfunction rowToAddress(row: Record<string, unknown>): EntityAddress {\n const ordinal = row.ordinal\n return {\n kind: String(row.kind) as EntityKind,\n machineId: String(row.machine_id),\n ...(ordinal === null || ordinal === undefined ? {} : { ordinal: toNumber(ordinal) }),\n shortId: String(row.short_id),\n mintedAt: String(row.minted_at),\n }\n}\n\nexport function openAddressingLedger(options: OpenAddressingLedgerOptions): AddressingLedger {\n const now = options.now ?? (() => new Date().toISOString())\n\n mkdirSync(dirname(options.path), { recursive: true })\n const db = new DatabaseSync(options.path, {\n timeout: options.timeoutMs ?? ADDRESSING_LEDGER_BUSY_TIMEOUT_MS,\n })\n db.exec('PRAGMA journal_mode=WAL')\n\n // Read BEFORE any schema statement runs, so a file this build cannot read is not touched on\n // its way to being refused. A hard fail that had already created a table would be a\n // migration nobody wrote — against the one store in the system that must never be rewritten.\n const stamped = toNumber(db.prepare('PRAGMA user_version').get()?.user_version)\n if (stamped !== 0 && stamped !== ADDRESSING_LEDGER_USER_VERSION) {\n db.close()\n throw new AddressingLedgerSchemaVersionError(\n options.path,\n ADDRESSING_LEDGER_USER_VERSION,\n stamped,\n )\n }\n for (const statement of SCHEMA_STATEMENTS) db.exec(statement)\n if (stamped === 0) {\n db.exec(`PRAGMA user_version=${String(ADDRESSING_LEDGER_USER_VERSION)}`)\n }\n\n // Every statement is parameterized. No SQL in this file is built by concatenating a caller's\n // string, and the two `PRAGMA` statements above are the only interpolations — both of pinned\n // integer constants declared in this module (T-387-01-01).\n const insertAddress = db.prepare(\n `INSERT INTO addresses (kind, machine_id, ordinal, short_id, minted_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT (kind, machine_id) DO NOTHING`,\n )\n const selectByKey = db.prepare(\n 'SELECT * FROM addresses WHERE kind = ? AND machine_id = ?',\n )\n const selectByShortId = db.prepare('SELECT * FROM addresses WHERE short_id = ?')\n const selectAll = db.prepare('SELECT * FROM addresses ORDER BY kind, short_id')\n const selectNextOrdinal = db.prepare(\n 'SELECT COALESCE(MAX(ordinal), 0) + 1 AS next FROM addresses WHERE kind = ?',\n )\n const insertRename = db.prepare(\n `INSERT INTO target_renames (from_slug, to_slug, recorded_at)\n VALUES (?, ?, ?)\n ON CONFLICT (from_slug) DO NOTHING`,\n )\n const selectRename = db.prepare('SELECT * FROM target_renames WHERE from_slug = ?')\n\n function inTransaction<T>(body: () => T): T {\n db.exec('BEGIN IMMEDIATE')\n try {\n const result = body()\n db.exec('COMMIT')\n return result\n } catch (error) {\n if (db.isTransaction) db.exec('ROLLBACK')\n throw error\n }\n }\n\n function readBack(kind: EntityKind, machineId: string): EntityAddress {\n const row = selectByKey.get(kind, machineId)\n if (row === undefined) {\n // Unreachable through the insert-then-read sequence below, and stated as a refusal\n // rather than a non-null assertion because the alternative is a silent `undefined`\n // travelling out as an address.\n throw new Error(`the addressing ledger lost the row it just wrote: ${kind} ${machineId}`)\n }\n return rowToAddress(row)\n }\n\n function readRename(fromSlug: string): TargetRename | undefined {\n const row = selectRename.get(fromSlug)\n return row === undefined\n ? undefined\n : {\n fromSlug: String(row.from_slug),\n toSlug: String(row.to_slug),\n recordedAt: String(row.recorded_at),\n }\n }\n\n function mintAddress(kind: EntityKind, machineId: string): EntityAddress {\n if (machineId.trim() === '') {\n throw new TypeError(`an empty machine id has no ${kind} address`)\n }\n\n if (isSlugAddressedKind(kind)) {\n // No ordinal to compute, so no read-modify-write and nothing to serialise: the unique\n // index alone makes this idempotent and race-safe.\n insertAddress.run(kind, machineId, null, formatSlugShortId(kind, machineId), now())\n return readBack(kind, machineId)\n }\n\n return inTransaction(() => {\n // `BEGIN IMMEDIATE` rather than a deferred begin: the next ordinal is read and then\n // written, and a second writer allowed in between would compute the same number. The\n // write lock is taken at BEGIN, so it cannot be.\n //\n // ONE mechanism decides the outcome, deliberately. An earlier draft also short-circuited\n // on an in-transaction pre-read of the existing row, and mutation probes found the pair\n // MUTUALLY MASKING: removing either one alone left every case green, so neither was\n // pinned by anything and a later edit could have deleted the one that mattered without a\n // single test noticing. What is left is the insert itself — a conflict on\n // `(kind, machine_id)` writes nothing — followed by an unconditional read-back.\n const next = toNumber(selectNextOrdinal.get(kind)?.next)\n insertAddress.run(kind, machineId, next, formatOrdinalShortId(kind, next), now())\n // Read back rather than returning what was computed. On the losing side of a race — and\n // on a plain second call in this process — the insert affected no rows, so the answer is\n // the WINNER's ordinal and never this caller's candidate. The candidate is simply\n // discarded: nothing consumed it, so the next distinct machine id still receives it.\n return readBack(kind, machineId)\n })\n }\n\n return {\n close() {\n db.close()\n },\n\n mint: mintAddress,\n\n lookup(kind, machineId) {\n const row = selectByKey.get(kind, machineId)\n return row === undefined ? undefined : rowToAddress(row)\n },\n\n lookupByShortId(shortId) {\n const row = selectByShortId.get(shortId)\n return row === undefined ? undefined : rowToAddress(row)\n },\n\n listAddresses() {\n return selectAll.all().map(rowToAddress)\n },\n\n recordTargetRename(fromSlug, toSlug) {\n if (fromSlug === toSlug) {\n throw new TypeError('a target rename names two different slugs')\n }\n // Both ends minted BEFORE the link is written, so a recorded rename can never point at\n // a slug that has no address of its own.\n mintAddress('TGT', fromSlug)\n mintAddress('TGT', toSlug)\n insertRename.run(fromSlug, toSlug, now())\n const recorded = readRename(fromSlug)\n if (recorded === undefined) {\n throw new Error(`the addressing ledger lost the rename it just wrote: ${fromSlug}`)\n }\n return recorded\n },\n\n lookupTargetRename: readRename,\n }\n}\n","// The entity resolver's tier ladder (Phase 387, ENTY-01 / D-01 / D-07 / D-09).\n//\n// (a) EXACT — an anchored address parse plus a ledger hit, or an exact machine-id\n// sighting. Deterministic, no ranking, no model, score 1.0. THIS FILE.\n// (b) a strong hit over the hybrid entity index, and\n// (c) a top-3 disambiguation set — both in `hybrid.ts`, reached only from the ONE place\n// tier (a) admits it cannot answer exactly.\n//\n// The order is fixed and the fall-through is deliberately narrow. Only free text that matched\n// no address and no machine id reaches the fuzzy tiers; a well-formed address that names\n// nothing stops HERE with `unknown-address`, because answering an address with whatever text\n// happened to rank is the silent guess this whole mechanism exists to prevent. ENTY-01 names\n// mis-linking a failing run to the wrong entity as the QA hazard, and a resolver that answered\n// \"probably that one\" would have shipped exactly that hazard behind a confident-looking card.\n//\n// Nothing in this file consults a model, a clock-dependent ordering, or any nondeterministic\n// tie-break, and tier (b) inherits the same discipline: two calls over the same ledger, the\n// same sources and the same projection answer identically.\n//\n// D-01's lazy mint lives here: an entity gets its permanent address the first time something\n// SIGHTS it, which is this function. No creation path anywhere calls the ledger.\n\nimport {\n ENTITY_EXACT_MATCH_SCORE,\n canonicalShortId,\n formatEntityUri,\n parseEntityUri,\n parseShortId,\n} from '@vostride/agent-qa-schema'\nimport type { EntityDescriptor, EntityKind, EntityResolution } from '@vostride/agent-qa-schema'\n\nimport type { AddressingLedger } from '../addressing/ledger.js'\nimport type { EmbedderPort } from '../embedder-port.js'\nimport { refreshEntity, type EntityIndexHandle } from '../entity-index/entity-index.js'\nimport { resolveHybrid } from './hybrid.js'\n\n/**\n * One store's answer to \"do you own an entity with exactly this machine id?\".\n *\n * A port rather than a switch over kinds, because each kind's machine ids live behind a\n * different store and the tracer wires only one of them. 387-03 adds sources for the\n * remaining kinds and neither this function nor its callers change.\n */\nexport interface EntitySightingSource {\n readonly kind: EntityKind\n /** The entity with this exact machine id, or `undefined`. Never a fuzzy match. */\n sight(machineId: string): EntitySighting | undefined\n /** The entity a minted address maps back to, for rendering a ledger hit. */\n hydrate(machineId: string): EntitySighting | undefined\n}\n\n/** What a store reports about one of its entities. Facts only — no card, no address. */\nexport interface EntitySighting {\n readonly machineId: string\n readonly title: string\n /**\n * The status as the OWNING store reports it. Validated against the kind's closed union at\n * the card boundary (D-12), not here: this layer reports, the producer renders, and the\n * schema refuses. Three responsibilities, three places.\n */\n readonly statusSource: string\n}\n\nexport interface ResolveEntityRefDeps {\n readonly ledger: AddressingLedger\n readonly sources: readonly EntitySightingSource[]\n /**\n * The D-06 projection, maintained by USE.\n *\n * Optional, and that is the degradation ladder rather than a convenience: a composition that\n * supplies no index gets tier (a) and the honest `none` arm, which is exactly what 387-01\n * shipped. Nothing here silently becomes a guess when the projection is absent.\n */\n readonly entityIndex?: EntityIndexHandle\n /** Test/integration seam for tier (b)'s dense leg; omission runs the acquisition ladder. */\n readonly embedder?: EmbedderPort\n}\n\nfunction describe(\n kind: EntityKind,\n shortId: string,\n sighting: EntitySighting,\n deps: ResolveEntityRefDeps,\n): EntityDescriptor {\n // Read at describe time rather than carried on the sighting, because a rename is a fact the\n // LEDGER holds and the owning store does not: the config that named the target has already\n // forgotten the old slug by the time anybody resolves it, which is exactly why the rename\n // had to be recorded (D-03).\n const successor = deps.ledger.lookupTargetRename(sighting.machineId)\n return {\n kind,\n shortId,\n uri: formatEntityUri(kind, shortId),\n machineId: sighting.machineId,\n title: sighting.title,\n statusSource: sighting.statusSource,\n ...(kind === 'TGT' && successor !== undefined\n ? { successorMachineId: successor.toSlug }\n : {}),\n }\n}\n\n/**\n * Project a sighted entity into the index and hand the descriptor back (D-01 + D-06).\n *\n * The four sighting sites D-01 names — a resolver hit, a card render, verdict authoring, a\n * list verb — all reach the ledger through THIS function, so routing the projection refresh\n * here makes the index maintained by the same act that mints. There is no separate\n * \"index an entity\" call anybody has to remember, and therefore no drift between what has an\n * address and what can be found by name.\n *\n * A failure to project is deliberately not fatal. The index is disposable and a rebuild heals\n * it; refusing to resolve an entity because its projection could not be written would let a\n * disposable file take down the durable answer.\n */\nfunction sighted(descriptor: EntityDescriptor, deps: ResolveEntityRefDeps): EntityDescriptor {\n if (deps.entityIndex === undefined) return descriptor\n try {\n refreshEntity(deps.entityIndex, descriptor)\n } catch {\n // Projection is best-effort; the ledger already answered.\n }\n return descriptor\n}\n\nfunction sourceFor(\n sources: readonly EntitySightingSource[],\n kind: EntityKind,\n): EntitySightingSource | undefined {\n return sources.find((source) => source.kind === kind)\n}\n\n/**\n * Resolve one already-minted address, or say why it does not resolve.\n *\n * Shared by the short-ID arm and the URI arm so the two spellings of one address cannot\n * diverge — the URI leg canonicalises to a short-ID and then joins this path, rather than\n * running a second, parallel lookup that could drift.\n */\nfunction resolveMintedAddress(\n shortId: string,\n kind: EntityKind,\n deps: ResolveEntityRefDeps,\n): EntityResolution {\n const address = deps.ledger.lookupByShortId(shortId)\n if (address === undefined) return { kind: 'none', reason: 'unknown-address' }\n\n const source = sourceFor(deps.sources, kind)\n const sighting = source?.hydrate(address.machineId)\n if (sighting === undefined) {\n // D-04's honest-status half is 387-07's: a permanent address whose entity is gone must\n // still resolve, to a card whose status says what happened. Until that landing this build\n // says it cannot describe the entity rather than inventing a status for it. It never\n // reports the address as unknown — the address IS known, and saying otherwise would be\n // the dead link D-04 forbids.\n return { kind: 'none', reason: 'unknown-address', closestSuggestion: address.shortId }\n }\n\n return {\n kind: 'resolved',\n descriptor: sighted(describe(kind, address.shortId, sighting, deps), deps),\n score: ENTITY_EXACT_MATCH_SCORE,\n }\n}\n\n/**\n * Every entity the ledger has ever addressed and a source can still describe.\n *\n * This is the set `rebuildEntityIndex` is rebuilt FROM and the set the daemon sweep re-renders\n * (D-06). It reads the LEDGER, never the index: a projection rebuilt from itself would\n * preserve exactly the state a rebuild is run to be rid of.\n *\n * An address whose source can no longer describe it is skipped rather than projected as a\n * husk. The address keeps resolving through tier (a) either way — D-04's permanence lives in\n * the ledger — but a row with no title is not something fuzzy text should ever match.\n */\nexport function describeAllEntities(deps: ResolveEntityRefDeps): EntityDescriptor[] {\n return deps.ledger.listAddresses().flatMap((address) => {\n const sighting = sourceFor(deps.sources, address.kind)?.hydrate(address.machineId)\n return sighting === undefined\n ? []\n : [describe(address.kind, address.shortId, sighting, deps)]\n })\n}\n\n/**\n * THE sighting leg (D-01): exact machine-id equality, mint, project, describe.\n *\n * Extracted so the resolver's own leg and the LIST VERBS' sighting site are one mechanism\n * rather than two that mint the same way today. D-01 names four sighting sites — a resolver\n * hit, a card render, verdict authoring, a list verb — and a second minting path written for\n * the fourth would be a second place where \"first sighting mints\" could stop being true, with\n * nothing comparing them.\n *\n * `undefined` means no registered source recognises the id at all.\n *\n * EXACT equality, always. A prefix or case-insensitive comparison here would be tier (b)\n * smuggled in below the never-guess contract. Sources are consulted in registered order so\n * the answer does not depend on iteration accidents.\n */\nexport function sightEntity(\n machineId: string,\n deps: ResolveEntityRefDeps,\n): EntityResolution | undefined {\n for (const source of deps.sources) {\n const sighting = source.sight(machineId)\n if (sighting === undefined) continue\n // First sighting mints (D-01). Idempotent in the ledger, so a re-sighting returns the\n // address that is already published rather than a second one.\n const address = deps.ledger.mint(source.kind, sighting.machineId)\n return {\n kind: 'resolved',\n descriptor: sighted(describe(source.kind, address.shortId, sighting, deps), deps),\n score: ENTITY_EXACT_MATCH_SCORE,\n }\n }\n return undefined\n}\n\n/**\n * Resolve a reference through the three tiers, minting on first sighting (D-01).\n *\n * Order matters and is fixed: URI, then short-ID, then exact machine id, then — for free text\n * only — the hybrid tiers. Addresses are tried before machine ids because an address is\n * unambiguous by construction, and a machine id that happened to LOOK like a short-ID would\n * otherwise be able to shadow a published address.\n *\n * ASYNC because tier (b)'s dense leg is: an embedding query cannot be made synchronous, and\n * the alternative — a second, synchronous entry that quietly answers with tier (a) only —\n * would be a resolver that under-answers depending on which function a caller happened to\n * import. The PORT this reaches surfaces through was already asynchronous, so no composition\n * edge changes shape.\n */\nexport async function resolveEntityRef(\n ref: string,\n deps: ResolveEntityRefDeps,\n): Promise<EntityResolution> {\n const trimmed = ref.trim()\n if (trimmed === '') return { kind: 'none', reason: 'no-match' }\n\n const uri = parseEntityUri(trimmed)\n if (uri !== undefined) return resolveMintedAddress(uri.shortId, uri.kind, deps)\n\n const shortId = parseShortId(trimmed)\n if (shortId !== undefined) {\n const canonical = canonicalShortId(trimmed)\n if (canonical !== undefined) return resolveMintedAddress(canonical, shortId.kind, deps)\n }\n\n // The sighting leg, which the list verbs also reach directly (387 D-01).\n const sightedOutcome = sightEntity(trimmed, deps)\n if (sightedOutcome !== undefined) return sightedOutcome\n\n // THE fall-through, and the only one. Free text that matched no address and no machine id\n // is what tiers (b)/(c) exist for; with no projection bound this stays the honest miss that\n // 387-01 shipped, rather than becoming a guess the moment a dependency is optional.\n if (deps.entityIndex === undefined) return { kind: 'none', reason: 'no-match' }\n return resolveHybrid(trimmed, {\n index: deps.entityIndex,\n // The LEDGER describes the winner, never the projection: a disposable index may hold a\n // stale row, and a stale title in front of a user is the failure D-06 keeps it out of.\n describe: (candidateShortId) => {\n const candidateKind = parseShortId(candidateShortId)?.kind\n if (candidateKind === undefined) return undefined\n const outcome = resolveMintedAddress(candidateShortId, candidateKind, deps)\n return outcome.kind === 'resolved' ? outcome.descriptor : undefined\n },\n ...(deps.embedder === undefined ? {} : { embedder: deps.embedder }),\n })\n}\n\n/**\n * `entities.get`'s read path: the descriptor for an EXACT address, or `undefined`.\n *\n * Deliberately narrower than `resolveEntityRef` — it neither mints nor consults the sighting\n * leg. `get` means \"I already have the address\", and a `get` that could mint would make every\n * card render a potential write.\n */\nexport function getEntityDescriptor(\n ref: string,\n deps: ResolveEntityRefDeps,\n): EntityDescriptor | undefined {\n const trimmed = ref.trim()\n const uri = parseEntityUri(trimmed)\n const shortId = uri?.shortId ?? canonicalShortId(trimmed)\n const kind = uri?.kind ?? parseShortId(trimmed)?.kind\n if (shortId === undefined || kind === undefined) return undefined\n\n // Reaches `resolveMintedAddress`, never the sighting leg, so no `get` can mint.\n const outcome = resolveMintedAddress(shortId, kind, deps)\n return outcome.kind === 'resolved' ? outcome.descriptor : undefined\n}\n","// The entity index: a rebuildable projection of the addressing ledger (Phase 387, D-06).\n//\n// WHY THIS IS A RECORDS-SHAPED DATABASE IN ITS OWN FILE\n//\n// D-05 says tier (b) of the resolver is the memidex hybrid pipeline — not a second scoring\n// engine, not fuse.js. `lexicalLeg` and `denseLeg` are the pipeline, and both are written\n// against a fixed projection shape: an FTS5 table joined to a row table carrying scope, status\n// and embedding columns. Reusing them therefore means presenting that shape, which is what\n// this module builds. The alternative — entity-shaped tables plus a hand-rolled BM25/cosine\n// query beside them — would have been a second scoring engine wearing a different name, and\n// the degradation ladder, the admission floors and the FTS escaping would all have had to be\n// rebuilt with it.\n//\n// The separation Pitfall 6 demands is achieved by the FILE, not by the table names. This\n// database lives beside the knowledge index and shares nothing with it: no statement here\n// resolves, opens or writes `knowledge.db`, and the projection tables inside this file are\n// reachable only through a handle opened from `entityIndexDbPath`. An entity therefore cannot\n// be served as a learned fact, because the serving reader opens a different file entirely —\n// asserted directly, with a positive control, in this module's suite.\n//\n// WHY THE DENSE RUNG IS ALWAYS BRUTE\n//\n// `denseVec0` refuses to answer unless the database carries the records index's private\n// vec-cleanup epoch marker, whose value is a module-private constant of `index-open.ts`.\n// Stamping it from here would be a second, unpinned spelling of somebody else's invariant —\n// exactly the drift the projection law exists to avoid — and RESEARCH A3 resolved that the\n// per-profile vec bookkeeping stays untouched. The entity corpus is bounded by the number of\n// things a human can name, where a brute cosine scan costs nothing worth optimising. So the\n// connection pins `brute` on every host, and no `vec0` virtual table is ever created here.\n//\n// WHY IT MAY BE DESTROYED AT WILL\n//\n// Every row is derived from the addressing ledger plus the owning stores. The ledger is the\n// one durable truth (D-02) and is never rebuilt; this file is disposable, and a full rebuild\n// heals arbitrary damage — deleted rows, a corrupted rendering, an orphaned FTS entry.\n\nimport { mkdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nimport {\n DEFAULT_EMBEDDING_PROFILE,\n type EmbeddingProfile,\n type EntityDescriptor,\n type EntityKind,\n} from '@vostride/agent-qa-schema'\n\nimport type { EmbedderPort } from '../embedder-port.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport {\n embeddingProfileKey,\n resolveActiveProfile,\n type IndexReaderConnection,\n} from '../index-open.js'\nimport type { RetrievalLegScope } from '../retrieval/legs.js'\nimport { renderEntity, type EntityRendering } from './renderings.js'\n\n/**\n * The projection's own file name, beside the knowledge index rather than inside it.\n *\n * Beside, because an entity is not a learned fact (D-06). Its own file, because the knowledge\n * index's schema version, rebuild and per-profile vec bookkeeping belong to records, and\n * sharing them would have coupled two projections whose only similarity is their shape.\n */\nexport const ENTITY_INDEX_DB_FILE = 'entity-index.db'\n\n/**\n * Stamped into `PRAGMA user_version` at creation and checked on every open.\n *\n * Stamp and hard-fail, never migrate — the 385 D-04 house style. Migration would be effort\n * spent on a file whose contents can be regenerated in full from the ledger; a refusal that\n * says which version it found is more useful than a migration nobody would maintain.\n */\nexport const ENTITY_INDEX_USER_VERSION = 2\n\n/** Busy timeout in milliseconds; the projection is written at a human-paced grain. */\nexport const ENTITY_INDEX_BUSY_TIMEOUT_MS = 2000\n\n/**\n * How often a standing daemon re-renders the projection from its sources (D-06).\n *\n * PROVISIONAL 600_000 (ten minutes); retune from operational evidence without adding config,\n * the `LEASE_HEARTBEAT_TTL_MS` house style. What it is bounding is STALENESS of a title or a\n * status in a fuzzy-match target — never correctness of an address, which the ledger owns and\n * no cadence can affect. Sightings already refresh an entity the moment anything touches it,\n * so this sweep exists for the entities nothing has touched since their source data moved.\n *\n * Deliberately its own interval rather than the daemon's `MAINTENANCE_CADENCE_MS`. That\n * cadence runs the lease-holding maintenance tail; this sweep must never require the writer\n * lease (D-02/D-06) because it writes only this file, and sharing a timer with lease-gated\n * work would have made a lease-free projection stop being maintained the moment a lease was\n * lost — a coupling nothing in the projection's own contract asks for.\n */\nexport const ENTITY_INDEX_SWEEP_INTERVAL_MS = 600_000\n\n/**\n * The single partition every entity row lives in.\n *\n * The retrieval legs enforce a product/scope tenancy wall on every scan. This projection has\n * exactly one tenant, so the wall is satisfied by one pinned partition rather than disabled —\n * a predicate that is always true is a predicate nobody notices has stopped applying.\n */\nexport const ENTITY_INDEX_PRODUCT = 'agentqa-entities'\n\n/** The one scope key every entity row carries; entities are global by construction. */\nexport const ENTITY_INDEX_SCOPE_KEY = 'scope:entities'\n\n/**\n * The projection's row state, which is NOT the entity's status.\n *\n * The scope predicate excludes `deprecated`/`superseded` rows from every scan. An entity that\n * a store reports as quarantined or tombstoned is still a nameable thing that must resolve\n * (D-04), so its row stays admissible and the store's own word lives in `status_source`.\n */\nconst ENTITY_INDEX_ROW_STATUS = 'active'\n\n/** Rows are derived, never authored: the closest origin the records vocabulary offers. */\nconst ENTITY_INDEX_ORIGIN_CLASS = 'import'\n\n/** The scope every entity query binds. One tenant, one key, four bindings. */\nexport const ENTITY_INDEX_SCOPE = {\n product: ENTITY_INDEX_PRODUCT,\n testKey: ENTITY_INDEX_SCOPE_KEY,\n suiteKey: ENTITY_INDEX_SCOPE_KEY,\n productKey: ENTITY_INDEX_SCOPE_KEY,\n globalKey: ENTITY_INDEX_SCOPE_KEY,\n} as const satisfies RetrievalLegScope\n\nexport class EntityIndexSchemaVersionError extends Error {\n readonly path: string\n readonly supportedVersion: number\n readonly foundVersion: number\n\n constructor(path: string, supportedVersion: number, foundVersion: number) {\n super(\n `entity index ${path} is stamped at version ${foundVersion}; this build reads ${supportedVersion}. `\n + 'The entity index is a disposable projection: delete the file and it rebuilds.',\n )\n this.name = 'EntityIndexSchemaVersionError'\n this.path = path\n this.supportedVersion = supportedVersion\n this.foundVersion = foundVersion\n }\n}\n\n/**\n * The projection shape the retrieval legs read.\n *\n * Column-for-column what `lexicalLeg`/`denseLeg` select, plus the descriptor columns that let\n * a row be read back as the entity it came from. The FTS tokenizer is copied verbatim from\n * the records index so `MEM-001` and `agentqa://memory/MEM-001` stay single tokens here too —\n * an address that tokenised differently in the two indexes would match differently, and the\n * two would disagree about what an exact handle is.\n */\nconst SCHEMA_STATEMENTS = [\n `CREATE TABLE IF NOT EXISTS records (\n record_rowid INTEGER PRIMARY KEY,\n bundle_id TEXT NOT NULL UNIQUE,\n product TEXT NOT NULL,\n kind TEXT NOT NULL,\n subtype TEXT,\n scope_tier TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n status TEXT NOT NULL,\n trust REAL NOT NULL,\n opened_at_ordinal REAL NOT NULL,\n closed_at_ordinal REAL,\n created_at_ordinal REAL NOT NULL,\n origin_class TEXT NOT NULL,\n summary TEXT NOT NULL,\n embedding_input TEXT NOT NULL,\n embed_status TEXT NOT NULL DEFAULT 'pending',\n embedding BLOB,\n entity_kind TEXT NOT NULL,\n machine_id TEXT NOT NULL,\n uri TEXT NOT NULL,\n title TEXT NOT NULL,\n status_source TEXT NOT NULL,\n successor_machine_id TEXT\n )`,\n `CREATE VIRTUAL TABLE IF NOT EXISTS fts_records USING fts5(\n identity,\n content,\n context,\n tokenize = \"unicode61 tokenchars '#-_./:[]=>@'\"\n )`,\n `CREATE TABLE IF NOT EXISTS meta (\n k TEXT PRIMARY KEY,\n v TEXT NOT NULL\n )`,\n] as const\n\nexport interface EntityIndexHandle {\n /** The connection shape the retrieval legs take. `vec` is pinned `brute` — see the header. */\n readonly connection: IndexReaderConnection\n readonly path: string\n close(): void\n}\n\nexport interface OpenEntityIndexOptions {\n /** Absolute path to the projection file, typically `entityIndexDbPath(knowledgeRoot)`. */\n readonly path: string\n /**\n * The knowledge root the path lives under. When given, the path's directory chain must stay\n * inside it (261003-mqc): a linked `memory/` or `memory/index/` is refused before the open.\n */\n readonly knowledgeRoot?: string\n readonly timeoutMs?: number\n}\n\n/** The projection's path: beside the knowledge index, never inside it. */\nexport function entityIndexDbPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, 'memory', 'index', ENTITY_INDEX_DB_FILE)\n}\n\nfunction toNumber(value: unknown): number {\n return typeof value === 'bigint' ? Number(value) : Number(value)\n}\n\nexport function openEntityIndex(options: OpenEntityIndexOptions): EntityIndexHandle {\n if (options.knowledgeRoot !== undefined) {\n assertWithinKnowledgeRoot(options.knowledgeRoot, dirname(options.path))\n }\n mkdirSync(dirname(options.path), { recursive: true })\n const db = new DatabaseSync(options.path, {\n timeout: options.timeoutMs ?? ENTITY_INDEX_BUSY_TIMEOUT_MS,\n })\n db.exec('PRAGMA journal_mode=WAL')\n\n const stamped = toNumber(db.prepare('PRAGMA user_version').get()?.user_version)\n if (stamped !== 0 && stamped !== ENTITY_INDEX_USER_VERSION) {\n db.close()\n throw new EntityIndexSchemaVersionError(\n options.path,\n ENTITY_INDEX_USER_VERSION,\n stamped,\n )\n }\n for (const statement of SCHEMA_STATEMENTS) db.exec(statement)\n if (stamped === 0) db.exec(`PRAGMA user_version = ${ENTITY_INDEX_USER_VERSION}`)\n\n return {\n connection: { db, vec: 'brute' },\n path: options.path,\n close(): void {\n db.close()\n },\n }\n}\n\nfunction immediateTransaction(db: DatabaseSync, operation: () => void): void {\n db.exec('BEGIN IMMEDIATE')\n try {\n operation()\n db.exec('COMMIT')\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the write error that caused the rollback.\n }\n throw error\n }\n}\n\nfunction writeFtsRow(\n db: DatabaseSync,\n recordRowid: number,\n rendering: EntityRendering,\n): void {\n db.prepare('DELETE FROM fts_records WHERE rowid = ?').run(recordRowid)\n db.prepare(`\n INSERT INTO fts_records (rowid, identity, content, context)\n VALUES (?, ?, ?, ?)\n `).run(recordRowid, rendering.identity, rendering.content, rendering.context)\n}\n\nfunction upsertEntityRow(db: DatabaseSync, descriptor: EntityDescriptor): void {\n const rendering = renderEntity(descriptor)\n const existing = db.prepare(`\n SELECT record_rowid, embedding_input FROM records WHERE bundle_id = ?\n `).get(descriptor.shortId)\n\n if (existing === undefined) {\n const inserted = db.prepare(`\n INSERT INTO records (\n bundle_id, product, kind, subtype,\n scope_tier, scope_key, status, trust,\n opened_at_ordinal, closed_at_ordinal, created_at_ordinal,\n origin_class, summary, embedding_input,\n embed_status, embedding,\n entity_kind, machine_id, uri, title, status_source, successor_machine_id\n ) VALUES (\n ?, ?, ?, NULL,\n 'global', ?, ?, 1,\n 0, NULL, 0,\n ?, ?, ?,\n 'pending', NULL,\n ?, ?, ?, ?, ?, ?\n )\n `).run(\n descriptor.shortId,\n ENTITY_INDEX_PRODUCT,\n descriptor.kind,\n ENTITY_INDEX_SCOPE_KEY,\n ENTITY_INDEX_ROW_STATUS,\n ENTITY_INDEX_ORIGIN_CLASS,\n rendering.content,\n rendering.embedding,\n descriptor.kind,\n descriptor.machineId,\n descriptor.uri,\n descriptor.title,\n descriptor.statusSource,\n descriptor.successorMachineId ?? null,\n )\n writeFtsRow(db, Number(inserted.lastInsertRowid), rendering)\n return\n }\n\n const recordRowid = toNumber(existing.record_rowid)\n // The embedding is dropped exactly when the text it was computed FROM changed. Keeping it\n // across an unrelated edit is the difference between a maintenance sweep that costs a read\n // and one that re-embeds the whole corpus every time a status moves.\n const embeddingStale = String(existing.embedding_input) !== rendering.embedding\n db.prepare(`\n UPDATE records SET\n kind = ?, summary = ?, embedding_input = ?,\n entity_kind = ?, machine_id = ?, uri = ?, title = ?, status_source = ?,\n successor_machine_id = ?\n ${embeddingStale ? \", embedding = NULL, embed_status = 'pending'\" : ''}\n WHERE record_rowid = ?\n `).run(\n descriptor.kind,\n rendering.content,\n rendering.embedding,\n descriptor.kind,\n descriptor.machineId,\n descriptor.uri,\n descriptor.title,\n descriptor.statusSource,\n descriptor.successorMachineId ?? null,\n recordRowid,\n )\n writeFtsRow(db, recordRowid, rendering)\n}\n\n/**\n * Project one entity into the index (D-06's incremental half).\n *\n * Called from the resolver's sighting/mint path, so every process posture — daemon, one-shot\n * CLI, a test harness — maintains the projection by using it. Idempotent: re-projecting an\n * unchanged entity leaves the same row.\n */\nexport function refreshEntity(handle: EntityIndexHandle, descriptor: EntityDescriptor): void {\n immediateTransaction(handle.connection.db, () => {\n upsertEntityRow(handle.connection.db, descriptor)\n })\n}\n\n/**\n * Drop everything and re-project from the supplied descriptor set (D-06's healing half).\n *\n * The set comes from the ledger plus the owning stores, which is what makes this a rebuild\n * rather than a repair: nothing in this file is consulted to produce the new contents, so a\n * file damaged in any way at all converges to the same result as a file that never existed.\n * Embeddings are re-derived rather than carried, because a rebuild that preserved derived\n * bytes would preserve exactly the state a rebuild is run to be rid of.\n */\nexport function rebuildEntityIndex(\n handle: EntityIndexHandle,\n descriptors: Iterable<EntityDescriptor>,\n): number {\n const { db } = handle.connection\n let projected = 0\n immediateTransaction(db, () => {\n db.exec('DELETE FROM fts_records')\n db.exec('DELETE FROM records')\n for (const descriptor of descriptors) {\n upsertEntityRow(db, descriptor)\n projected += 1\n }\n })\n return projected\n}\n\nexport interface EntityIndexSweepReport {\n readonly examined: number\n readonly refreshed: number\n}\n\n/**\n * Re-project the entities whose source data moved (D-06's maintenance-cadence half).\n *\n * A sweep is maintenance of a disposable projection, so it writes only where a row disagrees\n * with its source. It never touches the addressing ledger — the ledger is not a projection\n * (D-02) — and it takes no writer lease, because everything it writes lives in this file.\n */\nexport function sweepEntityIndex(\n handle: EntityIndexHandle,\n descriptors: Iterable<EntityDescriptor>,\n): EntityIndexSweepReport {\n const { db } = handle.connection\n let examined = 0\n let refreshed = 0\n immediateTransaction(db, () => {\n for (const descriptor of descriptors) {\n examined += 1\n const stored = readEntityDescriptor(handle, descriptor.shortId)\n if (stored !== undefined && descriptorsAgree(stored, descriptor)) continue\n upsertEntityRow(db, descriptor)\n refreshed += 1\n }\n })\n return { examined, refreshed }\n}\n\nfunction descriptorsAgree(left: EntityDescriptor, right: EntityDescriptor): boolean {\n return left.kind === right.kind\n && left.machineId === right.machineId\n && left.uri === right.uri\n && left.title === right.title\n && left.statusSource === right.statusSource\n && left.successorMachineId === right.successorMachineId\n}\n\n/** Read one projected row back as the entity it came from. */\nexport function readEntityDescriptor(\n handle: EntityIndexHandle,\n shortId: string,\n): EntityDescriptor | undefined {\n const row = handle.connection.db.prepare(`\n SELECT bundle_id, entity_kind, machine_id, uri, title, status_source, successor_machine_id\n FROM records WHERE bundle_id = ?\n `).get(shortId)\n if (row === undefined) return undefined\n\n const successor = row.successor_machine_id\n return {\n kind: String(row.entity_kind) as EntityKind,\n shortId: String(row.bundle_id),\n uri: String(row.uri),\n machineId: String(row.machine_id),\n title: String(row.title),\n statusSource: String(row.status_source),\n ...(successor === null || successor === undefined\n ? {}\n : { successorMachineId: String(successor) }),\n }\n}\n\n/** The rendering one projected row currently carries. */\nexport function readEntityRendering(\n handle: EntityIndexHandle,\n shortId: string,\n): EntityRendering | undefined {\n const descriptor = readEntityDescriptor(handle, shortId)\n return descriptor === undefined ? undefined : renderEntity(descriptor)\n}\n\nexport function countEntities(handle: EntityIndexHandle): number {\n return toNumber(handle.connection.db.prepare('SELECT COUNT(*) AS count FROM records').get()?.count)\n}\n\n/**\n * Embed every row whose rendering has no vector yet, returning how many were embedded.\n *\n * Separate from `refreshEntity` on purpose. Projecting an entity is synchronous and always\n * possible; embedding one needs a model that a floor host may not have. Splitting them is what\n * lets the degradation ladder work by omission — an index with no vectors simply serves its\n * lexical leg, and the resolver rides that without a posture flag anywhere.\n *\n * A profile change invalidates every stored vector rather than mixing two geometries in one\n * table, which is the same disposability law the records index applies to its own.\n */\nexport async function embedPendingEntities(\n handle: EntityIndexHandle,\n embedder: EmbedderPort,\n profile: EmbeddingProfile = DEFAULT_EMBEDDING_PROFILE,\n): Promise<number> {\n const { db } = handle.connection\n const key = embeddingProfileKey(profile)\n const stamped = db.prepare(\"SELECT v FROM meta WHERE k = 'embedding_profile'\").get()?.v\n if (stamped !== key) {\n immediateTransaction(db, () => {\n db.exec(\"UPDATE records SET embedding = NULL, embed_status = 'pending'\")\n db.prepare(`\n INSERT INTO meta (k, v) VALUES ('embedding_profile', ?)\n ON CONFLICT(k) DO UPDATE SET v = excluded.v\n `).run(key)\n })\n }\n\n const pending = db.prepare(`\n SELECT record_rowid, embedding_input FROM records\n WHERE embed_status = 'pending' ORDER BY record_rowid\n `).all()\n\n let embedded = 0\n for (const row of pending) {\n const vector = await embedder.embedDocument(String(row.embedding_input))\n if (vector.length !== profile.dim) {\n throw new RangeError(\n `entity embedding has ${vector.length} dimensions; profile ${profile.model_id} declares ${profile.dim}`,\n )\n }\n db.prepare(`\n UPDATE records SET embedding = ?, embed_status = 'present' WHERE record_rowid = ?\n `).run(\n Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength),\n toNumber(row.record_rowid),\n )\n embedded += 1\n }\n return embedded\n}\n\n/** The admission floor the dense leg's candidates are held to, from the stored profile. */\nexport function entityIndexTauDense(handle: EntityIndexHandle): number {\n return resolveActiveProfile(handle.connection.db).tau_dense\n}\n","/**\n * Derived-index SQLite host for IDX-01.\n *\n * D-10 keeps the records.embedding BLOB canonical even when vec0 is unavailable;\n * D-11/D-12 isolate native loading behind a capability flag and test seam; D-13\n * keeps WAL/lock/checkpoint tuning as internal constants. The database lives in\n * the gitignored memory/index partition (Research Pitfall 10), so these derived\n * writes intentionally do not pass through the committed-bundle egress gate.\n */\nimport { existsSync, mkdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\nimport { pathToFileURL } from 'node:url'\n\nimport {\n canonicalJson,\n DEFAULT_EMBEDDING_PROFILE,\n STATIC_FLOOR_EMBEDDING_PROFILE,\n} from '@vostride/agent-qa-schema'\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\n\nimport { assertWithinKnowledgeRoot } from './knowledge-containment.js'\nimport { getLoadablePath } from './sqlite-vec-loadable.js'\n\nexport const INDEX_DB_FILE = 'knowledge.db'\n\n/** Any other stamp resets the index. */\nexport const INDEX_SCHEMA_VERSION = 2\n\n/**\n * Phase 377 D-04 rendering epoch.\n *\n * Bump only when contextual-rendering bytes change. A stale stamp remains durable through writer\n * open, forces one full render/vector pass, and is advanced only when that pass succeeds.\n */\nexport const INDEX_RENDERING_SCHEMA_VERSION = 2\n\n/**\n * One-time derived-embedding invalidation epoch.\n *\n * Epoch 1 records the Phase 376 pre-lock-to-locked repair. The former writer could restamp an\n * index to the locked profile while preserving same-dimension bytes from the old revision, which\n * destroyed the mismatch evidence needed to prove their provenance. An absent or stale epoch\n * therefore forces invalidation before the marker's first upsert in the same transaction; a crash\n * rolls both back and a retry repeats the idempotent transition. Increment only if a future defect\n * again requires every persisted index to perform a one-time full re-embed.\n */\nconst EMBEDDING_TRANSITION_EPOCH = 1\n\n/**\n * Active vec-table cleanup completed by a connection that actually loaded sqlite-vec.\n *\n * This fact is intentionally separate from canonical invalidation. A brute writer can safely\n * disown records.embedding bytes, but it cannot prove or mutate the unloaded virtual table. Every\n * brute writer therefore removes this marker before exposing its mutable connection, and only a\n * vec0 writer may publish it after clearing the active table in the same transaction.\n */\nconst EMBEDDING_VEC_CLEANUP_EPOCH = 1\n\n/**\n * Projection tables every readable index must expose.\n *\n * Per-profile vec tables are deliberately excluded: vec0 is a conditional\n * capability, while operation-time failover and the next rebuild heal a lost\n * capability-specific table.\n */\nexport const REQUIRED_INDEX_TABLES = [\n 'records',\n 'fts_records',\n 'anchors',\n 'graph_nodes',\n 'graph_edges',\n 'meta',\n] as const\n\n/**\n * Writer busy timeout in milliseconds.\n *\n * PROVISIONAL 2000 pending Phase 375 contention measurements. The value may be\n * tuned, but the constant-driven shape remains internal and config-free.\n */\nexport const WRITER_BUSY_TIMEOUT_MS = 2000\n\n/**\n * Reader busy timeout in milliseconds.\n *\n * PROVISIONAL 500 pending Phase 375 contention measurements. The value may be\n * tuned, but the constant-driven shape remains internal and config-free.\n */\nexport const READER_BUSY_TIMEOUT_MS = 500\n\n/**\n * Number of committed bundles between passive WAL checkpoints.\n *\n * PROVISIONAL 32 pending Phase 375 write-volume measurements. The value may be\n * tuned, but the constant-driven shape remains internal and config-free.\n */\nexport const CHECKPOINT_EVERY_N_BUNDLES = 32\n\nexport type VecCapability = 'vec0' | 'brute'\n\nexport interface IndexWriterHandle {\n db: DatabaseSync\n vec: VecCapability\n readonly renderingEpochStale: boolean\n completeRenderingEpoch(): void\n checkpointPassive(): void\n close(): void\n}\n\nexport interface IndexReaderConnection {\n db: DatabaseSync\n vec: VecCapability\n}\n\n/** Durable writer work that can be inspected without opening a mutable index connection. */\nexport interface IndexMaintenanceState {\n indexAbsent: boolean\n pendingEmbeddings: number\n renderingEpochStale: boolean\n vectorReconciliationOutstanding: boolean\n}\n\nexport type IndexHealth =\n | { ok: true }\n | {\n ok: false\n probe: 'quick-check' | 'projection-schema' | 'schema-version'\n reason: string\n }\n\ninterface IndexOpenOptions {\n /** D-12 test seam. Production callers resolve sqlite-vec's pinned prebuild. */\n vecLoadablePath?: string\n}\n\nexport interface IndexReaderOpenOptions extends IndexOpenOptions {\n /**\n * For a probe that only ASKS about the index and releases the connection at once (`doctor`).\n * With no `-wal` beside the database, no connection holds it in WAL mode and the writer's close\n * checkpointed every page into the main file, so the open is `mode=ro&immutable=1` and SQLite\n * creates no `-wal`/`-shm` (432-09 #5). With a `-wal` present the open is the ordinary read-only\n * one, so a live writer's frames are still read. Serving readers never set it.\n */\n inspectCheckpointedImmutably?: boolean\n}\n\nexport function indexDbPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, 'memory', 'index', INDEX_DB_FILE)\n}\n\n/**\n * Inspect bounded durable maintenance facts without bootstrapping, migrating, or restamping.\n *\n * Absence is a valid schedulable state. Once the database exists, malformed or incomplete\n * projection schemas throw so callers cannot mistake an unreadable index for convergence.\n */\nexport function readIndexMaintenanceState(\n knowledgeRoot: string,\n): IndexMaintenanceState {\n const path = indexDbPath(knowledgeRoot)\n if (!existsSync(path)) {\n return {\n indexAbsent: true,\n pendingEmbeddings: 0,\n renderingEpochStale: false,\n vectorReconciliationOutstanding: false,\n }\n }\n\n // The lease-gated writer closes with a truncate checkpoint. Immutable read mode then avoids\n // SQLite creating WAL/SHM sidecars merely to inspect that closed, fully checkpointed database.\n const immutableUri = pathToFileURL(path)\n immutableUri.searchParams.set('mode', 'ro')\n immutableUri.searchParams.set('immutable', '1')\n const db = new DatabaseSync(immutableUri.href, {\n readOnly: true,\n timeout: READER_BUSY_TIMEOUT_MS,\n })\n try {\n db.exec('PRAGMA query_only=1')\n const tableNames = new Set(\n db.prepare(`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (\n 'records',\n 'fts_records',\n 'anchors',\n 'graph_nodes',\n 'graph_edges',\n 'meta'\n )\n `).all().map((row) => String(row.name)),\n )\n const missingTables = REQUIRED_INDEX_TABLES.filter((name) => !tableNames.has(name))\n if (missingTables.length > 0) {\n throw new Error(\n `index maintenance inspection found incomplete schema: ${missingTables.join(', ')}`,\n )\n }\n\n const pendingRow = db\n .prepare(\"SELECT COUNT(*) AS count FROM records WHERE embed_status = 'pending'\")\n .get()\n const pendingEmbeddings = Number(pendingRow?.count)\n if (!Number.isSafeInteger(pendingEmbeddings) || pendingEmbeddings < 0) {\n throw new Error('index maintenance inspection returned an invalid pending count')\n }\n\n const metadata = new Map(\n db.prepare(`\n SELECT k, v\n FROM meta\n WHERE k IN ('rendering_schema_version', 'embedding_vec_cleanup_epoch')\n `).all().map((row) => [String(row.k), String(row.v)]),\n )\n return {\n indexAbsent: false,\n pendingEmbeddings,\n renderingEpochStale:\n metadata.get('rendering_schema_version') !== String(INDEX_RENDERING_SCHEMA_VERSION),\n vectorReconciliationOutstanding:\n metadata.get('embedding_vec_cleanup_epoch') !== String(EMBEDDING_VEC_CLEANUP_EPOCH),\n }\n } finally {\n db.close()\n }\n}\n\nexport function resolveVecCapability(\n db: DatabaseSync,\n loadablePath?: string,\n): VecCapability {\n try {\n db.loadExtension(loadablePath ?? getLoadablePath())\n return 'vec0'\n } catch {\n return 'brute'\n }\n}\n\nexport function vecTableName(profile: EmbeddingProfile): string {\n const identity = `${profile.model_id}_${profile.revision}_${profile.dtype}_${profile.dim}`\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n\n if (identity === '') throw new Error('embedding profile produced an empty vec table identity')\n return `vec_${identity}`\n}\n\n/**\n * The closed set of embedding profiles whose per-profile vec tables belong to this schema.\n *\n * Active-profile resolution, profile migration, and destructive projection maintenance must\n * share this exact authority. Adding a profile therefore cannot silently make an old vec table\n * invisible to forgetting or purge.\n */\nexport const SCHEMA_OWNED_EMBEDDING_PROFILES = [\n DEFAULT_EMBEDDING_PROFILE,\n STATIC_FLOOR_EMBEDDING_PROFILE,\n] as const satisfies readonly EmbeddingProfile[]\n\n/**\n * Enumerate only materialized vec tables derived from the closed schema profile list.\n *\n * sqlite_master is safe to inspect even when this connection could not load sqlite-vec. Names\n * are bound as data, then returned in profile-list order; no caller-controlled identifier reaches\n * the dynamic DELETE statements used by maintenance.\n */\nexport function materializedSchemaVecTableNames(db: DatabaseSync): string[] {\n const schemaNames = SCHEMA_OWNED_EMBEDDING_PROFILES.map(vecTableName)\n const present = new Set(\n db.prepare(`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (?, ?)\n `).all(...schemaNames).map((row) => String(row.name)),\n )\n return schemaNames.filter((name) => present.has(name))\n}\n\n/**\n * Delete one record from every materialized schema-owned vec table, independent of capability.\n *\n * An existing vec0 table on a brute connection is not a valid no-op: preparing its DML fails\n * when sqlite-vec is unavailable. Preserve that failure with table context so the caller's\n * transaction rolls back and no maintenance report or purge receipt can claim partial success.\n */\nexport function deleteRecordFromAllSchemaVecTables(\n db: DatabaseSync,\n recordRowid: number,\n): void {\n for (const tableName of materializedSchemaVecTableNames(db)) {\n try {\n db.prepare(`DELETE FROM ${tableName} WHERE record_rowid = ?`)\n .run(BigInt(recordRowid))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(\n `deleting record ${recordRowid} from schema-owned vec table ${tableName} failed: ${message}`,\n { cause: error },\n )\n }\n }\n}\n\n/** Stable identity persisted in meta and used to select a closed-list profile. */\nexport function embeddingProfileKey(profile: EmbeddingProfile): string {\n return canonicalJson({\n model_id: profile.model_id,\n revision: profile.revision,\n dtype: profile.dtype,\n dim: profile.dim,\n })\n}\n\nfunction readEmbeddingProfileStamp(db: DatabaseSync): string | undefined {\n try {\n const row = db\n .prepare(\"SELECT v FROM meta WHERE k = 'embedding_profile'\")\n .get()\n return typeof row?.v === 'string' ? row.v : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readIndexSchemaVersionStamp(db: DatabaseSync): string | undefined {\n try {\n const row = db\n .prepare(\"SELECT v FROM meta WHERE k = 'index_schema_version'\")\n .get()\n return typeof row?.v === 'string' ? row.v : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readRenderingSchemaVersionStamp(db: DatabaseSync): string | undefined {\n try {\n const row = db\n .prepare(\"SELECT v FROM meta WHERE k = 'rendering_schema_version'\")\n .get()\n return typeof row?.v === 'string' ? row.v : undefined\n } catch {\n return undefined\n }\n}\n\nfunction hasProjectionTables(db: DatabaseSync): boolean {\n const row = db\n .prepare(`\n SELECT 1 AS present\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN ('records', 'fts_records', 'anchors', 'graph_nodes', 'graph_edges', 'meta')\n LIMIT 1\n `)\n .get()\n return row !== undefined\n}\n\nfunction readTransitionEpoch(db: DatabaseSync): string | undefined {\n try {\n const row = db\n .prepare(\"SELECT v FROM meta WHERE k = 'embedding_transition_epoch'\")\n .get()\n return typeof row?.v === 'string' ? row.v : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readVecCleanupEpoch(db: DatabaseSync): string | undefined {\n try {\n const row = db\n .prepare(\"SELECT v FROM meta WHERE k = 'embedding_vec_cleanup_epoch'\")\n .get()\n return typeof row?.v === 'string' ? row.v : undefined\n } catch {\n return undefined\n }\n}\n\n/** Internal dense-reader gate; deliberately absent from the package barrel. */\nexport function isEmbeddingVecCleanupCurrent(db: DatabaseSync): boolean {\n return readVecCleanupEpoch(db) === String(EMBEDDING_VEC_CLEANUP_EPOCH)\n}\n\n/**\n * Resolve the one active profile authority from the derived index's meta stamp.\n *\n * This is RESEARCH Pattern 5 step 1: Plan 07 flips this stamp atomically. D-18\n * keeps M2 selection closed to schema-owned constants, so absent, unknown, or\n * pre-bootstrap metadata always falls back to the ratified default.\n */\nexport function resolveActiveProfile(db: DatabaseSync): EmbeddingProfile {\n const stamp = readEmbeddingProfileStamp(db)\n\n return SCHEMA_OWNED_EMBEDDING_PROFILES.find(\n (profile) => embeddingProfileKey(profile) === stamp,\n )\n ?? DEFAULT_EMBEDDING_PROFILE\n}\n\nfunction bootstrapVecSchema(db: DatabaseSync, activeProfile: EmbeddingProfile): void {\n const tableName = vecTableName(activeProfile)\n db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS ${tableName} USING vec0(\n record_rowid integer primary key,\n product text partition key,\n scope_tier text,\n scope_key text,\n status text,\n embedding float[${activeProfile.dim}] distance_metric=cosine\n );\n `)\n}\n\n/**\n * Run-outcome projection tables (381-05, D-14/D-15).\n *\n * Derived per-test outcome counters and exercised-anchor sets live in this same gitignored\n * index SQLite — one derived-state home, one writer role, no new DB file. Rows carry test\n * identity (product + file_path + test_name) within the folded handoff's raw scope pair,\n * counters, and normalized anchors ONLY; no test file content ever enters the store.\n * `run_outcome_applied_runs` is the per-product/runId idempotency marker that makes\n * refolding a crash-rerun tail safe (receipt-gated at the caller, DB-gated here).\n * `run_fingerprint_windows` (390 D-07/D-09) carries one row per applied FAILED member keyed by\n * the failure fingerprint, which is the substrate the quarantine detection rule windows over.\n * All four tables are disposable: `rebuildRunOutcomes` reproduces them from\n * `.agent-qa/runs/<runId>/handoff.json` (plus each run's `analysis.json`) scans alone (L12).\n * Deliberately absent from REQUIRED_INDEX_TABLES — like the per-profile vec tables, a lost\n * projection heals on the next writer open + rebuild rather than failing health probes.\n * `run_outcome_projection_version` is the singleton stamp that says WHICH fold semantics produced\n * the rows beside it; `reconcileRunOutcomesProjection` compares it against\n * `RUN_OUTCOMES_PROJECTION_VERSION` and rebuilds the family whenever it is absent or differs, so\n * an index folded by older semantics converges instead of staying silently stale.\n */\nexport function ensureRunOutcomeTables(db: DatabaseSync): void {\n const outcomeColumns = db.prepare(\"PRAGMA table_info('run_test_outcomes')\").all()\n .map((row) => String(row.name))\n if (outcomeColumns.length > 0 && !outcomeColumns.includes('product')) {\n // L12 disposable-store migration: a shape change drops every projection table so\n // no writer can retain or silently read globally keyed pre-partition rows.\n db.exec(`\n DROP TABLE IF EXISTS run_test_outcomes;\n DROP TABLE IF EXISTS run_test_anchors;\n DROP TABLE IF EXISTS run_outcome_applied_runs;\n DROP TABLE IF EXISTS run_fingerprint_windows;\n DROP TABLE IF EXISTS suite_fingerprints;\n DROP TABLE IF EXISTS run_outcome_projection_version;\n `)\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS run_test_outcomes (\n product TEXT NOT NULL,\n scope_tier TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n file_path TEXT NOT NULL,\n test_name TEXT NOT NULL,\n passes INTEGER NOT NULL DEFAULT 0,\n failures INTEGER NOT NULL DEFAULT 0,\n heals INTEGER NOT NULL DEFAULT 0,\n flake_count INTEGER NOT NULL DEFAULT 0,\n last_outcomes_json TEXT NOT NULL DEFAULT '[]',\n last_build_ordinal INTEGER,\n PRIMARY KEY (product, file_path, test_name)\n );\n\n CREATE TABLE IF NOT EXISTS run_test_anchors (\n product TEXT NOT NULL,\n scope_tier TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n file_path TEXT NOT NULL,\n test_name TEXT NOT NULL,\n anchor_normalized_json TEXT NOT NULL,\n UNIQUE (product, file_path, test_name, anchor_normalized_json)\n );\n\n CREATE TABLE IF NOT EXISTS run_outcome_applied_runs (\n product TEXT NOT NULL,\n run_id TEXT NOT NULL,\n PRIMARY KEY (product, run_id)\n );\n\n CREATE TABLE IF NOT EXISTS run_fingerprint_windows (\n product TEXT NOT NULL,\n file_path TEXT NOT NULL,\n test_name TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n verdict_class TEXT NOT NULL,\n build_ordinal INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n UNIQUE (product, file_path, test_name, fingerprint, build_ordinal, run_id)\n );\n\n -- 393 D-15: gate 3's comparison substrate, folded by the same pass and cleared by the same\n -- rebuild as the tables above. One row per fingerprint element, ordered by seq, keyed by the\n -- stable test identity; run_id and build_ordinal are the provenance the fold's\n -- newest-evidence-wins replacement rule compares on (see projection/suite-fingerprints.ts).\n CREATE TABLE IF NOT EXISTS suite_fingerprints (\n product TEXT NOT NULL,\n file_path TEXT NOT NULL,\n test_name TEXT NOT NULL,\n seq INTEGER NOT NULL,\n element TEXT NOT NULL,\n run_id TEXT NOT NULL,\n build_ordinal INTEGER NOT NULL,\n PRIMARY KEY (product, file_path, test_name, seq)\n );\n\n -- 393 CR-02: the stored fold-semantics stamp for the five tables above. Singleton by\n -- construction (the CHECK admits exactly one row) because \"which semantics produced this\n -- family\" is one fact about one derived index, and a second row could only ever be a second\n -- answer to it. Absent is a legal state and means MISMATCH: a pre-stamp index and an index\n -- whose file was deleted both read as absent, and both want the same rebuild.\n CREATE TABLE IF NOT EXISTS run_outcome_projection_version (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n version INTEGER NOT NULL\n );\n `)\n}\n\nfunction bootstrapSchema(\n db: DatabaseSync,\n vec: VecCapability,\n activeProfile: EmbeddingProfile,\n): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS records (\n record_rowid INTEGER PRIMARY KEY,\n bundle_id TEXT NOT NULL UNIQUE,\n product TEXT NOT NULL,\n mutable_state_hash TEXT NOT NULL,\n trust_prior_digest TEXT NOT NULL DEFAULT '',\n kind TEXT NOT NULL,\n subtype TEXT,\n scope_tier TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n status TEXT NOT NULL,\n trust REAL NOT NULL,\n confirmed INTEGER NOT NULL,\n contradicted INTEGER NOT NULL,\n helpful INTEGER NOT NULL,\n harmful INTEGER NOT NULL,\n last_confirmed_ordinal INTEGER,\n opened_at_ordinal REAL NOT NULL,\n closed_at_ordinal REAL,\n created_at_ordinal REAL NOT NULL,\n origin_class TEXT NOT NULL,\n summary TEXT NOT NULL,\n embedding_input TEXT NOT NULL,\n situating_line TEXT NOT NULL DEFAULT '',\n contextual_rendering TEXT NOT NULL DEFAULT '',\n embed_status TEXT NOT NULL DEFAULT 'pending',\n embedding BLOB\n );\n\n CREATE VIRTUAL TABLE IF NOT EXISTS fts_records USING fts5(\n identity,\n content,\n context,\n tokenize = \"unicode61 tokenchars '#-_./:[]=>@'\"\n );\n\n CREATE TABLE IF NOT EXISTS anchors (\n record_rowid INTEGER NOT NULL,\n product TEXT NOT NULL,\n t TEXT NOT NULL,\n raw_json TEXT NOT NULL,\n normalized_json TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS graph_nodes (\n node_id TEXT PRIMARY KEY,\n node_type TEXT NOT NULL,\n natural_key_json TEXT NOT NULL,\n product TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS graph_edges (\n src_node_id TEXT NOT NULL,\n edge_type TEXT NOT NULL,\n dst_node_id TEXT NOT NULL,\n record_rowid INTEGER NOT NULL,\n product TEXT NOT NULL,\n recency_ordinal INTEGER NOT NULL DEFAULT 0,\n UNIQUE(src_node_id, edge_type, dst_node_id, record_rowid)\n );\n\n CREATE TABLE IF NOT EXISTS meta (\n k TEXT PRIMARY KEY,\n v TEXT NOT NULL\n );\n `)\n\n ensureRunOutcomeTables(db)\n\n if (vec === 'vec0') {\n bootstrapVecSchema(db, activeProfile)\n }\n}\n\nfunction stampMeta(\n db: DatabaseSync,\n activeProfile: EmbeddingProfile,\n vecCleanup: 'current' | 'pending',\n renderingEpoch: 'current' | 'preserve',\n): void {\n const upsert = db.prepare(`\n INSERT INTO meta (k, v) VALUES (?, ?)\n ON CONFLICT(k) DO UPDATE SET v = excluded.v\n `)\n\n if (vecCleanup === 'pending') {\n db.prepare(\"DELETE FROM meta WHERE k = 'embedding_vec_cleanup_epoch'\").run()\n }\n upsert.run('index_schema_version', String(INDEX_SCHEMA_VERSION))\n upsert.run('embedding_profile', embeddingProfileKey(activeProfile))\n if (renderingEpoch === 'current') {\n upsert.run('rendering_schema_version', String(INDEX_RENDERING_SCHEMA_VERSION))\n }\n upsert.run('embedding_transition_epoch', String(EMBEDDING_TRANSITION_EPOCH))\n if (vecCleanup === 'current') {\n upsert.run('embedding_vec_cleanup_epoch', String(EMBEDDING_VEC_CLEANUP_EPOCH))\n }\n}\n\nfunction stampRenderingSchemaVersion(db: DatabaseSync): void {\n db.prepare(`\n INSERT INTO meta (k, v) VALUES ('rendering_schema_version', ?)\n ON CONFLICT(k) DO UPDATE SET v = excluded.v\n `).run(String(INDEX_RENDERING_SCHEMA_VERSION))\n}\n\n/**\n * Close the pre-lock D-07 relabeling gap before a profile stamp and epoch are written.\n *\n * The transition also fires when the stamp already matches but the current epoch is absent: the\n * former writer could pair the locked stamp with old-revision, same-dimension `present` bytes and\n * erase every mismatch clue. The only sound repair is one full invalidation behind a durable\n * marker; genuinely healthy locked indexes pay the same one-time re-embed cost. Pending rows ride\n * D-19's unchanged benign-lag backfill selector. Old revision vec tables remain disposable,\n * embed-cache rows stay inert under revision keys, and no embedding work runs at open.\n *\n * A brute connection cannot execute DML against an unloaded vec0 virtual table, so it invalidates\n * canonical bytes and leaves vec cleanup pending. The next vec0 writer clears the active table\n * before publishing cleanup current; an ordinary rebuild then reconciles it from canonical state.\n * On vec0 connections both the canonical UPDATE and active-table DELETE run before stampMeta\n * inside one BEGIN IMMEDIATE transaction, so no crash can commit fresh metadata beside stale\n * bytes.\n */\nfunction invalidateDerivedEmbeddings(db: DatabaseSync): void {\n db.prepare(`\n UPDATE records\n SET embedding = NULL, embed_status = 'pending'\n WHERE embedding IS NOT NULL OR embed_status = 'present'\n `).run()\n}\n\nfunction recreateActiveVecTable(db: DatabaseSync, activeProfile: EmbeddingProfile): void {\n db.exec(`DROP TABLE IF EXISTS ${vecTableName(activeProfile)}`)\n bootstrapVecSchema(db, activeProfile)\n}\n\nfunction resetProjectionSchema(\n db: DatabaseSync,\n vec: VecCapability,\n activeProfile: EmbeddingProfile,\n): void {\n if (vec === 'vec0') {\n db.exec(`DROP TABLE IF EXISTS ${vecTableName(activeProfile)}`)\n }\n db.exec(`\n DROP TABLE IF EXISTS fts_records;\n DROP TABLE IF EXISTS graph_edges;\n DROP TABLE IF EXISTS graph_nodes;\n DROP TABLE IF EXISTS anchors;\n DROP TABLE IF EXISTS records;\n DROP TABLE IF EXISTS meta;\n `)\n bootstrapSchema(db, vec, activeProfile)\n}\n\nfunction immediateTransaction(db: DatabaseSync, operation: () => void): void {\n db.exec('BEGIN IMMEDIATE')\n try {\n operation()\n db.exec('COMMIT')\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the transition or cleanup error that caused the rollback.\n }\n throw error\n }\n}\n\nfunction closeAfterOpenFailure(db: DatabaseSync): void {\n try {\n db.close()\n } catch {\n // Preserve the original open/bootstrap failure.\n }\n}\n\nexport function openIndexWriter(\n knowledgeRoot: string,\n opts: IndexOpenOptions = {},\n): IndexWriterHandle {\n const path = indexDbPath(knowledgeRoot)\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(path))\n mkdirSync(dirname(path), { recursive: true })\n\n const db = new DatabaseSync(path, {\n allowExtension: true,\n timeout: WRITER_BUSY_TIMEOUT_MS,\n })\n\n try {\n const vec = resolveVecCapability(db, opts.vecLoadablePath)\n const activeProfile = resolveActiveProfile(db)\n const projectionTablesPresent = hasProjectionTables(db)\n const previousSchemaVersionStamp = readIndexSchemaVersionStamp(db)\n const previousSchemaVersion = Number(previousSchemaVersionStamp)\n const schemaResetRequired =\n projectionTablesPresent\n && (previousSchemaVersionStamp === undefined\n || !Number.isFinite(previousSchemaVersion)\n || previousSchemaVersion !== INDEX_SCHEMA_VERSION)\n const previousRenderingVersionStamp = readRenderingSchemaVersionStamp(db)\n const previousRenderingVersion = Number(previousRenderingVersionStamp)\n let renderingEpochStale =\n projectionTablesPresent\n && !schemaResetRequired\n && (previousRenderingVersionStamp === undefined\n || !Number.isFinite(previousRenderingVersion)\n || previousRenderingVersion !== INDEX_RENDERING_SCHEMA_VERSION)\n db.exec('PRAGMA journal_mode=WAL')\n bootstrapSchema(db, vec, activeProfile)\n\n immediateTransaction(db, () => {\n if (schemaResetRequired) {\n resetProjectionSchema(db, vec, activeProfile)\n stampMeta(\n db,\n activeProfile,\n vec === 'vec0' ? 'current' : 'pending',\n 'current',\n )\n renderingEpochStale = false\n return\n }\n\n const transitionRequired =\n readEmbeddingProfileStamp(db) !== embeddingProfileKey(activeProfile)\n || readTransitionEpoch(db) !== String(EMBEDDING_TRANSITION_EPOCH)\n const embeddingInvalidationRequired =\n transitionRequired || renderingEpochStale\n\n if (vec === 'brute') {\n if (embeddingInvalidationRequired) invalidateDerivedEmbeddings(db)\n stampMeta(\n db,\n activeProfile,\n 'pending',\n renderingEpochStale ? 'preserve' : 'current',\n )\n return\n }\n\n if (embeddingInvalidationRequired || !isEmbeddingVecCleanupCurrent(db)) {\n if (embeddingInvalidationRequired) invalidateDerivedEmbeddings(db)\n recreateActiveVecTable(db, activeProfile)\n }\n stampMeta(\n db,\n activeProfile,\n 'current',\n renderingEpochStale ? 'preserve' : 'current',\n )\n })\n\n let closed = false\n return {\n db,\n vec,\n get renderingEpochStale(): boolean {\n return renderingEpochStale\n },\n completeRenderingEpoch(): void {\n if (!renderingEpochStale) return\n immediateTransaction(db, () => {\n stampRenderingSchemaVersion(db)\n })\n renderingEpochStale = false\n },\n checkpointPassive(): void {\n db.exec('PRAGMA wal_checkpoint(PASSIVE)')\n },\n close(): void {\n if (closed) return\n try {\n db.exec('PRAGMA wal_checkpoint(TRUNCATE)')\n } finally {\n closed = true\n db.close()\n }\n },\n }\n } catch (error) {\n closeAfterOpenFailure(db)\n throw error\n }\n}\n\nexport function openIndexReaderConnection(\n knowledgeRoot: string,\n opts: IndexReaderOpenOptions = {},\n): IndexReaderConnection {\n const path = indexDbPath(knowledgeRoot)\n let location = path\n if (opts.inspectCheckpointedImmutably === true && !existsSync(`${path}-wal`)) {\n const immutableUri = pathToFileURL(path)\n immutableUri.searchParams.set('mode', 'ro')\n immutableUri.searchParams.set('immutable', '1')\n location = immutableUri.href\n }\n const db = new DatabaseSync(location, {\n readOnly: true,\n allowExtension: true,\n timeout: READER_BUSY_TIMEOUT_MS,\n })\n\n try {\n const vec = resolveVecCapability(db, opts.vecLoadablePath)\n db.exec('PRAGMA query_only=1')\n return { db, vec }\n } catch (error) {\n closeAfterOpenFailure(db)\n throw error\n }\n}\n\nexport function probeIndexHealth(db: DatabaseSync): IndexHealth {\n try {\n const row = db.prepare('PRAGMA quick_check').get()\n const result = row?.quick_check\n if (result !== 'ok') {\n return {\n ok: false,\n probe: 'quick-check',\n reason: `PRAGMA quick_check returned ${String(result)}`,\n }\n }\n } catch (error) {\n return {\n ok: false,\n probe: 'quick-check',\n reason: error instanceof Error ? error.message : String(error),\n }\n }\n\n try {\n const rows = db\n .prepare(\"SELECT name FROM sqlite_master WHERE type = 'table'\")\n .all()\n const present = new Set(rows.map((row) => String(row.name)))\n const missing = REQUIRED_INDEX_TABLES.filter((table) => !present.has(table))\n if (missing.length > 0) {\n return {\n ok: false,\n probe: 'projection-schema',\n reason: `required projection tables missing: ${missing.join(', ')}`,\n }\n }\n } catch (error) {\n return {\n ok: false,\n probe: 'projection-schema',\n reason: error instanceof Error ? error.message : String(error),\n }\n }\n\n try {\n const row = db\n .prepare(\"SELECT v FROM meta WHERE k = 'index_schema_version'\")\n .get()\n const version = Number(row?.v)\n if (\n row === undefined\n || !Number.isFinite(version)\n || version !== INDEX_SCHEMA_VERSION\n ) {\n return {\n ok: false,\n probe: 'schema-version',\n reason: `index schema version ${String(row?.v)} is not readable`,\n }\n }\n } catch (error) {\n return {\n ok: false,\n probe: 'schema-version',\n reason: error instanceof Error ? error.message : String(error),\n }\n }\n\n return { ok: true }\n}\n","// D-11 keeps native-extension package resolution behind one internal boundary.\n// index-open consumes this named export and remains responsible for load failures.\nexport { getLoadablePath } from 'sqlite-vec'\n","// Entity renderings for the D-06 projection, under the §5.3 embed-human-renderings law.\n//\n// Two audiences, one descriptor, and keeping them apart is the whole point.\n//\n// The DENSE leg indexes MEANING. What it must be able to answer is \"the test where we buy\n// something\" -> the checkout test, and the only text that can support that is text a human\n// would recognise: the kind said in words, the title as somebody wrote it. An opaque machine\n// id contributes nothing an embedding model can use and actively costs — it is a long token\n// of noise sitting inside a vector that has a fixed budget of meaning.\n//\n// The LEXICAL leg indexes IDENTITY. `TST-001`, the URI and the machine id are exact handles:\n// they either match or they do not, and BM25 over the identity column is exactly the right\n// instrument for that. They live there and nowhere else.\n//\n// The one deliberate crossing is slug-addressed kinds (D-03): a target's machine id ALREADY is\n// the human name its config gave it, so `checkout-web` is meaning, not a digest. Its words are\n// split out and embedded, because refusing to would make the one kind whose machine id is\n// readable the one kind semantic phrasing could not find.\n\nimport { ENTITY_URI_SEGMENTS, isSlugAddressedKind } from '@vostride/agent-qa-schema'\nimport type { EntityDescriptor } from '@vostride/agent-qa-schema'\n\n/** The four columns one entity projects onto: three FTS fields plus the embedded text. */\nexport interface EntityRendering {\n /** Exact handles, weighted highest by the lexical leg. Never embedded. */\n readonly identity: string\n /** The human title, as the owning store reports it. */\n readonly content: string\n /** Situating words: the kind said in words, plus slug words where the id is a name. */\n readonly context: string\n /** The §5.3 human rendering the dense leg embeds. */\n readonly embedding: string\n}\n\n/**\n * Split a slug into the words a reader would say.\n *\n * `checkout-web` is two words to a human and one token to the FTS tokenizer, whose\n * `tokenchars` deliberately keep `-` inside a token so that `MEM-001` stays one address. That\n * is right for identity and wrong for meaning, so meaning gets the split form.\n */\nfunction slugWords(slug: string): string[] {\n return slug.split(/[^\\p{L}\\p{N}]+/u).filter((word) => word !== '')\n}\n\nfunction meaningWords(descriptor: EntityDescriptor): string[] {\n return isSlugAddressedKind(descriptor.kind) ? slugWords(descriptor.machineId) : []\n}\n\n/**\n * The text embedded for one entity (§5.3).\n *\n * The kind word comes from the URI-segment table rather than a second vocabulary spelled here:\n * `memory` is already the word this system uses for `MEM` in a path a human reads, and two\n * tables naming the same five kinds is two tables to keep in step.\n *\n * The status is deliberately absent. Nearly every entity is `active`, so embedding it would\n * add one high-frequency token to every vector in the corpus — carrying no signal while\n * diluting the ones that do. A caller who wants \"the quarantined tests\" is asking a filter\n * question, not a similarity question.\n */\nexport function renderEntityForEmbedding(descriptor: EntityDescriptor): string {\n return [\n ENTITY_URI_SEGMENTS[descriptor.kind],\n descriptor.title,\n ...meaningWords(descriptor),\n ].filter((part) => part !== '').join(' ')\n}\n\n/** Project one descriptor onto its four indexed columns. */\nexport function renderEntity(descriptor: EntityDescriptor): EntityRendering {\n const identity = [descriptor.shortId, descriptor.uri, descriptor.machineId]\n // A recorded rename keeps the predecessor findable by the successor's handle too, which is\n // what makes an old CI log's short-ID an explanation rather than a dead end (D-03/D-04).\n if (descriptor.successorMachineId !== undefined) identity.push(descriptor.successorMachineId)\n\n return {\n identity: identity.join(' '),\n content: descriptor.title,\n context: [ENTITY_URI_SEGMENTS[descriptor.kind], ...meaningWords(descriptor)].join(' '),\n embedding: renderEntityForEmbedding(descriptor),\n }\n}\n","// Tiers (b) and (c) of the entity resolver (Phase 387, D-05 / D-07 / ENTY-01).\n//\n// (b) a STRONG HIT over the hybrid entity index — resolved, with a score.\n// (c) anything weaker — the top three, as a disambiguation set, or an honest miss.\n//\n// WHAT THIS FILE DOES NOT CONTAIN\n//\n// No scoring. Not a line of it. `lexicalLeg` runs the weighted BM25 recall, `denseLeg` runs the\n// embedding recall and owns the degradation ladder that decides whether there is an embedder at\n// all, and `fuseWeightedRrf` combines their rankings and breaks final ties on identity. D-05\n// picked the memidex pipeline over fuse.js precisely so semantic phrasings resolve, and a\n// second scoring engine living here would have re-opened every calibration those modules\n// already carry — the admission floors, the RRF constant, the FTS escaping, the vec/brute\n// rungs. What this file adds is the never-guess decision ON TOP of a ranking it did not compute.\n//\n// WHY THE FLOOR POSTURE NEEDS NO FLAG\n//\n// There is no branch here that asks whether this host has an embedder. `denseLeg` answers with\n// an empty leg when it cannot embed, `hasDenseCandidates` skips it when nothing is embedded at\n// all, and an empty leg contributes nothing to the fusion. A floor host therefore runs the same\n// code and gets the lexical-only rung by omission — which is what makes the degradation\n// direction a property of the arithmetic rather than of a posture check somebody has to keep\n// in step (D-08).\n//\n// WHY THE INDEX IS NOT ASKED WHAT AN ENTITY IS\n//\n// The index ranks short-IDs; the caller turns a short-ID back into a descriptor. The projection\n// is disposable and may hold a stale row for an entity its owning store has since forgotten\n// (D-06), so letting it describe the answer would let a stale row put a stale title in front of\n// a user. The ledger and the stores stay the truth; this file only decides which address wins.\n\nimport { ENTITY_RESOLUTION_MAX_CANDIDATES } from '@vostride/agent-qa-schema'\nimport type { EntityDescriptor, EntityResolution } from '@vostride/agent-qa-schema'\n\nimport type { EmbedderPort } from '../embedder-port.js'\nimport {\n ENTITY_INDEX_SCOPE,\n entityIndexTauDense,\n type EntityIndexHandle,\n} from '../entity-index/entity-index.js'\nimport { hasDenseCandidates } from '../retrieve.js'\nimport { admitCandidate, fuseWeightedRrf } from '../retrieval/fusion.js'\nimport { denseLeg, lexicalLeg, type LegCandidate } from '../retrieval/legs.js'\nimport {\n RESOLVER_CANDIDATE_K,\n RESOLVER_FUSED_SCORE_NORMALIZER,\n RESOLVER_LEG_WEIGHT_DENSE,\n RESOLVER_LEG_WEIGHT_LEXICAL,\n RESOLVER_LEXICAL_MIN_BM25,\n RESOLVER_STRONG_HIT_MARGIN,\n RESOLVER_STRONG_HIT_MIN_SCORE,\n} from './constants.js'\n\nexport interface ResolveHybridDeps {\n /** The D-06 projection this ranks over. */\n readonly index: EntityIndexHandle\n /**\n * A short-ID back to the entity it names, or `undefined` when no store can describe it any\n * more. Supplied by the caller so the LEDGER stays the authority — see the file header.\n */\n readonly describe: (shortId: string) => EntityDescriptor | undefined\n /** Test/integration seam; production omission runs denseLeg's automatic acquisition ladder. */\n readonly embedder?: EmbedderPort\n}\n\nexport interface RankedEntity {\n readonly descriptor: EntityDescriptor\n readonly score: number\n}\n\n/**\n * The lexical leg's admission for the ENTITY corpus.\n *\n * Deliberately not `admitCandidate`, and the reason is measured rather than stylistic: that\n * gate's lexical arm is `TAU_LEX`, calibrated from a serving replay over knowledge records,\n * and it rejects every entity candidate outright (see `RESOLVER_LEXICAL_MIN_BM25`). The dense\n * arm's floor is profile-owned and correct anywhere, so the dense leg keeps `admitCandidate`.\n */\nfunction admitLexical(candidate: LegCandidate): boolean {\n return (candidate.rawScores.bm25Positive ?? 0) >= RESOLVER_LEXICAL_MIN_BM25\n}\n\n/**\n * Rank the entity corpus against free text, returning describable candidates best-first.\n *\n * Exported because this is the ranking a corpus report reads (387-05): a per-case score log is\n * only comparable across postures if it comes from the same call the resolver made.\n */\nexport async function rankEntityCandidates(\n ref: string,\n deps: ResolveHybridDeps,\n): Promise<RankedEntity[]> {\n const { connection } = deps.index\n const lexical = lexicalLeg(connection.db, ref, ENTITY_INDEX_SCOPE, RESOLVER_CANDIDATE_K)\n .filter(admitLexical)\n\n const tauDense = entityIndexTauDense(deps.index)\n const dense = hasDenseCandidates(connection.db, ENTITY_INDEX_SCOPE)\n ? (await denseLeg(\n connection,\n [ref],\n ENTITY_INDEX_SCOPE,\n RESOLVER_CANDIDATE_K,\n deps.embedder === undefined ? {} : { embedder: deps.embedder },\n )).filter((candidate) => admitCandidate(candidate, { tauDense }))\n : []\n\n return fuseWeightedRrf([\n { weight: RESOLVER_LEG_WEIGHT_LEXICAL, ranked: lexical },\n { weight: RESOLVER_LEG_WEIGHT_DENSE, ranked: dense },\n ]).flatMap((candidate) => {\n const descriptor = deps.describe(candidate.bundleId)\n return descriptor === undefined\n ? []\n : [{\n descriptor,\n // A rescale by a constant: `fuseWeightedRrf` decided the order, this only puts the\n // number on the [0, 1] scale tier (a) already answers on. Clamped because a score\n // outside its declared range is refused at the schema boundary, and a resolver that\n // threw there would turn a presentation detail into a failed resolution.\n score: Math.min(1, candidate.fusedScore / RESOLVER_FUSED_SCORE_NORMALIZER),\n }]\n })\n}\n\n/**\n * The two numbers the D-07 rule is decided against.\n *\n * Parameterised for ONE reason, and it is not configuration: the corpus (387-05) has to be able\n * to ask where the boundary IS, not merely whether today's value sits on the right side of it.\n * A degradation gate that no input can redden is not a gate, and the only way to show this one\n * can redden is to run the same corpus, through this same function, at a margin below the bound\n * — which is a measurement, not a setting. No production call site passes this argument, the\n * defaults are the pinned constants, and nothing reads a config file to get here.\n */\nexport interface StrongHitThresholds {\n readonly minScore: number\n readonly margin: number\n}\n\nexport const RESOLVER_STRONG_HIT_THRESHOLDS: StrongHitThresholds = {\n minScore: RESOLVER_STRONG_HIT_MIN_SCORE,\n margin: RESOLVER_STRONG_HIT_MARGIN,\n}\n\n/**\n * The D-07 decision itself, over a ranking somebody else produced.\n *\n * The rule is two-part and BOTH parts must hold — an absolute threshold the winner clears on\n * its own, and a margin over the runner-up. Equal-strength candidates therefore always\n * disambiguate without a special case: a margin of zero is not greater than a positive margin,\n * so the arithmetic refuses before any tie-break could pick a favourite.\n */\nexport function applyStrongHitRule(\n ranked: readonly RankedEntity[],\n thresholds: StrongHitThresholds = RESOLVER_STRONG_HIT_THRESHOLDS,\n): EntityResolution {\n const top = ranked[0]\n if (top === undefined) return { kind: 'none', reason: 'no-match' }\n\n const runnerUp = ranked[1]?.score ?? 0\n if (top.score >= thresholds.minScore && top.score - runnerUp > thresholds.margin) {\n return { kind: 'resolved', descriptor: top.descriptor, score: top.score }\n }\n\n // Tier (c). Two candidates minimum, because a \"disambiguation\" between one option is not a\n // choice — it is a suggestion, and the miss arm is where a suggestion belongs.\n if (ranked.length >= 2) {\n return {\n kind: 'ambiguous',\n candidates: ranked.slice(0, ENTITY_RESOLUTION_MAX_CANDIDATES).map(({ descriptor, score }) => ({\n descriptor,\n score,\n })),\n }\n }\n\n return { kind: 'none', reason: 'no-match', closestSuggestion: top.descriptor.shortId }\n}\n\n/** Tier (b) then tier (c): rank the corpus, then apply the pinned rule to what came back. */\nexport async function resolveHybrid(\n ref: string,\n deps: ResolveHybridDeps,\n): Promise<EntityResolution> {\n return applyStrongHitRule(await rankEntityCandidates(ref, deps))\n}\n","/**\n * Public memory.md §5.5 retrieval composition.\n *\n * Usage telemetry (§5.5.9) is deferred by architecture: reader connections are query_only, so\n * counters land with Phases 378/380's writer-owned paths and are never an input to trust.\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n asRecordId,\n canonicalJson,\n supersessionKey,\n type Anchor,\n type IndexEntry,\n type ScopeKey,\n type TrustPriorTable,\n type VettedCandidateInput,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle, verifyBundleIntegrity } from './bundle-read.js'\nimport { enumerateBundleDirs, type KnowledgeHit } from './bundle-scan.js'\nimport type { AcquireEmbedderOutcome } from './embedder-acquire.js'\nimport type { KnowledgeReader } from './index-reader.js'\nimport {\n withKnowledgeReadSnapshot,\n type AuthoritativeKnowledgeHit,\n type KnowledgeRetrievalContext,\n} from './index-reader.js'\nimport { resolveActiveProfile, type IndexReaderConnection } from './index-open.js'\nimport { buildRetrievalQuery, type RetrievalQueryInput } from './query-helper.js'\nimport { expandOneHop, type ExpansionSeed } from './retrieval/expansion.js'\nimport {\n admitCandidate,\n capExpansion,\n fuseWeightedRrf,\n type FusedCandidate,\n type WeightedRrfLeg,\n} from './retrieval/fusion.js'\nimport {\n anchorSeedLeg,\n denseLeg,\n lexicalLeg,\n type LegCandidate,\n type RetrievalLegScope,\n} from './retrieval/legs.js'\nimport { preFilterPredicate } from './retrieval/pre-filter.js'\nimport {\n applyDiversityCaps,\n applyLifecycleTrustTreatments,\n collapseByOrdinal,\n rerankPrecedence,\n type MintUnknownConflict,\n type ValidityClass,\n} from './retrieval/rerank.js'\nimport {\n applyValidity,\n resolveAsOfBuild,\n type AsOfRange,\n type ValidityAnnotation,\n} from './retrieval/validity.js'\nimport { TAU_LEX } from './retrieval/constants.js'\n\nexport interface RetrieveOptions {\n n: number\n product: string\n testKey?: string\n suiteKey?: string\n asOfBuild?: number\n resolveLatestOrdinal?: (product: string) => number | undefined\n runtimeRoot?: string\n includeSuperseded?: boolean\n asOfRange?: AsOfRange\n /** Host-resolved posture; a deferred daemon capability forbids in-process fallback. */\n embeddingCapability?: AcquireEmbedderOutcome\n}\n\nexport type RetrieveResult = IndexEntry[]\n\ntype RankedLeg = WeightedRrfLeg<LegCandidate>\n\ninterface PipelineCandidate extends KnowledgeHit {\n readonly recordRowid: number\n readonly source: 'direct' | 'expanded'\n readonly legRanks: Readonly<Record<string, number>>\n readonly rawScores: LegCandidate['rawScores']\n readonly fusedScore: number\n readonly anchors: Anchor[]\n readonly scope: ScopeKey\n readonly openedAtOrdinal: number\n readonly closedAtOrdinal: number | null\n readonly createdAtOrdinal: number\n readonly originClass: 'agent' | 'user'\n readonly recencyOrdinal: number\n readonly validityClass: ValidityClass\n readonly lastConfirmedOrdinal: number\n readonly vettedCandidateInput?: VettedCandidateInput\n readonly unconfirmedSinceOrdinal?: number\n readonly unverified?: boolean\n readonly memoryOffTriggerKey?: string\n readonly servedAs?: 'current' | 'prior-build-hypothesis'\n readonly audit?: { status: string; openedAtOrdinal: number; closedAtOrdinal: number | null }\n readonly conflict?: { peerRecordId: string; unknownRecordId: string }\n}\n\ninterface ScanCandidateSource extends AuthoritativeKnowledgeHit {\n recordRowid: number\n}\n\nconst GLOBAL_SCOPE_KEY = 'global'\nconst MAX_SQL_LIMIT = 2_147_483_647\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction candidateLimit(n: number): number {\n return Math.max(32, Math.min(MAX_SQL_LIMIT, n > MAX_SQL_LIMIT / 4 ? MAX_SQL_LIMIT : n * 4))\n}\n\nfunction auditMode(options: RetrieveOptions): boolean {\n return options.includeSuperseded === true || options.asOfRange !== undefined\n}\n\nfunction memoryOffGroupKey(scope: ScopeKey, triggerKey: string): string {\n return canonicalJson([scope.tier, scope.key, triggerKey])\n}\n\nfunction factMemoryOffGroup(candidate: PipelineCandidate): string | undefined {\n return candidate.kind === 'fact'\n ? memoryOffGroupKey(candidate.scope, supersessionKey(candidate.anchors))\n : undefined\n}\n\nfunction thrashTriggerKey(anchor: Anchor | undefined): string | undefined {\n if (anchor?.t !== 'flow') return undefined\n const match = /^thrash:([0-9a-f]{64}):window:[0-9]+$/.exec(anchor.name)\n return match?.[1]\n}\n\n/**\n * D-07 targeted canonical lookup: a derived index may disappear, so the committed\n * unresolved unknown remains the serving switch. Only digest-verified unknowns\n * matching a retrieved fact group can suppress or enter this query.\n */\nfunction attachMemoryOffUnknowns(\n knowledgeRoot: string,\n candidates: readonly PipelineCandidate[],\n options: RetrieveOptions,\n priors?: TrustPriorTable,\n): PipelineCandidate[] {\n if (auditMode(options)) return [...candidates]\n\n const relevantGroups = new Set(\n candidates.flatMap((candidate) => {\n const key = factMemoryOffGroup(candidate)\n return key === undefined ? [] : [key]\n }),\n )\n if (relevantGroups.size === 0) return [...candidates]\n\n const augmented = [...candidates]\n const candidateIndexById = new Map(\n augmented.map((candidate, index) => [candidate.bundleId, index] as const),\n )\n let syntheticRowid = -1\n\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n if (!verifyBundleIntegrity(entry.dir).ok) continue\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded' || loaded.bundle.frontmatter.kind !== 'unknown') continue\n\n const trust = deriveBundleTrust(loaded.bundle, priors)\n if (\n (trust.status !== 'active' && trust.status !== 'candidate')\n || trust.validity.closedAtOrdinal !== undefined\n ) {\n continue\n }\n\n const anchors = loaded.bundle.frontmatter.anchors.map(({ normalized }) => normalized)\n const triggerKey = thrashTriggerKey(anchors[0])\n if (triggerKey === undefined) continue\n const markerKey = memoryOffGroupKey(loaded.bundle.frontmatter.scope, triggerKey)\n if (!relevantGroups.has(markerKey)) continue\n\n const existingIndex = candidateIndexById.get(loaded.bundle.manifest.id)\n if (existingIndex !== undefined) {\n augmented[existingIndex] = {\n ...augmented[existingIndex]!,\n memoryOffTriggerKey: markerKey,\n }\n continue\n }\n\n augmented.push({\n bundleId: loaded.bundle.manifest.id,\n product: entry.product,\n kind: 'unknown',\n subtype: null,\n status: trust.status,\n trust: trust.trust,\n validity: trust.validity,\n summary: loaded.bundle.summary,\n embeddingInput: loaded.bundle.manifest.embeddingInput,\n recordRowid: syntheticRowid,\n source: 'expanded',\n legRanks: { memoryOffUnknown: Math.abs(syntheticRowid) },\n rawScores: {},\n fusedScore: 0,\n anchors,\n scope: loaded.bundle.frontmatter.scope,\n openedAtOrdinal: trust.validity.openedAtOrdinal,\n closedAtOrdinal: trust.validity.closedAtOrdinal ?? null,\n createdAtOrdinal: loaded.bundle.frontmatter.createdAtOrdinal,\n originClass: loaded.bundle.frontmatter.originClass === 'user' ? 'user' : 'agent',\n recencyOrdinal: loaded.bundle.frontmatter.createdAtOrdinal,\n validityClass: 'current',\n lastConfirmedOrdinal: trust.lastConfirmedOrdinal,\n memoryOffTriggerKey: markerKey,\n })\n candidateIndexById.set(loaded.bundle.manifest.id, augmented.length - 1)\n syntheticRowid -= 1\n }\n\n return augmented\n}\n\nfunction suppressMemoryOffFacts(\n candidates: readonly PipelineCandidate[],\n audit: boolean,\n): PipelineCandidate[] {\n if (audit) return [...candidates]\n const suppressedGroups = new Set(\n candidates.flatMap((candidate) =>\n candidate.memoryOffTriggerKey === undefined\n ? []\n : [candidate.memoryOffTriggerKey]),\n )\n if (suppressedGroups.size === 0) return [...candidates]\n\n return candidates.filter((candidate) => {\n const key = factMemoryOffGroup(candidate)\n return key === undefined || !suppressedGroups.has(key)\n })\n}\n\nfunction retrievalScope(options: RetrieveOptions): RetrievalLegScope {\n return {\n product: options.product,\n testKey: options.testKey ?? `__missing_test_scope__:${options.product}`,\n suiteKey: options.suiteKey ?? `__missing_suite_scope__:${options.product}`,\n productKey: options.product,\n globalKey: GLOBAL_SCOPE_KEY,\n ...(options.includeSuperseded === undefined\n ? {}\n : { includeSuperseded: options.includeSuperseded }),\n }\n}\n\nfunction inScope(\n hit: Pick<AuthoritativeKnowledgeHit, 'product' | 'scope'>,\n scope: RetrievalLegScope,\n): boolean {\n const allowedKeys = new Set([\n scope.testKey,\n scope.suiteKey,\n scope.productKey,\n scope.globalKey,\n ])\n if (!allowedKeys.has(hit.scope.key)) return false\n return hit.scope.tier === 'global' || hit.product === scope.product\n}\n\nexport function hasDenseCandidates(db: DatabaseSync, scope: RetrievalLegScope): boolean {\n const predicate = preFilterPredicate(scope)\n return db.prepare(`\n SELECT 1 AS present\n FROM records r\n WHERE r.embed_status = 'present'\n AND r.embedding IS NOT NULL\n AND ${predicate.sql}\n LIMIT 1\n `).get(...predicate.binds) !== undefined\n}\n\nfunction admitLeg(\n candidates: readonly LegCandidate[],\n tauDense: number,\n): LegCandidate[] {\n return candidates.filter((candidate) => admitCandidate(candidate, { tauDense }))\n}\n\nfunction readAnchors(db: DatabaseSync, recordRowid: number): Anchor[] {\n return db.prepare(`\n SELECT normalized_json\n FROM anchors\n WHERE record_rowid = ?\n ORDER BY rowid\n `).all(recordRowid).flatMap((row) => {\n try {\n return [JSON.parse(String(row.normalized_json)) as Anchor]\n } catch {\n return []\n }\n })\n}\n\nfunction asKnowledgeHit(candidate: LegCandidate): KnowledgeHit {\n return {\n bundleId: candidate.bundleId,\n product: candidate.product,\n kind: candidate.kind as KnowledgeHit['kind'],\n subtype: candidate.subtype,\n status: candidate.status as KnowledgeHit['status'],\n trust: candidate.trust,\n validity: {\n openedAtOrdinal: candidate.openedAtOrdinal,\n ...(candidate.closedAtOrdinal === undefined\n ? {}\n : { closedAtOrdinal: candidate.closedAtOrdinal }),\n },\n summary: candidate.summary,\n embeddingInput: candidate.embeddingInput,\n }\n}\n\nfunction hydrateFusedCandidate(\n db: DatabaseSync,\n candidate: FusedCandidate<LegCandidate>,\n): PipelineCandidate {\n const hit = asKnowledgeHit(candidate)\n const confirmation = db.prepare(`\n SELECT last_confirmed_ordinal\n FROM records\n WHERE record_rowid = ?\n `).get(candidate.recordRowid)\n const lastConfirmed = confirmation?.last_confirmed_ordinal\n return {\n ...hit,\n recordRowid: candidate.recordRowid,\n source: candidate.source,\n legRanks: candidate.legRanks,\n rawScores: candidate.rawScores,\n fusedScore: candidate.fusedScore,\n anchors: readAnchors(db, candidate.recordRowid),\n scope: {\n tier: candidate.scopeTier as ScopeKey['tier'],\n key: candidate.scopeKey,\n },\n openedAtOrdinal: candidate.openedAtOrdinal,\n closedAtOrdinal: candidate.closedAtOrdinal ?? null,\n createdAtOrdinal: candidate.createdAtOrdinal,\n originClass: candidate.originClass === 'user' ? 'user' : 'agent',\n recencyOrdinal: candidate.createdAtOrdinal,\n validityClass: 'current',\n lastConfirmedOrdinal: Number(\n lastConfirmed === null || lastConfirmed === undefined\n ? candidate.openedAtOrdinal\n : lastConfirmed,\n ),\n }\n}\n\nfunction refreshPipelineCandidates(\n context: KnowledgeRetrievalContext,\n candidates: readonly PipelineCandidate[],\n): PipelineCandidate[] {\n return context.recheck(candidates, true).map((candidate) => ({\n ...candidate,\n openedAtOrdinal: candidate.validity.openedAtOrdinal,\n closedAtOrdinal: candidate.validity.closedAtOrdinal ?? null,\n originClass: candidate.originClass === 'user' ? 'user' : 'agent',\n recencyOrdinal: candidate.createdAtOrdinal,\n validityClass: 'current',\n lastConfirmedOrdinal: candidate.lastConfirmedOrdinal,\n vettedCandidateInput: candidate.vettedCandidateInput,\n }))\n}\n\nfunction rowToExpandedLeg(\n db: DatabaseSync,\n recordRowid: number,\n rank: number,\n): LegCandidate | undefined {\n const row = db.prepare(`\n SELECT\n record_rowid,\n bundle_id,\n product,\n kind,\n subtype,\n scope_tier,\n scope_key,\n status,\n trust,\n opened_at_ordinal,\n closed_at_ordinal,\n created_at_ordinal,\n origin_class,\n summary,\n embedding_input\n FROM records\n WHERE record_rowid = ?\n `).get(recordRowid)\n if (row === undefined) return undefined\n\n const closedAt = row.closed_at_ordinal\n return {\n recordRowid: Number(row.record_rowid),\n bundleId: String(row.bundle_id),\n product: String(row.product),\n kind: String(row.kind),\n subtype: row.subtype === null || row.subtype === undefined ? null : String(row.subtype),\n scopeTier: String(row.scope_tier),\n scopeKey: String(row.scope_key),\n status: String(row.status),\n trust: Number(row.trust),\n openedAtOrdinal: Number(row.opened_at_ordinal),\n ...(closedAt === null || closedAt === undefined\n ? {}\n : { closedAtOrdinal: Number(closedAt) }),\n createdAtOrdinal: Number(row.created_at_ordinal),\n originClass: String(row.origin_class),\n summary: String(row.summary),\n embeddingInput: String(row.embedding_input),\n source: 'expanded',\n legRanks: { expansion: rank },\n rawScores: {},\n }\n}\n\nfunction expansionSeeds(\n db: DatabaseSync,\n candidates: readonly FusedCandidate<LegCandidate>[],\n): ExpansionSeed[] {\n return candidates.map((candidate) => {\n const rows = db.prepare(`\n SELECT src_node_id, dst_node_id\n FROM graph_edges\n WHERE record_rowid = ?\n ORDER BY src_node_id, edge_type, dst_node_id\n `).all(candidate.recordRowid)\n const nodeIds = new Set<string>()\n for (const row of rows) {\n nodeIds.add(String(row.src_node_id))\n nodeIds.add(String(row.dst_node_id))\n }\n return {\n bundleId: candidate.bundleId,\n nodeIds: [...nodeIds].sort(compareText),\n }\n })\n}\n\nfunction mintUnknownConflicts(db: DatabaseSync): MintUnknownConflict[] {\n const rows = db.prepare(`\n SELECT r.bundle_id AS member_id, target.natural_key_json AS unknown_json\n FROM graph_edges edge\n JOIN records r ON r.record_rowid = edge.record_rowid\n JOIN graph_nodes target ON target.node_id = edge.dst_node_id\n WHERE edge.edge_type = 'conflicts-with'\n AND target.node_type = 'unknown'\n ORDER BY target.natural_key_json, r.bundle_id\n `).all()\n const membersByUnknown = new Map<string, Set<string>>()\n for (const row of rows) {\n let unknownRecordId: unknown\n try {\n unknownRecordId = JSON.parse(String(row.unknown_json))\n } catch {\n continue\n }\n if (typeof unknownRecordId !== 'string') continue\n const members = membersByUnknown.get(unknownRecordId) ?? new Set<string>()\n members.add(String(row.member_id))\n membersByUnknown.set(unknownRecordId, members)\n }\n\n const conflicts: MintUnknownConflict[] = []\n for (const [unknownRecordId, memberSet] of [...membersByUnknown].sort(([left], [right]) =>\n compareText(left, right))) {\n const members = [...memberSet].sort(compareText)\n for (let left = 0; left < members.length; left += 1) {\n for (let right = left + 1; right < members.length; right += 1) {\n conflicts.push({\n leftRecordId: members[left]!,\n rightRecordId: members[right]!,\n unknownRecordId,\n })\n }\n }\n }\n return conflicts\n}\n\nfunction validityClass(\n annotation: ValidityAnnotation,\n audit: boolean,\n): ValidityClass {\n if (audit) return 'auditReadmitted'\n return annotation.servedAs === 'prior-build-hypothesis'\n ? 'priorBuildHypothesis'\n : 'current'\n}\n\nfunction applyAssembly(\n candidates: readonly PipelineCandidate[],\n conflicts: readonly MintUnknownConflict[],\n options: RetrieveOptions,\n): PipelineCandidate[] {\n const audit = auditMode(options)\n const resolvedAsOf = resolveAsOfBuild({\n product: options.product,\n candidates,\n ...(options.asOfBuild === undefined ? {} : { asOfBuild: options.asOfBuild }),\n ...(options.resolveLatestOrdinal === undefined\n ? {}\n : { resolveLatestOrdinal: options.resolveLatestOrdinal }),\n ...(options.runtimeRoot === undefined ? {} : { runtimeRoot: options.runtimeRoot }),\n ...(options.asOfRange === undefined ? {} : { asOfRange: options.asOfRange }),\n })\n const valid = applyValidity(candidates, resolvedAsOf, {\n ...(options.asOfRange === undefined ? {} : { asOfRange: options.asOfRange }),\n }).map((candidate) => ({\n ...candidate,\n validityClass: validityClass(candidate, audit),\n ...(candidate.audit !== undefined\n ? {}\n : audit\n ? {\n audit: {\n status: candidate.status,\n openedAtOrdinal: candidate.openedAtOrdinal,\n closedAtOrdinal: candidate.closedAtOrdinal,\n },\n }\n : {}),\n }))\n // D-05/D-20 are ordinary serving treatments. Audit reads preserve raw authority.\n const treated = audit || resolvedAsOf === undefined\n ? valid\n : applyLifecycleTrustTreatments(valid, resolvedAsOf)\n const reranked = rerankPrecedence(treated)\n const collapsed = collapseByOrdinal(reranked, { audit, conflicts })\n const memorySafe = suppressMemoryOffFacts(collapsed, audit)\n return applyDiversityCaps(memorySafe, audit)\n}\n\nfunction finalRecheck(\n context: KnowledgeRetrievalContext,\n candidates: readonly PipelineCandidate[],\n scope: RetrievalLegScope,\n options: RetrieveOptions,\n): RetrieveResult {\n const audit = auditMode(options)\n const servedTrust = new Map(\n candidates.map((candidate) => [candidate.bundleId, candidate.trust] as const),\n )\n const refreshed = audit\n ? context.recheck(candidates, true)\n : candidates.flatMap((candidate) => {\n const priorHypothesis = candidate.servedAs === 'prior-build-hypothesis'\n return context.recheck([candidate], priorHypothesis).filter((hit) =>\n !priorHypothesis\n || (\n (hit.status === 'active' || hit.status === 'candidate')\n && hit.validity.closedAtOrdinal !== undefined\n ))\n })\n return refreshed\n .filter((candidate) => inScope(candidate, scope))\n .map((candidate): IndexEntry => {\n const closedAtOrdinal = candidate.validity.closedAtOrdinal ?? null\n return {\n id: asRecordId(candidate.bundleId),\n kind: candidate.kind,\n ...(candidate.subtype === null ? {} : { subtype: candidate.subtype }),\n title: candidate.summary,\n summary: candidate.summary,\n trust: audit\n ? candidate.trust\n : (servedTrust.get(candidate.bundleId) ?? candidate.trust),\n anchors: candidate.anchors,\n status: candidate.status,\n servedAsCanary: false,\n ...(candidate.servedAs === undefined ? {} : { servedAs: candidate.servedAs }),\n ...(candidate.unconfirmedSinceOrdinal === undefined\n ? {}\n : { unconfirmedSinceOrdinal: candidate.unconfirmedSinceOrdinal }),\n ...(candidate.unverified === true ? { unverified: true } : {}),\n ...(candidate.conflict === undefined\n ? {}\n : {\n conflict: {\n peerRecordId: asRecordId(candidate.conflict.peerRecordId),\n unknownRecordId: asRecordId(candidate.conflict.unknownRecordId),\n },\n }),\n ...(audit\n ? {\n audit: {\n status: candidate.status,\n openedAtOrdinal: candidate.validity.openedAtOrdinal,\n closedAtOrdinal,\n },\n }\n : {}),\n scope: candidate.scope,\n validity: candidate.servedAs ?? (audit ? 'audit' : 'current'),\n }\n })\n}\n\nasync function buildIndexLegs(\n connection: IndexReaderConnection,\n input: RetrievalQueryInput,\n scope: RetrievalLegScope,\n n: number,\n options: Pick<RetrieveOptions, 'embeddingCapability'>,\n): Promise<{ legs: RankedLeg[]; query: ReturnType<typeof buildRetrievalQuery> }> {\n const { db } = connection\n const query = buildRetrievalQuery(input)\n const k = candidateLimit(n)\n const lexical = lexicalLeg(db, query.lexicalQuery, scope, k)\n const anchors = anchorSeedLeg(db, query.normalizedAnchors, scope)\n const matchedKeys = new Set(anchors.flatMap((candidate) => candidate.matchedAnchorKeys ?? []))\n const fallback = query.fallbackRenderings.filter(\n (rendering) => !matchedKeys.has(rendering.lookupKey),\n )\n\n let dense: LegCandidate[] = []\n if (hasDenseCandidates(db, scope)) {\n dense = await denseLeg(\n connection,\n [query.semanticText, ...fallback.map((rendering) => rendering.text)],\n scope,\n k,\n options.embeddingCapability === undefined\n ? {}\n : { capability: options.embeddingCapability },\n )\n if (fallback.length > 0) {\n const confirmations = new Map(\n fallback.map((rendering) => [\n rendering.text,\n new Set(\n lexicalLeg(db, rendering.reconfirmToken, scope, k).map(({ bundleId }) => bundleId),\n ),\n ]),\n )\n dense = dense.map((candidate) => {\n const rendering = candidate.matchedDenseRendering\n return rendering !== undefined && confirmations.get(rendering)?.has(candidate.bundleId)\n ? {\n ...candidate,\n rawScores: { ...candidate.rawScores, anchorExact: true },\n }\n : candidate\n })\n }\n }\n\n const tauDense = resolveActiveProfile(db).tau_dense\n return {\n query,\n legs: [\n { weight: query.weights.wLex, ranked: admitLeg(lexical, tauDense) },\n { weight: query.weights.wDense, ranked: admitLeg(dense, tauDense) },\n { weight: query.weights.wAnchor, ranked: admitLeg(anchors, tauDense) },\n ],\n }\n}\n\nasync function retrieveFromIndex(\n context: KnowledgeRetrievalContext,\n input: RetrievalQueryInput,\n scope: RetrievalLegScope,\n options: RetrieveOptions,\n): Promise<RetrieveResult> {\n const connection = context.connection\n if (connection === undefined) throw new Error('index retrieval requires an index connection')\n\n const { legs } = await buildIndexLegs(connection, input, scope, options.n, options)\n const direct = fuseWeightedRrf(legs)\n const expanded = expandOneHop(\n connection.db,\n expansionSeeds(connection.db, direct),\n scope,\n options.n,\n )\n .flatMap((candidate, index) => {\n const hydrated = rowToExpandedLeg(connection.db, candidate.recordRowid, index + 1)\n return hydrated === undefined ? [] : [hydrated]\n })\n const finalLegs: RankedLeg[] = [\n ...legs,\n { weight: 1, ranked: expanded },\n ]\n const capped = capExpansion(fuseWeightedRrf(finalLegs), options.n)\n const candidates = capped.map((candidate) => hydrateFusedCandidate(connection.db, candidate))\n const authoritative = refreshPipelineCandidates(context, candidates)\n const withMemoryOffUnknowns = attachMemoryOffUnknowns(\n context.knowledgeRoot,\n authoritative,\n options,\n context.priors,\n )\n const assembled = applyAssembly(\n withMemoryOffUnknowns,\n mintUnknownConflicts(connection.db),\n options,\n )\n return finalRecheck(context, assembled, scope, options).slice(0, options.n)\n}\n\nfunction scanLegCandidate(\n source: ScanCandidateSource,\n leg: 'anchor' | 'lexical',\n rank: number,\n matchedAnchorKeys: readonly string[] = [],\n): LegCandidate {\n return {\n recordRowid: source.recordRowid,\n bundleId: source.bundleId,\n product: source.product,\n kind: source.kind,\n subtype: source.subtype,\n scopeTier: source.scope.tier,\n scopeKey: source.scope.key,\n status: source.status,\n trust: source.trust,\n openedAtOrdinal: source.validity.openedAtOrdinal,\n ...(source.validity.closedAtOrdinal === undefined\n ? {}\n : { closedAtOrdinal: source.validity.closedAtOrdinal }),\n createdAtOrdinal: source.createdAtOrdinal,\n originClass: source.originClass,\n summary: source.summary,\n embeddingInput: source.embeddingInput,\n source: 'direct',\n legRanks: { [leg]: rank },\n rawScores: leg === 'anchor' ? { anchorExact: true } : { bm25Positive: TAU_LEX },\n ...(matchedAnchorKeys.length === 0 ? {} : { matchedAnchorKeys }),\n }\n}\n\nfunction scanSources(\n context: KnowledgeRetrievalContext,\n hits: readonly KnowledgeHit[],\n scope: RetrievalLegScope,\n includeSuperseded: boolean,\n): ScanCandidateSource[] {\n const filtered = context.recheck(hits, true)\n .filter((hit) => inScope(hit, scope))\n .filter((hit) =>\n includeSuperseded || (hit.status !== 'deprecated' && hit.status !== 'superseded'))\n const byBundle = new Map(filtered.map((hit) => [hit.bundleId, hit]))\n return [...byBundle.values()]\n .sort((left, right) => compareText(left.bundleId, right.bundleId))\n .map((hit, index) => ({ ...hit, recordRowid: index + 1 }))\n}\n\nasync function retrieveFromScan(\n context: KnowledgeRetrievalContext,\n input: RetrievalQueryInput,\n scope: RetrievalLegScope,\n options: RetrieveOptions,\n): Promise<RetrieveResult> {\n const query = buildRetrievalQuery(input)\n const k = candidateLimit(options.n)\n const scan = context.scan\n if (scan === undefined) throw new Error('scan retrieval requires the scan delegate')\n const includeSuperseded = options.includeSuperseded === true\n const lexicalSources = scanSources(\n context,\n query.lexicalQuery === '' ? [] : scan(query.lexicalQuery, undefined),\n scope,\n includeSuperseded,\n ).slice(0, k)\n const anchorMatches = query.normalizedAnchors.map((anchor, index) => ({\n key: query.anchorLookupKeys[index]!,\n hits: scan(undefined, anchor),\n }))\n const anchorSources = scanSources(\n context,\n anchorMatches.flatMap(({ hits }) => hits),\n scope,\n includeSuperseded,\n ).slice(0, k)\n const sourceByBundle = new Map(\n [...lexicalSources, ...anchorSources].map((source) => [source.bundleId, source]),\n )\n const anchorKeysByBundle = new Map<string, Set<string>>()\n for (const { key, hits } of anchorMatches) {\n for (const hit of hits) {\n const keys = anchorKeysByBundle.get(hit.bundleId) ?? new Set<string>()\n keys.add(key)\n anchorKeysByBundle.set(hit.bundleId, keys)\n }\n }\n const lexical = lexicalSources.map((source, index) =>\n scanLegCandidate(source, 'lexical', index + 1))\n const anchor = anchorSources.map((source, index) =>\n scanLegCandidate(\n source,\n 'anchor',\n index + 1,\n [...(anchorKeysByBundle.get(source.bundleId) ?? [])].sort(compareText),\n ))\n const fused = capExpansion(\n fuseWeightedRrf([\n { weight: query.weights.wLex, ranked: lexical },\n { weight: query.weights.wAnchor, ranked: anchor },\n ]),\n options.n,\n )\n const candidates = fused.flatMap((candidate) => {\n const source = sourceByBundle.get(candidate.bundleId)\n if (source === undefined) return []\n const leg = scanLegCandidate(source, 'lexical', source.recordRowid)\n return [{\n ...asKnowledgeHit(leg),\n recordRowid: source.recordRowid,\n source: candidate.source,\n legRanks: candidate.legRanks,\n rawScores: candidate.rawScores,\n fusedScore: candidate.fusedScore,\n anchors: source.anchors,\n scope: source.scope,\n openedAtOrdinal: source.validity.openedAtOrdinal,\n closedAtOrdinal: source.validity.closedAtOrdinal ?? null,\n createdAtOrdinal: source.createdAtOrdinal,\n originClass: source.originClass === 'user' ? 'user' as const : 'agent' as const,\n recencyOrdinal: source.createdAtOrdinal,\n validityClass: 'current' as const,\n lastConfirmedOrdinal: source.lastConfirmedOrdinal,\n vettedCandidateInput: source.vettedCandidateInput,\n }]\n })\n const withMemoryOffUnknowns = attachMemoryOffUnknowns(\n context.knowledgeRoot,\n candidates,\n options,\n context.priors,\n )\n const assembled = applyAssembly(withMemoryOffUnknowns, [], options)\n return finalRecheck(context, assembled, scope, options).slice(0, options.n)\n}\n\nfunction validateOptions(options: RetrieveOptions): void {\n if (!Number.isSafeInteger(options.n) || options.n < 0) {\n throw new RangeError('n must be a non-negative safe integer')\n }\n if (options.product === '') throw new TypeError('product must not be empty')\n}\n\n/** Retrieve a deterministic ranked headline list through the reader's current capability. */\nexport function retrieve(\n reader: KnowledgeReader,\n query: RetrievalQueryInput,\n options: RetrieveOptions,\n): Promise<RetrieveResult> {\n validateOptions(options)\n if (options.n === 0) return Promise.resolve([])\n\n const scope = retrievalScope(options)\n return withKnowledgeReadSnapshot(reader, (context) =>\n context.source === 'index'\n ? retrieveFromIndex(context, query, scope, options)\n : retrieveFromScan(context, query, scope, options))\n}\n","/**\n * D-06/D-07/D-08 degrading reader facade for IDX-02 and memory.md §8.2.\n *\n * Index health is resolved at open and every later index operation is guarded. Any unhealthy state\n * permanently swaps the facade to an authoritative bundle scan plus a durable rebuild request,\n * while healthy readers stay read-only and query-only through openIndexReaderConnection. This\n * module never acquires the writer role or rebuilds inline.\n *\n * ONE ladder, ONE core, two callers (407 D-17, 407-13 CR-02): `classifyIndexFaceWithConnection`\n * runs the degrade ladder exactly once per call and hands back the live connection on the healthy\n * arm. `classifyIndexFace` is the PROBE wrapper — it releases that connection and writes nothing,\n * so `doctor`, the retrieval-rung resolver and the local composition root can ask about the index\n * without mutating it or leaking a handle. `openKnowledgeReader` is the SERVING facade — it KEEPS\n * the connection the ladder blessed and owns the marker write. The facade never closes what it is\n * about to reopen, so there is no window in which contention can degrade a healthy index.\n */\nimport { existsSync, statSync } from 'node:fs'\nimport { basename, join } from 'node:path'\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n canonicalJson,\n normalizeAnchor,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n BundleRelation,\n OriginClass,\n ScopeKey,\n TrustPriorTable,\n VettedCandidateInput,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle, verifyBundleIntegrity } from './bundle-read.js'\nimport {\n isServable,\n scanBundleById,\n scanBundles,\n scanBundlesForRetrieval,\n} from './bundle-scan.js'\nimport type { KnowledgeHit } from './bundle-scan.js'\nimport {\n indexDbPath,\n isEmbeddingVecCleanupCurrent,\n openIndexReaderConnection,\n probeIndexHealth,\n resolveActiveProfile,\n vecTableName,\n} from './index-open.js'\nimport type { IndexReaderConnection, VecCapability } from './index-open.js'\nimport { requestRebuild } from './rebuild-marker.js'\nimport type { RebuildReason } from './rebuild-marker.js'\nimport { buildLexicalMatchExpression } from './retrieval/fts-match.js'\nimport { assemblePromotionGateInput, snapshotTrustPriors } from './promotion-gate-input.js'\nimport {\n effectivePriorDigest,\n indexTrustEpochMatches,\n TrustPriorEpochMismatch,\n} from './trust-prior-context.js'\n\nexport interface KnowledgeSearchOptions {\n product?: string\n k?: number\n}\n\nexport interface DenseSearchOptions extends KnowledgeSearchOptions {\n k: number\n}\n\nexport type DenseHit = KnowledgeHit & { distance: number }\n\nexport interface KnowledgeReader {\n /** Current serving face; permanently changes to scan after an index operation failure. */\n readonly source: 'index' | 'scan'\n /** Current vector capability; changes to none when the serving face degrades to scan. */\n readonly vec: VecCapability | 'none'\n getById(bundleId: string): KnowledgeHit | undefined\n searchLexical(text: string, opts?: KnowledgeSearchOptions): KnowledgeHit[]\n lookupAnchor(anchor: Anchor, opts?: KnowledgeSearchOptions): KnowledgeHit[]\n searchDense(embedding: Float32Array, opts: DenseSearchOptions): DenseHit[]\n recheck(hits: readonly KnowledgeHit[]): KnowledgeHit[]\n close(): void\n}\n\n/** Internal bundle-truth shape consumed by retrieve.ts; deliberately absent from the barrel. */\nexport type AuthoritativeKnowledgeHit<THit extends KnowledgeHit = KnowledgeHit> = Omit<\n THit,\n | keyof KnowledgeHit\n | 'anchors'\n | 'scope'\n | 'createdAtOrdinal'\n | 'originClass'\n | 'relations'\n> & KnowledgeHit & {\n anchors: Anchor[]\n scope: ScopeKey\n createdAtOrdinal: number\n originClass: OriginClass\n relations: readonly BundleRelation[]\n lastConfirmedOrdinal: number\n vettedCandidateInput: VettedCandidateInput\n}\n\n/** Internal snapshot context that lets the public retrieve function compose on this facade. */\nexport interface KnowledgeRetrievalContext {\n readonly knowledgeRoot: string\n readonly priors?: TrustPriorTable\n readonly source: 'index' | 'scan'\n readonly vec: VecCapability | 'none'\n readonly connection: IndexReaderConnection | undefined\n readonly reader: KnowledgeReader\n readonly scan:\n | ((text: string | undefined, anchor: Anchor | undefined) => KnowledgeHit[])\n | undefined\n recheck<THit extends KnowledgeHit>(\n hits: readonly THit[],\n audit: boolean,\n ): Array<AuthoritativeKnowledgeHit<THit>>\n}\n\nexport type KnowledgeRetrievalOperation<TResult> = (\n context: KnowledgeRetrievalContext,\n) => TResult | Promise<TResult>\n\ninterface IndexedRecord {\n hit: KnowledgeHit\n recordRowid: number\n lastConfirmedOrdinal: number\n}\n\ntype RefreshedHit<THit extends KnowledgeHit> = Omit<THit, keyof KnowledgeHit> & KnowledgeHit\n\nconst RUN_RETRIEVAL = Symbol('knowledge-reader.run-retrieval')\n\ninterface InternalKnowledgeReader extends KnowledgeReader {\n [RUN_RETRIEVAL]<TResult>(operation: KnowledgeRetrievalOperation<TResult>): Promise<TResult>\n}\n\nconst RECORD_COLUMNS = `\n r.record_rowid,\n r.bundle_id,\n r.product,\n r.kind,\n r.subtype,\n r.status,\n r.trust,\n r.last_confirmed_ordinal,\n r.opened_at_ordinal,\n r.closed_at_ordinal,\n r.summary,\n r.embedding_input\n`\n\nconst MAX_SQL_LIMIT = 2_147_483_647\n\nexport interface OpenKnowledgeReaderOptions {\n /** Neutral host data retained across every read and index-to-scan transition. */\n priors?: TrustPriorTable\n /** D-12 test seam. Production callers resolve sqlite-vec's pinned prebuild. */\n vecLoadablePath?: string\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction lockedReason(detail: string): boolean {\n return /locked|busy/i.test(detail)\n}\n\nfunction requestRebuildBestEffort(\n knowledgeRoot: string,\n reason: RebuildReason,\n detail: string,\n): void {\n try {\n requestRebuild({ knowledgeRoot, reason, detail })\n } catch {\n // D-07 is an operations signal, not a serving gate. Bundle truth remains available.\n }\n}\n\nfunction closeBestEffort(connection: IndexReaderConnection): void {\n try {\n connection.db.close()\n } catch {\n // Preserve the health failure that selected authoritative scan mode.\n }\n}\n\nfunction queryLimit(k: number | undefined): number {\n if (k === undefined || k === Number.POSITIVE_INFINITY) return MAX_SQL_LIMIT\n if (!Number.isFinite(k)) return 0\n return Math.min(MAX_SQL_LIMIT, Math.max(0, Math.floor(k)))\n}\n\nfunction rowToIndexedRecord(row: Record<string, unknown>): IndexedRecord {\n const closedAt = row.closed_at_ordinal\n const lastConfirmed = row.last_confirmed_ordinal\n return {\n recordRowid: Number(row.record_rowid),\n lastConfirmedOrdinal: Number(\n lastConfirmed === null || lastConfirmed === undefined\n ? row.opened_at_ordinal\n : lastConfirmed,\n ),\n hit: {\n bundleId: String(row.bundle_id),\n product: String(row.product),\n kind: String(row.kind) as KnowledgeHit['kind'],\n subtype: row.subtype === null || row.subtype === undefined\n ? null\n : String(row.subtype),\n status: String(row.status) as KnowledgeHit['status'],\n trust: Number(row.trust),\n validity: {\n openedAtOrdinal: Number(row.opened_at_ordinal),\n ...(closedAt === null || closedAt === undefined\n ? {}\n : { closedAtOrdinal: Number(closedAt) }),\n },\n summary: String(row.summary),\n embeddingInput: String(row.embedding_input),\n },\n }\n}\n\nfunction safeBundleDir(knowledgeRoot: string, hit: KnowledgeHit): string | undefined {\n if (\n hit.product === ''\n || hit.product === '.'\n || hit.product === '..'\n || hit.product !== basename(hit.product)\n || hit.bundleId === ''\n || hit.bundleId === '.'\n || hit.bundleId === '..'\n || hit.bundleId !== basename(hit.bundleId)\n ) {\n return undefined\n }\n return join(knowledgeRoot, 'memory', hit.product, 'bundles', hit.bundleId)\n}\n\n/** D-09: refresh complete truth from a digest-verified bundle and preserve ranking metadata. */\nfunction recheckAuthoritativeHits<THit extends KnowledgeHit>(\n knowledgeRoot: string,\n hits: readonly THit[],\n audit: boolean,\n priors?: TrustPriorTable,\n): Array<AuthoritativeKnowledgeHit<THit>> {\n const refreshed: Array<AuthoritativeKnowledgeHit<THit>> = []\n for (const hit of hits) {\n const bundleDir = safeBundleDir(knowledgeRoot, hit)\n if (bundleDir === undefined) continue\n\n try {\n if (!verifyBundleIntegrity(bundleDir).ok) continue\n const outcome = loadBundle(bundleDir)\n if (outcome.kind !== 'loaded' || outcome.bundle.manifest.id !== hit.bundleId) continue\n const trust = deriveBundleTrust(outcome.bundle, priors)\n if (!audit && !isServable(trust)) continue\n\n refreshed.push({\n ...hit,\n kind: outcome.bundle.frontmatter.kind,\n subtype: outcome.bundle.frontmatter.subtype ?? null,\n status: trust.status,\n trust: trust.trust,\n validity: trust.validity,\n summary: outcome.bundle.summary,\n embeddingInput: outcome.bundle.manifest.embeddingInput,\n anchors: outcome.bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n scope: outcome.bundle.frontmatter.scope,\n createdAtOrdinal: outcome.bundle.frontmatter.createdAtOrdinal,\n originClass: outcome.bundle.frontmatter.originClass,\n relations: outcome.bundle.relations.relations,\n lastConfirmedOrdinal: trust.lastConfirmedOrdinal,\n vettedCandidateInput: assemblePromotionGateInput({\n knowledgeRoot,\n bundleDir,\n bundle: outcome.bundle,\n priors,\n }),\n } as AuthoritativeKnowledgeHit<THit>)\n } catch {\n // A changing, unreadable, or invalid bundle is never safe to serve from a stale index row.\n }\n }\n return refreshed\n}\n\n/** Serving recheck retains the historical KnowledgeHit runtime surface. */\nfunction recheckHits<THit extends KnowledgeHit>(\n knowledgeRoot: string,\n hits: readonly THit[],\n priors?: TrustPriorTable,\n): Array<RefreshedHit<THit>> {\n return recheckAuthoritativeHits(knowledgeRoot, hits, false, priors).map((hit) => {\n const {\n anchors: _anchors,\n scope: _scope,\n createdAtOrdinal: _createdAtOrdinal,\n originClass: _originClass,\n relations: _relations,\n lastConfirmedOrdinal: _lastConfirmedOrdinal,\n vettedCandidateInput: _vettedCandidateInput,\n ...refreshed\n } = hit\n return refreshed as unknown as RefreshedHit<THit>\n })\n}\n\nfunction recordByRowidWithActiveEmbedding(\n db: DatabaseSync,\n recordRowid: number,\n product: string,\n expectedBytes: number,\n): IndexedRecord | undefined {\n const row = db.prepare(`\n SELECT ${RECORD_COLUMNS}\n FROM records r\n WHERE r.record_rowid = ?\n AND r.product = ?\n AND r.embed_status = 'present'\n AND r.embedding IS NOT NULL\n AND length(r.embedding) = ?\n `).get(recordRowid, product, expectedBytes)\n return row === undefined\n ? undefined\n : rowToIndexedRecord(row as Record<string, unknown>)\n}\n\nfunction withReadSnapshot<T>(db: DatabaseSync, operation: () => T): T {\n db.exec('BEGIN')\n try {\n const result = operation()\n db.exec('COMMIT')\n return result\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the SQL or commit error that caused the rollback.\n }\n throw error\n }\n}\n\nasync function withAsyncReadSnapshot<T>(\n db: DatabaseSync,\n operation: () => T | Promise<T>,\n): Promise<T> {\n db.exec('BEGIN')\n try {\n const result = await operation()\n db.exec('COMMIT')\n return result\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the SQL, async operation, or commit error that caused the rollback.\n }\n throw error\n }\n}\n\nfunction float32View(value: unknown): Float32Array | undefined {\n if (!(value instanceof Uint8Array) || value.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0) {\n return undefined\n }\n const alignedCopy = Uint8Array.from(value)\n return new Float32Array(alignedCopy.buffer)\n}\n\nfunction cosineDistance(query: Float32Array, candidate: Float32Array): number | undefined {\n if (candidate.length !== query.length) return undefined\n let dot = 0\n for (let index = 0; index < query.length; index += 1) {\n dot += query[index]! * candidate[index]!\n }\n return 1 - dot\n}\n\nfunction scanReader(knowledgeRoot: string, priors?: TrustPriorTable): InternalKnowledgeReader {\n const reader: InternalKnowledgeReader = {\n source: 'scan',\n vec: 'none',\n getById(bundleId): KnowledgeHit | undefined {\n return scanBundleById({ knowledgeRoot, bundleId, priors })\n },\n searchLexical(text, opts = {}): KnowledgeHit[] {\n return scanBundles({ knowledgeRoot, text, ...opts, priors })\n },\n lookupAnchor(anchor, opts = {}): KnowledgeHit[] {\n // D-16: vec:none is the only reader rung allowed to widen beyond full identity.\n // Normalize through the schema authority before the scan compares role + name.\n return scanBundles({ knowledgeRoot, anchor: normalizeAnchor(anchor), ...opts, priors })\n },\n searchDense(): DenseHit[] {\n return []\n },\n recheck(hits): KnowledgeHit[] {\n return recheckHits(knowledgeRoot, hits, priors)\n },\n close(): void {},\n async [RUN_RETRIEVAL]<TResult>(\n operation: KnowledgeRetrievalOperation<TResult>,\n ): Promise<TResult> {\n return operation({\n knowledgeRoot,\n priors,\n source: 'scan',\n vec: 'none',\n connection: undefined,\n reader,\n scan: (text, anchor) => scanBundlesForRetrieval({\n knowledgeRoot,\n priors,\n ...(text === undefined ? {} : { text }),\n ...(anchor === undefined ? {} : { anchor }),\n }),\n recheck: (hits, audit) => recheckAuthoritativeHits(knowledgeRoot, hits, audit, priors),\n })\n },\n }\n return reader\n}\n\nfunction indexReader(\n knowledgeRoot: string,\n connection: IndexReaderConnection,\n priors?: TrustPriorTable,\n): InternalKnowledgeReader {\n let closed = false\n const { db } = connection\n const activeProfile = resolveActiveProfile(db)\n const priorDigest = effectivePriorDigest(priors)\n let snapshotDepth = 0\n\n function assertTrustEpoch(): void {\n if (!indexTrustEpochMatches(db, priorDigest)) throw new TrustPriorEpochMismatch()\n }\n\n function readSnapshot<TResult>(operation: () => TResult): TResult {\n // Calls made through a retrieval context share its already-pinned WAL snapshot.\n if (snapshotDepth > 0) return operation()\n return withReadSnapshot(db, () => {\n assertTrustEpoch()\n snapshotDepth += 1\n try {\n return operation()\n } finally {\n snapshotDepth -= 1\n }\n })\n }\n\n function recheckCurrent<THit extends KnowledgeHit>(\n hits: readonly THit[],\n ): Array<RefreshedHit<THit>> {\n return recheckHits(knowledgeRoot, hits, priors)\n }\n\n function denseVec0(embedding: Float32Array, opts: DenseSearchOptions): DenseHit[] {\n const k = queryLimit(opts.k)\n if (k === 0) return []\n\n const queryBlob = Buffer.from(\n embedding.buffer,\n embedding.byteOffset,\n embedding.byteLength,\n )\n const tableName = vecTableName(activeProfile)\n const expectedBytes = activeProfile.dim * Float32Array.BYTES_PER_ELEMENT\n\n return readSnapshot(() => {\n // The trust epoch and vector cleanup stamp must share the MATCH snapshot.\n if (!isEmbeddingVecCleanupCurrent(db)) return []\n\n const products = opts.product === undefined\n ? db.prepare(`\n SELECT DISTINCT r.product\n FROM records r\n WHERE r.embed_status = 'present'\n AND r.embedding IS NOT NULL\n AND length(r.embedding) = ?\n ORDER BY r.product\n `).all(expectedBytes).map((row) => String(row.product))\n : [opts.product]\n const knn = db.prepare(`\n SELECT record_rowid, distance\n FROM ${tableName}\n WHERE embedding MATCH ? AND product = ? AND k = ?\n ORDER BY distance\n `)\n const candidates: Array<{\n distance: number\n product: string\n recordRowid: number\n }> = []\n for (const product of products) {\n for (const row of knn.all(queryBlob, product, k)) {\n candidates.push({\n recordRowid: Number(row.record_rowid),\n product,\n distance: Number(row.distance),\n })\n }\n }\n candidates.sort(\n (left, right) => left.distance - right.distance || left.recordRowid - right.recordRowid,\n )\n\n return candidates.slice(0, k).flatMap(({ distance, product, recordRowid }) => {\n const record = recordByRowidWithActiveEmbedding(\n db,\n recordRowid,\n product,\n expectedBytes,\n )\n return record === undefined ? [] : [{ ...record.hit, distance }]\n })\n })\n }\n\n function denseBrute(embedding: Float32Array, opts: DenseSearchOptions): DenseHit[] {\n const k = queryLimit(opts.k)\n if (k === 0) return []\n\n const rows = opts.product === undefined\n ? db.prepare(`\n SELECT ${RECORD_COLUMNS}, r.embedding\n FROM records r\n WHERE r.embedding IS NOT NULL\n ORDER BY r.record_rowid\n `).all()\n : db.prepare(`\n SELECT ${RECORD_COLUMNS}, r.embedding\n FROM records r\n WHERE r.embedding IS NOT NULL AND r.product = ?\n ORDER BY r.record_rowid\n `).all(opts.product)\n const candidates: Array<{ distance: number; record: IndexedRecord }> = []\n for (const row of rows) {\n const vector = float32View(row.embedding)\n if (vector === undefined) continue\n const distance = cosineDistance(embedding, vector)\n if (distance === undefined) continue\n candidates.push({\n record: rowToIndexedRecord(row as Record<string, unknown>),\n distance,\n })\n }\n candidates.sort(\n (left, right) => left.distance - right.distance\n || left.record.recordRowid - right.record.recordRowid,\n )\n const hits = candidates\n .slice(0, k)\n .map(({ distance, record }) => ({ ...record.hit, distance }))\n return hits\n }\n\n const reader: InternalKnowledgeReader = {\n source: 'index',\n vec: connection.vec,\n getById(bundleId): KnowledgeHit | undefined {\n const row = db.prepare(`\n SELECT ${RECORD_COLUMNS}\n FROM records r\n WHERE r.bundle_id = ?\n `).get(bundleId)\n if (row === undefined) return undefined\n return recheckCurrent([rowToIndexedRecord(row as Record<string, unknown>).hit])[0]\n },\n searchLexical(text, opts = {}): KnowledgeHit[] {\n const k = queryLimit(opts.k)\n if (k === 0) return []\n const match = buildLexicalMatchExpression(text)\n const rows = match === ''\n ? opts.product === undefined\n ? db.prepare(`\n SELECT ${RECORD_COLUMNS}\n FROM records r\n ORDER BY r.record_rowid\n LIMIT ?\n `).all(k)\n : db.prepare(`\n SELECT ${RECORD_COLUMNS}\n FROM records r\n WHERE r.product = ?\n ORDER BY r.record_rowid\n LIMIT ?\n `).all(opts.product, k)\n : opts.product === undefined\n ? db.prepare(`\n SELECT ${RECORD_COLUMNS}\n FROM fts_records\n JOIN records r ON r.record_rowid = fts_records.rowid\n WHERE fts_records MATCH ?\n ORDER BY bm25(fts_records), r.bundle_id\n LIMIT ?\n `).all(match, k)\n : db.prepare(`\n SELECT ${RECORD_COLUMNS}\n FROM fts_records\n JOIN records r ON r.record_rowid = fts_records.rowid\n WHERE fts_records MATCH ? AND r.product = ?\n ORDER BY bm25(fts_records), r.bundle_id\n LIMIT ?\n `).all(match, opts.product, k)\n return recheckCurrent(\n rows.map((row) => rowToIndexedRecord(row as Record<string, unknown>).hit),\n )\n },\n lookupAnchor(anchor, opts = {}): KnowledgeHit[] {\n const k = queryLimit(opts.k)\n if (k === 0) return []\n const normalized = canonicalJson(normalizeAnchor(anchor))\n const rows = opts.product === undefined\n ? db.prepare(`\n SELECT DISTINCT ${RECORD_COLUMNS}\n FROM anchors a\n JOIN records r ON r.record_rowid = a.record_rowid\n WHERE a.normalized_json = ?\n ORDER BY r.record_rowid\n LIMIT ?\n `).all(normalized, k)\n : db.prepare(`\n SELECT DISTINCT ${RECORD_COLUMNS}\n FROM anchors a\n JOIN records r ON r.record_rowid = a.record_rowid\n WHERE a.normalized_json = ? AND r.product = ?\n ORDER BY r.record_rowid\n LIMIT ?\n `).all(normalized, opts.product, k)\n return recheckCurrent(\n rows.map((row) => rowToIndexedRecord(row as Record<string, unknown>).hit),\n )\n },\n searchDense(embedding, opts): DenseHit[] {\n const hits = connection.vec === 'vec0'\n ? denseVec0(embedding, opts)\n : denseBrute(embedding, opts)\n return recheckCurrent(hits)\n },\n recheck(hits): KnowledgeHit[] {\n return recheckCurrent(hits)\n },\n close(): void {\n if (closed) return\n closed = true\n connection.db.close()\n },\n async [RUN_RETRIEVAL]<TResult>(\n operation: KnowledgeRetrievalOperation<TResult>,\n ): Promise<TResult> {\n return withAsyncReadSnapshot(db, async () => {\n assertTrustEpoch()\n snapshotDepth += 1\n try {\n return await operation({\n knowledgeRoot,\n priors,\n source: 'index',\n vec: connection.vec,\n connection,\n reader: snapshotReader,\n scan: undefined,\n recheck: (hits, audit) => recheckAuthoritativeHits(knowledgeRoot, hits, audit, priors),\n })\n } finally {\n snapshotDepth -= 1\n }\n })\n },\n }\n const snapshotReader: InternalKnowledgeReader = {\n ...reader,\n getById: (id) => readSnapshot(() => reader.getById(id)),\n searchLexical: (text, opts) => readSnapshot(() => reader.searchLexical(text, opts)),\n lookupAnchor: (anchor, opts) => readSnapshot(() => reader.lookupAnchor(anchor, opts)),\n searchDense: (embedding, opts) => readSnapshot(() => reader.searchDense(embedding, opts)),\n }\n return snapshotReader\n}\n\n/**\n * Keep index failures behind a live facade so callers retain one reader while\n * its source and vector capability permanently degrade to authoritative scans.\n */\nfunction operationDegradingReader(\n knowledgeRoot: string,\n connection: IndexReaderConnection,\n priors?: TrustPriorTable,\n): InternalKnowledgeReader {\n let delegate = indexReader(knowledgeRoot, connection, priors)\n let closed = false\n\n function invoke<TResult>(operation: (reader: KnowledgeReader) => TResult): TResult {\n if (delegate.source === 'scan') return operation(delegate)\n\n try {\n return operation(delegate)\n } catch (error) {\n closeBestEffort(connection)\n if (!(error instanceof TrustPriorEpochMismatch)) {\n requestRebuildBestEffort(\n knowledgeRoot,\n 'corrupt',\n `derived index operation failed: ${errorMessage(error)}`,\n )\n }\n delegate = scanReader(knowledgeRoot, priors)\n return operation(delegate)\n }\n }\n\n async function invokeAsync<TResult>(\n operation: (reader: InternalKnowledgeReader) => TResult | Promise<TResult>,\n ): Promise<TResult> {\n if (delegate.source === 'scan') return operation(delegate)\n\n try {\n return await operation(delegate)\n } catch (error) {\n closeBestEffort(connection)\n if (!(error instanceof TrustPriorEpochMismatch)) {\n requestRebuildBestEffort(\n knowledgeRoot,\n 'corrupt',\n `derived index operation failed: ${errorMessage(error)}`,\n )\n }\n delegate = scanReader(knowledgeRoot, priors)\n return operation(delegate)\n }\n }\n\n const reader: InternalKnowledgeReader = {\n get source(): 'index' | 'scan' {\n return delegate.source\n },\n get vec(): VecCapability | 'none' {\n return delegate.vec\n },\n getById(bundleId): KnowledgeHit | undefined {\n return invoke((reader) => reader.getById(bundleId))\n },\n searchLexical(text, opts = {}): KnowledgeHit[] {\n return invoke((reader) => reader.searchLexical(text, opts))\n },\n lookupAnchor(anchor, opts = {}): KnowledgeHit[] {\n return invoke((reader) => reader.lookupAnchor(anchor, opts))\n },\n searchDense(embedding, opts): DenseHit[] {\n return invoke((reader) => reader.searchDense(embedding, opts))\n },\n recheck(hits): KnowledgeHit[] {\n return invoke((reader) => reader.recheck(hits))\n },\n close(): void {\n if (closed) return\n closed = true\n try {\n delegate.close()\n } catch {\n closeBestEffort(connection)\n }\n },\n async [RUN_RETRIEVAL]<TResult>(\n operation: KnowledgeRetrievalOperation<TResult>,\n ): Promise<TResult> {\n return invokeAsync((current) => current[RUN_RETRIEVAL](operation))\n },\n }\n return reader\n}\n\n/**\n * Run one retrieval operation on the facade's current capability. Index work receives one async\n * read snapshot; any operation failure follows the existing permanent index-to-scan retry path.\n */\nexport function withKnowledgeReadSnapshot<TResult>(\n reader: KnowledgeReader,\n operation: KnowledgeRetrievalOperation<TResult>,\n): Promise<TResult> {\n const internal = reader as Partial<InternalKnowledgeReader>\n const run = internal[RUN_RETRIEVAL]\n if (run === undefined) {\n throw new TypeError('retrieve requires a reader created by openKnowledgeReader')\n }\n return (reader as InternalKnowledgeReader)[RUN_RETRIEVAL](operation)\n}\n\nfunction degrade(\n knowledgeRoot: string,\n reason: RebuildReason,\n detail: string,\n priors?: TrustPriorTable,\n): KnowledgeReader {\n requestRebuildBestEffort(knowledgeRoot, reason, detail)\n return scanReader(knowledgeRoot, priors)\n}\n\n/**\n * Which face the derived index presents to a reader RIGHT NOW (407 D-17).\n *\n * `scan` carries the reason the ladder degraded, the detail the rebuild request would have\n * quoted, and whether the file was there at all — `absent` and `corrupt` are the same word to a\n * serving caller but different operator situations, and `doctor` says which.\n */\nexport type IndexFace =\n | { source: 'index' }\n | {\n source: 'scan'\n reason: RebuildReason\n detail: string\n filePresent: boolean\n }\n\n/**\n * The degrade ladder, ONE core, with the live connection on the healthy arm (407-13, CR-02).\n *\n * The healthy arm returns the connection it just probed WITHOUT closing it, because the caller\n * that is about to serve from the index must keep the very connection the ladder blessed. Closing\n * here and reopening in the facade opened a TOCTOU window: a writer, a drain or a sibling reader\n * holding the database across it made the reopen throw SQLITE_BUSY, which the facade could only\n * read as a `locked` degrade — a durable rebuild request plus a process-lifetime swap to bundle\n * scan, for an index that was healthy the whole time. The trust surface must never report a\n * degradation the trust surface itself caused.\n *\n * Unhealthy arms still close: nothing downstream wants a connection to an index that just failed.\n */\ntype ClassifiedIndex =\n | { face: { source: 'index' }; connection: IndexReaderConnection }\n | { face: Extract<IndexFace, { source: 'scan' }>; connection?: undefined }\n\nexport interface ClassifyIndexFaceOptions extends OpenKnowledgeReaderOptions {\n /** `IndexReaderOpenOptions.inspectCheckpointedImmutably`: the probe only, never the facade. */\n inspectCheckpointedImmutably?: boolean\n}\n\nfunction classifyIndexFaceWithConnection(\n knowledgeRoot: string,\n opts: ClassifyIndexFaceOptions,\n): ClassifiedIndex {\n if (!existsSync(indexDbPath(knowledgeRoot))) {\n return {\n face: {\n source: 'scan',\n reason: 'absent',\n detail: 'derived index file is absent',\n filePresent: false,\n },\n }\n }\n\n let connection: IndexReaderConnection\n try {\n connection = openIndexReaderConnection(knowledgeRoot, opts)\n } catch (error) {\n const detail = errorMessage(error)\n return {\n face: {\n source: 'scan',\n reason: lockedReason(detail) ? 'locked' : 'corrupt',\n detail,\n filePresent: true,\n },\n }\n }\n\n const health = probeIndexHealth(connection.db)\n if (!health.ok) {\n closeBestEffort(connection)\n let reason: RebuildReason\n if (health.probe === 'schema-version') {\n reason = 'schema-version'\n } else if (health.probe === 'projection-schema') {\n reason = 'corrupt'\n } else {\n reason = lockedReason(health.reason) ? 'locked' : 'corrupt'\n }\n return { face: { source: 'scan', reason, detail: health.reason, filePresent: true } }\n }\n\n return { face: { source: 'index' }, connection }\n}\n\n/**\n * The degrade ladder as a PURE READ (407 D-17, T-407-10).\n *\n * ONE ladder, ONE core, two callers. {@link openKnowledgeReader} below is the SERVING facade: it\n * keeps the connection the core blessed and keeps the side effect — a degraded open still writes\n * the durable D-07 rebuild request. This function is the PROBE half: the identical checks in the\n * identical order over the identical core, but it releases the connection and writes no marker,\n * because its other callers are the retrieval-rung resolver that `doctor` and the runner's\n * evidence recorder invoke, and the local composition root's knowledge probes. A probe that\n * requested a rebuild would make merely ASKING about the index a mutation of the knowledge root;\n * a probe that returned a live handle would make every `doctor` call a connection leak. The probe\n * hands back a face, never a handle — only the serving facade holds a connection.\n */\nexport function classifyIndexFace(\n knowledgeRoot: string,\n opts: ClassifyIndexFaceOptions = {},\n): IndexFace {\n const inspectedImmutably = opts.inspectCheckpointedImmutably === true\n ? indexFileFingerprint(knowledgeRoot)\n : undefined\n const result = classifyIndexFaceWithConnection(knowledgeRoot, opts)\n if (result.connection !== undefined) closeBestEffort(result.connection)\n if (\n inspectedImmutably !== undefined\n && !inspectedImmutably.walPresent\n && result.face.source === 'scan'\n && result.face.filePresent\n && indexFileChangedSince(knowledgeRoot, inspectedImmutably)\n ) {\n return {\n source: 'scan',\n reason: 'locked',\n detail: 'a writer opened the index while it was being inspected, so the inspection could '\n + `not be trusted (it read: ${result.face.detail}); the index is busy, not known to be `\n + 'corrupt. Check again when the writer finishes.',\n filePresent: true,\n }\n }\n return result.face\n}\n\ninterface IndexFileFingerprint {\n readonly walPresent: boolean\n readonly mtimeMs: number\n readonly ctimeMs: number\n readonly size: number\n readonly ino: number\n}\n\nfunction indexFileFingerprint(knowledgeRoot: string): IndexFileFingerprint | undefined {\n const path = indexDbPath(knowledgeRoot)\n try {\n const stat = statSync(path)\n return { walPresent: existsSync(`${path}-wal`), mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs,\n size: stat.size, ino: stat.ino }\n } catch {\n return undefined\n }\n}\n\n/**\n * 2026-10-03 (quick 261003-lgd, Phase 432 review IN-26): the immutable probe's check and its open\n * are not one step. A writer that opened the index in between (its `-wal` is now there), or that\n * checkpointed while the probe read (the main file changed), changed bytes under a connection\n * SQLite was told cannot change, so a failure read that way is a busy index, not a corrupt one.\n * Only `stat` and `existsSync` are used here: the probe still creates no `-wal`/`-shm`.\n */\nfunction indexFileChangedSince(knowledgeRoot: string, before: IndexFileFingerprint): boolean {\n const after = indexFileFingerprint(knowledgeRoot)\n return after === undefined || after.walPresent || after.mtimeMs !== before.mtimeMs\n || after.ctimeMs !== before.ctimeMs || after.size !== before.size || after.ino !== before.ino\n}\n\n/**\n * The SERVING facade: classify once, then serve from the connection the classifier blessed.\n *\n * 407-13 (CR-02): this used to call the pure probe and then open a SECOND connection of its own,\n * so a lock acquired in the gap between the probe's close and this open degraded a healthy index\n * — writing the durable rebuild marker and dropping every later retrieval in the process to\n * bundle scan on nothing but contention. It also let `resolveRetrievalRung` report `memidex` while\n * the reader it was describing served `bundle-scan`, the exact banner/reality disagreement D-17's\n * one-fold rule exists to prevent. The facade must never close what it is about to reopen: there\n * is one open on the healthy path and no window for a lock to arrive in.\n */\nexport function openKnowledgeReader(\n knowledgeRoot: string,\n opts: OpenKnowledgeReaderOptions = {},\n): KnowledgeReader {\n const priors = snapshotTrustPriors(opts.priors)\n const result = classifyIndexFaceWithConnection(knowledgeRoot, {\n ...opts,\n inspectCheckpointedImmutably: false,\n })\n if (result.connection === undefined) {\n // The marker write lives HERE, in the serving facade, and not in the classifier: requesting a\n // rebuild is what a reader that just failed to serve from the index owes the drainer.\n return degrade(knowledgeRoot, result.face.reason, result.face.detail, priors)\n }\n\n return operationDegradingReader(knowledgeRoot, result.connection, priors)\n}\n","/**\n * D-07's durable, idempotent rebuild signal survives the one-shot CLI process that detected a\n * degraded index. Phase 378's drainer consumes it. The marker lives in the gitignored\n * memory/index partition (Research Pitfall 10), so it deliberately bypasses committed egress.\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nimport { z } from 'zod'\n\nimport { assertWithinKnowledgeRoot } from './knowledge-containment.js'\n\nexport const REBUILD_MARKER_FILE = '.rebuild-requested'\n\nexport type RebuildReason = 'absent' | 'corrupt' | 'locked' | 'schema-version'\n\nexport interface RebuildRequest {\n reason: RebuildReason\n detail: string\n /** D-17 diagnostic operations metadata only; never an input to validity or serving decisions. */\n requestedAt: string\n}\n\nexport interface RequestRebuildOptions {\n knowledgeRoot: string\n reason: RebuildReason\n detail: string\n}\n\nexport type ReadRebuildRequestOutcome =\n | { present: false }\n | { present: true; request: RebuildRequest | undefined }\n\nconst rebuildRequestSchema = z\n .object({\n reason: z.enum(['absent', 'corrupt', 'locked', 'schema-version']),\n detail: z.string(),\n requestedAt: z.string(),\n })\n .strict()\n\nfunction markerPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, 'memory', 'index', REBUILD_MARKER_FILE)\n}\n\n/**\n * Write the first rebuild signal atomically; later signals never overwrite its diagnostic cause.\n */\nexport function requestRebuild(opts: RequestRebuildOptions): void {\n const file = markerPath(opts.knowledgeRoot)\n assertWithinKnowledgeRoot(opts.knowledgeRoot, dirname(file))\n mkdirSync(dirname(file), { recursive: true })\n if (existsSync(file)) return\n\n const request: RebuildRequest = {\n reason: opts.reason,\n detail: opts.detail,\n requestedAt: new Date().toISOString(),\n }\n const temporary = `${file}.tmp-${randomUUID()}`\n try {\n writeFileSync(temporary, `${JSON.stringify(request)}\\n`, { encoding: 'utf8', flag: 'wx' })\n renameSync(temporary, file)\n } finally {\n rmSync(temporary, { force: true })\n }\n}\n\n/** Read a marker through a strict disk-boundary guard; malformed bytes remain a bare signal. */\nexport function readRebuildRequest(knowledgeRoot: string): ReadRebuildRequestOutcome {\n const file = markerPath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return existsSync(file)\n ? { present: true, request: undefined }\n : { present: false }\n }\n\n try {\n const parsed = rebuildRequestSchema.safeParse(JSON.parse(raw))\n return parsed.success\n ? { present: true, request: parsed.data }\n : { present: true, request: undefined }\n } catch {\n return { present: true, request: undefined }\n }\n}\n\n/** Consume the durable rebuild signal. Clearing an absent marker is intentionally a no-op. */\nexport function clearRebuildRequest(knowledgeRoot: string): void {\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(markerPath(knowledgeRoot)))\n rmSync(markerPath(knowledgeRoot), { force: true })\n}\n","/** One deterministic, parameter-bound FTS5 serving contract for every lexical read path. */\nexport const LEXICAL_MATCH_SEMANTICS = 'quoted-token-or-v1' as const\n\nexport function buildLexicalMatchExpression(text: string): string {\n const seen = new Set<string>()\n const clauses: string[] = []\n\n for (const token of text.split(/\\s+/)) {\n if (token === '' || seen.has(token)) continue\n seen.add(token)\n clauses.push(`\"${token.replaceAll('\"', '\"\"')}\"`)\n }\n\n return clauses.join(' OR ')\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\n\nimport {\n canonicalJson,\n guardDistilledObservation,\n guardTrustPriorTable,\n isPromotionReceipt,\n survivingOutcomeEvents,\n supersessionKey,\n} from '@vostride/agent-qa-schema'\nimport type { GateReceipt, PromotionCandidateProvenance, PromotionGateInput, ResolvePromotionPosture, TrustPriorTable } from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, readGateReceipts } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\nimport { scanCanonicalBundles } from './lineage-fold.js'\n\n/** Copy host-owned data before any asynchronous work or writer mutation can observe it. */\nexport function snapshotTrustPriors(priors: TrustPriorTable | undefined): TrustPriorTable | undefined {\n if (priors === undefined) return undefined\n const snapshot = guardTrustPriorTable(priors)\n for (const row of Object.values(snapshot)) Object.freeze(row)\n return Object.freeze(snapshot)\n}\n\nfunction promotionObservations(\n bundleDir: string,\n): PromotionGateInput['distilledObservations'] {\n const file = join(bundleDir, 'observations.jsonl')\n if (!existsSync(file)) return []\n const text = readFileSync(file, 'utf8')\n if (text === '') return []\n if (!text.endsWith('\\n')) {\n throw new SyntaxError('observations.jsonl must end with a newline')\n }\n return text\n .slice(0, -1)\n .split('\\n')\n .map((line) => guardDistilledObservation(JSON.parse(line)))\n}\n\nfunction memoryOffForBundle(\n knowledgeRoot: string,\n bundle: LoadedBundle,\n): boolean {\n const anchors = bundle.frontmatter.anchors.map(({ normalized }) => normalized)\n const markerPrefix = `thrash:${supersessionKey(anchors)}:window:`\n const scope = canonicalJson(bundle.frontmatter.scope)\n // The lineage scan exposes status and identity only; this memory-off check never reads trust.\n return scanCanonicalBundles(knowledgeRoot).some((candidate) =>\n candidate.kind === 'unknown'\n && candidate.status !== 'deprecated'\n && candidate.status !== 'superseded'\n && canonicalJson(candidate.scope) === scope\n && candidate.anchors[0]?.t === 'flow'\n && candidate.anchors[0].name.startsWith(markerPrefix),\n )\n}\n\n/**\n * D-16/D-17 one durable evidence assembly for both admission and later promote().\n * The pure schema gate remains the only verdict authority; this storage-side view\n * performs strict loading and folds current canonical truth without index authority.\n */\nexport function assemblePromotionGateInput(input: {\n knowledgeRoot: string\n bundleDir: string\n bundle: LoadedBundle\n resolvePromotionPosture?: ResolvePromotionPosture\n priors?: TrustPriorTable\n}): PromotionGateInput {\n const trust = deriveBundleTrust(input.bundle, input.priors)\n const survivingEvents = survivingOutcomeEvents(input.bundle.events)\n const runLinkedProvenance = input.bundle.provenance.mode === 'run-linked'\n ? input.bundle.provenance\n : undefined\n const gateLines = readGateReceipts(input.bundleDir, input.bundle.manifest.id) ?? []\n const provenance = candidateProvenanceOf(input.bundleDir, input.bundle)\n const posture = input.resolvePromotionPosture?.({\n id: input.bundle.manifest.id,\n product: basename(dirname(dirname(input.bundleDir))),\n scope: input.bundle.frontmatter.scope,\n provenance,\n })\n return {\n gateReceipts: gateLines.filter((line): line is GateReceipt => !isPromotionReceipt(line)),\n ...(posture === undefined ? {} : { gatePosture: posture }),\n kind: input.bundle.frontmatter.kind,\n ...(input.bundle.frontmatter.subtype === undefined\n ? {}\n : { subtype: input.bundle.frontmatter.subtype }),\n status: trust.status,\n validityOpen: trust.validity.closedAtOrdinal === undefined,\n anchors: input.bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n originClass: input.bundle.frontmatter.originClass,\n withheld: runLinkedProvenance?.withheld === true,\n needsEnrichment: runLinkedProvenance?.needsEnrichment === true,\n evidenceIncomplete: input.bundle.manifest.evidenceIncomplete,\n distilledObservations: promotionObservations(input.bundleDir),\n confirmedOutcomeEvidenceTokens: survivingEvents.flatMap((event) =>\n event.type === 'confirmed' ? [event.evidenceToken] : [],\n ),\n // The current lifecycle event shape does not carry Deprecate origin. Treating\n // any surviving deprecation as sovereign is the fail-closed interpretation;\n // a retracted deprecation is removed above before this evidence is assembled.\n hasUserDeprecateInLineage: survivingEvents.some((event) => event.type === 'deprecated'),\n memoryOffForAnchorGroup: memoryOffForBundle(input.knowledgeRoot, input.bundle),\n }\n}\n\n/** 2026-09-07, 417 D-01: one provenance assembly shared by promotion and the candidate read. */\nexport function candidateProvenanceOf(\n bundleDir: string,\n bundle: LoadedBundle,\n): PromotionCandidateProvenance {\n const runLinked = bundle.provenance.mode === 'run-linked' ? bundle.provenance : undefined\n const gateLines = readGateReceipts(bundleDir, bundle.manifest.id) ?? []\n return {\n runIds: runLinked === undefined ? [] : [runLinked.runId],\n receiptDigests: gateLines.map(line => line.receiptDigest),\n capturedAtOrdinals: [...new Set([\n ...(runLinked?.sourceBuildOrdinal === undefined ? [] : [runLinked.sourceBuildOrdinal]),\n ...survivingOutcomeEvents(bundle.events).map(event => event.buildOrdinal),\n ].filter(Number.isInteger))].sort((left, right) => left - right),\n }\n}\n","import {\n asRecordId,\n normalizeAnchor,\n survivingOutcomeEvents,\n supersessionKey,\n type Anchor,\n type BundleOutcomeEvent,\n type BundleStatus,\n type RecordId,\n type ScopeKey,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle } from './bundle-read.js'\nimport { enumerateBundleDirs } from './bundle-scan.js'\n\n/**\n * LOCKED memory.md §9.5 trip depth. This is a constitution value ratified as\n * three supersessions, never a runtime config key.\n */\nexport const THRASH_MAX_SUPERSESSIONS = 3\n\n/**\n * LOCKED memory.md §9.5 ordinal window. This is a five-build constitution\n * value, never wall-clock time and never a runtime config key.\n */\nexport const THRASH_WINDOW_BUILDS = 5\n\n/**\n * PROVISIONAL 379 Open Question 1 ratification. Stable-window closure runs\n * disposition-side on Confirm and provisionally reuses the five-build thrash\n * width; a later calibrated phase may retune this constant, never via config.\n */\nexport const STABLE_WINDOW_BUILDS = 5\n\n/** PROVISIONAL D-09 burst threshold; calibration owns later tuning, not config. */\nexport const SCOPE_BURST_THRESHOLD = 8\n\n/** PROVISIONAL D-09 ordinal window; calibration owns later tuning, not config. */\nexport const SCOPE_BURST_WINDOW_BUILDS = 5\n\nexport interface CanonicalBundleSnapshot {\n recordId: RecordId\n kind: 'fact' | 'procedure' | 'caution' | 'unknown' | 'policy'\n anchors: readonly Anchor[]\n scope: ScopeKey\n createdAtOrdinal: number\n events: readonly BundleOutcomeEvent[]\n status: BundleStatus\n curationJobId?: string\n}\n\nexport interface SupersessionLineageFold {\n supersededDepthInWindow: number\n latestSupersessionOrdinal?: number\n chainRecordIds: RecordId[]\n windowOpenOrdinal: number\n}\n\nexport interface FirstSeenScopeFold {\n firstSeenCount: number\n windowOpenOrdinal: number\n recordIds: RecordId[]\n supersessionKeys: string[]\n}\n\nexport interface OrdinalWindowOptions {\n windowBuilds: number\n asOfBuildOrdinal?: number\n}\n\nfunction compareRecordIds(left: RecordId, right: RecordId): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction compareSnapshots(\n left: CanonicalBundleSnapshot,\n right: CanonicalBundleSnapshot,\n): number {\n return left.createdAtOrdinal - right.createdAtOrdinal\n || compareRecordIds(left.recordId, right.recordId)\n}\n\nfunction resolveAsOfBuildOrdinal(\n bundles: readonly CanonicalBundleSnapshot[],\n explicit: number | undefined,\n): number {\n if (explicit !== undefined) return explicit\n let latest = 0\n for (const bundle of bundles) {\n latest = Math.max(latest, bundle.createdAtOrdinal)\n for (const event of bundle.events) latest = Math.max(latest, event.buildOrdinal)\n }\n return latest\n}\n\nfunction windowOpenOrdinal(asOfBuildOrdinal: number, windowBuilds: number): number {\n if (!Number.isInteger(windowBuilds) || windowBuilds < 1) {\n throw new TypeError('windowBuilds must be a positive integer')\n }\n // The runner-local ordinal counter starts each product at one.\n return Math.max(1, asOfBuildOrdinal - windowBuilds + 1)\n}\n\n/**\n * Materialize one immutable canonical-bundle snapshot. Index rows never enter a\n * lifecycle decision: every status and event comes from complete bundle truth.\n */\nexport function scanCanonicalBundles(knowledgeRoot: string): CanonicalBundleSnapshot[] {\n return enumerateBundleDirs(knowledgeRoot)\n .flatMap((entry): CanonicalBundleSnapshot[] => {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded') return []\n // Lineage counts events and status; it has no numerical trust projection.\n const status = deriveBundleTrust(loaded.bundle).status\n return [{\n recordId: asRecordId(loaded.bundle.manifest.id),\n kind: loaded.bundle.frontmatter.kind,\n anchors: loaded.bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n scope: loaded.bundle.frontmatter.scope,\n createdAtOrdinal: loaded.bundle.manifest.createdAtOrdinal,\n events: loaded.bundle.events,\n status,\n ...(loaded.bundle.provenance.mode === 'run-linked'\n && loaded.bundle.provenance.curationJobId !== undefined\n ? { curationJobId: loaded.bundle.provenance.curationJobId }\n : {}),\n }]\n })\n .sort(compareSnapshots)\n}\n\n/**\n * Fold superseded depth by the one schema-owned supersession identity.\n *\n * Pitfall 5: only `superseded` events count. A stable multimodal widening emits\n * Confirm and therefore contributes depth zero; a real regime walk emits a\n * Supersede and advances this counter.\n */\nexport function foldSupersessionLineage(\n bundles: readonly CanonicalBundleSnapshot[],\n options: OrdinalWindowOptions,\n): Map<string, SupersessionLineageFold> {\n const asOfBuildOrdinal = resolveAsOfBuildOrdinal(bundles, options.asOfBuildOrdinal)\n const openOrdinal = windowOpenOrdinal(asOfBuildOrdinal, options.windowBuilds)\n const mutable = new Map<string, {\n supersededDepthInWindow: number\n latestSupersessionOrdinal?: number\n chainRecordIds: Set<RecordId>\n }>()\n\n for (const bundle of bundles) {\n if (bundle.kind === 'unknown') continue\n const key = supersessionKey(bundle.anchors)\n let folded = mutable.get(key)\n if (folded === undefined) {\n folded = {\n supersededDepthInWindow: 0,\n chainRecordIds: new Set<RecordId>(),\n }\n mutable.set(key, folded)\n }\n\n for (const event of survivingOutcomeEvents(bundle.events)) {\n if (\n event.type !== 'superseded'\n || event.buildOrdinal < openOrdinal\n || event.buildOrdinal > asOfBuildOrdinal\n ) {\n continue\n }\n folded.supersededDepthInWindow += 1\n folded.latestSupersessionOrdinal = Math.max(\n folded.latestSupersessionOrdinal ?? event.buildOrdinal,\n event.buildOrdinal,\n )\n folded.chainRecordIds.add(bundle.recordId)\n folded.chainRecordIds.add(event.byRecordId)\n }\n }\n\n return new Map(\n [...mutable.entries()].map(([key, folded]) => [key, {\n supersededDepthInWindow: folded.supersededDepthInWindow,\n ...(folded.latestSupersessionOrdinal === undefined\n ? {}\n : { latestSupersessionOrdinal: folded.latestSupersessionOrdinal }),\n chainRecordIds: [...folded.chainRecordIds].sort(compareRecordIds),\n windowOpenOrdinal: openOrdinal,\n }]),\n )\n}\n\n/** Page scopes take precedence; flow scopes cover records without a page anchor. */\nexport function anchorScopeKey(anchors: readonly Anchor[]): string | undefined {\n const normalized = anchors.map(normalizeAnchor)\n const page = normalized.find(\n (anchor): anchor is Extract<Anchor, { t: 'page' }> => anchor.t === 'page',\n )\n if (page !== undefined) return `page:${page.route}`\n const flow = normalized.find(\n (anchor): anchor is Extract<Anchor, { t: 'flow' }> => anchor.t === 'flow',\n )\n return flow === undefined ? undefined : `flow:${flow.name}`\n}\n\n/**\n * Fold first-seen supersession groups by page:/flow: scope. A group contributes\n * exactly once, at its earliest canonical bundle ordinal; later generations do\n * not inflate a restructuring burst.\n */\nexport function foldFirstSeenAnchorsByScope(\n bundles: readonly CanonicalBundleSnapshot[],\n options: OrdinalWindowOptions,\n): Map<string, FirstSeenScopeFold> {\n const asOfBuildOrdinal = resolveAsOfBuildOrdinal(bundles, options.asOfBuildOrdinal)\n const openOrdinal = windowOpenOrdinal(asOfBuildOrdinal, options.windowBuilds)\n const firstBySupersessionKey = new Map<string, CanonicalBundleSnapshot>()\n\n for (const bundle of bundles) {\n if (bundle.kind === 'unknown' || bundle.createdAtOrdinal > asOfBuildOrdinal) continue\n const key = supersessionKey(bundle.anchors)\n const current = firstBySupersessionKey.get(key)\n if (current === undefined || compareSnapshots(bundle, current) < 0) {\n firstBySupersessionKey.set(key, bundle)\n }\n }\n\n const mutable = new Map<string, {\n recordIds: RecordId[]\n supersessionKeys: string[]\n }>()\n for (const [key, first] of firstBySupersessionKey) {\n if (first.createdAtOrdinal < openOrdinal) continue\n const scopeKey = anchorScopeKey(first.anchors)\n if (scopeKey === undefined) continue\n const folded = mutable.get(scopeKey) ?? { recordIds: [], supersessionKeys: [] }\n folded.recordIds.push(first.recordId)\n folded.supersessionKeys.push(key)\n mutable.set(scopeKey, folded)\n }\n\n return new Map(\n [...mutable.entries()].map(([key, folded]) => [key, {\n firstSeenCount: folded.recordIds.length,\n windowOpenOrdinal: openOrdinal,\n recordIds: folded.recordIds.sort(compareRecordIds),\n supersessionKeys: folded.supersessionKeys.sort(),\n }]),\n )\n}\n","import { createHash } from 'node:crypto'\nimport type { DatabaseSync } from 'node:sqlite'\nimport { canonicalJson, guardTrustPriorTable, ORIGIN_PRIORS, type TrustPriorTable } from '@vostride/agent-qa-schema'\n\n/** Neutral fold identity: omitted origins have exactly the provisional meaning. */\nexport function effectivePriorDigest(priors?: TrustPriorTable): string {\n const table = priors === undefined ? undefined : guardTrustPriorTable(priors)\n return createHash('sha256').update(canonicalJson({ ...ORIGIN_PRIORS, ...table })).digest('hex')\n}\n\n/** Call inside the same read transaction as the numerical index selection. */\nexport function indexTrustEpochMatches(db: DatabaseSync, digest: string): boolean {\n return db.prepare(\"SELECT v FROM meta WHERE k = 'trust_prior_digest'\").get()?.v === digest\n && db.prepare('SELECT 1 FROM records WHERE trust_prior_digest != ? LIMIT 1').get(digest) === undefined\n}\n\nexport class TrustPriorEpochMismatch extends Error {\n constructor() { super('index trust epoch differs from the host snapshot') }\n}\n","/**\n * The deterministic memory.md §5.5.8 query door (377 D-13). Every identity anchor is normalized\n * through the schema authority before keys or matching helpers are derived. Raw selector atoms\n * remain lexical-only; dense text and fallback regions are assembled from structured fields.\n */\nimport {\n canonicalJson,\n normalizeAnchor,\n type Anchor,\n type ElementInfo,\n type ScreenState,\n} from '@vostride/agent-qa-schema'\n\nimport { QUERY_CLASS_WEIGHTS } from './retrieval/constants.js'\nimport { classifyQuery, type QueryClass } from './retrieval/query-class.js'\n\nexport interface RetrievalQueryInput {\n screenState?: ScreenState\n intent: string\n anchors: readonly Anchor[]\n}\n\nexport interface FallbackRendering {\n anchorIndex: number\n lookupKey: string\n text: string\n reconfirmToken: string\n fallback: true\n anchorExact: false\n}\n\nexport interface RetrievalQuery {\n lexicalQuery: string\n semanticText: string\n normalizedAnchors: Anchor[]\n anchorLookupKeys: string[]\n queryClass: QueryClass\n weights: (typeof QUERY_CLASS_WEIGHTS)[QueryClass]\n fallbackRenderings: FallbackRendering[]\n}\n\ntype ScreenRegionElement = {\n relation: 'anchor' | 'parent' | 'child' | 'previous' | 'next' | 'screen'\n role: string\n name: string\n labels: string[]\n}\n\nconst RELATION_ORDER: Record<ScreenRegionElement['relation'], number> = {\n anchor: 0,\n parent: 1,\n child: 2,\n previous: 3,\n next: 4,\n screen: 5,\n}\n\nfunction normalizedElementAnchor(element: ElementInfo): Extract<Anchor, { t: 'el' }> {\n return normalizeAnchor({ t: 'el', role: element.role, name: element.name }) as Extract<\n Anchor,\n { t: 'el' }\n >\n}\n\n/**\n * The role+name key used by the vec:none scan rung's widened D-16 comparison. Indexed callers\n * continue to use anchorLookupKey(), which retains the complete normalized identity.\n */\nexport function widenedRoleNameKey(anchor: Anchor): string | undefined {\n const normalized = normalizeAnchor(anchor)\n if (normalized.t !== 'el') return undefined\n return canonicalJson({ name: normalized.name, role: normalized.role })\n}\n\nexport function anchorLookupKey(anchor: Anchor): string {\n return canonicalJson(normalizeAnchor(anchor))\n}\n\nfunction rawLexicalTerms(anchor: Anchor): string[] {\n switch (anchor.t) {\n case 'page':\n return [anchor.route]\n case 'flow':\n return [anchor.name]\n case 'el':\n return [anchor.role, anchor.name]\n case 'platform':\n return [anchor.platform]\n case 'selector':\n return [anchor.literal]\n case 'error':\n return [anchor.message]\n }\n}\n\nfunction normalizedLexicalTerms(anchor: Anchor): string[] {\n switch (anchor.t) {\n case 'page':\n return [anchor.route]\n case 'flow':\n return [anchor.name]\n case 'el':\n return [anchor.role, anchor.name]\n case 'platform':\n return [anchor.platform]\n case 'selector':\n return [anchor.literal]\n case 'error':\n return [anchor.message]\n }\n}\n\nfunction semanticAnchor(anchor: Anchor): Record<string, string | number> | undefined {\n switch (anchor.t) {\n case 'page':\n return { kind: 'page', route: anchor.route }\n case 'flow':\n return { kind: 'flow', name: anchor.name }\n case 'el':\n return {\n kind: 'element',\n role: anchor.role,\n name: anchor.name,\n ...(anchor.ordinal === undefined ? {} : { ordinal: anchor.ordinal }),\n }\n case 'platform':\n return { kind: 'platform', platform: anchor.platform }\n case 'selector':\n return undefined\n case 'error':\n return { kind: 'error', message: anchor.message }\n }\n}\n\nfunction reconfirmToken(anchor: Anchor): string | undefined {\n switch (anchor.t) {\n case 'page':\n return anchor.route\n case 'flow':\n return anchor.name\n case 'el':\n return anchor.name\n case 'platform':\n case 'selector':\n return undefined\n case 'error':\n return anchor.message\n }\n}\n\nfunction normalizedLabels(element: ElementInfo): string[] {\n const values = [\n element.labels.ariaLabel,\n element.labels.placeholder,\n element.labels.title,\n ]\n return [...new Set(values.flatMap((value) => {\n if (value === undefined) return []\n const normalized = normalizeAnchor({ t: 'flow', name: value })\n return normalized.t !== 'flow' || normalized.name === '' ? [] : [normalized.name]\n }))].sort()\n}\n\nfunction regionElement(\n element: ElementInfo,\n relation: ScreenRegionElement['relation'],\n): ScreenRegionElement {\n const normalized = normalizedElementAnchor(element)\n return {\n relation,\n role: normalized.role,\n name: normalized.name,\n labels: normalizedLabels(element),\n }\n}\n\nfunction matchingElementIndex(screenState: ScreenState, anchor: Anchor): number {\n const key = widenedRoleNameKey(anchor)\n if (key === undefined) return -1\n const matchingIndexes = screenState.elements.flatMap((element, index) =>\n widenedRoleNameKey(normalizedElementAnchor(element)) === key ? [index] : [],\n )\n if (matchingIndexes.length === 0) return -1\n\n const normalized = normalizeAnchor(anchor)\n if (normalized.t !== 'el' || normalized.ordinal === undefined) return matchingIndexes[0]!\n const ordinalIndex = Math.max(0, normalized.ordinal - 1)\n return matchingIndexes[ordinalIndex] ?? matchingIndexes[0]!\n}\n\nfunction renderScreenRegion(screenState: ScreenState, anchor: Anchor): string {\n const anchorIndex = matchingElementIndex(screenState, anchor)\n const elementsByRef = new Map(\n screenState.elements.map((element, index) => [element.ref, { element, index }] as const),\n )\n const region = new Map<string, ScreenRegionElement & { screenIndex: number }>()\n\n function add(element: ElementInfo | undefined, relation: ScreenRegionElement['relation']): void {\n if (element === undefined || region.has(element.ref)) return\n const screenIndex = elementsByRef.get(element.ref)?.index ?? Number.MAX_SAFE_INTEGER\n region.set(element.ref, { ...regionElement(element, relation), screenIndex })\n }\n\n const matched = anchorIndex === -1 ? undefined : screenState.elements[anchorIndex]\n if (matched === undefined) {\n for (const element of screenState.elements.slice(0, 5)) add(element, 'screen')\n } else {\n add(matched, 'anchor')\n const parent = matched.hierarchy?.parentRef\n add(parent === undefined ? undefined : elementsByRef.get(parent)?.element, 'parent')\n for (const child of matched.hierarchy?.childRefs ?? []) {\n add(elementsByRef.get(child)?.element, 'child')\n }\n add(screenState.elements[anchorIndex - 1], 'previous')\n add(screenState.elements[anchorIndex + 1], 'next')\n\n if (parent !== undefined) {\n const parentElement = elementsByRef.get(parent)?.element\n for (const sibling of parentElement?.hierarchy?.childRefs ?? []) {\n add(elementsByRef.get(sibling)?.element, 'child')\n }\n }\n }\n\n const orderedRegion = [...region.values()]\n .sort(\n (left, right) =>\n RELATION_ORDER[left.relation] - RELATION_ORDER[right.relation]\n || left.screenIndex - right.screenIndex\n || left.role.localeCompare(right.role)\n || left.name.localeCompare(right.name),\n )\n .map(({ screenIndex: _screenIndex, ...element }) => element)\n\n return canonicalJson({\n anchor: semanticAnchor(anchor) ?? { kind: anchor.t },\n kind: 'live-screen-region',\n platform: screenState.platform,\n region: orderedRegion,\n })\n}\n\nfunction buildFallbackRenderings(\n screenState: ScreenState | undefined,\n normalizedAnchors: readonly Anchor[],\n lookupKeys: readonly string[],\n): FallbackRendering[] {\n if (screenState === undefined) return []\n\n return normalizedAnchors.flatMap((anchor, anchorIndex) => {\n const token = reconfirmToken(anchor)\n if (token === undefined || token === '') return []\n return [{\n anchorIndex,\n lookupKey: lookupKeys[anchorIndex]!,\n text: renderScreenRegion(screenState, anchor),\n reconfirmToken: token,\n fallback: true as const,\n anchorExact: false as const,\n }]\n })\n}\n\n/**\n * Build both recall inputs from structured runner state. Fallback renderings are candidates only:\n * callers use them after exact/normalized anchor lookup misses and may set the admission\n * anchorExact carve-out only after a lexical hit re-confirms reconfirmToken (T-377-23).\n */\nexport function buildRetrievalQuery(input: RetrievalQueryInput): RetrievalQuery {\n const normalizedAnchors = input.anchors.map((anchor) => normalizeAnchor(anchor))\n const anchorLookupKeys = normalizedAnchors.map((anchor) => canonicalJson(anchor))\n const lexicalQuery = [\n input.intent.trim(),\n ...input.anchors.flatMap(rawLexicalTerms),\n ...normalizedAnchors.flatMap(normalizedLexicalTerms),\n ]\n .filter((term) => term !== '')\n .join(' ')\n const semanticText = canonicalJson({\n anchors: normalizedAnchors.flatMap((anchor) => {\n const rendered = semanticAnchor(anchor)\n return rendered === undefined ? [] : [rendered]\n }),\n intent: input.intent.trim(),\n })\n const queryClass = classifyQuery(lexicalQuery)\n\n return {\n lexicalQuery,\n semanticText,\n normalizedAnchors,\n anchorLookupKeys,\n queryClass,\n weights: QUERY_CLASS_WEIGHTS[queryClass],\n fallbackRenderings: buildFallbackRenderings(\n input.screenState,\n normalizedAnchors,\n anchorLookupKeys,\n ),\n }\n}\n","import type { QueryClass } from './query-class.js'\n\n/**\n * Weighted reciprocal-rank-fusion denominator (spec §5.5.3).\n *\n * LOCKED at 60, ratified 2026-07-03. Changing it changes retrieval semantics rather than tuning a\n * deployment preference, so it remains an internal config-free constant.\n */\nexport const C_RRF = 60\n\n/**\n * Maximum one-hop graph fan-out per seed (GRPH-01/D-08).\n *\n * LOCKED at 32 by the phase requirement so graph expansion stays bounded and reproducible.\n */\nexport const FAN_OUT_CAP = 32\n\n/**\n * Positive-scale lexical admission floor (D-05/D-06).\n *\n * Calibrated 2026-07-15 from the schema-v2 `quoted-token-or-v1` serving replay: positive-scale\n * p05 6.864719139232, using linear interpolation and floored to two decimals. SQLite FTS5 returns negated raw bm25()\n * scores, so query sites apply this floor to -bm25(...). M3 owns refinement; D-05 requires no\n * human lock gate.\n */\nexport const TAU_LEX = 6.86\n\n/**\n * Identity-column BM25 weight (D-03).\n *\n * PROVISIONAL 10 pending the Plan 377-09 lexical calibration receipt. The runtime-verified\n * (10, 5, 1) triple keeps identity matches above context-only matches.\n */\nexport const FTS_WEIGHT_IDENTITY = 10\n\n/**\n * Self-content BM25 weight (D-03).\n *\n * PROVISIONAL 5 pending the Plan 377-09 lexical calibration receipt. It preserves self-field\n * relevance between identity and situating context.\n */\nexport const FTS_WEIGHT_CONTENT = 5\n\n/**\n * Situating-context BM25 weight (D-03).\n *\n * PROVISIONAL 1 pending the Plan 377-09 lexical calibration receipt. Context contributes recall\n * without outranking an otherwise-equivalent identity match.\n */\nexport const FTS_WEIGHT_CONTEXT = 1\n\n/**\n * Maximum situating-line length in characters (D-02).\n *\n * PROVISIONAL 240 pending retrieval-quality measurements; the constant-driven shape remains\n * internal and config-free at roughly one to two sentences.\n */\nexport const SITUATING_LINE_MAX_CHARS = 240\n\n/**\n * Maximum expanded share of a requested result budget (D-07).\n *\n * PROVISIONAL 0.25 pending recorded-query evaluation. capExpansion applies ceil(f * N), ensuring\n * graph-derived candidates cannot starve direct matches.\n */\nexport const EXPANSION_FRACTION_F = 0.25\n\n/**\n * Fusion-weight discount for graph-expanded candidates (D-07).\n *\n * PROVISIONAL 0.5 pending recorded-query evaluation; expanded evidence remains secondary to the\n * same query class's direct lexical, dense, and anchor legs.\n */\nexport const EXPANSION_DISCOUNT_WEIGHT = 0.5\n\n/**\n * Graph-node degree above which expansion skips the hub entirely (D-08).\n *\n * PROVISIONAL 64 pending graph-volume measurements. Ubiquity is treated as a poison signal, never\n * as implicit relevance.\n */\nexport const HUB_DEGREE_THRESHOLD = 64\n\n/**\n * Maximum distinct-seed fan-in admitted for an expanded candidate (D-11).\n *\n * PROVISIONAL 4 pending graph-volume measurements. Direct matches remain eligible above this\n * threshold, while ubiquitous expansion candidates are excluded.\n */\nexport const FAN_IN_THRESHOLD_K = 4\n\n/**\n * Maximum assembled results sharing one primary element or flow anchor (D-15/spec §5.5.6).\n *\n * PROVISIONAL 2 within the specified one-to-two range pending diversity measurements. Audit mode\n * bypasses this cap entirely.\n */\nexport const DIVERSITY_CAP_PER_ANCHOR = 2\n\ntype QueryClassWeightVector = {\n readonly wLex: number\n readonly wDense: number\n readonly wAnchor: number\n}\n\n/**\n * Fixed weighted-RRF vector for each deterministic query class (D-06).\n *\n * PROVISIONAL vectors pending M3's learned per-product replacements. Plain RRF with all three\n * weights equal to 1 is the declared cold-start floor; learning may replace vectors, never the\n * classifier itself.\n */\nexport const QUERY_CLASS_WEIGHTS = {\n literal: { wLex: 1.5, wDense: 0.5, wAnchor: 2 },\n mixed: { wLex: 1, wDense: 1, wAnchor: 1.5 },\n semantic: { wLex: 0.5, wDense: 1.5, wAnchor: 1 },\n} as const satisfies Record<QueryClass, QueryClassWeightVector>\n","/**\n * D-06's closed query-class contract. The classifier is deterministic and total; future learned\n * weights may replace class vectors, but they must not replace or widen these classes implicitly.\n */\nexport type QueryClass = 'literal' | 'mixed' | 'semantic'\n\nconst ID_SELECTOR_TOKEN = /^#[A-Za-z_][A-Za-z0-9_-]*[.,;!?]?$/\nconst ATTRIBUTE_SELECTOR_TOKEN = /^\\[[^\\]\\r\\n]+\\][.,;!?]?$/\nconst XPATH_TOKEN = /^\\/\\/\\S+$/\nconst XPATH_QUERY = /^\\/\\/[^\\r\\n]+$/\nconst URL_TOKEN = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/\\S+$/\nconst TEST_ID_TOKEN = /^(?:data-testid|testid)=[^\\s]+$/i\nconst GET_BY_TEST_ID_TOKEN = /^getByTestId\\([^\\)\\r\\n]*\\)[.,;!?]?$/i\nconst ERROR_NAME_TOKEN = /^(?:[A-Za-z_$][A-Za-z0-9_$]*(?:Error|Exception)|Error):$/\nconst ERROR_PREFIX = /^(?:[A-Za-z_$][A-Za-z0-9_$]*(?:Error|Exception)|Error):/\nconst STACK_FRAME = /^\\s*at\\s+\\S+/\n\nconst TOKEN_DETECTORS: readonly RegExp[] = [\n ID_SELECTOR_TOKEN,\n ATTRIBUTE_SELECTOR_TOKEN,\n XPATH_TOKEN,\n URL_TOKEN,\n TEST_ID_TOKEN,\n GET_BY_TEST_ID_TOKEN,\n ERROR_NAME_TOKEN,\n]\n\nfunction isLiteralToken(token: string): boolean {\n return TOKEN_DETECTORS.some((detector) => detector.test(token))\n}\n\nfunction containsBracketSelector(value: string): boolean {\n const opening = value.indexOf('[')\n if (opening === -1) return false\n return value.indexOf(']', opening + 1) > opening + 1\n}\n\nfunction containsStackFrame(value: string): boolean {\n return value.split('\\n').some((line) => STACK_FRAME.test(line))\n}\n\nfunction isOnlyLiteralShape(value: string, tokens: readonly string[]): boolean {\n if (ATTRIBUTE_SELECTOR_TOKEN.test(value) || XPATH_QUERY.test(value)) return true\n return tokens.length > 0 && tokens.every(isLiteralToken)\n}\n\n/**\n * Classify query text through anchored linear-time detectors only (D-06/T-377-09).\n * Empty or detector-free input is semantic; literal-shaped input plus prose is mixed.\n */\nexport function classifyQuery(lexicalQuery: string): QueryClass {\n const value = lexicalQuery.trim()\n if (value === '') return 'semantic'\n\n const tokens = value.split(/\\s+/u)\n const hasLiteralShape =\n tokens.some(isLiteralToken) ||\n containsBracketSelector(value) ||\n ERROR_PREFIX.test(value) ||\n containsStackFrame(value)\n\n if (!hasLiteralShape) return 'semantic'\n return isOnlyLiteralShape(value, tokens) ? 'literal' : 'mixed'\n}\n","/**\n * The single memory.md §5.5.1 scope/status predicate authority (377 D-15, §13.3).\n * FTS joins, brute scans, anchor seeds, and expansion admission bind this exact fragment so the\n * tenancy wall cannot drift between consumers. The vec0 leg in Plan 377-08 mirrors these clauses\n * in vec0 metadata syntax; any predicate change must update that named mirror site in the same\n * change. Scope keys remain caller-owned outputs of the schema scope-key helpers.\n */\nexport interface PreFilterOptions {\n product: string\n testKey: string\n suiteKey: string\n productKey: string\n globalKey: string\n includeSuperseded?: boolean\n}\n\nexport interface PreFilterPredicate {\n sql: string\n binds: string[]\n}\n\nexport interface ScopeLadderPredicateOptions {\n /** Slugged product column value used for the physical tenancy wall. */\n productRow?: string\n /** Logical product scope key stored in record frontmatter. */\n productScope?: string\n /** The member scope requested by Channel 1 or Channel 2. */\n requestedScope?: { tier: 'global' | 'product' | 'suite' | 'test'; key: string }\n /** Known containing scopes, currently the suite that owns a test member. */\n parentScopes?: readonly { tier: 'global' | 'product' | 'suite' | 'test'; key: string }[]\n}\n\nfunction distinctScopePairs(\n scopes: readonly { tier: 'global' | 'product' | 'suite' | 'test'; key: string }[],\n): Array<{ tier: 'product' | 'suite' | 'test'; key: string }> {\n const seen = new Set<string>()\n const result: Array<{ tier: 'product' | 'suite' | 'test'; key: string }> = []\n for (const scope of scopes) {\n if (scope.tier === 'global') continue\n const identity = `${scope.tier}\\u0000${scope.key}`\n if (seen.has(identity)) continue\n seen.add(identity)\n result.push({ tier: scope.tier, key: scope.key })\n }\n return result\n}\n\n/**\n * Shared serving scope ladder for Channel 1 and Channel 2.\n *\n * A concrete request admits global records plus every known containing scope. A test request\n * therefore sees product -> suite (when supplied) -> test, while sibling suites/tests remain\n * excluded by paired tier/key predicates. With no request, callers retain the product-wide scan\n * used by automatic caution matching.\n */\nexport function scopeLadderPredicate(\n options: ScopeLadderPredicateOptions,\n): PreFilterPredicate {\n const clauses: string[] = []\n const binds: string[] = []\n\n if (options.productRow !== undefined) {\n clauses.push(\"(r.product = ? OR r.scope_tier = 'global')\")\n binds.push(options.productRow)\n }\n\n const requested = options.requestedScope\n if (requested !== undefined) {\n if (requested.tier === 'global') {\n clauses.push(\"r.scope_tier = 'global'\")\n } else {\n const scopes = distinctScopePairs([\n ...(options.productScope === undefined\n ? []\n : [{ tier: 'product' as const, key: options.productScope }]),\n ...(options.parentScopes ?? []),\n requested,\n ])\n const pairClauses = scopes.map(() => '(r.scope_tier = ? AND r.scope_key = ?)')\n clauses.push(`(r.scope_tier = 'global'${pairClauses.length === 0 ? '' : ` OR ${pairClauses.join(' OR ')}`})`)\n for (const scope of scopes) binds.push(scope.tier, scope.key)\n }\n }\n\n return {\n sql: clauses.length === 0 ? '1 = 1' : clauses.join('\\nAND '),\n binds,\n }\n}\n\nexport function preFilterPredicate(options: PreFilterOptions): PreFilterPredicate {\n const clauses = [\n ...(options.includeSuperseded === true\n ? []\n : [\"r.status NOT IN ('deprecated', 'superseded')\"]),\n \"(r.product = ? OR r.scope_tier = 'global')\",\n 'r.scope_key IN (?, ?, ?, ?)',\n ]\n\n return {\n sql: clauses.join('\\nAND '),\n binds: [\n options.product,\n options.testKey,\n options.suiteKey,\n options.productKey,\n options.globalKey,\n ],\n }\n}\n","/**\n * Phase 377 D-08 bounded graph expansion (memory.md §5.5.4).\n *\n * The hot path is strictly one hop. Hubs are skipped entirely in both directions; the spec's\n * matched-anchor-type-only alternative is a deliberate non-choice.\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n FAN_IN_THRESHOLD_K,\n FAN_OUT_CAP,\n HUB_DEGREE_THRESHOLD,\n} from './constants.js'\nimport { preFilterPredicate } from './pre-filter.js'\nimport type { PreFilterOptions } from './pre-filter.js'\n\nexport interface ExpansionSeed {\n readonly bundleId: string\n readonly nodeIds: readonly string[]\n}\n\nexport type ExpansionQueryScope = PreFilterOptions\n\nexport interface ExpansionCandidate {\n readonly recordRowid: number\n readonly bundleId: string\n readonly nodeId: string\n readonly trust: number\n readonly recencyOrdinal: number\n readonly source: 'expanded'\n readonly seedBundleIds: readonly string[]\n}\n\ninterface DegreeRow {\n node_id: string\n degree: number\n}\n\ninterface NeighborRow {\n record_rowid: number\n bundle_id: string\n neighbor_node_id: string\n trust: number\n recency_ordinal: number\n}\n\ninterface NormalizedSeed {\n bundleId: string\n nodeIds: string[]\n}\n\ninterface CandidateAccumulator {\n best: ExpansionCandidate\n seedBundleIds: Set<string>\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** Compute undirected incident degree once for the complete expansion query. */\nfunction computeNodeDegrees(db: DatabaseSync): Map<string, number> {\n const rows = db.prepare(`\n WITH edge_endpoints(node_id) AS (\n SELECT src_node_id FROM graph_edges\n UNION ALL\n SELECT dst_node_id FROM graph_edges\n )\n SELECT node_id, COUNT(*) AS degree\n FROM edge_endpoints\n GROUP BY node_id\n ORDER BY node_id ASC\n `).all() as unknown as DegreeRow[]\n\n return new Map(rows.map((row) => [String(row.node_id), Number(row.degree)]))\n}\n\nfunction readNeighbors(\n db: DatabaseSync,\n seedNodeId: string,\n hubNodeIds: readonly string[],\n queryScope: ExpansionQueryScope,\n): NeighborRow[] {\n const predicate = preFilterPredicate(queryScope)\n const hubClause = hubNodeIds.length === 0\n ? ''\n : `AND incident.neighbor_node_id NOT IN (${hubNodeIds.map(() => '?').join(', ')})`\n const hasRecordNodes = db\n .prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'graph_nodes'\")\n .get() !== undefined\n // D-22 completes undirected record-relation traversal. The ordinary incident rows retain\n // edge-owner provenance; this extra arm materializes an outgoing record-node target so a live\n // rename replacement can reach its scrubbed predecessor when audit posture re-admits it.\n const outgoingRecordTargets = hasRecordNodes\n ? `\n UNION ALL\n\n SELECT\n edge.dst_node_id AS neighbor_node_id,\n edge.edge_type,\n target_record.record_rowid,\n edge.recency_ordinal\n FROM graph_edges AS edge\n JOIN graph_nodes AS target ON target.node_id = edge.dst_node_id\n JOIN records AS target_record\n ON target_record.bundle_id = json_extract(target.natural_key_json, '$')\n WHERE edge.src_node_id = ?\n AND target.node_type IN ('fact', 'procedure', 'caution', 'unknown', 'policy')\n `\n : ''\n\n return db.prepare(`\n WITH incident AS (\n SELECT\n edge.dst_node_id AS neighbor_node_id,\n edge.edge_type,\n edge.record_rowid,\n edge.recency_ordinal\n FROM graph_edges AS edge\n WHERE edge.src_node_id = ?\n\n UNION ALL\n\n SELECT\n edge.src_node_id AS neighbor_node_id,\n edge.edge_type,\n edge.record_rowid,\n edge.recency_ordinal\n FROM graph_edges AS edge\n WHERE edge.dst_node_id = ?\n\n ${outgoingRecordTargets}\n )\n SELECT\n r.record_rowid,\n r.bundle_id,\n incident.neighbor_node_id,\n r.trust,\n MAX(incident.recency_ordinal) AS recency_ordinal\n FROM incident\n JOIN records AS r ON r.record_rowid = incident.record_rowid\n WHERE ${predicate.sql}\n AND r.scope_tier <> 'global'\n ${hubClause}\n GROUP BY\n r.record_rowid,\n r.bundle_id,\n incident.neighbor_node_id,\n r.trust\n ORDER BY\n r.trust DESC,\n recency_ordinal DESC,\n incident.neighbor_node_id ASC,\n r.bundle_id ASC\n LIMIT ?\n `).all(\n seedNodeId,\n seedNodeId,\n ...(hasRecordNodes ? [seedNodeId] : []),\n ...predicate.binds,\n ...hubNodeIds,\n FAN_OUT_CAP,\n ) as unknown as NeighborRow[]\n}\n\nfunction compareRoutes(left: ExpansionCandidate, right: ExpansionCandidate): number {\n return right.trust - left.trust\n || right.recencyOrdinal - left.recencyOrdinal\n || compareText(left.nodeId, right.nodeId)\n || compareText(left.bundleId, right.bundleId)\n || left.recordRowid - right.recordRowid\n}\n\nfunction compareCandidates(left: ExpansionCandidate, right: ExpansionCandidate): number {\n return right.trust - left.trust\n || right.recencyOrdinal - left.recencyOrdinal\n || compareText(left.bundleId, right.bundleId)\n || compareText(left.nodeId, right.nodeId)\n || left.recordRowid - right.recordRowid\n}\n\nfunction normalizeSeeds(seeds: readonly ExpansionSeed[]): NormalizedSeed[] {\n const byBundle = new Map<string, Set<string>>()\n for (const seed of seeds) {\n const nodeIds = byBundle.get(seed.bundleId) ?? new Set<string>()\n for (const nodeId of seed.nodeIds) nodeIds.add(nodeId)\n byBundle.set(seed.bundleId, nodeIds)\n }\n return [...byBundle]\n .map(([bundleId, nodeIds]) => ({ bundleId, nodeIds: [...nodeIds].sort(compareText) }))\n .sort((left, right) => compareText(left.bundleId, right.bundleId))\n}\n\nfunction seedMayExpand(db: DatabaseSync, bundleId: string): boolean {\n const row = db.prepare(`\n SELECT scope_tier\n FROM records\n WHERE bundle_id = ?\n ORDER BY record_rowid ASC\n LIMIT 1\n `).get(bundleId)\n return row?.scope_tier === 'product'\n || row?.scope_tier === 'suite'\n || row?.scope_tier === 'test'\n}\n\nexport function expandOneHop(\n db: DatabaseSync,\n seeds: readonly ExpansionSeed[],\n queryScope: ExpansionQueryScope,\n n: number,\n): ExpansionCandidate[] {\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new RangeError('n must be a non-negative safe integer')\n }\n\n const degrees = computeNodeDegrees(db)\n const hubNodeIds = [...degrees]\n .filter(([, degree]) => degree > HUB_DEGREE_THRESHOLD)\n .map(([nodeId]) => nodeId)\n .sort(compareText)\n const hubs = new Set(hubNodeIds)\n const byBundle = new Map<string, CandidateAccumulator>()\n\n for (const seed of normalizeSeeds(seeds)) {\n // D-12: global records remain direct-match-only and never descend into product records.\n if (!seedMayExpand(db, seed.bundleId)) continue\n for (const seedNodeId of seed.nodeIds) {\n if (hubs.has(seedNodeId)) continue\n for (const row of readNeighbors(db, seedNodeId, hubNodeIds, queryScope)) {\n const candidate: ExpansionCandidate = {\n recordRowid: Number(row.record_rowid),\n bundleId: String(row.bundle_id),\n nodeId: String(row.neighbor_node_id),\n trust: Number(row.trust),\n recencyOrdinal: Number(row.recency_ordinal),\n source: 'expanded',\n seedBundleIds: [seed.bundleId],\n }\n const current = byBundle.get(candidate.bundleId)\n if (current === undefined) {\n byBundle.set(candidate.bundleId, {\n best: candidate,\n seedBundleIds: new Set([seed.bundleId]),\n })\n continue\n }\n current.seedBundleIds.add(seed.bundleId)\n if (compareRoutes(candidate, current.best) < 0) current.best = candidate\n }\n }\n }\n\n const expanded: ExpansionCandidate[] = []\n for (const { best, seedBundleIds } of byBundle.values()) {\n /**\n * D-11/§13.1 deliberately treats graph ubiquity as a poison/hub signal rather than a\n * relevance boost. This exclusion is expansion-local; direct recall remains the only door.\n */\n if (seedBundleIds.size > FAN_IN_THRESHOLD_K) continue\n expanded.push({ ...best, seedBundleIds: [...seedBundleIds].sort(compareText) })\n }\n\n // D-07's count cap is deliberately single-owned by fusion.capExpansion; N is contract input only.\n return expanded.sort(compareCandidates)\n}\n","import {\n C_RRF,\n EXPANSION_DISCOUNT_WEIGHT,\n EXPANSION_FRACTION_F,\n TAU_LEX,\n} from './constants.js'\n\nexport type CandidateSource = 'direct' | 'expanded'\n\nexport interface CandidateRawScores {\n readonly bm25Positive?: number\n readonly cosine?: number\n readonly anchorExact?: boolean\n}\n\nexport interface FusionCandidate {\n readonly bundleId: string\n readonly source: CandidateSource\n readonly legRanks: Readonly<Record<string, number>>\n readonly rawScores: CandidateRawScores\n}\n\nexport interface AdmissionFloors {\n readonly tauDense: number\n}\n\nexport interface WeightedRrfLeg<T extends FusionCandidate = FusionCandidate> {\n readonly weight: number\n readonly ranked: readonly T[]\n}\n\nexport type FusedCandidate<T extends FusionCandidate = FusionCandidate> = Omit<\n T,\n 'source' | 'legRanks' | 'rawScores'\n> & {\n readonly source: CandidateSource\n readonly legRanks: Readonly<Record<string, number>>\n readonly rawScores: CandidateRawScores\n readonly fusedScore: number\n}\n\ninterface FusionAccumulator<T extends FusionCandidate> {\n base: T\n source: CandidateSource\n legRanks: Record<string, number>\n rawScores: {\n bm25Positive?: number\n cosine?: number\n anchorExact?: boolean\n }\n fusedScore: number\n}\n\nfunction compareBundleIds(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction mergeRawScores(\n target: FusionAccumulator<FusionCandidate>['rawScores'],\n incoming: CandidateRawScores,\n): void {\n if (incoming.bm25Positive !== undefined) {\n target.bm25Positive = Math.max(target.bm25Positive ?? -Infinity, incoming.bm25Positive)\n }\n if (incoming.cosine !== undefined) {\n target.cosine = Math.max(target.cosine ?? -Infinity, incoming.cosine)\n }\n if (incoming.anchorExact !== undefined) {\n target.anchorExact = (target.anchorExact ?? false) || incoming.anchorExact\n }\n}\n\n/** Apply D-06's disjunctive admission gate before a candidate receives a rank. */\nexport function admitCandidate(\n candidate: Pick<FusionCandidate, 'rawScores'>,\n floors: AdmissionFloors,\n): boolean {\n const { anchorExact, bm25Positive, cosine } = candidate.rawScores\n return (\n anchorExact === true ||\n (cosine !== undefined && cosine >= floors.tauDense) ||\n (bm25Positive !== undefined && bm25Positive >= TAU_LEX)\n )\n}\n\n/**\n * Fuse already-admitted per-leg rankings with weighted RRF (D-06/D-07).\n * Expanded contributions receive the fixed discount, while final ties end in bundle identity.\n */\nexport function fuseWeightedRrf<T extends FusionCandidate>(\n legs: readonly WeightedRrfLeg<T>[],\n): FusedCandidate<T>[] {\n const byBundle = new Map<string, FusionAccumulator<T>>()\n\n for (const leg of legs) {\n const seenInLeg = new Set<string>()\n for (const [index, candidate] of leg.ranked.entries()) {\n if (seenInLeg.has(candidate.bundleId)) continue\n seenInLeg.add(candidate.bundleId)\n\n const contributionWeight =\n candidate.source === 'expanded'\n ? leg.weight * EXPANSION_DISCOUNT_WEIGHT\n : leg.weight\n const contribution = contributionWeight / (C_RRF + index + 1)\n const current = byBundle.get(candidate.bundleId)\n\n if (current === undefined) {\n byBundle.set(candidate.bundleId, {\n base: candidate,\n source: candidate.source,\n legRanks: { ...candidate.legRanks },\n rawScores: { ...candidate.rawScores },\n fusedScore: contribution,\n })\n continue\n }\n\n current.fusedScore += contribution\n Object.assign(current.legRanks, candidate.legRanks)\n mergeRawScores(current.rawScores, candidate.rawScores)\n if (candidate.source === 'direct' && current.source === 'expanded') {\n current.base = candidate\n current.source = 'direct'\n }\n }\n }\n\n return [...byBundle.values()]\n .map(\n (entry) =>\n ({\n ...entry.base,\n source: entry.source,\n legRanks: entry.legRanks,\n rawScores: entry.rawScores,\n fusedScore: entry.fusedScore,\n }) as FusedCandidate<T>,\n )\n .sort(\n (left, right) =>\n right.fusedScore - left.fusedScore ||\n compareBundleIds(left.bundleId, right.bundleId),\n )\n}\n\n/**\n * Keep at most ceil(f*N) expanded candidates while preserving every direct candidate (D-07).\n * Input rank order is preserved. retrieve() owns final top-N after assembly and recheck.\n */\nexport function capExpansion<T extends Pick<FusionCandidate, 'source'>>(\n fused: readonly T[],\n n: number,\n): T[] {\n const resultBudget = Math.max(0, Math.floor(n))\n const expansionBudget = Math.ceil(EXPANSION_FRACTION_F * resultBudget)\n const retained: T[] = []\n let expandedCount = 0\n\n for (const candidate of fused) {\n if (candidate.source === 'expanded') {\n if (expandedCount >= expansionBudget) continue\n expandedCount += 1\n }\n retained.push(candidate)\n }\n\n return retained\n}\n","/**\n * Fail-closed recall legs for memory.md §5.5.2 (377 D-13/T-377-21..23).\n *\n * SQLite owns scope/status exclusion at each scan. Scores stay on their native positive scales for\n * the admission gate, and every ordering ends in a stable record or bundle identity.\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n canonicalJson,\n normalizeAnchor,\n type Anchor,\n} from '@vostride/agent-qa-schema'\n\nimport {\n acquireEmbedder,\n resetEmbedderCapability,\n type AcquireEmbedderOutcome,\n type EmbedderProbes,\n} from '../embedder-acquire.js'\nimport { wrapEmbedderWithCache } from '../embed-cache.js'\nimport type { EmbedderPort } from '../embedder-port.js'\nimport { EmbedderWorkerTimeoutError } from '../embedder-worker/worker-registration.js'\nimport {\n embeddingProfileKey,\n isEmbeddingVecCleanupCurrent,\n resolveActiveProfile,\n vecTableName,\n type IndexReaderConnection,\n} from '../index-open.js'\nimport type { FallbackRendering } from '../query-helper.js'\nimport {\n FTS_WEIGHT_CONTENT,\n FTS_WEIGHT_CONTEXT,\n FTS_WEIGHT_IDENTITY,\n} from './constants.js'\nimport { buildLexicalMatchExpression } from './fts-match.js'\nimport type { CandidateRawScores, FusionCandidate } from './fusion.js'\nimport { preFilterPredicate, type PreFilterOptions } from './pre-filter.js'\n\nexport interface RetrievalLegScope extends PreFilterOptions {}\n\nexport interface LegCandidate extends FusionCandidate {\n readonly recordRowid: number\n readonly product: string\n readonly kind: string\n readonly subtype: string | null\n readonly scopeTier: string\n readonly scopeKey: string\n readonly status: string\n readonly trust: number\n readonly openedAtOrdinal: number\n readonly closedAtOrdinal?: number\n readonly createdAtOrdinal: number\n readonly originClass: string\n readonly summary: string\n readonly embeddingInput: string\n readonly matchedAnchorKeys?: readonly string[]\n readonly matchedDenseRendering?: string\n}\n\nexport interface DenseLegOptions {\n /** Test/integration seam; production omission runs the automatic acquisition ladder. */\n embedder?: EmbedderPort\n /** Host-resolved posture; a non-ready value deliberately suppresses the automatic ladder. */\n capability?: AcquireEmbedderOutcome\n allowDownload?: boolean\n probes?: EmbedderProbes\n}\n\nexport type DenseLegRendering =\n | string\n | readonly string[]\n | readonly FallbackRendering[]\n\ntype CandidateLeg = 'anchor' | 'dense' | 'lexical'\n\ninterface DenseRowCandidate extends LegCandidate {\n distance: number\n}\n\nconst CANDIDATE_COLUMNS = `\n r.record_rowid,\n r.bundle_id,\n r.product,\n r.kind,\n r.subtype,\n r.scope_tier,\n r.scope_key,\n r.status,\n r.trust,\n r.opened_at_ordinal,\n r.closed_at_ordinal,\n r.created_at_ordinal,\n r.origin_class,\n r.summary,\n r.embedding_input\n`\n\nconst MAX_SQL_LIMIT = 2_147_483_647\n\nfunction queryLimit(k: number): number {\n if (k === Number.POSITIVE_INFINITY) return MAX_SQL_LIMIT\n if (!Number.isFinite(k)) return 0\n return Math.min(MAX_SQL_LIMIT, Math.max(0, Math.floor(k)))\n}\n\nfunction compareBundleIds(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction rowToCandidate(\n row: Record<string, unknown>,\n leg: CandidateLeg,\n rank: number,\n rawScores: CandidateRawScores,\n context: Pick<LegCandidate, 'matchedAnchorKeys' | 'matchedDenseRendering'> = {},\n): LegCandidate {\n const closedAt = row.closed_at_ordinal\n return {\n bundleId: String(row.bundle_id),\n recordRowid: Number(row.record_rowid),\n product: String(row.product),\n kind: String(row.kind),\n subtype: row.subtype === null || row.subtype === undefined ? null : String(row.subtype),\n scopeTier: String(row.scope_tier),\n scopeKey: String(row.scope_key),\n status: String(row.status),\n trust: Number(row.trust),\n openedAtOrdinal: Number(row.opened_at_ordinal),\n ...(closedAt === null || closedAt === undefined\n ? {}\n : { closedAtOrdinal: Number(closedAt) }),\n createdAtOrdinal: Number(row.created_at_ordinal),\n originClass: String(row.origin_class),\n summary: String(row.summary),\n embeddingInput: String(row.embedding_input),\n source: 'direct',\n legRanks: { [leg]: rank },\n rawScores,\n ...context,\n }\n}\n\n/** Weighted, sign-corrected FTS5 recall over the shared scope/status join. */\nexport function lexicalLeg(\n db: DatabaseSync,\n lexicalQuery: string,\n scope: RetrievalLegScope,\n requestedK: number,\n): LegCandidate[] {\n const k = queryLimit(requestedK)\n const match = buildLexicalMatchExpression(lexicalQuery)\n if (k === 0 || match === '') return []\n\n const predicate = preFilterPredicate(scope)\n const rows = db.prepare(`\n SELECT ${CANDIDATE_COLUMNS},\n -bm25(fts_records, ?, ?, ?) AS bm25_positive\n FROM fts_records\n JOIN records r ON r.record_rowid = fts_records.rowid\n WHERE fts_records MATCH ?\n AND ${predicate.sql}\n ORDER BY bm25(fts_records, ?, ?, ?), r.bundle_id\n LIMIT ?\n `).all(\n FTS_WEIGHT_IDENTITY,\n FTS_WEIGHT_CONTENT,\n FTS_WEIGHT_CONTEXT,\n match,\n ...predicate.binds,\n FTS_WEIGHT_IDENTITY,\n FTS_WEIGHT_CONTENT,\n FTS_WEIGHT_CONTEXT,\n k,\n )\n\n return rows.map((row, index) =>\n rowToCandidate(\n row as Record<string, unknown>,\n 'lexical',\n index + 1,\n { bm25Positive: Number(row.bm25_positive) },\n ),\n )\n}\n\nfunction denseRenderingTexts(rendering: DenseLegRendering): string[] {\n const values = typeof rendering === 'string'\n ? [rendering]\n : rendering.map((value) => typeof value === 'string' ? value : value.text)\n return [...new Set(values.filter((value) => value !== ''))]\n}\n\nfunction hasEmbedCache(db: DatabaseSync): boolean {\n return db.prepare(`\n SELECT 1 AS present\n FROM sqlite_master\n WHERE type = 'table' AND name = 'embed_cache'\n `).get() !== undefined\n}\n\nasync function queryEmbedder(\n connection: IndexReaderConnection,\n options: DenseLegOptions,\n): Promise<EmbedderPort | undefined> {\n const profile = resolveActiveProfile(connection.db)\n let embedder = options.embedder\n\n if (embedder === undefined && options.capability !== undefined) {\n const outcome = options.capability\n if (\n outcome.kind !== 'ready'\n || embeddingProfileKey(outcome.profile) !== embeddingProfileKey(profile)\n ) {\n return undefined\n }\n embedder = outcome.embedder\n }\n\n if (embedder === undefined && options.capability === undefined) {\n const outcome = await acquireEmbedder({\n preferredProfile: profile,\n allowDownload: options.allowDownload ?? false,\n ...(options.probes === undefined ? {} : { probes: options.probes }),\n })\n if (\n outcome.kind !== 'ready'\n || embeddingProfileKey(outcome.profile) !== embeddingProfileKey(profile)\n ) {\n return undefined\n }\n embedder = outcome.embedder\n }\n if (embedder === undefined) return undefined\n\n // Reader connections cannot create the derived table. An absent cache is a read miss, while a\n // present cache always wraps in check-only mode and can never materialize query rows.\n return hasEmbedCache(connection.db)\n ? wrapEmbedderWithCache({\n embedder,\n profile,\n db: connection.db,\n mode: 'check-only',\n })\n : embedder\n}\n\nfunction queryBlob(embedding: Float32Array): Buffer {\n return Buffer.from(embedding.buffer, embedding.byteOffset, embedding.byteLength)\n}\n\nfunction float32View(value: unknown): Float32Array | undefined {\n if (!(value instanceof Uint8Array) || value.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0) {\n return undefined\n }\n const copied = Uint8Array.from(value)\n return new Float32Array(copied.buffer, copied.byteOffset, copied.byteLength / 4)\n}\n\nfunction cosineDistance(query: Float32Array, candidate: Float32Array): number | undefined {\n if (candidate.length !== query.length) return undefined\n let dot = 0\n let querySquared = 0\n let candidateSquared = 0\n for (let index = 0; index < query.length; index += 1) {\n const queryValue = query[index]!\n const candidateValue = candidate[index]!\n dot += queryValue * candidateValue\n querySquared += queryValue * queryValue\n candidateSquared += candidateValue * candidateValue\n }\n if (querySquared === 0 || candidateSquared === 0) return undefined\n return 1 - dot / Math.sqrt(querySquared * candidateSquared)\n}\n\nfunction hydrateDenseCandidate(\n db: DatabaseSync,\n recordRowid: number,\n distance: number,\n rendering: string,\n scope: RetrievalLegScope,\n expectedBytes: number,\n): DenseRowCandidate | undefined {\n const predicate = preFilterPredicate(scope)\n const row = db.prepare(`\n SELECT ${CANDIDATE_COLUMNS}\n FROM records r\n WHERE r.record_rowid = ?\n AND r.embed_status = 'present'\n AND r.embedding IS NOT NULL\n AND length(r.embedding) = ?\n AND ${predicate.sql}\n `).get(recordRowid, expectedBytes, ...predicate.binds)\n if (row === undefined) return undefined\n\n return {\n ...rowToCandidate(\n row as Record<string, unknown>,\n 'dense',\n 0,\n { cosine: 1 - distance },\n { matchedDenseRendering: rendering },\n ),\n distance,\n }\n}\n\nfunction vecStatusClauses(includeSuperseded: boolean | undefined): string {\n return includeSuperseded === true\n ? ''\n : \"AND status != 'deprecated' AND status != 'superseded'\"\n}\n\nfunction denseVec0(\n connection: IndexReaderConnection,\n embedding: Float32Array,\n rendering: string,\n scope: RetrievalLegScope,\n k: number,\n): DenseRowCandidate[] {\n const { db } = connection\n if (!isEmbeddingVecCleanupCurrent(db)) return []\n\n const profile = resolveActiveProfile(db)\n const expectedBytes = profile.dim * Float32Array.BYTES_PER_ELEMENT\n if (embedding.byteLength !== expectedBytes) {\n throw new RangeError(\n `query embedding byte length ${embedding.byteLength} does not match ${expectedBytes}`,\n )\n }\n const tableName = vecTableName(profile)\n const bytes = queryBlob(embedding)\n const statuses = vecStatusClauses(scope.includeSuperseded)\n\n // Query A: product partition, constrained to its test/suite/product scope keys.\n const productRows = db.prepare(`\n SELECT record_rowid, distance\n FROM ${tableName}\n WHERE embedding MATCH ?\n AND product = ?\n AND scope_key IN (?, ?, ?)\n ${statuses}\n AND k = ?\n ORDER BY distance\n `).all(\n bytes,\n scope.product,\n scope.testKey,\n scope.suiteKey,\n scope.productKey,\n k,\n )\n\n // Query B: partition-unconstrained global reach. Global records retain the enumeration product,\n // so imposing product here would silently lose valid rows stored under another partition.\n const globalRows = db.prepare(`\n SELECT record_rowid, distance\n FROM ${tableName}\n WHERE embedding MATCH ?\n AND scope_tier = 'global'\n AND scope_key = ?\n ${statuses}\n AND k = ?\n ORDER BY distance\n `).all(bytes, scope.globalKey, k)\n\n return [...productRows, ...globalRows]\n .map((row) => ({\n recordRowid: Number(row.record_rowid),\n distance: Number(row.distance),\n }))\n .sort(\n (left, right) => left.distance - right.distance || left.recordRowid - right.recordRowid,\n )\n .slice(0, k)\n .flatMap(({ recordRowid, distance }) => {\n const candidate = hydrateDenseCandidate(\n db,\n recordRowid,\n distance,\n rendering,\n scope,\n expectedBytes,\n )\n return candidate === undefined ? [] : [candidate]\n })\n}\n\nfunction denseBrute(\n connection: IndexReaderConnection,\n embedding: Float32Array,\n rendering: string,\n scope: RetrievalLegScope,\n k: number,\n): DenseRowCandidate[] {\n const { db } = connection\n const profile = resolveActiveProfile(db)\n const expectedBytes = profile.dim * Float32Array.BYTES_PER_ELEMENT\n if (embedding.byteLength !== expectedBytes) {\n throw new RangeError(\n `query embedding byte length ${embedding.byteLength} does not match ${expectedBytes}`,\n )\n }\n const predicate = preFilterPredicate(scope)\n const rows = db.prepare(`\n SELECT ${CANDIDATE_COLUMNS}, r.embedding\n FROM records r\n WHERE r.embed_status = 'present'\n AND r.embedding IS NOT NULL\n AND length(r.embedding) = ?\n AND ${predicate.sql}\n ORDER BY r.record_rowid\n `).all(expectedBytes, ...predicate.binds)\n\n return rows.flatMap((row) => {\n const vector = float32View(row.embedding)\n if (vector === undefined) return []\n const distance = cosineDistance(embedding, vector)\n if (distance === undefined) return []\n return [{\n ...rowToCandidate(\n row as Record<string, unknown>,\n 'dense',\n 0,\n { cosine: 1 - distance },\n { matchedDenseRendering: rendering },\n ),\n distance,\n }]\n })\n .sort(\n (left, right) => left.distance - right.distance || left.recordRowid - right.recordRowid,\n )\n .slice(0, k)\n}\n\n/** Embed query/fallback renderings through a check-only cache and run the selected dense rung. */\nexport async function denseLeg(\n connection: IndexReaderConnection,\n rendering: DenseLegRendering,\n scope: RetrievalLegScope,\n requestedK: number,\n options: DenseLegOptions = {},\n): Promise<LegCandidate[]> {\n const k = queryLimit(requestedK)\n const renderings = denseRenderingTexts(rendering)\n if (k === 0 || renderings.length === 0) return []\n\n const embedder = await queryEmbedder(connection, options)\n if (embedder === undefined) return []\n\n const byRecordRowid = new Map<number, DenseRowCandidate>()\n for (const text of renderings) {\n let embedding: Float32Array\n try {\n embedding = await embedder.embedQuery(text)\n } catch (error) {\n if (!(error instanceof EmbedderWorkerTimeoutError)) throw error\n resetEmbedderCapability()\n return []\n }\n const candidates = connection.vec === 'vec0'\n ? denseVec0(connection, embedding, text, scope, k)\n : denseBrute(connection, embedding, text, scope, k)\n for (const candidate of candidates) {\n const current = byRecordRowid.get(candidate.recordRowid)\n if (\n current === undefined\n || candidate.distance < current.distance\n || (candidate.distance === current.distance\n && (candidate.matchedDenseRendering ?? '') < (current.matchedDenseRendering ?? ''))\n ) {\n byRecordRowid.set(candidate.recordRowid, candidate)\n }\n }\n }\n\n return [...byRecordRowid.values()]\n .sort(\n (left, right) => left.distance - right.distance || left.recordRowid - right.recordRowid,\n )\n .slice(0, k)\n .map(({ distance: _distance, ...candidate }, index) => ({\n ...candidate,\n legRanks: { dense: index + 1 },\n }))\n}\n\n/** Exact canonical normalized-json seeds; widened role+name keys remain scan-rung-only. */\nexport function anchorSeedLeg(\n db: DatabaseSync,\n normalizedAnchors: readonly Anchor[],\n scope: RetrievalLegScope,\n): LegCandidate[] {\n const lookupKeys = [...new Set(\n normalizedAnchors.map((anchor) => canonicalJson(normalizeAnchor(anchor))),\n )]\n if (lookupKeys.length === 0) return []\n\n const predicate = preFilterPredicate(scope)\n const placeholders = lookupKeys.map(() => '?').join(', ')\n const rows = db.prepare(`\n SELECT ${CANDIDATE_COLUMNS}, a.normalized_json\n FROM anchors a\n JOIN records r ON r.record_rowid = a.record_rowid\n WHERE a.normalized_json IN (${placeholders})\n AND ${predicate.sql}\n ORDER BY r.bundle_id, a.normalized_json\n `).all(...lookupKeys, ...predicate.binds)\n\n const grouped = new Map<number, {\n row: Record<string, unknown>\n matchedAnchorKeys: string[]\n }>()\n for (const row of rows) {\n const recordRowid = Number(row.record_rowid)\n const key = String(row.normalized_json)\n const current = grouped.get(recordRowid)\n if (current === undefined) {\n grouped.set(recordRowid, {\n row: row as Record<string, unknown>,\n matchedAnchorKeys: [key],\n })\n } else if (!current.matchedAnchorKeys.includes(key)) {\n current.matchedAnchorKeys.push(key)\n }\n }\n\n return [...grouped.values()]\n .sort((left, right) =>\n compareBundleIds(String(left.row.bundle_id), String(right.row.bundle_id)))\n .map(({ row, matchedAnchorKeys }, index) =>\n rowToCandidate(\n row,\n 'anchor',\n index + 1,\n { anchorExact: true },\n { matchedAnchorKeys },\n ),\n )\n}\n","import { dirname } from 'node:path'\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n DEFAULT_EMBEDDING_PROFILE,\n STATIC_FLOOR_EMBEDDING_PROFILE,\n type EmbeddingProfile,\n} from '@vostride/agent-qa-schema'\n\nimport {\n type EmbedCacheMode,\n wrapEmbedderWithCache,\n} from './embed-cache.js'\nimport { createFloorEmbedder, loadFloorAssets } from './embedder-floor.js'\nimport {\n createNativeEmbedder,\n NativeEmbeddingModuleLoadError,\n} from './embedder-native.js'\nimport type { EmbedderPort } from './embedder-port.js'\nimport {\n asEmbeddingProfile,\n createEmbedderWorkerPort,\n embedderWorkerAgentQaRoot,\n embedderWorkerProcessIsAlive,\n embedderWorkerSocketPath,\n probeEmbedderWorkerSocket,\n readEmbedderWorkerRegistration,\n removeEmbedderWorkerRegistration,\n} from './embedder-worker/worker-registration.js'\nimport { embeddingProfileKey } from './index-open.js'\n\nexport type WorkerDiscoveryResult = { kind: 'no-worker' } | { kind: 'worker' }\nexport type EmbedderRung = 'native' | 'floor'\nexport type EmbedderWorkerPolicy = 'preferred' | 'required'\nexport type DeferReason =\n | 'cold-artifact'\n | 'load-failure'\n | 'worker-unavailable'\n\nexport type AcquireEmbedderOutcome =\n | {\n kind: 'ready'\n rung: EmbedderRung\n profile: EmbeddingProfile\n embedder: EmbedderPort\n }\n | { kind: 'deferred'; reason: DeferReason }\n | { kind: 'lexical-only' }\n\n/**\n * D-12/D-17 test-only capability injection seam.\n *\n * Production callers must omit this field so rung selection reflects host truth. No probe is a\n * user-facing selector, configuration key, environment variable, or CLI switch.\n */\nexport interface EmbedderProbes {\n discoverWorker?: (agentQaRoot: string) => Promise<WorkerDiscoveryResult>\n createNativeEmbedder?: (options: {\n profile: EmbeddingProfile\n allowDownload: boolean\n }) => Promise<EmbedderPort>\n createFloorEmbedder?: () => EmbedderPort | Promise<EmbedderPort>\n}\n\nexport interface AcquireEmbedderOptions {\n preferredProfile?: EmbeddingProfile\n allowDownload: boolean\n /** Daemon posture requires the child; ordinary one-shot callers retain the preferred ladder. */\n workerPolicy?: EmbedderWorkerPolicy\n /** Explicit hosted runtime root. Required policy must never infer it from ambient cwd. */\n agentQaRoot?: string\n cache?: {\n db: DatabaseSync\n mode: EmbedCacheMode\n }\n /** D-12/D-17 test seam. Production callers resolve actual host capabilities. */\n probes?: EmbedderProbes\n}\n\nexport interface ResolveEmbedderCapabilityOptions {\n preferredProfile?: EmbeddingProfile\n allowDownload: boolean\n /** Daemon posture requires the child; ordinary one-shot callers retain the preferred ladder. */\n workerPolicy?: EmbedderWorkerPolicy\n /** Explicit hosted runtime root. Required policy must never infer it from ambient cwd. */\n agentQaRoot?: string\n /** D-12/D-17 test seam. Production callers resolve actual host capabilities. */\n probes?: EmbedderProbes\n}\n\ntype CapabilityOutcome = AcquireEmbedderOutcome\n\nconst processCapabilities = new Map<string, Promise<CapabilityOutcome>>()\nconst injectedCapabilities = new WeakMap<\n EmbedderProbes,\n Map<string, Promise<CapabilityOutcome>>\n>()\nconst injectedCapabilityCaches = new Set<Map<string, Promise<CapabilityOutcome>>>()\n\n/**\n * Invalidate process-lifetime capability resolution without touching process-local pipelines.\n *\n * A named profile clears only its memo entry. Omitting the profile clears every production and\n * probe-isolated entry so a long-lived host can re-probe after its worker or artifact state moves.\n */\nexport function resetEmbedderCapability(profile?: EmbeddingProfile): void {\n if (profile === undefined) {\n processCapabilities.clear()\n for (const capabilities of injectedCapabilityCaches) capabilities.clear()\n injectedCapabilityCaches.clear()\n return\n }\n\n const prefix = capabilityProfilePrefix(profile)\n for (const key of processCapabilities.keys()) {\n if (key.startsWith(prefix)) processCapabilities.delete(key)\n }\n for (const capabilities of injectedCapabilityCaches) {\n for (const key of capabilities.keys()) {\n if (key.startsWith(prefix)) capabilities.delete(key)\n }\n }\n}\n\ninterface WorkerBackedDiscoveryResult {\n readonly kind: 'worker'\n readonly profile: EmbeddingProfile\n readonly embedder: EmbedderPort\n}\n\nexport interface DiscoverEmbedderWorkerOptions {\n /** Test-only shortening seam; production omits this and uses the pinned request deadline. */\n readonly requestTimeoutMs?: number\n}\n\nfunction isWorkerBackedDiscovery(\n result: WorkerDiscoveryResult,\n): result is WorkerDiscoveryResult & WorkerBackedDiscoveryResult {\n if (result.kind !== 'worker') return false\n const candidate = result as WorkerDiscoveryResult & Partial<WorkerBackedDiscoveryResult>\n return candidate.profile !== undefined && candidate.embedder !== undefined\n}\n\n/** D-09's worker arm, rooted in the hosted project rather than ambient process cwd. */\nexport async function discoverEmbedderWorker(\n agentQaRoot: string,\n options: DiscoverEmbedderWorkerOptions = {},\n): Promise<WorkerDiscoveryResult> {\n const projectRoot = dirname(agentQaRoot)\n const outcome = readEmbedderWorkerRegistration(agentQaRoot)\n if (outcome.kind !== 'parsed') return { kind: 'no-worker' }\n\n const { registration } = outcome\n let expectedSocketPath: string\n try {\n expectedSocketPath = embedderWorkerSocketPath(\n agentQaRoot,\n projectRoot,\n registration.instanceId,\n )\n } catch {\n return { kind: 'no-worker' }\n }\n if (registration.socketPath !== expectedSocketPath) return { kind: 'no-worker' }\n\n let pidIsLive: boolean\n try {\n pidIsLive = embedderWorkerProcessIsAlive(registration.pid)\n } catch {\n return { kind: 'no-worker' }\n }\n if (!pidIsLive) {\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n return { kind: 'no-worker' }\n }\n\n if (!await probeEmbedderWorkerSocket(registration.socketPath)) {\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n return { kind: 'no-worker' }\n }\n\n return {\n kind: 'worker',\n profile: asEmbeddingProfile(registration.profile),\n embedder: createEmbedderWorkerPort(\n registration.socketPath,\n registration.profile.dim,\n {\n ...(options.requestTimeoutMs === undefined\n ? {}\n : { requestTimeoutMs: options.requestTimeoutMs }),\n onUnavailable: () => {\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n resetEmbedderCapability(asEmbeddingProfile(registration.profile))\n },\n },\n ),\n } as WorkerDiscoveryResult\n}\n\nfunction errorRecord(error: unknown): Record<string, unknown> | undefined {\n return typeof error === 'object' && error !== null\n ? error as Record<string, unknown>\n : undefined\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction isNativeModuleUnavailable(error: unknown): boolean {\n if (error instanceof NativeEmbeddingModuleLoadError) return true\n\n const code = errorRecord(error)?.code\n if (\n code === 'ERR_MODULE_NOT_FOUND'\n || code === 'MODULE_NOT_FOUND'\n || code === 'ERR_DLOPEN_FAILED'\n ) {\n return true\n }\n\n const message = errorText(error).toLowerCase()\n return message.includes('cannot find package')\n || message.includes('cannot find module')\n || message.includes('could not locate the bindings file')\n}\n\nfunction isColdArtifact(error: unknown, allowDownload: boolean): boolean {\n if (allowDownload) return false\n\n const code = errorRecord(error)?.code\n if (code === 'ENOENT') return true\n\n const message = errorText(error).toLowerCase()\n return message.includes('local_files_only')\n || message.includes('not found locally')\n || message.includes('not present in the local cache')\n || message.includes('not found in the local cache')\n || message.includes('could not locate file')\n}\n\nfunction cacheFor(probes: EmbedderProbes | undefined): Map<string, Promise<CapabilityOutcome>> {\n if (probes === undefined) return processCapabilities\n\n const existing = injectedCapabilities.get(probes)\n if (existing !== undefined) {\n injectedCapabilityCaches.add(existing)\n return existing\n }\n\n const created = new Map<string, Promise<CapabilityOutcome>>()\n injectedCapabilities.set(probes, created)\n injectedCapabilityCaches.add(created)\n return created\n}\n\nfunction capabilityCacheKey(\n profile: EmbeddingProfile,\n workerPolicy: EmbedderWorkerPolicy,\n agentQaRoot: string,\n): string {\n const profileKey = embeddingProfileKey(profile)\n return `${profileKey.length}:${profileKey}:${workerPolicy}:${agentQaRoot}`\n}\n\nfunction capabilityProfilePrefix(profile: EmbeddingProfile): string {\n const profileKey = embeddingProfileKey(profile)\n return `${profileKey.length}:${profileKey}:`\n}\n\nasync function probeFloor(\n factory: NonNullable<EmbedderProbes['createFloorEmbedder']>,\n): Promise<CapabilityOutcome> {\n try {\n const embedder = await factory()\n return {\n kind: 'ready',\n rung: 'floor',\n profile: STATIC_FLOOR_EMBEDDING_PROFILE,\n embedder,\n }\n } catch {\n return { kind: 'lexical-only' }\n }\n}\n\nasync function probeCapability({\n preferredProfile,\n allowDownload,\n workerPolicy,\n agentQaRoot,\n probes,\n}: Required<Pick<\n ResolveEmbedderCapabilityOptions,\n 'preferredProfile' | 'allowDownload' | 'workerPolicy' | 'agentQaRoot'\n>> & Pick<ResolveEmbedderCapabilityOptions, 'probes'>): Promise<CapabilityOutcome> {\n const discoverWorker = probes?.discoverWorker ?? discoverEmbedderWorker\n const nativeFactory = probes?.createNativeEmbedder ?? createNativeEmbedder\n const floorFactory = probes?.createFloorEmbedder ?? (async () => {\n await loadFloorAssets()\n return createFloorEmbedder()\n })\n\n try {\n const worker = await discoverWorker(agentQaRoot)\n if (\n isWorkerBackedDiscovery(worker)\n && embeddingProfileKey(worker.profile) === embeddingProfileKey(preferredProfile)\n ) {\n return {\n kind: 'ready',\n rung: worker.profile.backend === 'static' ? 'floor' : 'native',\n profile: worker.profile,\n embedder: worker.embedder,\n }\n }\n if (workerPolicy === 'required') {\n return { kind: 'deferred', reason: 'worker-unavailable' }\n }\n } catch {\n return {\n kind: 'deferred',\n reason: workerPolicy === 'required' ? 'worker-unavailable' : 'load-failure',\n }\n }\n\n if (preferredProfile.backend === 'static') return probeFloor(floorFactory)\n\n try {\n const embedder = await nativeFactory({ profile: preferredProfile, allowDownload })\n return { kind: 'ready', rung: 'native', profile: preferredProfile, embedder }\n } catch (error) {\n if (isNativeModuleUnavailable(error)) return probeFloor(floorFactory)\n if (isColdArtifact(error, allowDownload)) {\n return { kind: 'deferred', reason: 'cold-artifact' }\n }\n return { kind: 'deferred', reason: 'load-failure' }\n }\n}\n\n/**\n * Resolve the automatic ladder once per profile for this process (D-17).\n *\n * Every host/runtime failure collapses to a typed capability outcome; callers cannot select a\n * rung. Injected test seams receive an isolated memo while production keys solely by the stable\n * embedding profile identity.\n */\nexport function resolveEmbedderCapability(\n options: ResolveEmbedderCapabilityOptions,\n): Promise<CapabilityOutcome> {\n const preferredProfile = options.preferredProfile ?? DEFAULT_EMBEDDING_PROFILE\n const workerPolicy = options.workerPolicy ?? 'preferred'\n if (workerPolicy === 'required' && options.agentQaRoot === undefined) {\n throw new TypeError('workerPolicy required needs an explicit agentQaRoot')\n }\n const agentQaRoot = options.agentQaRoot\n ?? embedderWorkerAgentQaRoot(process.cwd())\n const capabilities = cacheFor(options.probes)\n const key = capabilityCacheKey(preferredProfile, workerPolicy, agentQaRoot)\n const existing = capabilities.get(key)\n if (existing !== undefined) return existing\n\n const pending = probeCapability({\n preferredProfile,\n allowDownload: options.allowDownload,\n workerPolicy,\n agentQaRoot,\n probes: options.probes,\n })\n capabilities.set(key, pending)\n return pending\n}\n\nexport async function acquireEmbedder(\n options: AcquireEmbedderOptions,\n): Promise<AcquireEmbedderOutcome> {\n const outcome = await resolveEmbedderCapability(options)\n if (outcome.kind !== 'ready' || options.cache === undefined) return outcome\n\n return {\n ...outcome,\n embedder: wrapEmbedderWithCache({\n embedder: outcome.embedder,\n profile: outcome.profile,\n db: options.cache.db,\n mode: options.cache.mode,\n }),\n }\n}\n","/**\n * Rebuildable content-hash cache for both embedding legs.\n *\n * The raw rendering hash deliberately excludes profile prefixes because prefix application belongs\n * to EmbedderPort. The explicit leg discriminator closes RESEARCH Pitfall 6: asymmetric document\n * and query embeddings must never alias even when their raw rendering is byte-identical.\n */\nimport { createHash } from 'node:crypto'\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\n\nimport type { EmbedderPort } from './embedder-port.js'\n\nexport type EmbedCacheLeg = 'doc' | 'query'\nexport type EmbedCacheMode = 'check-only' | 'check-and-store'\n\nexport interface EmbedCacheLookup {\n db: DatabaseSync\n profile: EmbeddingProfile\n leg: EmbedCacheLeg\n rendering: string\n}\n\nexport interface EmbedCachePut extends EmbedCacheLookup {\n vector: Float32Array\n}\n\nexport interface EmbedCacheWrapperOptions {\n embedder: EmbedderPort\n profile: EmbeddingProfile\n db: DatabaseSync\n mode: EmbedCacheMode\n}\n\nfunction renderingSha256(rendering: string): string {\n return createHash('sha256').update(rendering).digest('hex')\n}\n\n/** Create the derived cache table from a writer-role connection. */\nexport function ensureEmbedCacheTable(db: DatabaseSync): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS embed_cache (\n model_id TEXT NOT NULL,\n dtype TEXT NOT NULL,\n revision TEXT NOT NULL,\n rendering_sha256 TEXT NOT NULL,\n dim INTEGER NOT NULL,\n leg TEXT NOT NULL CHECK (leg IN ('doc', 'query')),\n embedding BLOB NOT NULL,\n PRIMARY KEY (model_id, dtype, revision, leg, rendering_sha256)\n ) WITHOUT ROWID;\n `)\n}\n\n/** Return a copied vector so callers cannot mutate SQLite-owned row bytes. */\nexport function getCachedEmbedding({\n db,\n profile,\n leg,\n rendering,\n}: EmbedCacheLookup): Float32Array | undefined {\n const row = db\n .prepare(`\n SELECT dim, embedding\n FROM embed_cache\n WHERE model_id = ?\n AND dtype = ?\n AND revision = ?\n AND leg = ?\n AND rendering_sha256 = ?\n `)\n .get(\n profile.model_id,\n profile.dtype,\n profile.revision,\n leg,\n renderingSha256(rendering),\n )\n\n if (row === undefined) return undefined\n if (row.dim !== profile.dim) {\n const actualDim = String(row.dim)\n throw new RangeError(\n `cached embedding dimension ${actualDim} does not match profile dimension ${profile.dim}`,\n )\n }\n if (!(row.embedding instanceof Uint8Array)) {\n throw new TypeError('cached embedding must be a SQLite BLOB')\n }\n\n const expectedBytes = profile.dim * Float32Array.BYTES_PER_ELEMENT\n if (row.embedding.byteLength !== expectedBytes) {\n throw new RangeError(\n `cached embedding byte length ${row.embedding.byteLength} does not match ${expectedBytes}`,\n )\n }\n\n const bytes = Uint8Array.from(row.embedding)\n return new Float32Array(bytes.buffer, bytes.byteOffset, profile.dim)\n}\n\n/** Store an exact Float32 byte copy under the raw-rendering content hash. */\nexport function putCachedEmbedding({\n db,\n profile,\n leg,\n rendering,\n vector,\n}: EmbedCachePut): void {\n if (vector.length !== profile.dim) {\n throw new RangeError(\n `embedding dimension ${vector.length} does not match profile dimension ${profile.dim}`,\n )\n }\n\n const bytes = Uint8Array.from(\n new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength),\n )\n db.prepare(`\n INSERT OR REPLACE INTO embed_cache (\n model_id,\n dtype,\n revision,\n rendering_sha256,\n dim,\n leg,\n embedding\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(\n profile.model_id,\n profile.dtype,\n profile.revision,\n renderingSha256(rendering),\n profile.dim,\n leg,\n bytes,\n )\n}\n\n/** Evict every cached leg/revision/dtype row owned by one model id. */\nexport function dropEmbedCacheForModel(db: DatabaseSync, modelId: string): void {\n db.prepare('DELETE FROM embed_cache WHERE model_id = ?').run(modelId)\n}\n\n/**\n * Decorate an embedder with the M2 connection-role posture.\n *\n * Reader connections use check-only: they benefit from materialized rows but never write on a\n * miss. Writer-role backfill, migration, and bench paths use check-and-store, which is where the\n * steady-state cache materializes. Callers must ensure the table once through a writer first.\n */\nexport function wrapEmbedderWithCache({\n embedder,\n profile,\n db,\n mode,\n}: EmbedCacheWrapperOptions): EmbedderPort {\n async function resolve(\n leg: EmbedCacheLeg,\n rendering: string,\n embed: () => Promise<Float32Array>,\n ): Promise<Float32Array> {\n const cached = getCachedEmbedding({ db, profile, leg, rendering })\n if (cached !== undefined) return cached\n\n const vector = await embed()\n if (mode === 'check-and-store') {\n putCachedEmbedding({ db, profile, leg, rendering, vector })\n }\n return vector\n }\n\n return {\n embedDocument(rendering: string): Promise<Float32Array> {\n return resolve('doc', rendering, () => embedder.embedDocument(rendering))\n },\n embedQuery(rendering: string): Promise<Float32Array> {\n return resolve('query', rendering, () => embedder.embedQuery(rendering))\n },\n }\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { Tokenizer } from '@huggingface/tokenizers'\n\nimport type { EmbedderPort } from './embedder-port.js'\n\nconst PACKAGE_NAME = '@vostride/agent-qa-knowledge-local'\nconst ASSET_DIRECTORY = 'potion-retrieval-32m'\nconst BINARY_FILE = 'potion-retrieval-32m.i8bin'\nconst TOKENIZER_FILE = 'tokenizer.json'\nconst GOLDEN_FILE = 'golden-vectors.json'\nconst MANIFEST_FILE = 'manifest.json'\nconst MODEL_ID = 'minishlab/potion-retrieval-32M'\nconst MODEL_REVISION = '6fc8051fab2a1e0ee76689cf08c853792ac285e7'\nconst FLOOR_MAGIC = 'PTNF'\nconst FLOOR_FORMAT_VERSION = 1\nconst FLOOR_VOCABULARY_SIZE = 63_091\nconst FLOOR_DIMENSION = 512\nconst FLOOR_HEADER_BYTES = 16\nconst MANIFEST_MAX_BYTES = 1024 * 1024\nconst TOKENIZER_MAX_BYTES = 16 * 1024 * 1024\nconst GOLDEN_MAX_BYTES = 8 * 1024 * 1024\nconst SHA256_RE = /^[0-9a-f]{64}$/u\n\nexport type FloorAssetLoadErrorCode =\n | 'package-root-not-found'\n | 'manifest-invalid'\n | 'asset-read-failed'\n | 'asset-size-mismatch'\n | 'digest-mismatch'\n | 'binary-invalid'\n | 'tokenizer-invalid'\n | 'tokenizer-runtime-unavailable'\n\nexport class FloorAssetLoadError extends Error {\n readonly code: FloorAssetLoadErrorCode\n\n constructor(code: FloorAssetLoadErrorCode, message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = 'FloorAssetLoadError'\n this.code = code\n }\n}\n\nexport type FloorEmbeddingErrorCode =\n | 'empty-token-set'\n | 'token-id-out-of-range'\n | 'zero-vector'\n\nexport class FloorEmbeddingError extends Error {\n readonly code: FloorEmbeddingErrorCode\n\n constructor(code: FloorEmbeddingErrorCode, message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = 'FloorEmbeddingError'\n this.code = code\n }\n}\n\ninterface ManifestFileEntry {\n bytes: number\n sha256: string\n}\n\ninterface FloorManifest {\n modelId: string\n revision: string\n artifact: {\n magic: string\n version: number\n vocabularySize: number\n dimension: number\n quantization: string\n }\n files: Record<string, ManifestFileEntry>\n}\n\nexport interface FloorAssets {\n tokenizer: Tokenizer\n vocabularySize: number\n dimension: number\n scales: Float32Array\n weights: Int8Array\n}\n\nexport interface FloorAssetLoadOptions {\n /** Test-only injection seam. Production callers resolve the committed package asset. */\n assetsDir?: string\n /** Optional caller-owned token cap for bounded benchmark/runtime work. */\n maxTokens?: number\n}\n\nlet memoizedDefaultAssets: Promise<FloorAssets> | undefined\nlet tokenizerRuntime: Promise<typeof import('@huggingface/tokenizers')> | undefined\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction packageRootFromImportMeta(): string {\n let current = dirname(fileURLToPath(import.meta.url))\n while (true) {\n const packageJsonPath = join(current, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson: unknown = JSON.parse(readFileSync(packageJsonPath, 'utf8'))\n if (isRecord(packageJson) && packageJson.name === PACKAGE_NAME) return current\n } catch {\n // A parent package with unreadable metadata is not this package; continue upward.\n }\n }\n const parent = dirname(current)\n if (parent === current) break\n current = parent\n }\n throw new FloorAssetLoadError(\n 'package-root-not-found',\n `could not resolve ${PACKAGE_NAME} from ${fileURLToPath(import.meta.url)}`,\n )\n}\n\nfunction manifestEntry(value: unknown, file: string): ManifestFileEntry {\n if (!isRecord(value)) {\n throw new FloorAssetLoadError('manifest-invalid', `manifest files.${file} is invalid`)\n }\n if (!Number.isSafeInteger(value.bytes) || Number(value.bytes) <= 0) {\n throw new FloorAssetLoadError(\n 'manifest-invalid',\n `manifest files.${file}.bytes must be a positive safe integer`,\n )\n }\n if (typeof value.sha256 !== 'string' || !SHA256_RE.test(value.sha256)) {\n throw new FloorAssetLoadError(\n 'manifest-invalid',\n `manifest files.${file}.sha256 must be a lowercase sha256 digest`,\n )\n }\n return { bytes: Number(value.bytes), sha256: value.sha256 }\n}\n\nfunction parseManifest(value: unknown): FloorManifest {\n if (!isRecord(value) || value.schemaVersion !== 1 || value.format !== 'potion-static-int8') {\n throw new FloorAssetLoadError('manifest-invalid', 'floor manifest identity is invalid')\n }\n if (value.modelId !== MODEL_ID || value.revision !== MODEL_REVISION) {\n throw new FloorAssetLoadError('manifest-invalid', 'floor manifest model pin is invalid')\n }\n if (!isRecord(value.artifact)) {\n throw new FloorAssetLoadError('manifest-invalid', 'floor manifest artifact is invalid')\n }\n const artifact = value.artifact\n if (\n artifact.magic !== FLOOR_MAGIC ||\n artifact.version !== FLOOR_FORMAT_VERSION ||\n artifact.vocabularySize !== FLOOR_VOCABULARY_SIZE ||\n artifact.dimension !== FLOOR_DIMENSION ||\n artifact.quantization !== 'symmetric-per-row-int8'\n ) {\n throw new FloorAssetLoadError('manifest-invalid', 'floor manifest artifact lock is invalid')\n }\n if (!isRecord(value.files)) {\n throw new FloorAssetLoadError('manifest-invalid', 'floor manifest files are invalid')\n }\n const manifestFiles = value.files\n const requiredFiles = [BINARY_FILE, TOKENIZER_FILE, GOLDEN_FILE] as const\n const fileNames = Object.keys(manifestFiles).sort()\n if (\n fileNames.length !== requiredFiles.length ||\n requiredFiles.some((file) => !fileNames.includes(file))\n ) {\n throw new FloorAssetLoadError(\n 'manifest-invalid',\n 'floor manifest must contain exactly the committed runtime payloads',\n )\n }\n return {\n modelId: MODEL_ID,\n revision: MODEL_REVISION,\n artifact: {\n magic: FLOOR_MAGIC,\n version: FLOOR_FORMAT_VERSION,\n vocabularySize: FLOOR_VOCABULARY_SIZE,\n dimension: FLOOR_DIMENSION,\n quantization: 'symmetric-per-row-int8',\n },\n files: Object.fromEntries(\n requiredFiles.map((file) => [file, manifestEntry(manifestFiles[file], file)]),\n ),\n }\n}\n\nfunction readManifest(assetsDir: string): FloorManifest {\n const path = join(assetsDir, MANIFEST_FILE)\n try {\n const size = statSync(path).size\n if (size <= 0 || size > MANIFEST_MAX_BYTES) {\n throw new FloorAssetLoadError(\n 'manifest-invalid',\n `floor manifest byte length ${size} is outside the accepted range`,\n )\n }\n return parseManifest(JSON.parse(readFileSync(path, 'utf8')))\n } catch (error) {\n if (error instanceof FloorAssetLoadError) throw error\n throw new FloorAssetLoadError(\n 'manifest-invalid',\n `could not read floor manifest: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n}\n\nfunction expectedBinaryBytes(vocabularySize: number, dimension: number): number {\n const scalesBytes = vocabularySize * Float32Array.BYTES_PER_ELEMENT\n const weightsBytes = vocabularySize * dimension\n const total = FLOOR_HEADER_BYTES + scalesBytes + weightsBytes\n if (!Number.isSafeInteger(total)) {\n throw new FloorAssetLoadError('binary-invalid', 'floor binary length is not safe')\n }\n return total\n}\n\nfunction assertExpectedFileSize(\n assetsDir: string,\n file: string,\n entry: ManifestFileEntry,\n maximumBytes: number,\n): void {\n let actualBytes: number\n try {\n actualBytes = statSync(join(assetsDir, file)).size\n } catch (error) {\n throw new FloorAssetLoadError(\n 'asset-read-failed',\n `could not stat floor asset ${file}: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n if (actualBytes !== entry.bytes || actualBytes <= 0 || actualBytes > maximumBytes) {\n throw new FloorAssetLoadError(\n 'asset-size-mismatch',\n `floor asset ${file} has ${actualBytes} bytes; manifest declares ${entry.bytes}`,\n )\n }\n}\n\nfunction readAndVerifyFile(\n assetsDir: string,\n file: string,\n entry: ManifestFileEntry,\n): Buffer {\n let bytes: Buffer\n try {\n bytes = readFileSync(join(assetsDir, file))\n } catch (error) {\n throw new FloorAssetLoadError(\n 'asset-read-failed',\n `could not read floor asset ${file}: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n const actualDigest = createHash('sha256').update(bytes).digest('hex')\n if (actualDigest !== entry.sha256) {\n throw new FloorAssetLoadError(\n 'digest-mismatch',\n `floor asset ${file} does not match its committed sha256`,\n )\n }\n return bytes\n}\n\nfunction parseBinary(bytes: Buffer): Omit<FloorAssets, 'tokenizer'> {\n if (bytes.byteLength < FLOOR_HEADER_BYTES) {\n throw new FloorAssetLoadError('binary-invalid', 'floor binary is shorter than its header')\n }\n const magic = bytes.toString('ascii', 0, 4)\n const version = bytes.readUInt32LE(4)\n const vocabularySize = bytes.readUInt32LE(8)\n const dimension = bytes.readUInt32LE(12)\n if (magic !== FLOOR_MAGIC || version !== FLOOR_FORMAT_VERSION) {\n throw new FloorAssetLoadError('binary-invalid', 'floor binary magic or version is invalid')\n }\n if (vocabularySize !== FLOOR_VOCABULARY_SIZE || dimension !== FLOOR_DIMENSION) {\n throw new FloorAssetLoadError('binary-invalid', 'floor binary dimensions are invalid')\n }\n if (bytes.byteLength !== expectedBinaryBytes(vocabularySize, dimension)) {\n throw new FloorAssetLoadError('binary-invalid', 'floor binary length is invalid')\n }\n\n const scales = new Float32Array(vocabularySize)\n for (let row = 0; row < vocabularySize; row += 1) {\n const scale = bytes.readFloatLE(FLOOR_HEADER_BYTES + row * Float32Array.BYTES_PER_ELEMENT)\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new FloorAssetLoadError('binary-invalid', `floor binary row ${row} has invalid scale`)\n }\n scales[row] = scale\n }\n\n const weightsOffset = FLOOR_HEADER_BYTES + vocabularySize * Float32Array.BYTES_PER_ELEMENT\n const weights = new Int8Array(\n bytes.buffer,\n bytes.byteOffset + weightsOffset,\n vocabularySize * dimension,\n )\n return { vocabularySize, dimension, scales, weights }\n}\n\n// D-09: the runtime package loads at the first acquisition, never at import, so a host that only\n// reads never resolves it. A failed load is dropped so the next acquisition retries.\nfunction loadTokenizerRuntime(): Promise<typeof import('@huggingface/tokenizers')> {\n tokenizerRuntime ??= import('@huggingface/tokenizers').catch((error: unknown) => {\n tokenizerRuntime = undefined\n throw new FloorAssetLoadError(\n 'tokenizer-runtime-unavailable',\n `could not load the floor tokenizer runtime: ${errorMessage(error)}`,\n { cause: error },\n )\n })\n return tokenizerRuntime\n}\n\nasync function parseTokenizer(bytes: Buffer): Promise<Tokenizer> {\n const { Tokenizer } = await loadTokenizerRuntime()\n try {\n const tokenizerJson: unknown = JSON.parse(bytes.toString('utf8'))\n if (!isRecord(tokenizerJson)) throw new TypeError('tokenizer.json must contain an object')\n return new Tokenizer(tokenizerJson, {})\n } catch (error) {\n throw new FloorAssetLoadError(\n 'tokenizer-invalid',\n `could not construct floor tokenizer: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n}\n\nasync function loadFloorAssetsFrom(assetsDir: string): Promise<FloorAssets> {\n const manifest = readManifest(assetsDir)\n const binaryEntry = manifest.files[BINARY_FILE]!\n const tokenizerEntry = manifest.files[TOKENIZER_FILE]!\n const goldenEntry = manifest.files[GOLDEN_FILE]!\n const binaryExpectedBytes = expectedBinaryBytes(\n manifest.artifact.vocabularySize,\n manifest.artifact.dimension,\n )\n\n assertExpectedFileSize(assetsDir, BINARY_FILE, binaryEntry, binaryExpectedBytes)\n if (binaryEntry.bytes !== binaryExpectedBytes) {\n throw new FloorAssetLoadError(\n 'asset-size-mismatch',\n `floor binary manifest length must be ${binaryExpectedBytes}`,\n )\n }\n assertExpectedFileSize(assetsDir, TOKENIZER_FILE, tokenizerEntry, TOKENIZER_MAX_BYTES)\n assertExpectedFileSize(assetsDir, GOLDEN_FILE, goldenEntry, GOLDEN_MAX_BYTES)\n\n const binaryBytes = readAndVerifyFile(assetsDir, BINARY_FILE, binaryEntry)\n const tokenizerBytes = readAndVerifyFile(assetsDir, TOKENIZER_FILE, tokenizerEntry)\n readAndVerifyFile(assetsDir, GOLDEN_FILE, goldenEntry)\n\n const binary = parseBinary(binaryBytes)\n return { ...binary, tokenizer: await parseTokenizer(tokenizerBytes) }\n}\n\nexport function loadFloorAssets(options: FloorAssetLoadOptions = {}): Promise<FloorAssets> {\n if (options.assetsDir !== undefined) return loadFloorAssetsFrom(options.assetsDir)\n if (memoizedDefaultAssets !== undefined) return memoizedDefaultAssets\n const pending = (async () =>\n loadFloorAssetsFrom(join(packageRootFromImportMeta(), 'assets', ASSET_DIRECTORY)))()\n memoizedDefaultAssets = pending\n pending.catch(() => {\n if (memoizedDefaultAssets === pending) memoizedDefaultAssets = undefined\n })\n return pending\n}\n\nfunction embed(\n assets: FloorAssets,\n rendering: string,\n maxTokens: number | undefined,\n): Float32Array {\n const encoded = assets.tokenizer.encode(rendering, { add_special_tokens: false }).ids\n const tokenIds = maxTokens === undefined ? encoded : encoded.slice(0, maxTokens)\n if (tokenIds.length === 0) {\n throw new FloorEmbeddingError(\n 'empty-token-set',\n 'floor tokenizer produced no tokens for the rendering',\n )\n }\n\n const means = new Float64Array(assets.dimension)\n for (const tokenId of tokenIds) {\n if (!Number.isSafeInteger(tokenId) || tokenId < 0 || tokenId >= assets.vocabularySize) {\n throw new FloorEmbeddingError(\n 'token-id-out-of-range',\n `floor tokenizer produced out-of-range token id ${tokenId}`,\n )\n }\n const rowOffset = tokenId * assets.dimension\n const scale = assets.scales[tokenId]!\n for (let column = 0; column < assets.dimension; column += 1) {\n means[column] = means[column]! + assets.weights[rowOffset + column]! * scale\n }\n }\n\n let squaredLength = 0\n for (let column = 0; column < assets.dimension; column += 1) {\n const mean = means[column]! / tokenIds.length\n means[column] = mean\n squaredLength += mean * mean\n }\n const length = Math.sqrt(squaredLength)\n if (!Number.isFinite(length) || length === 0) {\n throw new FloorEmbeddingError('zero-vector', 'floor embedder produced a zero-length vector')\n }\n\n return Float32Array.from(means, (value) => value / length)\n}\n\n/**\n * Construct the pure-TypeScript degradation-floor embedder without loading assets eagerly.\n *\n * The static floor profile has empty document and query prefixes, so both legs intentionally\n * share exactly the same token lookup, mean pooling, and L2-normalization implementation.\n */\nexport function createFloorEmbedder(options: FloorAssetLoadOptions = {}): EmbedderPort {\n const maxTokens = options.maxTokens\n if (maxTokens !== undefined && (!Number.isSafeInteger(maxTokens) || maxTokens <= 0)) {\n throw new RangeError('maxTokens must be a positive safe integer')\n }\n return {\n async embedDocument(rendering: string): Promise<Float32Array> {\n return embed(await loadFloorAssets(options), rendering, maxTokens)\n },\n async embedQuery(rendering: string): Promise<Float32Array> {\n return embed(await loadFloorAssets(options), rendering, maxTokens)\n },\n }\n}\n","import { resolve, sep } from 'node:path'\n\nimport type {\n FeatureExtractionPipeline,\n PretrainedModelOptions,\n} from '@huggingface/transformers'\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\n\nimport type { EmbedderPort } from './embedder-port.js'\nimport { resolveModelCacheDir } from './model-cache-dir.js'\n\nconst nativePipelines = new Map<\n string,\n {\n maxTokens: number | undefined\n pipelinePromise: Promise<FeatureExtractionPipeline>\n }\n>()\nlet nativePipelineLoadTail: Promise<void> = Promise.resolve()\n\nexport class NativeEmbeddingModuleLoadError extends Error {\n constructor(cause: unknown) {\n super('Native embedding module could not be loaded', { cause })\n this.name = 'NativeEmbeddingModuleLoadError'\n }\n}\n\nexport class NativeEmbeddingDimensionError extends RangeError {\n readonly actualDim: number\n readonly expectedDim: number\n\n constructor(actualDim: number, expectedDim: number) {\n super(`Native embedding dimension ${actualDim} does not match profile dimension ${expectedDim}`)\n this.name = 'NativeEmbeddingDimensionError'\n this.actualDim = actualDim\n this.expectedDim = expectedDim\n }\n}\n\nfunction validateMaxTokens(maxTokens: number | undefined): number | undefined {\n if (maxTokens === undefined) return undefined\n if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {\n throw new RangeError('maxTokens must be a positive safe integer')\n }\n return maxTokens\n}\n\nfunction pipelineKey(profile: EmbeddingProfile): string {\n return `${profile.model_id}@${profile.revision}:${profile.dtype}`\n}\n\nfunction tokenBudgetLabel(maxTokens: number | undefined): string {\n return maxTokens === undefined ? 'uncapped' : String(maxTokens)\n}\n\nfunction pinnedModelDirectory(cacheDir: string, profile: EmbeddingProfile): string {\n const root = resolve(cacheDir)\n const directory = resolve(root, profile.model_id, profile.revision)\n if (directory === root || !directory.startsWith(`${root}${sep}`)) {\n throw new TypeError(`${profile.model_id} cannot be resolved safely inside the model cache`)\n }\n return directory\n}\n\nfunction capTokenizer(extractor: FeatureExtractionPipeline, maxTokens: number): void {\n const tokenizer = extractor.tokenizer\n const tokenizerConfig = tokenizer._tokenizerConfig as\n | Record<string, unknown>\n | null\n | undefined\n const modelMaximum = Number(tokenizerConfig?.model_max_length)\n // Transformers v4's feature-extraction pipeline hard-codes truncation and reads this\n // getter-backed config value; some pinned tokenizers expose a null config, so initialize it.\n tokenizer._tokenizerConfig = {\n ...(tokenizerConfig ?? {}),\n model_max_length:\n Number.isSafeInteger(modelMaximum) && modelMaximum > 0\n ? Math.min(modelMaximum, maxTokens)\n : maxTokens,\n }\n}\n\nasync function withNativePipelineLoadLock<T>(operation: () => Promise<T>): Promise<T> {\n const previous = nativePipelineLoadTail\n let release!: () => void\n nativePipelineLoadTail = new Promise<void>((resolvePending) => {\n release = resolvePending\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n}\n\nasync function loadPinnedPipeline(\n transformers: typeof import('@huggingface/transformers'),\n profile: EmbeddingProfile,\n allowDownload: boolean,\n maxTokens: number | undefined,\n): Promise<FeatureExtractionPipeline> {\n return withNativePipelineLoadLock(async () => {\n const cacheDir = resolveModelCacheDir()\n transformers.env.cacheDir = cacheDir\n const sharedOptions = {\n cache_dir: cacheDir,\n local_files_only: !allowDownload,\n revision: profile.revision,\n }\n const modelSource = allowDownload\n ? profile.model_id\n : pinnedModelDirectory(cacheDir, profile)\n const originalRemotePathTemplate = transformers.env.remotePathTemplate\n const originalAllowRemoteModels = transformers.env.allowRemoteModels\n\n if (allowDownload) {\n // Transformers.js v4.2's tokenizer metadata probe drops its options. Pin the\n // process-local URL template so even that probe addresses this exact revision.\n transformers.env.remotePathTemplate = `{model}/resolve/${encodeURIComponent(profile.revision)}/`\n } else {\n // The same metadata probe drops local_files_only. Loading from the exact local\n // revision directory with remote models disabled makes this path truly offline.\n transformers.env.allowRemoteModels = false\n }\n\n try {\n const [tokenizerResult, modelResult] = await Promise.allSettled([\n transformers.AutoTokenizer.from_pretrained(modelSource, sharedOptions),\n transformers.AutoModel.from_pretrained(modelSource, {\n ...sharedOptions,\n device: 'cpu',\n dtype: profile.dtype,\n session_options:\n profile.session_options as PretrainedModelOptions['session_options'],\n }),\n ])\n if (tokenizerResult.status === 'rejected') {\n if (modelResult.status === 'rejected') {\n // v4.2's option-dropping tokenizer metadata lookup can collapse an empty local\n // directory into a generic TypeError. The model loader retains the actionable\n // local-files-only error, which the acquisition ladder classifies as a cold artifact.\n throw modelResult.reason\n }\n await modelResult.value.dispose().catch(() => undefined)\n throw tokenizerResult.reason\n }\n if (modelResult.status === 'rejected') throw modelResult.reason\n\n const tokenizer = tokenizerResult.value\n const model = modelResult.value\n try {\n const extractor = new transformers.FeatureExtractionPipeline({\n task: 'feature-extraction',\n model,\n tokenizer,\n })\n if (maxTokens !== undefined) capTokenizer(extractor, maxTokens)\n return extractor\n } catch (error) {\n await model.dispose().catch(() => undefined)\n throw error\n }\n } finally {\n transformers.env.remotePathTemplate = originalRemotePathTemplate\n transformers.env.allowRemoteModels = originalAllowRemoteModels\n }\n })\n}\n\nfunction acquirePipeline(\n profile: EmbeddingProfile,\n allowDownload: boolean,\n maxTokens: number | undefined,\n): Promise<FeatureExtractionPipeline> {\n const key = pipelineKey(profile)\n const existing = nativePipelines.get(key)\n if (existing) {\n if (existing.maxTokens !== maxTokens) {\n throw new RangeError(\n `Native embedding pipeline budget conflict for ${key}: existing maxTokens=${tokenBudgetLabel(existing.maxTokens)}, requested maxTokens=${tokenBudgetLabel(maxTokens)}; one process-lifetime session per model identity permits only the first budget`,\n )\n }\n return existing.pipelinePromise\n }\n\n const pending = (async () => {\n let transformers: typeof import('@huggingface/transformers')\n try {\n transformers = await import('@huggingface/transformers')\n } catch (error) {\n throw new NativeEmbeddingModuleLoadError(error)\n }\n return loadPinnedPipeline(transformers, profile, allowDownload, maxTokens)\n })()\n\n nativePipelines.set(key, { maxTokens, pipelinePromise: pending })\n return pending\n}\n\nfunction toEmbedding(data: unknown, expectedDim: number): Float32Array {\n const vector =\n data instanceof Float32Array\n ? data\n : Float32Array.from(data as ArrayLike<number>)\n\n if (vector.length !== expectedDim) {\n throw new NativeEmbeddingDimensionError(vector.length, expectedDim)\n }\n\n return vector\n}\n\nexport async function createNativeEmbedder(options: {\n profile: EmbeddingProfile\n allowDownload: boolean\n /** Optional process-wide token budget fixed by the first acquisition for this model identity. */\n maxTokens?: number\n}): Promise<EmbedderPort> {\n const { profile, allowDownload } = options\n const maxTokens = validateMaxTokens(options.maxTokens)\n const extractor = await acquirePipeline(profile, allowDownload, maxTokens)\n\n async function embed(text: string, prefix: string): Promise<Float32Array> {\n const output = await extractor(`${prefix}${text}`, {\n pooling: 'mean',\n normalize: true,\n })\n\n return toEmbedding(output.data, profile.dim)\n }\n\n return {\n embedDocument: (rendering) => embed(rendering, profile.doc_prefix),\n embedQuery: (rendering) => embed(rendering, profile.query_prefix),\n }\n}\n","import { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport const MODEL_CACHE_DIR_ENV_VAR = 'AGENT_QA_MODEL_CACHE_DIR'\n\n/**\n * Resolve the shared model cache used by every native embedder acquisition.\n *\n * D-11: one download per machine across all projects, with artifacts identified\n * by (model_id, revision). An explicit agent-qa override wins, then the XDG\n * cache root, with the conventional home cache as the final fallback.\n */\nexport function resolveModelCacheDir(): string {\n const override = process.env[MODEL_CACHE_DIR_ENV_VAR]\n if (override) return override\n\n const xdgCacheHome = process.env.XDG_CACHE_HOME\n if (xdgCacheHome) return join(xdgCacheHome, 'agent-qa', 'models')\n\n return join(homedir(), '.cache', 'agent-qa', 'models')\n}\n","import { randomUUID, createHash } from 'node:crypto'\nimport {\n chmodSync,\n closeSync,\n existsSync,\n fsyncSync,\n linkSync,\n mkdirSync,\n openSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { request, type IncomingMessage } from 'node:http'\nimport { connect } from 'node:net'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, join, resolve } from 'node:path'\n\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport type { EmbedderPort } from '../embedder-port.js'\n\nexport const EMBEDDER_WORKER_REGISTRATION_FILE = 'embedder-worker.json'\nexport const EMBEDDER_WORKER_REGISTRATION_SCHEMA_VERSION = 2\n\n/**\n * What a worker records when it cannot attribute its own process.\n *\n * The field is required rather than optional on purpose: an absent incarnation would let a forged\n * registration opt out of the check entirely. A worker that genuinely cannot resolve its own start\n * time says so explicitly, and the host reads that as `unverifiable` — which withholds every\n * signal, exactly as an unresolvable pid does.\n */\nexport const EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION = 'unresolved'\nexport const EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION = 2\nexport const EMBEDDER_WORKER_SOCKET_PATH_BUDGET_BYTES = 100\nexport const MAX_EMBEDDER_WORKER_BODY_BYTES = 4_194_304\n\n/** D-15 provisional request deadline; retune from daemon telemetry without adding config. */\nexport const EMBEDDER_WORKER_REQUEST_TIMEOUT_MS = 30_000\n\n/** D-15 provisional child-readiness deadline; retune from daemon telemetry without adding config. */\nexport const EMBEDDER_WORKER_START_TIMEOUT_MS = 15_000\n\n/** D-15 provisional TERM grace; retune from daemon telemetry without adding config. */\nexport const EMBEDDER_WORKER_TERM_GRACE_MS = 5_000\n\nexport type EmbedderWorkerTimeoutPhase = 'request' | 'start' | 'terminate'\n\n/** A bounded worker wait expired; callers can defer by phase without parsing error text. */\nexport class EmbedderWorkerTimeoutError extends Error {\n readonly phase: EmbedderWorkerTimeoutPhase\n readonly timeoutMs: number\n\n constructor(phase: EmbedderWorkerTimeoutPhase, timeoutMs: number) {\n super(`Embedder worker ${phase} timed out after ${timeoutMs} ms`)\n this.name = 'EmbedderWorkerTimeoutError'\n this.phase = phase\n this.timeoutMs = timeoutMs\n }\n}\n\nexport const embeddingProfileSchema = z\n .object({\n model_id: z.string().min(1),\n revision: z.string().min(1),\n dim: z.number().int().positive(),\n dtype: z.literal('q8'),\n pooling: z.literal('mean'),\n normalize: z.literal(true),\n query_prefix: z.string(),\n doc_prefix: z.string(),\n backend: z.enum(['node', 'static']),\n session_options: z.record(z.string(), z.unknown()),\n tau_dense: z.number().finite(),\n })\n .strict()\n\nexport const embedderWorkerRegistrationSchema = z\n .object({\n schemaVersion: z.literal(EMBEDDER_WORKER_REGISTRATION_SCHEMA_VERSION),\n instanceId: z.string().uuid(),\n pid: z.number().int().positive(),\n socketPath: z.string().min(1),\n profile: embeddingProfileSchema,\n startedAtMs: z.number().int().nonnegative(),\n /** The registering process's own OS-anchored start-time token, or the unverifiable sentinel. */\n incarnation: z.string().min(1),\n })\n .strict()\n\nexport type EmbedderWorkerRegistration = z.infer<typeof embedderWorkerRegistrationSchema>\n\nexport type ReadEmbedderWorkerRegistrationOutcome =\n | { kind: 'absent' }\n | { kind: 'malformed' }\n | { kind: 'parsed'; registration: EmbedderWorkerRegistration }\n\nexport type ProcessIsAlive = (pid: number) => boolean\n\n/** Three-valued because the third value is a refusal, never a permissive default. */\nexport type EmbedderWorkerIncarnationVerdict = 'match' | 'mismatch' | 'unverifiable'\n\nconst singleEmbeddingRequestSchema = z.discriminatedUnion('method', [\n z\n .object({\n schemaVersion: z.literal(EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION),\n method: z.literal('embedDocument'),\n rendering: z.string(),\n })\n .strict(),\n z\n .object({\n schemaVersion: z.literal(EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION),\n method: z.literal('embedQuery'),\n rendering: z.string(),\n })\n .strict(),\n])\n\nexport const embedderWorkerRequestSchema = z.discriminatedUnion('method', [\n ...singleEmbeddingRequestSchema.options,\n z\n .object({\n schemaVersion: z.literal(EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION),\n method: z.literal('embedBatch'),\n requests: z.array(singleEmbeddingRequestSchema).min(1).max(256),\n })\n .strict(),\n])\n\nexport type EmbedderWorkerRequest = z.infer<typeof embedderWorkerRequestSchema>\n\nexport const embedderWorkerResponseSchema = z\n .object({\n schemaVersion: z.literal(EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION),\n vectors: z.array(z.array(z.number().finite())),\n })\n .strict()\n\nexport type EmbedderWorkerResponse = z.infer<typeof embedderWorkerResponseSchema>\n\nfunction projectHash(projectRoot: string): string {\n return createHash('sha256').update(realpathSync(projectRoot)).digest('hex').slice(0, 12)\n}\n\nexport function embedderWorkerAgentQaRoot(projectRoot = process.cwd()): string {\n return join(realpathSync(projectRoot), '.agent-qa')\n}\n\nexport function embedderWorkerRegistrationPath(agentQaRoot: string): string {\n return join(agentQaRoot, EMBEDDER_WORKER_REGISTRATION_FILE)\n}\n\nfunction instanceDiscriminator(instanceId: string): string {\n const validated = z.string().uuid().parse(instanceId)\n return createHash('sha256').update(validated).digest('hex').slice(0, 12)\n}\n\n/** Resolve an instance-scoped UDS path without crossing conservative POSIX sun_path limits. */\nexport function embedderWorkerSocketPath(\n agentQaRoot: string,\n projectRoot: string,\n instanceId: string,\n): string {\n const hash = projectHash(projectRoot)\n const instance = instanceDiscriminator(instanceId)\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\agent-qa-embedder-${hash}-${instance}`\n }\n\n const canonicalAgentQaRoot = join(realpathSync(dirname(agentQaRoot)), basename(agentQaRoot))\n const socketFile = `embedder-worker-${instance}.sock`\n const projectLocal = join(canonicalAgentQaRoot, socketFile)\n if (Buffer.byteLength(projectLocal) <= EMBEDDER_WORKER_SOCKET_PATH_BUDGET_BYTES) {\n return projectLocal\n }\n\n const fallback = join(tmpdir(), `agent-qa-${hash}`, `${instance}.sock`)\n if (Buffer.byteLength(fallback) > EMBEDDER_WORKER_SOCKET_PATH_BUDGET_BYTES) {\n throw new Error(\n `OS temporary directory is too deep for an agent-qa embedder socket: ${fallback}`,\n )\n }\n return fallback\n}\n\nexport function prepareEmbedderWorkerSocketParent(socketPath: string): void {\n if (process.platform === 'win32' || socketPath.startsWith('\\\\\\\\.\\\\pipe\\\\')) return\n const parent = dirname(socketPath)\n mkdirSync(parent, { recursive: true, mode: 0o700 })\n chmodSync(parent, 0o700)\n}\n\nfunction bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n code !== 'ENOENT'\n && code !== 'EINVAL'\n && code !== 'EISDIR'\n && code !== 'EPERM'\n && code !== 'ENOTSUP'\n ) {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\nfunction atomicRewrite(file: string, text: string): void {\n const parent = dirname(file)\n mkdirSync(parent, { recursive: true, mode: 0o700 })\n chmodSync(parent, 0o700)\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx', 0o600)\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n bestEffortFsyncDirectory(parent)\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\nexport function writeEmbedderWorkerRegistration(\n agentQaRoot: string,\n registration: EmbedderWorkerRegistration,\n): void {\n const validated = embedderWorkerRegistrationSchema.parse(registration)\n atomicRewrite(\n embedderWorkerRegistrationPath(agentQaRoot),\n `${JSON.stringify(validated)}\\n`,\n )\n}\n\nfunction readEmbedderWorkerRegistrationFile(\n file: string,\n): ReadEmbedderWorkerRegistrationOutcome {\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return existsSync(file) ? { kind: 'malformed' } : { kind: 'absent' }\n }\n\n try {\n const parsedJson = JSON.parse(raw) as unknown\n const parsed = embedderWorkerRegistrationSchema.safeParse(parsedJson)\n return parsed.success ? { kind: 'parsed', registration: parsed.data } : { kind: 'malformed' }\n } catch {\n return { kind: 'malformed' }\n }\n}\n\nexport function readEmbedderWorkerRegistration(\n agentQaRoot: string,\n): ReadEmbedderWorkerRegistrationOutcome {\n return readEmbedderWorkerRegistrationFile(embedderWorkerRegistrationPath(agentQaRoot))\n}\n\n/** Signal-zero liveness probe: EPERM proves existence; only ESRCH proves a stale pid. */\nexport function embedderWorkerProcessIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ESRCH') return false\n if (code === 'EPERM') return true\n throw error\n }\n}\n\nfunction sameRegistration(\n left: EmbedderWorkerRegistration,\n right: EmbedderWorkerRegistration,\n): boolean {\n return left.pid === right.pid\n && left.startedAtMs === right.startedAtMs\n && left.socketPath === right.socketPath\n && left.instanceId === right.instanceId\n && left.incarnation === right.incarnation\n}\n\nexport interface RemoveEmbedderWorkerRegistrationOptions {\n /** Test-only barrier after quarantine publication and before ownership verification. */\n readonly afterQuarantine?: (quarantinePath: string) => void\n /** Focused durability seam; production uses the best-effort platform fsync helper. */\n readonly fsyncDirectory?: (directory: string) => void\n}\n\n/** Atomically quarantine and remove only the exact registration owned by the caller. */\nexport function removeEmbedderWorkerRegistration(\n agentQaRoot: string,\n expected: EmbedderWorkerRegistration,\n options: RemoveEmbedderWorkerRegistrationOptions = {},\n): boolean {\n const file = embedderWorkerRegistrationPath(agentQaRoot)\n const parent = dirname(file)\n const quarantine = `${file}.remove-${expected.instanceId}-${randomUUID()}`\n const fsyncDirectory = options.fsyncDirectory ?? bestEffortFsyncDirectory\n\n try {\n renameSync(file, quarantine)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n fsyncDirectory(parent)\n options.afterQuarantine?.(quarantine)\n\n const outcome = readEmbedderWorkerRegistrationFile(quarantine)\n const quarantinedRegistration = outcome.kind === 'parsed' ? outcome.registration : undefined\n if (\n quarantinedRegistration !== undefined\n && sameRegistration(quarantinedRegistration, expected)\n ) {\n unlinkSync(quarantine)\n fsyncDirectory(parent)\n return true\n }\n\n try {\n linkSync(quarantine, file)\n fsyncDirectory(parent)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n }\n unlinkSync(quarantine)\n fsyncDirectory(parent)\n return false\n}\n\nexport function probeEmbedderWorkerSocket(socketPath: string): Promise<boolean> {\n return new Promise((resolveProbe) => {\n const socket = connect(socketPath)\n socket.once('connect', () => {\n socket.destroy()\n resolveProbe(true)\n })\n socket.once('error', () => {\n socket.destroy()\n resolveProbe(false)\n })\n })\n}\n\nfunction requestWorker(\n socketPath: string,\n envelope: EmbedderWorkerRequest,\n options: CreateEmbedderWorkerPortOptions,\n): Promise<EmbedderWorkerResponse> {\n const body = JSON.stringify(embedderWorkerRequestSchema.parse(envelope))\n return new Promise((resolveRequest, rejectRequest) => {\n const requestTimeoutMs = options.requestTimeoutMs ?? EMBEDDER_WORKER_REQUEST_TIMEOUT_MS\n const abortController = new AbortController()\n let responseStream: IncomingMessage | undefined\n let timeout: ReturnType<typeof setTimeout> | undefined\n let settled = false\n\n const settle = (\n outcome: { kind: 'resolved'; response: EmbedderWorkerResponse }\n | { kind: 'rejected'; error: unknown },\n ): boolean => {\n if (settled) return false\n settled = true\n if (timeout !== undefined) clearTimeout(timeout)\n if (outcome.kind === 'resolved') {\n resolveRequest(outcome.response)\n } else {\n try {\n options.onUnavailable?.(outcome.error)\n } catch {\n // Transport refusal remains authoritative even when best-effort invalidation cannot write.\n }\n rejectRequest(outcome.error)\n }\n return true\n }\n\n const workerRequest = request(\n {\n socketPath,\n path: '/embed',\n method: 'POST',\n signal: abortController.signal,\n headers: {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(body),\n },\n },\n (response) => {\n responseStream = response\n const chunks: Buffer[] = []\n let bytes = 0\n response.once('aborted', () => {\n settle({ kind: 'rejected', error: new Error('Embedder worker response was aborted') })\n })\n response.once('error', (error) => {\n settle({ kind: 'rejected', error })\n })\n response.on('data', (chunk: Buffer | string) => {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n bytes += buffer.byteLength\n if (bytes <= MAX_EMBEDDER_WORKER_BODY_BYTES) chunks.push(buffer)\n })\n response.on('end', () => {\n try {\n if (bytes > MAX_EMBEDDER_WORKER_BODY_BYTES) {\n throw new Error('Embedder worker response exceeded the body limit')\n }\n const parsedBody = JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown\n if (response.statusCode !== 200) {\n const message = z\n .object({ error: z.string() })\n .passthrough()\n .safeParse(parsedBody)\n throw new Error(\n message.success\n ? `Embedder worker rejected the request: ${message.data.error}`\n : `Embedder worker returned HTTP ${response.statusCode ?? 0}`,\n )\n }\n settle({\n kind: 'resolved',\n response: embedderWorkerResponseSchema.parse(parsedBody),\n })\n } catch (error) {\n settle({ kind: 'rejected', error })\n }\n })\n },\n )\n workerRequest.once('error', (error) => {\n const refusal = abortController.signal.aborted\n ? abortController.signal.reason\n : error\n settle({ kind: 'rejected', error: refusal })\n })\n timeout = setTimeout(() => {\n const error = new EmbedderWorkerTimeoutError('request', requestTimeoutMs)\n if (!settle({ kind: 'rejected', error })) return\n abortController.abort(error)\n responseStream?.destroy(error)\n workerRequest.destroy(error)\n }, requestTimeoutMs)\n workerRequest.end(body)\n })\n}\n\nfunction vectorFromResponse(\n response: EmbedderWorkerResponse,\n expectedDimension: number,\n): Float32Array {\n const [vector] = response.vectors\n if (vector === undefined || response.vectors.length !== 1) {\n throw new Error('Embedder worker returned an invalid single-vector response')\n }\n if (vector.length !== expectedDimension) {\n throw new Error(\n `Embedder worker returned dimension ${vector.length}; expected ${expectedDimension}`,\n )\n }\n return Float32Array.from(vector)\n}\n\nexport interface CreateEmbedderWorkerPortOptions {\n /** Test-only shortening seam; production always uses the pinned request deadline. */\n readonly requestTimeoutMs?: number\n /** Capability owner invalidates registration/cache after transport refusal. */\n readonly onUnavailable?: (error: unknown) => void\n}\n\nexport function createEmbedderWorkerPort(\n socketPath: string,\n expectedDimension: number,\n options: CreateEmbedderWorkerPortOptions = {},\n): EmbedderPort {\n return {\n async embedDocument(rendering) {\n return vectorFromResponse(\n await requestWorker(socketPath, {\n schemaVersion: EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION,\n method: 'embedDocument',\n rendering,\n }, options),\n expectedDimension,\n )\n },\n async embedQuery(rendering) {\n return vectorFromResponse(\n await requestWorker(socketPath, {\n schemaVersion: EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION,\n method: 'embedQuery',\n rendering,\n }, options),\n expectedDimension,\n )\n },\n }\n}\n\nexport function asEmbeddingProfile(\n profile: EmbedderWorkerRegistration['profile'],\n): EmbeddingProfile {\n return profile as EmbeddingProfile\n}\n","import {\n COLD_START_TRUST_DISCOUNT,\n LOWER_TRUST_PATH_DISCOUNT,\n isVettedCandidate,\n supersessionKey,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n ScopeKey,\n VettedCandidateInput,\n} from '@vostride/agent-qa-schema'\n\nimport { DIVERSITY_CAP_PER_ANCHOR } from './constants.js'\n\nexport type ValidityClass = 'current' | 'priorBuildHypothesis' | 'auditReadmitted'\n\nexport interface ConflictAnnotation {\n readonly peerRecordId: string\n readonly unknownRecordId: string\n}\n\nexport interface RerankEntry {\n readonly bundleId: string\n readonly validityClass: ValidityClass\n readonly trust: number\n readonly scope: ScopeKey\n readonly recencyOrdinal: number\n readonly createdAtOrdinal: number\n readonly originClass: 'agent' | 'user'\n readonly anchors: readonly Anchor[]\n readonly subtype: string | null\n readonly lastConfirmedOrdinal: number\n readonly vettedCandidateInput?: VettedCandidateInput\n readonly unconfirmedSinceOrdinal?: number\n readonly unverified?: boolean\n readonly lowerTrust?: true\n readonly conflict?: ConflictAnnotation\n}\n\nexport interface MintUnknownConflict {\n readonly leftRecordId: string\n readonly rightRecordId: string\n readonly unknownRecordId: string\n}\n\nexport interface CollapseByOrdinalOptions {\n readonly audit?: boolean\n readonly conflicts?: readonly MintUnknownConflict[]\n}\n\nconst VALIDITY_ORDER: Readonly<Record<ValidityClass, number>> = {\n current: 0,\n priorBuildHypothesis: 1,\n auditReadmitted: 2,\n}\n\nconst SCOPE_ORDER: Readonly<Record<ScopeKey['tier'], number>> = {\n test: 0,\n suite: 1,\n product: 2,\n global: 3,\n}\n\n/**\n * PROVISIONAL D-05 trust dampener. M3 owns calibration from attributed outcomes;\n * this remains an internal constitution value, never a config key.\n */\nexport const UNCONFIRMED_DOWNRANK_FACTOR = 0.6\n\n/** LOCKED D-05 durable-fact default: authority softens only after five builds. */\nexport const UNCONFIRMED_WINDOW_DURABLE_BUILDS = 5\n\n/**\n * PROVISIONAL D-06 volatile window. Measurements age sooner than the locked\n * durable default; M3 owns calibration, never user configuration.\n */\nexport const UNCONFIRMED_WINDOW_VOLATILE_BUILDS = 3\n\nfunction compareBundleIds(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction identityBearingAnchors(anchors: readonly Anchor[]): Anchor[] {\n return anchors.filter((anchor) => anchor.t !== 'platform')\n}\n\n/**\n * Sort by the precedence tuple from spec §5.5.6. Each axis is compared independently so a\n * lower-priority recency value can never overtake validity, trust, or scope specificity.\n */\nexport function rerankPrecedence<T extends RerankEntry>(entries: readonly T[]): T[] {\n return [...entries].sort(\n (left, right) =>\n VALIDITY_ORDER[left.validityClass] - VALIDITY_ORDER[right.validityClass] ||\n right.trust - left.trust ||\n SCOPE_ORDER[left.scope.tier] - SCOPE_ORDER[right.scope.tier] ||\n right.recencyOrdinal - left.recencyOrdinal ||\n compareBundleIds(left.bundleId, right.bundleId),\n )\n}\n\nfunction unconfirmedWindow(entry: RerankEntry): number {\n return entry.subtype === 'measurement'\n ? UNCONFIRMED_WINDOW_VOLATILE_BUILDS\n : UNCONFIRMED_WINDOW_DURABLE_BUILDS\n}\n\n/**\n * Apply D-05/D-06 staleness and D-20 cold-start treatment as trust modulation\n * before precedence sorting. Validity remains the first comparator axis: this\n * function never filters, changes validity, or adds another sort dimension.\n * Every annotation is re-derived from the supplied as-of ordinal; nothing is stored.\n */\nexport function applyLifecycleTrustTreatments<T extends RerankEntry>(\n entries: readonly T[],\n asOfBuild: number,\n): T[] {\n return entries.map((entry) => {\n const {\n unconfirmedSinceOrdinal: _priorUnconfirmed,\n unverified: _priorUnverified,\n ...base\n } = entry\n let trust = entry.trust\n let unconfirmedSinceOrdinal: number | undefined\n\n // D-06 binding: sovereign user knowledge is exempt from autonomous decay.\n if (\n entry.originClass !== 'user'\n && asOfBuild - entry.lastConfirmedOrdinal >= unconfirmedWindow(entry)\n ) {\n trust *= UNCONFIRMED_DOWNRANK_FACTOR\n unconfirmedSinceOrdinal = entry.lastConfirmedOrdinal\n }\n\n const unverified = entry.vettedCandidateInput !== undefined\n && isVettedCandidate(entry.vettedCandidateInput)\n if (unverified) trust *= COLD_START_TRUST_DISCOUNT\n if (entry.lowerTrust === true) trust *= LOWER_TRUST_PATH_DISCOUNT\n\n return {\n ...base,\n trust,\n ...(unconfirmedSinceOrdinal === undefined ? {} : { unconfirmedSinceOrdinal }),\n ...(unverified ? { unverified: true } : {}),\n ...(entry.lowerTrust === true ? { lowerTrust: true } : {}),\n } as T\n })\n}\n\nfunction annotateConflicts<T extends RerankEntry>(\n entries: readonly T[],\n conflicts: readonly MintUnknownConflict[],\n): T[] {\n const annotations = new Map<string, ConflictAnnotation>()\n\n for (const conflict of conflicts) {\n if (!annotations.has(conflict.leftRecordId)) {\n annotations.set(conflict.leftRecordId, {\n peerRecordId: conflict.rightRecordId,\n unknownRecordId: conflict.unknownRecordId,\n })\n }\n if (!annotations.has(conflict.rightRecordId)) {\n annotations.set(conflict.rightRecordId, {\n peerRecordId: conflict.leftRecordId,\n unknownRecordId: conflict.unknownRecordId,\n })\n }\n }\n\n return entries.map((entry) => {\n const conflict = entry.conflict ?? annotations.get(entry.bundleId)\n return conflict === undefined ? entry : ({ ...entry, conflict } as T)\n })\n}\n\nfunction collapseKey(entry: RerankEntry): string | undefined {\n if (entry.originClass === 'user' || entry.conflict !== undefined) return undefined\n\n const anchors = identityBearingAnchors(entry.anchors)\n if (anchors.length === 0) return undefined\n\n // Read-side mirror of spec §7.3.2; Phase 378's writer uses the same schema authority.\n return supersessionKey(anchors)\n}\n\n/**\n * Collapse agent-authored supersession groups onto their maximum creation ordinal (D-16).\n * Sovereign user entries and both annotated sides of a MintUnknown conflict always survive.\n */\nexport function collapseByOrdinal<T extends RerankEntry>(\n entries: readonly T[],\n options: CollapseByOrdinalOptions = {},\n): T[] {\n const annotated = annotateConflicts(entries, options.conflicts ?? [])\n if (options.audit === true) return annotated\n\n const winners = new Map<string, T>()\n for (const entry of annotated) {\n const key = collapseKey(entry)\n if (key === undefined) continue\n\n const current = winners.get(key)\n if (\n current === undefined ||\n entry.createdAtOrdinal > current.createdAtOrdinal ||\n (entry.createdAtOrdinal === current.createdAtOrdinal &&\n compareBundleIds(entry.bundleId, current.bundleId) < 0)\n ) {\n winners.set(key, entry)\n }\n }\n\n return annotated.filter((entry) => {\n const key = collapseKey(entry)\n return key === undefined || winners.get(key) === entry\n })\n}\n\nfunction primaryDiversityKey(entry: RerankEntry): string | undefined {\n const primary = identityBearingAnchors(entry.anchors)[0]\n if (primary?.t !== 'el' && primary?.t !== 'flow') return undefined\n\n return supersessionKey([primary])\n}\n\n/** Keep at most the configured number of naturally-ranked results per primary el/flow anchor. */\nexport function applyDiversityCaps<T extends RerankEntry>(\n entries: readonly T[],\n audit = false,\n): T[] {\n if (audit) return [...entries]\n\n const counts = new Map<string, number>()\n return entries.filter((entry) => {\n const key = primaryDiversityKey(entry)\n if (key === undefined) return true\n\n const count = counts.get(key) ?? 0\n if (count >= DIVERSITY_CAP_PER_ANCHOR) return false\n counts.set(key, count + 1)\n return true\n })\n}\n","/**\n * Pure D-14/D-15 temporal admission for memory.md §5.5.5.\n *\n * The write path expresses the deterministic drift exemption by minting the correction `active`;\n * this stage never invents a second candidate gate, so that born-active fact remains admissible.\n * Status withdrawal stays in pre-filter.ts, while range audit is deliberately status-agnostic so\n * includeSuperseded and asOfRange remain orthogonal.\n */\nimport { supersessionKey } from '@vostride/agent-qa-schema'\nimport type { Anchor } from '@vostride/agent-qa-schema'\n\nimport { readLatestBuildOrdinal } from '../build-ordinal-read.js'\n\nexport interface AsOfRange {\n lo: number\n hi: number\n}\n\nexport interface ValidityOptions {\n asOfBuild?: number\n resolveLatestOrdinal?: (product: string) => number | undefined\n runtimeRoot?: string\n asOfRange?: AsOfRange\n}\n\nexport interface ValidityCandidate {\n readonly bundleId: string\n readonly anchors: readonly Anchor[]\n readonly openedAtOrdinal: number\n readonly closedAtOrdinal: number | null\n readonly createdAtOrdinal: number\n readonly status: string\n readonly product: string\n}\n\nexport interface ResolveAsOfBuildOptions<TCandidate extends ValidityCandidate>\n extends ValidityOptions {\n product: string\n candidates: readonly TCandidate[]\n}\n\nexport interface ValidityAudit {\n status: string\n openedAtOrdinal: number\n closedAtOrdinal: number | null\n}\n\nexport interface ValidityAnnotation {\n servedAs?: 'current' | 'prior-build-hypothesis'\n audit?: ValidityAudit\n}\n\nfunction finiteOrdinal(value: number | undefined): number | undefined {\n return value !== undefined && Number.isFinite(value) ? value : undefined\n}\n\n/**\n * Resolve explicit → injected → disk truth → index-known maximum. The final rung is degraded:\n * candidate rows cannot reveal a fresh build for which no facts have been observed yet.\n */\nexport function resolveAsOfBuild<TCandidate extends ValidityCandidate>(\n options: ResolveAsOfBuildOptions<TCandidate>,\n): number | undefined {\n const explicit = finiteOrdinal(options.asOfBuild)\n if (explicit !== undefined) return explicit\n\n const injected = finiteOrdinal(options.resolveLatestOrdinal?.(options.product))\n if (injected !== undefined) return injected\n\n const disk = options.runtimeRoot === undefined\n ? undefined\n : readLatestBuildOrdinal(options.runtimeRoot, options.product)\n if (disk !== undefined) return disk\n\n let latest: number | undefined\n for (const candidate of options.candidates) {\n if (!Number.isFinite(candidate.openedAtOrdinal)) continue\n latest = latest === undefined\n ? candidate.openedAtOrdinal\n : Math.max(latest, candidate.openedAtOrdinal)\n }\n return latest\n}\n\nfunction isCurrentAt(candidate: ValidityCandidate, asOfBuild: number): boolean {\n return (\n candidate.openedAtOrdinal <= asOfBuild\n && (candidate.closedAtOrdinal === null || candidate.closedAtOrdinal > asOfBuild)\n )\n}\n\nfunction overlapsRange(candidate: ValidityCandidate, range: AsOfRange): boolean {\n return (\n candidate.openedAtOrdinal <= range.hi\n && (candidate.closedAtOrdinal === null || candidate.closedAtOrdinal > range.lo)\n )\n}\n\nfunction primaryAnchorKey(candidate: ValidityCandidate): string | undefined {\n const primary = candidate.anchors[0]\n return primary === undefined ? undefined : supersessionKey([primary])\n}\n\nfunction isPriorAt(candidate: ValidityCandidate, asOfBuild: number): boolean {\n return (\n candidate.openedAtOrdinal <= asOfBuild\n && candidate.closedAtOrdinal !== null\n && candidate.closedAtOrdinal <= asOfBuild\n )\n}\n\nfunction comparePrior(left: ValidityCandidate, right: ValidityCandidate): number {\n const leftClosed = left.closedAtOrdinal ?? Number.NEGATIVE_INFINITY\n const rightClosed = right.closedAtOrdinal ?? Number.NEGATIVE_INFINITY\n return (\n rightClosed - leftClosed\n || right.createdAtOrdinal - left.createdAtOrdinal\n || (left.bundleId < right.bundleId ? -1 : left.bundleId > right.bundleId ? 1 : 0)\n )\n}\n\nfunction auditAnnotation(candidate: ValidityCandidate): ValidityAudit {\n return {\n status: candidate.status,\n openedAtOrdinal: candidate.openedAtOrdinal,\n closedAtOrdinal: candidate.closedAtOrdinal,\n }\n}\n\n/**\n * Apply the half-open current window or, in range-audit posture, return every overlapping fact.\n * Default fallback is selected per normalized primary anchor and preserves the incoming rank order.\n */\nexport function applyValidity<TCandidate extends ValidityCandidate>(\n candidates: readonly TCandidate[],\n resolvedAsOf: number | undefined,\n options: Pick<ValidityOptions, 'asOfRange'> = {},\n): Array<TCandidate & ValidityAnnotation> {\n const range = options.asOfRange\n if (range !== undefined) {\n if (!Number.isFinite(range.lo) || !Number.isFinite(range.hi) || range.lo > range.hi) {\n return []\n }\n return candidates\n .filter((candidate) => overlapsRange(candidate, range))\n .map((candidate) => ({\n ...candidate,\n ...(resolvedAsOf !== undefined && isCurrentAt(candidate, resolvedAsOf)\n ? { servedAs: 'current' as const }\n : {}),\n audit: auditAnnotation(candidate),\n }))\n }\n\n if (resolvedAsOf === undefined || !Number.isFinite(resolvedAsOf)) return []\n\n const groups = new Map<\n string,\n { hasCurrent: boolean; prior: TCandidate | undefined }\n >()\n for (const candidate of candidates) {\n const key = primaryAnchorKey(candidate)\n if (key === undefined) continue\n\n const group = groups.get(key) ?? { hasCurrent: false, prior: undefined }\n if (isCurrentAt(candidate, resolvedAsOf)) {\n group.hasCurrent = true\n } else if (isPriorAt(candidate, resolvedAsOf)) {\n if (group.prior === undefined || comparePrior(candidate, group.prior) < 0) {\n group.prior = candidate\n }\n }\n groups.set(key, group)\n }\n\n const admitted: Array<TCandidate & ValidityAnnotation> = []\n for (const candidate of candidates) {\n if (isCurrentAt(candidate, resolvedAsOf)) {\n admitted.push({ ...candidate, servedAs: 'current' })\n continue\n }\n\n const key = primaryAnchorKey(candidate)\n const group = key === undefined ? undefined : groups.get(key)\n if (\n group?.hasCurrent === false\n && group.prior?.bundleId === candidate.bundleId\n ) {\n admitted.push({ ...candidate, servedAs: 'prior-build-hypothesis' })\n }\n }\n return admitted\n}\n","/**\n * Pure read-only mirror of runner-local/src/build-tag-map.ts latestBuildOrdinal semantics.\n *\n * knowledge-local deliberately cannot import runner-local, so D-14 resolves the shared\n * build-ordinals.json contract through this small host-local reader instead. `runtimeRoot` is the\n * explicitly supplied agent runtime root, not the committed knowledge root. Missing, corrupt, or\n * wrong-shaped state falls through without advancing, rewriting, or creating the counter file.\n */\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst BUILD_ORDINALS_FILE = 'build-ordinals.json'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nexport function readLatestBuildOrdinal(\n runtimeRoot: string,\n product: string,\n): number | undefined {\n try {\n const parsed: unknown = JSON.parse(\n readFileSync(join(runtimeRoot, BUILD_ORDINALS_FILE), 'utf8'),\n )\n if (!isRecord(parsed)) return undefined\n\n const ordinal = parsed[product]\n return typeof ordinal === 'number' && Number.isFinite(ordinal)\n ? ordinal\n : undefined\n } catch {\n return undefined\n }\n}\n","// The D-07 strong-hit rule's pinned constants (Phase 387, ENTY-01).\n//\n// The style is the `LEASE_HEARTBEAT_TTL_MS` idiom: named exports carrying the rationale a\n// retune needs, never configuration. A threshold that a project could set is a threshold that\n// differs per project, and \"never guesses\" would then mean something different in every repo.\n//\n// THE SCALE THESE NUMBERS LIVE ON, AND HOW IT WAS MEASURED\n//\n// Tier (b) ranks with `fuseWeightedRrf`, which is reciprocal-rank fusion: a candidate's\n// contribution from one leg is `weight / (C_RRF + rank)` and nothing else. Raw BM25 and cosine\n// magnitudes are discarded by design at that point — RRF ranks by AGREEMENT, not by score. So\n// with `C_RRF` at 60, one leg's rank-1 contribution is `weight / 61`, its rank-2 contribution\n// is `weight / 62`, and the gap between adjacent ranks (0.00026 at weight 1) is two orders of\n// magnitude smaller than the gap between being in one leg and being in two.\n//\n// Measured on 2026-08-02 against a six-entity index seeded through `refreshEntity` and queried\n// through `lexicalLeg` + `denseLeg` + `fuseWeightedRrf` at weights (1, 1): a lexical-only hit\n// scored 0.016393, a lexical rank-1 plus dense rank-2 hit scored 0.032522, and the whole\n// observed spread across four queries was 0.015625 .. 0.032787. That is the entire dynamic\n// range of the raw fused score, and it is why the reported score is NORMALISED (below) rather\n// than published as-is: \"0.0328\" is not a number any surface can render as confidence.\n//\n// THE CORPUS REPORT THESE VALUES WERE FINALISED AGAINST (387-05)\n//\n// `test-output/entity-resolution-report.json`, written by every run of the resolver corpus\n// suite: 106 entities across the five mintable kinds, 110 authored query cases, 220 rows —\n// every case scored under the full hybrid posture AND under the lexical-only floor. That file\n// is what a retune must argue from; retuning from a handful of observed queries is how a\n// never-guess contract quietly becomes a usually-right one.\n//\n// What the corpus measured on 2026-08-02, at the values below and with nothing changed:\n//\n// - 46 of 110 cases resolve under the full posture, 31 under the floor. Eleven of the floor's\n// are free text, so the lexical-only rung genuinely answers rather than merely surviving.\n// - No case resolves an entity other than the one it declares, in either posture.\n// - No case resolves a DIFFERENT entity at the floor than at the full posture.\n// - Every equal-strength pair disambiguates in both postures, with the two fused scores\n// differing by exactly zero.\n//\n// NEITHER VALUE MOVED, and the corpus is why rather than an excuse for it: both are derived\n// from `C_RRF` and the leg weights (below), so a value fitted to a corpus would have replaced\n// an arithmetic property with a curve fit. What the corpus adds is the boundary measurement the\n// margin's comment could not make on its own — see `RESOLVER_STRONG_HIT_MARGIN`.\n\nimport { C_RRF } from '../retrieval/constants.js'\n\n/**\n * The two leg weights, and they are EQUAL for a reason that is not aesthetic.\n *\n * The degradation invariant (D-08) says a floor host may only produce MORE disambiguation,\n * never a different answer. Floor mode is full mode minus the dense leg, so each candidate's\n * floor score is its full score minus its own dense contribution. With equal weights the most\n * any candidate can gain from the dense leg is one rank-1 contribution, which is what bounds\n * how far the dense leg can reorder the lexical ranking — and that bound is what\n * `RESOLVER_STRONG_HIT_MARGIN` is set against. Weighting the dense leg above the lexical one\n * (as the `semantic` query-class vector does for records) would let the dense leg invert an\n * ordering by more than the margin, and floor mode could then resolve to a different entity.\n *\n * The resolver therefore owns its own weights rather than importing a query-class vector: this\n * pair is load-bearing for a safety property, and a vector tuned for record retrieval has no\n * obligation to stay equal.\n */\nexport const RESOLVER_LEG_WEIGHT_LEXICAL = 1\nexport const RESOLVER_LEG_WEIGHT_DENSE = 1\n\n/**\n * The fused score of a candidate ranked first in EVERY leg — the scale's maximum.\n *\n * Derived rather than typed out, so a `C_RRF` change or a weight change moves the scale and\n * the thresholds below keep meaning what they say. Dividing by it turns the fused score into\n * agreement on [0, 1]: 1 means every leg put this candidate first, and exactly 0.5 means one\n * leg put it first and the other did not rank it at all.\n *\n * This is a rescale by a constant and nothing else — it preserves the ordering `fuseWeightedRrf`\n * produced, and no ranking decision is taken here. It exists so a card can print a number next\n * to tier (a)'s 1.0 without inventing a second vocabulary for confidence.\n */\nexport const RESOLVER_FUSED_SCORE_NORMALIZER =\n (RESOLVER_LEG_WEIGHT_LEXICAL + RESOLVER_LEG_WEIGHT_DENSE) / (C_RRF + 1)\n\n/**\n * The absolute half of the D-07 rule: a strong hit is at the head of at least one leg.\n *\n * 0.5 is exactly one leg's rank-1 contribution on the normalised scale, and picking it says\n * something narrow and true: a candidate that no leg ranked first is never a strong hit, no\n * matter how far ahead of the runner-up it ended up. That case is reachable in practice — the\n * index is refreshed on sighting, so it can hold a row for an entity whose owning store has\n * since forgotten it; when that row heads a leg it is dropped after fusion, and the survivor\n * behind it must NOT be promoted into a confident answer just because the leader vanished.\n *\n * Honest about its limits: on an RRF scale an absolute threshold cannot do much more than\n * this. The fused top is always at least one leg's rank-1 contribution whenever any leg head\n * survives, so a threshold below 0.5 would never fire, and a threshold above 0.5 would forbid\n * a floor host from ever resolving anything — including a reference that matched exactly one\n * entity. The discrimination work is therefore done by the margin below, which is where the\n * two-part rule's second half earns its place rather than restating the first.\n *\n * The corpus report confirms both halves of that claim rather than only the comfortable one:\n * 31 of its 110 cases resolve at the floor, so the threshold is not quietly forbidding the\n * floor rung; and the case where a leg head is dropped after fusion still refuses, so it is not\n * quietly permitting a survivor to inherit a leader's confidence.\n */\nexport const RESOLVER_STRONG_HIT_MIN_SCORE = 0.5\n\n/**\n * The margin half of the D-07 rule, and the number that makes a safety property structural.\n *\n * A candidate can gain at most 0.5 on the normalised scale by being ranked first in the dense\n * leg. For floor mode (which has no dense leg) to resolve entity E while full mode resolves a\n * DIFFERENT entity Z, the dense leg would have to move Z past E by more than twice the margin.\n * Any margin above 0.25 therefore makes that impossible rather than unlikely: floor mode can\n * only ever produce the same resolved entity or refuse to resolve at all. 0.26 is the pinned\n * value with room above the bound so an adjacent-rank rounding difference cannot reach it.\n *\n * Its everyday meaning is simpler: a strong hit is one the legs AGREE on more than they agree\n * on anything else. Two near-twins ranked 1 and 2 differ by 0.016 and always disambiguate —\n * including the equal-strength typo case, which differs by exactly zero and therefore cannot\n * be resolved by any positive margin at all (D-07).\n *\n * WHERE THE BOUNDARY ACTUALLY IS, measured by the 387-05 corpus rather than argued.\n *\n * The 0.25 above comes from a CONTINUOUS inequality, and this scale is not continuous. A floor\n * host's score comes from the lexical leg alone, so its top is one leg's rank-1 contribution\n * (0.5) and its runner-up, when it has one, is rank 2 (0.4919). The largest margin a floor host\n * can therefore ever clear against a rival is the gap between two adjacent ranks — 1/124, about\n * 0.00806 — and above that the floor can only resolve a reference that matched exactly ONE\n * entity, which no dense leg can reorder. So the real bound is thirty times smaller than the\n * one the paragraph above derives, and 0.26 clears both with room to spare.\n *\n * That is not a licence to lower it. The corpus runs its whole population through this same\n * rule at several margins and reports what it finds: no divergence at 0.26, none at 1.5×1/124,\n * and a real one BELOW 1/124, where a case whose two lexical candidates sit 0.008 apart resolves\n * the first at the floor while the dense leg promotes the second in full. That measurement is\n * what makes the invariant's test a gate rather than an arithmetic tautology — and it is only\n * reachable because the decision is applied through one exported function (`applyStrongHitRule`)\n * that the corpus can hand a different margin. Nothing in production passes it one.\n *\n * Retune only alongside `RESOLVER_STRONG_HIT_MIN_SCORE`, and only against the corpus report\n * named at the top of this file: dropping below 1/124 trades the degradation guarantee for\n * recall, and dropping to 0.25 or below gives up the argument that it cannot be traded at all.\n */\nexport const RESOLVER_STRONG_HIT_MARGIN = 0.26\n\n/**\n * How many candidates each leg is asked for.\n *\n * Larger than the top-3 a disambiguation card shows, because fusion needs to SEE the runner-up\n * to refuse: a leg truncated at 3 would hide the competitor that should have turned a resolve\n * into a disambiguation. Bounded because the entity corpus is bounded by what a human can name.\n */\nexport const RESOLVER_CANDIDATE_K = 32\n\n/**\n * The lexical admission floor for the ENTITY corpus, which is not the records corpus floor.\n *\n * `TAU_LEX` is 6.86, calibrated from a recorded serving replay over knowledge records. Measured\n * against entity renderings on 2026-08-02, the entire observed positive BM25 range was 0.0 to\n * 3.24 — an entity rendering is six words where a record rendering is a paragraph, so the two\n * corpora are not on the same scale and `TAU_LEX` rejects EVERY entity lexical candidate. The\n * dense leg keeps its own floor, `tau_dense`, which is profile-owned and therefore correct\n * wherever it is applied; only the lexical floor is corpus-specific, and applying a record\n * corpus's number here would have silently deleted the lexical leg.\n *\n * Zero means \"the FTS query matched at all\", and that is deliberately permissive. Under the\n * never-guess rule a weak extra candidate can only ADD a runner-up, and a runner-up can only\n * turn a resolve into a disambiguation — never into a different answer, because `lexicalLeg`\n * orders by BM25, so a genuine match always outranks a noise match. Raising this floor would\n * make small corpora answer `none` where several entities plainly do mention the word, which\n * is a worse lie than an honest disambiguation card.\n */\nexport const RESOLVER_LEXICAL_MIN_BM25 = 0\n","// The read-only bundle listing served by the /reader entry (Phase 384, D-06).\n//\n// `knowledge.bundles.list` had no reader-entry function before this module: bundle\n// enumeration and loading lived only behind the writer-gated main entry, so a surface that\n// wanted a listing had to reach through the write side. This composes the two existing read\n// faces — `enumerateBundleDirs` and `loadBundle`/`deriveBundleTrust` — into the schema-owned\n// `KnowledgeBundleSummary` projection and nothing else. No writer, no lease, no index.\n\nimport { relative } from 'node:path'\n\nimport type { KnowledgeBundleSummary, TrustPriorTable } from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle } from './bundle-read.js'\nimport { enumerateBundleDirs } from './bundle-scan.js'\n\n/**\n * List every committed bundle under a knowledge root, newest lifecycle state first-class.\n *\n * Deliberately UNFILTERED by serving lifecycle: unlike `scanBundles`, a listing is a review\n * surface, and a superseded or withdrawn record is exactly what a reviewer needs to see. The\n * serving firewall (`isServable`) belongs on retrieval paths, not on a catalog.\n *\n * A bundle whose canonical files do not strictly parse is SKIPPED rather than thrown on, so\n * one damaged bundle never hides every other bundle from the listing. A missing knowledge\n * root is an ordinary empty result — `enumerateBundleDirs` already treats an unreadable\n * directory as empty.\n *\n * Order is total and stable: product, then bundle directory name (which is the record id).\n * `enumerateBundleDirs` already sorts on exactly those two keys.\n */\nexport function listBundles(knowledgeRoot: string, priors?: TrustPriorTable): KnowledgeBundleSummary[] {\n const rows: KnowledgeBundleSummary[] = []\n\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const outcome = loadBundle(entry.dir)\n if (outcome.kind !== 'loaded') continue\n\n const { bundle } = outcome\n const trust = deriveBundleTrust(bundle, priors)\n\n rows.push({\n bundleId: bundle.manifest.id,\n product: entry.product,\n // Relative and slash-normalized so a row is portable across hosts and checkouts.\n dir: relative(knowledgeRoot, entry.dir).replaceAll('\\\\', '/'),\n kind: bundle.frontmatter.kind,\n ...(bundle.frontmatter.subtype === undefined\n ? {}\n : { subtype: bundle.frontmatter.subtype }),\n scope: bundle.frontmatter.scope,\n status: trust.status,\n trust: trust.trust,\n counters: trust.counters,\n openedAtOrdinal: trust.validity.openedAtOrdinal,\n ...(trust.validity.closedAtOrdinal === undefined\n ? {}\n : { closedAtOrdinal: trust.validity.closedAtOrdinal }),\n lastConfirmedOrdinal: trust.lastConfirmedOrdinal,\n summary: bundle.summary,\n evidenceIncomplete: bundle.manifest.evidenceIncomplete,\n })\n }\n\n return rows\n}\n","// The ONE bundle-status → MEM card-status mapping (Phase 387 plan 11, CR-04 / ENTY-02 / D-04).\n//\n// WHY THIS IS A MODULE AND NOT TWO PRIVATE TABLES\n//\n// It was two private tables, and they disagreed. The resolver's copy named three strings, two\n// of which (`withdrawn`, `retired`) are not members of `BundleStatus` at all, and it omitted\n// `deprecated` — the status every forget and every reject actually produces. Its reachable\n// domain was therefore a single member, so after a forget the resolver-path card said `active`\n// while the receipt handed to the same caller in the same operation said `tombstoned`. That is\n// CR-04, and it falsifies D-04's \"permanent address, honest status\" on the one transition this\n// phase's own destructive verb creates.\n//\n// The root-cause shape is worth naming because it decides this module's design: a table scoped\n// to hand-picked members of a set whose hazard belongs to the WHOLE set. So the fix is not\n// \"add `deprecated`\" — it is a mapping the compiler forces to be TOTAL over the complete union,\n// and a regression case that walks the complete union rather than the member that failed.\n//\n// TOTAL, AND TOTAL TWICE OVER\n//\n// `satisfies Record<BundleStatus, …>` is the 387-07 key-facts table pattern applied to\n// statuses: a fifth `BundleStatus` member becomes a type error HERE rather than a card that\n// silently renders a generic status, and an entry naming something outside the union is a type\n// error too — which is exactly what would have rejected `withdrawn` and `retired` on the day\n// they were written. There is deliberately NO fallback arm. A silent default is what made two\n// dead members and one missing member invisible for the life of the defect; an unknown status\n// must be loud.\n//\n// This module is package-internal on purpose and is NOT re-exported through the package\n// barrel. Its two consumers — the resolver's MEM sighting source, and the review apply path in\n// `review/apply-review.ts` (swapped by plan 387-12) — both live inside `knowledge-local`, and\n// a barrel export would invite a third vocabulary consumer outside the package, which is the\n// one-producer discipline D-12 exists to keep.\n\nimport { ENTITY_STATUSES } from '@vostride/agent-qa-schema'\nimport type { BundleStatus } from '@vostride/agent-qa-schema'\n\n/** The `MEM` card vocabulary, drawn off the schema's own table rather than respelled. */\nexport type MemoryCardStatus = (typeof ENTITY_STATUSES)['MEM'][number]\n\n/**\n * Every `BundleStatus`, and what a `MEM` card says about it.\n *\n * `candidate` maps to `active` rather than to a third thing because the `MEM` vocabulary has no\n * word for \"proposed but not yet promoted\": a candidate record exists, is addressable and is\n * not tombstoned, and `active` is the honest card answer for it. `superseded` and `deprecated`\n * both mean the thing this address names stopped standing, which is precisely what\n * `tombstoned` reports.\n *\n * `forgotten` is a legal `MEM` status that nothing here produces, and that is correct rather\n * than an omission: it is the D-19 forget receipt's word, applied at the card producer when a\n * receipt is in hand, and a bundle status never derives it.\n *\n * This table is also the RUNTIME enumeration of `BundleStatus` — the schema declares that union\n * as a type only, with no runtime array beside it — so a walk of these keys is a walk of the\n * union.\n */\nexport const MEMORY_STATUS_BY_BUNDLE_STATUS = {\n active: 'active',\n candidate: 'active',\n superseded: 'tombstoned',\n deprecated: 'tombstoned',\n} as const satisfies Record<BundleStatus, MemoryCardStatus>\n\n/** A status no `BundleStatus` names reached the mapping. Loud by design — never `active`. */\nexport class UnknownBundleStatusError extends TypeError {\n constructor(readonly status: string) {\n super(\n `no MEM card status is declared for bundle status ${JSON.stringify(status)}; `\n + `the declared bundle statuses are ${Object.keys(MEMORY_STATUS_BY_BUNDLE_STATUS)\n .sort()\n .join(', ')}`,\n )\n this.name = 'UnknownBundleStatusError'\n }\n}\n\n/**\n * The MEM card status for a bundle status. TOTAL — no fallback arm.\n *\n * The parameter stays `BundleStatus` rather than widening to `string`, and the choice is the\n * whole protection this module exists to give. Both production call sites already hold a\n * `BundleStatus` (`listBundles` sets `status` from `deriveBundleTrust`, and `locateRecord` in\n * the review apply path does the same), so a narrow parameter makes a fifth union member a\n * COMPILE error at every call site. Widening to `string` would buy a reachable throw arm at the\n * cost of that compile-time totality, which is trading the guarantee for the backstop.\n *\n * The runtime `Object.hasOwn` check therefore guards a boundary the type system cannot see\n * through — a status that arrives from a deserialized projection row or a DTO round-trip\n * through a cast. It throws rather than defaulting because the silent default is the defect.\n */\nexport function memoryStatusForBundle(status: BundleStatus): MemoryCardStatus {\n if (!Object.hasOwn(MEMORY_STATUS_BY_BUNDLE_STATUS, status)) {\n throw new UnknownBundleStatusError(status)\n }\n return MEMORY_STATUS_BY_BUNDLE_STATUS[status]\n}\n","// The MEM entity sighting source (Phase 387, plan 01 — the tracer's one wired kind).\n//\n// Reads through the same read-only bundle listing `knowledge.bundles.list` serves, so a\n// memory entity the catalog shows and a memory entity the resolver can sight are the same\n// set by construction rather than by two enumerations that agree today.\n//\n// Deliberately UNFILTERED by serving lifecycle, matching `listBundles`: a superseded or\n// deprecated record still has a permanent address and must still resolve (D-04). The card's\n// status is what says what happened to it.\n//\n// That status is derived by the ONE shared mapping in `memory-status.ts`, which is total over\n// the complete `BundleStatus` union. This module used to carry its own private table with a\n// silent `active` fallback; the fallback hid two members the union does not contain and one it\n// does, and the card contradicted the forget receipt as a result (CR-04, plan 387-11).\n\nimport { listBundles } from '../list-bundles.js'\nimport { memoryStatusForBundle } from '../memory-status.js'\nimport type { EntitySighting, EntitySightingSource } from './resolve.js'\n\n/** Build the MEM sighting source over a knowledge root. */\nexport function createMemorySightingSource(\n resolveKnowledgeRoot: () => string,\n): EntitySightingSource {\n function find(machineId: string): EntitySighting | undefined {\n for (const row of listBundles(resolveKnowledgeRoot())) {\n // EXACT equality. This leg is addressing, not search: a prefix or case-insensitive\n // comparison here would be tier (b) smuggled in below the never-guess contract.\n if (row.bundleId !== machineId) continue\n return {\n machineId: row.bundleId,\n title: row.summary,\n statusSource: memoryStatusForBundle(row.status),\n }\n }\n return undefined\n }\n\n return {\n kind: 'MEM',\n sight: find,\n // Sighting and hydration are the same lookup for MEM: a bundle id IS the machine id, so\n // there is no second index to consult. They stay two members on the port because for\n // RUN and TST (387-03) they will not be.\n hydrate: find,\n }\n}\n","// The committed quarantine ledger: read, pure state fold, shape-checked append\n// (Phase 390, D-01/D-03/D-04/D-11).\n//\n// `quarantine.jsonl` sits DIRECTLY under the committed knowledge root as its OWN top-level\n// artifact beside memory/ and policies/. It is the FIRST committed top-level operational artifact\n// — there is no sibling precedent to copy (the build-tag ordinal map lives under the gitignored\n// runtime root), so its placement is reconciled against the knowledge-store layout deliberately:\n// none of the root ignore rules (memory/index, memory/queue, the lease and epoch markers,\n// **/artifacts, skills/.staging) match this filename, which is pinned by a test.\n//\n// READ POSTURE — refusal as data, never healing to absence. The derived run-outcome projection\n// heals malformed bytes to an empty window because it is a rebuildable derivation. This file is\n// COMMITTED TRUTH that humans may hand-edit (D-12), and healing a quarantine entry to absent\n// silently UN-quarantines a test — the exact silent flip this phase exists to prevent. So a line\n// that fails to parse or fails the shape guard is REFUSED and surfaced in `refusedLines`, while\n// its neighbours still fold. A line declaring a NEWER schemaVersion propagates the typed\n// QuarantineLedgerVersionError: a build that cannot read the truth must not guess at it.\n//\n// WALL-CLOCK PURITY — the fold takes `now` as an argument and this module reads no clock. `at` and\n// `expiresAt` are stamped by callers at write time (D-11). That is what lets expiry boundaries be\n// pinned one second either side with no flake.\n//\n// WRITE POSTURE — fail-closed on ONE gate. Every append first pre-checks each event against BOTH\n// legs the READ's guard ranges — the VERSION IDENTITY (`=== CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION`)\n// and schema's `hasQuarantineEventShape`, which is the LAST of that guard's FIVE legs (390-22 /\n// IN-02) and asserts only that `schemaVersion` is a NUMBER — and only after all of it does a byte\n// reach the file. The pre-check asks \"can this ever be read back?\" and THROWS: a write the reader\n// refuses is corruption of a committed artifact, not a refusal a caller can sensibly carry on from\n// (it is invisible to `list`, unreleasable, and duplicates on retry). The text itself is written as\n// handed over; no detector scans it (Phase 441, D-15). Quarantine events are CODE-authored — threshold crossings, auto-exits, the gated verbs — never model output, which is\n// why CTX-FUT-01's propose-only posture deliberately does not bind these writes (D-04; the dated\n// posture note lands in REQUIREMENTS.md).\n//\n// SERIALIZATION belongs to two NAMED callers, and this module is not one of them — it holds no lock\n// of its own. Both mechanisms are real and each is enforced in code:\n// - the POST-RUN FOLD appends under a lease the drain already holds. `post-run-tail.ts:458`\n// acquires the writer lease and the fold runs inside that scope.\n// - the GATED VERBS acquire the lease INSIDE `createQuarantineOperations` and release it per\n// call, or ride the handed-in `writerAuthority` when the host process is already the holder\n// (the daemon). The whole read-fold-decide cycle is inside that scope, not just the append.\n// This paragraph previously claimed the verb half serialized POSITIONALLY, \"because of where the\n// callers are invoked from\". That was false and statically so — 390-09 / CR-03: no caller on the\n// path from `invokeFunction('quarantine.add')` to this function held any lease. It is true now\n// because the verb module takes one, not because anything here does.\n// The residual is honest and small, and 390-11 / WR-07 closed half of it — say both halves plainly:\n// - SERIALIZATION stays open. A THIRD caller of `appendQuarantineEvents`, added outside those two\n// paths, would be unserialized and would have to take the lease itself.\n// - SHAPE AND VERSION are both closed AT THIS SEAM. A third caller cannot author a structurally\n// unreadable line, because the append pre-checks every event against the read's structural\n// predicate before writing; and it cannot stamp a version the read refuses either, because the\n// same loop compares `schemaVersion` against CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION (390-14 /\n// G-390-1 — the structural predicate alone admitted five such versions, since it asks only that\n// the field be a number). That class needed closing here rather than at each caller precisely\n// because the caller set can grow.\n//\n// IDENTITY — entries are keyed by `(product, filePath, testName)`, never `testId`.\n\nimport { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n canonicalJson,\n guardQuarantineLedgerEvent,\n hasQuarantineEventShape,\n} from '@vostride/agent-qa-schema'\nimport type {\n QuarantineEntryState,\n QuarantineEntryStateName,\n QuarantineLedgerEvent,\n QuarantineOwner,\n} from '@vostride/agent-qa-schema'\n// The identity key, imported rather than re-spelled (390-28 / WR-01). The fold below keys entries\n// on exactly the bytes the detection ladder and `operations.ts`'s triage queue key on; a second\n// copy here is how two folds start disagreeing about which lines are the same test.\n//\n// THIS IMPORT sits on no cycle BY CONSTRUCTION (390-31): `identity.ts` is a leaf with zero import\n// statements, so there is no path out of it and therefore none back here. The claim is about this\n// edge and nothing more. It replaced a sentence asserting subsystem acyclicity off a check run one\n// hop deep, which was false — while the key lived in `detection.ts`, this import closed a four-edge\n// value cycle through the window read (`-> detection.ts -> fingerprint-window-read.ts ->\n// run-outcomes.ts -> ledger.ts`), round-5 gap 3a. That is why the key moved to a leaf rather than\n// getting a longer comment. Other cycles in this subsystem are unaffected and still stand.\nimport { quarantineIdentityKey } from './identity.js'\n\n/** The ledger's fixed name directly under the committed knowledge root — never caller-supplied. */\nexport const QUARANTINE_LEDGER_FILENAME = 'quarantine.jsonl'\n\n/** One line the read refused, surfaced as data so a caller can print or audit it. */\nexport interface RefusedQuarantineLine {\n /** 1-based, so it matches what an editor shows the human who has to fix the file. */\n lineNumber: number\n reason: string\n}\n\nexport interface QuarantineLedgerRead {\n events: readonly QuarantineLedgerEvent[]\n refusedLines: readonly RefusedQuarantineLine[]\n}\n\n/** The ledger's absolute path under one knowledge root. */\nexport function quarantineLedgerPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, QUARANTINE_LEDGER_FILENAME)\n}\n\n/**\n * Read every event the committed ledger carries, in file order.\n *\n * A missing ledger is an EMPTY ledger — no test is quarantined and run behavior is byte-identical\n * to pre-390 (the FLAK-03 empty-input edge). Blank lines are skipped silently; they are whitespace,\n * not damage. Everything else that fails is refused and reported.\n *\n * Throws {@link QuarantineLedgerVersionError} (typed) when a line declares a schemaVersion this\n * build cannot consume — committed truth hard-fails rather than degrading silently.\n */\nexport function readQuarantineLedger(knowledgeRoot: string): QuarantineLedgerRead {\n let text: string\n try {\n text = readFileSync(quarantineLedgerPath(knowledgeRoot), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return { events: [], refusedLines: [] }\n }\n throw error\n }\n\n const events: QuarantineLedgerEvent[] = []\n const refusedLines: RefusedQuarantineLine[] = []\n\n const lines = text.split('\\n')\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]\n if (line.trim().length === 0) continue\n\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (error) {\n refusedLines.push({\n lineNumber: index + 1,\n reason: `unparseable line: ${error instanceof Error ? error.message : String(error)}`,\n })\n continue\n }\n\n // The version guard's own reject-newer arm must propagate; only its structural rejection\n // folds to a refusal. Distinguishing them keeps a build-level \"cannot read this truth at all\"\n // apart from a line-level \"this one record is damaged\".\n let event: QuarantineLedgerEvent\n try {\n event = guardQuarantineLedgerEvent(parsed)\n } catch (error) {\n if (error instanceof TypeError) {\n refusedLines.push({ lineNumber: index + 1, reason: error.message })\n continue\n }\n throw error\n }\n events.push(event)\n }\n\n return { events, refusedLines }\n}\n\ninterface MutableEntry {\n product: string\n filePath: string\n testName: string\n fingerprint: string\n verdictClass: QuarantineEntryState['verdictClass']\n owner: QuarantineOwner\n enteredAt: string\n expiresAt: string\n /** Accumulated across every `entered` event for this key — never reset by the re-entry arm. */\n enteredCount: number\n /** The FIRST `entered` event's instant for this key; set once and carried forward. */\n firstEnteredAt: string\n /** The state the EVENTS put the entry in; expiry is applied against `now` afterwards. */\n eventState: 'quarantined' | 'released'\n}\n\n/**\n * Fold the event log into current per-entry state. PURE — identical `(events, now)` inputs answer\n * identically, and no clock is read.\n *\n * Per key, in event order: `entered` opens (or re-opens — D-10's re-entry needs no special rule,\n * the sliding window self-heals) a window carrying owner/expiry/fingerprint/class; `renewed`\n * extends the expiry and claims the owner when one is supplied; either released kind closes it.\n *\n * TWO OF THE ANSWERED FIELDS ARE HISTORY, NOT WINDOW FACTS (390-18). `enteredCount` is how many\n * `entered` events this key has accumulated — a renewal extends a window rather than opening one,\n * so it never increments — and `firstEnteredAt` is the first of those events' instant. They are\n * DERIVED here from bytes the log already holds: no new event kind carries them, no migration\n * exists for them and {@link CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION} is unmoved by them. A\n * reader meeting two new fields on a versioned artifact's state type will reasonably ask whether\n * the file format moved; it did not, and every ledger written before this fold existed answers\n * both questions correctly on its next read. This is the question D-03 chose an append-only log to\n * make free, finally being asked.\n *\n * THE TWO INSTANTS ANSWER DIFFERENT QUESTIONS and their names are close enough to be a drift\n * hazard, so: `enteredAt` is WHEN THIS WINDOW OPENED, which is the fact `expiresAt` and the\n * computed state are about; `firstEnteredAt` is WHEN THIS TEST'S QUARANTINE HISTORY BEGAN, which\n * is the fact a human triaging it needs (and the key `triageOrder` sorts on, so that a test on its\n * seventh re-entry cannot present as the newest thing in the queue).\n *\n * A renewal can extend an OPEN window — quarantined or lapsed — but NEVER re-opens a CLOSED one\n * (390-11 / WR-04). A release is the operator's decision, and re-entry has its own event:\n * `operations.add` already routes a released entry to the `entered` branch, so honoring a `renewed`\n * against a closed window would only ever resurrect a suppression a human deliberately ended. That\n * case is reachable solely through the committed file's documented human-editability (D-12) — no\n * code path authors it — which is exactly why the fold, not the verb, is where it has to be\n * refused. The guard keys on the EVENT state, never the computed one: a lapsed entry still carries\n * `eventState: 'quarantined'` (expiry is applied after this loop), so D-11's renew-an-expired-entry\n * behavior is untouched.\n *\n * `'expired'` is then COMPUTED, never read from an event: an open window whose `expiresAt` is at or\n * before `now` answers `'expired'`. Its suppression has stopped — the test fails builds again — and\n * the entry stays LISTED, renewable and releasable (D-11).\n *\n * SCOPE OF THAT GUARANTEE, stated because it is narrower than it reads: the lapse ends THIS\n * window, not the suppression. A fingerprint still crossing the threshold re-enters on the very\n * next fold with a fresh full-lifetime deadline, so a permanently failing test costs one red build\n * per lifetime and no human decision, indefinitely. Nothing in this fold or in the ladder bounds\n * that repetition (measured 2026-08-06; pinned in `cli/src/__tests__/quarantine-lifecycle.e2e.test.ts`'s\n * multi-cycle leg, and made legible to a human by plan 390-18's re-entry counter). What the lapse\n * IS, honestly: a 30-day review cadence on an indefinitely renewable suppression.\n *\n * `now` is an ISO-8601 instant, compared on the same scale the events are stamped on.\n */\nexport function foldQuarantineLedgerState(\n events: readonly QuarantineLedgerEvent[],\n now: string,\n): QuarantineEntryState[] {\n const entries = new Map<string, MutableEntry>()\n\n for (const event of events) {\n const key = quarantineIdentityKey(event)\n switch (event.kind) {\n case 'entered': {\n // Read the prior record BEFORE overwriting it. The arm still overwrites every mutable\n // fact — that is deliberate, a re-entry genuinely re-states owner, expiry, fingerprint and\n // class — but two of them are HISTORY rather than facts about the current window, and a\n // whole-record `set` discarded exactly the history D-03 chose an event log to keep.\n const prior = entries.get(key)\n entries.set(key, {\n product: event.product,\n filePath: event.filePath,\n testName: event.testName,\n fingerprint: event.fingerprint,\n verdictClass: event.verdictClass,\n owner: event.owner,\n enteredAt: event.at,\n expiresAt: event.expiresAt,\n enteredCount: (prior?.enteredCount ?? 0) + 1,\n firstEnteredAt: prior?.firstEnteredAt ?? event.at,\n eventState: 'quarantined',\n })\n break\n }\n case 'renewed': {\n const existing = entries.get(key)\n // A renewal with no window to renew is meaningless — refusing to synthesize one keeps the\n // fold honest about what the log actually says (no invented entries reach any surface).\n if (existing === undefined) break\n // Nor does a renewal re-open a CLOSED window: the release stands until an `entered` event\n // says otherwise (WR-04, above).\n if (existing.eventState === 'released') break\n existing.expiresAt = event.expiresAt\n if (event.owner !== undefined) existing.owner = event.owner\n existing.eventState = 'quarantined'\n break\n }\n case 'released-manual':\n case 'released-auto': {\n const existing = entries.get(key)\n if (existing === undefined) break\n existing.eventState = 'released'\n break\n }\n }\n }\n\n const nowMs = Date.parse(now)\n return [...entries.values()].map((entry) => {\n let state: QuarantineEntryStateName = entry.eventState\n if (state === 'quarantined') {\n const expiresMs = Date.parse(entry.expiresAt)\n // An unparseable deadline is treated as lapsed: the failing test fails builds again, which is\n // the safe direction. Silently suppressing forever on a mangled date is the one outcome D-11\n // exists to make impossible.\n if (Number.isNaN(expiresMs) || expiresMs <= nowMs) state = 'expired'\n }\n return {\n product: entry.product,\n filePath: entry.filePath,\n testName: entry.testName,\n fingerprint: entry.fingerprint,\n verdictClass: entry.verdictClass,\n owner: entry.owner,\n enteredAt: entry.enteredAt,\n expiresAt: entry.expiresAt,\n enteredCount: entry.enteredCount,\n firstEnteredAt: entry.firstEnteredAt,\n state,\n }\n })\n}\n\n/** What an append answers: how many lines it wrote. */\nexport type QuarantineAppendOutcome = { kind: 'appended'; lines: number }\n\n/**\n * Append lifecycle events to the committed ledger, as ONE fail-closed unit (D-04).\n *\n * Order is the whole point: shape-check EVERY event → serialize → only then write. Because the\n * check covers the unit, a single refused event withholds its clean siblings too, and the existing\n * file is left byte-unchanged. Partial writes are the failure mode that would leave the committed\n * truth half-updated and a reviewer unable to tell.\n *\n * Throws a `TypeError` naming the offending index — and which leg refused — when an event would\n * not survive {@link readQuarantineLedger}'s own guard, on EITHER of that guard's legs: the version\n * identity (390-14 / G-390-1) or the structural predicate (390-11 / WR-07). This is deliberately a\n * THROW rather than an outcome: authoring an unreadable line is a CALLER BUG that would otherwise\n * commit permanent, unlistable, unreleasable damage to a shared artifact.\n *\n * Callers stamp `at` and `expiresAt` themselves (D-11): this module reads no clock, which is what\n * keeps both the write path and the fold deterministic.\n */\nexport function appendQuarantineEvents(\n knowledgeRoot: string,\n events: readonly QuarantineLedgerEvent[],\n): QuarantineAppendOutcome {\n if (events.length === 0) return { kind: 'appended', lines: 0 }\n\n // The write refuses what the read refuses, on BOTH of the read's legs: the VERSION IDENTITY and\n // the STRUCTURAL predicate. One predicate was never enough on its own —\n // `hasQuarantineEventShape` asserts only that `schemaVersion` is a number, while the read\n // (`guardQuarantineLedgerEvent`) additionally requires it to BE the current version, so `3`, `1`,\n // `2.5`, `NaN` and `Infinity` were all admitted here (390-14 / G-390-1).\n //\n // AND THE READ REFUSES THEM IN TWO DIFFERENT WAYS — stated per member, because an argument for a\n // gate that misdescribes the failure it prevents will be trusted the next time it is quoted\n // (390-22 / WR-02; this paragraph used to claim a whole-file failure for all five, which is\n // false for two of them):\n //\n // `3`, `1`, `2.5` are FINITE, so they reach the guard's reject-newer and migration-walk legs\n // and raise the typed `QuarantineLedgerVersionError`, which `readQuarantineLedger` lets\n // PROPAGATE. One such line hard-fails the WHOLE file, taking `list`, `add` and `release`\n // down together.\n //\n // `NaN` and `Infinity` were never writable in that form at all: `canonicalJson` turns a\n // non-finite number into `null` before a byte reaches disk, so what the reader meets is a\n // NULL version, which fails the guard's finite-number leg with a plain `TypeError` and folds\n // into a LINE-LEVEL refusal — the neighbours still fold and all three verbs keep working.\n // They are refused here for a genuinely different reason than the reader refuses them for.\n //\n // The pre-check ranges both modes identically, and that is the symmetry argument: whichever way\n // the read would refuse a line, no byte of it is written. Splitting the read side does not split\n // the write side.\n //\n // `===`, not `<=`: two of those five are OLDER-side, and `NaN`/`Infinity` fail every ordering\n // comparison silently. The rule widens only if `QUARANTINE_LEDGER_MIGRATIONS` ever stops being\n // empty, at which point it becomes CURRENT plus every version with a registered migration — the\n // read guard's own rule.\n //\n // Why an explicit comparison rather than simply calling `guardQuarantineLedgerEvent` (the read's\n // whole predicate) here: that guard RETURNS a possibly-migrated value, while this append writes\n // the CALLER'S original object. Routing through it would make the write's refusal type depend on\n // the guard's internal leg order and would commit bytes the guard did not return — a latent\n // divergence the permanently-empty migration registry currently hides. The explicit comparison\n // has no such coupling, and it states the rule where the loop already states its sibling.\n //\n // Both legs run before any filesystem call, so a refused unit leaves no byte. The message names\n // the offending index AND which leg refused,\n // so an operator reading the throw can tell a malformed record from a wrong-version one.\n for (let index = 0; index < events.length; index += 1) {\n const version = events[index]?.schemaVersion\n if (version !== CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION) {\n throw new TypeError(\n `quarantine event at index ${String(index)} would be refused by the ledger read: ` +\n `schemaVersion ${String(version)} is not the current version ` +\n `${String(CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION)} — the committed ledger must never ` +\n 'carry a line no checkout can consume',\n )\n }\n if (hasQuarantineEventShape(events[index])) continue\n throw new TypeError(\n `quarantine event at index ${String(index)} would be refused by the ledger read: ` +\n 'the committed ledger must never carry a line no checkout can consume',\n )\n }\n\n const lines = events.map((event) => canonicalJson(event))\n mkdirSync(knowledgeRoot, { recursive: true })\n appendFileSync(quarantineLedgerPath(knowledgeRoot), `${lines.join('\\n')}\\n`, 'utf8')\n return { kind: 'appended', lines: lines.length }\n}\n","// The quarantine subsystem's identity LEAF (390-31).\n//\n// This module imports NOTHING — not the schema package, not the projection, not a sibling. That is\n// its whole job. Every module that has to decide \"are these two lines the same test?\" needs the\n// identity key: the detection ladder, `ledger.ts`'s `foldQuarantineLedgerState`, and\n// `operations.ts`'s `triageOrder`/`entryFor`. While the key lived in `detection.ts`, reaching it\n// meant acquiring an import edge INTO the detection ladder, and `detection.ts` re-exports §7.3's\n// window from the projection — so `ledger.ts`'s keying import closed a four-edge VALUE cycle\n// (`ledger.ts -> detection.ts -> fingerprint-window-read.ts -> run-outcomes.ts -> ledger.ts`),\n// measured by grep at 390-31's HEAD. Nothing broke, because every binding on that chain is consumed\n// inside a function body; but the comment justifying the import claimed an acyclicity check that\n// had only been run one hop deep (round-5 gap 3a).\n//\n// A leaf has no outgoing edges, so an import OF it can sit on no cycle by construction. That is a\n// property of this file's import list, checkable in one glance, and it is the reason the key lives\n// here rather than being documented where it was.\n//\n// SCOPE. This module holds the key and its input type — nothing else. `compareQuarantineIdentity`\n// and the module-private `compareBytes` stay in `detection.ts`, where their two real call sites\n// are; widening the leaf to pull them in would re-open 390-28's IN-01 visibility closure.\n\n/** The identity a quarantine record is keyed on: `(product, filePath, testName)`, never `testId`. */\nexport interface QuarantineIdentity {\n product: string\n filePath: string\n testName: string\n}\n\n/**\n * The identity key, spelled ONCE for the whole subsystem (390-22 / WR-06).\n *\n * `JSON.stringify` of the triple rather than a joined string: the parts are caller data and may\n * contain any character, and a separator that can appear inside a part is a collision waiting to\n * happen.\n *\n * ONCE IS TRUE OF THE CODE, NOT ONLY OF THE SENTENCE (390-28 / WR-01). Every keying site in the\n * subsystem IMPORTS this function rather than carrying a byte-identical copy: the detection ladder\n * in `detection.ts`, `ledger.ts`'s `foldQuarantineLedgerState`, which keys per-entry state on it,\n * and `operations.ts`'s `triageOrder`, which keys the triage queue on it. Until 390-28 only the\n * `operations.ts` half of that de-duplication had happened and the fold carried a private twin —\n * measured by mutating this function's bytes, under which `ledger.test.ts` stayed 57/57 green. It\n * reds now, and since 390-31 the fold reaches this definition without an edge into detection.\n *\n * The recipe is load-bearing history, not an implementation detail: it decides which committed\n * ledger lines merge onto one entry, so changing these bytes re-keys ledger history that is already\n * on disk (the 389 D-13 re-keying hazard, applied to entries).\n */\nexport function quarantineIdentityKey(identity: QuarantineIdentity): string {\n return JSON.stringify([identity.product, identity.filePath, identity.testName])\n}\n","// The detection ladder: the pure rule that turns fingerprint recurrence into quarantine lifecycle\n// events (Phase 390, D-05/D-06/D-07/D-10/D-11/D-12).\n//\n// PURE BY CONSTRUCTION. Every input arrives as plain data — recurrence answers the projection\n// already computed, per-test ordinal windows, the folded ledger state, and `now`. This module reads\n// no clock, opens no database and touches no filesystem, which is what lets every threshold be\n// pinned one step either side with zero flake. `expiresAt` is DERIVED from the supplied `now`\n// (390-01's wall-clock-purity-by-argument pattern, extended from the fold to the rule that authors).\n//\n// THE LADDER (D-06). Flag early, act at N. A fingerprint at QUARANTINE_FLAG_FLOOR distinct\n// occurrence ordinals is FLAGGED — visibility only, zero ledger bytes — and at\n// QUARANTINE_ESCALATE_THRESHOLD it ESCALATES. \"Flags and then escalates\" is temporally real: one\n// build of warning before anything changes.\n//\n// THE GATE IS TWO TOTAL TABLES OVER ONE CLOSED UNION (D-05, extended by 390-16). Escalation routes\n// through QUARANTINE_CLASS_DISPOSITIONS and QUARANTINE_FLOOR_ELIGIBILITY, both keyed on the CLOSED\n// eight-member VerdictClass union rather than a set membership test. That shape is deliberate: a\n// ninth verdict class cannot compile until someone decides BOTH answers for it, so each gate's\n// INPUT DOMAIN is enumerated, not just its outputs.\n//\n// - DISPOSITION answers \"may this class ever auto-quarantine\". Only the three classes\n// `eval-and-core-types.md` §A9 routes to A3 may. The other five escalate LOUDLY and append\n// nothing.\n// - FLOOR ELIGIBILITY answers the axis the class set alone cannot express: is the EVIDENCE behind\n// the class about THIS TEST, or about the run? It is one of TWO conjuncts on the floor arm\n// (390-19): the class answers whether the floor may decide this KIND of thing at all, and the\n// crossing's `sameBuildPassAndFail` answers whether there is per-test evidence in THIS crossing.\n// A crossing carrying an AUTHORED `analyze-run` verdict needs neither, because a model reading\n// this test's evidence IS the per-test statement.\n//\n// AND THE FLOOR ARM IS BUDGETED PER RUN (390-19). Neither table contains mass auto-quarantine on\n// the floor path and neither should be read as doing so — `classifyRootCause` returns `timeout`\n// before it ever reads its health probe, so a run-scoped hang arrives in the class the floor may\n// act on. QUARANTINE_FLOOR_AUTO_QUARANTINE_CAP budgets that arm per run. It RATE-LIMITS a fan-out\n// and does not contain one — a refused member is admitted on the next applied run (measured;\n// 390-28 / WR-02) — so nothing in this module bounds eventual entries. See its docstring.\n//\n// A crossing that either table refuses lands in `escalatedNotQuarantined` — the build keeps\n// failing, because auto-silencing a real regression is the one outcome this phase exists to\n// prevent. There is deliberately NO third arm: a refused crossing that goes nowhere is the\n// anti-silencing defect wearing another hat.\n//\n// THE UPSTREAM SHARPENING THIS MODULE DELIBERATELY DOES NOT TAKE. `classifyRootCause`'s two\n// run-scoped probe arms arguably should not mint a PER-TEST verdict at all — a down dependency is\n// a run-level condition, closer to `config_error` — and fixing it there would be more correct and\n// would help every verdict consumer, not just this one. But that rewrites phase 373's documented,\n// pinned branch order, which is that module's contract and not this one's. Named here so the next\n// reader knows the producer gate closes the MEASURED path rather than the root cause.\n//\n// WHY THE OTHER FIVE ARE ESCALATE-ONLY, individually:\n//\n// - `app_bug` / `test_bug`: a real regression and a genuinely broken test. Humans quarantine\n// known-broken tests deliberately through the `add` verb (D-12); nothing here does it for them.\n// - `unknown`: the LLM-judge abstention AND the deterministic floor's answer for any failure\n// carrying no verdict at all. Auto-quarantining it would silence essentially every recurring\n// failure on a project running without analysis, which is the anti-silencing defect wearing a\n// different hat.\n// - `config_error`: the harness or project is misconfigured. Deterministic, fixable, and it will\n// not heal itself — suppressing it hides the one thing a human must act on.\n// - `llm_error`: our own model plumbing failed. That is evidence about the agent, never evidence\n// that the test is flaky.\n//\n// SERIALIZATION and EGRESS belong to the caller. This module returns events as data; the fold\n// appends them through `appendQuarantineEvents`, inside the writer-lease scope, after the\n// projection transaction has committed.\n//\n// 2026-09-02 (Phase 412): the curation spec these notes once cited left with the Issue-slot cleanup;\n// the A3 routing lives in `eval-and-core-types.md` §A9 and the trigger in `memory.md` §9.5.\n\nimport {\n CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n QUARANTINE_UNASSIGNED_OWNER,\n VERDICT_CLASSES,\n} from '@vostride/agent-qa-schema'\nimport type {\n QuarantineEntryState,\n QuarantineLedgerEvent,\n QuarantineOwner,\n Verdict,\n VerdictClass,\n} from '@vostride/agent-qa-schema'\n\n// The identity key and its input type live in the subsystem's zero-import leaf (390-31), not here:\n// the ladder is only one of three keying sites, and hosting the key made every other site pay an\n// import edge into this module. `compareQuarantineIdentity` below still composes it.\nimport { quarantineIdentityKey } from './identity.js'\nimport type { QuarantineIdentity } from './identity.js'\n\n// §7.3's locked window is spelled ONCE, beside the table it slides over. Re-exported here because\n// the ladder's own contract is incomplete without it, and a second declaration is how a threshold\n// and the window it is counted against drift apart.\nexport { QUARANTINE_WINDOW_ORDINALS } from '../projection/fingerprint-window-read.js'\n\n/**\n * Visibility floor (D-06): distinct occurrence ordinals at which a fingerprint becomes suspected\n * flaky. Pinned, never config — retune from operational evidence in this source, where the change\n * is reviewable.\n */\nexport const QUARANTINE_FLAG_FLOOR = 2\n\n/**\n * `memory.md` §9.5's locked trigger, verbatim: the same fingerprint at three distinct ordinals\n * inside the window escalates. Pinned constant with no config key (386 D-15) — retune it here.\n */\nexport const QUARANTINE_ESCALATE_THRESHOLD = 3\n\n/**\n * THE PER-RUN BUDGET for mass auto-quarantine on the FLOOR path (390-19 / G-390-5): at most this\n * many `entered` events may be authored on the floor arm in ONE `evaluateQuarantineDetection` call.\n * One call is one run's fold, so this is PER RUN — and PER RUN is the whole of it, which is why\n * this reads \"budget\" and not \"containment\" (390-28 / WR-02; see the measurement below).\n *\n * WHY A COUNT AND NOT A CLASS. 390-16's motivating observation was itself a count — one probe\n * failure auto-quarantined 6 of 6 tests in a suite — and it was read as a statement about the class\n * `environment`. That reading is unsound under `classifyRootCause`'s branch order: its\n * `outcome === 'timeout'` arm RETURNS before the `baselineProbe` arms that mint `environment`, so a\n * run-scoped hang arrives classed `timeout`. Every class the floor can mint on a FAILING member is\n * reachable from a run-scoped cause, so no class-based gate can contain fan-out. This constant\n * states the property directly instead of proxying it through class semantics.\n *\n * WHAT THIS CONSTANT ACTUALLY BUYS: A RATE LIMIT, NOT CONTAINMENT (390-28 / WR-02, correcting the\n * 390-19 text). Two claims stood here and both were false, in opposite directions:\n *\n * 1. IT WOULD NOT HAVE CAUGHT THE MOTIVATING EVENT — that event never reaches this counter. The\n * measured 6-of-6 members classed `environment`, and `QUARANTINE_FLOOR_ELIGIBILITY.environment`\n * is `authored-required`, so `autoQuarantines` answers `'refused'` for a floor-produced\n * `environment` crossing one conjunct EARLIER; the cap is consulted only when that call answers\n * `'floor'`. Zero entered lines for those six is the CLASS gate's doing, pinned by\n * detection-fold.test.ts's \"writes ZERO entered lines for six floor-produced environment\n * failures\". The `timeout` RE-DERIVATION of the same event — a run-scoped hang arriving in a\n * floor-eligible class, per WHY A COUNT above — is INFERRED and has never been observed in the\n * field; it is the reason the cap exists, not evidence that the cap caught anything.\n * 2. IT DOES NOT BOUND EVENTUAL ENTRIES. Measured 2026-08-06 at CAP=2 over a SUITE=6 fan-out: six\n * floor-admissible crossings enter 2 / 2 / 2 across three consecutive evaluations and ALL SIX\n * are quarantined by run 3. Each refused member is admitted on the next applied run with no\n * human decision and no new evidence — which is exactly what OVERFLOW IS LOUD says below, so\n * the retracted containment clause contradicted its own docstring a paragraph later.\n * The first two evaluations of that shape now live in the corpus rather than only in a probe:\n * detection-fold.test.ts's \"the floor cap rate-limits a multi-member fan-out (390-28)\" produces\n * CAP + 1 floor admissions in ONE real fold, admits exactly CAP by identity order, and admits\n * the refused member on the very next run.\n *\n * So the purchase is TIME AND VISIBILITY, per run: every crossing this counter refuses is one build\n * in which a human sees the identity in `escalatedNotQuarantined` with the build still red, before\n * anything silences it. That is worth having and it is all of it.\n *\n * WHY 2 SPECIFICALLY, on the half that survives. Strictly above 1, so the mechanism is not a de\n * facto single-shot and two genuinely independent flaky tests can still both land in one run. A run\n * asking to silence three or more tests on the floor's word alone is the shape of FAN-OUT, not of\n * independent flakiness — simultaneity is the signal a shared cause leaves. The number is a\n * per-run BUDGET on that shape, and 2 is where the budget was set; it is not derived from the\n * 6-of-6 observation, which the class gate already refuses.\n *\n * IT SHARES `QUARANTINE_FLAG_FLOOR`'s VALUE BY COINCIDENCE AND IS NOT DERIVED FROM IT. Said\n * explicitly so a later retune of the flag floor cannot silently move this number too. A pinned\n * constant with no config key (386 D-15); retune it here, on its own evidence.\n *\n * OVERFLOW IS LOUD, NEVER DROPPED. Past the cap an identity routes to `escalatedNotQuarantined`\n * with the build still failing — D-05's already-ratified posture for a class-gated refusal, applied\n * to a count-gated one. It crosses again on the next applied run and may be admitted THEN; one that\n * stops failing was never a quarantine candidate. Nothing is lost: the cap slows the floor path\n * down, it does not close it.\n *\n * THE AUTHORED ARM IS EXEMPT, DELIBERATELY. An authored verdict is per-test evidence by\n * construction — a model read THIS test's evidence and named its cause — so it does not carry the\n * hazard this cap defends against, which is a RUN-level signal being read as per-test. Capping it\n * would also silently regress the arm 390-16 shipped, on no measurement. THE HONEST RESIDUAL: an\n * authored run CAN still class many tests identically, so the authored path's fan-out is unchanged\n * by this round — stated, not closed (T-390-19-07, accepted).\n */\nexport const QUARANTINE_FLOOR_AUTO_QUARANTINE_CAP = 2\n\n/**\n * D-10's exit: M consecutive PASSING distinct build ordinals release a quarantined test. Five is\n * symmetric with the detection window by design (~17% escape odds for a 30%-failure flake) and sits\n * inside LAST_OUTCOMES_LIMIT, so no window widening is needed. Retune from operational evidence.\n */\nexport const QUARANTINE_AUTO_EXIT_PASSES = 5\n\n/**\n * D-11's default lifetime in days. On lapse suppression STOPS and the entry stays listed as\n * `expired`.\n *\n * This is a REVIEW CADENCE, not a cap, and the difference is the fact somebody retuning the number\n * most needs: a still-crossing fingerprint re-enters with a fresh `expiryFrom(now)` on the very\n * next fold, indefinitely and with no attenuation. Measured over four full cycles (2026-08-06): 4\n * `entered` lines, 4 distinct deadlines, 0 released, cycle 4 indistinguishable from cycle 1. So\n * raising this number lengthens the gap between red builds; it does not change how many there\n * eventually are. A human deadline in a human-reviewed file; retune from operational evidence,\n * never from config.\n */\nexport const QUARANTINE_DEFAULT_EXPIRY_DAYS = 30\n\n/** What escalation does with a verdict class. */\nexport type QuarantineDisposition = 'auto-quarantine' | 'escalate-only'\n\n/**\n * The class gate, as a TOTAL function over the closed verdict vocabulary (D-05).\n *\n * `satisfies Record<VerdictClass, QuarantineDisposition>` is the load-bearing part: adding a ninth\n * member to VERDICT_CLASSES makes this object a compile error until its quarantine disposition is\n * decided. A `Set` of three names would have compiled forever while silently treating every future\n * class as escalate-only by accident rather than by decision.\n */\nexport const QUARANTINE_CLASS_DISPOSITIONS = {\n flake: 'auto-quarantine',\n environment: 'auto-quarantine',\n timeout: 'auto-quarantine',\n app_bug: 'escalate-only',\n test_bug: 'escalate-only',\n config_error: 'escalate-only',\n llm_error: 'escalate-only',\n unknown: 'escalate-only',\n} as const satisfies Record<VerdictClass, QuarantineDisposition>\n\n/**\n * Exactly `eval-and-core-types.md` §A9's A3 routing, DERIVED from the disposition table rather\n * than spelled a second time (388 C13) — the set and the table can never disagree about a class.\n */\nexport const AUTO_QUARANTINE_CLASSES: readonly VerdictClass[] = VERDICT_CLASSES.filter(\n (name) => QUARANTINE_CLASS_DISPOSITIONS[name] === 'auto-quarantine',\n)\n\n/**\n * Whether the deterministic floor may decide this KIND of failure AT ALL. Never sufficient on\n * its own: since 390-19 the floor arm also requires the crossing's own `sameBuildPassAndFail`,\n * so no class auto-quarantines on the floor's word alone. The pre-390-19 gloss on this line said\n * otherwise and was the same false-reachability shape 390-25 removed from the corpus header.\n */\nexport type QuarantineFloorEligibility = 'floor-eligible' | 'authored-required'\n\n/**\n * The SECOND total table over the same closed vocabulary (390-16, G-390-3).\n *\n * The disposition table above answers \"may this class ever auto-quarantine\". It cannot answer the\n * other question, because the answer is not a property of the class name: is the EVIDENCE behind\n * the class a statement about THIS TEST, or about the run it happened to be in? This table answers\n * that, and it is a table rather than `if (cls === 'environment' || cls === 'timeout')` for exactly\n * the reason D-05 gave for the first one — a rule stated over a subset of its own input domain\n * compiles forever while treating every future class as an accident. A ninth member of\n * VERDICT_CLASSES is a compile error here until someone decides its floor eligibility.\n *\n * This table is ONE OF TWO CONJUNCTS on the floor arm since 390-19. It licenses a CLASS; the\n * crossing's `sameBuildPassAndFail` supplies the per-test EVIDENCE. Neither alone may silence a\n * failing test on the deterministic floor's word.\n *\n * Per class, with the reasoning that decides it:\n *\n * - `timeout` → FLOOR-ELIGIBLE (re-decided by 390-19 / G-390-5, and the row that carries the LIVE\n * floor path). This row used to read authored-required because \"exceeded the budget\" is\n * per-test but semantically THIN — as consistent with an infinite spinner as with flakiness.\n * Thinness is exactly what a same-build pass∧fail cures: a test that passed and failed at the\n * same build ordinal is flaky by direct observation, whatever the budget did. So `timeout` may\n * now be decided on the floor's word PLUS the signature, and NEVER on the floor's word alone.\n * - `environment` → AUTHORED-REQUIRED, on its own merits, unchanged. Two of its three arms are\n * RUN-SCOPED probe reads (`baselineProbe.error !== undefined`, `baselineProbe.status >= 500`)\n * that fire before any per-test signal. One down staging dependency classifies every failing\n * member of a suite identically; the measured blast radius was 6 of 6 tests under one shared\n * 30-day deadline. A flapping dependency produces same-build pass∧fail across MANY tests at\n * once, so the signature does not make a run-scoped observation per-test — read the branch-order\n * paragraph below before treating this row as the containment, because it is not.\n * - `flake` → FLOOR-ELIGIBLE on the class's own merits, AND THIS ROW DECIDES NOTHING. Say it out\n * loud, because G-390-5 exists precisely because a row nobody could reach was described as the\n * mechanism keeping FLAK-01 alive. `classifyRootCause` mints `flake` only inside its\n * `outcome === 'passed' || outcome === 'healed'` arm — the test LITERALLY passed on retry, so\n * the class IS the signature — but a member that passed carries no `failure` row\n * (`projection/run-outcomes.ts`'s `...(passed ? {} : { failure })` spread) and a\n * `QuarantineDetectionFailure` is built only from `test.failure`. So no crossing can carry class\n * `flake` AND producer `deterministic-classifier`: every `flake` crossing the pipeline can build\n * is authored, and is admitted by the FIRST disjunct. `timeout` is the row that is\n * reachable-and-deciding on the floor path; this one is correct and inert.\n * - THE FIVE ESCALATE-ONLY CLASSES → AUTHORED-REQUIRED. They never reach the auto-quarantine\n * branch today, so this value is not observable — which is precisely why it is the strict one.\n * It makes authored-required the DEFAULT for any future widening of the disposition table, so a\n * later one-line class flip cannot silently also license the floor (T-390-16-04).\n *\n * THE BRANCH-ORDER FACT THAT KILLS THE CLASS-BASED CONTAINMENT, measured at HEAD against\n * `classifyRootCause` (`runner/src/run/root-cause.ts`). Its arms run in this order: the presence\n * rule, then the `passed || healed` arm that mints `flake`, then the `outcome === 'timeout'` arm —\n * WHICH RETURNS — and only THEN the `baselineProbe` reads that mint `environment`. So a hung or\n * flapping staging dependency does NOT arrive classed `environment` for the members that blew their\n * deadline: it arrives classed `timeout`, the class this table now licenses. The run-scoped\n * objection stated on the `environment` row above applies VERBATIM to those `timeout` members.\n *\n * DRAW THE CONCLUSION HERE RATHER THAN LEAVING IT TO BE INFERRED: every class the floor can mint on\n * a FAILING member (`timeout`, `environment`, `unknown`) is reachable from a RUN-SCOPED cause, so\n * THIS TABLE CANNOT BE THE CONTAINMENT FOR MASS AUTO-QUARANTINE AND MUST NOT BE READ AS ONE.\n * Keeping `environment` strict contains `environment`; it does not contain the hazard.\n * QUARANTINE_FLOOR_AUTO_QUARANTINE_CAP does — a per-run COUNT, which is the form 390-16's\n * motivating observation (one probe failure, 6 of 6 tests) actually took. A reader who inherits the\n * older framing — that `environment` is THE run-scoped class and `timeout` is the per-test one —\n * will re-derive exactly the defect this round closes: a true-sounding containment sentence about a\n * path the code does not take.\n *\n * WHY NOT flip the disposition table instead. That is wrong in both directions: it would disable\n * auto-quarantine for genuinely ANALYZED environment/timeout failures, and it would leave\n * floor-minted `flake` firing. The consistent rule — the one 390-05 already ratified once when it\n * made `unknown` escalate-only — is that a quarantine decision requires per-test EVIDENCE, and\n * `producer` plus `sameBuildPassAndFail` are what make that rule expressible.\n */\nexport const QUARANTINE_FLOOR_ELIGIBILITY = {\n flake: 'floor-eligible',\n environment: 'authored-required',\n timeout: 'floor-eligible',\n app_bug: 'authored-required',\n test_bug: 'authored-required',\n config_error: 'authored-required',\n llm_error: 'authored-required',\n unknown: 'authored-required',\n} as const satisfies Record<VerdictClass, QuarantineFloorEligibility>\n\n/**\n * WHICH ARM of the gate admitted a crossing, or that none did (390-19). A boolean was exactly the\n * information the per-run floor cap needs and cannot get: the cap counts FLOOR admissions and\n * exempts AUTHORED ones, so the ladder has to be able to tell them apart.\n */\ntype QuarantineAdmission = 'authored' | 'floor' | 'refused'\n\n/**\n * Whether a crossing may author an `entered` line, and — since 390-19 — WHICH ARM admitted it.\n *\n * The disposition must be auto-quarantine, and then EITHER this crossing's verdict was AUTHORED,\n * OR the class is floor-eligible AND the crossing carries the per-test flake signature. Everything\n * else routes to `escalatedNotQuarantined` — loud, rendered, build still failing.\n *\n * TWO CONJUNCTS ON THE FLOOR ARM, DELIBERATELY, and each refuses something the other admits:\n *\n * - The CLASS conjunct alone admits a floor-produced `timeout` from a run-scoped hang with no\n * per-test evidence behind it at all. That is 390-16's shape, and it is what the signature\n * refuses.\n * - The SIGNATURE conjunct alone admits a floor-produced `environment` — a class whose evidence is\n * a health probe, where a flapping dependency stamps the same-build pass∧fail across many tests\n * at once. That is what the class conjunct refuses.\n */\nfunction autoQuarantines(failure: QuarantineDetectionFailure): QuarantineAdmission {\n if (QUARANTINE_CLASS_DISPOSITIONS[failure.verdictClass] !== 'auto-quarantine') return 'refused'\n if (failure.producer === 'analyze-run') return 'authored'\n return QUARANTINE_FLOOR_ELIGIBILITY[failure.verdictClass] === 'floor-eligible'\n && failure.sameBuildPassAndFail\n ? 'floor'\n : 'refused'\n}\n\n/**\n * One failed fingerprint this run contributed, with the recurrence the projection answered for it.\n * Test identity travels beside the fingerprint because a crossing has to name the test it\n * quarantines; the recurrence itself is keyed `(product, fingerprint)` (D-07).\n */\nexport interface QuarantineDetectionFailure {\n product: string\n filePath: string\n testName: string\n fingerprint: string\n verdictClass: VerdictClass\n /**\n * WHICH pipeline authored `verdictClass` on the CROSSING run (390-16). The floor-eligibility\n * gate reads this beside the class, because for some classes the class alone does not say\n * whether the evidence is about this test or about the whole run.\n *\n * WHY THE CROSSING RUN'S PRODUCER, and not all three occurrence ordinals'. Gating on every\n * ordinal in the window would need a new `producer` column on `run_fingerprint_windows` plus an\n * index rebuild — cheap in itself, since L12 makes the projection a gitignored rebuildable\n * derivation — but it is a strictly larger change that buys nothing: the crossing run is the one\n * AUTHORING the `entered` line, so its evidence is the evidence the entry rests on. Recorded\n * here so the next reader does not have to re-derive the choice (T-390-16-05, accepted).\n */\n producer: Verdict['producer']\n /**\n * THE PER-TEST FLAKE SIGNATURE for this crossing (390-19 / G-390-5): did this test both pass and\n * not pass at some ONE build ordinal? Computed by `hasSameBuildPassAndFail` over the per-test\n * outcome window the projection already keeps (`run_test_outcomes`.`last_outcomes_json`), so it\n * is read off bytes this phase computes rather than invented for the gate.\n *\n * REQUIRED, not optional, on purpose: `tsc --noEmit` then enumerates every construction site,\n * which is the completeness oracle 390-16 did not have and the reason its widening shipped with\n * an unreachable arm.\n *\n * ITS THREE HONEST BOUNDS, so nobody reads a set field as a stronger claim than it is:\n *\n * 1. The window is CAPPED at LAST_OUTCOMES_LIMIT entries, so this is \"a same-build pass∧fail\n * within the recorded window\", never \"ever\".\n * 2. IT IS CONTEMPORANEOUS, and that bound is ENFORCED, not advisory (390-24, WR-05). The fold\n * hands this predicate only the outcomes inside `[windowFloor(buildOrdinal), buildOrdinal]`\n * — the crossing's OWN recurrence window, same floor `fingerprintRecurrence` counts over —\n * so a same-build pass∧fail OLDER than that window answers false by construction. A\n * since-fixed flake episode therefore cannot license the floor arm for a new hard\n * regression. The scope lives at the construction site (`run-outcomes.ts`), named below.\n * 3. WHAT IT TAKES TO PRODUCE ONE IN THE REAL WORLD — this is not a common event. An in-run\n * RETRY does NOT produce it: the member-runner collapses retries into a single member\n * outcome and `countedOutcome` maps `healed` to a PASS, so one applied run leaves exactly\n * ONE entry per member. Two entries at one ordinal therefore require TWO SEPARATE APPLIED\n * RUNS carrying the same `handoff.buildOrdinal` — in practice a CI job re-run without an\n * ordinal bump. Every claim in this phase that the floor path is \"live without an analysis\n * budget\" is true only under that condition, and this phase has already overstated\n * reachability three times.\n */\n sameBuildPassAndFail: boolean\n /** DISTINCT build ordinals inside the window carrying this fingerprint. */\n occurrenceOrdinals: number\n /** DISTINCT build ordinals inside the window carrying ANY failure — the honest denominator. */\n windowOrdinals: number\n}\n\n/** One recorded outcome, ordinal-keyed. Mirrors the projection's per-test outcome window entry. */\nexport interface QuarantineOrdinalOutcome {\n buildOrdinal: number\n passed: boolean\n}\n\n/** One quarantined test's recent outcome window — the auto-exit's only input. */\nexport interface QuarantineDetectionTestWindow {\n product: string\n filePath: string\n testName: string\n /** May carry several entries per ordinal (two runs in one build); order is irrelevant. */\n ordinals: readonly QuarantineOrdinalOutcome[]\n}\n\nexport interface EvaluateQuarantineDetectionInput {\n failures: readonly QuarantineDetectionFailure[]\n testWindows: readonly QuarantineDetectionTestWindow[]\n /** The ledger folded against this same `now` — the suppression and exit input. */\n entries: readonly QuarantineEntryState[]\n /** ISO-8601 instant. The ONLY way wall clock enters this rule. */\n now: string\n}\n\n/** A crossing the caller must SHOW: flagged, or escalated-and-deliberately-not-quarantined. */\nexport interface QuarantineDetectionSighting {\n product: string\n filePath: string\n testName: string\n fingerprint: string\n verdictClass: VerdictClass\n /**\n * The crossing run's producer, carried onto the sighting so an operator can ACT on it — and\n * RENDERED on the curation tail's withheld line since 390-22 / WR-03. Until then this docstring\n * claimed the field existed so an operator could tell two causes apart on that line, and the\n * field never reached the line: the claim was true of the shape and false of the operator. It is\n * reduced here to what the render delivers.\n *\n * `escalatedNotQuarantined` has THREE distinct causes, and the producer separates the first two:\n * a class that is never auto-quarantinable (run `analyze-run` and it still will not be), versus a\n * class that would have been had a verdict been authored (run `analyze-run` and it will be).\n * Those read identically on the curation tail's line unless the producer travels with the\n * sighting.\n *\n * THE THIRD CAUSE, ADDED BY 390-19, AND THE FACT THAT THIS FIELD DOES NOT DISTINGUISH IT: the\n * crossing was admissible on the floor arm but QUARANTINE_FLOOR_AUTO_QUARANTINE_CAP was already\n * spent on this run. The information gap is bounded — an operator sees the withheld line either\n * way, the build fails either way, and the identity crosses again on the next applied run — so no\n * field is added to carry it, which would widen this shape and the cli render inside the very\n * round that is closing a containment defect. Recorded as a STATED RESIDUAL instead, because a\n * docstring that enumerates causes and misses one is the defect class this whole round closes.\n */\n producer: Verdict['producer']\n occurrenceOrdinals: number\n windowOrdinals: number\n}\n\nexport interface QuarantineDetectionResult {\n /** Lifecycle events to append, entered-then-released, each group identity-sorted. */\n events: QuarantineLedgerEvent[]\n /** At the flag floor: suspected flaky, no state change, no ledger write (D-06). */\n flagged: QuarantineDetectionSighting[]\n /** Escalated but class-gated away from auto-quarantine — the build keeps failing (D-05). */\n escalatedNotQuarantined: QuarantineDetectionSighting[]\n}\n\nconst MS_PER_DAY = 86_400_000\n\n/**\n * The subsystem's ONE ordering rule: a TOTAL order over the identity key, by CODE UNIT.\n *\n * `<` on two strings compares UTF-16 code units. That is a total order over distinct strings — it\n * answers 0 only for equal keys — and it is a property of the STRINGS, not of the machine. Both\n * halves matter, and `String.prototype.localeCompare` (which this replaced) has neither:\n *\n * - it resolves against the host's default locale and ICU build, so two checkouts of one commit\n * could order the same ledger differently;\n * - it answers 0 for canonically-equivalent-but-distinct names (an NFC/NFD pair), and\n * `Array.prototype.sort` is stable, so a 0 hands the ordering decision back to the caller's\n * iteration order — which is exactly the dependency `evaluateQuarantineDetection` denies.\n *\n * Every ordering site in the subsystem routes through here: both sorts in the detection ladder and\n * the identity tiebreak in `operations.ts`'s `triageOrder`, which already compared bytes and is\n * where this spelling was lifted from.\n */\nexport function compareQuarantineIdentity(\n left: QuarantineIdentity,\n right: QuarantineIdentity,\n): number {\n return compareBytes(quarantineIdentityKey(left), quarantineIdentityKey(right))\n}\n\n/**\n * Code-unit comparison. MODULE-PRIVATE, and the visibility is the honest claim (390-28 / IN-01).\n *\n * It was exported \"so no ordering site in the subsystem has to re-spell it\" and had no consumer at\n * all — not `operations.ts`, not `detection.test.ts`, not the package barrel, which never published\n * it. An export that names consumers it does not have invites the next reader to preserve a\n * compatibility surface nothing depends on. Its TWO REAL CALL SITES are both in this file:\n * {@link compareQuarantineIdentity}, which compares the identity key with it, and the fingerprint\n * tiebreak in {@link evaluateQuarantineDetection}'s failure sort. Ordering sites OUTSIDE this\n * module reach the same primitive through `compareQuarantineIdentity`, which is exported.\n *\n * Both call sites want it for one reason: a comparison chain is only as deterministic as its least\n * deterministic leg, so leaving one `localeCompare` in the chain would reproduce WR-06 on a\n * narrower input class.\n */\nfunction compareBytes(left: string, right: string): number {\n if (left === right) return 0\n return left < right ? -1 : 1\n}\n\nfunction sighting(failure: QuarantineDetectionFailure): QuarantineDetectionSighting {\n return {\n product: failure.product,\n filePath: failure.filePath,\n testName: failure.testName,\n fingerprint: failure.fingerprint,\n verdictClass: failure.verdictClass,\n producer: failure.producer,\n occurrenceOrdinals: failure.occurrenceOrdinals,\n windowOrdinals: failure.windowOrdinals,\n }\n}\n\n/**\n * The deadline an auto-entry is licensed for. Derived from the SUPPLIED instant — `Date.parse` of a\n * caller's argument is arithmetic, not a clock read. An unparseable `now` is a caller bug, so it\n * surfaces as a thrown RangeError from `toISOString` rather than silently minting a forever entry.\n */\nfunction expiryFrom(now: string): string {\n return new Date(Date.parse(now) + QUARANTINE_DEFAULT_EXPIRY_DAYS * MS_PER_DAY).toISOString()\n}\n\n/**\n * D-07's counting law — \"two runs in one build are ONE ordinal\" — spelled ONCE, for every reader of\n * it (390-19).\n *\n * Both directions of that law now have a consumer: the EXIT path asks whether an ordinal passed,\n * and the ENTRY path asks whether an ordinal disagreed with itself. Answering per ordinal whether\n * ANY entry passed and whether ANY entry did not is strictly RICHER than the boolean AND-fold the\n * exit path used to compute inline, and it has to be: under the AND-fold an ordinal carrying a pass\n * and a fail is indistinguishable from an ordinal carrying only fails — which is exactly the\n * distinction the flake signature is about.\n *\n * Shared IN CODE rather than pinned by a test on purpose. Two implementations that agree only\n * because a fixture compares them are free to drift the moment somebody edits one, and the entry\n * path and the exit path disagreeing about what a build ordinal IS would be a silent defect in\n * both directions at once (T-390-19-04).\n *\n * Groups are non-empty by construction — a group exists only because an entry created it — so\n * `anyPassed || anyFailed` holds for every returned element.\n */\nfunction groupByBuildOrdinal(\n ordinals: readonly QuarantineOrdinalOutcome[],\n): { buildOrdinal: number; anyPassed: boolean; anyFailed: boolean }[] {\n const byOrdinal = new Map<number, { anyPassed: boolean; anyFailed: boolean }>()\n for (const entry of ordinals) {\n const seen = byOrdinal.get(entry.buildOrdinal) ?? { anyPassed: false, anyFailed: false }\n if (entry.passed) seen.anyPassed = true\n else seen.anyFailed = true\n byOrdinal.set(entry.buildOrdinal, seen)\n }\n return [...byOrdinal.entries()]\n .map(([buildOrdinal, seen]) => ({ buildOrdinal, ...seen }))\n .sort((a, b) => a.buildOrdinal - b.buildOrdinal)\n}\n\n/**\n * Collapse a per-test outcome window onto DISTINCT ordinals. An ordinal counts as passing only when\n * EVERY recorded run at that ordinal passed — two runs in one build are one ordinal (D-07's counting\n * law), and the safe direction for a mixed build is \"not a pass\", so a same-build pass∧fail (the\n * §8.2 flake signature itself) can never buy an exit.\n *\n * Expressed over `groupByBuildOrdinal` since 390-19: \"no entry at this ordinal failed\" is the same\n * answer the old AND-fold gave for every non-empty group, and every group is non-empty by\n * construction. The stated law and this function's signature are unchanged.\n */\nfunction distinctOrdinalOutcomes(\n window: QuarantineDetectionTestWindow,\n): { buildOrdinal: number; passed: boolean }[] {\n return groupByBuildOrdinal(window.ordinals)\n .map(({ buildOrdinal, anyFailed }) => ({ buildOrdinal, passed: !anyFailed }))\n}\n\n/**\n * THE PER-TEST FLAKE SIGNATURE (390-19 / G-390-5): at some ONE build ordinal this test both passed\n * and did not pass.\n *\n * This is the same shape `distinctOrdinalOutcomes` names above as \"the §8.2 flake signature\n * itself\", read here in the opposite direction — there it is the reason an ordinal cannot buy an\n * EXIT, here it is the per-test evidence the floor arm of the auto-quarantine gate requires before\n * it may silence anything. Both read `groupByBuildOrdinal`, so the counting law has ONE spelling in\n * code and not two that a test happens to compare.\n *\n * WHY THIS IS THE RIGHT PER-TEST SIGNAL, in the module's own vocabulary. The floor-eligibility\n * table below asks one question: is the EVIDENCE behind a class a statement about THIS TEST, or\n * about the run it happened to be in? A same-build pass∧fail is a statement about this test and\n * nothing else — at one build ordinal the same test both passed and failed, which no run-level\n * condition explains away.\n *\n * Deliberately NOT \"some pass and some fail anywhere in the window\": that is a test that broke and\n * was fixed, which is the ordinary shape of software rather than flakiness.\n *\n * TWO SITES, ONE RULE — WHO OWNS THE SCOPE (390-24). This function stays TOTAL over whatever\n * window it is handed and deliberately holds no opinion about how far back that window reaches.\n * The FOLD owns the scope: `evaluateQuarantineForFold` in `projection/run-outcomes.ts` filters the\n * per-test outcomes to `[windowFloor(buildOrdinal), buildOrdinal]` before calling here, so the\n * evidence licensing an entry is always about the SAME episode the recurrence counted. Narrowing\n * or widening one site without the other is the WR-05 defect returning: this predicate would still\n * be green over windows the fold no longer hands it.\n */\nexport function hasSameBuildPassAndFail(\n ordinals: readonly QuarantineOrdinalOutcome[],\n): boolean {\n return groupByBuildOrdinal(ordinals).some((entry) => entry.anyPassed && entry.anyFailed)\n}\n\n/** D-10's exit predicate: the M most recent DISTINCT ordinals exist and every one of them passed. */\nfunction releasesOnPasses(window: QuarantineDetectionTestWindow): boolean {\n const ordinals = distinctOrdinalOutcomes(window)\n if (ordinals.length < QUARANTINE_AUTO_EXIT_PASSES) return false\n return ordinals\n .slice(-QUARANTINE_AUTO_EXIT_PASSES)\n .every((entry) => entry.passed)\n}\n\n/**\n * WHOSE NAME an auto-authored `entered` event carries, stated over the prior entry's state\n * (390-18 / G-390-4). The rule is total across the three members of `QuarantineEntryStateName`:\n *\n * - `'expired'` → CARRY the prior owner. A lapsed window is the SAME window continuing:\n * suppression stopped, nobody closed it, and the person who claimed it still holds it.\n * Re-stamping the unassigned literal here silently UN-CLAIMS a window somebody had taken.\n * - `'released'` → the UNASSIGNED literal. A release is a human deliberately closing the window;\n * a later crossing opens a genuinely new one, and D-12's honest-absence rule (no git-identity\n * stamping, no CODEOWNERS guessing) says the truthful answer for it is that nobody has claimed\n * it yet. Carrying a name here would attribute a new window to somebody who signed off on the\n * old one.\n * - `'quarantined'` → UNREACHABLE on this path, not silently absent. The ladder skips an\n * already-suppressed identity (`activeKeys`, above) before it ever reaches the authoring\n * branch, so there is no owner decision to make for a suppressing entry. Pinned as unreachable\n * in detection.test.ts rather than left to be re-derived.\n *\n * No prior entry at all → the unassigned literal, unchanged.\n *\n * TWO AUTHORING PATHS, ONE RULE ABOUT SOMEBODY'S CLAIM. `createQuarantineOperations`'s RENEW arm\n * (operations.ts) makes the same decision from the other direction: it OMITS `owner` from the\n * `renewed` event when the caller named nobody, with a comment saying that writing the unassigned\n * literal there would silently un-claim a window somebody had taken. That is the identical rule\n * over an open window; this is it over a re-entry. Naming the sibling here is cheaper than a test\n * asserting the two agree — but it only works if a reader who changes one comes looking, so the\n * cross-reference is deliberately in BOTH.\n */\nfunction ownerForAutoEntry(prior: QuarantineEntryState | undefined): QuarantineOwner {\n if (prior === undefined) return QUARANTINE_UNASSIGNED_OWNER\n switch (prior.state) {\n case 'expired':\n return prior.owner\n case 'released':\n case 'quarantined':\n return QUARANTINE_UNASSIGNED_OWNER\n }\n}\n\n/**\n * The ladder, evaluated over one run's failures and the current ledger state.\n *\n * ORDERING IS DETERMINISTIC ON ANY HOST — entered events (identity-sorted) then released-auto\n * events (identity-sorted) — so the committed ledger's bytes are a function of ledger CONTENT and\n * not of projection iteration order. What makes that true rather than merely stated is\n * {@link compareQuarantineIdentity}: a TOTAL order over {@link quarantineIdentityKey} by code\n * unit. Total is the load-bearing word. A comparator that answers 0 for two DISTINCT identities\n * hands the decision back to the caller's iteration order, because `Array.prototype.sort` is\n * stable — so a zero here would falsify this paragraph directly. Code units also make the answer a\n * property of the strings rather than of the machine's locale and ICU build.\n *\n * Both sorts below and `operations.ts`'s `triageOrder` share that one comparator; the fingerprint\n * tiebreak uses the same `compareBytes` primitive. There is one ordering rule in this subsystem and\n * it is spelled once (390-22 / WR-06).\n *\n * Suppression is keyed on ledger STATE, not on the existence of an entry: only `'quarantined'`\n * suppresses a fresh `entered`. An `'expired'` entry has already stopped suppressing (D-11) and a\n * `'released'` one closed its window, so a fresh crossing re-enters in both cases — D-10's stated\n * \"re-entry needs no special rule\". The repeated `entered` lines are the ledger's own record that\n * this test has been here before, which is exactly the history D-03 chose an event log to keep.\n */\nexport function evaluateQuarantineDetection(\n input: EvaluateQuarantineDetectionInput,\n): QuarantineDetectionResult {\n const activeKeys = new Set(\n input.entries\n .filter((entry) => entry.state === 'quarantined')\n .map((entry) => quarantineIdentityKey(entry)),\n )\n // A SECOND lookup, over ALL entries. `activeKeys` deliberately holds only the suppressing ones,\n // and a re-entry by definition has none — so the set that answers \"is this test already\n // quarantined\" cannot also answer \"did somebody claim this test's last window\".\n const priorByKey = new Map(\n input.entries.map((entry) => [quarantineIdentityKey(entry), entry] as const),\n )\n\n const flagged: QuarantineDetectionSighting[] = []\n const escalatedNotQuarantined: QuarantineDetectionSighting[] = []\n const entered: QuarantineLedgerEvent[] = []\n const expiresAt = expiryFrom(input.now)\n // PER CALL, and a call is one run's fold — which is what makes the cap PER RUN. Declaring it in\n // module scope instead would satisfy every single-evaluation assertion in the corpus while\n // silently turning this into a PROCESS-LIFETIME cap, under which the third genuine flake in a\n // project is never auto-quarantined again for the life of the daemon. The two-call drain leg in\n // detection.test.ts is the discriminator that reds if this declaration ever moves.\n let floorAdmissions = 0\n\n for (const failure of [...input.failures].sort(\n // ONE ordering rule (390-22 / WR-06). Both legs compare CODE UNITS — the identity key through\n // the shared comparator, the fingerprint tiebreak through the same primitive — because a\n // comparison chain is only as deterministic as its least deterministic leg.\n (a, b) => compareQuarantineIdentity(a, b) || compareBytes(a.fingerprint, b.fingerprint),\n )) {\n // An already-suppressed test needs neither a flag nor an escalation: it is already quarantined,\n // which is louder than either. Checked before the ladder so the whole rung is a no-op.\n if (activeKeys.has(quarantineIdentityKey(failure))) continue\n\n if (failure.occurrenceOrdinals >= QUARANTINE_ESCALATE_THRESHOLD) {\n const admission = autoQuarantines(failure)\n // The cap counts FLOOR admissions only. Beyond it a floor-admissible crossing routes to\n // `escalatedNotQuarantined` exactly as a class-refused one does: build still failing,\n // identity visible, admitted on a later evaluation once the earlier ones are suppressing.\n const capped = admission === 'floor'\n && floorAdmissions >= QUARANTINE_FLOOR_AUTO_QUARANTINE_CAP\n if (admission !== 'refused' && !capped) {\n if (admission === 'floor') floorAdmissions += 1\n entered.push({\n schemaVersion: CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n kind: 'entered',\n at: input.now,\n product: failure.product,\n filePath: failure.filePath,\n testName: failure.testName,\n fingerprint: failure.fingerprint,\n verdictClass: failure.verdictClass,\n owner: ownerForAutoEntry(priorByKey.get(quarantineIdentityKey(failure))),\n expiresAt,\n })\n } else {\n escalatedNotQuarantined.push(sighting(failure))\n }\n continue\n }\n if (failure.occurrenceOrdinals >= QUARANTINE_FLAG_FLOOR) flagged.push(sighting(failure))\n }\n\n const windowsByKey = new Map(\n input.testWindows.map((window) => [quarantineIdentityKey(window), window] as const),\n )\n const released: QuarantineLedgerEvent[] = []\n for (const entry of [...input.entries].sort(compareQuarantineIdentity)) {\n // Release closes an entry that is still LISTED — `quarantined` or `expired`. Only a `released`\n // window is out of scope, and the old filter's justification was right about exactly that half:\n // re-releasing a closed window WOULD author an event that changes nothing while claiming the\n // exit path worked. It was wrong about the other half. A LAPSED entry is still listed, still\n // renewable, still in the triage queue and still the reason a human sees this test in\n // `quarantine.list` — a release genuinely closes it, so refusing to author one is what left a\n // FIXED test listed forever (390-17 / G-390-4). One condition was covering two states whose\n // answers differ.\n //\n // TWO SITES, ONE RULE. `evaluateQuarantineForFold` (projection/run-outcomes.ts) builds the\n // `testWindows` this loop reads, and its own exit-candidate filter must admit exactly the same\n // states. Narrow either one alone and the pair is a no-op: this loop would answer correctly\n // over a window the fold never built.\n if (entry.state === 'released') continue\n const window = windowsByKey.get(quarantineIdentityKey(entry))\n if (window === undefined || !releasesOnPasses(window)) continue\n released.push({\n schemaVersion: CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n kind: 'released-auto',\n at: input.now,\n product: entry.product,\n filePath: entry.filePath,\n testName: entry.testName,\n })\n }\n\n return { events: [...entered, ...released], flagged, escalatedNotQuarantined }\n}\n","/**\n * PROVISIONAL last-N window for per-test outcome history (~10 pending ABRF-02 ranking\n * measurements). Entries are {buildOrdinal, passed} — ordinals only, wall-clock never.\n * Shared by readers and writers without pulling writer authority into the read closure.\n */\nexport const LAST_OUTCOMES_LIMIT = 10\n","/**\n * Read side of the fingerprint-keyed recurrence window (Phase 390, D-07).\n *\n * `run_fingerprint_windows` is written by `applyRunOutcomes`; this module is the one place that\n * queries it. Strictly read-only: prepared SELECTs, no statement that mutates a row, ever — the\n * writer half stays whole in `run-outcomes.ts`, exactly as `run-outcome-read.ts` does for the\n * per-test counters it is the sibling of.\n *\n * KEY LAW — a window row is addressed by `(product, fingerprint)`. Stable test identity\n * `(product, filePath, testName)` travels ON the row because a crossing has to name the test it\n * quarantines, but it is never part of the recurrence key: one fingerprint may be exercised by\n * several tests, and D-07's rule is about the FAILURE recurring, not the test.\n *\n * THE WINDOW SLIDES OVER ORDINALS, NOT RUNS (D-07). Recurrence is counted over the ordinal range\n * `[current - QUARANTINE_WINDOW_ORDINALS + 1, current]`:\n *\n * - two failing runs inside ONE build ordinal count once (the numerator counts DISTINCT ordinals),\n * - a failure at ordinals 5/7/9 still crosses at 9 even though no two runs were consecutive,\n * - and an occurrence that has slid out of the range is FORGIVEN. That is the whole point of a\n * window: the lifetime `flake_count` never forgives, which is exactly why D-07 demoted it to a\n * ranking input and made this the trigger substrate instead.\n *\n * `windowOrdinals` is the honest denominator: how many distinct ordinals in the range this product\n * recorded a failure in at all. A caller renders \"3rd occurrence in 5 builds\" from the pair, and an\n * empty window answers typed zeros rather than an absence a renderer has to guess about.\n *\n * PRECONDITION — the caller supplies a connection where `ensureRunOutcomeTables` has run (every\n * `openIndexWriter` does). A read-only connection against a store predating these tables raises\n * sqlite's `no such table`, which the composition layer folds to typed absence the same way it\n * already does for `readTestOutcomeHistory`.\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport type { VerdictClass } from '@vostride/agent-qa-schema'\n\nimport { LAST_OUTCOMES_LIMIT } from './run-outcome-constants.js'\n\n/**\n * §7.3's locked detection window, verbatim: the same fingerprint recurring within the last five\n * build ordinals. A pinned constant with no config key (386 D-15) — retune it from operational\n * evidence, in the source, where the change is reviewable. Plan 05's rule reads the threshold\n * against this window; D-10's auto-exit is symmetric with it by design.\n */\nexport const QUARANTINE_WINDOW_ORDINALS = 5\n\n/** The recurrence key: the failure, inside one product partition. */\nexport interface FingerprintWindowIdentity {\n product: string\n fingerprint: string\n}\n\n/** One window row, as the writer stored it. */\nexport interface FingerprintWindowRow {\n product: string\n filePath: string\n testName: string\n fingerprint: string\n verdictClass: VerdictClass\n buildOrdinal: number\n runId: string\n}\n\nexport interface FingerprintRecurrence {\n /** DISTINCT build ordinals inside the window carrying this fingerprint. */\n occurrenceOrdinals: number\n /** DISTINCT build ordinals inside the window carrying ANY failure for this product. */\n windowOrdinals: number\n}\n\n/**\n * Inclusive lower bound of the ordinal window ending at `currentBuildOrdinal`.\n *\n * ONE SPELLING, TWO CONSUMERS (390-24). `fingerprintRecurrence` below bounds its SQL range with\n * it, and `run-outcomes.ts` bounds the per-crossing flake-signature read with it — the scope of\n * the evidence and the scope of the count are the same window BY CONSTRUCTION, not by two sites\n * agreeing. Exported for that second consumer; re-deriving\n * `buildOrdinal - QUARANTINE_WINDOW_ORDINALS + 1` anywhere else re-opens the drift.\n */\nexport function windowFloor(currentBuildOrdinal: number): number {\n return currentBuildOrdinal - QUARANTINE_WINDOW_ORDINALS + 1\n}\n\n/**\n * Every stored row for one fingerprint inside the bounded read scope, ordinal-ascending.\n *\n * The read scope is the last {@link LAST_OUTCOMES_LIMIT} ordinals rather than the detection window,\n * so a caller that wants to SHOW the recent history (D-10's M-consecutive-passes exit, the list\n * verb) sees the same depth the per-test outcome window carries. An identity the projection never\n * recorded answers `[]` — typed absence, never a stand-in row.\n */\nexport function readFingerprintWindow(\n db: DatabaseSync,\n identity: FingerprintWindowIdentity,\n currentBuildOrdinal: number,\n): FingerprintWindowRow[] {\n const rows = db.prepare(`\n SELECT product, file_path, test_name, fingerprint, verdict_class, build_ordinal, run_id\n FROM run_fingerprint_windows\n WHERE product = ?\n AND fingerprint = ?\n AND build_ordinal <= ?\n AND build_ordinal > ?\n ORDER BY build_ordinal, run_id, file_path, test_name\n `).all(\n identity.product,\n identity.fingerprint,\n currentBuildOrdinal,\n currentBuildOrdinal - LAST_OUTCOMES_LIMIT,\n ) as unknown as {\n product: string\n file_path: string\n test_name: string\n fingerprint: string\n verdict_class: string\n build_ordinal: number\n run_id: string\n }[]\n\n return rows.map((row) => ({\n product: String(row.product),\n filePath: String(row.file_path),\n testName: String(row.test_name),\n fingerprint: String(row.fingerprint),\n verdictClass: String(row.verdict_class) as VerdictClass,\n buildOrdinal: Number(row.build_ordinal),\n runId: String(row.run_id),\n }))\n}\n\n/**\n * One fingerprint's recurrence over the sliding ordinal window (D-07) — computed LIVE on every\n * call, never stored. Both legs count DISTINCT ordinals, which is what makes two failing runs in\n * one build one occurrence.\n */\nexport function fingerprintRecurrence(\n db: DatabaseSync,\n identity: FingerprintWindowIdentity,\n currentBuildOrdinal: number,\n): FingerprintRecurrence {\n const floor = windowFloor(currentBuildOrdinal)\n const occurrences = db.prepare(`\n SELECT COUNT(DISTINCT build_ordinal) AS ordinals\n FROM run_fingerprint_windows\n WHERE product = ?\n AND fingerprint = ?\n AND build_ordinal >= ?\n AND build_ordinal <= ?\n `).get(identity.product, identity.fingerprint, floor, currentBuildOrdinal) as\n | { ordinals: number }\n | undefined\n const observed = db.prepare(`\n SELECT COUNT(DISTINCT build_ordinal) AS ordinals\n FROM run_fingerprint_windows\n WHERE product = ?\n AND build_ordinal >= ?\n AND build_ordinal <= ?\n `).get(identity.product, floor, currentBuildOrdinal) as { ordinals: number } | undefined\n\n return {\n occurrenceOrdinals: Number(occurrences?.ordinals ?? 0),\n windowOrdinals: Number(observed?.ordinals ?? 0),\n }\n}\n","// The three quarantine verbs, over the committed ledger (Phase 390, D-11/D-12/D-13).\n//\n// `QuarantineOperationsPort` is declared in schema and bound at `composeLocalAgent`; this module is\n// its ONE implementation, and it owns exactly the three things the port contract deliberately does\n// not: the D-12 triage-queue ordering, the pinned default lifetime an absent deadline takes, and\n// the instant every event is stamped with. All three are host facts, and a port that accepted them\n// as arguments would let a caller decide them.\n//\n// WALL-CLOCK PURITY BY ARGUMENT. `now` is REQUIRED, not defaulted: this module reads no clock at\n// all (asserted by a source scan in its suite), which is 390-01's ledger posture extended to the\n// serving layer exactly as 390-03 extended it to the authoring reader. Each verb reads the injected\n// clock ONCE and threads that one instant through the fold, the event stamps and the derived\n// deadline — two reads inside one call could land either side of a deadline and answer a state the\n// caller never asked about.\n//\n// COMMITTED-TRUTH READ POSTURE. Every verb folds the ledger before it decides anything, and a\n// ledger this build cannot read PROPAGATES its typed error rather than degrading to an empty fold.\n// Healing there would answer \"nothing is quarantined\" about a file full of entries — silently\n// un-quarantining every one of them, which is the exact silent flip this phase exists to prevent.\n//\n// WRITES ARE ALL-OR-NOTHING. Every append goes through `appendQuarantineEvents`, whose shape and\n// version check runs before a byte reaches the file. The text is written as handed over; no\n// detector scans it (Phase 441, D-15).\n//\n// SERIALIZATION IS THIS MODULE'S, and it is taken here rather than assumed about a caller. `release`\n// and `add` run their WHOLE read-fold-decide-append cycle inside the MRSW writer lease — acquired\n// here, released here, on every exit — or inside the authority a host that already holds the lease\n// hands in (`resolveWriterAuthority`; the daemon acquires at startup and would otherwise be told\n// `held` by itself). That handed-in authority is CHECKED, not believed (390-15): both write verbs\n// re-read the monotonic epoch and the lease file before deciding anything, and a process whose\n// lease was reclaimed under it — the heartbeat-starved daemon — is refused with the lease module's\n// own `WriterAuthorityLostError`, ledger byte-unchanged. WITH ITS BOUNDARY (390-22 / WR-07): that\n// check runs inside NO lock, unlike the lease module's own `withCurrentWriterAuthority`, so it\n// proves the authority was current at the moment of the check rather than for the duration of the\n// decide that follows. The window is one synchronous `decide` instead of forever; it is not zero.\n// See `lease/under-writer-lease.ts` for the residual in full. Riding an unfenced authority is how a\n// reclaimed writer kept appending beside its reclaimer, which the two-OS-process harness measured\n// as two `entered` lines for one identity. Serializing only the append would leave the other half\n// of the interesting race intact: two writers folding a ledger with no entry for a test would both\n// decide `entered` and both append, so the DECISION is inside the scope and there is no await\n// point between the read and the write.\n// `list` acquires nothing — a reader that took the lease would queue every enumeration behind\n// whatever drain is running.\n//\n// This replaces a claim that serialization was the caller's, \"positionally\". It was false, and\n// statically so (390-09 / CR-03): nothing on the path from `invokeFunction('quarantine.add')` to\n// `appendQuarantineEvents` held a lease. The two-OS-process byte-interleaving consequence is a\n// separately filed human-verification item; what is enforced and pinned here is that a lease held\n// by another writer refuses this verb typed, with the ledger byte-unchanged.\n//\n// THE IDENTITY IS MINTED HERE, AT THE BOUNDARY, ON BOTH NORMALIZED LEGS (390-12 / D-01). The\n// ledger is keyed on `(product, filePath, testName)` and every reader compares those bytes with\n// `===`, so a verb that stores the spelling a human typed writes into a partition nothing reads.\n// `product` is slugged and `filePath` is minted through the host-supplied\n// `workspaceRelativeIdentityPath` (see `mintIdentityPath`); `testName` is stored raw, because it\n// is the one leg no reader transforms. An input that cannot mint is refused TYPED before a lease\n// is taken or a byte is read — see `QuarantineIdentityRefusedError`, and see its division of labour\n// with the ledger's own structural write guard.\n\nimport {\n CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n QUARANTINE_UNASSIGNED_OWNER,\n slugBranch,\n} from '@vostride/agent-qa-schema'\nimport type {\n QuarantineAddInput,\n QuarantineAddOutput,\n QuarantineEntryState,\n QuarantineLedgerEvent,\n QuarantineOperationsPort,\n QuarantineReleaseInput,\n QuarantineReleaseOutput,\n VerdictClass,\n} from '@vostride/agent-qa-schema'\n\nimport { underKnowledgeWriterLease } from '../lease/under-writer-lease.js'\nimport type { SynchronousDecision } from '../lease/under-writer-lease.js'\nimport type { WriterLease } from '../lease/writer-lease.js'\nimport { QUARANTINE_DEFAULT_EXPIRY_DAYS, compareQuarantineIdentity } from './detection.js'\nimport { quarantineIdentityKey } from './identity.js'\nimport {\n appendQuarantineEvents,\n foldQuarantineLedgerState,\n readQuarantineLedger,\n} from './ledger.js'\n\nconst MS_PER_DAY = 86_400_000\n\n/**\n * What a manually added window records where an auto-entry records the fingerprint that crossed.\n *\n * A human quarantining a known-broken test is not reporting a recurrence, so there is no window key\n * to carry — and the `entered` event REQUIRES one (an entry with no fingerprint would fail the\n * ledger's own shape guard). A typed literal that cannot be mistaken for a real key is the honest\n * answer: every computed fingerprint contains `::`, this one contains none.\n */\nexport const QUARANTINE_MANUAL_ENTRY_FINGERPRINT = 'manual-entry'\n\n/**\n * The class a manual entry records: `unknown`, on the merits rather than for convenience.\n *\n * `unknown` is precisely \"a failure carrying no verdict\" — nothing classified this test, because a\n * human decided to suppress it rather than a detector deciding it recurred. Recording a made-up\n * `flake` would put an assertion nobody made into committed truth, and the detection ladder reads\n * the class of AUTO entries only, so no rule changes behaviour on the strength of this value.\n */\nexport const QUARANTINE_MANUAL_ENTRY_CLASS: VerdictClass = 'unknown'\n\n/**\n * Another writer holds the MRSW lease, so the verb declined instead of writing beside it.\n *\n * The port's result unions carry no lease arm by design (390-04), so a refusal that is not one of\n * the named outcomes surfaces as a typed throw. The ledger is byte-unchanged when this is raised — the acquisition fails before the\n * read, so nothing was decided either.\n *\n * The holder is carried, not just named in the message, because the operator's next question is\n * always \"who?\" and the answer is a live pid the CLI can report without re-reading the lease file.\n *\n * WHICH ARM THIS IS (390-12 / WR-03 — the previous wording named only one and read as if it were\n * the whole rule). `acquireWriterLease` answers `held` — and therefore raises this — only when the\n * lease on disk parses AND `deriveWriterLeaseFreshness` calls it FRESH. Against a fresh holder this\n * verb genuinely does not wait and does not delegate: an operator retrying by hand is a better\n * failure mode than a human-facing verb that blocks for as long as a drain takes.\n *\n * Against a STALE holder — one whose heartbeat is older than `LEASE_HEARTBEAT_TTL_MS`, or whose\n * epoch no longer matches the one on disk — nothing is raised at all: the acquisition enters the\n * standard MRSW path and RECLAIMS, bumping the epoch and sweeping staged epochs below it, exactly\n * as the apply path does. So this verb can bump a fence and take a lock another process minted;\n * that routing is deliberate and shared, and the corpus produces it (`RECLAIMS a STALE lease and\n * writes`) rather than leaving the arm asserted only by the code that implements it.\n */\nexport class QuarantineLeaseHeldError extends Error {\n constructor(readonly holder: WriterLease) {\n super(\n 'the quarantine ledger write was refused: the knowledge writer lease is held by pid '\n + `${holder.pid} (lease ${holder.leaseId}, epoch ${holder.epoch}). `\n + 'Retry once that writer finishes.',\n )\n this.name = 'QuarantineLeaseHeldError'\n }\n}\n\n/**\n * The `filePath` a caller sent cannot mint the durable identity the ledger is keyed on (390-12).\n *\n * Same shape and same reason as the lease refusal above: the port's result unions carry no refusal\n * arm by design (390-04), so a refusal that is not one of the named outcomes surfaces as a typed\n * throw. Raised BEFORE the knowledge root is resolved, before the lease is acquired and before a\n * byte is read, so a refused call costs the ledger nothing and the next writer nothing.\n *\n * WHAT THIS OWNS, AND WHAT THE LEDGER'S OWN WRITE GUARD OWNS (390-11). They are not two spellings\n * of one rule and neither subsumes the other:\n *\n * - THIS decides what the identity IS. It is the only gate that knows the checkout root, so it is\n * the only one that can turn `/Users/me/repo/tests/a.yaml` — a real file inside the workspace,\n * the exact bytes an operator pastes out of a failure report — into `tests/a.yaml` and ACCEPT\n * it. The structural guard would refuse that input; refusing it is the wrong answer, because\n * the operator named a file the workspace genuinely contains.\n * - The STRUCTURAL guard in `appendQuarantineEvents` decides what the FILE may carry, for every\n * writer including one that never met a mint. It is a backstop with no host context, and it\n * throws rather than answering data because a line the reader refuses is corruption.\n *\n * What cannot be canonicalized at all — a path escaping the config directory — is refused here,\n * with the mint's own message carried so the operator learns why rather than that.\n */\nexport class QuarantineIdentityRefusedError extends Error {\n constructor(readonly filePath: string, readonly reason: unknown) {\n super(\n 'the quarantine ledger write was refused: this file path cannot mint the durable '\n + `workspace-relative identity the ledger is keyed on: ${filePath} `\n + `(${reason instanceof Error ? reason.message : String(reason)})`,\n )\n this.name = 'QuarantineIdentityRefusedError'\n }\n}\n\nexport interface QuarantineOperationsOptions {\n /** The committed knowledge root. A FACTORY, because the CLI host resolves it asynchronously. */\n resolveKnowledgeRoot: () => Promise<string> | string\n /** The ONLY way wall clock enters these verbs. Required — see the module head. */\n now: () => string\n /**\n * Mints the durable workspace-relative identity a `filePath` is stored under (390-12 / D-01).\n *\n * Production supplies core's ONE recipe, `workspaceRelativeIdentityPath`, pre-bound to the host's\n * own config directory. INJECTED rather than imported for two independent reasons, and either\n * alone would be sufficient: this package may not depend on `@vostride/agent-qa-core` (only the\n * surface packages may), and — the load-bearing one — the checkout root is a HOST fact these\n * verbs cannot discover. A verb that guessed it would mint identities against the wrong root.\n *\n * REQUIRED, with no default. A default passthrough is exactly the unvalidated pass-through that\n * produced the round-2 regression: the verbs answered `entered` over lines the reader is\n * guaranteed to refuse. An absent mint must be a compile error at the composition that forgot it,\n * not a runtime surprise inside a committed artifact.\n *\n * @throws whatever the mint throws for a path it cannot canonicalize; re-raised as\n * {@link QuarantineIdentityRefusedError}.\n */\n mintIdentityPath: (filePath: string) => string\n /**\n * The writer lease THIS process already holds, when it holds one (387-08 D-18 / D-5).\n *\n * Supplied by the daemon host, which acquires at startup and holds for its whole lifetime: a\n * holder that calls `acquireWriterLease` is answered `held` by itself and, unlike the apply path,\n * has nobody to delegate to. Absent on the CLI in-process host, which holds nothing and therefore\n * takes the lease per call.\n *\n * THE VALUE IS CONSULTED FOR FENCING (390-15 / G-390-2R), and this sentence used to say the\n * opposite. It is re-validated against disk on every write verb, so the question it answers is\n * \"is this process STILL the holder?\" rather than \"did this process already serialize itself?\".\n * The two are the same question only while nothing reclaims: a daemon whose heartbeat starved\n * and whose lease was then taken answers yes to the second one forever, and the two-OS-process\n * harness measured what that costs — two `entered` lines for one identity, and the verb\n * returning an owner committed truth does not record. See {@link underWriterLease}.\n *\n * AND WHAT THE RE-VALIDATION DOES NOT BUY (390-22 / WR-07): it is a read, not a lock. It answers\n * \"still the holder?\" as of the read, and the decide it licenses runs after it. A reclaim landing\n * between the two is still unfenced. `lease/under-writer-lease.ts` states the residual in full.\n */\n resolveWriterAuthority?: () => { leaseId: string; epoch: number } | undefined\n}\n\n/**\n * D-12's triage order, spelled once.\n *\n * Unassigned entries FIRST because they are the queue a human works — an owned entry already has\n * somebody accountable for it. Then `firstEnteredAt` ascending, so the oldest unclaimed\n * suppression is the first thing anyone sees. Ties break on identity bytes, which is what makes\n * the answer a function of the ledger's CONTENT rather than of the order events happened to be\n * appended in: two entries stamped in the same second must not swap places between two reads.\n *\n * THE INSTANT COMPARED IS `firstEnteredAt`, NOT `enteredAt` (390-18 / G-390-4). A test's place in\n * the queue is set by when its quarantine history BEGAN, so re-entering can never move it back\n * down the list. Comparing the current window's instant did the opposite: a test on its seventh\n * re-entry sorted as the newest thing in the queue, which put the longest-suffering test last —\n * the sort inverted against the purpose stated in the paragraph above it. The two instants are\n * different questions (see `QuarantineEntryState`), and this is the one the triage queue is about.\n */\nfunction triageOrder(left: QuarantineEntryState, right: QuarantineEntryState): number {\n const leftUnassigned = left.owner === QUARANTINE_UNASSIGNED_OWNER\n const rightUnassigned = right.owner === QUARANTINE_UNASSIGNED_OWNER\n if (leftUnassigned !== rightUnassigned) return leftUnassigned ? -1 : 1\n if (left.firstEnteredAt !== right.firstEnteredAt) {\n return left.firstEnteredAt < right.firstEnteredAt ? -1 : 1\n }\n // The subsystem's ONE identity ordering, imported rather than re-spelled (390-22 / WR-06). This\n // module's byte comparison is where the shared comparator was lifted FROM — it was already\n // correct here, and the detection ladder's collated spelling was the one deciding committed\n // bytes. Two spellings of one rule is how they came to disagree.\n return compareQuarantineIdentity(left, right)\n}\n\n/**\n * The deadline an absent `expiresAt` takes (D-11), derived from the SUPPLIED instant.\n *\n * `Date.parse` of a caller's argument is arithmetic, not a clock read. An unparseable `now` is a\n * caller bug, so it surfaces as a thrown RangeError from `toISOString` rather than silently minting\n * a forever entry — the same arm `detection.ts`'s `expiryFrom` documents for its own copy, stated\n * here too because a reader of this function should not have to find the sibling to learn it\n * (390-12 / IN-01).\n */\nfunction defaultExpiry(now: string): string {\n return new Date(Date.parse(now) + QUARANTINE_DEFAULT_EXPIRY_DAYS * MS_PER_DAY).toISOString()\n}\n\n/**\n * This module's serialized section — DELEGATED, since 391, to the one shared spelling of the rule.\n *\n * The whole read-fold-decide-append cycle (never just the append), the handed-in-authority\n * re-validation, the compile-time refusal of an async `decide` and the three exhaustive acquisition\n * arms all live in {@link underKnowledgeWriterLease} now. They moved because the grant verbs mutate\n * a SECOND committed artifact under the SAME writer lease, and a serialization rule written twice\n * is a serialization rule that agrees until it does not — this module's own history is a\n * serialization claim that turned out to be false, so a second copy of the corrected one is exactly\n * the wrong thing to author beside it. Read that module for the ladder, the ordering and the WR-07\n * residual in full.\n *\n * What stays HERE is the one thing that is genuinely this subsystem's: which refusal a held lease\n * raises. The port contract carries no lease arm (390-04), so it surfaces as a typed throw, and a\n * throw naming the wrong committed artifact would send an operator looking in the wrong file.\n *\n * The signature is UNCHANGED and the export is kept: the `@ts-expect-error` pin that proves the\n * async-`decide` refusal is a guard rather than a claim points at this name, and a constraint\n * nothing exercises is a claim. Deliberately NOT added to this package's barrel (`src/index.ts`),\n * on 390-11's reasoning about `appendQuarantineEvents`: the committed-write surface only ever\n * shrinks.\n */\nexport async function underWriterLease<T>(\n knowledgeRoot: string,\n resolveWriterAuthority: (() => { leaseId: string; epoch: number } | undefined) | undefined,\n decide: () => T & SynchronousDecision<T>,\n): Promise<T> {\n return await underKnowledgeWriterLease(\n knowledgeRoot,\n resolveWriterAuthority,\n decide,\n (holder: WriterLease) => new QuarantineLeaseHeldError(holder),\n )\n}\n\n/**\n * The three verbs over one committed ledger.\n *\n * Each call is a full read-fold-decide-append cycle. Nothing is cached between calls, which is what\n * makes `quarantine.list` and the sentence's ladder clause two readings of ONE live computation\n * (SC4): an event appended between two calls is visible to both.\n */\nexport function createQuarantineOperations(\n options: QuarantineOperationsOptions,\n): QuarantineOperationsPort {\n /** One read of the injected clock, one fold against it — the whole state a verb decides on. */\n function readState(knowledgeRoot: string): {\n now: string\n entries: QuarantineEntryState[]\n } {\n const now = options.now()\n // Typed refusals propagate — see the module head. `refusedLines` are the ledger's own\n // line-level damage report and do not stop the neighbours from folding.\n const { events } = readQuarantineLedger(knowledgeRoot)\n return { now, entries: foldQuarantineLedgerState(events, now) }\n }\n\n /** This composition's serialized section, over the module-scope lease scope. */\n async function serialized<T>(\n knowledgeRoot: string,\n decide: () => T & SynchronousDecision<T>,\n ): Promise<T> {\n return await underWriterLease(knowledgeRoot, options.resolveWriterAuthority, decide)\n }\n\n function append(knowledgeRoot: string, events: readonly QuarantineLedgerEvent[]): void {\n appendQuarantineEvents(knowledgeRoot, events)\n }\n\n function entryFor(\n entries: readonly QuarantineEntryState[],\n identity: { product: string; filePath: string; testName: string },\n ): QuarantineEntryState | undefined {\n const key = quarantineIdentityKey(identity)\n return entries.find((entry) => quarantineIdentityKey(entry) === key)\n }\n\n /**\n * The mint's throw, re-raised typed (390-12). Only the mint's failure is caught here: a\n * `slugBranch` that threw would be a bug in this module, not a refusal about the caller's input.\n */\n function mintFilePath(filePath: string): string {\n try {\n return options.mintIdentityPath(filePath)\n } catch (error) {\n throw new QuarantineIdentityRefusedError(filePath, error)\n }\n }\n\n /**\n * The write verbs' ONE normalization, taken at the boundary before anything decides.\n *\n * TWO of the three identity legs are normalized, and the third deliberately is not. The rule is\n * the same for both: a leg the READER transforms gets a WRITER-side transform, so the ledger keeps\n * one vocabulary instead of two that agree only by convention.\n *\n * - `product` is SLUGGED (WR-01 / 390-09). Every reader compares the slugged partition —\n * `resolveRunQuarantineSnapshot` filters on `entry.product === slugBranch(input.product)`, and\n * the detection path authors from projection rows already partitioned that way. Storing the raw\n * spelling wrote a real entry into a partition nothing reads.\n * - `filePath` is MINTED through {@link QuarantineOperationsOptions.mintIdentityPath} (390-12,\n * the round-2 regression). Every reader compares `===` against core's workspace-relative\n * identity, so an absolute path became a permanently refused, unlistable, unreleasable,\n * self-duplicating line in a COMMITTED artifact, and `./x`, `x\\y`, `../x` folded and listed as\n * `quarantined` while suppressing nothing. This half exists because the round hardened the READ\n * and the RUN path and left these two verbs — the documented human half of the exit path, the\n * surface most likely to receive a hand-typed path — as an unvalidated door into the same file.\n * - `testName` is stored RAW. It is the one leg no reader transforms; inventing a rule for it\n * here would be the mirror-image defect.\n *\n * Normalizing (rather than refusing a mismatch) is the choice on the merits: a human exit-path\n * verb should DO what was meant. Both rules are idempotent on their own output, so an input\n * already in canonical form round-trips byte-identically and no existing entry moves.\n *\n * Applied once, here, and threaded to all four places the identity is used — the fold lookup, the\n * authored event, the answered entry, and the release join. A rule applied at only one of them is\n * strictly worse than none: the write and the lookup would then disagree with each other as well\n * as with the reader.\n */\n function normalize(\n input: { product: string; filePath: string; testName: string },\n ): { product: string; filePath: string; testName: string } {\n return {\n product: slugBranch(input.product),\n filePath: mintFilePath(input.filePath),\n testName: input.testName,\n }\n }\n\n return {\n async list(): Promise<readonly QuarantineEntryState[]> {\n // Acquisition-free ON PURPOSE: this reads and answers, and a reader that took the writer\n // lease would queue every enumeration behind whatever drain happens to be running.\n const { entries } = readState(await options.resolveKnowledgeRoot())\n // Every state, unfiltered (the op's own contract): an operator deciding what to release\n // needs the expired and released rows as much as the suppressing ones.\n return [...entries].sort(triageOrder)\n },\n\n async release(input: QuarantineReleaseInput): Promise<QuarantineReleaseOutput> {\n // FIRST, before the root is resolved and before the lease is acquired: an input that cannot\n // mint an identity has no business taking a lock or opening a committed file.\n const identity = normalize(input)\n const knowledgeRoot = await options.resolveKnowledgeRoot()\n return await serialized(knowledgeRoot, () => {\n const { now, entries } = readState(knowledgeRoot)\n const entry = entryFor(entries, identity)\n // An OPEN window is one no release event has closed — `expired` counts, because D-11 keeps\n // an expired entry listed, renewable AND releasable; it stopped suppressing, it did not\n // vanish. Absent or already-closed answers the named arm and appends nothing: \"that test is\n // not quarantined\" is an ordinary answer, and an event recording a release that released\n // nothing would put a lie in committed history.\n if (entry === undefined || entry.state === 'released') return { kind: 'no-entry' }\n\n append(knowledgeRoot, [{\n schemaVersion: CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n kind: 'released-manual',\n at: now,\n product: entry.product,\n filePath: entry.filePath,\n testName: entry.testName,\n }])\n\n // The entry as it stands AFTER the release — a caller reading `released` learns what it\n // closed without a second read, and the state it reports is the post-write one.\n return { kind: 'released', entry: { ...entry, state: 'released' } }\n })\n },\n\n async add(input: QuarantineAddInput): Promise<QuarantineAddOutput> {\n // Same ordering as `release`, for the same reason: the refusal costs the ledger nothing and\n // the next writer nothing, and an input tripping BOTH this and a held lease answers THIS.\n const identity = normalize(input)\n const knowledgeRoot = await options.resolveKnowledgeRoot()\n return await serialized(knowledgeRoot, () => {\n const { now, entries } = readState(knowledgeRoot)\n const entry = entryFor(entries, identity)\n const expiresAt = input.expiresAt ?? defaultExpiry(now)\n\n // An open window (suppressing OR lapsed) is EXTENDED rather than reopened, so the ledger\n // keeps one continuous window instead of two overlapping ones. A closed window re-enters —\n // D-10's \"re-entry needs no special rule\", and the repeated `entered` lines are the history\n // the event log was chosen to keep (390-05: the intended record, not duplication).\n if (entry !== undefined && entry.state !== 'released') {\n append(knowledgeRoot, [{\n schemaVersion: CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n kind: 'renewed',\n at: now,\n product: entry.product,\n filePath: entry.filePath,\n testName: entry.testName,\n expiresAt,\n // OMITTED when the caller named nobody: an absent owner leaves the existing claim (or\n // the unassigned literal) exactly as it was. Writing `unassigned` here would silently\n // UN-claim a window somebody had taken.\n //\n // TWO AUTHORING PATHS, ONE RULE. `ownerForAutoEntry` (detection.ts) makes the same\n // decision for an AUTO re-entry, stated over the prior entry's state: carry across a\n // lapse, start unassigned after a deliberate release. Until 390-18 the rule was\n // written down here and applied only here, and the auto path did exactly what this\n // comment refuses to. If you change one, change the other.\n ...(input.owner === undefined ? {} : { owner: input.owner }),\n }])\n return {\n kind: 'renewed',\n entry: {\n ...entry,\n owner: input.owner ?? entry.owner,\n expiresAt,\n // A renewal on a lapsed entry puts it back under suppression, which is the whole\n // point of keeping an expired entry renewable.\n state: 'quarantined',\n },\n }\n }\n\n const owner = input.owner ?? QUARANTINE_UNASSIGNED_OWNER\n append(knowledgeRoot, [{\n schemaVersion: CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n kind: 'entered',\n at: now,\n ...identity,\n fingerprint: QUARANTINE_MANUAL_ENTRY_FINGERPRINT,\n verdictClass: QUARANTINE_MANUAL_ENTRY_CLASS,\n owner,\n expiresAt,\n }])\n\n return {\n kind: 'entered',\n entry: {\n // The identity that was STORED, never the spelling the caller sent: an answer naming\n // the raw product would tell an operator a partition exists that does not.\n ...identity,\n fingerprint: QUARANTINE_MANUAL_ENTRY_FINGERPRINT,\n verdictClass: QUARANTINE_MANUAL_ENTRY_CLASS,\n owner,\n enteredAt: now,\n expiresAt,\n // The history the NEXT fold of this file will answer, answered here too. This branch\n // is reached both for a first entry and for a re-entry over a CLOSED window, so the\n // count continues the prior entry's rather than restarting — an answer that restarted\n // would disagree with the ledger one read later, and the caller would have no way to\n // know which of the two was lying.\n enteredCount: (entry?.enteredCount ?? 0) + 1,\n firstEnteredAt: entry?.firstEnteredAt ?? now,\n state: 'quarantined',\n },\n }\n })\n },\n }\n}\n","// The committed-write verbs' serialized section, spelled ONCE (Phase 390 D-11 · WR-02 · G-390-2R;\n// lifted here by Phase 391 D-03).\n//\n// WHY THIS MODULE EXISTS. The quarantine verbs and the grant verbs mutate two different committed\n// artifacts under the SAME knowledge root and therefore under the same MRSW writer lease. Until 391\n// the whole read-fold-decide-append scope — the handed-in-authority re-validation, the compile-time\n// refusal of an async `decide`, the acquire/release discipline and the three exhaustive acquisition\n// arms — lived inside `quarantine/operations.ts`, because quarantine was the only client. A second\n// client written beside it would have been a second spelling of a serialization rule, and this\n// repository's own measured lesson is that two spellings of one rule agree until they do not.\n//\n// So the rule lives here and the callers name their own refusal. What is NOT parameterised is\n// everything else: the ladder, the ordering and the residual below are shared verbatim, which is\n// the whole point of the move.\n//\n// WHAT THE SCOPE PROVES, AND WHAT IT DOES NOT (390-22 / WR-07). A HANDED-IN authority is re-read\n// against disk before it licenses anything, and that check holds NO lock — unlike the lease\n// module's own `withCurrentWriterAuthority`, which runs inside `withMutationLock`. So what it\n// proves is bounded exactly: the authority was current AT THE MOMENT OF THE CHECK, not for the\n// duration of the `decide` that follows it. A reclaim landing in that window is still unfenced and\n// the append it licenses still lands. Before the check the window was FOREVER — a heartbeat-starved\n// daemon kept appending beside its reclaimer for the rest of its life, which the two-OS-process\n// harness measured as two `entered` lines for one identity. Narrowing forever to ONE SYNCHRONOUS\n// call is a real improvement and it is not closure; closing it needs the APPEND itself to carry a\n// fence, which is larger than either phase took.\n\nimport {\n LEASE_HEARTBEAT_TTL_MS,\n WriterAuthorityLostError,\n acquireWriterLease,\n assertEpochCurrent,\n readWriterLease,\n releaseLease,\n} from './writer-lease.js'\nimport type { LeaseOperationOptions, WriterLease, WriterLeaseAuthority } from './writer-lease.js'\n\n/** `process.emitWarning` code for a lease not given back after the work it guarded. */\nexport const LEASE_RELEASE_DEFERRED_WARNING = 'AGENT_QA_LEASE_RELEASE_DEFERRED'\n\n/**\n * Give a lease back after the work it guarded, without letting the release decide that work's\n * outcome (2026-10-03, quick 261003-lgd, Phase 432 review WR-11).\n *\n * Called from a `finally`. A release that throws there (the lease guard stayed busy for its\n * whole wait, or its directory chain was refused) would replace a committed result with that\n * throw, or mask the work's own error. It is a named warning instead, and the lease lapses by\n * its heartbeat TTL, or at once when this process exits and its pid is gone. A typed refusal was\n * already left to the same lapse.\n */\nexport function releaseLeaseAfterWork(opts: LeaseOperationOptions): void {\n try {\n releaseLease(opts)\n } catch (error) {\n const reason = error instanceof Error ? `${error.name}: ${error.message}` : String(error)\n process.emitWarning(\n `the knowledge writer lease ${opts.leaseId} was not released after its work (${reason}); `\n + `it lapses within ${LEASE_HEARTBEAT_TTL_MS / 1_000} s, or when this process exits`,\n { code: LEASE_RELEASE_DEFERRED_WARNING },\n )\n }\n}\n\n/**\n * A `decide` that returns a promise, refused at COMPILE time (390-12 / WR-02).\n *\n * {@link underKnowledgeWriterLease} releases the lease in a `finally`, so an async `decide` would\n * hand back a PENDING promise, the `finally` would run immediately, and the lease would be given up\n * while the work it serializes is still running — reinstating precisely the race CR-03 closed,\n * without failing to compile (`Promise<Promise<X>>` collapses in the return position, so nothing\n * objects). The quarantine module's own history is a serialization claim that turned out to be\n * false; a signature that permits the false version by construction is the wrong default here\n * specifically, and it is now the wrong default for the grant verbs too.\n *\n * Spelled as an INTERSECTION on the callback's return rather than as a constraint on the type\n * parameter (`T extends NotSynchronous<T>` is rejected as a circular constraint) and rather than as\n * a conditional RETURN type (which resolves to `never`, and `never` is assignable to everything, so\n * the call site would still compile). In this position inference is preserved — `T` is still read\n * off the callback — and a promise-returning closure fails to satisfy `never`.\n */\nexport type SynchronousDecision<T> = T extends PromiseLike<unknown> ? never : unknown\n\n/**\n * The handed-in authority, re-read against disk before it licenses a write (390-15 / G-390-2R).\n *\n * WHY THE EPOCH IS THE FENCING TOKEN, and why no clock is involved. `acquireWriterLease` bumps the\n * monotonic epoch on EVERY acquisition including a reclaim, so \"my epoch is no longer the disk\n * epoch\" is exactly \"somebody took this lease from under me\" — no TTL, no timing window, nothing\n * to tune. And the daemon's captured epoch never legitimately moves during its lifetime:\n * `refreshWriterLeaseAuthority` heartbeats and returns THE SAME authority, throwing rather than\n * renumbering, so the value the daemon host closes over is a fixed constant that stays valid for\n * exactly as long as the daemon holds the lease. This check therefore cannot refuse a healthy\n * daemon; the accept-direction control in the quarantine suite is what keeps that a measurement.\n *\n * WHY THE LEASE IS READ TOO. `releaseLease` deliberately RETAINS the epoch forever, so a holder\n * that released still carries a matching counter while owning nothing. The epoch answers \"did\n * anybody reclaim?\"; the lease answers \"am I still the holder?\", and neither subsumes the other.\n *\n * WHY NOT `refreshWriterLeaseAuthority`, which asks nearly the same question. It also HEARTBEATS —\n * it rewrites the lease file — and a read-fold-decide-append verb has no business mutating the\n * lease as a side effect of answering a question about it. Both legs here are read-only.\n *\n * FAIL-CLOSED ON A STATE NOBODY CAN EVALUATE. `readCurrentEpoch` throws `CorruptEpochStateError`\n * for an unreadable or malformed epoch file and that propagates unflattened, exactly as an\n * `unreadable` lease raises rather than degrading to \"nobody holds it\". Authority that cannot be\n * proven is not a licence to write, which is the posture `acquireWriterLease` already takes for\n * the same inputs.\n *\n * Every reason raised here is an existing member of `WriterAuthorityLostReason`; nothing widens.\n */\nfunction assertHandedInAuthority(\n knowledgeRoot: string,\n authority: { leaseId: string; epoch: number },\n): void {\n const full: WriterLeaseAuthority = { knowledgeRoot, ...authority }\n\n const epoch = assertEpochCurrent({ knowledgeRoot, epoch: authority.epoch })\n if (!epoch.current) {\n throw new WriterAuthorityLostError(full, 'stale-epoch', epoch.observedEpoch)\n }\n\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'absent') {\n throw new WriterAuthorityLostError(full, 'lease-missing', authority.epoch)\n }\n if (current.kind === 'malformed') {\n throw new WriterAuthorityLostError(full, 'lease-malformed', authority.epoch)\n }\n if (current.kind === 'unreadable') {\n throw new WriterAuthorityLostError(full, 'lease-unreadable', authority.epoch)\n }\n if (current.lease.leaseId !== authority.leaseId) {\n throw new WriterAuthorityLostError(full, 'lease-id-mismatch', authority.epoch)\n }\n}\n\n/**\n * Run one committed-write verb's WHOLE read-fold-decide-append cycle under the knowledge writer\n * lease — not just the append.\n *\n * Serializing only the file write would leave the interesting race intact: two writers could both\n * fold a ledger with no entry for a subject, both decide to open one, and both append, producing\n * two opening events for one window. So `decide` runs INSIDE the scope and is synchronous BY\n * SIGNATURE (see {@link SynchronousDecision}) — there is no await point between the read and the\n * append for another writer to be scheduled at.\n *\n * Three arms, and they are exhaustive over the acquisition outcome:\n * - a handed-in authority is VALIDATED against disk and, if it is still current, means this\n * process IS the holder; it then acquires nothing and releases nothing, because the lease it was\n * given outlives this call (the daemon's arm). An authority this process no longer holds raises\n * the lease module's own `WriterAuthorityLostError` before `decide` runs, so a reclaimed daemon\n * writes nothing — BOUNDED as the module head states;\n * - `held` hands the live holder to the caller's own refusal factory, having written nothing and\n * having taken nothing from the holder. The factory is the ONE parameterised thing here: the\n * port contracts these verbs implement carry no lease arm, so a refusal that is not one of their\n * named outcomes surfaces as a typed throw, and a throw naming the WRONG committed artifact\n * would send an operator looking in the wrong file;\n * - every other non-`acquired` outcome rethrows the union's own error, which every refusal arm\n * carries precisely so a new arm surfaces by name instead of being swallowed here.\n */\nexport async function underKnowledgeWriterLease<T>(\n knowledgeRoot: string,\n resolveWriterAuthority: (() => { leaseId: string; epoch: number } | undefined) | undefined,\n decide: () => T & SynchronousDecision<T>,\n onLeaseHeld: (holder: WriterLease) => Error,\n): Promise<T> {\n const authority = resolveWriterAuthority?.()\n if (authority !== undefined) {\n assertHandedInAuthority(knowledgeRoot, authority)\n return decide()\n }\n\n const acquired = acquireWriterLease(knowledgeRoot)\n if (acquired.kind === 'held') throw onLeaseHeld(acquired.holder)\n if (acquired.kind !== 'acquired') throw acquired.error\n\n try {\n return decide()\n } finally {\n // Given back on EVERY exit, including the typed ledger refusals the read raises: a verb that\n // failed must not leave the next drain locked out of the knowledge root. A release that throws\n // never replaces the verb's own result or error (WR-11).\n releaseLeaseAfterWork({ knowledgeRoot, leaseId: acquired.leaseId })\n }\n}\n","// Binary artifact bytes land only in the gitignore-covered artifacts/ directory and bypass the\n// committed-text checkpoint, following the eval-local blob precedent (BNDL-01/D-13). The writer\n// commits a separately checkpointed inventory containing only this function's `copied` rows.\n// This layer verifies content hashes, enforces copied-byte caps, and never emits a row before its\n// content-addressed file exists. 2026-10-15 (441-25, D-28/D-21): DOM and accessibility snapshots\n// are written through the caller's declared mask; every other artifact is copied byte-for-byte.\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { ArtifactRef, MaskFn } from '@vostride/agent-qa-schema'\n\nexport const ARTIFACT_STEP_CAP_BYTES = 2 * 1024 * 1024\nexport const ARTIFACT_RUN_CAP_BYTES = 25 * 1024 * 1024\n\nexport interface ArtifactCopyInput {\n ref: ArtifactRef\n sourcePath: string\n stepIndex: number\n role?: string\n originalName?: string\n}\n\nexport interface CopiedArtifact {\n ref: ArtifactRef\n relPath: string\n bytes: number\n stepIndex: number\n role?: string\n originalName?: string\n}\n\nexport type ArtifactCopySkipReason =\n | 'step-cap'\n | 'run-cap'\n | 'pruned-source'\n | 'sha-mismatch'\n\nexport interface SkippedArtifact<Reason extends string = ArtifactCopySkipReason> {\n ref: ArtifactRef\n stepIndex: number\n reason: Reason\n}\n\nexport interface ArtifactCopyResult {\n copied: CopiedArtifact[]\n skipped: SkippedArtifact[]\n evidenceIncomplete: boolean\n}\n\nexport interface ArtifactCopyOptions {\n /** Pre-copy refusals retained in the same inventory as copy-time refusals. */\n preSkipped?: readonly SkippedArtifact[]\n mask?: MaskFn\n}\n\nconst ARTIFACT_SHA_RE = /^[0-9a-f]{64}$/\nconst TEXT_ARTIFACT_ROLES: ReadonlySet<string> = new Set(['dom-snapshot', 'ax-snapshot'])\n\nfunction byteSha(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex')\n}\n\nfunction copiedRow(\n input: ArtifactCopyInput,\n ref: ArtifactRef,\n bytes: number,\n): CopiedArtifact {\n return {\n ref,\n relPath: `artifacts/${ref.sha}`,\n bytes,\n stepIndex: input.stepIndex,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.originalName === undefined ? {} : { originalName: input.originalName }),\n }\n}\n\nfunction maskTextArtifact(bytes: Buffer, role: string | undefined, mask: MaskFn | undefined): Buffer {\n if (mask === undefined || role === undefined || !TEXT_ARTIFACT_ROLES.has(role)) return bytes\n return Buffer.from(mask(bytes.toString('utf8')))\n}\n\nfunction skippedRow(\n input: ArtifactCopyInput,\n reason: ArtifactCopySkipReason,\n): SkippedArtifact<ArtifactCopySkipReason> {\n return { ref: input.ref, stepIndex: input.stepIndex, reason }\n}\n\nexport function copyArtifacts(\n inputs: readonly ArtifactCopyInput[],\n destArtifactsDir: string,\n options: ArtifactCopyOptions = {},\n): ArtifactCopyResult {\n const copied: CopiedArtifact[] = []\n const skipped: SkippedArtifact[] = [...(options.preSkipped ?? [])]\n const copiedBytesByStep = new Map<number, number>()\n let copiedBytesForRun = 0\n\n mkdirSync(destArtifactsDir, { recursive: true })\n\n for (const input of inputs) {\n if (!ARTIFACT_SHA_RE.test(input.ref.sha)) {\n skipped.push(skippedRow(input, 'sha-mismatch'))\n continue\n }\n\n let sourceBytes: Buffer\n try {\n sourceBytes = readFileSync(input.sourcePath)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n skipped.push(skippedRow(input, 'pruned-source'))\n continue\n }\n throw error\n }\n\n if (byteSha(sourceBytes) !== input.ref.sha) {\n skipped.push(skippedRow(input, 'sha-mismatch'))\n continue\n }\n\n const copyBytes = maskTextArtifact(sourceBytes, input.role, options.mask)\n const copiedRef = copyBytes.equals(sourceBytes)\n ? input.ref\n : { ...input.ref, sha: byteSha(copyBytes) }\n const targetPath = join(destArtifactsDir, copiedRef.sha)\n if (existsSync(targetPath)) {\n const existingBytes = readFileSync(targetPath)\n if (byteSha(existingBytes) !== copiedRef.sha || !existingBytes.equals(copyBytes)) {\n skipped.push(skippedRow(input, 'sha-mismatch'))\n continue\n }\n copied.push(copiedRow(input, copiedRef, copyBytes.byteLength))\n continue\n }\n\n const stepBytes = copiedBytesByStep.get(input.stepIndex) ?? 0\n if (stepBytes + copyBytes.byteLength > ARTIFACT_STEP_CAP_BYTES) {\n skipped.push(skippedRow(input, 'step-cap'))\n continue\n }\n if (copiedBytesForRun + copyBytes.byteLength > ARTIFACT_RUN_CAP_BYTES) {\n skipped.push(skippedRow(input, 'run-cap'))\n continue\n }\n\n try {\n writeFileSync(targetPath, copyBytes, { flag: 'wx' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const existingBytes = readFileSync(targetPath)\n if (byteSha(existingBytes) !== copiedRef.sha || !existingBytes.equals(copyBytes)) {\n skipped.push(skippedRow(input, 'sha-mismatch'))\n continue\n }\n copied.push(copiedRow(input, copiedRef, copyBytes.byteLength))\n continue\n }\n\n copiedBytesByStep.set(input.stepIndex, stepBytes + copyBytes.byteLength)\n copiedBytesForRun += copyBytes.byteLength\n copied.push(copiedRow(input, copiedRef, copyBytes.byteLength))\n }\n\n return { copied, skipped, evidenceIncomplete: skipped.length > 0 }\n}\n","// Deterministic committed-part rendering for one immutable bundle publication (D-01/D-02).\n// Every returned text part is checkpointed as one unit by bundle-publish; manifest.json is\n// deliberately rendered last and hashes every preceding committed part without hashing itself.\n\nimport { createHash } from 'node:crypto'\n\nimport {\n BUNDLE_SCHEMA_VERSION,\n canonicalJson,\n committedFileText,\n computeBundleIdentityHash,\n computeMutableStateHash,\n deriveDiscriminantKey,\n emitRecordMarkdown,\n mintBundleId,\n normalizeAnchor,\n renderEmbeddingInput,\n screenStateSnapshotRelPath,\n} from '@vostride/agent-qa-schema'\nimport type {\n ArtifactsIndex,\n BundleDiscriminant,\n BundleDraft,\n BundleIdentityCore,\n BundleIdentityInput,\n BundleManifest,\n BundleOutcomeEvent,\n BundleProvenance,\n BundleRelation,\n BundleRelations,\n CurationAuthorship,\n DistilledObservation,\n OriginClass,\n RecordFrontmatter,\n RecordId,\n ScreenState,\n} from '@vostride/agent-qa-schema'\n\nimport type { ArtifactCopyResult } from './artifact-copy.js'\n\nexport interface RenderedBundlePart {\n relPath: string\n label: string\n text: string\n}\n\nexport type BundleProvenanceInput =\n | {\n mode: 'run-linked'\n runId: string\n testId: string\n stepIndex: number\n curationJobId?: string\n sourceBuildOrdinal?: number\n authorship?: CurationAuthorship\n needsEnrichment?: boolean\n withheld?: boolean\n }\n | {\n mode: 'standalone'\n sourceDescription: string\n }\n\nexport interface RenderBundlePartsInput {\n draft: BundleDraft\n discriminant: BundleDiscriminant\n originClass: OriginClass\n createdAtOrdinal: number\n screenStates: readonly ScreenState[]\n initialEvents: readonly BundleOutcomeEvent[]\n relations: readonly BundleRelation[]\n provenance: BundleProvenanceInput\n copiedArtifacts: ArtifactCopyResult\n evidenceIncomplete: boolean\n evidenceMarkdown?: string\n distilledObservations?: readonly DistilledObservation[]\n}\n\nfunction textSha(text: string): string {\n return createHash('sha256').update(text).digest('hex')\n}\n\nfunction part(relPath: string, text: string): RenderedBundlePart {\n return { relPath, label: relPath, text }\n}\n\nfunction validateIdentityInputs(\n draft: BundleDraft,\n discriminant: BundleDiscriminant,\n): NonNullable<BundleDraft['subtype']> | null {\n if (draft.anchors.length === 0) {\n throw new TypeError('bundle draft requires at least one anchor')\n }\n if (discriminant.kind !== draft.kind) {\n throw new TypeError('bundle discriminant kind must match the draft kind')\n }\n if (draft.kind === 'fact') {\n if (draft.subtype === undefined) {\n throw new TypeError('fact bundle draft requires a subtype')\n }\n if (discriminant.kind !== 'fact' || discriminant.subtype !== draft.subtype) {\n throw new TypeError('fact bundle discriminant subtype must match the draft subtype')\n }\n return draft.subtype\n }\n if (draft.subtype !== undefined) {\n throw new TypeError('only fact bundle drafts may carry a subtype')\n }\n return null\n}\n\nfunction renderProvenance(\n provenance: BundleProvenanceInput,\n originClass: OriginClass,\n): BundleProvenance {\n return provenance.mode === 'run-linked'\n ? {\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n mode: provenance.mode,\n originClass,\n runId: provenance.runId,\n testId: provenance.testId,\n stepIndex: provenance.stepIndex,\n ...(provenance.curationJobId === undefined\n ? {}\n : { curationJobId: provenance.curationJobId }),\n ...(provenance.sourceBuildOrdinal === undefined\n ? {}\n : { sourceBuildOrdinal: provenance.sourceBuildOrdinal }),\n ...(provenance.authorship === undefined\n ? {}\n : { authorship: provenance.authorship }),\n ...(provenance.needsEnrichment === undefined\n ? {}\n : { needsEnrichment: provenance.needsEnrichment }),\n ...(provenance.withheld === undefined\n ? {}\n : { withheld: provenance.withheld }),\n }\n : {\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n mode: provenance.mode,\n originClass,\n sourceDescription: provenance.sourceDescription,\n }\n}\n\nexport function renderArtifactIndex(\n copiedArtifacts: ArtifactCopyResult,\n): ArtifactsIndex {\n return {\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n artifacts: copiedArtifacts.copied.map((copied) => ({\n id: copied.ref.id,\n sha: copied.ref.sha,\n bytes: copied.bytes,\n stepIndex: copied.stepIndex,\n relPath: copied.relPath,\n ...(copied.role === undefined ? {} : { role: copied.role }),\n ...(copied.originalName === undefined ? {} : { originalName: copied.originalName }),\n ...(copied.ref.evidenceIncomplete === undefined\n ? {}\n : { evidenceIncomplete: copied.ref.evidenceIncomplete }),\n })),\n ...(copiedArtifacts.skipped.length === 0\n ? {}\n : {\n skipped: copiedArtifacts.skipped.map((skipped) => ({\n id: skipped.ref.id,\n sha: skipped.ref.sha,\n stepIndex: skipped.stepIndex,\n path: `artifacts/${skipped.ref.sha}`,\n reason: skipped.reason,\n })),\n }),\n }\n}\n\nexport function renderBundleParts(input: RenderBundlePartsInput): {\n parts: RenderedBundlePart[]\n id: RecordId\n identityHash: string\n identityCore: BundleIdentityCore\n} {\n const subtype = validateIdentityInputs(input.draft, input.discriminant)\n const primaryAnchor = input.draft.anchors[0]!\n const discriminantKey = deriveDiscriminantKey(input.discriminant)\n const identityInput: BundleIdentityInput = {\n kind: input.draft.kind,\n ...(subtype === null ? {} : { subtype }),\n primaryAnchor,\n scope: input.draft.scope,\n discriminantKey,\n }\n const identityCore: BundleIdentityCore = {\n kind: input.draft.kind,\n subtype,\n primaryAnchor: normalizeAnchor(primaryAnchor),\n scope: input.draft.scope,\n discriminantKey,\n }\n const identityHash = computeBundleIdentityHash(identityInput)\n const id = mintBundleId(identityInput)\n const evidenceIncomplete =\n input.evidenceIncomplete || input.copiedArtifacts.evidenceIncomplete\n const anchors = input.draft.anchors.map((raw) => ({\n raw,\n normalized: normalizeAnchor(raw),\n }))\n const recordFrontmatter: RecordFrontmatter = {\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n id,\n kind: input.draft.kind,\n ...(subtype === null ? {} : { subtype }),\n anchors,\n scope: input.draft.scope,\n createdAtOrdinal: input.createdAtOrdinal,\n originClass: input.originClass,\n evidenceIncomplete,\n }\n const relations: BundleRelations = {\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n relations: [...input.relations],\n }\n const artifactsIndex = renderArtifactIndex(input.copiedArtifacts)\n const outcomesText = input.initialEvents\n .map((event) => `${canonicalJson(event)}\\n`)\n .join('')\n const relationsText = committedFileText(relations)\n const artifactsIndexText = committedFileText(artifactsIndex)\n\n const parts: RenderedBundlePart[] = [\n part(\n 'record.md',\n emitRecordMarkdown(recordFrontmatter, {\n summary: input.draft.summary,\n body: input.draft.body,\n }),\n ),\n part(\n 'provenance.json',\n committedFileText(renderProvenance(input.provenance, input.originClass)),\n ),\n part('relations.json', relationsText),\n ...input.screenStates.map((screenState, stepIndex) =>\n part(screenStateSnapshotRelPath(stepIndex), committedFileText(screenState)),\n ),\n ...(input.distilledObservations === undefined\n ? []\n : [\n part(\n 'observations.jsonl',\n input.distilledObservations\n .map((observation) => `${canonicalJson(observation)}\\n`)\n .join(''),\n ),\n ]),\n part('evidence/outcomes.jsonl', outcomesText),\n ...(input.evidenceMarkdown === undefined\n ? []\n : [part('evidence/evidence.md', input.evidenceMarkdown)]),\n part('artifacts.index.json', artifactsIndexText),\n ]\n\n const manifest: BundleManifest = {\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n id,\n identityHash,\n identityCore,\n embeddingInput: renderEmbeddingInput({\n summary: input.draft.summary,\n body: input.draft.body,\n anchors: input.draft.anchors,\n }),\n contentHashes: Object.fromEntries(\n parts.map(({ relPath, text }) => [relPath, textSha(text)]),\n ),\n mutableStateHash: computeMutableStateHash({\n outcomes: textSha(outcomesText),\n relations: textSha(relationsText),\n artifactsIndex: textSha(artifactsIndexText),\n }),\n evidenceIncomplete,\n complete: true,\n createdAtOrdinal: input.createdAtOrdinal,\n originClass: input.originClass,\n }\n\n parts.push(part('manifest.json', committedFileText(manifest)))\n return { parts, id, identityHash, identityCore }\n}\n","// Bundle publication is the D-11/D-12/D-15 store seam beneath KnowledgePort (D-04).\n// It copies capped artifacts into an invisible sibling staging directory, writes every\n// committed text part with manifest.json last (§7.8), then atomically renames.\n// BNDL-02/D-05 only treats an occupied target as already-exists after full-identity equality.\n\nimport { randomUUID } from 'node:crypto'\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join } from 'node:path'\n\nimport {\n canonicalJson,\n guardBundleManifest,\n slugBranch,\n verifyManifestIdentity,\n} from '@vostride/agent-qa-schema'\nimport type {\n BundleIdentityCore,\n BundleManifest,\n RecordId,\n} from '@vostride/agent-qa-schema'\n\nimport { copyArtifacts } from './artifact-copy.js'\nimport type {\n ArtifactCopyInput,\n ArtifactCopyResult,\n ArtifactCopySkipReason,\n SkippedArtifact,\n} from './artifact-copy.js'\nimport { renderBundleParts } from './bundle-parts.js'\nimport type { RenderBundlePartsInput } from './bundle-parts.js'\nimport { durableRename, fsyncDirectory, fsyncTree } from './durable-fs.js'\nimport { assertWithinKnowledgeRoot } from './knowledge-containment.js'\n\nexport interface BundleStoreConfig {\n /** Absolute committed-root path. Deliberately no working-directory default. */\n knowledgeRoot: string\n productKey: string\n commitArtifacts: 'none' | 'thumbnails'\n /** Active writer identity used to attribute crash-left staging trees. */\n writerLeaseId?: string\n /** Fencing epoch embedded in reader-invisible staging names. */\n writerEpoch?: number\n hooks?: {\n /** Test/chaos seam after all staged bytes exist but before the visibility rename. */\n beforePublishRename?: () => void\n /** Test/chaos seam after each durable mutable-file replacement. */\n afterMutableReplacement?: (targetRelPath: string) => void\n }\n}\n\nexport interface PublishBundleInput\n extends Omit<RenderBundlePartsInput, 'copiedArtifacts' | 'evidenceIncomplete'> {\n artifacts: readonly ArtifactCopyInput[]\n /** Refusals already decided by the Curator's pre-copy pass. */\n preSkippedArtifacts?: readonly SkippedArtifact<ArtifactCopySkipReason>[]\n}\n\nexport type PublishBundleOutcome =\n | { kind: 'published'; id: RecordId; dir: string; evidenceIncomplete: boolean }\n | { kind: 'already-exists'; id: RecordId }\n | {\n kind: 'identity-collision'\n id: RecordId\n dir: string\n reason:\n | 'identity-hash-mismatch'\n | 'identity-core-mismatch'\n | 'existing-manifest-corrupt'\n expectedIdentityHash: string\n existingIdentityHash: string | null\n }\n\nexport interface StagedBundlePublication {\n kind: 'staged'\n id: RecordId\n finalDir: string\n stagingDir: string\n stagingRoot: string\n bundlesDir: string\n evidenceIncomplete: boolean\n expected: ExpectedBundleIdentity\n beforePublishRename?: () => void\n}\n\nexport type StageBundleOutcome =\n | StagedBundlePublication\n | Exclude<PublishBundleOutcome, { kind: 'published' }>\n\nconst EMPTY_ARTIFACT_COPY: ArtifactCopyResult = {\n copied: [],\n skipped: [],\n evidenceIncomplete: false,\n}\n\n// Matches the path-safe token grammar enforced for claimed queue lease directories.\nconst SAFE_WRITER_LEASE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\ntype ExistingBundleTargetClassification =\n | { kind: 'same-identity' }\n | {\n kind: 'collision'\n reason:\n | 'identity-hash-mismatch'\n | 'identity-core-mismatch'\n | 'existing-manifest-corrupt'\n existingIdentityHash: string | null\n }\n\ninterface ExpectedBundleIdentity {\n id: RecordId\n identityHash: string\n identityCore: BundleIdentityCore\n}\n\nfunction classifyExistingBundleTarget(\n finalDir: string,\n expected: ExpectedBundleIdentity,\n): ExistingBundleTargetClassification {\n let manifest: BundleManifest\n try {\n manifest = guardBundleManifest(\n JSON.parse(readFileSync(join(finalDir, 'manifest.json'), 'utf8')),\n )\n } catch {\n return {\n kind: 'collision',\n reason: 'existing-manifest-corrupt',\n existingIdentityHash: null,\n }\n }\n\n if (manifest.complete !== true || verifyManifestIdentity(manifest).length > 0) {\n return {\n kind: 'collision',\n reason: 'existing-manifest-corrupt',\n existingIdentityHash: manifest.identityHash,\n }\n }\n if (manifest.identityHash !== expected.identityHash) {\n return {\n kind: 'collision',\n reason: 'identity-hash-mismatch',\n existingIdentityHash: manifest.identityHash,\n }\n }\n if (canonicalJson(manifest.identityCore) !== canonicalJson(expected.identityCore)) {\n return {\n kind: 'collision',\n reason: 'identity-core-mismatch',\n existingIdentityHash: manifest.identityHash,\n }\n }\n return { kind: 'same-identity' }\n}\n\nfunction identityCollisionOutcome(\n finalDir: string,\n expected: ExpectedBundleIdentity,\n collision: Extract<ExistingBundleTargetClassification, { kind: 'collision' }>,\n): Extract<PublishBundleOutcome, { kind: 'identity-collision' }> {\n return {\n kind: 'identity-collision',\n id: expected.id,\n dir: finalDir,\n reason: collision.reason,\n expectedIdentityHash: expected.identityHash,\n existingIdentityHash: collision.existingIdentityHash,\n }\n}\n\nfunction removeEmptyStagingRoot(stagingRoot: string, bundlesDir: string): void {\n let removed = false\n try {\n rmdirSync(stagingRoot)\n removed = true\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n if (removed) fsyncDirectory(bundlesDir)\n}\n\nfunction removeStaging(\n stagingDir: string,\n stagingRoot: string,\n bundlesDir: string,\n): void {\n rmSync(stagingDir, { recursive: true, force: true })\n if (existsSync(stagingRoot)) fsyncDirectory(stagingRoot)\n removeEmptyStagingRoot(stagingRoot, bundlesDir)\n}\n\nfunction writePart(stagingDir: string, part: { relPath: string; text: string }): void {\n const target = join(stagingDir, part.relPath)\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, part.text, 'utf8')\n}\n\nexport function stageBundle(\n config: BundleStoreConfig,\n input: PublishBundleInput,\n): StageBundleOutcome {\n if (config.commitArtifacts === 'thumbnails') {\n throw new Error(\n \"commitArtifacts 'thumbnails' is not implemented; Phase 380 visual review owns it\",\n )\n }\n if (!isAbsolute(config.knowledgeRoot)) {\n throw new TypeError('BundleStoreConfig.knowledgeRoot must be absolute')\n }\n if (\n config.writerLeaseId !== undefined\n && !SAFE_WRITER_LEASE_ID.test(config.writerLeaseId)\n ) {\n throw new TypeError('BundleStoreConfig.writerLeaseId must be a non-empty path-safe token')\n }\n if (\n config.writerEpoch !== undefined\n && (!Number.isSafeInteger(config.writerEpoch) || config.writerEpoch < 0)\n ) {\n throw new TypeError('BundleStoreConfig.writerEpoch must be a nonnegative safe integer')\n }\n\n const { artifacts, preSkippedArtifacts, ...renderInput } = input\n const identity = renderBundleParts({\n ...renderInput,\n copiedArtifacts: EMPTY_ARTIFACT_COPY,\n evidenceIncomplete: false,\n })\n const bundlesDir = join(\n config.knowledgeRoot,\n 'memory',\n slugBranch(config.productKey),\n 'bundles',\n )\n const finalDir = join(bundlesDir, identity.id)\n\n if (existsSync(finalDir)) {\n const existing = classifyExistingBundleTarget(finalDir, identity)\n return existing.kind === 'same-identity'\n ? { kind: 'already-exists', id: identity.id }\n : identityCollisionOutcome(finalDir, identity, existing)\n }\n\n const stagingRoot = join(bundlesDir, '.staging')\n // 261003-mqc: a `memory/`, product or `bundles/` linked out of the knowledge root is refused\n // before anything is staged; the rename into `bundlesDir` then stays inside it too.\n assertWithinKnowledgeRoot(config.knowledgeRoot, stagingRoot)\n const stagingBasename = `.staged-epoch-${config.writerEpoch ?? 0}-${randomUUID()}`\n const stagingDir = join(stagingRoot, stagingBasename)\n mkdirSync(stagingDir, { recursive: true })\n\n try {\n const copiedArtifacts = copyArtifacts(\n artifacts,\n join(stagingDir, 'artifacts'),\n { preSkipped: preSkippedArtifacts },\n )\n const rendered = renderBundleParts({\n ...renderInput,\n copiedArtifacts,\n evidenceIncomplete: copiedArtifacts.evidenceIncomplete,\n })\n const manifest = rendered.parts.at(-1)\n if (manifest?.relPath !== 'manifest.json') {\n throw new TypeError('renderBundleParts must return manifest.json last')\n }\n for (const renderedPart of rendered.parts.slice(0, -1)) {\n writePart(stagingDir, renderedPart)\n }\n writePart(stagingDir, manifest)\n fsyncTree(stagingDir)\n fsyncDirectory(stagingRoot)\n return {\n kind: 'staged',\n id: rendered.id,\n finalDir,\n stagingDir,\n stagingRoot,\n bundlesDir,\n evidenceIncomplete: copiedArtifacts.evidenceIncomplete,\n expected: rendered,\n ...(config.hooks?.beforePublishRename === undefined\n ? {}\n : { beforePublishRename: config.hooks.beforePublishRename }),\n }\n } catch (error) {\n removeStaging(stagingDir, stagingRoot, bundlesDir)\n throw error\n }\n}\n\n/** Remove one reader-invisible staged tree after a fenced refusal or failed finalize. */\nexport function discardStagedBundle(\n staged: StagedBundlePublication,\n removeEmptyBundlesDir = false,\n): void {\n removeStaging(staged.stagingDir, staged.stagingRoot, staged.bundlesDir)\n if (!removeEmptyBundlesDir) return\n try {\n rmdirSync(staged.bundlesDir)\n fsyncDirectory(dirname(staged.bundlesDir))\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n}\n\n/** Make a complete staged tree visible. Callers that hold writer authority own this boundary. */\nexport function finalizeStagedBundle(\n staged: StagedBundlePublication,\n): PublishBundleOutcome {\n staged.beforePublishRename?.()\n try {\n durableRename(staged.stagingDir, staged.finalDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n (code === 'EEXIST' || code === 'ENOTEMPTY')\n && existsSync(staged.finalDir)\n ) {\n const existing = classifyExistingBundleTarget(staged.finalDir, staged.expected)\n discardStagedBundle(staged)\n return existing.kind === 'same-identity'\n ? { kind: 'already-exists', id: staged.id }\n : identityCollisionOutcome(staged.finalDir, staged.expected, existing)\n }\n throw error\n }\n removeEmptyStagingRoot(staged.stagingRoot, staged.bundlesDir)\n return {\n kind: 'published',\n id: staged.id,\n dir: staged.finalDir,\n evidenceIncomplete: staged.evidenceIncomplete,\n }\n}\n","// Test fixtures sometimes need to seed a canonical bundle without composing a writer lease.\n// Production code must never import this module; commit paths stage through bundle-publish.ts\n// and finalize only inside withCurrentWriterAuthority.\n\nimport {\n discardStagedBundle,\n finalizeStagedBundle,\n stageBundle,\n} from './bundle-publish.js'\nimport type {\n BundleStoreConfig,\n PublishBundleInput,\n PublishBundleOutcome,\n} from './bundle-publish.js'\n\nexport * from './bundle-publish.js'\n\n/** Unfenced compatibility composition for test data setup only. */\nexport function publishBundle(\n config: BundleStoreConfig,\n input: PublishBundleInput,\n): PublishBundleOutcome {\n const staged = stageBundle(config, input)\n if (staged.kind !== 'staged') return staged\n try {\n return finalizeStagedBundle(staged)\n } catch (error) {\n discardStagedBundle(staged)\n throw error\n }\n}\n","// Per-mutation bundle writes rewrite the content and manifest as one journaled unit. BNDL-03\n// deduplicates before writing, while the schema fold repeats that defense in depth. Every mutable\n// file uses a full same-directory temp rewrite plus atomic rename (§4).\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { isAbsolute, join } from 'node:path'\n\nimport {\n BUNDLE_SCHEMA_VERSION,\n BundleOutcomeEventSchema,\n GateReceiptSchema,\n PromotionReceiptSchema,\n isPromotionReceipt,\n receiptDigestOf,\n stampReceiptDigest,\n canonicalJson,\n committedFileText,\n computeMutableStateHash,\n emitRecordMarkdown,\n eventDedupKey,\n guardBundleManifest,\n guardBundleProvenance,\n guardBundleRelations,\n measurementBaselineSchema,\n measurementObservationSchema,\n parseRecordMarkdown,\n renderEmbeddingInput,\n slugBranch,\n} from '@vostride/agent-qa-schema'\nimport type {\n BundleManifest,\n GateReceipt,\n PromotionReceipt,\n BundleOutcomeEvent,\n CurationAuthorship,\n BundleRelation,\n BundleRelations,\n MeasurementBaseline,\n MeasurementObservation,\n RecordId,\n} from '@vostride/agent-qa-schema'\n\nimport type { BundleStoreConfig } from './bundle-publish.js'\nimport { GATES_REL_PATH, readGateReceipts, readMeasurements } from './bundle-read.js'\nimport { commitBundleMutation } from './journal/bundle-mutation.js'\n\nexport type AppendOutcome =\n | { kind: 'appended' }\n | { kind: 'duplicate' }\n | { kind: 'not-found' }\n\n/** 416 D-04: receipt identity is its verified content digest, before any committed write. */\nexport function appendGateReceipt(\n config: BundleStoreConfig, id: RecordId, receipt: GateReceipt,\n): AppendOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n const parsed = GateReceiptSchema.parse(receipt)\n if (parsed.candidateId !== id) throw new TypeError('foreign candidateId')\n if (receiptDigestOf(parsed) !== parsed.receiptDigest) throw new TypeError('receiptDigest mismatch')\n const existing = readGateReceipts(dir, id) ?? []\n if (existing.some(line => line.receiptDigest === parsed.receiptDigest)) return { kind: 'duplicate' }\n const file = join(dir, GATES_REL_PATH)\n const existingText = existsSync(file) ? readFileSync(file, 'utf8') : ''\n const rewrittenText = existingText + canonicalJson(parsed) + '\\n'\n return rewriteBundleFile(config, dir, id, GATES_REL_PATH, rewrittenText,\n rewriteManifest(manifest, GATES_REL_PATH, rewrittenText))\n}\n\n/** 416 D-05/D-07: one promotion line per candidate/path; lifecycle bytes remain unchanged. */\nexport function appendPromotionReceipt(\n config: BundleStoreConfig,\n id: RecordId,\n lineWithoutDigest: Omit<PromotionReceipt, 'receiptDigest' | 'citedReceiptDigests'> & {\n citedReceiptDigests: readonly string[]\n },\n): AppendOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n const parsed = PromotionReceiptSchema.parse(stampReceiptDigest({\n ...lineWithoutDigest, citedReceiptDigests: [...lineWithoutDigest.citedReceiptDigests],\n }))\n if (parsed.candidateId !== id) throw new TypeError('foreign candidateId')\n const existing = readGateReceipts(dir, id) ?? []\n if (existing.some(line => line.receiptDigest === parsed.receiptDigest ||\n (isPromotionReceipt(line) && line.promotionPath === parsed.promotionPath))) {\n return { kind: 'duplicate' }\n }\n const file = join(dir, GATES_REL_PATH)\n const existingText = existsSync(file) ? readFileSync(file, 'utf8') : ''\n const rewrittenText = existingText + canonicalJson(parsed) + '\\n'\n return rewriteBundleFile(config, dir, id, GATES_REL_PATH, rewrittenText,\n rewriteManifest(manifest, GATES_REL_PATH, rewrittenText))\n}\n\nexport type AppendEnrichedOutcome =\n | { kind: 'appended' | 'duplicate'; enriched: boolean }\n | { kind: 'not-found' }\n\nexport interface BundleProseEnrichment {\n summary: string\n body: string\n authorship: CurationAuthorship\n}\n\nconst OUTCOMES_REL_PATH = 'evidence/outcomes.jsonl'\nexport const MEASUREMENTS_REL_PATH = 'evidence/measurements.json'\nconst RELATIONS_REL_PATH = 'relations.json'\nconst ARTIFACTS_INDEX_REL_PATH = 'artifacts.index.json'\n\nfunction textSha(text: string): string {\n return createHash('sha256').update(text).digest('hex')\n}\n\nfunction bundleDir(config: BundleStoreConfig, id: RecordId): string {\n if (!isAbsolute(config.knowledgeRoot)) {\n throw new TypeError('BundleStoreConfig.knowledgeRoot must be absolute')\n }\n return join(\n config.knowledgeRoot,\n 'memory',\n slugBranch(config.productKey),\n 'bundles',\n slugBranch(id),\n )\n}\n\nfunction completeManifest(dir: string): BundleManifest | null {\n const file = join(dir, 'manifest.json')\n if (!existsSync(file)) return null\n const manifest = guardBundleManifest(JSON.parse(readFileSync(file, 'utf8')))\n return manifest.complete === true ? manifest : null\n}\n\nfunction mutableStateHash(contentHashes: BundleManifest['contentHashes']): string {\n const measurements = contentHashes[MEASUREMENTS_REL_PATH]\n const gates = contentHashes[GATES_REL_PATH]\n return computeMutableStateHash({\n outcomes: contentHashes[OUTCOMES_REL_PATH] ?? null,\n relations: contentHashes[RELATIONS_REL_PATH] ?? null,\n artifactsIndex: contentHashes[ARTIFACTS_INDEX_REL_PATH] ?? null,\n ...(measurements === undefined ? {} : { measurements }),\n ...(gates === undefined ? {} : { gates }),\n })\n}\n\nfunction rewriteManifest(\n manifest: BundleManifest,\n relPath: string,\n rewrittenText: string,\n): string {\n const contentHashes = {\n ...manifest.contentHashes,\n [relPath]: textSha(rewrittenText),\n }\n return committedFileText({\n ...manifest,\n contentHashes,\n mutableStateHash: mutableStateHash(contentHashes),\n })\n}\n\nfunction rewriteManifestParts(\n manifest: BundleManifest,\n rewrittenParts: Readonly<Record<string, string>>,\n embeddingInput: string,\n): string {\n const contentHashes = { ...manifest.contentHashes }\n for (const [relPath, rewrittenText] of Object.entries(rewrittenParts)) {\n contentHashes[relPath] = textSha(rewrittenText)\n }\n return committedFileText({\n ...manifest,\n embeddingInput,\n contentHashes,\n mutableStateHash: mutableStateHash(contentHashes),\n })\n}\n\nfunction rewriteBundleFile(\n config: BundleStoreConfig,\n dir: string,\n id: RecordId,\n relPath: string,\n rewrittenText: string,\n manifestText: string,\n): AppendOutcome {\n commitBundleMutation({\n knowledgeRoot: config.knowledgeRoot,\n bundleDir: dir,\n bundleId: id,\n writerLeaseId: config.writerLeaseId,\n replacements: [\n { targetRelPath: relPath, text: rewrittenText },\n { targetRelPath: 'manifest.json', text: manifestText },\n ],\n afterMutableReplacement: config.hooks?.afterMutableReplacement,\n })\n return { kind: 'appended' }\n}\n\nfunction parseOutcomeLog(text: string): BundleOutcomeEvent[] {\n if (text === '') return []\n if (!text.endsWith('\\n')) {\n throw new SyntaxError(`${OUTCOMES_REL_PATH} must end with a newline`)\n }\n return text\n .slice(0, -1)\n .split('\\n')\n .map((line) => BundleOutcomeEventSchema.parse(JSON.parse(line)))\n}\n\nexport function appendOutcomeEvent(\n config: BundleStoreConfig,\n id: RecordId,\n event: BundleOutcomeEvent,\n): AppendOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n\n const file = join(dir, OUTCOMES_REL_PATH)\n const existingText = readFileSync(file, 'utf8')\n const existingEvents = parseOutcomeLog(existingText)\n const parsedEvent = BundleOutcomeEventSchema.parse(event)\n if (existingEvents.some((candidate) => eventDedupKey(candidate) === eventDedupKey(parsedEvent))) {\n return { kind: 'duplicate' }\n }\n\n const rewrittenText = `${existingText}${canonicalJson(parsedEvent)}\\n`\n const manifestText = rewriteManifest(manifest, OUTCOMES_REL_PATH, rewrittenText)\n return rewriteBundleFile(config, dir, id, OUTCOMES_REL_PATH, rewrittenText, manifestText)\n}\n\n/**\n * Persist D-03's immutable validity-window snapshot. An existing measurements\n * file is an idempotent refusal: baseline bytes are never rewritten.\n */\nexport function writeMeasurementBaseline(\n config: BundleStoreConfig,\n id: RecordId,\n baseline: MeasurementBaseline,\n): AppendOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n\n const file = join(dir, MEASUREMENTS_REL_PATH)\n if (existsSync(file)) return { kind: 'duplicate' }\n\n const parsedBaseline = measurementBaselineSchema.parse(baseline)\n const baselineText = `${canonicalJson(parsedBaseline)}\\n`\n const manifestText = rewriteManifest(\n manifest,\n MEASUREMENTS_REL_PATH,\n baselineText,\n )\n return rewriteBundleFile(config, dir, id, MEASUREMENTS_REL_PATH, baselineText, manifestText)\n}\n\n/**\n * Append one observation through the full journaled replacement path. Existing\n * lines remain byte-for-byte unchanged; only the new canonical line is added.\n */\nexport function appendMeasurementObservation(\n config: BundleStoreConfig,\n id: RecordId,\n observation: MeasurementObservation,\n): AppendOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n\n const measurements = readMeasurements(dir)\n if (measurements === undefined) return { kind: 'not-found' }\n\n const file = join(dir, MEASUREMENTS_REL_PATH)\n const existingText = readFileSync(file, 'utf8')\n const parsedObservation = measurementObservationSchema.parse(observation)\n const rewrittenText = `${existingText}${canonicalJson(parsedObservation)}\\n`\n const manifestText = rewriteManifest(\n manifest,\n MEASUREMENTS_REL_PATH,\n rewrittenText,\n )\n return rewriteBundleFile(config, dir, id, MEASUREMENTS_REL_PATH, rewrittenText, manifestText)\n}\n\n/**\n * Confirm a capable-model duplicate Add while backfilling only the mutable prose and provenance\n * fields of a fallback bundle. The identity frontmatter is parsed and re-emitted unchanged; the\n * stable content address therefore cannot drift during CUR-02 enrichment.\n */\nexport function appendOutcomeEventWithEnrichment(\n config: BundleStoreConfig,\n id: RecordId,\n event: BundleOutcomeEvent,\n enrichment: BundleProseEnrichment,\n): AppendEnrichedOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n\n const provenanceFile = join(dir, 'provenance.json')\n const provenance = guardBundleProvenance(\n JSON.parse(readFileSync(provenanceFile, 'utf8')),\n )\n if (provenance.mode !== 'run-linked' || provenance.needsEnrichment !== true) {\n const appended = appendOutcomeEvent(config, id, event)\n return appended.kind === 'appended' || appended.kind === 'duplicate'\n ? { ...appended, enriched: false }\n : appended\n }\n\n const recordFile = join(dir, 'record.md')\n const record = parseRecordMarkdown(readFileSync(recordFile, 'utf8'))\n const recordText = emitRecordMarkdown(record.frontmatter, {\n summary: enrichment.summary,\n body: enrichment.body,\n })\n const provenanceText = committedFileText({\n ...provenance,\n authorship: enrichment.authorship,\n needsEnrichment: false,\n })\n\n const outcomesFile = join(dir, OUTCOMES_REL_PATH)\n const existingOutcomesText = readFileSync(outcomesFile, 'utf8')\n const existingEvents = parseOutcomeLog(existingOutcomesText)\n const parsedEvent = BundleOutcomeEventSchema.parse(event)\n const duplicate = existingEvents.some(\n (candidate) => eventDedupKey(candidate) === eventDedupKey(parsedEvent),\n )\n const appendedText = duplicate ? '' : `${canonicalJson(parsedEvent)}\\n`\n const outcomesText = `${existingOutcomesText}${appendedText}`\n const embeddingInput = renderEmbeddingInput({\n summary: enrichment.summary,\n body: enrichment.body,\n anchors: record.frontmatter.anchors.map(({ raw }) => raw),\n })\n const rewrittenParts = {\n 'record.md': recordText,\n 'provenance.json': provenanceText,\n [OUTCOMES_REL_PATH]: outcomesText,\n }\n const manifestText = rewriteManifestParts(manifest, rewrittenParts, embeddingInput)\n commitBundleMutation({\n knowledgeRoot: config.knowledgeRoot,\n bundleDir: dir,\n bundleId: id,\n writerLeaseId: config.writerLeaseId,\n replacements: [\n { targetRelPath: 'record.md', text: recordText },\n { targetRelPath: 'provenance.json', text: provenanceText },\n ...(duplicate\n ? []\n : [{ targetRelPath: OUTCOMES_REL_PATH, text: outcomesText }]),\n { targetRelPath: 'manifest.json', text: manifestText },\n ],\n afterMutableReplacement: config.hooks?.afterMutableReplacement,\n })\n return { kind: duplicate ? 'duplicate' : 'appended', enriched: true }\n}\n\nfunction relationDedupKey(relation: BundleRelation): string {\n return `${relation.type}:${relation.targetId}:${relation.curationJobId}`\n}\n\nfunction parseRelation(relation: BundleRelation): BundleRelation {\n const parsed = guardBundleRelations({\n schemaVersion: BUNDLE_SCHEMA_VERSION,\n relations: [relation],\n })\n return parsed.relations[0]!\n}\n\nexport function appendRelation(\n config: BundleStoreConfig,\n id: RecordId,\n relation: BundleRelation,\n): AppendOutcome {\n const dir = bundleDir(config, id)\n const manifest = completeManifest(dir)\n if (manifest === null) return { kind: 'not-found' }\n\n const file = join(dir, RELATIONS_REL_PATH)\n const existing = guardBundleRelations(JSON.parse(readFileSync(file, 'utf8')))\n const parsedRelation = parseRelation(relation)\n if (\n existing.relations.some(\n (candidate) => relationDedupKey(candidate) === relationDedupKey(parsedRelation),\n )\n ) {\n return { kind: 'duplicate' }\n }\n\n const rewritten: BundleRelations = {\n ...existing,\n relations: [...existing.relations, parsedRelation],\n }\n const rewrittenText = committedFileText(rewritten)\n const manifestText = rewriteManifest(manifest, RELATIONS_REL_PATH, rewrittenText)\n return rewriteBundleFile(config, dir, id, RELATIONS_REL_PATH, rewrittenText, manifestText)\n}\n","import { createHash, randomUUID } from 'node:crypto'\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport type { Dirent } from 'node:fs'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\nimport { canonicalJson, slugBranch } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport { durableRename, fsyncDirectory, fsyncFile, fsyncTree } from '../durable-fs.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\n\nexport const BUNDLE_MUTATION_JOURNAL_VERSION = 2\n\nconst SAFE_PATH_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\nconst SHA256 = /^[0-9a-f]{64}$/\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst JOURNAL_FILE = 'mutation.json'\nconst RECOVERY_DIR = 'recovery'\nconst DIRECT_LIBRARY_LEASE_ID = 'direct-library'\n/**\n * 378-17 canonical mutable-target order, additively extended by 379 D-03:\n * record, provenance, outcomes, measurements, relations, then manifest.\n */\n// 2026-09-06, 416 D-03: the seventh mutable part is born only on first receipt append.\n// prettier-ignore\nexport const MUTABLE_BUNDLE_TARGETS = ['record.md', 'provenance.json', 'evidence/outcomes.jsonl', 'evidence/measurements.json', 'evidence/gates.jsonl', 'relations.json', 'manifest.json'] as const\nconst MUTABLE_TARGETS = new Set<string>(MUTABLE_BUNDLE_TARGETS)\n\nconst journalReplacementSchema = z\n .object({\n targetRelPath: z.string().min(1),\n recoveryRelPath: z.string().min(1),\n sha256: z.string().regex(SHA256),\n manifest: z.boolean(),\n })\n .strict()\n\nconst bundleMutationJournalSchema = z\n .object({\n version: z.literal(BUNDLE_MUTATION_JOURNAL_VERSION),\n leaseId: z.string().min(1),\n bundleId: z.string().min(1),\n replacements: z.array(journalReplacementSchema).min(2),\n })\n .strict()\n\ntype BundleMutationJournal = z.infer<typeof bundleMutationJournalSchema>\n\nexport interface BundleMutationInput {\n knowledgeRoot: string\n bundleDir: string\n bundleId: string\n writerLeaseId?: string\n replacements: readonly {\n targetRelPath: string\n text: string\n }[]\n afterMutableReplacement?: (targetRelPath: string) => void\n}\n\nexport interface BundleMutationRecoveryReport {\n mutationsRecovered: number\n recoveredBundleIds: string[]\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex')\n}\n\nfunction assertSafeSegment(value: string, label: string): void {\n if (!SAFE_PATH_SEGMENT.test(value) || value === '.' || value === '..') {\n throw new TypeError(`${label} must be a safe path segment`)\n }\n}\n\nfunction isWithin(parent: string, candidate: string): boolean {\n const rel = relative(resolve(parent), resolve(candidate))\n return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))\n}\n\nfunction assertBundleLocation(knowledgeRoot: string, bundleDir: string, bundleId: string): void {\n if (!isAbsolute(knowledgeRoot) || !isAbsolute(bundleDir)) {\n throw new TypeError('knowledgeRoot and bundleDir must be absolute')\n }\n if (!isWithin(knowledgeRoot, bundleDir)) {\n throw new TypeError('bundleDir must remain inside knowledgeRoot')\n }\n if (slugBranch(bundleId) !== bundleId) {\n throw new TypeError('bundleId must already be a canonical path segment')\n }\n if (basename(bundleDir) !== slugBranch(bundleId)) {\n throw new TypeError('bundleDir must end with the canonical bundle id')\n }\n const rel = relative(resolve(knowledgeRoot), resolve(bundleDir)).split(sep)\n if (rel.length !== 4 || rel[0] !== 'memory' || rel[2] !== 'bundles') {\n throw new TypeError('bundleDir must use the canonical memory/<product>/bundles/<id> layout')\n }\n // 261003-mqc: the checks above are lexical. A `memory/`, product, `bundles/` or bundle directory\n // linked out of the knowledge root is refused before any journal or replacement is written.\n assertWithinKnowledgeRoot(knowledgeRoot, bundleDir)\n assertWithinKnowledgeRoot(knowledgeRoot, join(dirname(bundleDir), '.staging'))\n}\n\nfunction assertTargetsContained(\n knowledgeRoot: string,\n bundleDir: string,\n targetRelPaths: readonly string[],\n): void {\n for (const targetRelPath of targetRelPaths) {\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(join(bundleDir, targetRelPath)))\n }\n}\n\nfunction assertMutableTarget(targetRelPath: string): void {\n if (!MUTABLE_TARGETS.has(targetRelPath)) {\n throw new TypeError(`unsupported mutable bundle target: ${targetRelPath}`)\n }\n if (isAbsolute(targetRelPath) || targetRelPath.includes('\\\\')) {\n throw new TypeError(`mutable bundle target must be relative: ${targetRelPath}`)\n }\n}\n\nfunction recoveryRelPath(index: number): string {\n return `${RECOVERY_DIR}/${String(index).padStart(4, '0')}`\n}\n\nfunction validateJournalSemantics(journal: BundleMutationJournal): void {\n assertSafeSegment(journal.leaseId, 'mutation leaseId')\n if (slugBranch(journal.bundleId) !== journal.bundleId) {\n throw new TypeError('mutation bundleId must already be a canonical path segment')\n }\n\n const targets = new Set<string>()\n for (const [index, replacement] of journal.replacements.entries()) {\n assertMutableTarget(replacement.targetRelPath)\n if (targets.has(replacement.targetRelPath)) {\n throw new TypeError(`duplicate mutable bundle target: ${replacement.targetRelPath}`)\n }\n targets.add(replacement.targetRelPath)\n if (replacement.recoveryRelPath !== recoveryRelPath(index)) {\n throw new TypeError('mutation recovery paths must be canonical and ordered')\n }\n const isManifest = replacement.targetRelPath === 'manifest.json'\n if (replacement.manifest !== isManifest) {\n throw new TypeError('mutation manifest marker must match manifest.json')\n }\n if (isManifest !== (index === journal.replacements.length - 1)) {\n throw new TypeError('mutation manifest replacement must be last')\n }\n }\n}\n\nfunction parseCanonicalJournal(transactionDir: string): BundleMutationJournal {\n const text = readFileSync(join(transactionDir, JOURNAL_FILE), 'utf8')\n const journal = bundleMutationJournalSchema.parse(JSON.parse(text))\n validateJournalSemantics(journal)\n if (text !== `${canonicalJson(journal)}\\n`) {\n throw new TypeError('mutation journal must use canonical JSON bytes')\n }\n return journal\n}\n\nfunction assertTransactionName(\n transactionDir: string,\n journal: BundleMutationJournal,\n): void {\n const prefix = `${journal.leaseId}-mutation-${journal.bundleId}-`\n const name = basename(transactionDir)\n if (!name.startsWith(prefix) || !UUID.test(name.slice(prefix.length))) {\n throw new TypeError('mutation directory name does not bind its lease and bundle')\n }\n}\n\nfunction readRecoveryPayloads(\n transactionDir: string,\n journal: BundleMutationJournal,\n): Buffer[] {\n const rootEntries = readdirSync(transactionDir, { withFileTypes: true })\n .map((entry) => `${entry.isDirectory() ? 'd' : entry.isFile() ? 'f' : 'x'}:${entry.name}`)\n .sort()\n if (canonicalJson(rootEntries) !== canonicalJson(['d:recovery', 'f:mutation.json'])) {\n throw new TypeError('mutation directory contains unexpected entries')\n }\n\n const recoveryRoot = join(transactionDir, RECOVERY_DIR)\n const expectedNames = journal.replacements.map((_replacement, index) =>\n basename(recoveryRelPath(index)),\n )\n const actualEntries = readdirSync(recoveryRoot, { withFileTypes: true }).sort((left, right) =>\n left.name.localeCompare(right.name),\n )\n if (\n actualEntries.some((entry) => !entry.isFile())\n || canonicalJson(actualEntries.map((entry) => entry.name)) !== canonicalJson(expectedNames)\n ) {\n throw new TypeError('mutation recovery set is incomplete or contains unexpected entries')\n }\n\n return journal.replacements.map((replacement) => {\n const recoveryPath = join(transactionDir, replacement.recoveryRelPath)\n if (!isWithin(transactionDir, recoveryPath)) {\n throw new TypeError('mutation recovery path escapes its transaction')\n }\n const bytes = readFileSync(recoveryPath)\n if (sha256(bytes) !== replacement.sha256) {\n throw new TypeError(`mutation recovery digest mismatch: ${replacement.targetRelPath}`)\n }\n return bytes\n })\n}\n\nfunction applyJournal(\n bundleDir: string,\n transactionDir: string,\n journal: BundleMutationJournal,\n afterMutableReplacement?: (targetRelPath: string) => void,\n): void {\n const recoveryPayloads = readRecoveryPayloads(transactionDir, journal)\n\n for (const [index, replacement] of journal.replacements.entries()) {\n const target = join(bundleDir, replacement.targetRelPath)\n if (!isWithin(bundleDir, target)) {\n throw new TypeError('mutation target escapes its bundle')\n }\n const temporary = join(\n dirname(target),\n `.${basename(target)}.mutation-${randomUUID()}.tmp`,\n )\n try {\n writeFileSync(temporary, recoveryPayloads[index]!, { flag: 'wx' })\n fsyncFile(temporary)\n durableRename(temporary, target)\n } finally {\n if (existsSync(temporary)) {\n rmSync(temporary, { force: true })\n fsyncDirectory(dirname(temporary))\n }\n }\n afterMutableReplacement?.(replacement.targetRelPath)\n }\n\n for (const replacement of journal.replacements) {\n if (sha256(readFileSync(join(bundleDir, replacement.targetRelPath))) !== replacement.sha256) {\n throw new TypeError(`mutation destination digest mismatch: ${replacement.targetRelPath}`)\n }\n }\n}\n\nfunction removeEmptyStagingRoot(stagingRoot: string): void {\n let removed = false\n try {\n rmdirSync(stagingRoot)\n removed = true\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n if (removed) fsyncDirectory(dirname(stagingRoot))\n}\n\nfunction removeCompletedTransaction(transactionDir: string): void {\n const stagingRoot = dirname(transactionDir)\n rmSync(transactionDir, { recursive: true, force: true })\n fsyncDirectory(stagingRoot)\n removeEmptyStagingRoot(stagingRoot)\n}\n\nfunction orderedReplacements(\n replacements: BundleMutationInput['replacements'],\n): BundleMutationInput['replacements'] {\n const manifests = replacements.filter(({ targetRelPath }) => targetRelPath === 'manifest.json')\n if (manifests.length !== 1) {\n throw new TypeError('bundle mutation requires exactly one manifest.json replacement')\n }\n const ordered = [\n ...replacements.filter(({ targetRelPath }) => targetRelPath !== 'manifest.json'),\n manifests[0]!,\n ]\n if (ordered.length < 2) {\n throw new TypeError('bundle mutation requires at least one target before manifest.json')\n }\n const targets = new Set<string>()\n for (const replacement of ordered) {\n assertMutableTarget(replacement.targetRelPath)\n if (targets.has(replacement.targetRelPath)) {\n throw new TypeError(`duplicate mutable bundle target: ${replacement.targetRelPath}`)\n }\n targets.add(replacement.targetRelPath)\n }\n return ordered\n}\n\n/** Commit one immutable, lease-attributed replacement set and expose manifest.json last. */\nexport function commitBundleMutation(input: BundleMutationInput): void {\n assertBundleLocation(input.knowledgeRoot, input.bundleDir, input.bundleId)\n const leaseId = input.writerLeaseId ?? DIRECT_LIBRARY_LEASE_ID\n assertSafeSegment(leaseId, 'writerLeaseId')\n const replacements = orderedReplacements(input.replacements)\n assertTargetsContained(input.knowledgeRoot, input.bundleDir,\n replacements.map((replacement) => replacement.targetRelPath))\n const bundlesDir = dirname(input.bundleDir)\n const stagingRoot = join(bundlesDir, '.staging')\n const transactionDir = join(\n stagingRoot,\n `${leaseId}-mutation-${input.bundleId}-${randomUUID()}`,\n )\n const recoveryRoot = join(transactionDir, RECOVERY_DIR)\n let journalDurable = false\n\n mkdirSync(recoveryRoot, { recursive: true })\n fsyncDirectory(bundlesDir)\n fsyncDirectory(stagingRoot)\n\n try {\n const journal: BundleMutationJournal = {\n version: BUNDLE_MUTATION_JOURNAL_VERSION,\n leaseId,\n bundleId: input.bundleId,\n replacements: replacements.map((replacement, index) => {\n const bytes = Buffer.from(replacement.text)\n const relPath = recoveryRelPath(index)\n writeFileSync(join(transactionDir, relPath), bytes, { flag: 'wx' })\n return {\n targetRelPath: replacement.targetRelPath,\n recoveryRelPath: relPath,\n sha256: sha256(bytes),\n manifest: replacement.targetRelPath === 'manifest.json',\n }\n }),\n }\n validateJournalSemantics(journal)\n writeFileSync(join(transactionDir, JOURNAL_FILE), `${canonicalJson(journal)}\\n`, {\n encoding: 'utf8',\n flag: 'wx',\n })\n fsyncTree(transactionDir)\n fsyncDirectory(stagingRoot)\n journalDurable = true\n\n applyJournal(\n input.bundleDir,\n transactionDir,\n journal,\n input.afterMutableReplacement,\n )\n removeCompletedTransaction(transactionDir)\n } catch (error) {\n if (!journalDurable) removeCompletedTransaction(transactionDir)\n throw error\n }\n}\n\nfunction listMutationRoots(knowledgeRoot: string): string[] {\n if (!isAbsolute(knowledgeRoot)) throw new TypeError('knowledgeRoot must be absolute')\n const memoryRoot = join(knowledgeRoot, 'memory')\n let products: Dirent<string>[]\n try {\n products = readdirSync(memoryRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n return products\n .filter((entry) => entry.isDirectory())\n .map((entry) => join(memoryRoot, entry.name, 'bundles', '.staging'))\n .filter((stagingRoot) => existsSync(stagingRoot))\n .sort()\n}\n\nfunction matchingExpiredLease(name: string, expiredLeaseIds: readonly string[]): string | undefined {\n return expiredLeaseIds.find((leaseId) => name.startsWith(`${leaseId}-mutation-`))\n}\n\n/** Replay complete mutation journals owned by expired writers and preserve malformed evidence. */\nexport function recoverExpiredBundleMutations(\n knowledgeRoot: string,\n expiredLeaseIds: readonly string[],\n): BundleMutationRecoveryReport {\n const leases = [...new Set(expiredLeaseIds)].sort((left, right) =>\n right.length - left.length || left.localeCompare(right),\n )\n for (const leaseId of leases) assertSafeSegment(leaseId, 'expired leaseId')\n\n const recoveredBundleIds: string[] = []\n for (const stagingRoot of listMutationRoots(knowledgeRoot)) {\n const entries = readdirSync(stagingRoot, { withFileTypes: true }).sort((left, right) =>\n left.name.localeCompare(right.name),\n )\n for (const entry of entries) {\n const expectedLeaseId = matchingExpiredLease(entry.name, leases)\n if (expectedLeaseId === undefined) continue\n if (!entry.isDirectory()) {\n throw new TypeError(`expired mutation entry must be a directory: ${entry.name}`)\n }\n\n const transactionDir = join(stagingRoot, entry.name)\n const journal = parseCanonicalJournal(transactionDir)\n assertTransactionName(transactionDir, journal)\n if (journal.leaseId !== expectedLeaseId) {\n throw new TypeError('mutation journal lease does not match its expired owner')\n }\n const bundleDir = join(dirname(stagingRoot), journal.bundleId)\n assertBundleLocation(knowledgeRoot, bundleDir, journal.bundleId)\n assertTargetsContained(knowledgeRoot, bundleDir,\n journal.replacements.map((replacement) => replacement.targetRelPath))\n applyJournal(bundleDir, transactionDir, journal)\n removeCompletedTransaction(transactionDir)\n recoveredBundleIds.push(journal.bundleId)\n }\n }\n\n return {\n mutationsRecovered: recoveredBundleIds.length,\n recoveredBundleIds,\n }\n}\n","// 2026-09-07 (418 D-11): the bundle half of the validity compare, as DATA. Reads only.\nimport { basename } from 'node:path'\n\nimport { distilledScreenStateDigest } from '@vostride/agent-qa-schema'\n\nimport { loadBundle, verifyBundleIntegrity } from './bundle-read.js'\nimport { enumerateBundleDirs } from './bundle-scan.js'\n\nexport type CanonicalBundleStateDigests =\n | { kind: 'found'; digests: string[] }\n | { kind: 'not-found' }\n\nexport function readCanonicalBundleStateDigests(input: {\n knowledgeRoot: string\n candidateId: string\n}): CanonicalBundleStateDigests {\n const found = enumerateBundleDirs(input.knowledgeRoot)\n .find(({ dir }) => basename(dir) === input.candidateId)\n if (found === undefined) return { kind: 'not-found' }\n const loaded = loadBundle(found.dir)\n if (loaded.kind !== 'loaded'\n || loaded.bundle.manifest.id !== input.candidateId\n || !verifyBundleIntegrity(found.dir).ok) return { kind: 'not-found' }\n return {\n kind: 'found',\n digests: loaded.bundle.screenStates.map((state) => distilledScreenStateDigest(state)),\n }\n}\n","import { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport type { KnowledgeHintReader } from '@vostride/agent-qa-runner'\nimport { wrapAppObservedData } from '@vostride/agent-qa-safety'\nimport {\n asRecordId,\n canonicalJson,\n EMPTY_PROCEDURE_BINDING_AVAILABILITY,\n isVettedCandidate,\n normalizeAnchor,\n slugBranch,\n strongestPromotionPath,\n type Anchor,\n type CanaryOutcome,\n type CautionBlock,\n type IndexEntry,\n type ReadOptions,\n type RecordBody,\n type RecordId,\n type ScopeKey,\n type ScreenState,\n type SearchOptions,\n type TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport {\n deriveBundleTrust,\n loadBundle,\n readGateReceipts,\n readMeasurements,\n verifyBundleIntegrity,\n type LoadedBundle,\n} from '../bundle-read.js'\nimport { enumerateBundleDirs } from '../bundle-scan.js'\nimport { enqueueCanaryOutcome } from '../canary-emit.js'\nimport {\n indexDbPath,\n openIndexReaderConnection,\n} from '../index-open.js'\nimport {\n openKnowledgeReader as openIndexKnowledgeReader,\n type KnowledgeReader,\n type OpenKnowledgeReaderOptions,\n} from '../index-reader.js'\nimport { assemblePromotionGateInput, snapshotTrustPriors } from '../promotion-gate-input.js'\nimport { scopeLadderPredicate } from '../retrieval/pre-filter.js'\nimport { effectivePriorDigest, indexTrustEpochMatches } from '../trust-prior-context.js'\nimport { selectCautions } from './get-cautions.js'\nimport { admitsProcedure, matchProcedure } from './get-procedure.js'\nimport { assembleRunBrief } from './get-run-brief.js'\nimport { readPolicyLadder } from './policy-ladder.js'\n\nconst DEFAULT_RECORD_CAP = 20\nconst CHARS_PER_TOKEN_ESTIMATE = 4\n\nexport interface OpenServingKnowledgeReaderConfig {\n knowledgeRoot: string\n /** Neutral host data, snapshotted when this reader is opened. */\n priors?: TrustPriorTable\n product?: string\n scopeDefaults?: {\n asOfBuild?: number\n /** Known containing scopes for member requests (for example, the owning suite). */\n parentScopes?: readonly ScopeKey[]\n }\n budgets?: { recordCap?: number }\n}\n\nexport interface IndexRow {\n bundle_id: string\n product: string\n scope_tier: string\n scope_key: string\n}\n\nexport interface HydratedEntry {\n dir: string\n bundle: LoadedBundle\n entry: IndexEntry\n}\n\ntype OriginStampedEntry = IndexEntry & {\n originClass: LoadedBundle['frontmatter']['originClass']\n}\n\n/** @deprecated The safe serving reader reports misses as `undefined` and never throws this. */\nexport class KnowledgeRecordNotFoundError extends Error {\n readonly recordId: RecordId\n\n constructor(recordId: RecordId) {\n super(`knowledge record not found: ${recordId}`)\n this.name = 'KnowledgeRecordNotFoundError'\n this.recordId = recordId\n }\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction normalizedRecordCap(config: OpenServingKnowledgeReaderConfig): number {\n const configured = config.budgets?.recordCap ?? DEFAULT_RECORD_CAP\n return Number.isFinite(configured) ? Math.max(0, Math.floor(configured)) : 0\n}\n\nfunction productSlug(config: OpenServingKnowledgeReaderConfig): string | undefined {\n return config.product === undefined ? undefined : slugBranch(config.product)\n}\n\n/** Shared serving internal: scope-laddered index rows (also feeds the authoring reader). */\nexport function readIndexRows(\n config: OpenServingKnowledgeReaderConfig,\n scope?: ScopeKey,\n): IndexRow[] {\n if (!existsSync(indexDbPath(config.knowledgeRoot))) return []\n\n const reader = openIndexReaderConnection(config.knowledgeRoot)\n try {\n reader.db.exec('BEGIN')\n const boundProduct = productSlug(config)\n const predicate = scopeLadderPredicate({\n ...(boundProduct === undefined ? {} : { productRow: boundProduct }),\n ...(config.product === undefined ? {} : { productScope: config.product }),\n ...(scope === undefined ? {} : { requestedScope: scope }),\n ...(config.scopeDefaults?.parentScopes === undefined\n ? {}\n : { parentScopes: config.scopeDefaults.parentScopes }),\n })\n // Pin eligibility before selection: rehydrating mismatched selected rows cannot recover\n // canonical bundles that another epoch's index omitted. Keep the shared SQL scope wall.\n if (!indexTrustEpochMatches(reader.db, effectivePriorDigest(config.priors))) {\n const admits = reader.db.prepare(`\n SELECT 1 FROM (SELECT ? AS product, ? AS scope_tier, ? AS scope_key) r\n WHERE ${predicate.sql}\n `)\n return enumerateBundleDirs(config.knowledgeRoot).flatMap(({ dir, product }) => {\n const loaded = loadBundle(dir)\n if (loaded.kind !== 'loaded' || !verifyBundleIntegrity(dir).ok) return []\n const { scope: bundleScope } = loaded.bundle.frontmatter\n if (admits.get(product, bundleScope.tier, bundleScope.key, ...predicate.binds) === undefined) {\n return []\n }\n return [{\n bundle_id: loaded.bundle.manifest.id,\n product,\n scope_tier: bundleScope.tier,\n scope_key: bundleScope.key,\n }]\n }).sort((left, right) => (\n compareText(left.product, right.product) || compareText(left.bundle_id, right.bundle_id)\n ))\n }\n return reader.db.prepare(`\n SELECT r.bundle_id, r.product, r.scope_tier, r.scope_key\n FROM records r\n WHERE ${predicate.sql}\n ORDER BY r.product, r.bundle_id\n `).all(...predicate.binds).map((row) => ({\n bundle_id: String(row.bundle_id),\n product: String(row.product),\n scope_tier: String(row.scope_tier),\n scope_key: String(row.scope_key),\n }))\n } finally {\n // Closing also releases the read transaction, including on hydration/selection failure.\n reader.db.close()\n }\n}\n\nfunction bundleDirs(config: OpenServingKnowledgeReaderConfig): Map<string, {\n dir: string\n product: string\n}> {\n return new Map(\n enumerateBundleDirs(config.knowledgeRoot).map(({ dir, product }) => [\n basename(dir),\n { dir, product },\n ]),\n )\n}\n\n/** Shared serving internal: integrity-checked bundle hydration (also feeds the authoring reader). */\nexport function hydrateRows(\n config: OpenServingKnowledgeReaderConfig,\n rows: readonly IndexRow[],\n audit: boolean,\n): HydratedEntry[] {\n const dirs = bundleDirs(config)\n return rows.flatMap((row): HydratedEntry[] => {\n const found = dirs.get(row.bundle_id)\n if (found === undefined || found.product !== row.product) return []\n const loaded = loadBundle(found.dir)\n if (loaded.kind !== 'loaded' || !verifyBundleIntegrity(found.dir).ok) return []\n\n const { bundle } = loaded\n const trust = deriveBundleTrust(bundle, config.priors)\n const vetted = trust.status === 'candidate' && isVettedCandidate(\n assemblePromotionGateInput({\n knowledgeRoot: config.knowledgeRoot,\n bundleDir: found.dir,\n bundle,\n priors: config.priors,\n }),\n )\n // 2026-09-08, 418 D-15/D-16: offline-only actives keep attracting live credit.\n const lowerTrust = trust.status === 'active'\n && strongestPromotionPath(readGateReceipts(found.dir, bundle.manifest.id) ?? []) === 'gate1-lower-trust'\n const entry: OriginStampedEntry = {\n id: asRecordId(bundle.manifest.id),\n kind: bundle.frontmatter.kind,\n ...(bundle.frontmatter.subtype === undefined\n ? {}\n : { subtype: bundle.frontmatter.subtype }),\n title: bundle.summary,\n summary: bundle.summary,\n trust: trust.trust,\n anchors: bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n status: trust.status,\n servedAsCanary: vetted || lowerTrust,\n ...(lowerTrust ? { lowerTrust: true as const } : {}),\n ...(vetted ? { unverified: true } : {}),\n ...(audit\n ? {\n audit: {\n status: trust.status,\n openedAtOrdinal: trust.validity.openedAtOrdinal,\n closedAtOrdinal: trust.validity.closedAtOrdinal ?? null,\n },\n }\n : {}),\n scope: bundle.frontmatter.scope,\n validity: trust.validity.closedAtOrdinal === undefined\n ? 'current'\n : `${trust.validity.openedAtOrdinal}:${trust.validity.closedAtOrdinal}`,\n originClass: bundle.frontmatter.originClass,\n }\n return [{ dir: found.dir, bundle, entry }]\n })\n}\n\nfunction currentServingEntries(entries: readonly HydratedEntry[]): IndexEntry[] {\n return entries.flatMap(({ entry }) => {\n if (entry.kind === 'policy') return []\n if (entry.status === 'active') return [entry]\n return entry.status === 'candidate' && entry.unverified === true ? [entry] : []\n })\n}\n\nfunction normalizedAnchorKey(anchor: Anchor): string {\n return canonicalJson(normalizeAnchor(anchor))\n}\n\n/**\n * Derive the current page anchors from a live ScreenState for procedure matching. Both authored\n * page-anchor shapes are covered: the full-URL form (the failure-caution derivation idiom) and\n * the route-path form (committed procedure guard descriptors carry routes like '/login'). Every\n * derived anchor goes through the one normalizeAnchor authority.\n */\nfunction screenStatePageAnchors(screenState: ScreenState): Anchor[] {\n if (screenState.url === undefined || screenState.url.trim() === '') return []\n const anchors: Anchor[] = [normalizeAnchor({ t: 'page', route: screenState.url })]\n try {\n const parsed = new URL(screenState.url)\n anchors.push(normalizeAnchor({ t: 'page', route: `${parsed.pathname}${parsed.search}` }))\n } catch {\n // Non-URL routes stay as the single raw-form anchor.\n }\n return anchors\n}\n\nfunction anchorMatches(entry: IndexEntry, anchors: readonly Anchor[]): boolean {\n if (anchors.length === 0) return false\n const requested = new Set(anchors.map(normalizedAnchorKey))\n return entry.anchors.some((anchor) => requested.has(normalizedAnchorKey(anchor)))\n}\n\nfunction lexicalMatches(bundle: LoadedBundle, query: string): boolean {\n const tokens = query.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []\n if (tokens.length === 0) return false\n const text = [\n bundle.summary,\n bundle.body,\n bundle.manifest.embeddingInput,\n ...bundle.frontmatter.anchors.map(({ normalized }) => canonicalJson(normalized)),\n ].join('\\n').toLowerCase()\n return tokens.every((token) => text.includes(token))\n}\n\nfunction overlapsRange(\n openedAtOrdinal: number,\n closedAtOrdinal: number | undefined,\n range: NonNullable<SearchOptions['asOfRange']>,\n): boolean {\n const from = range.from ?? Number.NEGATIVE_INFINITY\n const to = range.to ?? Number.POSITIVE_INFINITY\n return openedAtOrdinal <= to && (closedAtOrdinal === undefined || closedAtOrdinal > from)\n}\n\nfunction validAtBuild(\n openedAtOrdinal: number,\n closedAtOrdinal: number | undefined,\n buildOrdinal: number,\n): boolean {\n return openedAtOrdinal <= buildOrdinal\n && (closedAtOrdinal === undefined || buildOrdinal < closedAtOrdinal)\n}\n\nfunction searchEntries(\n config: OpenServingKnowledgeReaderConfig,\n query: string,\n options: SearchOptions,\n): IndexEntry[] {\n const anchors = options.anchors ?? []\n if (query.trim() === '' && anchors.length === 0) return []\n\n const auditMode = options.includeSuperseded === true || options.asOfRange !== undefined\n const hydrated = hydrateRows(config, readIndexRows(config, options.scope), auditMode)\n return hydrated\n .filter(({ bundle, entry }) => (\n lexicalMatches(bundle, query) || anchorMatches(entry, anchors)\n ))\n .filter(({ bundle, entry }) => {\n if (entry.kind === 'policy') return false\n if (options.kind !== undefined && entry.kind !== options.kind) return false\n if (entry.status === 'candidate') {\n return options.includeCandidates === true && entry.unverified === true\n }\n if (\n !auditMode\n && (entry.status === 'deprecated' || entry.status === 'superseded')\n ) {\n return false\n }\n const trust = deriveBundleTrust(bundle, config.priors)\n if (\n options.asOfBuild !== undefined\n && !validAtBuild(\n trust.validity.openedAtOrdinal,\n trust.validity.closedAtOrdinal,\n options.asOfBuild,\n )\n ) {\n return false\n }\n return options.asOfRange === undefined || overlapsRange(\n trust.validity.openedAtOrdinal,\n trust.validity.closedAtOrdinal,\n options.asOfRange,\n )\n })\n .map(({ bundle, entry }): IndexEntry => {\n const appObserved = bundle.frontmatter.originClass === 'agent-observed'\n return {\n ...entry,\n summary: appObserved ? wrapAppObservedData(entry.summary) : entry.summary,\n ...(options.asOfBuild !== undefined && entry.status !== 'active'\n ? { servedAs: 'prior-build-hypothesis' as const }\n : {}),\n }\n })\n .sort((left, right) => (\n Number(anchorMatches(right, anchors)) - Number(anchorMatches(left, anchors))\n || right.trust - left.trust\n || compareText(String(left.id), String(right.id))\n ))\n}\n\nfunction findReadableBundle(\n config: OpenServingKnowledgeReaderConfig,\n id: RecordId,\n options?: ReadOptions,\n): { dir: string; bundle: LoadedBundle } | undefined {\n const row = readIndexRows(config, options?.scope)\n .find(({ bundle_id }) => bundle_id === id)\n if (row === undefined) return undefined\n\n const hydrated = hydrateRows(config, [row], false)[0]\n if (hydrated === undefined) return undefined\n /**\n * G-381-4: `currentServingEntries` is the BRIEF/CAUTION serving wall — it admits candidates\n * only through the vetted-canary flag, which is fact/caution-only, so a committed procedure\n * (agent-verified candidate, promotion-excluded in M2 by 379 D-16) was permanently unreadable\n * even when `getProcedure` had just recommended replaying it. The read face therefore falls\n * back to the matcher's OWN admission predicate: what getProcedure can recommend, read() can\n * serve. This is read admission only — `currentServingEntries` is untouched, so nothing new\n * reaches getRunBrief, getCautions, or search.\n */\n if (\n currentServingEntries([hydrated]).length === 0\n && !admitsProcedure({ entry: hydrated.entry, bundle: hydrated.bundle })\n ) {\n return undefined\n }\n\n const trust = deriveBundleTrust(hydrated.bundle, config.priors)\n const asOfBuild = options?.asOfBuild ?? config.scopeDefaults?.asOfBuild\n if (\n asOfBuild !== undefined\n && !validAtBuild(\n trust.validity.openedAtOrdinal,\n trust.validity.closedAtOrdinal,\n asOfBuild,\n )\n ) {\n return undefined\n }\n return { dir: hydrated.dir, bundle: hydrated.bundle }\n}\n\nfunction estimatedBodyCost(body: string): number {\n return Math.ceil(body.length / CHARS_PER_TOKEN_ESTIMATE)\n}\n\nfunction renderedBody(body: string, appObserved: boolean): string {\n return appObserved ? wrapAppObservedData(body) : body\n}\n\nfunction truncateBody(\n body: string,\n appObserved: boolean,\n budget: number | undefined,\n): string {\n if (budget === undefined) return renderedBody(body, appObserved)\n const limit = Number.isFinite(budget) ? Math.max(0, Math.floor(budget)) : 0\n const whole = renderedBody(body, appObserved)\n if (estimatedBodyCost(whole) <= limit) return whole\n\n const admitted: string[] = []\n for (const line of body.split('\\n')) {\n const candidate = renderedBody([...admitted, line].join('\\n'), appObserved)\n if (estimatedBodyCost(candidate) > limit) break\n admitted.push(line)\n }\n if (admitted.length === 0) return ''\n return renderedBody(admitted.join('\\n'), appObserved)\n}\n\nfunction readRecord(\n config: OpenServingKnowledgeReaderConfig,\n id: RecordId,\n options?: ReadOptions,\n): RecordBody | undefined {\n const found = findReadableBundle(config, id, options)\n if (found === undefined) return undefined\n\n const { bundle } = found\n const measurements = readMeasurements(found.dir)\n return {\n id: asRecordId(bundle.manifest.id),\n title: bundle.summary,\n body: truncateBody(\n bundle.body,\n bundle.frontmatter.originClass === 'agent-observed',\n options?.budget,\n ),\n anchors: bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n evidenceDigest: bundle.manifest.contentHashes['evidence/evidence.md']\n ?? bundle.manifest.contentHashes['record.md']\n ?? bundle.manifest.identityHash,\n ...(measurements === undefined\n ? {}\n : { measurement: canonicalJson(measurements) }),\n relations: bundle.relations.relations.map((relation) => ({\n kind: relation.type,\n targetId: asRecordId(relation.targetId),\n })),\n }\n}\n\nfunction servingReader(\n config: OpenServingKnowledgeReaderConfig,\n): KnowledgeHintReader {\n return {\n getRunBrief(scope, budget) {\n const entries = currentServingEntries(\n hydrateRows(config, readIndexRows(config, scope), true),\n )\n // D-16: the composite is returned verbatim. The reader does not unwrap and re-wrap it,\n // so there is no point in this path at which a brief exists without its trace.\n return assembleRunBrief({\n candidates: entries,\n policy: readPolicyLadder(config.knowledgeRoot, config.product),\n scope,\n budget,\n recordCap: normalizedRecordCap(config),\n ...(config.scopeDefaults?.asOfBuild === undefined\n ? {}\n : { asOfBuild: config.scopeDefaults.asOfBuild }),\n })\n },\n\n search(query, options) {\n return searchEntries(config, query, options)\n },\n\n read(id, options) {\n return readRecord(config, id, options)\n },\n\n getCautions(anchors, budget) {\n const selected = selectCautions({\n candidates: currentServingEntries(\n hydrateRows(config, readIndexRows(config), false),\n ),\n anchors,\n budget,\n recordCap: normalizedRecordCap(config),\n })\n if (selected.overflow === undefined) {\n return { block: selected.block, trace: selected.trace }\n }\n\n /**\n * Reserved terminal id: consumers must display this cap signal but skip it for ledger\n * admission because it is not a committed knowledge record. It gets no trace line for the\n * same reason: it names no record, so there is nothing to attribute. The cut cautions it\n * summarizes are already enumerated individually in the trace's truncation ledger.\n */\n const overflowLine: CautionBlock['cautions'][number] = {\n id: asRecordId('caution:truncated'),\n anchors: [],\n summary: `truncated ${selected.overflow.served} of ${selected.overflow.eligible}`,\n }\n return {\n block: {\n ...selected.block,\n cautions: [...selected.block.cautions, overflowLine],\n },\n trace: selected.trace,\n }\n },\n\n getProcedure(intent, screenState, availability) {\n return matchProcedure({\n entries: hydrateRows(config, readIndexRows(config), false),\n intent,\n anchors: screenStatePageAnchors(screenState),\n availability: availability ?? EMPTY_PROCEDURE_BINDING_AVAILABILITY,\n })\n },\n\n emitCanaryOutcome(payload: CanaryOutcome) {\n // D-20: one synchronous, atomic, content-addressed emit pattern.\n enqueueCanaryOutcome(config.knowledgeRoot, payload)\n },\n }\n}\n\nexport function openKnowledgeReader(\n config: OpenServingKnowledgeReaderConfig,\n): KnowledgeHintReader\nexport function openKnowledgeReader(\n knowledgeRoot: string,\n opts?: OpenKnowledgeReaderOptions,\n): KnowledgeReader\nexport function openKnowledgeReader(\n configOrKnowledgeRoot: OpenServingKnowledgeReaderConfig | string,\n opts?: OpenKnowledgeReaderOptions,\n): KnowledgeHintReader | KnowledgeReader {\n // Preserve the established low-level index-reader overload while the new object form is the\n // KnowledgeHintReader composition seam used by the runner.\n return typeof configOrKnowledgeRoot === 'string'\n ? openIndexKnowledgeReader(configOrKnowledgeRoot, opts)\n : servingReader({ ...configOrKnowledgeRoot, priors: snapshotTrustPriors(configOrKnowledgeRoot.priors) })\n}\n","import {\n canonicalJson,\n createServingAdmissionState,\n normalizeAnchor,\n servingRecordMetadata,\n tryAdmitServingRecord,\n type Anchor,\n type CautionBlock,\n type IndexEntry,\n type ServedRetrievalTraceV1,\n type TraceLine,\n} from '@vostride/agent-qa-schema'\n\nimport { compareServingTrustThenId } from './brief-selection.js'\nimport { renderCautionLine } from './brief-render.js'\nimport {\n CHANNEL_3_CAUTION_LEG,\n composeServedTrace,\n traceLine,\n} from './serve-trace.js'\n\nexport interface CautionSelectionOverflow {\n served: number\n eligible: number\n}\n\nexport interface CautionSelectionResult {\n block: CautionBlock\n overflow?: CautionSelectionOverflow\n /**\n * The serve-time trace for this Channel-3 selection (D-16). Produced as part of selecting, not\n * as a second pass over the result: `rank` is the position in the ranking below and `score` is\n * the trust value that ranking ordered by after the anchor-match priority.\n */\n trace: ServedRetrievalTraceV1\n}\n\nexport interface SelectCautionsInput {\n readonly candidates: readonly IndexEntry[]\n readonly anchors: readonly Anchor[]\n readonly budget: number\n readonly recordCap?: number\n}\n\ninterface RankedCaution {\n readonly record: IndexEntry\n readonly matchPriority: number\n readonly summary: string\n readonly cost: number\n}\n\nconst MATCH_PRIORITY: Readonly<Partial<Record<Anchor['t'], number>>> = {\n el: 0,\n page: 1,\n flow: 2,\n}\n\nfunction normalizedAnchorKey(anchor: Anchor): string {\n return canonicalJson(normalizeAnchor(anchor))\n}\n\nfunction queryPriorities(anchors: readonly Anchor[]): Map<string, number> {\n const priorities = new Map<string, number>()\n\n for (const anchor of anchors) {\n const priority = MATCH_PRIORITY[anchor.t]\n if (priority === undefined) continue\n const key = normalizedAnchorKey(anchor)\n priorities.set(key, Math.min(priority, priorities.get(key) ?? priority))\n }\n\n return priorities\n}\n\nfunction bestMatchPriority(\n anchors: readonly Anchor[],\n priorities: ReadonlyMap<string, number>,\n): number | undefined {\n let best: number | undefined\n\n for (const anchor of anchors) {\n const priority = priorities.get(normalizedAnchorKey(anchor))\n if (priority !== undefined) best = Math.min(best ?? priority, priority)\n }\n\n return best\n}\n\nfunction isEligibleCaution(record: IndexEntry): boolean {\n if (record.kind !== 'caution') return false\n if (record.status === 'active') return true\n return record.status === 'candidate' && record.unverified === true\n}\n\nfunction rankedCautions(input: SelectCautionsInput): RankedCaution[] {\n const priorities = queryPriorities(input.anchors)\n\n return input.candidates\n .flatMap((record): RankedCaution[] => {\n if (!isEligibleCaution(record)) return []\n const matchPriority = bestMatchPriority(record.anchors, priorities)\n if (matchPriority === undefined) return []\n const rendered = renderCautionLine(record)\n return [{\n record,\n matchPriority,\n summary: rendered.summary,\n cost: rendered.cost,\n }]\n })\n .sort((left, right) => (\n left.matchPriority - right.matchPriority\n || compareServingTrustThenId(left.record, right.record)\n ))\n}\n\n/**\n * Select automatic Channel-3 cautions without consulting Channel-1 membership. D-16 deliberately\n * re-surfaces an L1 caution at the failure moment; dedup against the frozen brief does not belong\n * at this selection site.\n */\nexport function selectCautions(input: SelectCautionsInput): CautionSelectionResult {\n const ranked = rankedCautions(input)\n const recordCap = input.recordCap ?? ranked.length\n const admission = createServingAdmissionState()\n const cautions: CautionBlock['cautions'] = []\n const admissions: CautionBlock['admissions'] = []\n const servedLines: TraceLine[] = []\n const truncated: TraceLine[] = []\n\n for (const [index, candidate] of ranked.entries()) {\n const metadata = servingRecordMetadata({\n id: candidate.record.id,\n anchors: candidate.record.anchors,\n renderedCost: candidate.cost,\n })\n /**\n * D-16: the trace records the ONE ranking this loop walks. `rank` is that position; `score`\n * is the trust the ranking ordered by within an anchor-match priority band, so a caution and\n * a cut caution report the same quantity. The band itself is not a score and is deliberately\n * not flattened into one — the rank already carries it.\n */\n const line = traceLine({\n recordId: String(candidate.record.id),\n leg: CHANNEL_3_CAUTION_LEG,\n rank: index + 1,\n score: candidate.record.trust,\n })\n if (!tryAdmitServingRecord({\n record: metadata,\n budget: input.budget,\n recordCap,\n }, admission).admitted) {\n truncated.push(line)\n continue\n }\n\n cautions.push({\n id: candidate.record.id,\n anchors: candidate.record.anchors,\n summary: candidate.summary,\n })\n admissions.push(metadata)\n servedLines.push(line)\n }\n\n const block: CautionBlock = { cautions, budgetUsed: admission.usedBudget, admissions }\n const trace = composeServedTrace({ servedLines, truncated })\n return cautions.length < ranked.length\n ? { block, overflow: { served: cautions.length, eligible: ranked.length }, trace }\n : { block, trace }\n}\n","import {\n applyColdStartSubCap,\n createServingAdmissionState,\n isVettedCandidate,\n normalizeAnchor,\n servingRecordMetadata,\n tryAdmitServingRecord,\n type Anchor,\n type IndexEntry,\n type ScopeKey,\n type ServingRecordMetadata,\n type VettedCandidateInput,\n} from '@vostride/agent-qa-schema'\n\nimport {\n preFilterPredicate,\n type PreFilterOptions,\n} from '../retrieval/pre-filter.js'\nimport {\n applyDiversityCaps,\n applyLifecycleTrustTreatments,\n rerankPrecedence,\n type RerankEntry,\n type ValidityClass,\n} from '../retrieval/rerank.js'\nimport {\n applyValidity,\n resolveAsOfBuild,\n type ValidityCandidate,\n} from '../retrieval/validity.js'\nimport { renderBriefLine } from './brief-render.js'\n\nexport interface ServingTierFilter extends PreFilterOptions {}\n\nexport interface SelectServingRecordsInput {\n readonly candidates: readonly IndexEntry[]\n readonly scope: ScopeKey\n readonly channelBudget: number\n readonly recordCap: number\n readonly asOfBuild?: number\n /** Canonical §5.5.1 product/scope material when the loaded set spans more than one tier. */\n readonly tier?: ServingTierFilter\n /** Raw schema inputs are optional because an IndexEntry may already carry derived `unverified`. */\n readonly candidateVetting?: Readonly<Record<string, VettedCandidateInput>>\n}\n\ninterface TemporalServingCandidate extends ValidityCandidate {\n readonly record: IndexEntry\n readonly vettedCandidateInput?: VettedCandidateInput\n}\n\ninterface RankedServingCandidate extends TemporalServingCandidate, RerankEntry {\n readonly record: IndexEntry\n}\n\ninterface CostedServingCandidate extends RankedServingCandidate {\n readonly tokenEstimate: number\n}\n\ninterface ScoredServingCandidate {\n readonly candidate: CostedServingCandidate\n readonly score: number\n}\n\nconst KIND_PRECEDENCE: Readonly<Record<string, number>> = {\n caution: 0,\n procedure: 1,\n fact: 2,\n}\n\nfunction normalizeLimit(value: number): number {\n return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0\n}\n\nexport function compareServingRecordIds(left: IndexEntry, right: IndexEntry): number {\n const leftId = String(left.id)\n const rightId = String(right.id)\n return leftId < rightId ? -1 : leftId > rightId ? 1 : 0\n}\n\nfunction servingTrust(entry: IndexEntry): number {\n return Number.isFinite(entry.trust) ? Math.max(0, entry.trust) : 0\n}\n\nexport function compareServingTrustThenId(left: IndexEntry, right: IndexEntry): number {\n return servingTrust(right) - servingTrust(left) || compareServingRecordIds(left, right)\n}\n\nfunction normalizedAnchorText(anchor: Anchor): string {\n const normalized = normalizeAnchor(anchor)\n switch (normalized.t) {\n case 'page':\n return normalized.route\n case 'flow':\n return normalized.name\n case 'el':\n return `${normalized.role} ${normalized.name}`\n case 'platform':\n return normalized.platform\n case 'selector':\n return normalized.literal\n case 'error':\n return normalized.message\n }\n}\n\nfunction affinityTokens(value: string): Set<string> {\n return new Set(value.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [])\n}\n\n/**\n * PROVISIONAL §10 scope affinity: one baseline point plus the largest normalized anchor-token\n * overlap with the scope key. M3 may calibrate weights, not its deterministic/no-model posture.\n */\nfunction anchorMatch(anchors: readonly Anchor[], scope: ScopeKey): number {\n const scopeTokens = affinityTokens(scope.key)\n let bestOverlap = 0\n\n for (const anchor of anchors) {\n const anchorTokens = affinityTokens(normalizedAnchorText(anchor))\n let overlap = 0\n for (const token of anchorTokens) {\n if (scopeTokens.has(token)) overlap += 1\n }\n bestOverlap = Math.max(bestOverlap, overlap)\n }\n\n return 1 + bestOverlap\n}\n\nfunction candidateVetting(\n input: SelectServingRecordsInput,\n candidate: IndexEntry,\n): VettedCandidateInput | undefined {\n return input.candidateVetting?.[String(candidate.id)]\n}\n\nfunction isEligibleCandidate(\n input: SelectServingRecordsInput,\n candidate: IndexEntry,\n): boolean {\n if (candidate.status !== 'candidate') return candidate.status === 'active'\n\n const vetting = candidateVetting(input, candidate)\n if (vetting !== undefined) return isVettedCandidate(vetting)\n\n // `unverified` is the read-side projection of that same schema predicate. Keep the schema's\n // fact/caution boundary explicit so a malformed IndexEntry cannot widen the canary channel.\n return candidate.unverified === true\n && (candidate.kind === 'fact' || candidate.kind === 'caution')\n}\n\nfunction preFilter(\n input: SelectServingRecordsInput,\n): IndexEntry[] {\n const material: PreFilterOptions = input.tier ?? {\n product: '',\n testKey: input.scope.key,\n suiteKey: input.scope.key,\n productKey: input.scope.key,\n globalKey: input.scope.key,\n }\n const predicate = preFilterPredicate(material)\n const admittedScopeKeys = new Set(predicate.binds.slice(1))\n\n return input.candidates.filter((candidate) => {\n // D-08: a rule is either sovereign or it is not yet a rule.\n if (candidate.kind === 'policy') return false\n if (\n material.includeSuperseded !== true\n && (candidate.status === 'deprecated' || candidate.status === 'superseded')\n ) {\n return false\n }\n if (input.tier !== undefined && !admittedScopeKeys.has(candidate.scope.key)) return false\n return isEligibleCandidate(input, candidate)\n })\n}\n\nfunction temporalCandidate(\n input: SelectServingRecordsInput,\n record: IndexEntry,\n product: string,\n): TemporalServingCandidate {\n const openedAtOrdinal = record.audit?.openedAtOrdinal ?? 0\n const closedAtOrdinal = record.audit?.closedAtOrdinal ?? null\n const vetting = candidateVetting(input, record)\n\n return {\n bundleId: String(record.id),\n anchors: record.anchors,\n openedAtOrdinal,\n closedAtOrdinal,\n createdAtOrdinal: openedAtOrdinal,\n status: record.status,\n product,\n record,\n ...(vetting === undefined ? {} : { vettedCandidateInput: vetting }),\n }\n}\n\nfunction validityClass(\n candidate: TemporalServingCandidate & { servedAs?: IndexEntry['servedAs'] },\n): ValidityClass {\n return candidate.servedAs === 'prior-build-hypothesis'\n ? 'priorBuildHypothesis'\n : 'current'\n}\n\nfunction rankedCandidate(\n candidate: TemporalServingCandidate & { servedAs?: IndexEntry['servedAs'] },\n): RankedServingCandidate {\n const lastConfirmedOrdinal = candidate.record.unconfirmedSinceOrdinal\n ?? candidate.openedAtOrdinal\n const originClass = candidate.vettedCandidateInput?.originClass === 'user'\n ? 'user' as const\n : 'agent' as const\n\n return {\n ...candidate,\n validityClass: validityClass(candidate),\n trust: candidate.record.trust,\n scope: candidate.record.scope,\n recencyOrdinal: candidate.createdAtOrdinal,\n originClass,\n subtype: candidate.record.subtype ?? null,\n lastConfirmedOrdinal,\n ...(candidate.record.unconfirmedSinceOrdinal === undefined\n ? {}\n : { unconfirmedSinceOrdinal: candidate.record.unconfirmedSinceOrdinal }),\n ...(candidate.record.unverified === true ? { unverified: true } : {}),\n ...(candidate.record.lowerTrust === true ? { lowerTrust: true as const } : {}),\n ...(candidate.record.conflict === undefined ? {} : { conflict: candidate.record.conflict }),\n }\n}\n\nfunction reflectedRecord(candidate: RankedServingCandidate): IndexEntry {\n const { record } = candidate\n return {\n ...record,\n trust: candidate.trust,\n ...(candidate.unconfirmedSinceOrdinal === undefined\n ? {}\n : { unconfirmedSinceOrdinal: candidate.unconfirmedSinceOrdinal }),\n ...(candidate.unverified === true ? { unverified: true } : {}),\n }\n}\n\nfunction kindPrecedence(kind: string): number {\n return KIND_PRECEDENCE[kind] ?? 3\n}\n\nfunction compareScored(\n left: ScoredServingCandidate,\n right: ScoredServingCandidate,\n): number {\n return (\n kindPrecedence(left.candidate.record.kind) - kindPrecedence(right.candidate.record.kind)\n || right.score - left.score\n // PROVISIONAL deterministic tie-break; M3 may retune scoring, never input-order dependence.\n || compareServingRecordIds(left.candidate.record, right.candidate.record)\n )\n}\n\nfunction scoreCandidates(\n candidates: readonly CostedServingCandidate[],\n scope: ScopeKey,\n): ScoredServingCandidate[] {\n return candidates\n .map((candidate) => ({\n candidate,\n score: (Number.isFinite(candidate.trust) ? Math.max(0, candidate.trust) : 0)\n * anchorMatch(candidate.anchors, scope),\n }))\n .sort(compareScored)\n}\n\nfunction stageCandidates(\n input: SelectServingRecordsInput,\n channelBudget: number,\n): ScoredServingCandidate[] {\n const product = input.tier?.product ?? ''\n const temporal = preFilter(input).map((record) => temporalCandidate(input, record, product))\n const resolvedAsOf = resolveAsOfBuild({\n product,\n candidates: temporal,\n ...(input.asOfBuild === undefined ? {} : { asOfBuild: input.asOfBuild }),\n })\n const valid = applyValidity(temporal, resolvedAsOf).map(rankedCandidate)\n const treated = resolvedAsOf === undefined\n ? valid\n : applyLifecycleTrustTreatments(valid, resolvedAsOf).map((candidate) => (\n candidate.record.unverified === true && candidate.unverified !== true\n ? { ...candidate, unverified: true as const }\n : candidate\n ))\n const costed: CostedServingCandidate[] = treated.map((candidate) => ({\n ...candidate,\n tokenEstimate: renderBriefLine(reflectedRecord(candidate)).cost,\n }))\n const reranked = applyDiversityCaps(rerankPrecedence(costed))\n const scored = scoreCandidates(reranked, input.scope)\n const vetted = scored.filter(({ candidate }) => candidate.unverified === true)\n const admittedVetted = new Set(\n applyColdStartSubCap(\n vetted.map(({ candidate }) => candidate),\n channelBudget,\n ).map(({ bundleId }) => bundleId),\n )\n\n return scored\n .filter(({ candidate }) => candidate.unverified !== true || admittedVetted.has(candidate.bundleId))\n .sort(compareScored)\n}\n\n/**\n * One selected record together with the two facts the selection ALREADY computed about it:\n * the score it was ordered by and its 1-based position in that order (KREV-02 · D-13/D-14).\n *\n * These are not new quantities. `score` is exactly what `scoreCandidates` produced and\n * `compareScored` ordered by; `rank` is the position that order put the record in. The serve-time\n * trace needs both, and re-deriving them at a later moment would answer about *now* — the precise\n * dishonesty KREV-02 exists to prevent. So the selection surfaces what it knew instead.\n */\nexport interface ServingSelectionEntry {\n readonly record: IndexEntry\n readonly score: number\n /** 1-based, matching the retrieval legs' own `index + 1` convention. */\n readonly rank: number\n}\n\n/**\n * Pure Channel-1/Channel-3 selection over already-loaded records, with the selection's own\n * provenance retained. Retrieval legs, fusion, models, and persistence stay outside this\n * assembly floor.\n *\n * This is the ONE selection pass. {@link selectServingRecords} is a projection of it, so a caller\n * that wants both records and provenance never runs the selection twice.\n */\nexport function selectServingRecordsWithProvenance(\n input: SelectServingRecordsInput,\n): ServingSelectionEntry[] {\n const channelBudget = normalizeLimit(input.channelBudget)\n const recordCap = normalizeLimit(input.recordCap)\n if (channelBudget === 0 || recordCap === 0 || input.candidates.length === 0) return []\n\n const selected: ServingSelectionEntry[] = []\n const admission = createServingAdmissionState()\n\n for (const { candidate, score } of stageCandidates(input, channelBudget)) {\n if (admission.selectedCount >= recordCap) break\n const record = reflectedRecord(candidate)\n const metadata: ServingRecordMetadata = servingRecordMetadata({\n id: record.id,\n anchors: record.anchors,\n renderedCost: candidate.tokenEstimate,\n })\n if (!tryAdmitServingRecord({\n record: metadata,\n budget: channelBudget,\n recordCap,\n }, admission).admitted) continue\n\n selected.push({ record, score, rank: selected.length + 1 })\n }\n\n return selected\n}\n\n/**\n * Pure Channel-1/Channel-3 selection over already-loaded records. Retrieval legs, fusion, models,\n * and persistence stay outside this assembly floor.\n */\nexport function selectServingRecords(input: SelectServingRecordsInput): IndexEntry[] {\n return selectServingRecordsWithProvenance(input).map(({ record }) => record)\n}\n","// D-08: the shared brief renderer lives in runner.\n// Keep knowledge-local's serving import paths stable through these re-exports.\nexport {\n CHARS_PER_TOKEN_ESTIMATE,\n estimateRenderedServingCost,\n renderBriefLine,\n renderCautionLine,\n renderCautionSummary,\n} from '@vostride/agent-qa-runner'\nexport type { RenderedCautionLine } from '@vostride/agent-qa-runner'\n","// Serve-time trace composition for the four serving channels (Phase 387, KREV-02 · D-13/D-14/D-16).\n//\n// D-16 makes producing a trace inseparable from serving: every serving entry returns brief and\n// trace as ONE value, so no code path can hand a caller a brief while quietly discarding how it\n// was chosen. This module owns the two small decisions that composition needs — which leg a\n// channel's ranking attributes to, and how the truncation ledger is bounded — so those decisions\n// live in one place with their reasoning rather than being restated per channel.\n//\n// LEG ATTRIBUTION, STATED HONESTLY. The trace's leg vocabulary is the RETRIEVAL vocabulary, and\n// the run-brief/caution assemblies do NOT run the retrieval legs: Channel 1 orders candidates by\n// `trust x anchorMatch(anchors, scope)` and Channel 3 admits a caution only when one of its\n// anchors matches the failure anchors. In both, the ONLY query-shaped signal is anchor overlap —\n// no FTS scan and no embedding participates. `anchor` is therefore what actually put a line in\n// those channels, and naming any other leg would be a fabricated attribution in exactly the place\n// KREV-02 exists to make honest. The authoring channel is different: its relevance really is a\n// weighted sum of an anchor term, a lexical term and an optional dense term, so it attributes per\n// line to whichever term contributed most (see `dominantAuthoringLeg`).\nimport {\n RETRIEVAL_TRACE_LEGS,\n RETRIEVAL_TRACE_SCHEMA_VERSION,\n TRACE_TRUNCATION_TOP_K,\n type RetrievalTraceLeg,\n type ServedRetrievalTraceV1,\n type TraceLine,\n} from '@vostride/agent-qa-schema'\n\n/**\n * The leg Channel-1 run-brief assembly attributes to. See the module header: the assembly's whole\n * ordering signal is the scope/anchor token overlap, so this is a statement about the code that\n * ranks, not a default.\n */\nexport const CHANNEL_1_SERVING_LEG: RetrievalTraceLeg = 'anchor'\n\n/**\n * The leg Channel-3 caution selection attributes to. Unambiguous here: a caution with no matching\n * anchor is dropped before it is ever ranked.\n */\nexport const CHANNEL_3_CAUTION_LEG: RetrievalTraceLeg = 'anchor'\n\n/**\n * Fixed precedence for a tie between authoring relevance terms. Anchor overlap is the authoring\n * assembly's primary signal and the lexical term is explicitly secondary and additive, so an\n * exact tie resolves toward the stronger claim rather than toward whichever term the loop\n * happened to visit last.\n */\nconst AUTHORING_LEG_PRECEDENCE: readonly RetrievalTraceLeg[] = ['anchor', 'lexical', 'dense']\n\n/**\n * The leg that contributed most to one authoring relevance value. Contributions arrive ALREADY\n * weighted — the caller passes the same products it summed into relevance, so this reads the\n * decomposition of a number that was actually computed rather than recomputing a second one.\n */\nexport function dominantAuthoringLeg(\n contributions: Readonly<Record<RetrievalTraceLeg, number>>,\n): RetrievalTraceLeg {\n let best = AUTHORING_LEG_PRECEDENCE[0]!\n for (const leg of AUTHORING_LEG_PRECEDENCE) {\n if (contributions[leg] > contributions[best]) best = leg\n }\n return best\n}\n\n/**\n * A score that the persistence boundary will accept. `TraceLineSchema` requires a finite number,\n * and the load boundary validates a PRESENT trace, so one non-finite score would make an entire\n * run handoff unloadable rather than degrading a single attribution. A non-finite ranking score\n * cannot occur through the current selection paths (every input is finite-guarded upstream); this\n * keeps that a local property of this module instead of an inherited assumption.\n */\nfunction finiteScore(value: number): number {\n return Number.isFinite(value) ? value : 0\n}\n\n/** Build one attributed trace line, normalizing rank to the schema's 1-based positive contract. */\nexport function traceLine(input: {\n recordId: string\n leg: RetrievalTraceLeg\n rank: number\n score: number\n}): TraceLine {\n return {\n recordId: input.recordId,\n leg: input.leg,\n rank: Math.max(1, Math.floor(input.rank)),\n score: finiteScore(input.score),\n }\n}\n\n/**\n * Bound the truncation ledger at the pinned top-K (D-14). The cut set is unbounded in principle;\n * the ledger keeps the highest-ranked cuts because those are the ones a \"why didn't it mention X\"\n * question is actually asked about. Input order IS rank order at every call site, so this keeps a\n * prefix rather than re-sorting a ranking somebody else produced.\n */\nexport function boundTruncationLedger(lines: readonly TraceLine[]): TraceLine[] {\n return lines.slice(0, TRACE_TRUNCATION_TOP_K)\n}\n\n/** Assemble the persisted trace value from its two ledgers. */\nexport function composeServedTrace(input: {\n servedLines: readonly TraceLine[]\n truncated: readonly TraceLine[]\n}): ServedRetrievalTraceV1 {\n return {\n schemaVersion: RETRIEVAL_TRACE_SCHEMA_VERSION,\n servedLines: [...input.servedLines],\n truncated: boundTruncationLedger(input.truncated),\n }\n}\n\n/**\n * The legs a serving channel in this package can actually emit. This is the `knowledge-local` half\n * of the cross-package vocabulary check the trace DTO asks for: the schema declares\n * `RETRIEVAL_TRACE_LEGS`, the retrieval legs module declares a module-private `CandidateLeg`, and\n * this package is the only one that can see both. Exported so a test can assert the three sets\n * agree instead of a comment claiming they do.\n */\nexport const SERVING_TRACE_LEGS: readonly RetrievalTraceLeg[] = RETRIEVAL_TRACE_LEGS\n","import {\n canonicalJson,\n curatorTier,\n normalizeAnchor,\n parseProcedureBody,\n procedureParameterFillability,\n survivingOutcomeEvents,\n type Anchor,\n type BundleOutcomeEvent,\n type BundleProvenance,\n type CuratorTier,\n type IndexEntry,\n type ProcedureBindingAvailability,\n type ProcedureMatch,\n} from '@vostride/agent-qa-schema'\n\n/**\n * D-05 replay-eligibility confirmation bars per curator tier (PROVISIONAL, retrieval/constants.ts\n * style — internal constitution values, never config keys; M3 owns calibration from attributed\n * outcomes). Degraded authorship needs a higher confirmation bar than full; floor tier has no bar\n * because it is hint-only forever (D-06) and is deliberately absent from this record.\n */\nexport const PROCEDURE_REPLAY_CONFIRMATIONS: Record<'full' | 'degraded', number> = {\n full: 2,\n degraded: 4,\n}\n\n/**\n * D-05 minimum composed confidence for a replay recommendation (PROVISIONAL). Below it a match\n * still serves as a hint; the fold can only ever downrank, never promote past this floor.\n */\nexport const PROCEDURE_REPLAY_CONFIDENCE_FLOOR = 0.5\n\n/**\n * D-06 tier factor of the confidence fold (PROVISIONAL). Floor tier is discounted hardest and is\n * additionally hard-walled out of replay below, so this factor only shapes hint ordering there.\n */\nconst PROCEDURE_TIER_FACTOR: Record<CuratorTier, number> = {\n full: 1,\n degraded: 0.8,\n floor: 0.5,\n}\n\n/**\n * Weight of the intent-text lexical signal inside relevance (PROVISIONAL). Anchor overlap is the\n * primary signal; lexical relevance is secondary and purely additive on the zero-embedder floor.\n */\nconst PROCEDURE_LEXICAL_WEIGHT = 0.5\n\n/**\n * Weight of the optional dense-leg contribution (PROVISIONAL). The dense term joins only when an\n * embedder is up (caller-supplied per-record scores); absent scores contribute exactly zero so the\n * lexical floor stays deterministic.\n */\nconst PROCEDURE_DENSE_WEIGHT = 0.25\n\n/**\n * D-08 fillability downrank factor (PROVISIONAL). An unfillable required parameter both halves\n * confidence and hard-walls the match out of replay — the factor exists so hint ordering still\n * prefers fillable procedures.\n */\nconst PROCEDURE_UNFILLABLE_FACTOR = 0.5\n\n/**\n * The bundle facts the matcher folds. `LoadedBundle` satisfies this structurally, so the reader\n * passes hydrated entries straight through; tests construct the narrow shape directly.\n */\nexport interface ProcedureMatchCandidate {\n entry: IndexEntry\n bundle: {\n summary: string\n body: string\n events: readonly BundleOutcomeEvent[]\n provenance: BundleProvenance\n }\n}\n\nexport interface MatchProcedureInput {\n /** Already-hydrated entries; the reader's SQL scope ladder has applied the scope walls. */\n entries: readonly ProcedureMatchCandidate[]\n intent: string\n /** ScreenState-derived anchors; normalized here via canonicalJson(normalizeAnchor(...)). */\n anchors: readonly Anchor[]\n /** Source-tagged binding NAMES only — no value ever reaches the matcher (D-08). */\n availability: ProcedureBindingAvailability\n /** Optional additive dense-leg scores keyed by record id, present only when an embedder is up. */\n denseScoreByRecordId?: ReadonlyMap<string, number>\n}\n\nfunction normalizedAnchorKey(anchor: Anchor): string {\n return canonicalJson(normalizeAnchor(anchor))\n}\n\nfunction compareRecordId(left: IndexEntry, right: IndexEntry): number {\n const leftId = String(left.id)\n const rightId = String(right.id)\n return leftId < rightId ? -1 : leftId > rightId ? 1 : 0\n}\n\n/**\n * The ONE kind-aware procedure admission predicate, shared by BOTH serving faces (G-381-4):\n * the MATCH face (`matchProcedure` below) and the READ face (`findReadableBundle` in\n * serving/reader.ts). Procedures can never be `active` in M2 (379 D-16 excludes procedure-kind\n * from promotion) and the brief's vetted-candidate path is fact/caution-only, so candidate-status\n * procedures are admitted here through explicit status walls — candidate + validity-open +\n * not-withheld + no surviving user-deprecate.\n *\n * Sharing it is load-bearing, not tidiness: the two faces had diverged, so the matcher could\n * recommend a replay whose body the reader then refused to serve, silently starving every earned\n * replay into a hint. Keep this the sole admission authority for both faces so they cannot\n * diverge again. This is READ admission, never promotion — nothing here makes a procedure\n * `active`, brief-servable, or caution-servable. TRUST lives in the fold (hint/replay), never in\n * admission (T-381-11).\n */\nexport function admitsProcedure({ entry, bundle }: ProcedureMatchCandidate): boolean {\n if (entry.kind !== 'procedure') return false\n if (entry.status === 'active') return true\n if (entry.status !== 'candidate') return false\n if (entry.validity !== 'current') return false\n if (bundle.provenance.mode === 'run-linked' && bundle.provenance.withheld === true) return false\n return !survivingOutcomeEvents(bundle.events).some((event) => event.type === 'deprecated')\n}\n\n/** Matched share of the record's flow:/page: anchors under normalized-key equality. */\nfunction anchorRelevance(entry: IndexEntry, requestedKeys: ReadonlySet<string>): number {\n const flowPageAnchors = entry.anchors.filter(\n (anchor) => anchor.t === 'flow' || anchor.t === 'page',\n )\n if (flowPageAnchors.length === 0) return 0\n const matched = flowPageAnchors.filter(\n (anchor) => requestedKeys.has(normalizedAnchorKey(anchor)),\n ).length\n return matched / flowPageAnchors.length\n}\n\n/** Matched share of intent tokens against summary + body on the lexical floor. */\nfunction lexicalRelevance(bundle: ProcedureMatchCandidate['bundle'], intent: string): number {\n const tokens = intent.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []\n if (tokens.length === 0) return 0\n const text = [bundle.summary, bundle.body].join('\\n').toLowerCase()\n return tokens.filter((token) => text.includes(token)).length / tokens.length\n}\n\n/**\n * Surviving Confirm evidence minus the creation/authoring observation. A run-linked bundle's\n * creation event shares the bundle-creating candidate id with provenance.curationJobId; counting\n * it would cross every D-05 bar one organic canary early (CR-03). Re-extraction and canary\n * confirmations arrive from distinct curation jobs and continue to count.\n */\nfunction confirmationCount(\n events: readonly BundleOutcomeEvent[],\n provenance: BundleProvenance,\n): number {\n const creationJobId = provenance.mode === 'run-linked'\n ? provenance.curationJobId\n : undefined\n return survivingOutcomeEvents(events)\n .flatMap((event) => (\n event.type === 'confirmed' && event.curationJobId !== creationJobId\n ? [event.evidenceToken]\n : []\n ))\n .filter((token) => token.length > 0)\n .length\n}\n\ninterface ScoredMatch {\n entry: IndexEntry\n match: ProcedureMatch\n}\n\n/**\n * D-07 pure procedure matcher: pre-filter (kind-aware admission) -> anchor match (normalized-key\n * equality, lexical intent as a secondary additive signal) -> rerank fold (tier x confirmations x\n * fillability). Deterministic on the zero-embedder lexical floor: snapshot-pure inputs only, no\n * wall-clock, float-order-stable single-pass scoring, ties broken by record id. Misses return\n * undefined, never a throw.\n */\nexport function matchProcedure(input: MatchProcedureInput): ProcedureMatch | undefined {\n const requestedKeys = new Set(input.anchors.map(normalizedAnchorKey))\n\n const scored = input.entries.flatMap((candidate): ScoredMatch[] => {\n if (!admitsProcedure(candidate)) return []\n\n const anchorScore = anchorRelevance(candidate.entry, requestedKeys)\n if (anchorScore === 0) return []\n\n // Unparseable bodies are skipped fail-closed (T-381-01), matching parseProcedureBody's law.\n const payload = parseProcedureBody(candidate.bundle.body)\n if (payload === undefined) return []\n\n const flowAnchor = candidate.entry.anchors.find((anchor) => anchor.t === 'flow')\n ?? candidate.entry.anchors[0]\n if (flowAnchor === undefined) return []\n\n const denseScore = input.denseScoreByRecordId?.get(String(candidate.entry.id)) ?? 0\n const relevance = Math.min(\n 1,\n anchorScore\n + PROCEDURE_LEXICAL_WEIGHT * lexicalRelevance(candidate.bundle, input.intent)\n + PROCEDURE_DENSE_WEIGHT * denseScore,\n )\n\n const tier = curatorTier(\n candidate.bundle.provenance.mode === 'run-linked'\n ? candidate.bundle.provenance.authorship\n : undefined,\n )\n const confirmations = confirmationCount(\n candidate.bundle.events,\n candidate.bundle.provenance,\n )\n // The shared schema contract is also enforced by the loop binder. Matcher admission and\n // loop-side source/type binding therefore cannot drift (WR-03).\n const { fillable } = procedureParameterFillability(payload, input.availability)\n\n // Laplace-shaped confirmation factor: 0 confirmations => 0.5, saturating toward 1. Hint\n // matches keep a meaningful confidence while unconfirmed procedures stay below replay bars.\n const confidence = relevance\n * PROCEDURE_TIER_FACTOR[tier]\n * ((confirmations + 1) / (confirmations + 2))\n * (fillable ? 1 : PROCEDURE_UNFILLABLE_FACTOR)\n\n const replay = tier !== 'floor'\n && confirmations >= PROCEDURE_REPLAY_CONFIRMATIONS[tier]\n && fillable\n && confidence >= PROCEDURE_REPLAY_CONFIDENCE_FLOOR\n\n return [{\n entry: candidate.entry,\n match: {\n id: candidate.entry.id,\n flowAnchor: normalizeAnchor(flowAnchor),\n confidence,\n authoringModelTier: tier,\n parameterSchema: payload.parameters.map(({ name, type, required }) => ({\n name,\n type,\n required,\n })),\n replayRecommendation: replay ? 'replay' : 'hint',\n },\n }]\n })\n\n scored.sort((left, right) => (\n right.match.confidence - left.match.confidence\n || compareRecordId(left.entry, right.entry)\n ))\n return scored[0]?.match\n}\n","import { assembleBriefTiers } from '@vostride/agent-qa-runner'\nimport {\n servingRecordMetadata,\n type BriefBlock,\n type BriefLine,\n type IndexEntry,\n type ScopeKey,\n type ServedRetrievalTraceV1,\n type TraceLine,\n} from '@vostride/agent-qa-schema'\n\nimport {\n selectServingRecordsWithProvenance,\n type ServingSelectionEntry,\n} from './brief-selection.js'\nimport { estimateRenderedServingCost, renderBriefLine } from './brief-render.js'\nimport {\n CHANNEL_1_SERVING_LEG,\n composeServedTrace,\n traceLine,\n} from './serve-trace.js'\nimport type { readPolicyLadder } from './policy-ladder.js'\n\ntype OriginStampedEntry = IndexEntry & {\n origin?: 'app-observed' | 'user'\n originClass?: 'agent-observed' | 'agent-verified' | 'import' | 'user'\n}\n\ninterface AssembleRunBriefInput {\n candidates: IndexEntry[]\n policy: ReturnType<typeof readPolicyLadder>\n scope: ScopeKey\n budget: number\n recordCap: number\n asOfBuild?: number\n}\n\nfunction isUserFact(entry: IndexEntry): boolean {\n const stampedEntry = entry as OriginStampedEntry\n return entry.kind === 'fact'\n && entry.status === 'active'\n && (stampedEntry.origin === 'user' || stampedEntry.originClass === 'user')\n}\n\nfunction compareRecordId(left: IndexEntry, right: IndexEntry): number {\n const leftId = String(left.id)\n const rightId = String(right.id)\n return leftId < rightId ? -1 : leftId > rightId ? 1 : 0\n}\n\nfunction renderSovereignLine(entry: IndexEntry): { briefLine: BriefLine; cost: number } {\n return {\n cost: estimateRenderedServingCost(entry.summary),\n briefLine: {\n id: entry.id,\n kind: entry.kind,\n summary: entry.summary,\n trust: entry.trust,\n status: entry.status,\n servedAsCanary: entry.servedAsCanary,\n tier: 'L0',\n },\n }\n}\n\nfunction normalizedRecordCap(value: number): number {\n return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0\n}\n\nfunction policyWarnings(policy: ReturnType<typeof readPolicyLadder>): string[] {\n return policy.oversized.map(({ file, approxTokens }) => (\n `oversized policy ${file}: approximately ${approxTokens} tokens; served whole`\n ))\n}\n\nfunction truncationSignal(\n served: number,\n eligible: number,\n warnings: readonly string[],\n): string {\n const signals = served < eligible ? [`truncated ${served} of ${eligible}`] : []\n signals.push(...warnings)\n return signals.join('\\n')\n}\n\n/**\n * The Channel-1 brief together with the serve-time trace that explains it (D-13/D-16). One value,\n * never two calls: a caller cannot obtain the brief without also receiving how it was chosen.\n */\nexport interface AssembledRunBrief {\n readonly brief: BriefBlock\n readonly trace: ServedRetrievalTraceV1\n}\n\n/**\n * Attribute the served and cut candidates from the ONE ranking the assembly already produced.\n *\n * `eligible` is the full serve-time ranking (unbounded budget, no record cap); `selected` is what\n * the real budget admitted from it. Both were computed above for the truncation SIGNAL the brief\n * already carries, so the trace adds no retrieval work — it reads the same two lists.\n *\n * Rank is the candidate's position in the FULL ranking, so a served line and a cut candidate are\n * comparable numbers: \"served, ranked 2nd\" and \"cut, ranked 21st\" answer the same question. A\n * served record is always present in the full ranking (the budgeted pass admits a subset of what\n * the unbounded pass stages), which `__tests__/serve-trace.test.ts` asserts directly rather than assuming;\n * the fallback below exists so that a future change to the staging path degrades into a\n * still-valid, still-ordered rank instead of an invalid one.\n */\nfunction assembleTrace(\n eligible: readonly ServingSelectionEntry[],\n selected: readonly ServingSelectionEntry[],\n): ServedRetrievalTraceV1 {\n const fullRanking = new Map(\n eligible.map((entry) => [String(entry.record.id), entry]),\n )\n const servedIds = new Set(selected.map(({ record }) => String(record.id)))\n\n const servedLines: TraceLine[] = selected.map((entry, index) => {\n const ranked = fullRanking.get(String(entry.record.id))\n return traceLine({\n recordId: String(entry.record.id),\n leg: CHANNEL_1_SERVING_LEG,\n rank: ranked?.rank ?? eligible.length + index + 1,\n score: ranked?.score ?? entry.score,\n })\n })\n\n const truncated: TraceLine[] = eligible\n .filter(({ record }) => !servedIds.has(String(record.id)))\n .map((entry) => traceLine({\n recordId: String(entry.record.id),\n leg: CHANNEL_1_SERVING_LEG,\n rank: entry.rank,\n score: entry.score,\n }))\n\n return composeServedTrace({ servedLines, truncated })\n}\n\n/**\n * Assemble the deterministic Channel-1 brief over records already loaded by the reader, together\n * with its serve-time retrieval trace (D-13/D-16).\n * L0 is sovereign and whole; the supplied budget applies only to learned L1/L2 records.\n *\n * The trace covers the LEARNED lines only. Sovereign L0 user facts never enter the ranking — they\n * are filtered out before selection and served whole because they are sovereign — so listing them\n * in a retrieval trace would attribute them to a leg that took no part in serving them. Their\n * \"why\" is the sovereignty rule, not a retrieval decision.\n */\nexport function assembleRunBrief(input: AssembleRunBriefInput): AssembledRunBrief {\n const userFacts = input.candidates.filter(isUserFact).sort(compareRecordId)\n const learnedCandidates = input.candidates.filter((entry) => !isUserFact(entry))\n const recordCap = Math.max(0, normalizedRecordCap(input.recordCap) - userFacts.length)\n const temporalInput = input.asOfBuild === undefined\n ? {}\n : { asOfBuild: input.asOfBuild }\n\n const eligibleEntries = selectServingRecordsWithProvenance({\n candidates: learnedCandidates,\n scope: input.scope,\n channelBudget: Number.MAX_SAFE_INTEGER,\n recordCap: learnedCandidates.length,\n ...temporalInput,\n })\n const selectedEntries = selectServingRecordsWithProvenance({\n candidates: learnedCandidates,\n scope: input.scope,\n channelBudget: input.budget,\n recordCap,\n ...temporalInput,\n })\n const selected = selectedEntries.map(({ record }) => record)\n const rendered = selected.map(renderBriefLine)\n const sovereignLines = userFacts.map((record) => ({\n record,\n rendered: renderSovereignLine(record),\n }))\n\n const brief: BriefBlock = {\n tiers: assembleBriefTiers(\n input.policy.text,\n userFacts.map(({ summary }) => summary),\n rendered.map(({ line, briefLine }) => ({ line, tier: briefLine.tier })),\n ),\n lines: [\n ...sovereignLines.map(({ rendered: { briefLine } }) => briefLine),\n ...rendered.map(({ briefLine }) => briefLine),\n ],\n truncation: truncationSignal(\n selected.length,\n eligibleEntries.length,\n policyWarnings(input.policy),\n ),\n admissions: [\n ...sovereignLines.map(({ record, rendered }) => servingRecordMetadata({\n id: record.id,\n anchors: record.anchors,\n renderedCost: rendered.cost,\n })),\n ...selected.map((record, index) => servingRecordMetadata({\n id: record.id,\n anchors: record.anchors,\n renderedCost: rendered[index]!.cost,\n })),\n ],\n }\n\n return { brief, trace: assembleTrace(eligibleEntries, selectedEntries) }\n}\n","import { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { slugBranch } from '@vostride/agent-qa-schema'\n\n/**\n * D-07: Provisional authored-policy warning threshold. This is an operator\n * signal only, never a serving budget or user-facing configuration key.\n */\nconst POLICY_SIZE_WARNING_CHARACTERS = 16_000\n\nexport interface OversizedPolicy {\n file: string\n approxTokens: number\n}\n\nexport interface PolicyLadder {\n text: string\n files: string[]\n oversized: OversizedPolicy[]\n}\n\ninterface PolicyRung {\n file: string\n text: string\n}\n\nexport type MalformedPolicyCommentReason =\n | 'nested-opener'\n | 'stray-closer'\n | 'unclosed-comment'\n\nexport class MalformedPolicyCommentError extends SyntaxError {\n readonly sourceFile: string\n readonly reason: MalformedPolicyCommentReason\n readonly line: number\n readonly column: number\n\n constructor(\n sourceFile: string,\n reason: MalformedPolicyCommentReason,\n line: number,\n column: number,\n ) {\n super(`Malformed HTML comment in ${sourceFile} at ${line}:${column} (${reason})`)\n this.name = 'MalformedPolicyCommentError'\n this.sourceFile = sourceFile\n this.reason = reason\n this.line = line\n this.column = column\n }\n}\n\n/**\n * Remove authored HTML comment regions without changing any active byte.\n * `sourceFile` is the already-sanitized policy-relative label used for diagnostics.\n */\nexport function stripPolicyHtmlComments(text: string, sourceFile: string): string {\n let index = 0\n let line = 1\n let column = 1\n let activeStart = 0\n let rendered = ''\n\n const advance = (characters: number): void => {\n const end = index + characters\n while (index < end) {\n if (text[index] === '\\n') {\n line += 1\n column = 1\n } else {\n column += 1\n }\n index += 1\n }\n }\n\n while (index < text.length) {\n if (text.startsWith('<!--', index)) {\n rendered += text.slice(activeStart, index)\n const commentStart = { line, column }\n advance(4)\n\n let closed = false\n while (index < text.length) {\n if (text.startsWith('<!--', index)) {\n throw new MalformedPolicyCommentError(\n sourceFile,\n 'nested-opener',\n line,\n column,\n )\n }\n if (text.startsWith('-->', index)) {\n advance(3)\n activeStart = index\n closed = true\n break\n }\n advance(1)\n }\n\n if (!closed) {\n throw new MalformedPolicyCommentError(\n sourceFile,\n 'unclosed-comment',\n commentStart.line,\n commentStart.column,\n )\n }\n continue\n }\n\n if (text.startsWith('-->', index)) {\n throw new MalformedPolicyCommentError(\n sourceFile,\n 'stray-closer',\n line,\n column,\n )\n }\n advance(1)\n }\n\n return rendered + text.slice(activeStart)\n}\n\nfunction readOptionalPolicy(knowledgeRoot: string, file: string): PolicyRung | undefined {\n try {\n const text = stripPolicyHtmlComments(\n readFileSync(join(knowledgeRoot, ...file.split('/')), 'utf8'),\n file,\n )\n if (text.trim().length === 0) return undefined\n return {\n file,\n text,\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\nfunction renderPolicyLadder(rungs: readonly PolicyRung[]): string {\n if (rungs.length === 0) return ''\n\n let rendered = rungs[0]!.text\n for (const rung of rungs.slice(1)) {\n const leadingNewline = rendered.length > 0 && !rendered.endsWith('\\n') ? '\\n' : ''\n rendered += `${leadingNewline}--- POLICY SOURCE: ${rung.file} ---\\n${rung.text}`\n }\n return rendered\n}\n\nexport function readPolicyLadder(\n knowledgeRoot: string,\n product?: string,\n): PolicyLadder {\n // D-06: The ladder is deliberately closed at two rungs, general before specific.\n const requestedFiles = ['policies/global.md']\n if (product !== undefined && product.length > 0) {\n // Product identity is data, not a caller-controlled path. Reuse the shared\n // path-segment sanitizer so a product cannot escape the authored shelf.\n requestedFiles.push(`policies/${slugBranch(product)}.md`)\n }\n\n const rungs = requestedFiles.flatMap((file) => {\n const rung = readOptionalPolicy(knowledgeRoot, file)\n return rung === undefined ? [] : [rung]\n })\n\n return {\n // D-07: Validated active policy bytes are concatenated whole. Labels frame\n // sources but no active text is summarized, truncated, normalized, or reflowed.\n text: renderPolicyLadder(rungs),\n files: rungs.map(({ file }) => file),\n oversized: rungs.flatMap(({ file, text }) =>\n text.length > POLICY_SIZE_WARNING_CHARACTERS\n ? [{ file, approxTokens: Math.ceil(text.length / 4) }]\n : [],\n ),\n }\n}\n","/**\n * knowledge-local implementation of the agent-side AuthoringReadPort (D-13): the 4th channel's\n * composition boundary. Shares the serving reader's hydration internals and the one derived\n * index SQLite; keeps servingReader/KnowledgeHintReader untouched.\n */\nimport { existsSync } from 'node:fs'\n\nimport type { AuthoringReadPort } from '@vostride/agent-qa-agent'\nimport {\n identityTupleKey,\n normalizeAnchor,\n slugBranch,\n type Anchor,\n type AuthoringBrief,\n type ScopeKey,\n} from '@vostride/agent-qa-schema'\n\nimport type { EmbedderPort } from '../embedder-port.js'\nimport { indexDbPath, openIndexReaderConnection } from '../index-open.js'\nimport { foldQuarantineLedgerState, readQuarantineLedger } from '../quarantine/ledger.js'\nimport { hasDenseCandidates } from '../retrieve.js'\nimport { snapshotTrustPriors } from '../promotion-gate-input.js'\nimport { denseLeg, type RetrievalLegScope } from '../retrieval/legs.js'\nimport { scopeLadderPredicate } from '../retrieval/pre-filter.js'\nimport {\n assembleAuthoringBrief,\n type AuthoringExemplarRow,\n type AuthoringTestRef,\n} from './get-authoring-brief.js'\nimport {\n hydrateRows,\n readIndexRows,\n type OpenServingKnowledgeReaderConfig,\n} from './reader.js'\n\n/**\n * PROVISIONAL authoring-brief budget, computed as a plain number at this composition boundary\n * (377 D-07 lineage: budgets are numbers passed down, never config reads inside assemblies).\n */\nexport const AUTHORING_BRIEF_DEFAULT_BUDGET = 2_000\n\n/** PROVISIONAL dense candidate cap pending authoring-channel retrieval telemetry. */\nexport const AUTHORING_DENSE_K = 32\n\nexport interface AuthoringReaderDependencies {\n /** Consumer-owned test inventory crossing this boundary as identity refs only. */\n discoverKnownTests?: () => readonly AuthoringTestRef[]\n /** Test/integration seam; production omission uses denseLeg's automatic acquisition ladder. */\n embedder?: EmbedderPort\n /**\n * ISO-8601 instant the quarantine fold compares expiry against (390 D-11). A seam rather than a\n * clock read inside the fold: `'expired'` is COMPUTED from this value, so pinning an expiry\n * boundary one second either side has to be possible without waiting for wall time. Production\n * omission reads the clock ONCE per brief, at this composition boundary.\n */\n now?: () => string\n}\n\ninterface OutcomeRow {\n product: string\n file_path: string\n test_name: string\n passes: number\n failures: number\n heals: number\n flake_count: number\n last_outcomes_json: string\n}\n\n/**\n * The identities the committed ledger currently suppresses (390 D-02), keyed exactly the way the\n * projection is keyed — `(product, filePath, testName)`, with the ledger's `product` carrying the\n * same slugged partition the projection rows do.\n *\n * Only `'quarantined'` counts. `'expired'` and both released states are deliberately NOT excluded:\n * an entry whose deadline lapsed has stopped suppressing (D-11) while staying listed, and a\n * released entry is a decision someone made.\n *\n * NO try/catch. A ledger this build cannot read propagates its typed error, because the one\n * outcome that must be impossible here is degrading unreadable committed truth to \"nothing is\n * quarantined\" — that silently un-quarantines every entry in the file. Refused individual LINES\n * are already surfaced as data by the read itself and never became entries.\n */\nfunction quarantinedIdentityKeys(knowledgeRoot: string, now: string): ReadonlySet<string> {\n const { events } = readQuarantineLedger(knowledgeRoot)\n return new Set(\n foldQuarantineLedgerState(events, now)\n .filter((entry) => entry.state === 'quarantined')\n .map((entry) => identityTupleKey([entry.product, entry.filePath, entry.testName])),\n )\n}\n\nfunction parseLastOutcomes(json: string): { buildOrdinal: number; passed: boolean }[] {\n try {\n const parsed: unknown = JSON.parse(json)\n if (!Array.isArray(parsed)) return []\n return parsed.flatMap((entry) => (\n typeof entry === 'object'\n && entry !== null\n && typeof (entry as { buildOrdinal?: unknown }).buildOrdinal === 'number'\n && typeof (entry as { passed?: unknown }).passed === 'boolean'\n ? [{\n buildOrdinal: (entry as { buildOrdinal: number }).buildOrdinal,\n passed: (entry as { passed: boolean }).passed,\n }]\n : []\n ))\n } catch {\n // A malformed window heals through the projection rebuild; serve the row without it.\n return []\n }\n}\n\n/**\n * Read the run-outcome projection through the one index reader connection and the same\n * scope ladder as ordinary knowledge records. The tables are deliberately outside\n * REQUIRED_INDEX_TABLES, so an absent or pre-partition shape is an empty projection —\n * the ABRF-02 empty edge, never a throw or an unfiltered cross-product read.\n */\nfunction readProjectionRows(\n config: OpenServingKnowledgeReaderConfig,\n scope: ScopeKey,\n now: string,\n): AuthoringExemplarRow[] {\n if (!existsSync(indexDbPath(config.knowledgeRoot))) return []\n\n const reader = openIndexReaderConnection(config.knowledgeRoot)\n try {\n const present = reader.db.prepare(`\n SELECT count(*) AS tables\n FROM sqlite_master\n WHERE type = 'table' AND name IN ('run_test_outcomes', 'run_test_anchors')\n `).get() as { tables: number } | undefined\n if (Number(present?.tables ?? 0) < 2) return []\n\n const partitionColumnsPresent = [\n \"PRAGMA table_info('run_test_outcomes')\",\n \"PRAGMA table_info('run_test_anchors')\",\n ].every((pragma) => {\n const columns = new Set(reader.db.prepare(pragma).all().map((row) => String(row.name)))\n return ['product', 'scope_tier', 'scope_key'].every((column) => columns.has(column))\n })\n if (!partitionColumnsPresent) return []\n\n const predicate = scopeLadderPredicate({\n ...(config.product === undefined\n ? {}\n : { productRow: slugBranch(config.product), productScope: config.product }),\n requestedScope: scope,\n ...(config.scopeDefaults?.parentScopes === undefined\n ? {}\n : { parentScopes: config.scopeDefaults.parentScopes }),\n })\n\n const anchorsByTest = new Map<string, string[]>()\n const anchorRows = reader.db.prepare(`\n SELECT r.product, r.file_path, r.test_name, r.anchor_normalized_json\n FROM run_test_anchors r\n WHERE ${predicate.sql}\n ORDER BY r.product, r.file_path, r.test_name, r.anchor_normalized_json\n `).all(...predicate.binds)\n for (const row of anchorRows) {\n const key = identityTupleKey([\n String(row.product), String(row.file_path), String(row.test_name),\n ])\n const keys = anchorsByTest.get(key)\n if (keys === undefined) anchorsByTest.set(key, [String(row.anchor_normalized_json)])\n else keys.push(String(row.anchor_normalized_json))\n }\n\n const quarantinedKeys = quarantinedIdentityKeys(config.knowledgeRoot, now)\n\n return (reader.db.prepare(`\n SELECT r.product, r.file_path, r.test_name, r.passes, r.failures, r.heals,\n r.flake_count,\n last_outcomes_json\n FROM run_test_outcomes r\n WHERE ${predicate.sql}\n ORDER BY r.product, r.file_path, r.test_name\n `).all(...predicate.binds) as unknown as OutcomeRow[]).map((row) => ({\n filePath: String(row.file_path),\n testName: String(row.test_name),\n passes: Number(row.passes),\n failures: Number(row.failures),\n heals: Number(row.heals),\n flakeCount: Number(row.flake_count),\n quarantined: quarantinedKeys.has(identityTupleKey([\n String(row.product), String(row.file_path), String(row.test_name),\n ])),\n lastOutcomes: parseLastOutcomes(String(row.last_outcomes_json)),\n anchorKeys: anchorsByTest.get(identityTupleKey([\n String(row.product), String(row.file_path), String(row.test_name),\n ])) ?? [],\n }))\n } finally {\n reader.db.close()\n }\n}\n\n/**\n * PROVISIONAL screenless target-anchor derivation (D-13: intent on the dense leg, page:/flow:\n * anchors on the lexical leg). Every derived anchor goes through the one normalizeAnchor\n * authority: '/'-prefixed and 'page:'-prefixed intent tokens become page anchors;\n * 'flow:'-prefixed tokens and the whole intent become flow-name candidates. The scope key\n * contributes through the SQL scope ladder, not through anchors.\n */\nfunction deriveTargetAnchors(intent: string): Anchor[] {\n const anchors: Anchor[] = []\n for (const token of intent.split(/\\s+/)) {\n if (token.startsWith('/')) anchors.push({ t: 'page', route: token })\n else if (token.startsWith('page:')) anchors.push({ t: 'page', route: token.slice(5) })\n else if (token.startsWith('flow:')) anchors.push({ t: 'flow', name: token.slice(5) })\n }\n if (intent.trim() !== '') anchors.push({ t: 'flow', name: intent })\n\n const seen = new Set<string>()\n return anchors.map(normalizeAnchor).filter((anchor) => {\n const key = JSON.stringify(anchor)\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\nfunction authoringRetrievalScope(\n config: OpenServingKnowledgeReaderConfig,\n scope: ScopeKey,\n): RetrievalLegScope {\n const containingScopes = [scope, ...(config.scopeDefaults?.parentScopes ?? [])]\n const productKey = config.product\n ?? containingScopes.find((candidate) => candidate.tier === 'product')?.key\n ?? scope.key\n return {\n product: slugBranch(productKey),\n testKey: containingScopes.find((candidate) => candidate.tier === 'test')?.key\n ?? `__missing_test_scope__:${productKey}`,\n suiteKey: containingScopes.find((candidate) => candidate.tier === 'suite')?.key\n ?? `__missing_suite_scope__:${productKey}`,\n productKey,\n globalKey: 'global',\n }\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n return Math.min(1, Math.max(0, value))\n}\n\nfunction knownTestUniverse(\n projectionRows: readonly AuthoringExemplarRow[],\n discovered: readonly AuthoringTestRef[],\n): AuthoringTestRef[] {\n const byIdentity = new Map<string, AuthoringTestRef>()\n for (const { filePath, testName } of discovered) {\n byIdentity.set(identityTupleKey([filePath, testName]), { filePath, testName })\n }\n // Projection-known identities are the floor, never the ceiling. Re-setting them last makes\n // the trusted projection identity win without allowing consumer-owned content across D-16.\n for (const { filePath, testName } of projectionRows) {\n byIdentity.set(identityTupleKey([filePath, testName]), { filePath, testName })\n }\n return [...byIdentity.values()].sort((left, right) => (\n (left.filePath < right.filePath ? -1 : left.filePath > right.filePath ? 1 : 0)\n || (left.testName < right.testName ? -1 : left.testName > right.testName ? 1 : 0)\n ))\n}\n\n/**\n * Read optional dense scores without widening the authoring-reader contract. Embedder\n * acquisition and query failures deliberately degrade to the deterministic lexical/anchor\n * floor required by ABRF-01; they never abort the authoring channel.\n */\nasync function readDenseScores(\n config: OpenServingKnowledgeReaderConfig,\n deps: AuthoringReaderDependencies,\n intent: string,\n scope: ScopeKey,\n): Promise<ReadonlyMap<string, number> | undefined> {\n if (!existsSync(indexDbPath(config.knowledgeRoot))) return undefined\n\n const connection = openIndexReaderConnection(config.knowledgeRoot)\n try {\n const legScope = authoringRetrievalScope(config, scope)\n if (!hasDenseCandidates(connection.db, legScope)) return undefined\n\n const candidates = await denseLeg(\n connection,\n [intent],\n legScope,\n AUTHORING_DENSE_K,\n deps.embedder === undefined ? {} : { embedder: deps.embedder },\n )\n if (candidates.length === 0) return undefined\n return new Map(candidates.map((candidate) => [\n String(candidate.bundleId),\n clamp01(candidate.rawScores.cosine ?? 0),\n ]))\n } catch {\n // The dense leg is optional by contract: acquisition or query failure deliberately\n // degrades silently to the deterministic lexical/anchor floor instead of aborting ABRF-01.\n return undefined\n } finally {\n connection.db.close()\n }\n}\n\n/** Open the screenless authoring channel over the same store config as the serving reader. */\nexport function createAuthoringReader(\n config: OpenServingKnowledgeReaderConfig,\n deps: AuthoringReaderDependencies = {},\n): AuthoringReadPort {\n config = { ...config, priors: snapshotTrustPriors(config.priors) }\n return {\n async getAuthoringBrief(intent: string, scope: ScopeKey): Promise<AuthoringBrief> {\n const entries = hydrateRows(config, readIndexRows(config, scope), false)\n // ONE clock read per brief, here at the composition boundary — the quarantine fold below is\n // pure in `now` (D-11), and a second read could put two rows on two sides of one deadline.\n const projectionRows = readProjectionRows(\n config,\n scope,\n (deps.now ?? (() => new Date().toISOString()))(),\n )\n const denseScoreByRecordId = await readDenseScores(config, deps, intent, scope)\n const knownTests = knownTestUniverse(\n projectionRows,\n deps.discoverKnownTests?.() ?? [],\n )\n // D-16: the assembly seam ALWAYS produces the trace, so capture is already running for the\n // 4th channel. The AuthoringReadPort contract still carries only the brief because there is\n // no authoring evidence artifact to persist it onto yet; 393/394 mint the draft receipt and\n // then only have to stop discarding this value. Deliberately not a fabricated persistence\n // path today: a trace written nowhere would be a trace nobody could answer from.\n const { brief } = assembleAuthoringBrief({\n entries,\n projectionRows,\n // D-16: the consumer owns the filesystem and supplies identity refs only. Projection\n // identities remain a deterministic floor, while never-run tests widen the universe.\n knownTests,\n intent,\n scope,\n targetAnchors: deriveTargetAnchors(intent),\n budget: AUTHORING_BRIEF_DEFAULT_BUDGET,\n ...(denseScoreByRecordId === undefined ? {} : { denseScoreByRecordId }),\n })\n return brief\n },\n }\n}\n","/**\n * Screenless authoring-brief assembly (ABRF-01/ABRF-02, D-13/D-15/D-16).\n *\n * The 4th serving channel: facts/cautions/procedures from already-hydrated store entries plus\n * projection-ranked exemplar TEST REFERENCES — no ScreenState anywhere in the signature. The\n * assembly is pure (snapshot inputs only, no wall-clock, no file reads) and deterministic on the\n * zero-embedder lexical floor: intent tokens drive the lexical relevance leg, `page:`/`flow:`\n * target anchors drive the anchor leg, and dense scores join only as an optional additive term.\n *\n * Locked tight-budget precedence (Pitfall 8 — deliberately NOT the run brief's L0-L2 tiers):\n * caution > procedure > exemplar > fact. Buckets admit in that order against one shared\n * admission ledger; once a bucket sheds anything, every lower-precedence bucket is shed whole,\n * so an exemplar can never be dropped before a fact at the same budget.\n */\nimport {\n asRecordId,\n canonicalJson,\n createServingAdmissionState,\n EMPTY_PROCEDURE_BINDING_AVAILABILITY,\n identityTupleKey,\n normalizeAnchor,\n servingRecordMetadata,\n tryAdmitServingRecord,\n type Anchor,\n type AuthoringBrief,\n type BriefLine,\n type CautionLine,\n type ExemplarTest,\n type IndexEntry,\n type ProcedureMatch,\n type RetrievalTraceLeg,\n type ScopeKey,\n type ServedRetrievalTraceV1,\n type ServingRecordMetadata,\n type TraceLine,\n} from '@vostride/agent-qa-schema'\n\nimport { applyDiversityCaps, type RerankEntry } from '../retrieval/rerank.js'\nimport {\n composeServedTrace,\n dominantAuthoringLeg,\n traceLine,\n} from './serve-trace.js'\nimport {\n estimateRenderedServingCost,\n renderBriefLine,\n renderCautionLine,\n} from './brief-render.js'\nimport { matchProcedure, type ProcedureMatchCandidate } from './get-procedure.js'\n\n/**\n * PROVISIONAL exemplar cap (D-15's \"~3-5\"). Internal constitution value in the\n * retrieval/constants.ts style — never a config key; M3 owns calibration.\n */\nexport const AUTHORING_EXEMPLAR_CAP = 4\n\n/** PROVISIONAL top-N procedures served to the authoring consumer (D-15). */\nexport const AUTHORING_PROCEDURE_CAP = 5\n\n/**\n * PROVISIONAL bounded-excerpt budget in UTF-16 code units (D-16). The excerpt is title +\n * outcome outline composed from projection-known metadata — never test file content.\n */\nexport const AUTHORING_EXCERPT_CHAR_BUDGET = 240\n\n/**\n * PROVISIONAL discount for never-run exemplars (D-15's ratified degraded posture): flagged\n * `unverifiedOutcomes`, discounted below any observed pass-rate signal, never dropped.\n */\nconst AUTHORING_UNVERIFIED_OUTCOMES_DISCOUNT = 0.25\n\n/**\n * PROVISIONAL MMR diversity weight: each selection round penalizes a candidate by this factor\n * times its best anchor-key overlap share with already-selected exemplars.\n */\nconst AUTHORING_MMR_WEIGHT = 0.5\n\n/**\n * Weight of the intent-text lexical signal inside relevance (PROVISIONAL). Anchor overlap is\n * the primary signal; the lexical leg is secondary and additive on the zero-embedder floor.\n */\nconst AUTHORING_LEXICAL_WEIGHT = 0.5\n\n/**\n * Weight of the optional dense-leg contribution (PROVISIONAL). Absent scores contribute\n * exactly zero so the lexical floor stays deterministic.\n */\nconst AUTHORING_DENSE_WEIGHT = 0.25\n\n/** Hydrated store entry: `LoadedBundle`-backed entries satisfy this structurally. */\nexport type AuthoringEntryCandidate = ProcedureMatchCandidate\n\n/** One run-outcome projection row (381-05 tables), read through the index reader connection. */\nexport interface AuthoringExemplarRow {\n filePath: string\n testName: string\n passes: number\n failures: number\n heals: number\n flakeCount: number\n /** Resolved by the hydrating reader from the committed quarantine ledger (390 D-02). */\n quarantined: boolean\n /** Last-N window entries — ordinals only, wall-clock never. */\n lastOutcomes: readonly { buildOrdinal: number; passed: boolean }[]\n /** canonicalJson(normalizeAnchor(...)) keys — the ABRF-02 byte-deterministic encoding. */\n anchorKeys: readonly string[]\n}\n\n/** A test reference in the caller-supplied discovery universe (refs only, never content). */\nexport interface AuthoringTestRef {\n filePath: string\n testName: string\n}\n\nexport interface AssembleAuthoringBriefInput {\n /** Already-hydrated entries; the reader's SQL scope ladder has applied the scope walls. */\n entries: readonly AuthoringEntryCandidate[]\n /** Per-test outcome counters + exercised-anchor sets from the run-outcome projection. */\n projectionRows: readonly AuthoringExemplarRow[]\n /**\n * D-15 never-run discovery universe: test references the CALLER knows about (the consumer\n * owns the filesystem; M4 passes its authored shelf, the M2 reader passes projection-known\n * identities). Refs absent from the projection surface flagged `unverifiedOutcomes`,\n * discounted, never dropped — and still work against an EMPTY projection.\n */\n knownTests?: readonly AuthoringTestRef[]\n intent: string\n scope: ScopeKey\n /** `page:`/`flow:` anchors derived from scope + intent by the caller — never a ScreenState. */\n targetAnchors: readonly Anchor[]\n budget: number\n /** Optional additive dense-leg scores keyed by record id, present only when an embedder is up. */\n denseScoreByRecordId?: ReadonlyMap<string, number>\n}\n\nfunction normalizedAnchorKey(anchor: Anchor): string {\n return canonicalJson(normalizeAnchor(anchor))\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction intentTokens(intent: string): string[] {\n return intent.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []\n}\n\n/** Matched share of intent tokens against the candidate text on the lexical floor. */\nfunction lexicalRelevance(tokens: readonly string[], text: string): number {\n if (tokens.length === 0) return 0\n const haystack = text.toLowerCase()\n return tokens.filter((token) => haystack.includes(token)).length / tokens.length\n}\n\n/** Matched share of the requested target anchors under normalized-key equality. */\nfunction anchorOverlapShare(\n candidateKeys: ReadonlySet<string>,\n targetKeys: ReadonlySet<string>,\n): number {\n if (targetKeys.size === 0) return 0\n let matched = 0\n for (const key of targetKeys) {\n if (candidateKeys.has(key)) matched += 1\n }\n return matched / targetKeys.size\n}\n\n/** Brief-eligible learned entries: active, or vetted candidates already annotated upstream. */\nfunction isServableEntry(entry: IndexEntry, kind: 'fact' | 'caution'): boolean {\n if (entry.kind !== kind) return false\n if (entry.status === 'active') return true\n return entry.status === 'candidate' && entry.unverified === true\n}\n\ninterface ScoredEntry {\n entry: IndexEntry\n score: number\n /** D-16 attribution: whichever weighted relevance term contributed most to `score`. */\n leg: RetrievalTraceLeg\n}\n\nfunction scoreEntries(\n input: AssembleAuthoringBriefInput,\n kind: 'fact' | 'caution',\n targetKeys: ReadonlySet<string>,\n tokens: readonly string[],\n): ScoredEntry[] {\n return input.entries\n .flatMap(({ entry }): ScoredEntry[] => {\n if (!isServableEntry(entry, kind)) return []\n const candidateKeys = new Set(entry.anchors.map(normalizedAnchorKey))\n const dense = input.denseScoreByRecordId?.get(String(entry.id)) ?? 0\n // The three weighted terms are named once and both summed AND attributed from, so the\n // recorded leg is a decomposition of the number that actually ranked this entry rather\n // than a second, independently computed opinion about it (KREV-02).\n const contributions: Record<RetrievalTraceLeg, number> = {\n anchor: anchorOverlapShare(candidateKeys, targetKeys),\n lexical: AUTHORING_LEXICAL_WEIGHT\n * lexicalRelevance(tokens, `${entry.title}\\n${entry.summary}`),\n dense: AUTHORING_DENSE_WEIGHT * dense,\n }\n const relevance = Math.min(\n 1,\n contributions.anchor + contributions.lexical + contributions.dense,\n )\n if (relevance === 0) return []\n const trust = Number.isFinite(entry.trust) ? Math.max(0, entry.trust) : 0\n return [{ entry, score: trust * relevance, leg: dominantAuthoringLeg(contributions) }]\n })\n .sort((left, right) => (\n right.score - left.score\n || compareText(String(left.entry.id), String(right.entry.id))\n ))\n}\n\n/**\n * Top-N procedures through matchProcedure's own kind-aware admission and tier x confirmations x\n * fillability fold. Matches serve as hint-shaped entries — replay eligibility is irrelevant to\n * authoring — and the screenless call passes empty source-tagged availability.\n */\nfunction topProcedures(\n input: AssembleAuthoringBriefInput,\n): ProcedureMatch[] {\n const matches: ProcedureMatch[] = []\n let remaining = [...input.entries]\n while (matches.length < AUTHORING_PROCEDURE_CAP) {\n const match = matchProcedure({\n entries: remaining,\n intent: input.intent,\n anchors: input.targetAnchors,\n availability: EMPTY_PROCEDURE_BINDING_AVAILABILITY,\n ...(input.denseScoreByRecordId === undefined\n ? {}\n : { denseScoreByRecordId: input.denseScoreByRecordId }),\n })\n if (match === undefined) break\n matches.push(match)\n remaining = remaining.filter(({ entry }) => String(entry.id) !== String(match.id))\n }\n return matches\n}\n\ninterface ExemplarCandidate {\n identity: string\n exemplar: ExemplarTest\n anchorKeys: ReadonlySet<string>\n score: number\n leg: RetrievalTraceLeg\n}\n\nfunction anchorDisplayText(anchor: Anchor): string {\n switch (anchor.t) {\n case 'page':\n return anchor.route\n case 'flow':\n return anchor.name\n default:\n return canonicalJson(anchor)\n }\n}\n\nfunction boundedExcerpt(parts: readonly string[]): string {\n return parts.filter((part) => part !== '').join(' — ').slice(0, AUTHORING_EXCERPT_CHAR_BUDGET)\n}\n\nfunction verifiedExemplarCandidate(\n row: AuthoringExemplarRow,\n targetKeys: ReadonlySet<string>,\n tokens: readonly string[],\n): ExemplarCandidate[] {\n // D-15 hard excludes fire on the FIRST observed negative signal: any observed flake or a\n // currently-failing recent window, before relevance scoring. The quarantine leg is the third,\n // and as of 390 D-02 its truth is the COMMITTED ledger's state fold, not a derived projection\n // column — this assembler stays pure, so the flag arrives already resolved on the row and the\n // reader that hydrates it owns the ledger read. (Store-status candidate/deprecated exclusion is\n // vacuous in M2 — tests are never memidex records; the clause activates if that ever changes.)\n const latestOutcome = row.lastOutcomes.at(-1)\n if (row.quarantined || row.flakeCount >= 1 || latestOutcome?.passed === false) return []\n const windowPasses = row.lastOutcomes.filter(({ passed }) => passed).length\n\n const rowKeys = new Set(row.anchorKeys)\n // Two terms here, not three: an exemplar is a test reference in the run-outcome projection and\n // the dense leg never scores one. Attribution reads the same two products relevance summed.\n const contributions: Record<RetrievalTraceLeg, number> = {\n anchor: anchorOverlapShare(rowKeys, targetKeys),\n lexical: AUTHORING_LEXICAL_WEIGHT\n * lexicalRelevance(tokens, `${row.testName} ${row.filePath}`),\n dense: 0,\n }\n const relevance = Math.min(1, contributions.anchor + contributions.lexical)\n if (relevance === 0) return []\n\n const recentPassRate = row.lastOutcomes.length > 0\n ? windowPasses / row.lastOutcomes.length\n : (row.passes + row.failures > 0 ? row.passes / (row.passes + row.failures) : 1)\n const matchedKeys = [...rowKeys].filter((key) => targetKeys.has(key)).sort()\n const matchedAnchors = matchedKeys.map((key) => JSON.parse(key) as Anchor)\n const total = row.passes + row.failures\n\n return [{\n identity: identityTupleKey([row.filePath, row.testName]),\n anchorKeys: new Set(matchedKeys),\n // D-15 fold: trust (neutral 1 for projection-verified rows) x recent-pass-rate x relevance.\n score: recentPassRate * relevance,\n leg: dominantAuthoringLeg(contributions),\n exemplar: {\n filePath: row.filePath,\n testName: row.testName,\n matchedAnchors,\n ...(total > 0 ? { passRate: row.passes / total } : {}),\n recentOutcomes: row.lastOutcomes.map(({ buildOrdinal, passed }) => (\n { buildOrdinal, passed }\n )),\n unverifiedOutcomes: false,\n excerpt: boundedExcerpt([\n row.testName,\n `outcomes ${row.passes} pass / ${row.failures} fail${\n row.heals > 0 ? ` (${row.heals} heals)` : ''}`,\n matchedAnchors.length > 0\n ? `anchors: ${matchedAnchors.map(anchorDisplayText).join(', ')}`\n : '',\n ]),\n },\n }]\n}\n\nfunction neverRunExemplarCandidate(\n ref: AuthoringTestRef,\n tokens: readonly string[],\n): ExemplarCandidate[] {\n const relevance = lexicalRelevance(tokens, `${ref.testName} ${ref.filePath}`)\n if (relevance === 0) return []\n\n return [{\n identity: identityTupleKey([ref.filePath, ref.testName]),\n anchorKeys: new Set<string>(),\n // Neutral trust, no observed pass-rate: discounted below verified rows, never dropped.\n score: AUTHORING_UNVERIFIED_OUTCOMES_DISCOUNT * relevance,\n // A never-run reference has no projection anchors at all, so the lexical match against its\n // identity is the entire reason it is here.\n leg: 'lexical',\n exemplar: {\n filePath: ref.filePath,\n testName: ref.testName,\n matchedAnchors: [],\n unverifiedOutcomes: true,\n excerpt: boundedExcerpt([\n ref.testName,\n 'unverified-outcomes: no completed-run evidence yet',\n ]),\n },\n }]\n}\n\nfunction exemplarRerankEntry(\n candidate: ExemplarCandidate,\n scope: ScopeKey,\n): RerankEntry & { candidate: ExemplarCandidate } {\n return {\n candidate,\n bundleId: candidate.identity,\n validityClass: 'current',\n trust: candidate.score,\n scope,\n recencyOrdinal: 0,\n createdAtOrdinal: 0,\n originClass: 'agent',\n anchors: candidate.exemplar.matchedAnchors,\n subtype: null,\n lastConfirmedOrdinal: 0,\n }\n}\n\nfunction mmrOverlapPenalty(\n candidate: ExemplarCandidate,\n selected: readonly ExemplarCandidate[],\n): number {\n if (candidate.anchorKeys.size === 0) return 0\n let best = 0\n for (const other of selected) {\n let matched = 0\n for (const key of candidate.anchorKeys) {\n if (other.anchorKeys.has(key)) matched += 1\n }\n best = Math.max(best, matched / candidate.anchorKeys.size)\n }\n return best\n}\n\n/**\n * The no-analog exemplar bucket composed from parts: anchor-overlap scoring on the projection's\n * normalized keys, per-anchor diversity via applyDiversityCaps, then greedy MMR selection.\n */\nfunction selectExemplars(\n input: AssembleAuthoringBriefInput,\n targetKeys: ReadonlySet<string>,\n tokens: readonly string[],\n): ExemplarCandidate[] {\n const projectionIdentities = new Set(\n input.projectionRows.map((row) => identityTupleKey([row.filePath, row.testName])),\n )\n const candidates = [\n ...input.projectionRows.flatMap((row) =>\n verifiedExemplarCandidate(row, targetKeys, tokens)),\n ...(input.knownTests ?? []).flatMap((ref) =>\n projectionIdentities.has(identityTupleKey([ref.filePath, ref.testName]))\n ? []\n : neverRunExemplarCandidate(ref, tokens)),\n ].sort((left, right) => (\n right.score - left.score || compareText(left.identity, right.identity)\n ))\n\n const diverse = applyDiversityCaps(\n candidates.map((candidate) => exemplarRerankEntry(candidate, input.scope)),\n ).map(({ candidate }) => candidate)\n\n const selected: ExemplarCandidate[] = []\n const pool = [...diverse]\n while (selected.length < AUTHORING_EXEMPLAR_CAP && pool.length > 0) {\n let bestIndex = 0\n let bestValue = Number.NEGATIVE_INFINITY\n for (const [index, candidate] of pool.entries()) {\n const value = candidate.score\n - AUTHORING_MMR_WEIGHT * mmrOverlapPenalty(candidate, selected)\n if (\n value > bestValue\n || (value === bestValue\n && compareText(candidate.identity, pool[bestIndex]!.identity) < 0)\n ) {\n bestIndex = index\n bestValue = value\n }\n }\n selected.push(...pool.splice(bestIndex, 1))\n }\n return selected\n}\n\nfunction exemplarRecordId(exemplar: ExemplarTest): string {\n return `exemplar:${identityTupleKey([exemplar.filePath, exemplar.testName])}`\n}\n\ninterface ServableItem {\n metadata: ServingRecordMetadata\n serve: () => void\n /** D-16 attribution carried from the scoring that produced this candidate's position. */\n leg: RetrievalTraceLeg\n score: number\n}\n\n/**\n * The §10.6 authoring brief together with its serve-time trace (D-16). The 4th channel returns the\n * composite for the same reason the run brief does — capture is generic at the SEAM, so 393/394\n * inherit it by destructuring rather than by re-implementing it.\n */\nexport interface AssembledAuthoringBrief {\n readonly brief: AuthoringBrief\n readonly trace: ServedRetrievalTraceV1\n}\n\n/**\n * Pure screenless assembly over already-loaded snapshot inputs. Retrieval SQL, hydration,\n * budgets-as-plain-numbers, and the projection read all live at the composition boundary\n * (`createAuthoringReader`); nothing here touches a connection, the clock, or the filesystem.\n *\n * The trace's `rank` is the candidate's 1-based position in the ONE admission walk below —\n * caution, then procedure, then exemplar, then fact — which is the actual total order this\n * assembly serves in. Everything the ledger admits becomes a served line; everything it sheds\n * becomes a cut candidate, bounded by the pinned top-K.\n */\nexport function assembleAuthoringBrief(\n input: AssembleAuthoringBriefInput,\n): AssembledAuthoringBrief {\n const targetKeys = new Set(input.targetAnchors.map(normalizedAnchorKey))\n const tokens = intentTokens(input.intent)\n\n const cautions: CautionLine[] = []\n const cautionItems: ServableItem[] = scoreEntries(input, 'caution', targetKeys, tokens)\n .map(({ entry, score, leg }) => {\n const rendered = renderCautionLine(entry)\n return {\n metadata: servingRecordMetadata({\n id: entry.id,\n anchors: entry.anchors,\n renderedCost: rendered.cost,\n }),\n leg,\n score,\n serve: () => cautions.push({\n id: entry.id,\n anchors: entry.anchors,\n summary: rendered.summary,\n }),\n }\n })\n\n const procedures: ProcedureMatch[] = []\n const procedureItems: ServableItem[] = topProcedures(input).map((match) => ({\n metadata: servingRecordMetadata({\n id: match.id,\n anchors: [match.flowAnchor],\n renderedCost: estimateRenderedServingCost(canonicalJson(match)),\n }),\n // matchProcedure drops any candidate whose anchor relevance is zero before scoring it, so a\n // procedure is here because an anchor matched. Its confidence IS the fold's own score.\n leg: 'anchor',\n score: match.confidence,\n serve: () => procedures.push(match),\n }))\n\n const exemplars: ExemplarTest[] = []\n const exemplarItems: ServableItem[] = selectExemplars(input, targetKeys, tokens)\n .map(({ exemplar, score, leg }) => ({\n metadata: servingRecordMetadata({\n id: asRecordId(exemplarRecordId(exemplar)),\n anchors: exemplar.matchedAnchors,\n renderedCost: estimateRenderedServingCost(canonicalJson(exemplar)),\n }),\n leg,\n score,\n serve: () => exemplars.push(exemplar),\n }))\n\n const facts: BriefLine[] = []\n const factItems: ServableItem[] = scoreEntries(input, 'fact', targetKeys, tokens)\n .map(({ entry, score, leg }) => {\n const rendered = renderBriefLine(entry)\n return {\n metadata: servingRecordMetadata({\n id: entry.id,\n anchors: entry.anchors,\n renderedCost: rendered.cost,\n }),\n leg,\n score,\n serve: () => facts.push(rendered.briefLine),\n }\n })\n\n // Locked shed order: admit caution -> procedure -> exemplar -> fact against ONE ledger; a shed\n // in any bucket closes every lower-precedence bucket so facts always drop first.\n const admission = createServingAdmissionState()\n const admissions: ServingRecordMetadata[] = []\n const servedLines: TraceLine[] = []\n const truncated: TraceLine[] = []\n let eligible = 0\n let served = 0\n let closed = false\n let rank = 0\n const cutLine = (item: ServableItem, ordinal: number): TraceLine => traceLine({\n recordId: String(item.metadata.id),\n leg: item.leg,\n rank: ordinal,\n score: item.score,\n })\n for (const bucket of [cautionItems, procedureItems, exemplarItems, factItems]) {\n eligible += bucket.length\n if (closed) {\n // A closed bucket is shed WHOLE without consulting the ledger. Those candidates are\n // recorded here rather than inferred later from what is missing from the brief — a\n // whole-bucket shed is exactly the \"why didn't it mention X\" case D-14 exists for.\n for (const item of bucket) {\n rank += 1\n truncated.push(cutLine(item, rank))\n }\n continue\n }\n let bucketShed = false\n for (const item of bucket) {\n rank += 1\n const line = cutLine(item, rank)\n if (!tryAdmitServingRecord({\n record: item.metadata,\n budget: input.budget,\n recordCap: Number.POSITIVE_INFINITY,\n }, admission).admitted) {\n bucketShed = true\n truncated.push(line)\n continue\n }\n item.serve()\n admissions.push(item.metadata)\n servedLines.push(line)\n served += 1\n }\n if (bucketShed) closed = true\n }\n\n return {\n brief: {\n exemplars,\n procedures,\n facts,\n cautions,\n coverage: {},\n truncation: served < eligible ? `truncated ${served} of ${eligible}` : '',\n admissions,\n },\n trace: composeServedTrace({ servedLines, truncated }),\n }\n}\n","/**\n * The ONE fold from the host's two retrieval axes to the recorded rung (407 TRST-01 · D-13/D-17).\n *\n * ONE resolver, three callers: the runner's evidence recorder (407-07) stamps the value into\n * `StepEvidence.retrievalRung`, `doctor` (407-08) grades it live, and the run header banner\n * (407-10) renders the recorded copy. Three callers deriving a rung independently from the same\n * two axes is exactly how a banner and a doctor row come to disagree about one machine, so the\n * fold table lives here once and its cells are pinned by `__tests__/retrieval-rung.test.ts`.\n *\n * WHAT THE VALUE MEANS. It is the HOST's ladder at serve time — never a claim about how any\n * individual brief line was ranked. The run-brief serve path reads index rows directly and\n * attributes channels 1 and 3 to the `anchor` leg by construction; the dense leg and the\n * bundle-scan fallback belong to the general `retrieve()` path the curator, the entity resolver\n * and the authoring reader use. A surface renders \"retrieval was on rung X for this run\".\n *\n * This module lives in knowledge-local because it is the only package that can see either axis:\n * the index face is `index-reader`'s degrade ladder and the embedder outcome is\n * `embedder-acquire`'s capability probe. What it hands back is the schema-owned value.\n */\nimport {\n DEFAULT_EMBEDDING_PROFILE,\n type EmbeddingProfile,\n type RecordedRetrievalRung,\n type RetrievalRungReason,\n} from '@vostride/agent-qa-schema'\n\nimport {\n resolveEmbedderCapability,\n type AcquireEmbedderOutcome,\n type DeferReason,\n type EmbedderProbes,\n} from './embedder-acquire.js'\nimport { classifyIndexFace, type IndexFace } from './index-reader.js'\nimport type { RebuildReason } from './rebuild-marker.js'\n\n/** The index half of the fold — `index-reader`'s degrade ladder, read without side effects. */\nexport type IndexAxis = IndexFace\n\n/** The embedder half of the fold — `embedder-acquire`'s capability outcome, unchanged. */\nexport type EmbedderAxis = AcquireEmbedderOutcome\n\n/**\n * `RebuildReason` → the recorded cause (423 D-22), as a total map for the same reason as below.\n *\n * `schema-version` and `corrupt` share one cause: both mean \"rebuild requested\" and the operator\n * does the same thing for either. `index-unavailable` is deliberately NOT a value here — it is the\n * historical word for a scan whose cause was never recorded, and no current fold may mint it.\n */\nconst INDEX_REASONS: Record<RebuildReason, RetrievalRungReason> = {\n absent: 'index-not-built',\n locked: 'index-locked',\n corrupt: 'index-corrupt',\n 'schema-version': 'index-corrupt',\n}\n\n/**\n * `DeferReason` → the recorded reason word, as a total map rather than a switch with a default.\n * A new `DeferReason` arm becomes a compile error here instead of silently folding to a wrong\n * word that a banner would then print to a person.\n */\nconst DEFERRED_REASONS: Record<DeferReason, RetrievalRungReason> = {\n 'cold-artifact': 'model-not-downloaded',\n 'load-failure': 'embedder-load-failed',\n 'worker-unavailable': 'profile-unresolved',\n}\n\n/**\n * Fold the two axes into the value that gets recorded (D-17).\n *\n * ORDERING IS PART OF THE CONTRACT: the index axis is consulted FIRST. No dense leg can run\n * against an index that will not open, whatever the embedder resolved to, so a `scan` face is\n * `bundle-scan` even on a host with a live native embedder. Folding the embedder first would\n * label a host with an unopenable index `memidex` and make the banner lie.\n *\n * `reason` is ABSENT for `memidex` — the top rung is not a degradation and has no cause to name.\n * Every lower rung carries one, which is what lets the banner say rung AND cause in one line.\n */\nexport function foldRetrievalRung(\n index: IndexAxis,\n embedder: EmbedderAxis,\n preferredProfile: EmbeddingProfile = DEFAULT_EMBEDDING_PROFILE,\n): RecordedRetrievalRung {\n if (index.source === 'scan') {\n return { schemaVersion: 2, rung: 'bundle-scan', reason: INDEX_REASONS[index.reason] }\n }\n\n if (embedder.kind === 'ready') {\n if (embedder.rung === 'native') {\n return { schemaVersion: 2, rung: 'memidex' }\n }\n // Same rung, two different truths. A static PREFERRED profile means the floor is serving\n // because it was asked for; anything else means the native runtime could not load. An\n // operator reading `native-runtime-unavailable` on a deliberately-static host would go\n // hunting for a fault that does not exist.\n return {\n schemaVersion: 2,\n rung: 'static-floor',\n reason:\n preferredProfile.backend === 'static'\n ? 'profile-static-configured'\n : 'native-runtime-unavailable',\n }\n }\n\n if (embedder.kind === 'deferred') {\n return { schemaVersion: 2, rung: 'lexical-only', reason: DEFERRED_REASONS[embedder.reason] }\n }\n\n return { schemaVersion: 2, rung: 'lexical-only', reason: 'floor-disabled' }\n}\n\nexport interface ResolveRetrievalRungOptions {\n knowledgeRoot: string\n /** Explicit hosted runtime root for worker discovery; defaults to the acquirer's own rule. */\n agentQaRoot?: string\n preferredProfile?: EmbeddingProfile\n /** D-12/D-17 test seam, passed through unchanged. Production callers omit it. */\n probes?: EmbedderProbes\n}\n\n/**\n * Probe both axes and fold them (D-17). NEVER throws, NEVER downloads, NEVER writes.\n *\n * - `allowDownload: false` is hard-coded, not an option: this call answers \"what is this host\n * doing today\", and a probe that fetched a model would change the answer by asking it (T-407-09).\n * - A `scan` face short-circuits before the embedder is touched at all. The fold does not need the\n * embedder axis in that arm, and the probe can cost a model load.\n * - A rejected capability probe folds to `deferred/load-failure` rather than propagating. This\n * resolver's callers are a banner, a doctor row and an evidence recorder; none of them has a\n * sensible behaviour for \"asking about the ladder threw\".\n * - `classifyIndexFace` writes no rebuild marker, so asking is not a mutation of the knowledge root.\n *\n * The memo inside `resolveEmbedderCapability` is what makes a second call in the same process free,\n * which is why `doctor` and the runner can both ask without paying twice.\n */\nexport async function resolveRetrievalRung(\n options: ResolveRetrievalRungOptions,\n): Promise<RecordedRetrievalRung> {\n const preferredProfile = options.preferredProfile ?? DEFAULT_EMBEDDING_PROFILE\n const index = classifyIndexFace(options.knowledgeRoot)\n if (index.source === 'scan') {\n return foldRetrievalRung(index, { kind: 'lexical-only' }, preferredProfile)\n }\n\n let embedder: EmbedderAxis\n try {\n embedder = await resolveEmbedderCapability({\n preferredProfile,\n allowDownload: false,\n agentQaRoot: options.agentQaRoot,\n probes: options.probes,\n })\n } catch {\n embedder = { kind: 'deferred', reason: 'load-failure' }\n }\n\n return foldRetrievalRung(index, embedder, preferredProfile)\n}\n","/**\n * IDX-01's derived-index writer over canonical Phase 374 bundles.\n *\n * D-02 keeps an absent embedder as a successful all-pending posture; D-05 indexes the bundle's\n * committed embeddingInput; D-10 stores every vector canonically in records before optionally\n * accelerating it through vec0. Per 374 D-03, loadBundle + deriveBundleTrust are the only bundle\n * projection faces. Relation edges are emitted from the complete integrity-valid walk in a second\n * pass so bundle ordering cannot change dangling-target behavior and late targets heal without\n * re-projecting an unchanged source.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { basename, join } from 'node:path'\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n anchorGraphNode,\n canonicalJson,\n guardDistilledObservation,\n guardTrustPriorTable,\n recordGraphNode,\n} from '@vostride/agent-qa-schema'\nimport type {\n BundleStatus,\n DistilledObservation,\n EmbeddingProfile,\n GraphNodeNaturalKey,\n GraphNodeType,\n Platform,\n TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle, verifyBundleIntegrity } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\nimport {\n enumerateBundleDirs,\n resolveProductQualifiedBundleDir,\n} from './bundle-scan.js'\nimport {\n buildSituatingLine,\n computeRenderingDrift,\n renderContextual,\n} from './contextual-rendering.js'\nimport type { EmbedderPort } from './embedder-port.js'\nimport {\n deriveEquivalentToBridges,\n deriveLocatesViaEdges,\n deriveObservationEdges,\n} from './graph-derive.js'\nimport type {\n DerivedGraphEdge,\n DerivedGraphNode,\n GraphDerivation,\n GraphDerivationContext,\n} from './graph-derive.js'\nimport {\n CHECKPOINT_EVERY_N_BUNDLES,\n deleteRecordFromAllSchemaVecTables,\n indexDbPath,\n isEmbeddingVecCleanupCurrent,\n openIndexWriter,\n resolveActiveProfile,\n vecTableName,\n} from './index-open.js'\nimport type { VecCapability } from './index-open.js'\nimport {\n withCurrentWriterAuthority,\n type WriterLeaseAuthority,\n} from './lease/writer-lease.js'\nimport { clearRebuildRequest } from './rebuild-marker.js'\nimport { effectivePriorDigest } from './trust-prior-context.js'\nimport { snapshotTrustPriors } from './promotion-gate-input.js'\n\nexport interface RebuildReport {\n projected: number\n skippedIncomplete: number\n scanIssues: string[]\n removed: number\n backfilled: number\n vec: VecCapability\n pendingEmbeddings: number\n maintenanceRemaining: boolean\n}\n\nexport type RebuildMutationFamily =\n | 'project-bundle'\n | 'checkpoint-passive'\n | 'remove-missing-bundles'\n | 'complete-rendering-epoch'\n | 'complete-trust-epoch'\n | 'clear-rebuild-request'\n\nexport interface RebuildIndexHooks {\n /** Test/chaos seam after synchronous DML and immediately before the final commit fence. */\n beforeTransactionCommit?: () => void\n /** Test/chaos seam immediately before one named authority unit acquires its hold. */\n beforeMutationAuthority?: (family: RebuildMutationFamily) => void\n /** Test/chaos seam after authority is held and before the named mutation begins. */\n insideMutationAuthority?: (family: RebuildMutationFamily) => void\n}\n\nexport interface RebuildIndexOptions {\n knowledgeRoot: string\n priors?: TrustPriorTable\n embedder?: EmbedderPort\n vecLoadablePath?: string\n writerAuthority?: WriterLeaseAuthority\n hooks?: RebuildIndexHooks\n}\n\nexport interface ProjectBundleIndexRowOptions {\n knowledgeRoot: string\n priors?: TrustPriorTable\n bundleId: string\n /** Required whenever the same content-addressed id exists in more than one product. */\n product?: string\n}\n\nexport const EMBED_STATUS_PENDING = 'pending'\nexport const EMBED_STATUS_PRESENT = 'present'\n/**\n * SAFE-02 terminal state: lexical projection exists, but dense bytes must never be backfilled.\n * 2026-10-15 (441-24, D-27): nothing writes it now; rows indexed before 441 may still hold it.\n */\nexport const EMBED_STATUS_SUPPRESSED = 'suppressed'\n/**\n * Structurally-dead dense suppression (Deprecate/Supersede scrub), distinct from the SAFE-02\n * terminal above. The contract pair: structural death is reversible — projecting the record live\n * again (e.g. a rollback restore) resets this value to pending so ordinary backfill re-embeds it —\n * while a row already holding EMBED_STATUS_SUPPRESSED stays terminal, including through a\n * death-and-revival cycle.\n */\nexport const EMBED_STATUS_SCRUBBED = 'scrubbed'\n\nexport interface PendingEmbeddingRow {\n record_rowid: number\n bundle_id: string\n contextual_rendering: string\n}\n\n/** The single selector used by ordinary vector backfill; terminal suppression is not pending. */\nexport function selectPendingEmbeddingRows(db: DatabaseSync): PendingEmbeddingRow[] {\n return db\n .prepare(`\n SELECT record_rowid, bundle_id, contextual_rendering\n FROM records\n WHERE embed_status = ?\n ORDER BY record_rowid\n `)\n .all(EMBED_STATUS_PENDING)\n .map((row) => ({\n record_rowid: Number(row.record_rowid),\n bundle_id: String(row.bundle_id),\n contextual_rendering: String(row.contextual_rendering),\n }))\n}\n\ninterface ProjectedBundle {\n bundle: LoadedBundle\n dir: string\n product: string\n}\n\ntype AnchorNode = NonNullable<ReturnType<typeof anchorGraphNode>>\n\ninterface InsertableGraphNode {\n nodeId: string\n type: GraphNodeType\n naturalKey: GraphNodeNaturalKey\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\ntype MutationAuthorityContext =\n | { hold: WriterLeaseAuthority }\n | { withinHeldAuthority: true }\n\n/**\n * The hold form owns one authority-store transaction for the operation. The within-held form is\n * deliberately raw: its caller already owns that outer transaction and must not re-enter the\n * non-reentrant authority primitive.\n */\nfunction withMutationAuthority<T>(\n authority: MutationAuthorityContext | undefined,\n operation: () => T,\n): T {\n if (authority !== undefined && 'hold' in authority) {\n return withCurrentWriterAuthority(\n authority.hold.knowledgeRoot,\n authority.hold,\n operation,\n )\n }\n return operation()\n}\n\nfunction withNamedMutationAuthority<T>(\n authority: MutationAuthorityContext | undefined,\n family: RebuildMutationFamily,\n hooks: RebuildIndexHooks | undefined,\n operation: () => T,\n): T {\n hooks?.beforeMutationAuthority?.(family)\n return withMutationAuthority(authority, () => {\n hooks?.insideMutationAuthority?.(family)\n return operation()\n })\n}\n\nfunction transaction(\n db: DatabaseSync,\n operation: () => void,\n authority?: MutationAuthorityContext,\n beforeCommit?: () => void,\n namedMutation?: {\n family: RebuildMutationFamily\n hooks: RebuildIndexHooks | undefined\n },\n): void {\n const transact = (): void => {\n db.exec('BEGIN IMMEDIATE')\n try {\n operation()\n beforeCommit?.()\n db.exec('COMMIT')\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the projection error that caused the rollback.\n }\n throw error\n }\n }\n if (namedMutation === undefined) {\n withMutationAuthority(authority, transact)\n return\n }\n withNamedMutationAuthority(\n authority,\n namedMutation.family,\n namedMutation.hooks,\n transact,\n )\n}\n\nfunction embeddingBuffer(vector: Float32Array, activeProfile: EmbeddingProfile): Buffer {\n if (vector.length !== activeProfile.dim) {\n throw new RangeError(\n `embedder returned ${vector.length} dimensions; expected ${activeProfile.dim}`,\n )\n }\n return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength)\n}\n\ninterface VecRowMetadata {\n product: string\n scopeTier: string\n scopeKey: string\n status: string\n}\n\nfunction recordVecMetadata(db: DatabaseSync, recordRowid: number): VecRowMetadata {\n const row = db\n .prepare(`\n SELECT product, scope_tier, scope_key, status\n FROM records\n WHERE record_rowid = ?\n `)\n .get(recordRowid)\n if (row === undefined) {\n throw new Error(`vec metadata source record ${recordRowid} is missing`)\n }\n return {\n product: String(row.product),\n scopeTier: String(row.scope_tier),\n scopeKey: String(row.scope_key),\n status: String(row.status),\n }\n}\n\nfunction identityText(bundle: LoadedBundle): string {\n return bundle.frontmatter.anchors\n .flatMap(({ raw }) => {\n const serialized = canonicalJson(raw)\n if (raw.t === 'selector') return [serialized, raw.literal]\n if (raw.t === 'error') return [serialized, raw.message]\n return [serialized]\n })\n .join('\\n')\n}\n\nfunction bundlePlatform(bundle: LoadedBundle): Platform | undefined {\n for (const { normalized } of bundle.frontmatter.anchors) {\n if (normalized.t === 'platform') return normalized.platform\n }\n return undefined\n}\n\nfunction insertGraphNode(\n db: DatabaseSync,\n node: InsertableGraphNode,\n product: string,\n): void {\n db.prepare(`\n INSERT OR IGNORE INTO graph_nodes (\n node_id, node_type, natural_key_json, product\n ) VALUES (?, ?, ?, ?)\n `).run(node.nodeId, node.type, canonicalJson(node.naturalKey), product)\n}\n\nfunction insertGraphEdge(\n db: DatabaseSync,\n edge: {\n srcNodeId: string\n edgeType: string\n dstNodeId: string\n recordRowid: number\n product: string\n recencyOrdinal: number\n },\n): void {\n db.prepare(`\n INSERT OR IGNORE INTO graph_edges (\n src_node_id, edge_type, dst_node_id, record_rowid, product, recency_ordinal\n ) VALUES (?, ?, ?, ?, ?, ?)\n `).run(\n edge.srcNodeId,\n edge.edgeType,\n edge.dstNodeId,\n edge.recordRowid,\n edge.product,\n edge.recencyOrdinal,\n )\n}\n\nfunction insertGraphDerivation(db: DatabaseSync, projection: GraphDerivation): void {\n for (const node of projection.nodes) insertGraphNode(db, node, node.product)\n for (const edge of projection.edges) insertGraphEdge(db, edge)\n}\n\nfunction upsertRecord(\n db: DatabaseSync,\n bundle: LoadedBundle,\n product: string,\n priors?: TrustPriorTable,\n): { recordRowid: number; status: BundleStatus } {\n const trust = deriveBundleTrust(bundle, priors)\n const digest = effectivePriorDigest(priors)\n // A delta may change one row to another epoch, but cannot certify the full index.\n db.prepare(\"DELETE FROM meta WHERE k = 'trust_prior_digest' AND v != ?\").run(digest)\n db.prepare(`\n INSERT INTO records (\n bundle_id, product, mutable_state_hash, kind, subtype, scope_tier, scope_key,\n status, trust, confirmed, contradicted, helpful, harmful, last_confirmed_ordinal,\n opened_at_ordinal, closed_at_ordinal, created_at_ordinal, origin_class, summary,\n embedding_input, situating_line, contextual_rendering, trust_prior_digest\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(bundle_id) DO UPDATE SET\n product = excluded.product,\n mutable_state_hash = excluded.mutable_state_hash,\n kind = excluded.kind,\n subtype = excluded.subtype,\n scope_tier = excluded.scope_tier,\n scope_key = excluded.scope_key,\n status = excluded.status,\n trust = excluded.trust,\n trust_prior_digest = excluded.trust_prior_digest,\n confirmed = excluded.confirmed,\n contradicted = excluded.contradicted,\n helpful = excluded.helpful,\n harmful = excluded.harmful,\n last_confirmed_ordinal = excluded.last_confirmed_ordinal,\n opened_at_ordinal = excluded.opened_at_ordinal,\n closed_at_ordinal = excluded.closed_at_ordinal,\n created_at_ordinal = excluded.created_at_ordinal,\n origin_class = excluded.origin_class,\n summary = excluded.summary,\n embedding_input = excluded.embedding_input\n `).run(\n bundle.manifest.id,\n product,\n bundle.manifest.mutableStateHash,\n bundle.frontmatter.kind,\n bundle.frontmatter.subtype ?? null,\n bundle.frontmatter.scope.tier,\n bundle.frontmatter.scope.key,\n trust.status,\n trust.trust,\n trust.counters.confirmed,\n trust.counters.contradicted,\n trust.counters.helpful,\n trust.counters.harmful,\n trust.lastConfirmedOrdinal,\n trust.validity.openedAtOrdinal,\n trust.validity.closedAtOrdinal ?? null,\n bundle.frontmatter.createdAtOrdinal,\n bundle.frontmatter.originClass,\n bundle.summary,\n bundle.manifest.embeddingInput,\n '',\n bundle.manifest.embeddingInput,\n digest,\n )\n\n const row = db\n .prepare('SELECT record_rowid FROM records WHERE bundle_id = ?')\n .get(bundle.manifest.id)\n if (row === undefined) throw new Error(`record upsert lost bundle ${bundle.manifest.id}`)\n return { recordRowid: Number(row.record_rowid), status: trust.status }\n}\n\nfunction replaceFtsAndAnchors(\n db: DatabaseSync,\n bundle: LoadedBundle,\n product: string,\n recordRowid: number,\n): void {\n const rendering = db\n .prepare('SELECT situating_line FROM records WHERE record_rowid = ?')\n .get(recordRowid)\n if (rendering === undefined) {\n throw new Error(`FTS projection source record ${recordRowid} is missing`)\n }\n db.prepare('DELETE FROM fts_records WHERE rowid = ?').run(recordRowid)\n db.prepare(`\n INSERT INTO fts_records (rowid, identity, content, context)\n VALUES (?, ?, ?, ?)\n `).run(\n recordRowid,\n identityText(bundle),\n bundle.manifest.embeddingInput,\n String(rendering.situating_line),\n )\n\n db.prepare('DELETE FROM anchors WHERE record_rowid = ?').run(recordRowid)\n const insertAnchor = db.prepare(`\n INSERT INTO anchors (\n record_rowid, product, t, raw_json, normalized_json\n ) VALUES (?, ?, ?, ?, ?)\n `)\n for (const anchor of bundle.frontmatter.anchors) {\n insertAnchor.run(\n recordRowid,\n product,\n anchor.normalized.t,\n canonicalJson(anchor.raw),\n canonicalJson(anchor.normalized),\n )\n }\n}\n\nfunction replaceAnchorGraph(\n db: DatabaseSync,\n bundle: LoadedBundle,\n product: string,\n recordRowid: number,\n): void {\n db.prepare('DELETE FROM graph_edges WHERE record_rowid = ?').run(recordRowid)\n\n const recordNode = recordGraphNode(bundle.frontmatter.kind, bundle.manifest.id)\n insertGraphNode(db, recordNode, product)\n\n const platform = bundlePlatform(bundle)\n const nodes = new Map<string, AnchorNode>()\n for (const { normalized } of bundle.frontmatter.anchors) {\n const node = anchorGraphNode(normalized, platform)\n if (node !== null) nodes.set(node.nodeId, node)\n }\n\n const elementNodes: AnchorNode[] = []\n const pageNodes: AnchorNode[] = []\n for (const node of nodes.values()) {\n insertGraphNode(db, node, product)\n insertGraphEdge(db, {\n srcNodeId: recordNode.nodeId,\n edgeType: 'about',\n dstNodeId: node.nodeId,\n recordRowid,\n product,\n recencyOrdinal: bundle.frontmatter.createdAtOrdinal,\n })\n if (node.type === 'element' || node.type === 'web-element' || node.type === 'mobile-element') {\n elementNodes.push(node)\n }\n if (node.type === 'page' || node.type === 'web-page' || node.type === 'mobile-screen') {\n pageNodes.push(node)\n }\n }\n\n for (const element of elementNodes) {\n for (const page of pageNodes) {\n insertGraphEdge(db, {\n srcNodeId: element.nodeId,\n edgeType: 'part-of',\n dstNodeId: page.nodeId,\n recordRowid,\n product,\n recencyOrdinal: bundle.frontmatter.createdAtOrdinal,\n })\n }\n }\n\n insertGraphDerivation(\n db,\n deriveLocatesViaEdges(\n bundle.frontmatter.anchors.map(({ normalized }) => normalized),\n platform,\n {\n bundleId: bundle.manifest.id,\n recordRowid,\n product,\n createdAtOrdinal: bundle.frontmatter.createdAtOrdinal,\n },\n ),\n )\n}\n\nfunction storeEmbedding(\n db: DatabaseSync,\n vec: VecCapability,\n recordRowid: number,\n vector: Float32Array,\n activeProfile: EmbeddingProfile,\n): void {\n const bytes = embeddingBuffer(vector, activeProfile)\n db.prepare(`\n UPDATE records\n SET embedding = ?, embed_status = ?\n WHERE record_rowid = ?\n `).run(bytes, EMBED_STATUS_PRESENT, recordRowid)\n\n if (vec === 'vec0') {\n const metadata = recordVecMetadata(db, recordRowid)\n const tableName = vecTableName(activeProfile)\n db.prepare(`DELETE FROM ${tableName} WHERE record_rowid = ?`).run(BigInt(recordRowid))\n db.prepare(`\n INSERT INTO ${tableName} (\n record_rowid, product, scope_tier, scope_key, status, embedding\n ) VALUES (?, ?, ?, ?, ?, ?)\n `).run(\n BigInt(recordRowid),\n metadata.product,\n metadata.scopeTier,\n metadata.scopeKey,\n metadata.status,\n bytes,\n )\n }\n}\n\nfunction refreshVecMetadata(\n db: DatabaseSync,\n vec: VecCapability,\n recordRowid: number,\n activeProfile: EmbeddingProfile,\n): void {\n if (vec !== 'vec0') return\n const metadata = recordVecMetadata(db, recordRowid)\n db.prepare(`\n UPDATE ${vecTableName(activeProfile)}\n SET scope_tier = ?, scope_key = ?, status = ?\n WHERE record_rowid = ?\n `).run(\n metadata.scopeTier,\n metadata.scopeKey,\n metadata.status,\n BigInt(recordRowid),\n )\n}\n\nfunction isDeadStatus(status: unknown): status is 'superseded' | 'deprecated' {\n return status === 'superseded' || status === 'deprecated'\n}\n\nfunction deleteOrphanGraphNodes(db: DatabaseSync): void {\n db.exec(`\n DELETE FROM graph_nodes\n WHERE node_id NOT IN (\n SELECT src_node_id FROM graph_edges\n UNION\n SELECT dst_node_id FROM graph_edges\n )\n `)\n}\n\n/**\n * 379 D-10/D-11 structural forgetting lives inside the canonical projection unit. Every full or\n * single-bundle projection therefore re-derives the scrub: lexical/vector/graph recall rows die,\n * while records and anchors deliberately survive for includeSuperseded/as-of audit reads. The\n * status pre-filter remains the second wall during the commit-to-projection gap.\n */\nfunction scrubDeadRecallRows(\n db: DatabaseSync,\n bundle: LoadedBundle,\n recordRowid: number,\n): void {\n db.prepare('DELETE FROM fts_records WHERE rowid = ?').run(recordRowid)\n deleteRecordFromAllSchemaVecTables(db, recordRowid)\n /**\n * RATIFICATION (revised, round 4): the round-1 ratification reused SAFE-02's terminal suppressed\n * state here. Round-4 verification proved that conflation makes a rollback-restored supersession\n * victim permanently lose dense recall — the restore re-projection cannot distinguish structural\n * death from governed redaction, and D-15 requires the scrub effect to be invertible. Structural\n * death therefore takes its own reversible scrubbed value, while a row already redacted under\n * SAFE-02 before dying keeps the terminal value through death (terminal wins) so revival can\n * never resurrect redacted content. While dead, both values stay outside the pending backfill\n * selector, rendering refresh, and present-only reconciliation exactly as before the split.\n */\n db.prepare(`\n UPDATE records\n SET embedding = NULL,\n embed_status = CASE WHEN embed_status = ? THEN ? ELSE ? END\n WHERE record_rowid = ?\n `).run(EMBED_STATUS_SUPPRESSED, EMBED_STATUS_SUPPRESSED, EMBED_STATUS_SCRUBBED, recordRowid)\n\n const recordNode = recordGraphNode(bundle.frontmatter.kind, bundle.manifest.id)\n db.prepare(`\n DELETE FROM graph_edges\n WHERE record_rowid = ?\n OR src_node_id = ?\n OR (dst_node_id = ? AND edge_type <> 'renamed-from')\n `).run(recordRowid, recordNode.nodeId, recordNode.nodeId)\n deleteOrphanGraphNodes(db)\n}\n\nfunction projectBundle(\n db: DatabaseSync,\n vec: VecCapability,\n projected: ProjectedBundle,\n activeProfile: EmbeddingProfile,\n authority?: MutationAuthorityContext,\n beforeCommit?: () => void,\n hooks?: RebuildIndexHooks,\n priors?: TrustPriorTable,\n): void {\n transaction(db, () => {\n const { recordRowid, status } = upsertRecord(\n db,\n projected.bundle,\n projected.product,\n priors,\n )\n replaceFtsAndAnchors(db, projected.bundle, projected.product, recordRowid)\n if (isDeadStatus(status)) {\n scrubDeadRecallRows(db, projected.bundle, recordRowid)\n return\n }\n /**\n * D-15 revival seam: a rollback restore re-projects through applyIndexDeltaForBundle, so the\n * reset lives on this default projection path. The WHERE clause makes it a no-op for\n * pending/present rows and deliberately unable to match the SAFE-02 terminal value — only a\n * structurally scrubbed row projecting live again re-enters the ordinary backfill pipeline.\n */\n db.prepare(`\n UPDATE records\n SET embed_status = ?\n WHERE record_rowid = ? AND embed_status = ?\n `).run(EMBED_STATUS_PENDING, recordRowid, EMBED_STATUS_SCRUBBED)\n refreshVecMetadata(db, vec, recordRowid, activeProfile)\n replaceAnchorGraph(db, projected.bundle, projected.product, recordRowid)\n }, authority, beforeCommit, { family: 'project-bundle', hooks })\n}\n\n/**\n * Project exactly one canonical bundle through the same record/FTS/anchor/graph units used by a\n * full rebuild. Commit and journal recovery both call this authority; no projection SQL exists in\n * either orchestration layer.\n */\nexport function projectBundleIndexRow(opts: ProjectBundleIndexRowOptions): void {\n projectBundleIndexRowWithAuthority(opts)\n}\n\n/** @internal Caller already owns the current writer-authority section. */\nexport function projectBundleIndexRowWithinCurrentAuthority(\n opts: ProjectBundleIndexRowOptions,\n): void {\n projectBundleIndexRowWithAuthority(opts, { withinHeldAuthority: true })\n}\n\nfunction projectBundleIndexRowWithAuthority(\n opts: ProjectBundleIndexRowOptions,\n authority?: MutationAuthorityContext,\n): void {\n const priors = opts.priors === undefined ? undefined : guardTrustPriorTable(opts.priors)\n const target = resolveProductQualifiedBundleDir({\n knowledgeRoot: opts.knowledgeRoot,\n recordId: opts.bundleId,\n ...(opts.product === undefined ? {} : { product: opts.product }),\n })\n const outcome = loadBundle(target.dir)\n if (outcome.kind !== 'loaded' || outcome.bundle.manifest.id !== opts.bundleId) {\n throw new Error(`bundle ${target.product}/${opts.bundleId} was not loadable`)\n }\n const integrity = verifyBundleIntegrity(target.dir)\n if (!integrity.ok) {\n throw new Error(\n `cannot project invalid bundle ${target.product}/${opts.bundleId}: `\n + integrity.violations.join('; '),\n )\n }\n const projected: ProjectedBundle = {\n bundle: outcome.bundle,\n dir: target.dir,\n product: target.product,\n }\n\n const writer = openIndexWriter(opts.knowledgeRoot)\n const activeProfile = resolveActiveProfile(writer.db)\n try {\n projectBundle(writer.db, writer.vec, projected, activeProfile, authority, undefined, undefined, priors)\n emitRelationEdges(writer.db, [projected], authority)\n const scanIssues: string[] = []\n emitObservationEdges(\n writer.db,\n opts.knowledgeRoot,\n [projected],\n scanIssues,\n authority,\n )\n if (scanIssues.length > 0) {\n throw new Error(`bundle ${opts.bundleId} observation projection failed: ${scanIssues.join('; ')}`)\n }\n emitEquivalentToBridges(writer.db, authority)\n removeOrphanGraphNodes(writer.db, authority)\n refreshContextualRenderings(writer.db, writer.renderingEpochStale, authority)\n withMutationAuthority(authority, () => writer.completeRenderingEpoch())\n } finally {\n writer.close()\n }\n}\n\n/**\n * Reconcile relations from every integrity-valid bundle in the current walk, including sources\n * skipped by mutable-state hashing. INSERT OR IGNORE keeps unchanged re-emission idempotent, while\n * relations already participate in mutableStateHash, so only target membership can require healing\n * without a source re-projection.\n */\nfunction emitRelationEdges(\n db: DatabaseSync,\n relationSources: readonly ProjectedBundle[],\n authority?: MutationAuthorityContext,\n): void {\n transaction(db, () => {\n for (const { bundle, product } of relationSources) {\n const sourceRow = db\n .prepare('SELECT record_rowid, status FROM records WHERE bundle_id = ?')\n .get(bundle.manifest.id)\n if (sourceRow === undefined || isDeadStatus(sourceRow.status)) continue\n const recordRowid = Number(sourceRow.record_rowid)\n const sourceNode = recordGraphNode(bundle.frontmatter.kind, bundle.manifest.id)\n\n for (const relation of bundle.relations.relations) {\n const targetRow = db\n .prepare('SELECT kind, status FROM records WHERE bundle_id = ?')\n .get(relation.targetId)\n if (\n targetRow === undefined\n || (isDeadStatus(targetRow.status) && relation.type !== 'renamed-from')\n ) {\n continue\n }\n /**\n * D-22: `renamed-from` is the one intentional dead-target relation. The live replacement\n * owns the edge, so audit expansion can still traverse new → old after the victim's own\n * recall rows and edges are structurally scrubbed. Every other dead target stays omitted.\n */\n const targetKind = targetRow.kind as LoadedBundle['frontmatter']['kind']\n const targetNode = recordGraphNode(targetKind, relation.targetId)\n insertGraphNode(db, targetNode, product)\n insertGraphEdge(db, {\n srcNodeId: sourceNode.nodeId,\n edgeType: relation.type,\n dstNodeId: targetNode.nodeId,\n recordRowid,\n product,\n recencyOrdinal: relation.addedAtOrdinal,\n })\n }\n }\n }, authority)\n}\n\nfunction safeObservationPath(\n knowledgeRoot: string,\n source: ProjectedBundle,\n): string | undefined {\n const bundleDir = basename(source.dir)\n if (\n source.product === ''\n || source.product === '.'\n || source.product === '..'\n || source.product !== basename(source.product)\n || bundleDir === ''\n || bundleDir === '.'\n || bundleDir === '..'\n || source.dir !== join(knowledgeRoot, 'memory', source.product, 'bundles', bundleDir)\n ) {\n return undefined\n }\n return join(source.dir, 'observations.jsonl')\n}\n\nfunction loadObservations(\n knowledgeRoot: string,\n source: ProjectedBundle,\n scanIssues: string[],\n): DistilledObservation[] {\n const observationPath = safeObservationPath(knowledgeRoot, source)\n if (observationPath === undefined) {\n scanIssues.push(`${source.dir}: observations.jsonl: unsafe bundle path`)\n return []\n }\n if (!existsSync(observationPath)) return []\n\n let text: string\n try {\n text = readFileSync(observationPath, 'utf8')\n } catch (error) {\n scanIssues.push(`${observationPath}: ${errorMessage(error)}`)\n return []\n }\n\n const observations: DistilledObservation[] = []\n const lines = text.split('\\n')\n if (lines.at(-1) === '') lines.pop()\n for (const [index, line] of lines.entries()) {\n try {\n observations.push(guardDistilledObservation(JSON.parse(line)))\n } catch (error) {\n scanIssues.push(`${observationPath}:${index + 1}: ${errorMessage(error)}`)\n }\n }\n return observations\n}\n\nfunction deleteObservationEdges(db: DatabaseSync, recordRowid: number): void {\n db.prepare(`\n DELETE FROM graph_edges\n WHERE record_rowid = ?\n AND EXISTS (\n SELECT 1\n FROM graph_nodes AS source\n WHERE source.node_id = graph_edges.src_node_id\n AND (\n (graph_edges.edge_type = 'contains' AND source.node_type = 'test')\n OR (\n graph_edges.edge_type = 'composed-of'\n AND source.node_type = 'procedure'\n )\n OR (\n graph_edges.edge_type IN ('uses', 'on', 'part-of')\n AND source.node_type = 'step'\n )\n OR (graph_edges.edge_type = 'precedes' AND source.node_type = 'flow')\n OR (graph_edges.edge_type = 'caused-by' AND source.node_type = 'error')\n )\n )\n `).run(recordRowid)\n}\n\n/** Re-read every valid bundle so fixture/live observation changes do not depend on bundle hashes. */\nfunction emitObservationEdges(\n db: DatabaseSync,\n knowledgeRoot: string,\n sources: readonly ProjectedBundle[],\n scanIssues: string[],\n authority?: MutationAuthorityContext,\n): void {\n const prepared: GraphDerivation[] = []\n const recordRowids: number[] = []\n for (const source of sources) {\n const row = db\n .prepare('SELECT record_rowid, status FROM records WHERE bundle_id = ?')\n .get(source.bundle.manifest.id)\n if (row === undefined) continue\n const recordRowid = Number(row.record_rowid)\n if (isDeadStatus(row.status)) {\n // Rule 2: the unconditional observation pass is another graph resurrection vector.\n recordRowids.push(recordRowid)\n continue\n }\n const context: GraphDerivationContext = {\n bundleId: source.bundle.manifest.id,\n recordRowid,\n product: source.product,\n createdAtOrdinal: source.bundle.frontmatter.createdAtOrdinal,\n }\n recordRowids.push(recordRowid)\n prepared.push(\n deriveObservationEdges(\n loadObservations(knowledgeRoot, source, scanIssues),\n context,\n ),\n )\n }\n\n transaction(db, () => {\n for (const recordRowid of recordRowids) deleteObservationEdges(db, recordRowid)\n for (const projection of prepared) insertGraphDerivation(db, projection)\n }, authority)\n}\n\ninterface UsesEdgeRow {\n src_node_id: string\n dst_node_id: string\n record_rowid: number\n product: string\n recency_ordinal: number\n bundle_id: string\n node_type: GraphNodeType\n natural_key_json: string\n}\n\nfunction accumulatedUsesEdges(db: DatabaseSync): {\n nodes: DerivedGraphNode[]\n edges: DerivedGraphEdge[]\n} {\n const rows = db.prepare(`\n SELECT\n edge.src_node_id,\n edge.dst_node_id,\n edge.record_rowid,\n edge.product,\n edge.recency_ordinal,\n records.bundle_id,\n target.node_type,\n target.natural_key_json\n FROM graph_edges AS edge\n JOIN records ON records.record_rowid = edge.record_rowid\n JOIN graph_nodes AS target ON target.node_id = edge.dst_node_id\n WHERE edge.edge_type = 'uses'\n ORDER BY\n edge.src_node_id,\n edge.edge_type,\n edge.dst_node_id,\n edge.record_rowid\n `).all() as unknown as UsesEdgeRow[]\n\n const nodes = new Map<string, DerivedGraphNode>()\n const edges: DerivedGraphEdge[] = []\n for (const row of rows) {\n if (!nodes.has(row.dst_node_id)) {\n nodes.set(row.dst_node_id, {\n nodeId: row.dst_node_id,\n type: row.node_type,\n naturalKey: JSON.parse(row.natural_key_json) as GraphNodeNaturalKey,\n product: row.product,\n })\n }\n edges.push({\n srcNodeId: row.src_node_id,\n edgeType: 'uses',\n dstNodeId: row.dst_node_id,\n recordRowid: Number(row.record_rowid),\n bundleId: row.bundle_id,\n product: row.product,\n recencyOrdinal: Number(row.recency_ordinal),\n })\n }\n return { nodes: [...nodes.values()], edges }\n}\n\nfunction emitEquivalentToBridges(\n db: DatabaseSync,\n authority?: MutationAuthorityContext,\n): void {\n const accumulated = accumulatedUsesEdges(db)\n const bridges = deriveEquivalentToBridges(accumulated.nodes, accumulated.edges)\n\n transaction(db, () => {\n db.exec(`\n DELETE FROM graph_edges\n WHERE edge_type = 'equivalent-to'\n AND EXISTS (\n SELECT 1\n FROM graph_nodes AS source\n JOIN graph_nodes AS target\n ON target.node_id = graph_edges.dst_node_id\n WHERE source.node_id = graph_edges.src_node_id\n AND source.node_type = 'web-element'\n AND target.node_type = 'mobile-element'\n )\n `)\n for (const edge of bridges) insertGraphEdge(db, edge)\n }, authority)\n}\n\nfunction removeOrphanGraphNodes(\n db: DatabaseSync,\n authority?: MutationAuthorityContext,\n): void {\n transaction(db, () => {\n deleteOrphanGraphNodes(db)\n }, authority)\n}\n\n/** Recompute graph-derived prose only after every graph-producing pass has converged. */\nfunction refreshContextualRenderings(\n db: DatabaseSync,\n force = false,\n authority?: MutationAuthorityContext,\n): number {\n const rows = db.prepare(`\n SELECT record_rowid, embedding_input, contextual_rendering, status\n FROM records\n ORDER BY record_rowid\n `).all()\n let refreshed = 0\n\n for (const row of rows) {\n if (isDeadStatus(row.status)) continue\n const recordRowid = Number(row.record_rowid)\n const situatingLine = buildSituatingLine(db, recordRowid)\n const contextualRendering = renderContextual(\n String(row.embedding_input),\n situatingLine,\n )\n if (\n !force\n && !computeRenderingDrift(\n contextualRendering,\n String(row.contextual_rendering),\n )\n ) {\n continue\n }\n\n transaction(db, () => {\n const fts = db\n .prepare('SELECT identity FROM fts_records WHERE rowid = ?')\n .get(recordRowid)\n if (fts === undefined) {\n throw new Error(`contextual FTS row ${recordRowid} is missing`)\n }\n db.prepare(`\n UPDATE records\n SET\n situating_line = ?,\n contextual_rendering = ?,\n embed_status = CASE\n WHEN embed_status = ? THEN ?\n ELSE ?\n END,\n embedding = NULL\n WHERE record_rowid = ?\n `).run(\n situatingLine,\n contextualRendering,\n EMBED_STATUS_SUPPRESSED,\n EMBED_STATUS_SUPPRESSED,\n EMBED_STATUS_PENDING,\n recordRowid,\n )\n db.prepare('DELETE FROM fts_records WHERE rowid = ?').run(recordRowid)\n db.prepare(`\n INSERT INTO fts_records (rowid, identity, content, context)\n VALUES (?, ?, ?, ?)\n `).run(\n recordRowid,\n String(fts.identity),\n String(row.embedding_input),\n situatingLine,\n )\n }, authority)\n refreshed += 1\n }\n return refreshed\n}\n\n/** The total per-record projection deletion set shared by the missing-bundle and drain-tail passes. */\nfunction deleteRecordProjectionRows(\n db: DatabaseSync,\n recordRowid: number,\n bundleId: string,\n kind: LoadedBundle['frontmatter']['kind'],\n): void {\n const recordNode = recordGraphNode(kind, bundleId)\n deleteRecordFromAllSchemaVecTables(db, recordRowid)\n db.prepare('DELETE FROM fts_records WHERE rowid = ?').run(recordRowid)\n db.prepare('DELETE FROM anchors WHERE record_rowid = ?').run(recordRowid)\n db.prepare(`\n DELETE FROM graph_edges\n WHERE record_rowid = ? OR src_node_id = ? OR dst_node_id = ?\n `).run(recordRowid, recordNode.nodeId, recordNode.nodeId)\n db.prepare('DELETE FROM records WHERE record_rowid = ?').run(recordRowid)\n}\n\nfunction removeMissingBundles(\n db: DatabaseSync,\n seenBundleIds: ReadonlySet<string>,\n authority?: MutationAuthorityContext,\n hooks?: RebuildIndexHooks,\n): number {\n const missing = db\n .prepare('SELECT record_rowid, bundle_id, kind FROM records ORDER BY record_rowid')\n .all()\n .filter((row) => !seenBundleIds.has(String(row.bundle_id)))\n if (missing.length === 0) return 0\n\n transaction(db, () => {\n for (const row of missing) {\n deleteRecordProjectionRows(\n db,\n Number(row.record_rowid),\n String(row.bundle_id),\n row.kind as LoadedBundle['frontmatter']['kind'],\n )\n }\n }, authority, undefined, { family: 'remove-missing-bundles', hooks })\n\n return missing.length\n}\n\n/**\n * WR-01 record-scoped healing: delete the total projection set for exactly the supplied bundle\n * ids inside one transaction and return the number of records removed. An absent index db,\n * empty ids, and ids without records rows are no-ops; embed_cache is untouched (purge-only A4).\n */\nexport function removeBundleProjectionRows(\n knowledgeRoot: string,\n bundleIds: readonly string[],\n writerAuthority: WriterLeaseAuthority,\n): number {\n if (writerAuthority.knowledgeRoot !== knowledgeRoot) {\n throw new TypeError('projection cleanup writerAuthority must belong to knowledgeRoot')\n }\n if (bundleIds.length === 0 || !existsSync(indexDbPath(knowledgeRoot))) return 0\n\n const writer = openIndexWriter(knowledgeRoot)\n try {\n const selectRecord = writer.db.prepare(\n 'SELECT record_rowid, kind FROM records WHERE bundle_id = ?',\n )\n const found = bundleIds.flatMap((bundleId) => {\n const row = selectRecord.get(bundleId)\n return row === undefined\n ? []\n : [{\n recordRowid: Number(row.record_rowid),\n bundleId,\n kind: row.kind as LoadedBundle['frontmatter']['kind'],\n }]\n })\n if (found.length === 0) return 0\n\n withCurrentWriterAuthority(knowledgeRoot, writerAuthority, () => {\n transaction(writer.db, () => {\n for (const row of found) {\n deleteRecordProjectionRows(writer.db, row.recordRowid, row.bundleId, row.kind)\n }\n }, { withinHeldAuthority: true })\n })\n return found.length\n } finally {\n writer.close()\n }\n}\n\nasync function backfillPendingEmbeddings(\n db: DatabaseSync,\n vec: VecCapability,\n embedder: EmbedderPort | undefined,\n activeProfile: EmbeddingProfile,\n newlyProjectedBundleIds: ReadonlySet<string>,\n authority?: MutationAuthorityContext,\n): Promise<number> {\n if (embedder === undefined) return 0\n\n const pending = selectPendingEmbeddingRows(db)\n let backfilled = 0\n for (const row of pending) {\n let vector: Float32Array\n try {\n vector = await embedder.embedDocument(String(row.contextual_rendering))\n } catch (error) {\n throw new Error(\n `embedding ${String(row.bundle_id)} failed: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n transaction(db, () => {\n storeEmbedding(\n db,\n vec,\n Number(row.record_rowid),\n vector,\n activeProfile,\n )\n }, authority)\n // Keep RebuildReport.backfilled's established meaning: rows carried pending into this rebuild.\n if (!newlyProjectedBundleIds.has(String(row.bundle_id))) backfilled += 1\n }\n return backfilled\n}\n\nfunction reconcileVecRows(\n db: DatabaseSync,\n vec: VecCapability,\n activeProfile: EmbeddingProfile,\n authority?: MutationAuthorityContext,\n): void {\n if (vec !== 'vec0') return\n const tableName = vecTableName(activeProfile)\n const vecRows = new Map(\n db.prepare(`\n SELECT record_rowid, scope_tier, scope_key, status\n FROM ${tableName}\n `).all().map((row) => [\n Number(row.record_rowid),\n {\n scopeTier: String(row.scope_tier),\n scopeKey: String(row.scope_key),\n status: String(row.status),\n },\n ]),\n )\n /**\n * Writer open verifies the meta stamp before any present canonical bytes are trusted, so the\n * stamp is their profile provenance without adding a per-row profile column. Status and exact\n * byte length remain defense-in-depth gates: the active vec table must never receive bytes that\n * the active profile could not have produced.\n */\n const canonical = db\n .prepare(`\n SELECT record_rowid, product, scope_tier, scope_key, status, embedding\n FROM records\n WHERE embedding IS NOT NULL\n AND embed_status = ?\n AND length(embedding) = ?\n ORDER BY record_rowid\n `)\n .all(EMBED_STATUS_PRESENT, activeProfile.dim * Float32Array.BYTES_PER_ELEMENT)\n const canonicalRowids = new Set(canonical.map((row) => Number(row.record_rowid)))\n\n transaction(db, () => {\n const deleteVec = db.prepare(`DELETE FROM ${tableName} WHERE record_rowid = ?`)\n for (const recordRowid of vecRows.keys()) {\n if (!canonicalRowids.has(recordRowid)) deleteVec.run(BigInt(recordRowid))\n }\n\n const insertVec = db.prepare(`\n INSERT INTO ${tableName} (\n record_rowid, product, scope_tier, scope_key, status, embedding\n ) VALUES (?, ?, ?, ?, ?, ?)\n `)\n const updateMetadata = db.prepare(`\n UPDATE ${tableName}\n SET scope_tier = ?, scope_key = ?, status = ?\n WHERE record_rowid = ?\n `)\n for (const row of canonical) {\n const recordRowid = Number(row.record_rowid)\n const scopeTier = String(row.scope_tier)\n const scopeKey = String(row.scope_key)\n const status = String(row.status)\n const vecRow = vecRows.get(recordRowid)\n if (vecRow === undefined) {\n insertVec.run(\n BigInt(recordRowid),\n String(row.product),\n scopeTier,\n scopeKey,\n status,\n row.embedding as Uint8Array,\n )\n continue\n }\n if (\n vecRow.scopeTier !== scopeTier\n || vecRow.scopeKey !== scopeKey\n || vecRow.status !== status\n ) {\n updateMetadata.run(scopeTier, scopeKey, status, BigInt(recordRowid))\n }\n }\n }, authority)\n}\n\n/** Hash-selected projection plus the independent D-02 backfill and D-10 reconciliation passes. */\nexport async function rebuildIndex(opts: RebuildIndexOptions): Promise<RebuildReport> {\n const priors = snapshotTrustPriors(opts.priors)\n const digest = effectivePriorDigest(priors)\n const writerAuthority = opts.writerAuthority\n if (\n writerAuthority !== undefined\n && writerAuthority.knowledgeRoot !== opts.knowledgeRoot\n ) {\n throw new TypeError('rebuild writerAuthority must belong to knowledgeRoot')\n }\n const authority: MutationAuthorityContext | undefined = writerAuthority === undefined\n ? undefined\n : { hold: writerAuthority }\n const writer = withMutationAuthority(\n authority,\n () => openIndexWriter(\n opts.knowledgeRoot,\n opts.vecLoadablePath === undefined\n ? {}\n : { vecLoadablePath: opts.vecLoadablePath },\n ),\n )\n const activeProfile = resolveActiveProfile(writer.db)\n const report: RebuildReport = {\n projected: 0,\n skippedIncomplete: 0,\n scanIssues: [],\n removed: 0,\n backfilled: 0,\n vec: writer.vec,\n pendingEmbeddings: 0,\n maintenanceRemaining: true,\n }\n const projected: ProjectedBundle[] = []\n const relationSources: ProjectedBundle[] = []\n const seenBundleIds = new Set<string>()\n let processedBundles = 0\n\n try {\n // Invalidate before any row can commit. An interruption cannot look complete, even\n // when retrying the same epoch after a partially completed prior pass.\n transaction(writer.db, () => {\n writer.db.prepare(\"DELETE FROM meta WHERE k = 'trust_prior_digest'\").run()\n }, authority)\n for (const entry of enumerateBundleDirs(opts.knowledgeRoot)) {\n const outcome = loadBundle(entry.dir)\n if (outcome.kind === 'incomplete') {\n seenBundleIds.add(basename(entry.dir))\n report.skippedIncomplete += 1\n continue\n }\n if (outcome.kind !== 'loaded') {\n seenBundleIds.add(basename(entry.dir))\n const reason = 'reason' in outcome ? `: ${outcome.reason}` : ''\n report.scanIssues.push(`${entry.dir}: ${outcome.kind}${reason}`)\n continue\n }\n\n seenBundleIds.add(outcome.bundle.manifest.id)\n const integrity = verifyBundleIntegrity(entry.dir)\n if (!integrity.ok) {\n report.scanIssues.push(`${entry.dir}: integrity: ${integrity.violations.join('; ')}`)\n continue\n }\n const item = { bundle: outcome.bundle, dir: entry.dir, product: entry.product }\n relationSources.push(item)\n const current = writer.db\n .prepare(`\n SELECT mutable_state_hash, trust_prior_digest\n FROM records\n WHERE bundle_id = ?\n `)\n .get(outcome.bundle.manifest.id)\n processedBundles += 1\n if (current?.mutable_state_hash === outcome.bundle.manifest.mutableStateHash) {\n if (current.trust_prior_digest !== digest) {\n // Trust-only reprojection must not undo SAFE-02 lexical redaction or disturb\n // rendering, graph, embedding provenance, counters or lifecycle fields.\n transaction(writer.db, () => {\n writer.db.prepare('UPDATE records SET trust = ?, trust_prior_digest = ? WHERE bundle_id = ?')\n .run(deriveBundleTrust(outcome.bundle, priors).trust, digest, outcome.bundle.manifest.id)\n }, authority, opts.hooks?.beforeTransactionCommit, { family: 'project-bundle', hooks: opts.hooks })\n report.projected += 1\n }\n if (processedBundles % CHECKPOINT_EVERY_N_BUNDLES === 0) {\n withNamedMutationAuthority(\n authority,\n 'checkpoint-passive',\n opts.hooks,\n () => writer.checkpointPassive(),\n )\n }\n continue\n }\n\n projectBundle(\n writer.db,\n writer.vec,\n item,\n activeProfile,\n authority,\n opts.hooks?.beforeTransactionCommit,\n opts.hooks,\n priors,\n )\n projected.push(item)\n report.projected += 1\n if (processedBundles % CHECKPOINT_EVERY_N_BUNDLES === 0) {\n withNamedMutationAuthority(\n authority,\n 'checkpoint-passive',\n opts.hooks,\n () => writer.checkpointPassive(),\n )\n }\n }\n\n report.removed = removeMissingBundles(\n writer.db,\n seenBundleIds,\n authority,\n opts.hooks,\n )\n emitRelationEdges(writer.db, relationSources, authority)\n emitObservationEdges(\n writer.db,\n opts.knowledgeRoot,\n relationSources,\n report.scanIssues,\n authority,\n )\n emitEquivalentToBridges(writer.db, authority)\n removeOrphanGraphNodes(writer.db, authority)\n refreshContextualRenderings(writer.db, writer.renderingEpochStale, authority)\n report.backfilled = await backfillPendingEmbeddings(\n writer.db,\n writer.vec,\n opts.embedder,\n activeProfile,\n new Set(projected.map(({ bundle }) => bundle.manifest.id)),\n authority,\n )\n reconcileVecRows(writer.db, writer.vec, activeProfile, authority)\n withNamedMutationAuthority(\n authority,\n 'complete-rendering-epoch',\n opts.hooks,\n () => writer.completeRenderingEpoch(),\n )\n if (writerAuthority !== undefined && report.skippedIncomplete === 0 && report.scanIssues.length === 0) {\n transaction(writer.db, () => {\n const mixed = writer.db.prepare('SELECT 1 FROM records WHERE trust_prior_digest != ? LIMIT 1').get(digest)\n if (mixed !== undefined) return\n writer.db.prepare(\"INSERT INTO meta (k, v) VALUES ('trust_prior_digest', ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v\").run(digest)\n }, authority, undefined, { family: 'complete-trust-epoch', hooks: opts.hooks })\n }\n report.pendingEmbeddings = selectPendingEmbeddingRows(writer.db).length\n report.maintenanceRemaining =\n report.pendingEmbeddings > 0\n || writer.renderingEpochStale\n || !isEmbeddingVecCleanupCurrent(writer.db)\n if (!report.maintenanceRemaining) {\n withNamedMutationAuthority(\n authority,\n 'clear-rebuild-request',\n opts.hooks,\n () => clearRebuildRequest(opts.knowledgeRoot),\n )\n }\n return report\n } finally {\n writer.close()\n }\n}\n","/**\n * Phase 377 D-01/D-02 contextual rendering (memory.md §5.3).\n *\n * The complete rendering is a derived-index projection only. Committed bundle bytes retain their\n * self-fields rendering and never depend on cross-bundle graph state.\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport { recordGraphNode } from '@vostride/agent-qa-schema'\n\nimport { SITUATING_LINE_MAX_CHARS } from './retrieval/constants.js'\n\ntype RecordKind = 'fact' | 'procedure' | 'caution' | 'unknown' | 'policy'\n\ninterface CandidateRow {\n node_id: string\n node_type?: string\n natural_key_json?: string\n summary?: string\n support_trust: number\n recency_ordinal: number\n}\n\ninterface SituatingCandidate {\n nodeId: string\n text: string\n trust: number\n recencyOrdinal: number\n}\n\nfunction recordKind(value: unknown): RecordKind {\n if (\n value === 'fact'\n || value === 'procedure'\n || value === 'caution'\n || value === 'unknown'\n || value === 'policy'\n ) {\n return value\n }\n throw new TypeError(`unsupported contextual-rendering record kind ${String(value)}`)\n}\n\nfunction compareCandidates(left: SituatingCandidate, right: SituatingCandidate): number {\n return right.trust - left.trust\n || right.recencyOrdinal - left.recencyOrdinal\n || (left.nodeId < right.nodeId ? -1 : left.nodeId > right.nodeId ? 1 : 0)\n}\n\nfunction sentence(prefix: string, value: string): string {\n const trimmed = value.trim()\n if (trimmed === '') return ''\n return `${prefix}: ${trimmed}${/[.!?]$/.test(trimmed) ? '' : '.'}`\n}\n\nfunction naturalKeyText(serialized: string): string {\n const parsed = JSON.parse(serialized) as unknown\n if (typeof parsed === 'string') return parsed\n if (typeof parsed === 'number' || typeof parsed === 'boolean') return String(parsed)\n if (parsed !== null && typeof parsed === 'object') {\n const value = parsed as Record<string, unknown>\n for (const key of ['name', 'route', 'id', 'naturalKey']) {\n if (typeof value[key] === 'string') return value[key]\n }\n }\n return serialized\n}\n\nfunction candidate(row: CandidateRow, text: string): SituatingCandidate | undefined {\n if (text === '') return undefined\n return {\n nodeId: String(row.node_id),\n text,\n trust: Number(row.support_trust),\n recencyOrdinal: Number(row.recency_ordinal),\n }\n}\n\nfunction ownershipCandidates(\n db: DatabaseSync,\n recordRowid: number,\n recordNodeId: string,\n): SituatingCandidate[] {\n const rows = db.prepare(`\n WITH record_seeds(node_id) AS (\n SELECT ?\n UNION\n SELECT dst_node_id\n FROM graph_edges\n WHERE src_node_id = ? AND edge_type = 'about'\n UNION\n SELECT src_node_id FROM graph_edges WHERE record_rowid = ?\n UNION\n SELECT dst_node_id FROM graph_edges WHERE record_rowid = ?\n ),\n owner_support AS (\n SELECT\n target.node_id,\n target.node_type,\n target.natural_key_json,\n support.trust AS support_trust,\n edge.recency_ordinal\n FROM graph_edges AS edge\n JOIN record_seeds AS seed ON seed.node_id = edge.src_node_id\n JOIN graph_nodes AS target ON target.node_id = edge.dst_node_id\n JOIN records AS support ON support.record_rowid = edge.record_rowid\n WHERE edge.edge_type IN ('part-of', 'on')\n AND target.node_type IN ('page', 'web-page', 'mobile-screen', 'flow', 'procedure')\n\n UNION ALL\n\n SELECT\n source.node_id,\n source.node_type,\n source.natural_key_json,\n support.trust AS support_trust,\n edge.recency_ordinal\n FROM graph_edges AS edge\n JOIN record_seeds AS seed ON seed.node_id = edge.dst_node_id\n JOIN graph_nodes AS source ON source.node_id = edge.src_node_id\n JOIN records AS support ON support.record_rowid = edge.record_rowid\n WHERE edge.edge_type = 'composed-of'\n AND source.node_type = 'procedure'\n\n UNION ALL\n\n SELECT\n target.node_id,\n target.node_type,\n target.natural_key_json,\n support.trust AS support_trust,\n edge.recency_ordinal\n FROM graph_edges AS edge\n JOIN graph_nodes AS target ON target.node_id = edge.dst_node_id\n JOIN records AS support ON support.record_rowid = edge.record_rowid\n WHERE edge.src_node_id = ?\n AND edge.edge_type = 'about'\n AND target.node_type IN ('page', 'web-page', 'mobile-screen', 'flow', 'procedure')\n )\n SELECT node_id, node_type, natural_key_json, support_trust, recency_ordinal\n FROM owner_support\n ORDER BY support_trust DESC, recency_ordinal DESC, node_id ASC\n `).all(recordNodeId, recordNodeId, recordRowid, recordRowid, recordNodeId) as unknown as CandidateRow[]\n\n const candidates = new Map<string, SituatingCandidate>()\n for (const row of rows) {\n const prefix = row.node_type === 'flow'\n ? 'Flow'\n : row.node_type === 'procedure'\n ? 'Procedure'\n : 'Page'\n const value = naturalKeyText(String(row.natural_key_json))\n const next = candidate(row, sentence(prefix, value))\n if (next !== undefined && !candidates.has(next.nodeId)) candidates.set(next.nodeId, next)\n }\n return [...candidates.values()]\n}\n\nfunction relatedRecordCandidate(\n db: DatabaseSync,\n recordNodeId: string,\n kind: 'lineage' | 'caution',\n): SituatingCandidate | undefined {\n const edgePredicate = kind === 'lineage'\n ? \"edge.edge_type IN ('supersedes', 'superseded-by')\"\n : \"edge.edge_type IN ('derived-from', 'conflicts-with', 'relates-to', 'renamed-from', 'equivalent-to')\"\n const kindPredicate = kind === 'caution' ? \"AND neighbor_record.kind = 'caution'\" : ''\n const row = db.prepare(`\n SELECT\n neighbor.node_id,\n neighbor_record.summary,\n neighbor_record.trust AS support_trust,\n edge.recency_ordinal\n FROM graph_edges AS edge\n JOIN graph_nodes AS neighbor\n ON neighbor.node_id = CASE\n WHEN edge.src_node_id = ? THEN edge.dst_node_id\n ELSE edge.src_node_id\n END\n JOIN records AS neighbor_record\n ON neighbor.natural_key_json = json_quote(neighbor_record.bundle_id)\n WHERE ${edgePredicate}\n AND (edge.src_node_id = ? OR edge.dst_node_id = ?)\n ${kindPredicate}\n ORDER BY support_trust DESC, recency_ordinal DESC, node_id ASC\n LIMIT 1\n `).get(recordNodeId, recordNodeId, recordNodeId) as unknown as CandidateRow | undefined\n if (row === undefined) return undefined\n return candidate(\n row,\n sentence(kind === 'lineage' ? 'Supersession' : 'Caution', String(row.summary)),\n )\n}\n\nexport function buildSituatingLine(db: DatabaseSync, recordRowid: number): string {\n if (!Number.isSafeInteger(recordRowid) || recordRowid <= 0) {\n throw new RangeError('recordRowid must be a positive safe integer')\n }\n const record = db\n .prepare('SELECT bundle_id, kind FROM records WHERE record_rowid = ?')\n .get(recordRowid)\n if (record === undefined) return ''\n\n const recordNodeId = recordGraphNode(\n recordKind(record.kind),\n String(record.bundle_id),\n ).nodeId\n const candidates = ownershipCandidates(db, recordRowid, recordNodeId)\n const lineage = relatedRecordCandidate(db, recordNodeId, 'lineage')\n const caution = relatedRecordCandidate(db, recordNodeId, 'caution')\n if (lineage !== undefined) candidates.push(lineage)\n if (caution !== undefined) candidates.push(caution)\n candidates.sort(compareCandidates)\n\n const clauses: string[] = []\n let length = 0\n for (const item of candidates) {\n const nextLength = length + (clauses.length === 0 ? 0 : 1) + item.text.length\n if (nextLength > SITUATING_LINE_MAX_CHARS) break\n clauses.push(item.text)\n length = nextLength\n }\n return clauses.join(' ')\n}\n\nexport function renderContextual(selfFields: string, situatingLine: string): string {\n return situatingLine === '' ? selfFields : `${selfFields}\\n${situatingLine}`\n}\n\nexport function computeRenderingDrift(expected: string, stored: string): boolean {\n return expected !== stored\n}\n","/**\n * Phase 377 D-09 deterministic graph projection (memory.md §6.1).\n *\n * Open Question 3 is pinned here: element-to-surface containment remains `part-of`, as emitted by\n * the anchor projection and consumed by D-02 situating lines. `on` is reserved for Step→WebPage or\n * Step→MobileScreen observations. Every edge below is derived from guarded observations or typed\n * anchors; no model output or wall-clock value participates.\n */\nimport {\n anchorGraphNode,\n graphNodeId,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n DistilledObservation,\n GraphEdgeType,\n GraphNodeNaturalKey,\n GraphNodeType,\n Platform,\n} from '@vostride/agent-qa-schema'\n\nexport interface GraphDerivationContext {\n bundleId: string\n recordRowid: number\n product: string\n createdAtOrdinal: number\n}\n\nexport interface DerivedGraphNode {\n nodeId: string\n type: GraphNodeType\n naturalKey: GraphNodeNaturalKey\n product: string\n}\n\nexport interface DerivedGraphEdge {\n srcNodeId: string\n edgeType: GraphEdgeType\n dstNodeId: string\n recordRowid: number\n bundleId: string\n product: string\n recencyOrdinal: number\n}\n\nexport interface GraphDerivation {\n nodes: DerivedGraphNode[]\n edges: DerivedGraphEdge[]\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction compareEdges(left: DerivedGraphEdge, right: DerivedGraphEdge): number {\n return compareText(left.srcNodeId, right.srcNodeId)\n || compareText(left.edgeType, right.edgeType)\n || compareText(left.dstNodeId, right.dstNodeId)\n || compareText(left.bundleId, right.bundleId)\n || left.recordRowid - right.recordRowid\n}\n\nfunction compareNodes(left: DerivedGraphNode, right: DerivedGraphNode): number {\n return compareText(left.nodeId, right.nodeId) || compareText(left.product, right.product)\n}\n\nfunction edgeIdentity(edge: DerivedGraphEdge): string {\n return [\n edge.srcNodeId,\n edge.edgeType,\n edge.dstNodeId,\n edge.bundleId,\n edge.recordRowid,\n ].join('\\u0000')\n}\n\nfunction node(type: GraphNodeType, naturalKey: GraphNodeNaturalKey, product: string): DerivedGraphNode {\n return { nodeId: graphNodeId(type, naturalKey), type, naturalKey, product }\n}\n\nclass DerivationBuilder {\n readonly #nodes = new Map<string, DerivedGraphNode>()\n readonly #edges = new Map<string, DerivedGraphEdge>()\n\n addNode(value: DerivedGraphNode): void {\n const key = `${value.nodeId}\\u0000${value.product}`\n if (!this.#nodes.has(key)) this.#nodes.set(key, value)\n }\n\n addEdge(value: DerivedGraphEdge): void {\n const key = edgeIdentity(value)\n const current = this.#edges.get(key)\n if (current === undefined || value.recencyOrdinal > current.recencyOrdinal) {\n this.#edges.set(key, value)\n }\n }\n\n connect(\n source: DerivedGraphNode,\n edgeType: GraphEdgeType,\n target: DerivedGraphNode,\n context: GraphDerivationContext,\n recencyOrdinal: number,\n ): void {\n this.addNode(source)\n this.addNode(target)\n this.addEdge({\n srcNodeId: source.nodeId,\n edgeType,\n dstNodeId: target.nodeId,\n recordRowid: context.recordRowid,\n bundleId: context.bundleId,\n product: context.product,\n recencyOrdinal,\n })\n }\n\n result(): GraphDerivation {\n return {\n nodes: [...this.#nodes.values()].sort(compareNodes),\n edges: [...this.#edges.values()].sort(compareEdges),\n }\n }\n}\n\nfunction observationStep(\n observation: DistilledObservation,\n product: string,\n): DerivedGraphNode {\n return node(\n 'step',\n { naturalKey: observation.step.naturalKey, ordinal: observation.step.ordinal },\n product,\n )\n}\n\nfunction observationElement(\n observation: DistilledObservation,\n product: string,\n): DerivedGraphNode | undefined {\n if (observation.element === undefined || observation.platform === undefined) return undefined\n return node(\n observation.platform === 'web' ? 'web-element' : 'mobile-element',\n observation.element.naturalKey,\n product,\n )\n}\n\n/** Derive the complete observation-backed §6.1 edge vocabulary for one bundle. */\nexport function deriveObservationEdges(\n observations: readonly DistilledObservation[],\n context: GraphDerivationContext,\n): GraphDerivation {\n const builder = new DerivationBuilder()\n\n for (const observation of observations) {\n const step = observationStep(observation, context.product)\n const element = observationElement(observation, context.product)\n const recency = observation.observedAtOrdinal\n\n if (observation.test !== undefined) {\n builder.connect(\n node('test', observation.test.id, context.product),\n 'contains',\n step,\n context,\n recency,\n )\n }\n if (observation.procedure !== undefined) {\n builder.connect(\n node('procedure', observation.procedure.id, context.product),\n 'composed-of',\n step,\n context,\n recency,\n )\n }\n if (element !== undefined) {\n builder.connect(step, 'uses', element, context, recency)\n }\n if (observation.surface !== undefined) {\n builder.connect(\n step,\n 'on',\n node(\n observation.surface.kind === 'page' ? 'web-page' : 'mobile-screen',\n observation.surface.naturalKey,\n context.product,\n ),\n context,\n recency,\n )\n }\n if (observation.flow !== undefined) {\n const flow = node('flow', observation.flow.name, context.product)\n builder.connect(step, 'part-of', flow, context, recency)\n if (observation.flow.precedes !== undefined) {\n builder.connect(\n flow,\n 'precedes',\n node('flow', observation.flow.precedes, context.product),\n context,\n recency,\n )\n }\n }\n if (observation.error !== undefined && element !== undefined) {\n builder.connect(\n node('error', observation.error.naturalKey, context.product),\n 'caused-by',\n element,\n context,\n recency,\n )\n }\n }\n\n return builder.result()\n}\n\n/** Derive element→locator edges from bundle anchors using anchorGraphNode's platform gate. */\nexport function deriveLocatesViaEdges(\n anchors: readonly Anchor[],\n platform: Platform | undefined,\n context: GraphDerivationContext,\n): GraphDerivation {\n const builder = new DerivationBuilder()\n const elements: DerivedGraphNode[] = []\n const locators: DerivedGraphNode[] = []\n\n for (const anchor of anchors) {\n const projected = anchorGraphNode(anchor, platform)\n if (projected === null) continue\n const derived = { ...projected, product: context.product }\n if (\n derived.type === 'element'\n || derived.type === 'web-element'\n || derived.type === 'mobile-element'\n ) {\n elements.push(derived)\n } else if (\n derived.type === 'web-locator'\n || derived.type === 'android-locator'\n || derived.type === 'ios-locator'\n ) {\n locators.push(derived)\n }\n }\n\n for (const element of elements.sort(compareNodes)) {\n for (const locator of locators.sort(compareNodes)) {\n builder.connect(\n element,\n 'locates-via',\n locator,\n context,\n context.createdAtOrdinal,\n )\n }\n }\n\n return builder.result()\n}\n\nfunction preferSupport(\n left: DerivedGraphEdge | undefined,\n right: DerivedGraphEdge,\n): DerivedGraphEdge {\n if (left === undefined || right.recencyOrdinal > left.recencyOrdinal) return right\n if (right.recencyOrdinal < left.recencyOrdinal) return left\n return compareText(right.bundleId, left.bundleId) < 0\n || (right.bundleId === left.bundleId && right.recordRowid < left.recordRowid)\n ? right\n : left\n}\n\n/**\n * Join uses-edges by product and shared step identity. Only explicit web/mobile element node types\n * participate; the unresolved shared `element` type is intentionally invisible to this join.\n */\nexport function deriveEquivalentToBridges(\n nodes: readonly DerivedGraphNode[],\n edges: readonly DerivedGraphEdge[],\n): DerivedGraphEdge[] {\n const nodeTypes = new Map(nodes.map((value) => [value.nodeId, value.type]))\n const groups = new Map<string, {\n web: Map<string, DerivedGraphEdge>\n mobile: Map<string, DerivedGraphEdge>\n }>()\n\n for (const edge of [...edges].sort(compareEdges)) {\n if (edge.edgeType !== 'uses') continue\n const type = nodeTypes.get(edge.dstNodeId)\n if (type !== 'web-element' && type !== 'mobile-element') continue\n const key = `${edge.product}\\u0000${edge.srcNodeId}`\n const group = groups.get(key) ?? { web: new Map(), mobile: new Map() }\n const side = type === 'web-element' ? group.web : group.mobile\n side.set(edge.dstNodeId, preferSupport(side.get(edge.dstNodeId), edge))\n groups.set(key, group)\n }\n\n const bridges: DerivedGraphEdge[] = []\n for (const key of [...groups.keys()].sort(compareText)) {\n const group = groups.get(key)!\n const web = [...group.web.entries()].sort(([left], [right]) => compareText(left, right))\n const mobile = [...group.mobile.entries()]\n .sort(([left], [right]) => compareText(left, right))\n\n for (const [webNodeId, webSupport] of web) {\n for (const [mobileNodeId, mobileSupport] of mobile) {\n const support = preferSupport(webSupport, mobileSupport)\n bridges.push({\n srcNodeId: webNodeId,\n edgeType: 'equivalent-to',\n dstNodeId: mobileNodeId,\n recordRowid: support.recordRowid,\n bundleId: support.bundleId,\n product: support.product,\n recencyOrdinal: support.recencyOrdinal,\n })\n }\n }\n }\n\n return bridges.sort(compareEdges)\n}\n","/**\n * Run-outcome projection: per-test outcome counters and exercised-anchor sets (ABRF-02, D-14/D-15).\n *\n * Third application of the handoff-to-projection fold idiom (after curation emit and canary\n * emit): a pure projection over one CompletedRunHandoff, a SQLite writer against the one\n * derived-index connection, and a full rebuild that reproduces identical tables from\n * `.agent-qa/runs/<runId>/handoff.json` scans alone (L12 — derived state is disposable).\n *\n * The projection knows ABOUT tests (identity, counters, anchors, flags) and never CONTAINS\n * them: no test file content enters the store, and tests are never memidex-indexed.\n */\nimport { readFileSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport {\n ANALYSIS_FILE,\n admitAnalysisArtifactForRun,\n canonicalJson,\n errorTextOf,\n exercisedAnchors,\n failingStepOf,\n failureFingerprint,\n guardCompletedRunHandoff,\n guardRunAnalysisArtifact,\n normalizeAnchor,\n resolveRunVerdicts,\n slugBranch,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n CompletedRunHandoff,\n PerTestOutcome,\n RunAnalysisArtifact,\n ScopeKey,\n StepEvidence,\n Verdict,\n VerdictClass,\n} from '@vostride/agent-qa-schema'\n\nimport { QuarantineLedgerVersionError } from '@vostride/agent-qa-schema'\nimport type { QuarantineLedgerEvent } from '@vostride/agent-qa-schema'\n\nimport { ensureRunOutcomeTables, openIndexWriter } from '../index-open.js'\nimport { withCurrentWriterAuthority } from '../lease/writer-lease.js'\nimport { evaluateQuarantineDetection, hasSameBuildPassAndFail } from '../quarantine/detection.js'\nimport type {\n QuarantineDetectionFailure,\n QuarantineDetectionSighting,\n QuarantineDetectionTestWindow,\n} from '../quarantine/detection.js'\nimport {\n appendQuarantineEvents,\n foldQuarantineLedgerState,\n readQuarantineLedger,\n} from '../quarantine/ledger.js'\nimport type {\n QuarantineAppendOutcome,\n RefusedQuarantineLine,\n} from '../quarantine/ledger.js'\nimport { fingerprintRecurrence, windowFloor } from './fingerprint-window-read.js'\nimport { isAbsenceErrno, pathPresent } from './path-present.js'\nimport { LAST_OUTCOMES_LIMIT } from './run-outcome-constants.js'\nimport { readTestOutcomeHistory } from './run-outcome-read.js'\nimport { applySuiteFingerprints, suiteFingerprintDeltas } from './suite-fingerprints.js'\nimport type { SuiteFingerprintTestDelta } from './suite-fingerprints.js'\n\n/**\n * Stamped into the curation-tail receipt's projection component. Bump when the fold\n * semantics or table shapes change so already-receipted runs refold on the next tail.\n *\n * HOW THAT REFOLD ACTUALLY HAPPENS (393 CR-02), because the receipt alone cannot do it. The tail\n * stores this number in each run's receipt, so a bump invalidates every receipt and the sweep\n * re-runs each historical run — but the per-run fold then answers 'already-applied' off the\n * durable marker and writes nothing. The stamp is therefore ALSO stored in the index itself, in\n * `run_outcome_projection_version`, and `reconcileRunOutcomesProjection` compares the two ONCE per\n * curation-tail sweep, before the per-run loop: a differing or absent stamp rebuilds the whole\n * projection family from the runs root through `rebuildRunOutcomes`, which clears the family\n * (marker included) and re-reads every `handoff.json` + `analysis.json` from disk. THAT is how an\n * already-receipted run contributes its elements. The per-run receipts then rewrite at the new\n * version through the same sweep. The family is derived, so the rebuild is the whole upgrade, and\n * it is a mechanism that runs, not an argument that it is unnecessary.\n *\n * NOT the case argued at `cli/src/commands/run.ts:1949` (390-08 D-01), where a bump was\n * deliberately declined: there the rebuild would have replayed stored handoffs carrying the OLD\n * identities, landing in the same mixed state the bump was meant to clear. Here the new table has\n * no historical rows at all, and every row it will hold is derivable from evidence the stored\n * handoffs already carry — so the refold produces the complete answer rather than a mixed one.\n */\nexport const RUN_OUTCOMES_PROJECTION_VERSION = 2\n\nexport { LAST_OUTCOMES_LIMIT } from './run-outcome-constants.js'\n\n/**\n * Mirrors runner-local's HANDOFF_FILE. knowledge-local sits below runner-local in the\n * package layering, so the constant cannot be imported without inverting the dependency\n * direction; the rebuild receives the runs root and joins this fixed leaf name.\n */\nconst RUN_HANDOFF_FILE = 'handoff.json'\n\n/** Anchor extraction seam: the CLI tail passes its exercisedAnchors(step) walk. */\nexport type ExtractStepAnchors = (step: StepEvidence) => Anchor[]\n\n/**\n * Projection inputs contain no exclusion override. The durable handoff marker is the sole\n * authority for current-run folds, sibling backfill, and full rebuild alike (D-14 §6).\n */\nexport interface ProjectRunOutcomesOptions {\n extractAnchors: ExtractStepAnchors\n /**\n * The run's persisted analysis artifact when one exists (390 D-09, the `ProjectCanaryOutcomes\n * Input.artifact` precedent). DATA, not a port: `foldRunOutcomes` and `rebuildRunOutcomes` each\n * load it from the run's own dir through the one shared loader and hand it here, so ONE\n * projection function with ONE signature serves both paths — a second signature only one path\n * calls is exactly how L12 rebuild parity breaks in silence.\n */\n artifact?: RunAnalysisArtifact\n}\n\n/**\n * What a FAILED member contributes to the fingerprint-keyed recurrence window (390 D-07).\n *\n * The fingerprint is composed through the ONE exported vocabulary — `failingStepOf`/`errorTextOf`\n * over `exercisedAnchors`, keyed by `failureFingerprint` — so this window and the render-time\n * cluster presentation cannot disagree about what \"the same failure\" is. The verdict class is part\n * of the key by recipe, which is why it travels beside it rather than being re-derived downstream.\n */\nexport interface RunOutcomeFailureKey {\n fingerprint: string\n verdictClass: VerdictClass\n /**\n * WHICH pipeline authored the class (390-16). Not part of the fingerprint and not stored on\n * `run_fingerprint_windows` — it travels on the in-memory delta only, because the quarantine\n * ladder's floor-eligibility gate needs to know whether the class is a statement about THIS\n * TEST (an authored `analyze-run` verdict) or about the RUN (the deterministic floor, whose\n * `environment` arms are one health-probe result applied to every failing member).\n */\n producer: Verdict['producer']\n}\n\nexport interface RunOutcomeTestDelta {\n filePath: string\n testName: string\n passed: boolean\n heals: number\n flake: boolean\n /** canonicalJson(normalizeAnchor(...)) keys — byte-deterministic (ABRF-02 encoding edge). */\n anchorKeys: string[]\n /** Present for exactly the failed members — a pass contributes no window row (D-07). */\n failure?: RunOutcomeFailureKey\n}\n\nexport interface RunOutcomesProjection {\n product: string\n scope: ScopeKey\n runId: string\n buildOrdinal: number\n excluded: boolean\n tests: RunOutcomeTestDelta[]\n /**\n * The suite-fingerprint deltas for the SAME members (393 D-15). They travel on this projection\n * rather than being folded by a second pass so that one traversal of the handoff produces both\n * tables, one transaction commits them, and one applied-runs marker covers them — which is what\n * makes rebuild parity structural instead of asserted.\n */\n fingerprints: SuiteFingerprintTestDelta[]\n}\n\nexport type ApplyRunOutcomesResult =\n | { kind: 'applied'; tests: number }\n | { kind: 'already-applied'; tests: 0 }\n\nexport interface RebuildRunOutcomesOptions {\n extractAnchors: ExtractStepAnchors\n}\n\n/**\n * What one rebuild did, with its two skip causes kept APART (393 round 7, CR-01-WIDENED).\n *\n * A single conflating counter answered \"how many runs did not fold\" and nothing an operator could\n * act on: a malformed `handoff.json` and an unloadable `analysis.json` are different files, written\n * by different producers, and fixed differently. There is deliberately no third counter for a\n * projection or write failure — that class is no longer a skip at all. It propagates out of\n * `rebuildRunOutcomes` and the rebuild produces no report.\n */\nexport interface RebuildRunOutcomesReport {\n folded: number\n /** Runs whose `handoff.json` would not load or carries a pre-381 / structurally unsafe shape. */\n skippedHandoffs: number\n /** Runs whose `handoff.json` loaded but whose `analysis.json` threw (the D-09 second document). */\n skippedArtifacts: number\n}\n\n/**\n * What the fold needs before it may evaluate the quarantine detection ladder (390 D-08).\n *\n * Grouped and OPTIONAL on purpose: a caller that cannot supply a clock does\n * not get a silently empty evaluation, it gets `{kind: 'not-evaluated', reason: 'not-requested'}`\n * on the report. \"Detection ran and found nothing\" and \"detection never ran\" are different facts.\n */\nexport interface QuarantineDetectionOptions {\n /**\n * The ISO-8601 instant the evaluation is anchored to — the drain's own wall clock, read ONCE by\n * the caller. The fold and the rule below it stay clock-free (390-01's purity-by-argument), which\n * is what lets both expiry and the ladder be pinned one step either side.\n */\n now: string\n}\n\nexport interface FoldRunOutcomesOptions {\n /** Absolute agent-qa-knowledge root hosting the derived index SQLite. */\n knowledgeRoot: string\n handoff: CompletedRunHandoff\n extractAnchors: ExtractStepAnchors\n /**\n * The run's own directory (`.agent-qa/runs/<slug(runId)>/`). When supplied, the fold loads\n * `analysis.json` from it so the counters read RESOLVED verdicts (D-09). Absent — a caller that\n * has no run dir — folds the deterministic floor, byte-identically to pre-390.\n */\n runDir?: string\n /** Present when the caller wants the D-08 detection step; absent skips it explicitly. */\n quarantine?: QuarantineDetectionOptions\n}\n\n/**\n * What the fold's detection step did, as DATA (390 Pitfall 4).\n *\n * Every arm is a fact the caller can print. A ledger that could not be read is a value, not an\n * exception: a failure that vanished inside a catch is exactly how an `entered` event goes missing\n * in silence, and a missing `entered` event is a test that keeps failing builds with nobody told\n * why it was supposed to stop.\n */\nexport type QuarantineFoldOutcome =\n | { kind: 'not-evaluated'; reason: 'already-applied' | 'not-requested' }\n /** The committed ledger could not be read at all — detection refuses rather than guessing. */\n | { kind: 'ledger-unreadable'; reason: string }\n | {\n kind: 'evaluated'\n append: QuarantineAppendOutcome\n events: readonly QuarantineLedgerEvent[]\n flagged: readonly QuarantineDetectionSighting[]\n escalatedNotQuarantined: readonly QuarantineDetectionSighting[]\n refusedLines: readonly RefusedQuarantineLine[]\n }\n\nexport type FoldRunOutcomesReport = ApplyRunOutcomesResult & {\n quarantine: QuarantineFoldOutcome\n}\n\ninterface OutcomeEntry {\n buildOrdinal: number\n passed: boolean\n}\n\n/**\n * Derive the projection partition from the same scope-key law as committed records.\n * Product bytes are path-safe to match serving's productSlug bind; the raw scope pair\n * stays alongside them for the shared scope-ladder predicate.\n */\nexport function projectionPartition(scope: ScopeKey): {\n product: string\n scopeTier: ScopeKey['tier']\n scopeKey: string\n} {\n return {\n product: slugBranch(scope.key),\n scopeTier: scope.tier,\n scopeKey: scope.key,\n }\n}\n\nfunction countedOutcome(outcome: PerTestOutcome['outcome']): boolean | undefined {\n switch (outcome) {\n case 'passed':\n case 'healed':\n return true\n case 'failed':\n case 'timeout':\n return false\n default:\n // 'skipped' and 'cancelled' members never ran to a verdict — no counter entry.\n return undefined\n }\n}\n\n/**\n * The RESOLVED VERDICT per member test, computed ONCE per fold (390 D-09, mirroring the canary\n * fold's `resolveAttributionClasses` member-for-member — same class of fold, same input treatment).\n *\n * It answers the whole `Verdict`, not just `.class` (390-16). Both layers below already HOLD one —\n * layer 1 reads `member.rootCause`, which IS a Verdict, and layer 2 reads `resolveRunVerdicts`,\n * which returns them — so keeping only the class was discarding `producer` one step short of the\n * quarantine decision that needs it.\n *\n * Two layers, in overwrite order:\n *\n * 1. Members OUTSIDE the accessor's domain first — a clean pass keeps its persisted class, which\n * is how the runner's one pass-mintable `flake` (classifyRootCause's retry rule) still counts.\n * 2. THE one supersedable-verdict read, `resolveRunVerdicts` (D-10): artifact verdicts when the\n * artifact is present, the deterministic floor when it is absent. It OVERWRITES layer 1\n * wherever it governs, which is exactly how an unknown→flake upgrade moves the flake counter\n * instead of the projection contradicting the resolved verdict.\n *\n * ACCEPTED SHAPE (the 389-06 precedent): a run whose artifact is written AFTER its fold does not\n * refold at the projection version it was folded at. The `run_outcome_applied_runs` marker is\n * final WITHIN a version, so an upgraded class reaches the counters and the fingerprint windows\n * only through LATER runs. ACROSS a version it is not final at all (393 CR-02):\n * `reconcileRunOutcomesProjection` clears the marker through `rebuildRunOutcomes`, which re-reads\n * every artifact from disk — which is where a late upgrade eventually lands, and which is why the\n * version-4 note at the head of this file and this paragraph describe one mechanism rather than\n * contradicting each other.\n */\nfunction resolveProjectionClasses(\n handoff: CompletedRunHandoff,\n artifact: RunAnalysisArtifact | undefined,\n): ReadonlyMap<number, Verdict> {\n const members = handoff.tests ?? []\n const verdicts = new Map<number, Verdict>()\n for (const member of members) {\n if (member.rootCause !== undefined) verdicts.set(member.testIndex, member.rootCause)\n }\n // The accessor traverses `tests` on the floor path; the rebuild's WR-03 wall admits a handoff\n // whose `tests` key is absent, so it is normalized to the same empty array used above.\n for (const verdict of resolveRunVerdicts(artifact, { ...handoff, tests: members })) {\n verdicts.set(verdict.perTest, verdict)\n }\n return verdicts\n}\n\nfunction testDelta(\n test: PerTestOutcome,\n extractAnchors: ExtractStepAnchors,\n resolvedVerdicts: ReadonlyMap<number, Verdict>,\n): RunOutcomeTestDelta | undefined {\n const passed = countedOutcome(test.outcome)\n if (passed === undefined) return undefined\n\n const steps = test.steps ?? []\n const anchorKeys = new Set<string>()\n for (const step of steps) {\n for (const anchor of extractAnchors(step)) {\n anchorKeys.add(canonicalJson(normalizeAnchor(anchor)))\n }\n }\n\n const resolved = resolvedVerdicts.get(test.testIndex)\n return {\n filePath: test.filePath,\n testName: test.testName,\n passed,\n heals: steps.filter((step) => step.selfHeal !== undefined).length,\n flake: resolved?.class === 'flake',\n anchorKeys: [...anchorKeys].sort(),\n ...(passed ? {} : { failure: failureKey({ ...test, steps }, resolved) }),\n }\n}\n\n/**\n * The window key for one failed member (390 D-07).\n *\n * Every input rule is IMPORTED, never respelled here: which step the failure is about\n * (`failingStepOf`), which recorded bytes describe it (`errorTextOf`), which anchors it touched\n * (`exercisedAnchors`), and how those compose into the frozen key (`failureFingerprint`). The\n * anchor walk is schema's own — deliberately NOT the injected `extractAnchors` seam, which exists\n * so callers can vary the projection's anchor ROWS; keying the window through a variable seam would\n * let the window and the cluster presentation drift apart on a test host.\n *\n * A failed member always has a resolved verdict (`resolveRunVerdicts` mints `unknown` for a failure\n * carrying no verdict), so the fallbacks below are total-function guards, not expected paths. The\n * `producer` fallback matches `mintedUnknown`'s own value for the same reason the class fallback\n * matches its class: an absent verdict is exactly the floor's answer, never an authored one.\n */\nfunction failureKey(\n test: PerTestOutcome,\n resolved: Verdict | undefined,\n): RunOutcomeFailureKey {\n const step = failingStepOf(test)\n const anchors = step === undefined ? [] : exercisedAnchors(step)\n const verdictClass = resolved?.class ?? 'unknown'\n return {\n fingerprint: failureFingerprint(\n { anchors, errorText: errorTextOf(step, test) },\n verdictClass,\n ),\n verdictClass,\n producer: resolved?.producer ?? 'deterministic-classifier',\n }\n}\n\n/** Pure fold: identical (handoff, artifact) bytes yield identical row deltas. */\nexport function projectRunOutcomes(\n handoff: CompletedRunHandoff,\n opts: ProjectRunOutcomesOptions,\n): RunOutcomesProjection {\n const partition = projectionPartition(handoff.scope)\n const excluded = handoff.excludedFromOutcomes === true\n const resolvedClasses = resolveProjectionClasses(handoff, opts.artifact)\n // THE ONE EXCLUSION GATE, and every projection below is computed from its output (393 D-15 /\n // WTST-06). A flagged gate-run reaches no counter, no anchor row, no fingerprint element,\n // because after this line there are no members to reach them with. A second gate — one per\n // table — would be the shape in which the two could eventually disagree about the same run,\n // which is exactly Pitfall 8: a gate-run seeding the union it is later compared against.\n const members = excluded ? [] : (handoff.tests ?? [])\n const tests = members.flatMap((test) => {\n const delta = testDelta(test, opts.extractAnchors, resolvedClasses)\n return delta === undefined ? [] : [delta]\n })\n return {\n product: partition.product,\n scope: { tier: partition.scopeTier, key: partition.scopeKey },\n runId: String(handoff.runId),\n buildOrdinal: handoff.buildOrdinal,\n excluded,\n tests,\n fingerprints: suiteFingerprintDeltas(members),\n }\n}\n\nfunction mergeOutcomeEntries(\n existingJson: string | undefined,\n entry: OutcomeEntry,\n): string {\n let entries: OutcomeEntry[] = []\n if (existingJson !== undefined) {\n try {\n const parsed: unknown = JSON.parse(existingJson)\n if (Array.isArray(parsed)) entries = parsed as OutcomeEntry[]\n } catch {\n // A malformed history heals through the rebuild; start the window fresh.\n }\n }\n entries.push(entry)\n // Ordinal-sorted (tiebreak on passed) so incremental fold order and rebuild scan order\n // produce byte-identical windows — the L12 parity requirement.\n entries.sort((a, b) =>\n a.buildOrdinal - b.buildOrdinal || Number(a.passed) - Number(b.passed),\n )\n return canonicalJson(entries.slice(-LAST_OUTCOMES_LIMIT))\n}\n\nfunction runAlreadyApplied(db: DatabaseSync, product: string, runId: string): boolean {\n return db\n .prepare(`\n SELECT 1 AS present\n FROM run_outcome_applied_runs\n WHERE product = ? AND run_id = ?\n `)\n .get(product, runId) !== undefined\n}\n\n/**\n * Writer against the one index connection. Idempotent per product/runId: the applied-runs\n * marker commits in the same transaction as the counter rows, so a crash-rerun tail that\n * refolds an already-applied partition (receipt withheld mid-tail) changes nothing.\n */\nexport function applyRunOutcomes(\n db: DatabaseSync,\n projection: RunOutcomesProjection,\n): ApplyRunOutcomesResult {\n ensureRunOutcomeTables(db)\n if (runAlreadyApplied(db, projection.product, projection.runId)) {\n return { kind: 'already-applied', tests: 0 }\n }\n\n const selectRow = db.prepare(`\n SELECT passes, failures, heals, flake_count, last_outcomes_json, last_build_ordinal\n FROM run_test_outcomes\n WHERE product = ? AND file_path = ? AND test_name = ?\n `)\n const upsertRow = db.prepare(`\n INSERT INTO run_test_outcomes (\n product, scope_tier, scope_key, file_path, test_name, passes, failures, heals,\n flake_count, last_outcomes_json, last_build_ordinal\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (product, file_path, test_name) DO UPDATE SET\n scope_tier = excluded.scope_tier,\n scope_key = excluded.scope_key,\n passes = excluded.passes,\n failures = excluded.failures,\n heals = excluded.heals,\n flake_count = excluded.flake_count,\n last_outcomes_json = excluded.last_outcomes_json,\n last_build_ordinal = excluded.last_build_ordinal\n `)\n const insertAnchor = db.prepare(`\n INSERT OR IGNORE INTO run_test_anchors (\n product, scope_tier, scope_key, file_path, test_name, anchor_normalized_json\n ) VALUES (?, ?, ?, ?, ?, ?)\n `)\n // 390 D-07: window rows commit in the SAME transaction as the counters and behind the SAME\n // applied-runs marker, so a refold can neither double-count a recurrence nor leave counters and\n // windows describing different histories. OR IGNORE makes the uniqueness constraint the second\n // line of defence rather than an error path.\n const insertWindow = db.prepare(`\n INSERT OR IGNORE INTO run_fingerprint_windows (\n product, file_path, test_name, fingerprint, verdict_class, build_ordinal, run_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `)\n\n db.exec('BEGIN IMMEDIATE')\n try {\n for (const test of projection.tests) {\n const existing = selectRow.get(projection.product, test.filePath, test.testName) as\n | {\n passes: number\n failures: number\n heals: number\n flake_count: number\n last_outcomes_json: string\n last_build_ordinal: number | null\n }\n | undefined\n const passes = (existing?.passes ?? 0) + (test.passed ? 1 : 0)\n const failures = (existing?.failures ?? 0) + (test.passed ? 0 : 1)\n const heals = (existing?.heals ?? 0) + test.heals\n const flakeCount = (existing?.flake_count ?? 0) + (test.flake ? 1 : 0)\n const lastBuildOrdinal = Math.max(\n existing?.last_build_ordinal ?? projection.buildOrdinal,\n projection.buildOrdinal,\n )\n upsertRow.run(\n projection.product,\n projection.scope.tier,\n projection.scope.key,\n test.filePath,\n test.testName,\n passes,\n failures,\n heals,\n flakeCount,\n mergeOutcomeEntries(existing?.last_outcomes_json, {\n buildOrdinal: projection.buildOrdinal,\n passed: test.passed,\n }),\n lastBuildOrdinal,\n )\n for (const anchorKey of test.anchorKeys) {\n insertAnchor.run(\n projection.product,\n projection.scope.tier,\n projection.scope.key,\n test.filePath,\n test.testName,\n anchorKey,\n )\n }\n if (test.failure !== undefined) {\n insertWindow.run(\n projection.product,\n test.filePath,\n test.testName,\n test.failure.fingerprint,\n test.failure.verdictClass,\n projection.buildOrdinal,\n projection.runId,\n )\n }\n }\n // 393 D-15: the suite-fingerprint rows commit in the SAME transaction and behind the SAME\n // applied-runs marker as the counters, on the 390 D-07 precedent one paragraph up. The write\n // is convergent on its own (newest `(buildOrdinal, runId)` wins), so the marker is what makes\n // the two tables describe one history rather than what makes this idempotent.\n applySuiteFingerprints(db, {\n product: projection.product,\n runId: projection.runId,\n buildOrdinal: projection.buildOrdinal,\n tests: projection.fingerprints,\n })\n db.prepare('INSERT INTO run_outcome_applied_runs (product, run_id) VALUES (?, ?)')\n .run(projection.product, projection.runId)\n db.exec('COMMIT')\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the apply error that caused the rollback.\n }\n throw error\n }\n return { kind: 'applied', tests: projection.tests.length }\n}\n\n/**\n * An errno-coded fs failure — the FILESYSTEM refusing, not the file's contents being wrong. Every\n * `fs` throw carries a string `code`; `JSON.parse` throws a `SyntaxError` and the schema guard\n * throws a `VersionGuardError`, and neither carries one. Absence errnos never reach this predicate: both\n * loaders convert them to `undefined` (legitimate absence) before anything else can rethrow.\n */\nfunction isErrnoHostFault(error: unknown): boolean {\n return typeof error === 'object'\n && error !== null\n && typeof (error as NodeJS.ErrnoException).code === 'string'\n}\n\n/**\n * One run's persisted analysis artifact, loaded from that run's OWN dir (390 D-09). THE shared\n * loader: the incremental fold and the full rebuild both call it, which is what keeps L12 parity\n * true rather than asserted.\n *\n * The fs glue is local; every rule that matters belongs to schema. An absent file is `undefined` —\n * the deterministic floor. A newer schemaVersion is the guard's typed hard failure, never swallowed\n * into a silent floor. A PRESENT file recording ANOTHER run's id is refused by identity\n * (`admitAnalysisArtifactForRun`, G-389-3A) and folds to the floor: counters and windows never key\n * off another run's verdicts, the 388 cross-instance class.\n *\n * THE LOADER ALWAYS RETHROWS, and what that costs is the CALLER's call (393 round 6, CR-01). On the\n * incremental `foldRunOutcomes` path the throw stands: one run's fold fails loudly rather than\n * silently recording a resolved run at its unresolved floor. In `rebuildRunOutcomes` the per-run\n * body catches the BAD-BYTES class and counts a skip, because there those throws would abandon a\n * family from one malformed run — while an errno-coded HOST fault rethrows from that same\n * call site (393 round 8, CR-01-READ). Two postures, one loader — do not \"fix\" this by softening\n * the loader.\n */\nfunction loadRunArtifact(runDir: string, runId: string): RunAnalysisArtifact | undefined {\n let bytes: string\n try {\n bytes = readFileSync(join(runDir, ANALYSIS_FILE), 'utf8')\n } catch (error) {\n if (isAbsenceErrno(error)) return undefined\n throw error\n }\n const admission = admitAnalysisArtifactForRun(\n guardRunAnalysisArtifact(JSON.parse(bytes)),\n runId,\n )\n return admission.kind === 'admitted' ? admission.artifact : undefined\n}\n\nfunction loadRebuildHandoff(file: string): CompletedRunHandoff | undefined {\n let bytes: string\n try {\n bytes = readFileSync(file, 'utf8')\n } catch (error) {\n if (isAbsenceErrno(error)) return undefined\n throw error\n }\n\n try {\n const guarded = guardCompletedRunHandoff(JSON.parse(bytes))\n\n // WR-03 / L12 fail-closed boundary: EVERY structural access on this untrusted\n // persisted document stays inside this try. A malformed file is a counted skip,\n // never an exception that aborts the disposable derived-state rebuild.\n const tests = (guarded as { tests?: unknown }).tests\n if (tests !== undefined && !Array.isArray(tests)) return undefined\n\n // The guard-level shape hook and this consumer wall are independent: reject unsafe\n // members and steps here before projection traversal can observe them.\n const structurallyCurrent = (tests ?? []).every((test) => {\n if (test === null || typeof test !== 'object' || Array.isArray(test)) return false\n\n const member = test as {\n filePath?: unknown\n testName?: unknown\n steps?: unknown\n }\n return (\n typeof member.filePath === 'string'\n && member.filePath.length > 0\n && typeof member.testName === 'string'\n && member.testName.length > 0\n && (member.steps === undefined\n || (Array.isArray(member.steps)\n && member.steps.every(\n (step) => step !== null && typeof step === 'object' && !Array.isArray(step),\n )))\n )\n })\n return structurallyCurrent ? guarded : undefined\n } catch {\n return undefined\n }\n}\n\n/** The stored fold-semantics stamp, or `undefined` on an index that has never carried one. */\nfunction readStoredProjectionVersion(db: DatabaseSync): number | undefined {\n const row = db\n .prepare('SELECT version FROM run_outcome_projection_version WHERE id = 1')\n .get() as { version: number } | undefined\n return row?.version\n}\n\n/**\n * Full rebuild: scan and read every run dir under `runsRoot`, then clear the projection tables\n * and refold each loadable handoff. Reproduces tables byte-identical to the incremental fold\n * (L12); a rebuild over zero handoff dirs yields empty tables without error (ABRF-02\n * empty edge). BAD-BYTES load failures and pre-381 shapes are counted skips — including a run whose\n * `analysis.json` will not decode, which costs that run's contribution and nothing else (393 round\n * 6, CR-01). One undecodable artifact must never truncate a family this function has already\n * read; an errno-coded HOST fault on either document, on the runs root, or on any run dir\n * propagates BEFORE the family is deleted, so no sweep can stamp — or empty — a family the\n * filesystem prevented it from reading (418-12, CR-01-EXISTS).\n *\n * Phase A: no document is destroyed before every document was read — a host fault during reads\n * leaves the previous family and its stamp untouched (418-12, CR-02-DESTRUCTIVE, load-before-delete).\n * The list holds parsed handoffs for one sweep; the runs root is bounded by host run retention.\n *\n * Phase B is DELETE-FIRST, STAMP-LAST, and that order is the crash story rather than a style choice (393\n * CR-02). The version row is cleared with the family it describes and re-written only after the\n * refold loop has run to completion, so a crash anywhere in between leaves NO stamp — which\n * `reconcileRunOutcomesProjection` reads as a mismatch and rebuilds again. The projection\n * therefore self-heals from a partial rebuild instead of stamping a half-built family as current.\n */\nexport function rebuildRunOutcomes(\n db: DatabaseSync,\n runsRoot: string,\n opts: RebuildRunOutcomesOptions,\n): RebuildRunOutcomesReport {\n const loaded: { handoff: CompletedRunHandoff; artifact?: RunAnalysisArtifact }[] = []\n const report: RebuildRunOutcomesReport = { folded: 0, skippedHandoffs: 0, skippedArtifacts: 0 }\n // A missing runs root is the ABRF-02 empty edge, not a failure: the family is legitimately\n // empty at the CURRENT semantics, so it still earns the stamp below — otherwise a project with\n // no runs yet would rebuild on every single sweep forever.\n if (pathPresent(runsRoot, 'directory') === 'present') {\n const runDirs = readdirSync(runsRoot, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => join(runsRoot, entry.name))\n .filter((dir) => pathPresent(join(dir, RUN_HANDOFF_FILE), 'file') === 'present')\n .sort()\n\n for (const runDir of runDirs) {\n const handoff = loadRebuildHandoff(join(runDir, RUN_HANDOFF_FILE))\n if (handoff === undefined) {\n report.skippedHandoffs += 1\n continue\n }\n // D-09 / L12: share the incremental artifact loader but keep the established per-run\n // BAD-BYTES skip. Only the loader sits in this catch: host faults propagate, and\n // projection/write failures in phase B must never be mistaken for malformed bytes.\n // An unreadable artifact skips the whole run rather than inventing floor counters.\n let artifact: RunAnalysisArtifact | undefined\n try {\n artifact = loadRunArtifact(runDir, String(handoff.runId))\n } catch (error) {\n if (isErrnoHostFault(error)) throw error\n report.skippedArtifacts += 1\n continue\n }\n loaded.push({ handoff, ...(artifact === undefined ? {} : { artifact }) })\n }\n }\n\n ensureRunOutcomeTables(db)\n db.exec(`\n DELETE FROM run_test_outcomes;\n DELETE FROM run_test_anchors;\n DELETE FROM run_outcome_applied_runs;\n DELETE FROM run_fingerprint_windows;\n DELETE FROM suite_fingerprints;\n DELETE FROM run_outcome_projection_version;\n `)\n\n for (const { handoff, artifact } of loaded) {\n // Each apply owns its transaction; a write failure leaves no stamp and retries next sweep.\n applyRunOutcomes(db, projectRunOutcomes(handoff, {\n extractAnchors: opts.extractAnchors,\n ...(artifact === undefined ? {} : { artifact }),\n }))\n report.folded += 1\n }\n\n db.prepare('INSERT OR REPLACE INTO run_outcome_projection_version (id, version) VALUES (1, ?)')\n .run(RUN_OUTCOMES_PROJECTION_VERSION)\n return report\n}\n\n/** What one reconcile did — a fact the caller can print, never a silent side effect. */\nexport type ReconcileRunOutcomesProjectionResult =\n | { kind: 'current' }\n | { kind: 'rebuilt'; report: RebuildRunOutcomesReport }\n | { kind: 'skipped'; reason: 'no-writer-authority' }\n\nexport interface ReconcileRunOutcomesProjectionOptions {\n /** The exact live writer lease owned by the caller; never inferred from an epoch alone. */\n authority?: { leaseId: string; epoch: number }\n /** Absolute agent-qa-knowledge root hosting the derived index SQLite. */\n knowledgeRoot: string\n /** `<agentQaRoot>/runs` — the scan root the rebuild refolds from. */\n runsRoot: string\n extractAnchors: ExtractStepAnchors\n}\n\n/**\n * THE version trigger: reconcile the stored fold semantics with the shipped ones (393 CR-02).\n *\n * `RUN_OUTCOMES_PROJECTION_VERSION`'s doc block has always promised that a bump makes\n * already-receipted runs refold. Nothing performed that refold: `applyRunOutcomes` short-circuits\n * on the `run_outcome_applied_runs` marker before it can reach the fingerprint write, and nothing\n * cleared the marker on a version change — so on any project that folded runs before a bump, the\n * new table stayed empty forever and gate 3's fingerprint lane never had data to decide on. This\n * function is what makes that promise true, and it composes machinery that already existed rather\n * than adding a parallel path: `rebuildRunOutcomes` already clears the family, already re-reads\n * every `handoff.json` + `analysis.json` through the one shared loader, and already reaches\n * `applySuiteFingerprints` for every fold.\n *\n * ABSENT MEANS MISMATCH, deliberately. Every pre-stamp index reads as absent, which is exactly the\n * population that needs to converge; so does an index whose file was deleted, which is exactly the\n * population that needs to re-heal. Treating absence as \"probably fine\" would have made the\n * upgrade path the one path this function does not serve.\n *\n * WHY A REBUILD RATHER THAN A PER-RUN VERSION COLUMN. Refolding runs in place through the\n * incremental path would add each run's counters a SECOND time — the fold accumulates, it does not\n * replace. The rebuild is the mechanism precisely because it clears before it refolds, which is\n * also why the derived family is safe to move this way at all (L12: every row here is reproducible\n * from run artifacts on disk).\n *\n * 418-12 WR-03: a destructive rebuild of a shared derived family is a leased act. A caller\n * without authority gets a typed skip before opening a writer; it stays stale until a leased\n * sweep. The version check and entire rebuild share the current-authority generation lock.\n */\nexport function reconcileRunOutcomesProjection(\n opts: ReconcileRunOutcomesProjectionOptions,\n): ReconcileRunOutcomesProjectionResult {\n if (opts.authority === undefined) return { kind: 'skipped', reason: 'no-writer-authority' }\n return withCurrentWriterAuthority(opts.knowledgeRoot, opts.authority, () => {\n const handle = openIndexWriter(opts.knowledgeRoot)\n try {\n ensureRunOutcomeTables(handle.db)\n if (readStoredProjectionVersion(handle.db) === RUN_OUTCOMES_PROJECTION_VERSION) {\n return { kind: 'current' }\n }\n return {\n kind: 'rebuilt',\n report: rebuildRunOutcomes(handle.db, opts.runsRoot, {\n extractAnchors: opts.extractAnchors,\n }),\n }\n } finally {\n handle.close()\n }\n })\n}\n\n/**\n * The D-08 detection step: evaluate the quarantine ladder over the JUST-COMMITTED window and\n * append whatever lifecycle events it authors.\n *\n * ORDERING, stated rather than pretended (Open Q1). The projection lives in SQLite and the ledger\n * is a committed JSONL file; there is no transaction that spans both, so this cannot be atomic and\n * the code does not claim to be. The append orders AFTER the projection commit, which means a\n * crash between the two leaves the counters applied and no event written.\n * That state SELF-HEALS: the window is still crossed, so the next applied fold re-evaluates and\n * appends then. The opposite order (append first) would have the strictly worse failure: a\n * quarantine entry for a run whose counters never landed.\n *\n * The reads below run on the same connection immediately after `applyRunOutcomes` returned\n * `'applied'`, so the recurrence they see includes this run.\n *\n * TWO PER-TEST OUTCOME READS THAT LOOK REDUNDANT AND ARE NOT (390-21). `testWindows` is built for\n * ENTRIES — tests the ledger already carries — and answers the EXIT question. The flake signature\n * is needed for CROSSINGS, and a crossing is by definition NOT in the ledger yet, so it has no\n * window here: the exit path reads windows for entries, the entry path needs a window for a test\n * that has none. That asymmetry is the whole reason the signature is computed in this function and\n * nowhere else — the failure loop is the only place holding both the crossing's identity and the db\n * handle at once.\n *\n * THE READ COST, stated honestly: one indexed point lookup per CROSSING failure, on a connection\n * already open, after the projection has committed. Crossings are rare by construction — this loop\n * is reached only for members that failed — so this is not a per-test cost on the common path.\n */\nfunction evaluateQuarantineForFold(\n db: DatabaseSync,\n projection: RunOutcomesProjection,\n knowledgeRoot: string,\n opts: QuarantineDetectionOptions,\n): QuarantineFoldOutcome {\n let read\n try {\n read = readQuarantineLedger(knowledgeRoot)\n } catch (error) {\n // Refuse, never heal. A ledger this build cannot parse is committed truth it must not guess\n // at — evaluating against \"no entries\" would re-quarantine released tests and re-enter open\n // ones. The counters already applied; only detection stands down, and it says so.\n if (error instanceof QuarantineLedgerVersionError) {\n return { kind: 'ledger-unreadable', reason: error.message }\n }\n throw error\n }\n const entries = foldQuarantineLedgerState(read.events, opts.now)\n\n const failures: QuarantineDetectionFailure[] = projection.tests.flatMap((test) =>\n test.failure === undefined ? [] : [{\n product: projection.product,\n filePath: test.filePath,\n testName: test.testName,\n fingerprint: test.failure.fingerprint,\n verdictClass: test.failure.verdictClass,\n producer: test.failure.producer,\n // THE PER-CROSSING FLAKE SIGNATURE, read from this test's OWN outcome window (390-21).\n // `hasSameBuildPassAndFail` is called rather than re-derived: the exit path's\n // `distinctOrdinalOutcomes` and this entry-side read share one `groupByBuildOrdinal`, so\n // \"what a build ordinal is\" has exactly one spelling and the two directions cannot drift.\n // A test with no history row answers false through the `?? []` — typed absence, never a\n // throw and never a fabricated window. (Defensive in-tree: the reads below run after\n // `applyRunOutcomes` returned `applied`, so a crossing test always has a row by now.)\n //\n // AND IT IS SCOPED TO THIS CROSSING'S OWN RECURRENCE WINDOW (390-24, WR-05). The per-test\n // outcome window keeps LAST_OUTCOMES_LIMIT entries, which is DEEPER than the detection\n // window, so an unscoped read let a since-fixed flake episode license a new hard regression\n // several ordinals later — the gate silencing exactly what the disposition table exists to\n // keep failing the build. The floor here is `fingerprintRecurrence`'s floor, from the same\n // export: the evidence and the count are bounded by ONE window, so evidence expires with the\n // window that licensed nothing (D-07 windows-forgive; D-05 anti-silencing).\n sameBuildPassAndFail: hasSameBuildPassAndFail(\n (readTestOutcomeHistory(db, {\n product: projection.product,\n filePath: test.filePath,\n testName: test.testName,\n })?.lastOutcomes ?? []).filter(\n (outcome) => outcome.buildOrdinal >= windowFloor(projection.buildOrdinal)\n && outcome.buildOrdinal <= projection.buildOrdinal,\n ),\n ),\n ...fingerprintRecurrence(\n db,\n { product: projection.product, fingerprint: test.failure.fingerprint },\n projection.buildOrdinal,\n ),\n }])\n\n // Exit candidates are every entry in this product that is still LISTED — `quarantined` or\n // `expired` — and not only the tests that ran here: a test whose window filled with passes\n // several runs ago must still be released. A LAPSED entry is included because a test fixed while\n // its window was lapsed is still listed and can otherwise only be closed by hand (390-17).\n //\n // TWO SITES, ONE RULE. `evaluateQuarantineDetection`'s release loop (quarantine/detection.ts)\n // applies the same state test to the entries themselves. This filter decides whether a window is\n // BUILT at all, so narrowing it alone silently disables the release for a whole state class while\n // the pure rule's own tests stay green over windows the fold never hands it.\n const testWindows: QuarantineDetectionTestWindow[] = entries.flatMap((entry) => {\n if (entry.state === 'released' || entry.product !== projection.product) return []\n const history = readTestOutcomeHistory(db, {\n product: entry.product,\n filePath: entry.filePath,\n testName: entry.testName,\n })\n if (history === undefined) return []\n return [{\n product: entry.product,\n filePath: entry.filePath,\n testName: entry.testName,\n ordinals: history.lastOutcomes,\n }]\n })\n\n const detection = evaluateQuarantineDetection({\n failures,\n testWindows,\n entries,\n now: opts.now,\n })\n\n const append = appendQuarantineEvents(knowledgeRoot, detection.events)\n\n return {\n kind: 'evaluated',\n append,\n events: detection.events,\n flagged: detection.flagged,\n escalatedNotQuarantined: detection.escalatedNotQuarantined,\n refusedLines: read.refusedLines,\n }\n}\n\n/**\n * Incremental fold wrapper for the post-verdict tail: opens the one index writer, applies\n * the projection, and closes. The tail invokes it inside the SAME crash boundary and the\n * SAME (extended) receipt as candidate/canary emit — never a second marker file.\n *\n * Detection hangs off the `'applied'` arm ONLY (D-08). `applyRunOutcomes` answers\n * `'already-applied'` from an early return that fires before its transaction even opens, so\n * \"a refold never double-quarantines\" is true by POSITION — there is no second idempotency\n * condition here to keep in sync with the marker.\n */\nexport function foldRunOutcomes(opts: FoldRunOutcomesOptions): FoldRunOutcomesReport {\n const artifact = opts.runDir === undefined\n ? undefined\n : loadRunArtifact(opts.runDir, String(opts.handoff.runId))\n const projection = projectRunOutcomes(opts.handoff, {\n extractAnchors: opts.extractAnchors,\n ...(artifact === undefined ? {} : { artifact }),\n })\n const handle = openIndexWriter(opts.knowledgeRoot)\n try {\n const applied = applyRunOutcomes(handle.db, projection)\n if (applied.kind !== 'applied') {\n return { ...applied, quarantine: { kind: 'not-evaluated', reason: 'already-applied' } }\n }\n if (opts.quarantine === undefined) {\n return { ...applied, quarantine: { kind: 'not-evaluated', reason: 'not-requested' } }\n }\n return {\n ...applied,\n quarantine: evaluateQuarantineForFold(\n handle.db,\n projection,\n opts.knowledgeRoot,\n opts.quarantine,\n ),\n }\n } finally {\n handle.close()\n }\n}\n","import { statSync } from 'node:fs'\n\nexport type PathPresence = 'present' | 'absent'\n\n/** The only filesystem errors that establish absence, including a vanished parent. */\nexport function isAbsenceErrno(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const code = (error as NodeJS.ErrnoException).code\n return code === 'ENOENT' || code === 'ENOTDIR'\n}\n\n/**\n * Distinguish absence from a filesystem refusal at every projection read boundary.\n * Only ENOENT/ENOTDIR mean absent. A present wrong kind is a host fault: EISDIR\n * for a directory in a document slot, and the same explicit shape for a non-directory\n * in the runs-root slot. Never manufacture ENOTDIR here: it would disguise a present\n * malformed root as absence. Other stat failures propagate unchanged.\n */\nexport function pathPresent(path: string, expect: 'file' | 'directory'): PathPresence {\n let stat\n try {\n stat = statSync(path)\n } catch (error) {\n if (isAbsenceErrno(error)) return 'absent'\n throw error\n }\n if (expect === 'file' ? stat.isFile() : stat.isDirectory()) return 'present'\n throw Object.assign(new Error(`EISDIR: expected ${expect} at projection read boundary`), {\n code: 'EISDIR',\n path,\n })\n}\n","/**\n * Read side of the run-outcome projection (389 ANLZ-03, RESEARCH Pitfall 2).\n *\n * `run_test_outcomes` is written by `foldRunOutcomes`/`applyRunOutcomes`; this module is\n * the one place that queries it. Strictly read-only: one prepared SELECT, no statement\n * that mutates a row, ever — the writer half stays whole in `run-outcomes.ts`.\n *\n * KEY LAW — stable test identity is `(product, filePath, testName)`, exactly the\n * projection's primary key and per-test-outcome.ts's identity rule. Callers joining from\n * a handoff use `PerTestOutcome.filePath` + `testName`, NEVER `testId` (a per-run\n * explicit id, not a durable identity).\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport { LAST_OUTCOMES_LIMIT } from './run-outcome-constants.js'\n\n/** One window entry: ordinals only, wall-clock never (mirrors the writer's OutcomeEntry). */\nexport interface TestOutcomeEntry {\n buildOrdinal: number\n passed: boolean\n}\n\nexport interface TestOutcomeHistory {\n passes: number\n failures: number\n heals: number\n flakeCount: number\n /** Ordinal-ascending, at most LAST_OUTCOMES_LIMIT entries; [] when the stored JSON is malformed. */\n lastOutcomes: TestOutcomeEntry[]\n lastBuildOrdinal: number | undefined\n}\n\n/** The projection's key, spelled the way the table is keyed. */\nexport interface TestOutcomeIdentity {\n product: string\n filePath: string\n testName: string\n}\n\nfunction isOutcomeEntry(value: unknown): value is TestOutcomeEntry {\n return (\n value !== null\n && typeof value === 'object'\n && !Array.isArray(value)\n && typeof (value as { buildOrdinal?: unknown }).buildOrdinal === 'number'\n && typeof (value as { passed?: unknown }).passed === 'boolean'\n )\n}\n\n/**\n * Heal-to-empty parse of `last_outcomes_json` — the same tolerance posture as the\n * writer's `mergeOutcomeEntries`: a malformed history is an empty window, never a throw.\n * The ascending sort and window cap are re-derived defensively so the read-side\n * invariants hold even over bytes an older writer left behind.\n */\nfunction parseLastOutcomes(json: string): TestOutcomeEntry[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(json)\n } catch {\n return []\n }\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(isOutcomeEntry)\n .map((entry) => ({ buildOrdinal: entry.buildOrdinal, passed: entry.passed }))\n .sort((a, b) => a.buildOrdinal - b.buildOrdinal || Number(a.passed) - Number(b.passed))\n .slice(-LAST_OUTCOMES_LIMIT)\n}\n\n/**\n * Answer one test's failure history from `run_test_outcomes`, or `undefined` when the\n * projection has never counted the test — typed absence, never an empty stand-in row.\n */\nexport function readTestOutcomeHistory(\n db: DatabaseSync,\n identity: TestOutcomeIdentity,\n): TestOutcomeHistory | undefined {\n const row = db\n .prepare(`\n SELECT passes, failures, heals, flake_count, last_outcomes_json, last_build_ordinal\n FROM run_test_outcomes\n WHERE product = ? AND file_path = ? AND test_name = ?\n `)\n .get(identity.product, identity.filePath, identity.testName) as\n | {\n passes: number\n failures: number\n heals: number\n flake_count: number\n last_outcomes_json: string\n last_build_ordinal: number | null\n }\n | undefined\n if (row === undefined) return undefined\n return {\n passes: row.passes,\n failures: row.failures,\n heals: row.heals,\n flakeCount: row.flake_count,\n lastOutcomes: parseLastOutcomes(row.last_outcomes_json),\n lastBuildOrdinal: row.last_build_ordinal ?? undefined,\n }\n}\n\n/**\n * Every identity the projection has counted inside ONE file, in one product (394-17 · WTST-05).\n *\n * The neighbours side of D-14's stability read: \"which tests does this suite file already have run\n * evidence for\". Keyed on the projection's own primary key, so `product` is REQUIRED for the same\n * reason `readTestOutcomeHistory` requires it — a query that dropped it would serve every\n * product's rows under one file path and report another application's tests as this target's.\n *\n * `test_name` ORDER, so a caller's message names its neighbours in a stable order across runs. An\n * empty array is the honest answer for a file the projection has never counted; the caller turns\n * that into a `no-history` posture rather than into a clean bill of health.\n */\nexport function listTestsInFile(\n db: DatabaseSync,\n scope: { product: string; filePath: string },\n): string[] {\n return db\n .prepare(`\n SELECT test_name\n FROM run_test_outcomes\n WHERE product = ? AND file_path = ?\n ORDER BY test_name\n `)\n .all(scope.product, scope.filePath)\n .map((row) => String((row as { test_name: unknown }).test_name))\n}\n\n/**\n * D-02's forced discriminator channel: did the same step pass on the previous build?\n * Answers the entry with the greatest buildOrdinal STRICTLY below `currentBuildOrdinal`,\n * or `undefined` when no prior build is in the window (empty history, a single\n * current-build entry, or every entry at/above current) — prior-build honestly absent,\n * never faked from the current entry.\n */\nexport function priorBuildOutcome(\n history: TestOutcomeHistory,\n currentBuildOrdinal: number,\n): TestOutcomeEntry | undefined {\n let prior: TestOutcomeEntry | undefined\n for (const entry of history.lastOutcomes) {\n if (entry.buildOrdinal >= currentBuildOrdinal) continue\n if (prior === undefined || entry.buildOrdinal >= prior.buildOrdinal) prior = entry\n }\n return prior\n}\n\nexport interface FailureRecurrence {\n /** Failed entries with buildOrdinal AT OR BELOW current — includes the current failure when recorded. */\n kth: number\n /** Distinct buildOrdinals observed in lastOutcomes — honest about the ≤LAST_OUTCOMES_LIMIT window. */\n windowBuilds: number\n}\n\n/**\n * Feeds \"Kth failure in the last N builds\", computed LIVE at render time (D-08) — counts\n * derived from the window on every call, never stored prose. 390 rebinds the same seam to\n * its fingerprint-window computation; this derivation is 389's binding, not the seam's\n * final owner. An empty history answers {kth: 0, windowBuilds: 0}: the renderer (plan 05)\n * turns zero-history into an explicit no-history clause, so absence stays typed.\n */\nexport function failureRecurrence(\n history: TestOutcomeHistory,\n currentBuildOrdinal: number,\n): FailureRecurrence {\n const kth = history.lastOutcomes.filter(\n (entry) => !entry.passed && entry.buildOrdinal <= currentBuildOrdinal,\n ).length\n const windowBuilds = new Set(\n history.lastOutcomes.map((entry) => entry.buildOrdinal),\n ).size\n return { kth, windowBuilds }\n}\n","// The suite-fingerprint table: gate 3's comparison substrate (Phase 393, D-15 · WTST-06).\n//\n// A SIBLING of `run-outcomes.ts` inside the same derived-index discipline, not a new store. It\n// lives in the gitignored index, is computed at the SAME post-run fold from the SAME handoff\n// evidence, is keyed by the project-wide stable test identity (`filePath` + `testName`, never\n// `testId`), and is reproduced byte-identically by the rebuild — which is why bumping\n// `RUN_OUTCOMES_PROJECTION_VERSION` IS this table's migration (L12: derived state is disposable).\n//\n// WHAT A ROW IS. One `(product, filePath, testName, seq)` row per fingerprint element, where the\n// element bytes are minted by schema's `actionAnchorElement` (D-13's v1 recipe). No element\n// serialization exists in this package: a second spelling of \"what is the same exercised surface\"\n// is exactly what the sibling-recipe design in `verdict/action-anchor-fingerprint.ts` exists to\n// prevent, and gate 3 compares a draft's elements against these bytes.\n//\n// WHY THE ROWS CARRY `run_id` AND `build_ordinal`. \"Latest evidence wins\" has to mean something\n// order-independent, or the incremental fold and the rebuild would disagree the moment two runs\n// arrived in a different order than the rebuild scans them in (the rebuild sorts run dirs by\n// name). The replacement rule is therefore a COMPARISON — a fold replaces an identity's rows only\n// when its `(buildOrdinal, runId)` is strictly greater than what the table already holds — rather\n// than a last-writer-wins overwrite. That makes the table CONVERGENT: any permutation of the same\n// runs, and a full rebuild over them, land on the same rows. It is also why re-applying one run is\n// a no-op without needing the applied-runs marker to make it one.\n//\n// THE EXCLUSION (WTST-06, Pitfall 8). A gate-run handoff must never seed the union it is later\n// compared against — a draft would then be measured against its own evidence and every element\n// would read as already covered. The production path enforces this WITHOUT a second read: the one\n// `excludedFromOutcomes` read in `projectRunOutcomes` gates ONE member list, and both the outcome\n// deltas and the fingerprint deltas are computed from that already-gated list. The standalone\n// `foldSuiteFingerprints` door below takes the same decision as an argument for the same reason —\n// this module does not re-decide a fact the fold already established.\n\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport { testFingerprintElements } from '@vostride/agent-qa-schema'\nimport type { CompletedRunHandoff, PerTestOutcome } from '@vostride/agent-qa-schema'\n\nimport { ensureRunOutcomeTables } from '../index-open.js'\n\n/** The one table name, so the read port and every writer cannot spell it apart. */\nexport const SUITE_FINGERPRINTS_TABLE = 'suite_fingerprints'\n\n/**\n * The element walk, re-exported from its home in `schema` (393-06).\n *\n * It lived here until gate 3's DRAFT side became its second reader. `agent` names neither this\n * package nor `core` and never will, so a walk that stayed here could only have been mirrored on\n * the draft side — and a mirrored recipe is two recipes, free to disagree the first time either\n * is retuned. Its own doc comment already promised that \"the draft's own fingerprint is computed\n * by this same function at the consumer\"; moving it is what makes that sentence true rather than\n * aspirational. `ASSERT_ACTION_TYPES` moved with it on the trigger its comment named.\n *\n * Re-exported rather than dropped because this module is where the fold's readers look for it,\n * and the package barrel already publishes the name.\n */\nexport { testFingerprintElements }\n\n/** One test's ordered fingerprint elements, keyed by the stable identity. */\nexport interface SuiteFingerprintTestDelta {\n filePath: string\n testName: string\n /** `actionAnchorElement` bytes, in exercised order. Never empty — see `testFingerprint`. */\n elements: string[]\n}\n\n/** The row set one run contributes, plus the provenance the replacement rule compares on. */\nexport interface SuiteFingerprintsProjection {\n product: string\n runId: string\n buildOrdinal: number\n tests: SuiteFingerprintTestDelta[]\n}\n\nexport interface FoldSuiteFingerprintsOptions {\n /**\n * The projection partition — `projectionPartition(handoff.scope).product`. Supplied by the\n * caller so this module never re-spells the partition law that `run-outcomes.ts` owns (and so\n * the two modules do not have to import each other).\n */\n product: string\n /**\n * The `excludedFromOutcomes` decision, CARRIED rather than re-read. See the exclusion note in\n * this module's header: a gate-run contributes no rows.\n */\n excluded: boolean\n}\n\n/**\n * The per-identity deltas for a member list (pure).\n *\n * Takes MEMBERS rather than a handoff because the production caller has already applied the one\n * exclusion gate to them — see the exclusion note in the header. A test contributing zero\n * elements yields no delta at all, which is what stops an evidence-less run from ERASING an\n * identity's accumulated coverage: the union only ever moves through evidence.\n */\nexport function suiteFingerprintDeltas(\n members: readonly PerTestOutcome[],\n): SuiteFingerprintTestDelta[] {\n const byIdentity = new Map<string, SuiteFingerprintTestDelta>()\n for (const member of members) {\n const elements = testFingerprintElements(member)\n if (elements.length === 0) continue\n // Within ONE run the same identity can appear more than once (a retried member). Later\n // evidence inside a single handoff wins, matching the cross-run rule below.\n byIdentity.set(`${member.filePath}\\u0000${member.testName}`, {\n filePath: member.filePath,\n testName: member.testName,\n elements,\n })\n }\n return [...byIdentity.values()]\n}\n\ninterface ExistingProvenance {\n build_ordinal: number\n run_id: string\n}\n\n/**\n * Whether incoming evidence supersedes what the table holds for one identity.\n *\n * Strictly greater, with `runId` as the tiebreak inside one build ordinal, so the answer does not\n * depend on which run folded first. Equality is deliberately NOT a supersession: re-applying the\n * same run rewrites nothing.\n */\nfunction supersedes(\n incoming: { buildOrdinal: number; runId: string },\n existing: ExistingProvenance | undefined,\n): boolean {\n if (existing === undefined) return true\n if (incoming.buildOrdinal !== existing.build_ordinal) {\n return incoming.buildOrdinal > existing.build_ordinal\n }\n return incoming.runId > existing.run_id\n}\n\n/**\n * Writer against the one index connection.\n *\n * Deliberately opens NO transaction of its own. On the production path it runs inside\n * `applyRunOutcomes`'s `BEGIN IMMEDIATE`, so the fingerprint rows and the outcome counters commit\n * or roll back together and the two tables can never describe different runs; SQLite has no\n * nested transactions, so a second `BEGIN IMMEDIATE` here would fail exactly on that path. Called\n * standalone it rides autocommit, which is sound because the replacement rule is convergent.\n */\nexport function applySuiteFingerprints(\n db: DatabaseSync,\n projection: SuiteFingerprintsProjection,\n): number {\n const readProvenance = db.prepare(`\n SELECT build_ordinal, run_id\n FROM ${SUITE_FINGERPRINTS_TABLE}\n WHERE product = ? AND file_path = ? AND test_name = ?\n LIMIT 1\n `)\n const clearIdentity = db.prepare(`\n DELETE FROM ${SUITE_FINGERPRINTS_TABLE}\n WHERE product = ? AND file_path = ? AND test_name = ?\n `)\n const insertElement = db.prepare(`\n INSERT INTO ${SUITE_FINGERPRINTS_TABLE} (\n product, file_path, test_name, seq, element, run_id, build_ordinal\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `)\n\n let written = 0\n for (const test of projection.tests) {\n const existing = readProvenance.get(projection.product, test.filePath, test.testName) as\n | ExistingProvenance\n | undefined\n if (!supersedes(projection, existing)) continue\n clearIdentity.run(projection.product, test.filePath, test.testName)\n for (const [seq, element] of test.elements.entries()) {\n insertElement.run(\n projection.product,\n test.filePath,\n test.testName,\n seq,\n element,\n projection.runId,\n projection.buildOrdinal,\n )\n written += 1\n }\n }\n return written\n}\n\n/**\n * The standalone fold door: project one handoff's fingerprints and write them.\n *\n * The production path does NOT come through here — it folds both projections in one pass through\n * `projectRunOutcomes`/`applyRunOutcomes` so a single transaction and a single applied-runs marker\n * cover both tables. This entry exists for callers that hold a handoff and want only the\n * fingerprint half (the gate evaluator's own harness, and this module's corpus).\n */\nexport function foldSuiteFingerprints(\n db: DatabaseSync,\n handoff: CompletedRunHandoff,\n opts: FoldSuiteFingerprintsOptions,\n): SuiteFingerprintsProjection {\n ensureRunOutcomeTables(db)\n const projection: SuiteFingerprintsProjection = {\n product: opts.product,\n runId: String(handoff.runId),\n buildOrdinal: handoff.buildOrdinal,\n tests: suiteFingerprintDeltas(opts.excluded ? [] : (handoff.tests ?? [])),\n }\n applySuiteFingerprints(db, projection)\n return projection\n}\n\n/**\n * The read port gate 3 consumes through composition (D-15).\n *\n * MINIMAL BY DESIGN. Conservatism lives in the normalizer (D-14), not here: this port answers\n * what the table holds and nothing more, so a later retune of \"near-same elements normalize\n * equal\" moves in exactly one place. There is no similarity verb here because there is no\n * similarity threshold to defend — gate 3's value test is set membership, spec §6.3 verbatim.\n */\nexport interface SuiteFingerprintIndex {\n /** The union D-14's novel-element test compares against. Empty table, empty union. */\n elementUnion(): Set<string>\n /**\n * The identities that HAVE fingerprint rows, sorted. The consumer subtracts these from the\n * authored-test universe to derive the evidence-less set that rides D-16's text lane — which is\n * why this port reports coverage rather than trying to enumerate the suite, a fact it does not\n * own and could only guess at.\n */\n coveredTests(): Array<{ filePath: string; testName: string }>\n /** One identity's elements in exercised order; `[]` for an identity with no rows. */\n elementsForTest(filePath: string, testName: string): string[]\n}\n\nexport interface SuiteFingerprintIndexOptions {\n /**\n * The partition to read. REQUIRED rather than optional: an unscoped union would compare a draft\n * against another product's suite, and \"everything in the table\" is never the question gate 3 is\n * asking.\n */\n product: string\n}\n\nexport function createSuiteFingerprintIndex(\n db: DatabaseSync,\n opts: SuiteFingerprintIndexOptions,\n): SuiteFingerprintIndex {\n return {\n elementUnion() {\n const rows = db.prepare(`\n SELECT DISTINCT element FROM ${SUITE_FINGERPRINTS_TABLE} WHERE product = ?\n `).all(opts.product) as unknown as Array<{ element: string }>\n return new Set(rows.map((row) => row.element))\n },\n coveredTests() {\n const rows = db.prepare(`\n SELECT DISTINCT file_path, test_name FROM ${SUITE_FINGERPRINTS_TABLE}\n WHERE product = ?\n ORDER BY file_path, test_name\n `).all(opts.product) as unknown as Array<{ file_path: string; test_name: string }>\n return rows.map((row) => ({ filePath: row.file_path, testName: row.test_name }))\n },\n elementsForTest(filePath: string, testName: string) {\n const rows = db.prepare(`\n SELECT element FROM ${SUITE_FINGERPRINTS_TABLE}\n WHERE product = ? AND file_path = ? AND test_name = ?\n ORDER BY seq\n `).all(opts.product, filePath, testName) as unknown as Array<{ element: string }>\n return rows.map((row) => row.element)\n },\n }\n}\n","import { rmSync } from 'node:fs'\nimport { isAbsolute } from 'node:path'\n\nimport { asRecordId, survivingOutcomeEvents } from '@vostride/agent-qa-schema'\nimport type {\n DerivedTrustState,\n RecordId,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\nimport { enumerateBundleDirs } from './bundle-scan.js'\nimport { assertWithinKnowledgeRoot } from './knowledge-containment.js'\nimport {\n foldSupersessionLineage,\n scanCanonicalBundles,\n} from './curator/lineage-fold.js'\nimport type { CanonicalBundleSnapshot } from './curator/lineage-fold.js'\nimport {\n withCurrentWriterAuthority,\n type WriterLeaseAuthority,\n} from './lease/writer-lease.js'\n\n/**\n * PROVISIONAL D-13 superseded-generation retention depth. M3 may calibrate the\n * value against gate receipts, but it remains an internal constitution value\n * and never a runtime config key.\n */\nexport const GC_SUPERSEDED_RETAIN_K = 3\n\n/**\n * D-13 gate seam. M2 always passes `{ kind: 'none' }`; M3 plugs real gate\n * receipt ordinals into the second variant with zero shape change.\n */\nexport type GateHorizon =\n | { kind: 'none' }\n | { kind: 'ordinal'; deepestGateOrdinal: number }\n\nexport interface GcSummary {\n trimmedRecordIds: RecordId[]\n skipped: {\n unknownRef: number\n withinK: number\n userOrigin: number\n horizon: number\n }\n}\n\nexport interface RunKnowledgeGcInput {\n knowledgeRoot: string\n horizon: GateHorizon\n retainK?: number\n}\n\nexport interface RunKnowledgeGcHooks {\n /** Test/chaos seam immediately before the authority check for one planned removal. */\n beforeGcRemoval?(recordId: RecordId): void\n}\n\ninterface GcBundle {\n recordId: RecordId\n dir: string\n bundle: LoadedBundle\n // GC selection depends only on lifecycle and horizon, never numerical trust.\n trust: Pick<DerivedTrustState, 'status' | 'validity'>\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction validateInput(input: RunKnowledgeGcInput): number {\n if (!isAbsolute(input.knowledgeRoot)) {\n throw new TypeError('runKnowledgeGc knowledgeRoot must be absolute')\n }\n const retainK = input.retainK ?? GC_SUPERSEDED_RETAIN_K\n if (!Number.isSafeInteger(retainK) || retainK < 0) {\n throw new RangeError('runKnowledgeGc retainK must be a non-negative safe integer')\n }\n if (\n input.horizon.kind === 'ordinal'\n && (\n !Number.isSafeInteger(input.horizon.deepestGateOrdinal)\n || input.horizon.deepestGateOrdinal < 0\n )\n ) {\n throw new RangeError(\n 'runKnowledgeGc deepestGateOrdinal must be a non-negative safe integer',\n )\n }\n return retainK\n}\n\nfunction loadGcBundles(knowledgeRoot: string): Map<RecordId, GcBundle> {\n const bundles = new Map<RecordId, GcBundle>()\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded') continue\n const recordId = asRecordId(loaded.bundle.manifest.id)\n bundles.set(recordId, {\n recordId,\n dir: entry.dir,\n bundle: loaded.bundle,\n trust: deriveBundleTrust(loaded.bundle),\n })\n }\n return bundles\n}\n\nfunction latestBuildOrdinal(bundles: readonly CanonicalBundleSnapshot[]): number {\n let latest = 1\n for (const bundle of bundles) {\n latest = Math.max(latest, bundle.createdAtOrdinal)\n for (const event of bundle.events) latest = Math.max(latest, event.buildOrdinal)\n }\n return latest\n}\n\nfunction latestSupersessionOrdinal(bundle: CanonicalBundleSnapshot): number {\n let latest = bundle.createdAtOrdinal\n for (const event of survivingOutcomeEvents(bundle.events)) {\n if (event.type === 'superseded') latest = Math.max(latest, event.buildOrdinal)\n }\n return latest\n}\n\nfunction unknownConflictRecordIds(bundle: LoadedBundle): string[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(bundle.manifest.identityCore.discriminantKey)\n } catch (error) {\n throw new TypeError(\n `unknown bundle ${bundle.manifest.id} has a non-JSON discriminant key`,\n { cause: error },\n )\n }\n if (\n typeof parsed !== 'object'\n || parsed === null\n || !('kind' in parsed)\n || parsed.kind !== 'unknown'\n || !('conflictRecordIds' in parsed)\n || !Array.isArray(parsed.conflictRecordIds)\n || parsed.conflictRecordIds.some((recordId) => typeof recordId !== 'string')\n ) {\n throw new TypeError(\n `unknown bundle ${bundle.manifest.id} has an invalid conflict-record discriminant`,\n )\n }\n return parsed.conflictRecordIds\n}\n\nfunction buildUnknownReferenceExclusion(bundles: Iterable<GcBundle>): Set<string> {\n const referenced = new Set<string>()\n for (const candidate of bundles) {\n if (\n candidate.bundle.frontmatter.kind !== 'unknown'\n || candidate.trust.status === 'deprecated'\n || candidate.trust.status === 'superseded'\n ) {\n continue\n }\n for (const recordId of unknownConflictRecordIds(candidate.bundle)) {\n referenced.add(recordId)\n }\n for (const relation of candidate.bundle.relations.relations) {\n referenced.add(relation.targetId)\n }\n }\n return referenced\n}\n\nfunction intersectsGateHorizon(\n validity: DerivedTrustState['validity'],\n horizon: GateHorizon,\n): boolean {\n if (horizon.kind === 'none') return false\n // Validity is half-open [opened, closed). It intersects [N, +infinity) iff\n // it remains open strictly beyond N; an unclosed window always intersects.\n return validity.closedAtOrdinal === undefined\n || validity.closedAtOrdinal > horizon.deepestGateOrdinal\n}\n\nfunction buildWithinKExclusion(\n snapshots: readonly CanonicalBundleSnapshot[],\n retainK: number,\n): { supersededChainIds: Set<RecordId>; withinK: Set<RecordId> } {\n const byRecordId = new Map(snapshots.map((snapshot) => [snapshot.recordId, snapshot]))\n const asOfBuildOrdinal = latestBuildOrdinal(snapshots)\n const lineage = foldSupersessionLineage(snapshots, {\n windowBuilds: asOfBuildOrdinal,\n asOfBuildOrdinal,\n })\n const supersededChainIds = new Set<RecordId>()\n const withinK = new Set<RecordId>()\n\n for (const folded of lineage.values()) {\n const superseded = folded.chainRecordIds\n .flatMap((recordId) => {\n const snapshot = byRecordId.get(recordId)\n return snapshot?.status === 'superseded' ? [snapshot] : []\n })\n .sort((left, right) =>\n latestSupersessionOrdinal(right) - latestSupersessionOrdinal(left)\n || right.createdAtOrdinal - left.createdAtOrdinal\n || compareText(right.recordId, left.recordId),\n )\n for (const snapshot of superseded) supersededChainIds.add(snapshot.recordId)\n for (const snapshot of superseded.slice(0, retainK)) withinK.add(snapshot.recordId)\n }\n\n return { supersededChainIds, withinK }\n}\n\n/**\n * Trim only whole superseded bundle directories after constructing every D-13\n * exclusion set. No projection SQL exists here by design: the drain tail feeds\n * trimmedRecordIds straight into removeBundleProjectionRows, so the disposable\n * index heals in the same drain (WR-01).\n *\n * RATIFICATION: this typed in-memory summary, surfaced through drain diagnostics,\n * is the low-cost §9.2-style operational note. GC writes no persisted note artifact.\n */\nexport function runKnowledgeGc(\n input: RunKnowledgeGcInput,\n writerAuthority: WriterLeaseAuthority,\n hooks: RunKnowledgeGcHooks = {},\n): GcSummary {\n const retainK = validateInput(input)\n if (writerAuthority.knowledgeRoot !== input.knowledgeRoot) {\n throw new TypeError('GC writerAuthority must belong to knowledgeRoot')\n }\n const snapshots = scanCanonicalBundles(input.knowledgeRoot)\n const loaded = loadGcBundles(input.knowledgeRoot)\n\n // Pitfall 10: build the complete exclusion set before the first destructive write.\n const unknownRef = buildUnknownReferenceExclusion(loaded.values())\n const { supersededChainIds, withinK } = buildWithinKExclusion(snapshots, retainK)\n const userOrigin = new Set(\n [...loaded.values()]\n .filter(({ bundle }) => bundle.frontmatter.originClass === 'user')\n .map(({ recordId }) => recordId),\n )\n const horizon = new Set(\n [...loaded.values()]\n .filter(({ trust }) => intersectsGateHorizon(trust.validity, input.horizon))\n .map(({ recordId }) => recordId),\n )\n\n const skipped = { unknownRef: 0, withinK: 0, userOrigin: 0, horizon: 0 }\n const trim: GcBundle[] = []\n for (const recordId of [...supersededChainIds].sort(compareText)) {\n const candidate = loaded.get(recordId)\n if (candidate === undefined || candidate.trust.status !== 'superseded') continue\n if (withinK.has(recordId)) {\n skipped.withinK += 1\n continue\n }\n let excluded = false\n if (unknownRef.has(recordId)) {\n skipped.unknownRef += 1\n excluded = true\n }\n if (userOrigin.has(recordId)) {\n skipped.userOrigin += 1\n excluded = true\n }\n if (horizon.has(recordId)) {\n skipped.horizon += 1\n excluded = true\n }\n if (!excluded) trim.push(candidate)\n }\n\n for (const candidate of trim) {\n hooks.beforeGcRemoval?.(candidate.recordId)\n withCurrentWriterAuthority(\n input.knowledgeRoot,\n writerAuthority,\n () => {\n // 261003-mqc: never delete a bundle reached through a link out of the knowledge root.\n assertWithinKnowledgeRoot(input.knowledgeRoot, candidate.dir)\n rmSync(candidate.dir, { recursive: true, force: false })\n },\n )\n }\n return {\n trimmedRecordIds: trim.map(({ recordId }) => recordId),\n skipped,\n }\n}\n","/**\n * D-19 active-profile migration over the derived index.\n *\n * M2 keeps this library-only: Phase 378's drainer binds it to runtime\n * coordination, while Phase 382 owns any eventual CLI cutover surface. Rows\n * projected after the frozen snapshot take the benign lag direction: the flip\n * marks them pending so 375's unchanged backfill selector heals them.\n */\nimport type { DatabaseSync } from 'node:sqlite'\n\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\n\nimport {\n dropEmbedCacheForModel,\n ensureEmbedCacheTable,\n wrapEmbedderWithCache,\n} from './embed-cache.js'\nimport type { EmbedderPort } from './embedder-port.js'\nimport {\n SCHEMA_OWNED_EMBEDDING_PROFILES,\n embeddingProfileKey,\n resolveActiveProfile,\n vecTableName,\n} from './index-open.js'\nimport type { VecCapability } from './index-open.js'\n\nexport type MigrationOutcome =\n | { flipped: true; profileKey: string }\n | { flipped: false; missing: string[] }\n\nexport interface SetActiveEmbeddingProfileOptions {\n db: DatabaseSync\n vec: VecCapability\n target: {\n profile: EmbeddingProfile\n embedder: EmbedderPort\n }\n}\n\ninterface FrozenMember {\n recordRowid: number\n bundleId: string\n embeddingInput: string\n}\n\ninterface CurrentMember extends FrozenMember {\n product: string\n scopeTier: string\n scopeKey: string\n status: string\n}\n\ninterface MigrationSnapshot {\n outgoingProfile: EmbeddingProfile\n frozenMembers: FrozenMember[]\n}\n\ninterface StagedEmbedding {\n recordRowid: number\n embedding: Uint8Array\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction transaction<T>(\n db: DatabaseSync,\n begin: 'BEGIN' | 'BEGIN IMMEDIATE',\n operation: () => T,\n): T {\n db.exec(begin)\n try {\n const result = operation()\n db.exec('COMMIT')\n return result\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the migration error that caused the rollback.\n }\n throw error\n }\n}\n\nfunction knownProfile(profile: EmbeddingProfile): {\n key: string\n profile: EmbeddingProfile\n} {\n const key = embeddingProfileKey(profile)\n const known = SCHEMA_OWNED_EMBEDDING_PROFILES.find(\n (candidate) => embeddingProfileKey(candidate) === key,\n )\n\n if (known === undefined) {\n throw new TypeError(`embedding profile ${key} is not schema-owned`)\n }\n return { key, profile: known }\n}\n\nfunction snapshotMigration(db: DatabaseSync): MigrationSnapshot {\n return transaction(db, 'BEGIN', () => ({\n outgoingProfile: resolveActiveProfile(db),\n frozenMembers: db\n .prepare(`\n SELECT record_rowid, bundle_id, embedding_input\n FROM records\n ORDER BY record_rowid\n `)\n .all()\n .map((row) => ({\n recordRowid: Number(row.record_rowid),\n bundleId: String(row.bundle_id),\n embeddingInput: String(row.embedding_input),\n })),\n }))\n}\n\nfunction ensureMigrationTables(\n db: DatabaseSync,\n vec: VecCapability,\n targetProfile: EmbeddingProfile,\n): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS profile_embed_status (\n record_rowid INTEGER NOT NULL,\n profile_key TEXT NOT NULL,\n status TEXT NOT NULL,\n embedding BLOB,\n PRIMARY KEY (record_rowid, profile_key)\n ) WITHOUT ROWID;\n `)\n ensureEmbedCacheTable(db)\n\n if (vec === 'vec0') {\n const tableName = vecTableName(targetProfile)\n db.exec(`\n DROP TABLE IF EXISTS ${tableName};\n CREATE VIRTUAL TABLE ${tableName} USING vec0(\n record_rowid integer primary key,\n product text partition key,\n scope_tier text,\n scope_key text,\n status text,\n embedding float[${targetProfile.dim}] distance_metric=cosine\n );\n `)\n }\n}\n\nfunction isTargetEmbedding(\n value: unknown,\n targetProfile: EmbeddingProfile,\n): value is Uint8Array {\n return value instanceof Uint8Array\n && value.byteLength\n === targetProfile.dim * Float32Array.BYTES_PER_ELEMENT\n}\n\nfunction embeddingBytes(\n vector: Float32Array,\n targetProfile: EmbeddingProfile,\n): Buffer {\n if (vector.length !== targetProfile.dim) {\n throw new RangeError(\n `embedder returned ${vector.length} dimensions; expected ${targetProfile.dim}`,\n )\n }\n return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength)\n}\n\nfunction stagedEmbedding(\n db: DatabaseSync,\n recordRowid: number,\n profileKey: string,\n targetProfile: EmbeddingProfile,\n): Uint8Array | undefined {\n const row = db\n .prepare(`\n SELECT status, embedding\n FROM profile_embed_status\n WHERE record_rowid = ? AND profile_key = ?\n `)\n .get(recordRowid, profileKey)\n\n if (row?.status !== 'present') return undefined\n return isTargetEmbedding(row.embedding, targetProfile)\n ? Uint8Array.from(row.embedding)\n : undefined\n}\n\nfunction writeStagedStatus(\n db: DatabaseSync,\n member: FrozenMember,\n profileKey: string,\n status: 'present' | 'missing',\n embedding: Uint8Array | null,\n): void {\n transaction(db, 'BEGIN IMMEDIATE', () => {\n db.prepare(`\n INSERT INTO profile_embed_status (\n record_rowid, profile_key, status, embedding\n ) VALUES (?, ?, ?, ?)\n ON CONFLICT(record_rowid, profile_key) DO UPDATE SET\n status = excluded.status,\n embedding = excluded.embedding\n `).run(member.recordRowid, profileKey, status, embedding)\n })\n}\n\nasync function stageFrozenMembers(options: {\n db: DatabaseSync\n targetProfile: EmbeddingProfile\n targetEmbedder: EmbedderPort\n profileKey: string\n frozenMembers: readonly FrozenMember[]\n}): Promise<void> {\n const cachedEmbedder = wrapEmbedderWithCache({\n embedder: options.targetEmbedder,\n profile: options.targetProfile,\n db: options.db,\n mode: 'check-and-store',\n })\n\n for (const member of options.frozenMembers) {\n if (\n stagedEmbedding(\n options.db,\n member.recordRowid,\n options.profileKey,\n options.targetProfile,\n ) !== undefined\n ) {\n continue\n }\n\n let vector: Float32Array\n try {\n vector = await cachedEmbedder.embedDocument(member.embeddingInput)\n } catch {\n try {\n writeStagedStatus(\n options.db,\n member,\n options.profileKey,\n 'missing',\n null,\n )\n } catch (error) {\n throw new Error(\n `recording failed embedding for ${member.bundleId} failed: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n continue\n }\n\n try {\n writeStagedStatus(\n options.db,\n member,\n options.profileKey,\n 'present',\n embeddingBytes(vector, options.targetProfile),\n )\n } catch (error) {\n throw new Error(\n `staging embedding for ${member.bundleId} failed: ${errorMessage(error)}`,\n { cause: error },\n )\n }\n }\n}\n\nfunction currentMembers(db: DatabaseSync): CurrentMember[] {\n return db\n .prepare(`\n SELECT record_rowid, bundle_id, product, scope_tier, scope_key, status,\n embedding_input\n FROM records\n ORDER BY record_rowid\n `)\n .all()\n .map((row) => ({\n recordRowid: Number(row.record_rowid),\n bundleId: String(row.bundle_id),\n product: String(row.product),\n scopeTier: String(row.scope_tier),\n scopeKey: String(row.scope_key),\n status: String(row.status),\n embeddingInput: String(row.embedding_input),\n }))\n}\n\nfunction stagedPresentByRowid(\n db: DatabaseSync,\n profileKey: string,\n targetProfile: EmbeddingProfile,\n): Map<number, StagedEmbedding> {\n const staged = new Map<number, StagedEmbedding>()\n for (const row of db\n .prepare(`\n SELECT record_rowid, status, embedding\n FROM profile_embed_status\n WHERE profile_key = ?\n ORDER BY record_rowid\n `)\n .all(profileKey)) {\n if (row.status !== 'present' || !isTargetEmbedding(row.embedding, targetProfile)) {\n continue\n }\n const recordRowid = Number(row.record_rowid)\n staged.set(recordRowid, {\n recordRowid,\n embedding: Uint8Array.from(row.embedding),\n })\n }\n return staged\n}\n\n/**\n * SC5 completeness law: subtract staged-present member ids from the frozen\n * eligible ids and require the difference to be empty. Row counts are never a\n * proxy for identity; a post-snapshot row cannot stand in for a missing member.\n */\nfunction missingFrozenMembers(\n frozenMembers: readonly FrozenMember[],\n currentByRowid: ReadonlyMap<number, CurrentMember>,\n stagedByRowid: ReadonlyMap<number, StagedEmbedding>,\n): FrozenMember[] {\n const stagedPresentMemberIds = new Set(stagedByRowid.keys())\n return frozenMembers.filter((member) => {\n const current = currentByRowid.get(member.recordRowid)\n return current === undefined\n || current.bundleId !== member.bundleId\n || current.embeddingInput !== member.embeddingInput\n || !stagedPresentMemberIds.has(member.recordRowid)\n })\n}\n\nfunction flipProfile(options: {\n db: DatabaseSync\n vec: VecCapability\n outgoingProfile: EmbeddingProfile\n targetProfile: EmbeddingProfile\n targetKey: string\n frozenMembers: readonly FrozenMember[]\n}): MigrationOutcome {\n return transaction(options.db, 'BEGIN IMMEDIATE', () => {\n const currentProfile = resolveActiveProfile(options.db)\n const currentKey = embeddingProfileKey(currentProfile)\n if (currentKey === options.targetKey) {\n return { flipped: true, profileKey: options.targetKey }\n }\n\n const outgoingKey = embeddingProfileKey(options.outgoingProfile)\n if (currentKey !== outgoingKey) {\n throw new Error(\n `active embedding profile changed during migration: ${outgoingKey} -> ${currentKey}`,\n )\n }\n\n const current = currentMembers(options.db)\n const currentByRowid = new Map(\n current.map((member) => [member.recordRowid, member] as const),\n )\n const stagedByRowid = stagedPresentByRowid(\n options.db,\n options.targetKey,\n options.targetProfile,\n )\n const missing = missingFrozenMembers(\n options.frozenMembers,\n currentByRowid,\n stagedByRowid,\n )\n if (missing.length > 0) {\n return {\n flipped: false,\n missing: missing.map((member) => member.bundleId),\n }\n }\n\n const frozenRowids = new Set(\n options.frozenMembers.map((member) => member.recordRowid),\n )\n const updatePresent = options.db.prepare(`\n UPDATE records\n SET embedding = ?, embed_status = 'present'\n WHERE record_rowid = ? AND bundle_id = ?\n `)\n const updatePending = options.db.prepare(`\n UPDATE records\n SET embedding = NULL, embed_status = 'pending'\n WHERE record_rowid = ?\n `)\n\n for (const member of options.frozenMembers) {\n const staged = stagedByRowid.get(member.recordRowid)\n if (staged === undefined) {\n throw new Error(`complete migration lost staged member ${member.bundleId}`)\n }\n updatePresent.run(staged.embedding, member.recordRowid, member.bundleId)\n }\n for (const member of current) {\n if (!frozenRowids.has(member.recordRowid)) {\n updatePending.run(member.recordRowid)\n }\n }\n\n if (options.vec === 'vec0') {\n const tableName = vecTableName(options.targetProfile)\n options.db.exec(`DELETE FROM ${tableName}`)\n const insertTargetVec = options.db.prepare(`\n INSERT INTO ${tableName} (\n record_rowid, product, scope_tier, scope_key, status, embedding\n ) VALUES (?, ?, ?, ?, ?, ?)\n `)\n for (const member of options.frozenMembers) {\n const currentMember = currentByRowid.get(member.recordRowid)\n const staged = stagedByRowid.get(member.recordRowid)\n if (currentMember === undefined || staged === undefined) {\n throw new Error(`complete migration lost frozen member ${member.bundleId}`)\n }\n insertTargetVec.run(\n BigInt(member.recordRowid),\n currentMember.product,\n currentMember.scopeTier,\n currentMember.scopeKey,\n currentMember.status,\n staged.embedding,\n )\n }\n }\n\n options.db\n .prepare(`\n INSERT INTO meta (k, v) VALUES ('embedding_profile', ?)\n ON CONFLICT(k) DO UPDATE SET v = excluded.v\n `)\n .run(options.targetKey)\n dropEmbedCacheForModel(options.db, options.outgoingProfile.model_id)\n\n return { flipped: true, profileKey: options.targetKey }\n })\n}\n\n/**\n * Stage every frozen record for a schema-owned target profile, then atomically\n * flip only when the exact frozen member set is complete.\n */\nexport async function setActiveEmbeddingProfile(\n options: SetActiveEmbeddingProfileOptions,\n): Promise<MigrationOutcome> {\n const target = knownProfile(options.target.profile)\n const snapshot = snapshotMigration(options.db)\n if (embeddingProfileKey(snapshot.outgoingProfile) === target.key) {\n return { flipped: true, profileKey: target.key }\n }\n\n ensureMigrationTables(options.db, options.vec, target.profile)\n await stageFrozenMembers({\n db: options.db,\n targetProfile: target.profile,\n targetEmbedder: options.target.embedder,\n profileKey: target.key,\n frozenMembers: snapshot.frozenMembers,\n })\n\n return flipProfile({\n db: options.db,\n vec: options.vec,\n outgoingProfile: snapshot.outgoingProfile,\n targetProfile: target.profile,\n targetKey: target.key,\n frozenMembers: snapshot.frozenMembers,\n })\n}\n","/**\n * The embedder worker's half of the one process-identity vocabulary in this package.\n *\n * This is a separate module from `worker-registration.ts` on purpose. Registration reading and\n * socket probing are reachable from the read-only serving entry, and `reader-import-closure`\n * forbids that closure from crossing into `lease/`. The *signal decision* is a writer-side concern\n * that the reader never makes, so it lives here — which lets both kill paths in this package share\n * CR-04's single `resolveProcessIncarnation` definition instead of growing a second, subtly\n * different identity scheme.\n */\nimport { incarnationFormat, resolveProcessIncarnation } from '../lease/writer-lease.js'\n\nimport {\n EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION,\n type EmbedderWorkerIncarnationVerdict,\n type EmbedderWorkerRegistration,\n} from './worker-registration.js'\n\nexport { resolveProcessIncarnation }\n\n/**\n * The token a worker records about ITSELF at registration time.\n *\n * The worker is the only party that can attribute the registration without a race: it is the\n * process being described, and it is alive while describing itself. A worker that cannot resolve\n * its own start time records the sentinel rather than fabricating a value, accepting that it will\n * later be replaced without a signal instead of terminated.\n */\nexport function ownEmbedderWorkerIncarnation(): string {\n return resolveProcessIncarnation(process.pid) ?? EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION\n}\n\n/**\n * Compare the registration's recorded incarnation against the pid's CURRENT occupant.\n *\n * CR-05: a schema-valid registration naming a live pid whose socket has stopped answering is not\n * proof that the worker is still there. Once the worker died, the kernel is free to hand its pid to\n * a stranger, and every decision keyed on that number alone targets whoever holds it now. The one\n * fact that separates them is assigned by the OS and cannot be forged from inside the file: when\n * the process at that pid started.\n *\n * `mismatch` means the registered worker is provably gone; `unverifiable` means we cannot say, and\n * that is a refusal rather than a default-allow. Neither may be signalled — and neither needs to\n * be, because generation-specific sockets (Plan 24) let a fresh worker take a clean address without\n * the old pid ever being touched.\n */\nexport function verifyEmbedderWorkerIncarnation(\n registration: EmbedderWorkerRegistration,\n): EmbedderWorkerIncarnationVerdict {\n if (registration.incarnation === EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION) {\n return 'unverifiable'\n }\n const occupant = resolveProcessIncarnation(registration.pid)\n if (occupant === undefined) return 'unverifiable'\n if (incarnationFormat(occupant) !== incarnationFormat(registration.incarnation)) {\n return 'unverifiable'\n }\n return occupant === registration.incarnation ? 'match' : 'mismatch'\n}\n","import { z } from 'zod'\n\nimport {\n canonicalJson,\n cautionRootCauseClassSchema,\n distilledObservationSchema,\n sha256hex,\n} from '@vostride/agent-qa-schema'\nimport type {\n ArtifactRef,\n BundleKind,\n CautionRootCauseClass,\n ExecutionContext,\n FactSubtype,\n ScopeKey,\n} from '@vostride/agent-qa-schema'\n\nimport { anchorSchema } from '../anchor-schema.js'\n\nexport const CURATION_QUEUE_SCHEMA_VERSION = 2\n\nconst SHA256_HEX = /^[0-9a-f]{64}$/\n\nconst scopeSchema: z.ZodType<ScopeKey> = z\n .object({\n tier: z.enum(['global', 'product', 'suite', 'test']),\n key: z.string().min(1),\n })\n .strict()\n\nconst bundleKindSchema: z.ZodType<BundleKind> = z.enum([\n 'fact',\n 'procedure',\n 'caution',\n 'unknown',\n 'policy',\n])\nconst factSubtypeSchema: z.ZodType<FactSubtype> = z.enum([\n 'selector',\n 'behavioral',\n 'navigational',\n 'measurement',\n 'content',\n])\nconst executionContextSchema: z.ZodType<ExecutionContext> = z.enum([\n 'local-interactive',\n 'local-headless',\n 'ci',\n 'cloud',\n])\n\nexport const curationArtifactRoleSchema = z.enum([\n 'screenshot',\n 'dom-snapshot',\n 'ax-snapshot',\n 'opaque-evidence',\n])\n\nconst artifactRefSchema: z.ZodType<ArtifactRef> = z\n .object({\n id: z.string().min(1),\n sha: z.string().regex(SHA256_HEX),\n evidenceIncomplete: z.boolean().optional(),\n })\n .strict()\n\nexport const curationArtifactDescriptorSchema = z\n .object({\n ref: artifactRefSchema,\n stepIndex: z.number().int().nonnegative(),\n role: curationArtifactRoleSchema,\n originalName: z.string().min(1),\n })\n .strict()\n\nconst artifactInventoryEntryShape = {\n relativePath: z.string().regex(/^artifacts\\/[0-9a-f]{64}$/),\n sha256: z.string().regex(SHA256_HEX),\n bytes: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n} as const\n\nfunction validateArtifactInventoryEntry(\n entry: { relativePath: string; sha256: string },\n ctx: z.RefinementCtx,\n): void {\n if (entry.relativePath !== `artifacts/${entry.sha256}`) {\n ctx.addIssue({\n code: 'custom',\n path: ['relativePath'],\n message: 'artifact relativePath must match its SHA-256 digest',\n })\n }\n}\n\nconst artifactInventoryEntrySchema = z\n .object({\n ...artifactInventoryEntryShape,\n role: curationArtifactRoleSchema,\n originalName: z.string().min(1),\n })\n .strict()\n .superRefine(validateArtifactInventoryEntry)\n\nconst candidateSeedShape = {\n sourceRunId: z.string().min(1),\n scope: scopeSchema,\n buildOrdinal: z.number().int().nonnegative(),\n executionContext: executionContextSchema,\n kind: bundleKindSchema,\n subtype: factSubtypeSchema.optional(),\n /**\n * 379 D-16 additive-optional typed caution evidence. Existing queue-v2\n * bytes remain valid; when present this real evidence joins the address.\n */\n rootCauseClass: cautionRootCauseClassSchema.optional(),\n anchors: z.array(anchorSchema).min(1),\n summarySeed: z.string(),\n bodySeed: z.string(),\n distilledObservations: z.array(distilledObservationSchema),\n evidenceToken: z.string().min(1),\n attributingObservationId: z.string().min(1),\n} as const\n\nconst addressShape = {\n schemaVersion: z.literal(CURATION_QUEUE_SCHEMA_VERSION),\n ...candidateSeedShape,\n artifactInventory: z.array(artifactInventoryEntrySchema),\n /** Diagnostic only; wall-clock metadata is excluded from queue identity. */\n emittedAt: z.string(),\n} as const\n\nexport const curationCandidateProjectionSchema = z\n .object({\n ...candidateSeedShape,\n artifactDescriptors: z.array(curationArtifactDescriptorSchema),\n /** Diagnostic only; queue finalization excludes wall-clock metadata from identity. */\n emittedAt: z.string(),\n })\n .strict()\n .superRefine(validateProjectionSemantics)\n\nfunction validateKindSemantics(\n value: {\n kind: BundleKind\n subtype?: FactSubtype\n rootCauseClass?: CautionRootCauseClass\n },\n ctx: z.RefinementCtx,\n): void {\n if (value.kind === 'fact' && value.subtype === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'fact candidates require a fact subtype',\n })\n }\n if (value.kind !== 'fact' && value.subtype !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'only fact candidates may carry a fact subtype',\n })\n }\n if (value.rootCauseClass !== undefined && value.kind !== 'caution') {\n ctx.addIssue({\n code: 'custom',\n path: ['rootCauseClass'],\n message: 'only caution candidates may carry a root-cause class',\n })\n }\n}\n\nfunction validateProjectionSemantics(\n value: {\n kind: BundleKind\n subtype?: FactSubtype\n rootCauseClass?: CautionRootCauseClass\n artifactDescriptors: readonly { ref: ArtifactRef }[]\n },\n ctx: z.RefinementCtx,\n): void {\n validateKindSemantics(value, ctx)\n const refs = new Set<string>()\n for (const [index, descriptor] of value.artifactDescriptors.entries()) {\n if (refs.has(descriptor.ref.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['artifactDescriptors', index, 'ref', 'id'],\n message: 'artifact descriptor refs must be unique',\n })\n }\n refs.add(descriptor.ref.id)\n }\n}\n\nfunction validateAddressSemantics(\n value: {\n kind: BundleKind\n subtype?: FactSubtype\n rootCauseClass?: CautionRootCauseClass\n artifactInventory: readonly {\n relativePath: string\n sha256: string\n stepIndex: number\n role: z.infer<typeof curationArtifactRoleSchema>\n originalName: string\n }[]\n },\n ctx: z.RefinementCtx,\n): void {\n validateKindSemantics(value, ctx)\n const paths = new Set<string>()\n for (const [index, artifact] of value.artifactInventory.entries()) {\n if (paths.has(artifact.relativePath)) {\n ctx.addIssue({\n code: 'custom',\n path: ['artifactInventory', index, 'relativePath'],\n message: 'artifact inventory paths must be unique',\n })\n }\n paths.add(artifact.relativePath)\n }\n}\n\nconst curationCandidateAddressFieldsSchema = z\n .object(addressShape)\n .strict()\n .superRefine(validateAddressSemantics)\n\nexport const curationCandidatePayloadSchema = z\n .object({\n candidateId: z.string().regex(SHA256_HEX),\n ...addressShape,\n })\n .strict()\n .superRefine((payload, ctx) => {\n validateAddressSemantics(payload, ctx)\n const { candidateId, ...fields } = payload\n if (candidateId !== candidateContentAddress(fields)) {\n ctx.addIssue({\n code: 'custom',\n path: ['candidateId'],\n message: 'candidateId must equal the deterministic payload content address',\n })\n }\n })\n\nexport type CurationCandidateAddressFields = z.infer<\n typeof curationCandidateAddressFieldsSchema\n>\nexport type CurationCandidatePayload = z.infer<typeof curationCandidatePayloadSchema>\nexport type CurationCandidateArtifact = z.infer<typeof artifactInventoryEntrySchema>\nexport type CurationArtifactRole = z.infer<typeof curationArtifactRoleSchema>\nexport type CurationArtifactDescriptor = z.infer<\n typeof curationArtifactDescriptorSchema\n>\nexport type CurationCandidateProjection = z.infer<\n typeof curationCandidateProjectionSchema\n>\nexport type BuildCurationCandidateAddressFieldsInput = CurationCandidateAddressFields\n\n/** Constructs strict version-2 fields with descriptor metadata for every copied artifact. */\nexport function buildCurationCandidateAddressFields(\n input: BuildCurationCandidateAddressFieldsInput,\n): CurationCandidateAddressFields {\n return curationCandidateAddressFieldsSchema.parse(input)\n}\n\n/**\n * Hashes every payload field except derived candidateId and diagnostic emittedAt. Identity covers\n * schema/run/scope/ordinal/execution context, candidate kind/subtype, anchors and seeds, distilled\n * observations, evidence attribution, and the complete artifact inventory.\n */\nexport function candidateContentAddress(fields: CurationCandidateAddressFields): string {\n const parsed = curationCandidateAddressFieldsSchema.parse(fields)\n const { emittedAt: _diagnostic, ...deterministic } = parsed\n return sha256hex(canonicalJson(deterministic))\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n existsSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n} from 'node:fs'\nimport { basename, isAbsolute, join } from 'node:path'\n\nimport { canonicalJson, type MaskFn } from '@vostride/agent-qa-schema'\nimport { ZodError } from 'zod'\n\nimport { copyArtifacts } from '../artifact-copy.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport type {\n ArtifactCopyInput,\n CopiedArtifact,\n SkippedArtifact,\n} from '../artifact-copy.js'\nimport {\n bestEffortFsyncDirectory,\n durableWrite,\n publishStagedQueueEntry,\n removeEmptyDir,\n} from '../queue-transport.js'\nimport {\n withCurrentWriterAuthority,\n type CurrentWriterAuthority,\n} from '../lease/writer-lease.js'\nexport {\n bestEffortFsyncDirectory,\n durableWrite,\n publishStagedQueueEntry,\n removeEmptyDir,\n} from '../queue-transport.js'\nexport type { PublishStagedQueueEntryOutcome } from '../queue-transport.js'\nimport {\n claimedCandidateDir,\n claimedLeaseDir,\n claimedRoot,\n jobStatePath,\n jobsRoot,\n QUEUE_MAX_EMITS_PER_RUN,\n QUEUE_MAX_JOBS_PER_SCOPE,\n quarantinedCandidateDir,\n quarantinedRoot,\n queueRoot,\n queueStagingRoot,\n queuedCandidateDir,\n queuedRoot,\n} from './queue-layout.js'\nimport {\n readJobState,\n writeJobStateWithinCurrentAuthority,\n} from './job-state.js'\nimport {\n buildCurationCandidateAddressFields,\n candidateContentAddress,\n CURATION_QUEUE_SCHEMA_VERSION,\n curationCandidatePayloadSchema,\n curationCandidateProjectionSchema,\n type BuildCurationCandidateAddressFieldsInput,\n type CurationArtifactDescriptor,\n type CurationCandidatePayload,\n type CurationCandidateProjection,\n} from './queue-payload.js'\n\nexport interface CurationProjectionArtifactSource {\n /** Binds one raw projection descriptor by its ArtifactRef id. */\n artifactId: string\n /** Absolute source outside the queue's durable projection. */\n sourcePath: string\n}\n\nexport interface EnqueueCurationCandidateProjectionOptions {\n knowledgeRoot: string\n projection: CurationCandidateProjection\n artifactSources: readonly CurationProjectionArtifactSource[]\n mask?: MaskFn\n}\n\nexport type CurationEnqueueRefusalReason =\n | 'invalid-payload'\n | 'artifact-inventory-mismatch'\n | 'artifact-missing'\n | 'artifact-sha-mismatch'\n | 'artifact-byte-length-mismatch'\n | 'artifact-step-cap'\n | 'artifact-run-cap'\n\nexport type EnqueueCurationCandidateProjectionOutcome =\n | { kind: 'enqueued'; candidateId: string }\n | { kind: 'coalesced'; candidateId: string }\n | { kind: 'cap-exceeded'; candidateId: string }\n | { kind: 'refused'; reason: CurationEnqueueRefusalReason }\n\nexport type ReadCurationCandidatePayloadOutcome =\n | { kind: 'absent'; present: false }\n | { kind: 'parsed'; present: true; payload: CurationCandidatePayload }\n | { kind: 'malformed'; present: true }\n\nexport interface ClaimNextJobOptions {\n knowledgeRoot: string\n leaseId: string\n authority: CurrentWriterAuthority\n}\n\nexport interface ClaimedCurationJob {\n kind: 'claimed'\n candidateId: string\n leaseId: string\n payload: CurationCandidatePayload\n candidateDir: string\n payloadPath: string\n artifactsDir: string\n}\n\nexport interface MalformedClaimedCurationJob {\n kind: 'malformed'\n candidateId: string\n leaseId: string\n candidateDir: string\n payloadPath: string\n artifactsDir: string\n payloadPresent: true\n}\n\nexport type ClaimNextJobOutcome = ClaimedCurationJob | MalformedClaimedCurationJob\n\nexport interface RequeueClaimedOptions {\n knowledgeRoot: string\n leaseId: string\n authority: CurrentWriterAuthority\n}\n\nexport interface InspectDrainableCurationWorkOptions {\n readonly knowledgeRoot: string\n readonly currentLeaseId: string\n}\n\nexport interface DrainableCurationWork {\n readonly queuedCandidateIds: readonly string[]\n readonly recoverableClaimedCandidateIds: readonly string[]\n}\n\nexport interface CountRemainingCurationWorkOptions {\n /** Diagnostic identity only. The current claim remains included in the count. */\n readonly currentLeaseId?: string\n}\n\nexport interface CurationRemainingWork {\n readonly queued: number\n readonly claimedNonterminal: number\n readonly quarantined: number\n}\n\nexport const CURATION_QUARANTINE_SCHEMA_VERSION = 2\nexport const CURATION_QUARANTINE_FILE = 'quarantine.json'\n\nexport type CurationQuarantineReason =\n | 'malformed-payload'\n | 'malformed-job-state'\n | 'malformed-authored-checkpoint'\n\nexport interface QuarantineClaimedOptions {\n readonly knowledgeRoot: string\n readonly leaseId: string\n readonly candidateId: string\n readonly authority: CurrentWriterAuthority\n readonly reason: CurationQuarantineReason\n}\n\nfunction directoryNames(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))\n .map((entry) => entry.name)\n .sort()\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n}\n\nconst CANDIDATE_ID = /^[0-9a-f]{64}$/\nconst SAFE_LEASE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/** Return deterministic candidate-id order and ignore non-contract directory names. */\nexport function listQueuedCandidates(knowledgeRoot: string): string[] {\n return directoryNames(queuedRoot(knowledgeRoot)).filter((name) => CANDIDATE_ID.test(name))\n}\n\n/** Visibility-only count over the same durable pending layout consumed by claimNextJob. */\nexport function countPendingCurationJobs(knowledgeRoot: string): number {\n return listQueuedCandidates(knowledgeRoot).length\n}\n\n/**\n * Count every durable unit that prevents the queue from being complete.\n *\n * Unlike recovery visibility this includes the current writer's claim: a process can crash\n * after its last pending rename, so excluding that claim would produce a false zero.\n */\nexport function countRemainingCurationWork(\n knowledgeRoot: string,\n _options: CountRemainingCurationWorkOptions = {},\n): CurationRemainingWork {\n let claimedNonterminal = 0\n for (const leaseId of listClaimedLeases(knowledgeRoot)) {\n claimedNonterminal += directoryNames(claimedLeaseDir(knowledgeRoot, leaseId))\n .filter((candidateId) => CANDIDATE_ID.test(candidateId)).length\n }\n return {\n queued: listQueuedCandidates(knowledgeRoot).length,\n claimedNonterminal,\n quarantined: directoryNames(quarantinedRoot(knowledgeRoot))\n .filter((candidateId) => CANDIDATE_ID.test(candidateId)).length,\n }\n}\n\n/** Return deterministic active/recoverable lease directory order. */\nexport function listClaimedLeases(knowledgeRoot: string): string[] {\n return directoryNames(claimedRoot(knowledgeRoot)).filter((name) => SAFE_LEASE_ID.test(name))\n}\n\n/**\n * Observe work the current writer can reach through the canonical reconciliation path.\n *\n * This deliberately performs no recovery itself. The current lease is excluded by the same\n * identity rule as reconcileOnDrainStart; drainQueue remains the only owner of requeue mutation.\n */\nexport function inspectDrainableCurationWork(\n options: InspectDrainableCurationWorkOptions,\n): DrainableCurationWork {\n const recoverableClaimedCandidateIds = new Set<string>()\n for (const leaseId of listClaimedLeases(options.knowledgeRoot)) {\n if (leaseId === options.currentLeaseId) continue\n for (const candidateId of directoryNames(\n claimedLeaseDir(options.knowledgeRoot, leaseId),\n )) {\n if (CANDIDATE_ID.test(candidateId)) recoverableClaimedCandidateIds.add(candidateId)\n }\n }\n return {\n queuedCandidateIds: listQueuedCandidates(options.knowledgeRoot),\n recoverableClaimedCandidateIds: [...recoverableClaimedCandidateIds].sort(),\n }\n}\n\nexport function readCurationCandidatePayload(\n candidateDir: string,\n): ReadCurationCandidatePayloadOutcome {\n const file = join(candidateDir, 'payload.json')\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return existsSync(file) || existsSync(candidateDir)\n ? { kind: 'malformed', present: true }\n : { kind: 'absent', present: false }\n }\n\n try {\n const parsed = curationCandidatePayloadSchema.safeParse(JSON.parse(raw))\n return parsed.success && parsed.data.candidateId === basename(candidateDir)\n ? { kind: 'parsed', present: true, payload: parsed.data }\n : { kind: 'malformed', present: true }\n } catch {\n return { kind: 'malformed', present: true }\n }\n}\n\nfunction queuedPayloads(knowledgeRoot: string): CurationCandidatePayload[] {\n return listQueuedCandidates(knowledgeRoot).flatMap((candidateId) => {\n const outcome = readCurationCandidatePayload(\n queuedCandidateDir(knowledgeRoot, candidateId),\n )\n return outcome.kind === 'parsed' ? [outcome.payload] : []\n })\n}\n\nfunction initializeClaimedState(\n knowledgeRoot: string,\n candidateId: string,\n authority: CurrentWriterAuthority,\n): void {\n const state = readJobState(knowledgeRoot, candidateId)\n if (state.kind === 'absent') {\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot,\n candidateId,\n authority,\n lifecycle: 'queued',\n })\n }\n}\n\n/** Atomically claim the lexicographically first queued content address. */\nexport function claimNextJob(opts: ClaimNextJobOptions): ClaimNextJobOutcome | undefined {\n if (opts.leaseId !== opts.authority.leaseId) {\n throw new TypeError('claimNextJob leaseId must match writer authority')\n }\n assertWithinKnowledgeRoot(opts.knowledgeRoot, queuedRoot(opts.knowledgeRoot))\n assertWithinKnowledgeRoot(opts.knowledgeRoot, claimedLeaseDir(opts.knowledgeRoot, opts.leaseId))\n assertWithinKnowledgeRoot(opts.knowledgeRoot, jobsRoot(opts.knowledgeRoot))\n return withCurrentWriterAuthority(opts.knowledgeRoot, opts.authority, () => {\n for (const candidateId of listQueuedCandidates(opts.knowledgeRoot)) {\n const sourceDir = queuedCandidateDir(opts.knowledgeRoot, candidateId)\n const leaseDir = claimedLeaseDir(opts.knowledgeRoot, opts.leaseId)\n const candidateDir = claimedCandidateDir(\n opts.knowledgeRoot,\n opts.leaseId,\n candidateId,\n )\n mkdirSync(leaseDir, { recursive: true })\n try {\n renameSync(sourceDir, candidateDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n removeEmptyDir(leaseDir)\n continue\n }\n if ((code === 'EEXIST' || code === 'ENOTEMPTY') && existsSync(candidateDir)) {\n removeEmptyDir(leaseDir)\n continue\n }\n throw error\n }\n bestEffortFsyncDirectory(leaseDir)\n bestEffortFsyncDirectory(queuedRoot(opts.knowledgeRoot))\n initializeClaimedState(opts.knowledgeRoot, candidateId, opts.authority)\n\n const payloadPath = join(candidateDir, 'payload.json')\n const artifactsDir = join(candidateDir, 'artifacts')\n const payload = readCurationCandidatePayload(candidateDir)\n if (payload.kind !== 'parsed') {\n return {\n kind: 'malformed',\n candidateId,\n leaseId: opts.leaseId,\n candidateDir,\n payloadPath,\n artifactsDir,\n payloadPresent: true,\n }\n }\n return {\n kind: 'claimed',\n candidateId,\n leaseId: opts.leaseId,\n payload: payload.payload,\n candidateDir,\n payloadPath,\n artifactsDir,\n }\n }\n return undefined\n })\n}\n\ntype RequeueClaimedWithinCurrentAuthorityOptions = Omit<\n RequeueClaimedOptions,\n 'authority'\n> & { authority: CurrentWriterAuthority }\n\n/** @internal The caller must already hold withCurrentWriterAuthority for this root. */\nexport function requeueClaimedWithinCurrentAuthority(\n opts: RequeueClaimedWithinCurrentAuthorityOptions,\n): string[] {\n const leaseDir = claimedLeaseDir(opts.knowledgeRoot, opts.leaseId)\n assertWithinKnowledgeRoot(opts.knowledgeRoot, leaseDir)\n assertWithinKnowledgeRoot(opts.knowledgeRoot, queuedRoot(opts.knowledgeRoot))\n assertWithinKnowledgeRoot(opts.knowledgeRoot, jobsRoot(opts.knowledgeRoot))\n const candidateIds = directoryNames(leaseDir).filter((name) => CANDIDATE_ID.test(name))\n const requeued: string[] = []\n mkdirSync(queuedRoot(opts.knowledgeRoot), { recursive: true })\n for (const candidateId of candidateIds) {\n const sourceDir = claimedCandidateDir(opts.knowledgeRoot, opts.leaseId, candidateId)\n const targetDir = queuedCandidateDir(opts.knowledgeRoot, candidateId)\n if (existsSync(targetDir)) {\n rmSync(sourceDir, { recursive: true, force: true })\n } else {\n try {\n renameSync(sourceDir, targetDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if ((code === 'EEXIST' || code === 'ENOTEMPTY') && existsSync(targetDir)) {\n rmSync(sourceDir, { recursive: true, force: true })\n } else if (code === 'ENOENT') {\n continue\n } else {\n throw error\n }\n }\n }\n\n const state = readJobState(opts.knowledgeRoot, candidateId)\n if (state.kind === 'parsed') {\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot: opts.knowledgeRoot,\n candidateId,\n authority: opts.authority,\n lifecycle: 'queued',\n embedCrashCount: state.state.embedCrashCount,\n ...(state.state.authored === undefined ? {} : { authored: state.state.authored }),\n })\n } else if (state.kind === 'absent') {\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot: opts.knowledgeRoot,\n candidateId,\n authority: opts.authority,\n lifecycle: 'queued',\n })\n }\n requeued.push(candidateId)\n }\n removeEmptyDir(leaseDir)\n removeEmptyDir(claimedRoot(opts.knowledgeRoot))\n bestEffortFsyncDirectory(queuedRoot(opts.knowledgeRoot))\n return requeued\n}\n\n/** Reclaim one dead lease without discarding an already-authored deterministic checkpoint. */\nexport function requeueClaimed(opts: RequeueClaimedOptions): string[] {\n return withCurrentWriterAuthority(\n opts.knowledgeRoot,\n opts.authority,\n () => requeueClaimedWithinCurrentAuthority(opts),\n )\n}\n\n/**\n * Fenced terminal disposition for a claimed job whose durable inputs cannot be interpreted.\n * The claimed payload, optional lifecycle bytes, and reason document move as one directory.\n */\nexport function quarantineClaimed(opts: QuarantineClaimedOptions): string {\n if (opts.leaseId !== opts.authority.leaseId) {\n throw new TypeError('quarantineClaimed leaseId must match writer authority')\n }\n assertWithinKnowledgeRoot(opts.knowledgeRoot, claimedLeaseDir(opts.knowledgeRoot, opts.leaseId))\n assertWithinKnowledgeRoot(opts.knowledgeRoot, quarantinedRoot(opts.knowledgeRoot))\n assertWithinKnowledgeRoot(opts.knowledgeRoot, jobsRoot(opts.knowledgeRoot))\n return withCurrentWriterAuthority(opts.knowledgeRoot, opts.authority, () => {\n const sourceDir = claimedCandidateDir(\n opts.knowledgeRoot,\n opts.leaseId,\n opts.candidateId,\n )\n const targetRoot = quarantinedRoot(opts.knowledgeRoot)\n const targetDir = quarantinedCandidateDir(opts.knowledgeRoot, opts.candidateId)\n if (!existsSync(sourceDir)) {\n if (existsSync(targetDir)) return targetDir\n throw new Error(`claimed candidate ${opts.candidateId} is absent`)\n }\n\n const reasonPath = join(sourceDir, CURATION_QUARANTINE_FILE)\n if (!existsSync(reasonPath)) {\n durableWrite(\n reasonPath,\n `${canonicalJson({\n schemaVersion: CURATION_QUARANTINE_SCHEMA_VERSION,\n candidateId: opts.candidateId,\n leaseId: opts.leaseId,\n reason: opts.reason,\n quarantinedAt: new Date().toISOString(),\n })}\\n`,\n )\n }\n\n const statePath = jobStatePath(opts.knowledgeRoot, opts.candidateId)\n if (existsSync(statePath)) {\n const firstArchive = join(sourceDir, 'job-state.json')\n renameSync(\n statePath,\n existsSync(firstArchive)\n ? join(sourceDir, `job-state-${randomUUID()}.json`)\n : firstArchive,\n )\n bestEffortFsyncDirectory(jobsRoot(opts.knowledgeRoot))\n }\n bestEffortFsyncDirectory(sourceDir)\n mkdirSync(targetRoot, { recursive: true })\n try {\n renameSync(sourceDir, targetDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if ((code === 'EEXIST' || code === 'ENOTEMPTY') && existsSync(targetDir)) {\n rmSync(sourceDir, { recursive: true, force: true })\n } else {\n throw error\n }\n }\n const leaseDir = claimedLeaseDir(opts.knowledgeRoot, opts.leaseId)\n bestEffortFsyncDirectory(leaseDir)\n bestEffortFsyncDirectory(targetRoot)\n removeEmptyDir(leaseDir)\n bestEffortFsyncDirectory(claimedRoot(opts.knowledgeRoot))\n removeEmptyDir(claimedRoot(opts.knowledgeRoot))\n bestEffortFsyncDirectory(queueRoot(opts.knowledgeRoot))\n return targetDir\n })\n}\n\nfunction queueCapExceeded(\n knowledgeRoot: string,\n payload: CurationCandidatePayload,\n): boolean {\n let scopeCount = 0\n let sourceRunCount = 0\n const scopeKey = canonicalJson(payload.scope)\n for (const queued of queuedPayloads(knowledgeRoot)) {\n if (canonicalJson(queued.scope) === scopeKey) scopeCount += 1\n if (queued.sourceRunId === payload.sourceRunId) sourceRunCount += 1\n }\n return (\n scopeCount >= QUEUE_MAX_JOBS_PER_SCOPE || sourceRunCount >= QUEUE_MAX_EMITS_PER_RUN\n )\n}\n\nfunction skippedArtifactReason(reason: SkippedArtifact['reason']): CurationEnqueueRefusalReason {\n switch (reason) {\n case 'step-cap':\n return 'artifact-step-cap'\n case 'run-cap':\n return 'artifact-run-cap'\n case 'pruned-source':\n return 'artifact-missing'\n case 'sha-mismatch':\n return 'artifact-sha-mismatch'\n }\n}\n\ntype ProjectionArtifactInputsOutcome =\n | { kind: 'ready'; inputs: ArtifactCopyInput[] }\n | { kind: 'refused'; reason: CurationEnqueueRefusalReason }\n\nfunction projectionArtifactInputs(\n projection: CurationCandidateProjection,\n artifactSources: readonly CurationProjectionArtifactSource[],\n): ProjectionArtifactInputsOutcome {\n const sourceByArtifactId = new Map<string, string>()\n for (const source of artifactSources) {\n if (\n source.artifactId === ''\n || !isAbsolute(source.sourcePath)\n || sourceByArtifactId.has(source.artifactId)\n ) {\n return { kind: 'refused', reason: 'artifact-inventory-mismatch' }\n }\n sourceByArtifactId.set(source.artifactId, source.sourcePath)\n }\n if (\n sourceByArtifactId.size !== projection.artifactDescriptors.length\n || projection.artifactDescriptors.some(\n (descriptor) => !sourceByArtifactId.has(descriptor.ref.id),\n )\n ) {\n return { kind: 'refused', reason: 'artifact-inventory-mismatch' }\n }\n\n return {\n kind: 'ready',\n inputs: projection.artifactDescriptors.map((descriptor) => ({\n ref: descriptor.ref,\n sourcePath: sourceByArtifactId.get(descriptor.ref.id)!,\n stepIndex: descriptor.stepIndex,\n role: descriptor.role,\n originalName: descriptor.originalName,\n })),\n }\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction descriptorById(\n descriptors: readonly CurationArtifactDescriptor[],\n): Map<string, CurationArtifactDescriptor> {\n return new Map(descriptors.map((descriptor) => [descriptor.ref.id, descriptor]))\n}\n\nfunction artifactInventoryFromSafeCopies(\n copied: readonly CopiedArtifact[],\n descriptors: ReadonlyMap<string, CurationArtifactDescriptor>,\n): BuildCurationCandidateAddressFieldsInput['artifactInventory'] | undefined {\n const inventory: BuildCurationCandidateAddressFieldsInput['artifactInventory'] = []\n for (const artifact of copied) {\n const descriptor = descriptors.get(artifact.ref.id)\n if (descriptor === undefined) return undefined\n inventory.push({\n relativePath: artifact.relPath,\n sha256: artifact.ref.sha,\n bytes: artifact.bytes,\n stepIndex: artifact.stepIndex,\n role: descriptor.role,\n originalName: descriptor.originalName,\n })\n }\n return inventory.sort((left, right) =>\n compareText(left.relativePath, right.relativePath)\n || left.stepIndex - right.stepIndex\n || compareText(left.role, right.role)\n || compareText(left.originalName, right.originalName),\n )\n}\n\nfunction fsyncCopiedArtifacts(stagingDir: string, copied: readonly CopiedArtifact[]): void {\n for (const artifact of copied) {\n const fd = openSync(join(stagingDir, artifact.relPath), 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n }\n}\n\ntype FinalizeProjectionOutcome =\n | { kind: 'ready'; payload: CurationCandidatePayload }\n | { kind: 'refused'; reason: CurationEnqueueRefusalReason }\n\nfunction finalizeProjection(\n stagingDir: string,\n projection: CurationCandidateProjection,\n sourceInputs: readonly ArtifactCopyInput[],\n mask: MaskFn | undefined,\n): FinalizeProjectionOutcome {\n const copied = copyArtifacts(\n sourceInputs,\n join(stagingDir, 'artifacts'),\n mask === undefined ? {} : { mask },\n )\n const [failedCopy] = copied.skipped\n if (failedCopy !== undefined) {\n return { kind: 'refused', reason: skippedArtifactReason(failedCopy.reason) }\n }\n fsyncCopiedArtifacts(stagingDir, copied.copied)\n\n const descriptors = descriptorById(projection.artifactDescriptors)\n const artifactInventory = artifactInventoryFromSafeCopies(copied.copied, descriptors)\n if (artifactInventory === undefined) {\n return { kind: 'refused', reason: 'artifact-inventory-mismatch' }\n }\n\n try {\n const fields = buildCurationCandidateAddressFields({\n schemaVersion: CURATION_QUEUE_SCHEMA_VERSION,\n sourceRunId: projection.sourceRunId,\n scope: projection.scope,\n buildOrdinal: projection.buildOrdinal,\n executionContext: projection.executionContext,\n kind: projection.kind,\n ...(projection.subtype === undefined ? {} : { subtype: projection.subtype }),\n ...(projection.rootCauseClass === undefined\n ? {}\n : { rootCauseClass: projection.rootCauseClass }),\n anchors: projection.anchors,\n summarySeed: projection.summarySeed,\n bodySeed: projection.bodySeed,\n distilledObservations: projection.distilledObservations,\n evidenceToken: projection.evidenceToken,\n attributingObservationId: projection.attributingObservationId,\n artifactInventory,\n emittedAt: projection.emittedAt,\n })\n const candidateId = candidateContentAddress(fields)\n return {\n kind: 'ready',\n payload: curationCandidatePayloadSchema.parse({ candidateId, ...fields }),\n }\n } catch (error) {\n if (error instanceof ZodError) {\n return { kind: 'refused', reason: 'artifact-inventory-mismatch' }\n }\n throw error\n }\n}\n\n/**\n * Copies the projection's artifacts through the declared mask before the candidate content\n * address or any queue-visible directory exists.\n */\nexport function enqueueCurationCandidateProjection(\n opts: EnqueueCurationCandidateProjectionOptions,\n): EnqueueCurationCandidateProjectionOutcome {\n const parsed = curationCandidateProjectionSchema.safeParse(opts.projection)\n if (!parsed.success) return { kind: 'refused', reason: 'invalid-payload' }\n const projection = parsed.data\n const sourceInputs = projectionArtifactInputs(projection, opts.artifactSources)\n if (sourceInputs.kind === 'refused') return sourceInputs\n\n const stagingRoot = queueStagingRoot(opts.knowledgeRoot)\n assertWithinKnowledgeRoot(opts.knowledgeRoot, stagingRoot)\n assertWithinKnowledgeRoot(opts.knowledgeRoot, queuedRoot(opts.knowledgeRoot))\n const stagingDir = join(stagingRoot, randomUUID())\n mkdirSync(stagingDir, { recursive: true })\n try {\n const finalized = finalizeProjection(stagingDir, projection, sourceInputs.inputs, opts.mask)\n if (finalized.kind === 'refused') return finalized\n const { payload } = finalized\n const candidateId = payload.candidateId\n const finalDir = queuedCandidateDir(opts.knowledgeRoot, candidateId)\n if (existsSync(finalDir)) return { kind: 'coalesced', candidateId }\n if (queueCapExceeded(opts.knowledgeRoot, payload)) {\n return { kind: 'cap-exceeded', candidateId }\n }\n\n durableWrite(join(stagingDir, 'payload.json'), `${canonicalJson(payload)}\\n`)\n bestEffortFsyncDirectory(join(stagingDir, 'artifacts'))\n bestEffortFsyncDirectory(stagingDir)\n const published = publishStagedQueueEntry(\n stagingDir,\n finalDir,\n queuedRoot(opts.knowledgeRoot),\n )\n if (published === 'coalesced') return { kind: 'coalesced', candidateId }\n return { kind: 'enqueued', candidateId }\n } finally {\n rmSync(stagingDir, { recursive: true, force: true })\n removeEmptyDir(stagingRoot)\n }\n}\n\nexport const enqueueCurationCandidate = enqueueCurationCandidateProjection\n","import { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n existsSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nimport { canonicalJson } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport {\n withCurrentWriterAuthority,\n type CurrentWriterAuthority,\n} from '../lease/writer-lease.js'\nimport {\n claimedCandidateDir,\n claimedLeaseDir,\n jobStatePath,\n jobsRoot,\n} from './queue-layout.js'\n\nexport const CURATION_JOB_STATE_SCHEMA_VERSION = 2\n\nexport type CurationJobLifecycle =\n | 'queued'\n | 'authored'\n | 'bundling'\n | 'committing'\n | 'done'\n\nconst jobLifecycleSchema: z.ZodType<CurationJobLifecycle> = z.enum([\n 'queued',\n 'authored',\n 'bundling',\n 'committing',\n 'done',\n])\n\nexport const curationJobStateSchema = z\n .object({\n schemaVersion: z.literal(CURATION_JOB_STATE_SCHEMA_VERSION),\n candidateId: z.string().regex(/^[0-9a-f]{64}$/),\n lifecycle: jobLifecycleSchema,\n embedCrashCount: z.number().int().nonnegative().default(0),\n /**\n * Opaque transport slot. Plan 378-06's authoredCheckpointSchema owns semantic validation.\n */\n authored: z.unknown().optional(),\n /** Diagnostic wall-clock metadata only; never identity, ordering, or disposition input. */\n updatedAt: z.string(),\n })\n .strict()\n\nexport type CurationJobState = z.infer<typeof curationJobStateSchema>\n\nexport interface WriteJobStateOptions {\n knowledgeRoot: string\n candidateId: string\n lifecycle: CurationJobLifecycle\n authority: CurrentWriterAuthority\n embedCrashCount?: number\n authored?: unknown\n}\n\nexport type ReadJobStateOutcome =\n | { kind: 'absent'; present: false }\n | { kind: 'parsed'; present: true; state: CurationJobState }\n | { kind: 'malformed'; present: true }\n\nexport interface PersistAuthoredCheckpointOptions {\n knowledgeRoot: string\n candidateId: string\n authority: CurrentWriterAuthority\n authored: unknown\n}\n\nexport type PersistAuthoredCheckpointOutcome =\n | { kind: 'persisted'; state: CurationJobState }\n | { kind: 'malformed-state'; present: true }\n\nfunction bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n code !== 'ENOENT' &&\n code !== 'EINVAL' &&\n code !== 'EISDIR' &&\n code !== 'EPERM' &&\n code !== 'ENOTSUP'\n ) {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\nfunction removeEmptyDir(dir: string): void {\n try {\n rmdirSync(dir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n}\n\nfunction atomicRewrite(file: string, state: CurationJobState): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, `${canonicalJson(state)}\\n`)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n bestEffortFsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\nfunction removeClaimedCandidate(\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n candidateId: string,\n): void {\n const leaseDir = claimedLeaseDir(knowledgeRoot, authority.leaseId)\n rmSync(\n claimedCandidateDir(knowledgeRoot, authority.leaseId, candidateId),\n { recursive: true, force: true },\n )\n removeEmptyDir(leaseDir)\n}\n\n/** Read a strict lifecycle checkpoint; corrupt bytes remain a typed present signal. */\nexport function readJobState(\n knowledgeRoot: string,\n candidateId: string,\n): ReadJobStateOutcome {\n const file = jobStatePath(knowledgeRoot, candidateId)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return existsSync(file)\n ? { kind: 'malformed', present: true }\n : { kind: 'absent', present: false }\n }\n\n try {\n const parsed = curationJobStateSchema.safeParse(JSON.parse(raw))\n return parsed.success\n ? { kind: 'parsed', present: true, state: parsed.data }\n : { kind: 'malformed', present: true }\n } catch {\n return { kind: 'malformed', present: true }\n }\n}\n\n/**\n * Atomically replaces one lifecycle file. Writing done removes both the state file and any\n * claimed candidate directory. State-file absence for an absent candidate therefore means\n * done/never-existed; Plan 378-05's journal reconciliation distinguishes those cases.\n */\ntype WriteJobStateWithinCurrentAuthorityOptions = Omit<\n WriteJobStateOptions,\n 'authority'\n> & { authority: CurrentWriterAuthority }\n\n/** @internal The caller must already hold withCurrentWriterAuthority for this root. */\nexport function writeJobStateWithinCurrentAuthority(\n opts: WriteJobStateWithinCurrentAuthorityOptions,\n): CurationJobState {\n const state = curationJobStateSchema.parse({\n schemaVersion: CURATION_JOB_STATE_SCHEMA_VERSION,\n candidateId: opts.candidateId,\n lifecycle: opts.lifecycle,\n embedCrashCount: opts.embedCrashCount ?? 0,\n ...(opts.authored === undefined ? {} : { authored: opts.authored }),\n updatedAt: new Date().toISOString(),\n })\n const file = jobStatePath(opts.knowledgeRoot, opts.candidateId)\n assertWithinKnowledgeRoot(opts.knowledgeRoot, jobsRoot(opts.knowledgeRoot))\n if (state.lifecycle === 'done') {\n assertWithinKnowledgeRoot(opts.knowledgeRoot, claimedLeaseDir(opts.knowledgeRoot, opts.authority.leaseId))\n rmSync(file, { force: true })\n bestEffortFsyncDirectory(jobsRoot(opts.knowledgeRoot))\n removeClaimedCandidate(opts.knowledgeRoot, opts.authority, opts.candidateId)\n return state\n }\n\n atomicRewrite(file, state)\n return state\n}\n\nexport function writeJobState(opts: WriteJobStateOptions): CurationJobState {\n return withCurrentWriterAuthority(\n opts.knowledgeRoot,\n opts.authority,\n () => writeJobStateWithinCurrentAuthority(opts),\n )\n}\n\n/** Persist the validated-later authored value before any deterministic bundle mutation begins. */\nexport function persistAuthoredCheckpoint(\n opts: PersistAuthoredCheckpointOptions,\n): PersistAuthoredCheckpointOutcome {\n const current = readJobState(opts.knowledgeRoot, opts.candidateId)\n if (current.kind === 'malformed') return { kind: 'malformed-state', present: true }\n const state = writeJobState({\n knowledgeRoot: opts.knowledgeRoot,\n candidateId: opts.candidateId,\n authority: opts.authority,\n lifecycle: 'authored',\n embedCrashCount: current.kind === 'parsed' ? current.state.embedCrashCount : 0,\n authored: opts.authored,\n })\n return { kind: 'persisted', state }\n}\n","/**\n * Per-candidate write-ahead intents for the deterministic commit tail.\n *\n * Plan 378-10 must write and fsync an intent before a bundle publish rename can happen, then\n * clear it only after the index delta apply confirms. One file per candidate makes both\n * replacement and removal atomic without log compaction.\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join } from 'node:path'\n\nimport { canonicalJson } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\nimport { curationObservationSchema } from './curation-effect-receipt.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\n\nexport const JOURNAL_SUBDIR = 'memory/queue/journal'\nexport const COMMIT_INTENT_SCHEMA_VERSION = 2\n\n/**\n * Highest writer epoch whose reconciliation has completed, relative to knowledgeRoot. Pinned\n * state, not configuration: reconciliation writes it inside the authority section it already\n * holds, so the watermark can never lag a completed pass.\n */\nexport const RECONCILED_EPOCH_FILE = `${JOURNAL_SUBDIR}/.reconciled-epoch`\n\nconst CANDIDATE_ID = /^[0-9a-f]{64}$/\nconst INTENT_FILE = /^([0-9a-f]{64})\\.intent\\.json$/\n\nexport const commitIntentSchema = z\n .object({\n schemaVersion: z.literal(COMMIT_INTENT_SCHEMA_VERSION),\n candidateId: z.string().regex(CANDIDATE_ID),\n bundleId: z.string().min(1),\n deltaKind: z.enum(['Add', 'Confirm', 'Supersede', 'Deprecate', 'MintUnknown', 'Noop']),\n targetRecordId: z.string().min(1).optional(),\n epoch: z.number().int().positive(),\n observation: curationObservationSchema.optional(),\n })\n .strict()\n\nexport type CommitIntent = z.infer<typeof commitIntentSchema>\n\nexport type ListedCommitIntent =\n | { parsed: CommitIntent }\n | { malformed: true; candidateId: string }\n\nfunction journalRoot(knowledgeRoot: string): string {\n if (!isAbsolute(knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n return join(knowledgeRoot, JOURNAL_SUBDIR)\n}\n\nfunction intentPath(knowledgeRoot: string, candidateId: string): string {\n const parsedCandidateId = z.string().regex(CANDIDATE_ID).parse(candidateId)\n return join(journalRoot(knowledgeRoot), `${parsedCandidateId}.intent.json`)\n}\n\nfunction bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n code !== 'ENOENT' &&\n code !== 'EINVAL' &&\n code !== 'EISDIR' &&\n code !== 'EPERM' &&\n code !== 'ENOTSUP'\n ) {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\nfunction atomicRewrite(file: string, text: string): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n bestEffortFsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\n/** Durably replace one candidate's intent before any reader-visible bundle mutation. */\nexport function writeCommitIntent(knowledgeRoot: string, intent: CommitIntent): void {\n const parsed = commitIntentSchema.parse(intent)\n assertWithinKnowledgeRoot(knowledgeRoot, journalRoot(knowledgeRoot))\n atomicRewrite(\n intentPath(knowledgeRoot, parsed.candidateId),\n `${canonicalJson(parsed)}\\n`,\n )\n}\n\n/**\n * Highest epoch whose reconciliation completed. Tolerant by construction: an absent or\n * unreadable watermark is zero, which admits every intent and preserves crash recovery on a\n * root that has never been reconciled.\n */\nexport function readReconciledEpoch(knowledgeRoot: string): number {\n let raw: string\n try {\n raw = readFileSync(join(knowledgeRoot, RECONCILED_EPOCH_FILE), 'utf8')\n } catch {\n return 0\n }\n const parsed = z.number().int().nonnegative().safeParse(Number(raw.trim()))\n return parsed.success ? parsed.data : 0\n}\n\n/** @internal The caller must already hold withCurrentWriterAuthority for this root. */\nexport function writeReconciledEpochWithinCurrentAuthority(\n knowledgeRoot: string,\n epoch: number,\n): void {\n const validated = z.number().int().positive().parse(epoch)\n assertWithinKnowledgeRoot(knowledgeRoot, journalRoot(knowledgeRoot))\n atomicRewrite(join(knowledgeRoot, RECONCILED_EPOCH_FILE), `${validated}\\n`)\n}\n\nexport type QuarantineStaleCommitIntentOutcome =\n /** The bytes were preserved under `name`, which `listCommitIntents` never returns. */\n | { kind: 'quarantined'; name: string }\n /** The source intent no longer exists: nothing to preserve, nothing to count. */\n | { kind: 'already-gone' }\n\n/**\n * Preserve a superseded generation's intent bytes under a name `listCommitIntents` never\n * returns. Discarding them silently would erase the only record that a fenced-out writer\n * reached the journal at all (T-386-28-03).\n *\n * The name carries a per-invocation discriminator because `(epoch, candidateId)` is not unique\n * over time: one candidate can be authored more than once at the same stale epoch, and a\n * `renameSync` onto an existing quarantine file would destroy the earlier evidence silently.\n *\n * ENOENT on the source is the one benign classification: the file is already gone, so no\n * evidence can be lost and the caller's pass — which runs inside a held authority section —\n * has nothing left to do for it. Every other errno means bytes exist and we failed to preserve\n * them, and still propagates (386-28's contract that real failures surface).\n */\nexport function quarantineStaleCommitIntent(\n knowledgeRoot: string,\n candidateId: string,\n epoch: number,\n): QuarantineStaleCommitIntentOutcome {\n const file = intentPath(knowledgeRoot, candidateId)\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(file))\n const quarantined = `.stale-${epoch}-${candidateId}-${randomUUID()}.intent.json`\n try {\n renameSync(file, join(dirname(file), quarantined))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n return { kind: 'already-gone' }\n }\n bestEffortFsyncDirectory(dirname(file))\n return { kind: 'quarantined', name: quarantined }\n}\n\n/** Clear one confirmed intent after its index projection has been applied. */\nexport function clearCommitIntent(knowledgeRoot: string, candidateId: string): void {\n const file = intentPath(knowledgeRoot, candidateId)\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(file))\n rmSync(file, { force: true })\n bestEffortFsyncDirectory(dirname(file))\n}\n\n/** List strict intents in candidate-id order while retaining torn bytes as recovery signals. */\nexport function listCommitIntents(knowledgeRoot: string): ListedCommitIntent[] {\n let names: string[]\n try {\n names = readdirSync(journalRoot(knowledgeRoot), { withFileTypes: true })\n .filter((entry) => entry.isFile() && INTENT_FILE.test(entry.name))\n .map((entry) => entry.name)\n .sort()\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n\n return names.map((name) => {\n const candidateId = INTENT_FILE.exec(name)![1]!\n try {\n const parsed = commitIntentSchema.safeParse(\n JSON.parse(readFileSync(join(journalRoot(knowledgeRoot), name), 'utf8')),\n )\n return parsed.success && parsed.data.candidateId === candidateId\n ? { parsed: parsed.data }\n : { malformed: true, candidateId }\n } catch {\n return { malformed: true, candidateId }\n }\n })\n}\n","import {\n DELTA_ORIGINS,\n asEvidenceToken,\n asRecordId,\n type Anchor,\n type ArtifactRef,\n type BundleDraft,\n type BundleKind,\n type CompareAndSet,\n type CurationAuthorship,\n type CurationFallbackReason,\n type Delta,\n type DeltaOrigin,\n type ExecutionContext,\n type FactSubtype,\n type RecordId,\n type ScopeKey,\n} from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport type { CurationCandidatePayload } from '../queue/queue-payload.js'\n\nexport const AUTHORED_CHECKPOINT_SCHEMA_VERSION = 2\n\n/** The deterministic author-facing projection of one durable queue payload. */\nexport type CurationJobView = Pick<\n CurationCandidatePayload,\n | 'candidateId'\n | 'kind'\n | 'subtype'\n | 'rootCauseClass'\n | 'anchors'\n | 'summarySeed'\n | 'bodySeed'\n | 'distilledObservations'\n | 'scope'\n | 'buildOrdinal'\n | 'attributingObservationId'\n | 'executionContext'\n>\n\n/** One retrieval hit as shown to the author through a small integer alias. */\ninterface NeighborRecordBase {\n alias: number\n recordId: RecordId\n summary: string\n anchors: Anchor[]\n observedStatus: string\n observedOrdinal: number\n}\n\ntype NonFactNeighborRecord = {\n [Kind in Exclude<BundleKind, 'fact'>]: { kind: Kind; subtype?: never }\n}[Exclude<BundleKind, 'fact'>]\n\nexport type NeighborRecord = NeighborRecordBase &\n ({ kind: 'fact'; subtype: FactSubtype } | NonFactNeighborRecord)\n\n/**\n * One authored outcome may carry multiple deltas (D-02): a procedure-extraction job can yield\n * whole-flow AND sub-flow candidates from one trajectory. Fact/caution authoring produces a\n * one-element array. The array is never empty.\n */\nexport type AuthorOutcome =\n | { kind: 'authored'; deltas: Delta[]; authorship: CurationAuthorship }\n | {\n kind: 'fallback-required'\n reason: CurationFallbackReason\n }\n\n/** Provider-neutral author seam injected by the CLI composition root. */\nexport type CuratorAuthor = (\n job: CurationJobView,\n neighbors: NeighborRecord[],\n) => Promise<AuthorOutcome>\n\n/**\n * Caller-owned disposition authority. Phase 379 may extend this profile with its deterministic\n * born-active drift-supersede carve-out without changing the author or checkpoint contracts.\n */\nexport interface DispositionProfile {\n mode: 'drain-to-active' | 'propose-only'\n}\n\n/**\n * Resolve automatic curation authority from the run's already-captured execution context.\n * Local work applies directly (432 D-08); CI and cloud stay proposed for the rolling-PR flow.\n */\nexport function resolveDispositionProfile(\n executionContext: ExecutionContext,\n): DispositionProfile {\n switch (executionContext) {\n case 'local-interactive':\n case 'local-headless':\n return { mode: 'drain-to-active' }\n case 'ci':\n case 'cloud':\n return { mode: 'propose-only' }\n default: {\n const exhaustive: never = executionContext\n return exhaustive\n }\n }\n}\n\nconst recordIdSchema = z.string().min(1).transform(asRecordId)\nconst evidenceTokenSchema = z.string().min(1).transform(asEvidenceToken)\n\nconst scopeSchema: z.ZodType<ScopeKey> = z\n .object({\n tier: z.enum(['global', 'product', 'suite', 'test']),\n key: z.string().min(1),\n })\n .strict()\n\nconst anchorSchema: z.ZodType<Anchor> = z.discriminatedUnion('t', [\n z.object({ t: z.literal('page'), route: z.string() }).strict(),\n z.object({ t: z.literal('flow'), name: z.string() }).strict(),\n z\n .object({\n t: z.literal('el'),\n role: z.string(),\n name: z.string(),\n ordinal: z.number().int().optional(),\n })\n .strict(),\n z\n .object({\n t: z.literal('platform'),\n platform: z.enum(['web', 'android', 'ios']),\n })\n .strict(),\n z.object({ t: z.literal('selector'), literal: z.string() }).strict(),\n z.object({ t: z.literal('error'), message: z.string() }).strict(),\n])\n\nconst artifactRefSchema: z.ZodType<ArtifactRef> = z\n .object({\n id: z.string().min(1),\n sha: z.string().regex(/^[0-9a-f]{64}$/),\n evidenceIncomplete: z.boolean().optional(),\n })\n .strict()\n\nconst bundleKindSchema: z.ZodType<BundleKind> = z.enum([\n 'fact',\n 'procedure',\n 'caution',\n 'unknown',\n 'policy',\n])\nconst factSubtypeSchema: z.ZodType<FactSubtype> = z.enum([\n 'selector',\n 'behavioral',\n 'navigational',\n 'measurement',\n 'content',\n])\n\ntype CheckpointBundleDraft = BundleDraft & { needsEnrichment?: true }\n\nconst bundleDraftSchema: z.ZodType<CheckpointBundleDraft> = z\n .object({\n kind: bundleKindSchema,\n subtype: factSubtypeSchema.optional(),\n anchors: z.array(anchorSchema).min(1),\n scope: scopeSchema,\n summary: z.string(),\n body: z.string(),\n distilledEvidenceRef: artifactRefSchema,\n originStage: z.literal('run-curation'),\n /** Transient CUR-02 signal consumed when commit renders run-linked provenance. */\n needsEnrichment: z.literal(true).optional(),\n })\n .strict()\n .superRefine((bundle, ctx) => {\n if (bundle.kind === 'fact' && bundle.subtype === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'fact bundle drafts require a fact subtype',\n })\n }\n if (bundle.kind !== 'fact' && bundle.subtype !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'only fact bundle drafts may carry a fact subtype',\n })\n }\n })\n\nconst compareAndSetSchema: z.ZodType<CompareAndSet> = z\n .object({\n recordId: recordIdSchema,\n observedStatus: z.string(),\n observedOrdinal: z.number(),\n })\n .strict()\n\nconst curationAuthorshipSchema: z.ZodType<CurationAuthorship> = z\n .object({\n path: z.enum(['llm', 'llm-repaired', 'deterministic-fallback']),\n model: z\n .object({\n id: z.string().min(1),\n family: z.string().optional(),\n fingerprint: z.string().optional(),\n })\n .strict()\n .optional(),\n executionContext: z.enum(['local-interactive', 'local-headless', 'ci', 'cloud']),\n // 381-47 additive-optional: an absent member still parses (pre-stamp checkpoints).\n fallbackReason: z\n .enum(['malformed', 'no-model', 'token-budget', 'model-error'])\n .optional(),\n })\n .strict()\n\nconst envelopeShape = {\n // Projected from the schema package's registry rather than re-listed here. A hand-written\n // member list is the class of defect this phase keeps closing: it is a second vocabulary that\n // has to be kept in step with the first, and nothing makes it.\n origin: z.enum(DELTA_ORIGINS),\n scope: scopeSchema,\n citedIds: z.array(recordIdSchema),\n precondition: z.array(compareAndSetSchema).optional(),\n authorship: curationAuthorshipSchema.optional(),\n} as const\n\nconst deltaSchema = z.discriminatedUnion('kind', [\n z\n .object({\n kind: z.literal('Add'),\n ...envelopeShape,\n bundle: bundleDraftSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('Confirm'),\n ...envelopeShape,\n targetId: recordIdSchema,\n evidenceToken: evidenceTokenSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('Supersede'),\n ...envelopeShape,\n victimId: recordIdSchema,\n newBundle: bundleDraftSchema,\n evidenceToken: evidenceTokenSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('Deprecate'),\n ...envelopeShape,\n targetId: recordIdSchema,\n reason: z.string(),\n })\n .strict(),\n z\n .object({\n kind: z.literal('MintUnknown'),\n ...envelopeShape,\n conflict: z\n .object({\n recordIds: z.array(recordIdSchema),\n kind: z.enum(['contradiction', 'drift', 'clarification']),\n })\n .strict(),\n })\n .strict(),\n z\n .object({\n kind: z.literal('Noop'),\n ...envelopeShape,\n })\n .strict(),\n]) satisfies z.ZodType<Delta>\n\n/**\n * The SHARED structural boundary for a checkpoint. Neighbor membership and CAS freshness are\n * deliberately disposition checks, so this schema validates structure without applying them.\n * D-02: the checkpoint carries the authored outcome's FULL delta array — one durable authoring\n * checkpoint per job, disposed delta-by-delta through the commit boundary.\n *\n * Deliberately origin-WIDE, and that is not an oversight — see\n * `AUTHORED_CHECKPOINT_ORIGIN_ADMISSION` below. `AuthoredCheckpoint`'s inferred delta type is\n * the type every in-process checkpoint carries, including the user-origin deltas the review\n * verbs commit and the system-origin deltas rollback and the canary commit. Origin admission is\n * a property of the DRAIN's parse boundary, not of the checkpoint shape.\n */\nexport const authoredCheckpointSchema = z\n .object({\n schemaVersion: z.literal(AUTHORED_CHECKPOINT_SCHEMA_VERSION),\n deltas: z.array(deltaSchema).min(1),\n neighborIds: z.array(recordIdSchema),\n preconditions: z.array(compareAndSetSchema),\n authorship: curationAuthorshipSchema,\n })\n .strict()\n\nexport type AuthoredCheckpoint = z.infer<typeof authoredCheckpointSchema>\n\n/**\n * Which origins may cross the DRAIN's authored-checkpoint boundary.\n *\n * MECHANISM, stated so the claim can be reded rather than believed: totality is the `satisfies`\n * clause — a fifth member of `DeltaOrigin` is a compile error AT THIS TABLE — and each member's\n * behaviour is pinned by the DELTA_ORIGINS walk in `__tests__/author-contract.test.ts`, whose\n * expectations are declared independently of this literal. Dropping a member fails `tsc`;\n * flipping a member's value reds a named row.\n *\n * CONSEQUENCE the table exists for: `parseAuthoredCheckpoint` is the drain's only reader of the\n * durable `authored` job-state slot (drain.ts:992, crash recovery). Before this table, a\n * persisted checkpoint claiming `origin: 'user'` parsed, re-entered `commitCurationDelta`, and\n * on a broken citation threw `UserDeltaCitationIntegrityError` — which the drain records as a\n * COMMIT failure and requeues durably, so every subsequent drain retried the same deterministic\n * refusal and stopped the pass. A rejected origin is now a ZodError at parse, which drain.ts\n * :993-1003 routes to `quarantineMalformedClaim`: typed, terminal, once.\n *\n * PRODUCER ENUMERATION that decides the members — the slot's writers, not just the author:\n *\n * - drain.ts:593 `persistCheckpoint` → `persistAuthoredCheckpoint` (queue/job-state.ts:218),\n * carrying `checkpointFromAuthored` (drain.ts:537) over the INJECTED `options.author` seam.\n * The two production authors are cli `curator-author.ts` and `curator/fallback.ts`, and both\n * hard-code `agent`. This is the writer drain.ts:992 re-reads.\n * - drain.ts:682 `preserveAuthoredCheckpointAndRequeue` re-persists that same parsed value.\n * - commit.ts:1065 / :1183 write the slot with the origin of whatever delta is being\n * committed, which for knowledge-port callers is `user` (the review verbs) or `system` (the\n * canary Confirm). Those candidates are never queued and never claimed — 387-17's write-free\n * `bridgeDelta` materializes no claimed candidate, and `reconcileOnDrainStart`'s\n * `requeueCandidate` returns early unless a claimed or queued candidate directory exists —\n * so the drain cannot reach their job state. A candidateId collision cannot bridge the gap\n * either: `candidateContentAddress` hashes `sourceRunId: 'knowledge-port'` and an\n * `attributingObservationId` derived from the delta's own canonical hash.\n * - journal/reconcile.ts:173 carries an existing value forward on requeue; it mints no origin.\n *\n * Admitted set: exactly `{ agent }`. `user` is rejected because that is the retry-forever\n * closure. `import` and `system` are rejected because NO producer can put them here — admitting\n * an origin on the grounds that it exists somewhere in the vocabulary is how the widened enum\n * this table replaces came to admit `user` in the first place.\n *\n * NOT the same question as `AUTONOMOUS_DEPRECATE_BY_ORIGIN` in disposition.ts, which asks who\n * may tombstone standing knowledge. `system` is allowed there and rejected here without\n * contradiction: rollback's `maintenanceCheckpoint` and knowledge-store's `bridgeDelta` build\n * plain in-process checkpoints and never parse at this boundary. The two tables are in fact\n * mutually load-bearing — the floor can afford to let a `user` Deprecate through precisely\n * because this boundary guarantees the model cannot mint one.\n */\nexport const AUTHORED_CHECKPOINT_ORIGIN_ADMISSION = {\n agent: 'admitted',\n import: 'rejected',\n system: 'rejected',\n user: 'rejected',\n} as const satisfies Record<DeltaOrigin, 'admitted' | 'rejected'>\n\n/**\n * Structure PLUS drain origin admission. Applied per delta and at every array position: a check\n * written against `deltas[0]` would be the same one-member-of-a-set defect at the array axis,\n * and a widened checkpoint carries the job's full delta array (D-02).\n */\nconst drainAuthoredCheckpointSchema = authoredCheckpointSchema.superRefine((checkpoint, ctx) => {\n checkpoint.deltas.forEach((delta, index) => {\n if (AUTHORED_CHECKPOINT_ORIGIN_ADMISSION[delta.origin] === 'admitted') return\n ctx.addIssue({\n code: 'custom',\n path: ['deltas', index, 'origin'],\n message:\n `origin '${delta.origin}' is not admitted at the drain's authored-checkpoint boundary: `\n + 'the drain authors deltas on the agent\\'s behalf, and no producer can place another '\n + 'origin in this slot',\n })\n })\n})\n\n/**\n * Parse authored bytes at the drain's boundary — both when wrapping fresh author output\n * (drain.ts:537) and when replaying crash-recovered state (drain.ts:992).\n *\n * BOTH sites, deliberately. Guarding only the recovery read would leave the injected author seam\n * able to put a non-agent origin into the durable slot in the first place, which is the same\n * defect one step upstream: a delta the store attributes to a person, authored by a model, that\n * the autonomy floor would then let tombstone standing knowledge.\n */\nexport function parseAuthoredCheckpoint(value: unknown): AuthoredCheckpoint {\n return drainAuthoredCheckpointSchema.parse(value)\n}\n\n/**\n * The per-delta commit unit sliced from a widened checkpoint. `commitCurationDelta` remains\n * the ONE serialized mutation boundary and disposes exactly one delta per call; the drain\n * slices the checkpoint and disposes each delta independently (D-02).\n */\nexport interface AuthoredDeltaCheckpoint {\n schemaVersion: typeof AUTHORED_CHECKPOINT_SCHEMA_VERSION\n delta: AuthoredCheckpoint['deltas'][number]\n neighborIds: AuthoredCheckpoint['neighborIds']\n preconditions: AuthoredCheckpoint['preconditions']\n authorship: AuthoredCheckpoint['authorship']\n}\n\n/** Slice one widened checkpoint into its ordered per-delta commit units. */\nexport function sliceAuthoredCheckpoint(\n checkpoint: AuthoredCheckpoint,\n): AuthoredDeltaCheckpoint[] {\n return checkpoint.deltas.map((delta) => ({\n schemaVersion: checkpoint.schemaVersion,\n delta,\n neighborIds: checkpoint.neighborIds,\n preconditions: checkpoint.preconditions,\n authorship: checkpoint.authorship,\n }))\n}\n\n/** Re-widen one commit unit into a parseable singleton checkpoint (job-state persistence). */\nexport function widenAuthoredDeltaCheckpoint(\n slice: AuthoredDeltaCheckpoint,\n): AuthoredCheckpoint {\n return {\n schemaVersion: slice.schemaVersion,\n deltas: [slice.delta],\n neighborIds: slice.neighborIds,\n preconditions: slice.preconditions,\n authorship: slice.authorship,\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { existsSync, mkdirSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n asEvidenceToken,\n canonicalJson,\n computeStepSequenceSignature,\n evaluatePromotionGate,\n GATE_RECEIPT_SCHEMA_VERSION,\n parseProcedureBody,\n procedureStepKeys,\n sha256hex,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n BundleDiscriminant,\n BundleDraft,\n BundleRelation,\n Delta,\n EvidenceToken,\n PromotionGateHoldReason,\n PromotionPath,\n RecordId,\n ResolvePromotionPosture,\n ScreenState,\n TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport { copyArtifacts } from '../artifact-copy.js'\nimport type { ArtifactCopyInput, ArtifactCopyResult } from '../artifact-copy.js'\nimport {\n appendMeasurementObservation,\n appendOutcomeEvent,\n appendOutcomeEventWithEnrichment,\n appendPromotionReceipt,\n appendRelation,\n writeMeasurementBaseline,\n} from '../bundle-append.js'\nimport { loadBundle, readMeasurements } from '../bundle-read.js'\nimport type { LoadedBundle } from '../bundle-read.js'\nimport { renderBundleParts } from '../bundle-parts.js'\nimport type { RenderBundlePartsInput } from '../bundle-parts.js'\nimport {\n discardStagedBundle,\n finalizeStagedBundle,\n stageBundle,\n} from '../bundle-publish.js'\nimport type {\n BundleStoreConfig,\n PublishBundleInput,\n PublishBundleOutcome,\n StageBundleOutcome,\n} from '../bundle-publish.js'\nimport {\n BundleTargetResolutionError,\n resolveProductQualifiedBundleDir,\n type ProductQualifiedBundleDir,\n} from '../bundle-scan.js'\nimport {\n projectBundleIndexRow,\n projectBundleIndexRowWithinCurrentAuthority,\n} from '../index-rebuild.js'\nimport {\n COMMIT_INTENT_SCHEMA_VERSION,\n clearCommitIntent,\n writeCommitIntent,\n} from '../journal/intent-journal.js'\nimport {\n isCurationEffectCommitted, receiptForEffect, writeCurationEffectReceiptWithinCurrentAuthority,\n type CurationEffect, type CurationObservation,\n} from '../journal/curation-effect-receipt.js'\nimport {\n assertEpochCurrent,\n readCurrentEpoch,\n withCurrentWriterAuthority,\n WriterAuthorityLostError,\n} from '../lease/writer-lease.js'\nimport { assemblePromotionGateInput, snapshotTrustPriors } from '../promotion-gate-input.js'\nimport type { ClaimedCurationJob } from '../queue/curation-queue.js'\nimport {\n writeJobState,\n writeJobStateWithinCurrentAuthority,\n} from '../queue/job-state.js'\nimport { widenAuthoredDeltaCheckpoint } from './author-contract.js'\nimport type { AuthoredDeltaCheckpoint, DispositionProfile } from './author-contract.js'\nimport { disposeDelta, originalDispositionDelta } from './disposition.js'\nimport type {\n DispositionDrainState,\n FirstSeenRegistration,\n RelationIntent,\n UnknownMintIntent,\n UnknownResolutionIntent,\n} from './disposition.js'\n\nexport { assemblePromotionGateInput } from '../promotion-gate-input.js'\n\ntype CheckpointDraft = BundleDraft & { needsEnrichment?: true }\n\nexport interface CommitCurationJob extends ClaimedCurationJob {\n screenStates?: readonly ScreenState[]\n /** Product authority resolved with the checkpoint; absent ids must be globally unique. */\n targetProducts?: Readonly<Record<string, string>>\n}\n\nexport interface CommitCurationDependencies {\n knowledgeRoot: string\n epoch: number\n profile: DispositionProfile\n drainState: DispositionDrainState\n /** Host-resolved posture as data; absent means the v51 floor. */\n resolvePromotionPosture?: ResolvePromotionPosture\n priors?: TrustPriorTable\n /**\n * Multi-delta disposal (D-02): when set, terminal paths skip queue completion so the\n * claimed candidate directory stays available for the checkpoint's remaining deltas.\n * The drain leaves it unset on the final delta, which completes the job as before.\n */\n deferCompletion?: true\n hooks?: {\n /**\n * Test/chaos seam after every pre-staging write and immediately before the commit tail\n * enters its current-writer-authority section. Nothing durable and reader-relevant to this\n * candidate has been published yet when it fires.\n */\n beforeCommitAuthorityEntry?: () => void\n /** Test/chaos seam immediately after the durable intent rename. */\n afterIntentWritten?: () => void\n /** Test/chaos seam while the complete bundle is staged but still reader-invisible. */\n beforePublishRename?: () => void\n /** Test/chaos seam after lock-held authority comparison and before finalize. */\n afterFinalAuthorityCompare?: () => void\n /** Test-only bounded-takeover override; production uses the pinned lock deadline. */\n mutationLockTakeoverMs?: number\n /** Test/chaos seam after each durable mutable-file replacement. */\n afterMutableReplacement?: (targetRelPath: string) => void\n /** Test/chaos seam after a fresh bundle publish and before its index projection. */\n afterBundlePublished?: (bundleId: RecordId) => void\n /** Test/chaos seam after the index transaction and before intent removal. */\n afterIndexApplied?: (bundleId: RecordId) => void\n /** Test/chaos seams around the durable observation/cleanup boundary. */\n afterEffectReceiptsWritten?: () => void\n afterIntentCleared?: () => void\n }\n operations?: {\n /** Test/chaos seam; production always uses the canonical publisher. */\n publishBundle?: (\n config: BundleStoreConfig,\n input: PublishBundleInput,\n ) => PublishBundleOutcome\n }\n}\n\ninterface CommittedBundleResult {\n bundleId: RecordId\n bundleDir: string\n deltaKind: Delta['kind']\n /** D-16 exception-bucket observability; absent when the gate promotes or never runs. */\n promotionHoldReason?: PromotionGateHoldReason\n promotionPath?: PromotionPath\n}\n\n/**\n * 381-47 (F-381-45-1): WHY a delta-noop disposition had nothing to apply. `authored-noop`\n * = a capable-model author deliberately emitted a Noop delta; the `fallback-*` members\n * name WHICH author fallback defeated extraction (the §7.9 one-element procedure Noop).\n * Benign noop reasons (evidence-token dedup, disposition rejects) never carry a cause.\n */\nexport type EmptyDeltaCause =\n | 'authored-noop'\n | 'fallback-malformed'\n | 'fallback-no-model'\n | 'fallback-token-budget'\n | 'fallback-model-error'\n\nexport type CommitCurationOutcome =\n | ({ kind: 'applied' } & CommittedBundleResult)\n | ({ kind: 'downgraded'; reason: string; original: Delta } & CommittedBundleResult)\n | ({ kind: 'converted-confirm' } & CommittedBundleResult)\n | { kind: 'abandoned-stale-epoch'; observedEpoch: number }\n | {\n kind: 'failed'\n reason: 'identity-collision' | 'append-failed'\n collisionReason?: Extract<\n PublishBundleOutcome,\n { kind: 'identity-collision' }\n >['reason']\n }\n | { kind: 'noop'; reason: string; emptyDeltaCause?: EmptyDeltaCause }\n | { kind: 'requeue-resynthesis'; reason: string }\n\nexport interface ApplyIndexDeltaForBundleInput {\n knowledgeRoot: string\n priors?: TrustPriorTable\n bundleId: string\n product?: string\n}\n\n/** Shared Plan 378-10 projection authority used by commit and journal reconciliation. */\nexport function applyIndexDeltaForBundle(input: ApplyIndexDeltaForBundleInput): void {\n projectBundleIndexRow(input)\n}\n\n/** @internal The caller must already hold withCurrentWriterAuthority for this root. */\nexport function applyIndexDeltaForBundleWithinCurrentAuthority(\n input: ApplyIndexDeltaForBundleInput,\n): void {\n projectBundleIndexRowWithinCurrentAuthority(input)\n}\n\n/** Recovery alias deliberately delegates to the same projection unit as the live tail. */\nexport function deriveIndexRowFromBundle(input: ApplyIndexDeltaForBundleInput): void {\n projectBundleIndexRow(input)\n}\n\n/** Plan 379-06's replay-safe promoted-token composition, shared by both seams. */\nexport function derivePromotedEvidenceToken(sourceToken: string): EvidenceToken {\n return asEvidenceToken(\n sha256hex(canonicalJson({ token: sourceToken, event: 'promoted' })),\n )\n}\n\nfunction staleEpoch(\n deps: CommitCurationDependencies,\n): Extract<CommitCurationOutcome, { kind: 'abandoned-stale-epoch' }> | undefined {\n const current = assertEpochCurrent({\n knowledgeRoot: deps.knowledgeRoot,\n epoch: deps.epoch,\n })\n return current.current\n ? undefined\n : { kind: 'abandoned-stale-epoch', observedEpoch: current.observedEpoch }\n}\n\nfunction originClass(delta: Delta): RenderBundlePartsInput['originClass'] {\n switch (delta.origin) {\n case 'user':\n return 'user'\n case 'import':\n return 'import'\n case 'agent':\n case 'system':\n return 'agent-verified'\n }\n}\n\nfunction elementRef(anchors: readonly Anchor[]): { role: string; name: string } {\n const element = anchors.find(\n (anchor): anchor is Extract<Anchor, { t: 'el' }> => anchor.t === 'el',\n )\n if (element !== undefined) return { role: element.role, name: element.name }\n const primary = anchors[0]!\n return { role: primary.t, name: canonicalJson(primary) }\n}\n\nfunction discriminant(\n draft: BundleDraft,\n delta: Delta,\n structuralProcedureStepKeys: readonly string[],\n): BundleDiscriminant {\n switch (draft.kind) {\n case 'fact': {\n if (draft.subtype === undefined) throw new TypeError('fact commit requires a subtype')\n if (draft.subtype === 'measurement') {\n return {\n kind: 'fact',\n subtype: 'measurement',\n // A superseding validity window keeps the same anchor-level supersession key while its\n // code-derived evidence token gives the replacement a distinct, replay-stable identity.\n metricKey: canonicalJson({\n anchors: draft.anchors,\n ...(delta.kind === 'Supersede'\n ? { validityWindowEvidenceToken: delta.evidenceToken }\n : {}),\n }),\n }\n }\n return { kind: 'fact', subtype: draft.subtype, elementRef: elementRef(draft.anchors),\n // Same-anchor corrections replace immutable authored content. Give that actual\n // validity-window generation its evidence identity, as measurements already do;\n // Add and historical identities remain unchanged and prose never enters the key.\n ...(delta.kind === 'Supersede'\n ? { validityWindowEvidenceToken: delta.evidenceToken } : {}),\n }\n }\n case 'procedure': {\n const flow = draft.anchors.find(\n (anchor): anchor is Extract<Anchor, { t: 'flow' }> => anchor.t === 'flow',\n )\n return {\n kind: 'procedure',\n flowName: flow?.name ?? canonicalJson(draft.anchors[0]),\n // D-01: procedureStepKeys is the schema-owned identity authority. Observation\n // naturalKeys are evidence prose and must never enter the content address.\n stepSignature: computeStepSequenceSignature(structuralProcedureStepKeys),\n }\n }\n case 'caution': {\n const error = draft.anchors.find(\n (anchor): anchor is Extract<Anchor, { t: 'error' }> => anchor.t === 'error',\n )\n return { kind: 'caution', errorKey: error?.message ?? canonicalJson(draft.anchors[0]) }\n }\n case 'unknown':\n return {\n kind: 'unknown',\n conflictRecordIds: delta.kind === 'MintUnknown' ? delta.conflict.recordIds : delta.citedIds,\n }\n case 'policy':\n return { kind: 'policy', ruleKey: canonicalJson(draft.anchors[0]),\n ...(delta.kind === 'Supersede'\n ? { validityWindowEvidenceToken: delta.evidenceToken } : {}),\n }\n }\n}\n\nfunction syntheticDraft(job: CommitCurationJob): BundleDraft {\n return {\n kind: job.payload.kind,\n ...(job.payload.subtype === undefined ? {} : { subtype: job.payload.subtype }),\n anchors: [...job.payload.anchors],\n scope: job.payload.scope,\n summary: job.payload.summarySeed,\n body: job.payload.bodySeed,\n distilledEvidenceRef: {\n id: `curation-candidate-${job.candidateId}`,\n sha: job.candidateId,\n },\n originStage: 'run-curation',\n }\n}\n\nfunction draftForDelta(delta: Delta, job: CommitCurationJob): CheckpointDraft | undefined {\n if (delta.kind === 'Add') return delta.bundle\n if (delta.kind === 'Supersede') return delta.newBundle\n if (delta.kind === 'MintUnknown') return syntheticDraft(job)\n return undefined\n}\n\nfunction evidenceMarkdown(job: CommitCurationJob): string {\n const lines = job.payload.distilledObservations.map(\n (observation) => `- ${canonicalJson(observation)}`,\n )\n return `${lines.length === 0 ? job.payload.bodySeed : lines.join('\\n')}\\n`\n}\n\nfunction observationOrdinal(job: CommitCurationJob): number | undefined {\n return job.payload.distilledObservations[0]?.observedAtOrdinal\n}\n\nfunction measurementSeedValue(job: CommitCurationJob): string | undefined {\n if (job.payload.kind !== 'fact' || job.payload.subtype !== 'measurement') return undefined\n const metric = job.payload.anchors.find(\n (anchor): anchor is Extract<Anchor, { t: 'flow' }> =>\n anchor.t === 'flow' && anchor.name.startsWith('measurement:'),\n )\n if (metric === undefined) return undefined\n const prefix = `${metric.name.slice('measurement:'.length)} measured as `\n return job.payload.summarySeed.startsWith(prefix)\n ? job.payload.summarySeed.slice(prefix.length)\n : undefined\n}\n\nfunction numericMeasurementSeed(job: CommitCurationJob): number | undefined {\n const value = measurementSeedValue(job)\n if (value === undefined) return undefined\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction confirmedEvent(\n job: CommitCurationJob,\n delta: Delta,\n evidenceToken = job.payload.evidenceToken,\n): Extract<LoadedBundle['events'][number], { type: 'confirmed' }> {\n return {\n type: 'confirmed',\n evidenceToken: asEvidenceToken(evidenceToken),\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n observationId: job.payload.attributingObservationId,\n ...(observationOrdinal(job) === undefined\n ? {}\n : { observationOrdinal: observationOrdinal(job) }),\n origin: originClass(delta),\n }\n}\n\nfunction relations(\n intents: readonly RelationIntent[],\n delta: Delta,\n job: CommitCurationJob,\n): BundleRelation[] {\n const values: BundleRelation[] = intents.map((intent) => ({\n type: intent.type,\n targetId: intent.targetId,\n addedAtOrdinal: job.payload.buildOrdinal,\n curationJobId: job.candidateId,\n }))\n if (delta.kind === 'Supersede') {\n values.unshift({\n type: 'supersedes',\n targetId: delta.victimId,\n addedAtOrdinal: job.payload.buildOrdinal,\n curationJobId: job.candidateId,\n })\n }\n return values\n}\n\nfunction artifactInputs(job: CommitCurationJob): ArtifactCopyInput[] {\n return job.payload.artifactInventory.map((artifact) => ({\n ref: {\n id: `${job.candidateId}:${artifact.stepIndex}:${artifact.sha256}`,\n sha: artifact.sha256,\n },\n sourcePath: join(job.candidateDir, artifact.relativePath),\n stepIndex: artifact.stepIndex,\n role: artifact.role,\n originalName: artifact.originalName,\n }))\n}\n\n/**\n * Pre-copy the job's artifacts into the preflight dir — and touch the filesystem only if it has\n * artifacts to copy.\n *\n * THE EMPTY SHORT-CIRCUIT IS NOT A MICRO-OPTIMISATION, it is what makes 387-17's write-free\n * `bridgeDelta` true on the SUCCESS path. `copyArtifacts` opens with an unconditional\n * `mkdirSync(destArtifactsDir, { recursive: true })`, and `preflightDir` lives INSIDE\n * `job.candidateDir` — so for a knowledge-port job, whose `candidateDir` deliberately no longer\n * exists, that one recursive mkdir re-created the entire `memory/queue/claimed/<lease>/<id>/…`\n * chain. `markDone` then removed the candidate and its lease dir again, but `memory/queue/claimed`\n * itself survived: MEASURED as `existsSync(claimedRoot) === true` after a successful port-bridged\n * fact `Add`. The corpus's whole-root digest counts directories, so that is residue, and the\n * regression case in knowledge-store.test.ts now reds if it comes back.\n *\n * PROVABLY INERT FOR THE DRAIN, which is the sibling-input half. A drain job's `candidateDir` is\n * a real directory that the queue wrote long before commit, its artifacts dir is created by this\n * call only to be removed by `commitCurationDelta`'s `finally`, and the result returned here for\n * an empty input list is the same object `copyArtifacts` builds for one: nothing copied, nothing\n * skipped, and evidence complete. A job WITH artifacts is untouched by this branch.\n */\nfunction preCopyArtifacts(\n job: CommitCurationJob,\n preflightDir: string,\n): ArtifactCopyResult {\n const inputs = artifactInputs(job)\n if (inputs.length === 0) {\n return { copied: [], skipped: [], evidenceIncomplete: false }\n }\n return copyArtifacts(inputs, join(preflightDir, 'artifacts'))\n}\n\nfunction publisherArtifacts(\n preCopy: ArtifactCopyResult,\n preflightDir: string,\n): ArtifactCopyInput[] {\n return preCopy.copied.map((artifact) => ({\n ref: artifact.ref,\n sourcePath: join(preflightDir, artifact.relPath),\n stepIndex: artifact.stepIndex,\n ...(artifact.role === undefined ? {} : { role: artifact.role }),\n ...(artifact.originalName === undefined ? {} : { originalName: artifact.originalName }),\n }))\n}\n\nfunction storeConfig(\n deps: CommitCurationDependencies,\n productKey: string,\n writerLeaseId: string,\n): BundleStoreConfig {\n const hooks: NonNullable<BundleStoreConfig['hooks']> = {\n ...(deps.hooks?.beforePublishRename === undefined\n ? {}\n : { beforePublishRename: deps.hooks.beforePublishRename }),\n ...(deps.hooks?.afterMutableReplacement === undefined\n ? {}\n : { afterMutableReplacement: deps.hooks.afterMutableReplacement }),\n }\n return {\n knowledgeRoot: deps.knowledgeRoot,\n productKey,\n commitArtifacts: 'none',\n writerLeaseId,\n writerEpoch: deps.epoch,\n ...(Object.keys(hooks).length === 0 ? {} : { hooks }),\n }\n}\n\ntype PreparedBundlePublication =\n | {\n kind: 'override'\n publish: NonNullable<\n NonNullable<CommitCurationDependencies['operations']>['publishBundle']\n >\n config: BundleStoreConfig\n input: PublishBundleInput\n }\n | { kind: 'canonical'; outcome: StageBundleOutcome }\n\nfunction prepareBundlePublication(\n deps: CommitCurationDependencies,\n config: BundleStoreConfig,\n input: PublishBundleInput,\n): PreparedBundlePublication {\n const publishOverride = deps.operations?.publishBundle\n if (publishOverride !== undefined) {\n return { kind: 'override', publish: publishOverride, config, input }\n }\n return { kind: 'canonical', outcome: stageBundle(config, input) }\n}\n\nfunction finalizePreparedPublicationWithinCurrentAuthority(\n deps: CommitCurationDependencies,\n writerLeaseId: string,\n prepared: PreparedBundlePublication,\n): PublishBundleOutcome {\n if (prepared.kind === 'override') {\n return prepared.publish(prepared.config, prepared.input)\n }\n if (prepared.outcome.kind !== 'staged') return prepared.outcome\n try {\n return finalizeStagedBundle(prepared.outcome)\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code === 'ENOENT'\n && !existsSync(prepared.outcome.stagingDir)\n ) {\n throw new WriterAuthorityLostError(\n { knowledgeRoot: deps.knowledgeRoot, leaseId: writerLeaseId, epoch: deps.epoch },\n 'mutation-lock-generation-lost',\n readCurrentEpoch(deps.knowledgeRoot),\n )\n }\n throw error\n }\n}\n\nfunction discardPreparedPublication(prepared: PreparedBundlePublication): void {\n if (prepared.kind !== 'canonical' || prepared.outcome.kind !== 'staged') return\n discardStagedBundle(prepared.outcome, true)\n}\n\nfunction unknownEvidenceRecordIds(\n intent: UnknownMintIntent,\n committedBundleId: RecordId,\n): RecordId[] {\n const ids = [\n ...intent.evidenceRecordIds,\n ...(intent.includeCommittedBundle ? [committedBundleId] : []),\n ]\n return ids.filter((id, index) => ids.indexOf(id) === index).sort()\n}\n\nfunction recordFirstSeenBundle(\n state: DispositionDrainState,\n registration: FirstSeenRegistration,\n recordId: RecordId,\n): void {\n state.firstSeenAnchorsByScope ??= new Map()\n const entries = state.firstSeenAnchorsByScope.get(registration.scopeKey) ?? new Map()\n entries.set(registration.supersessionKey, {\n buildOrdinal: registration.buildOrdinal,\n recordId,\n })\n state.firstSeenAnchorsByScope.set(registration.scopeKey, entries)\n}\n\nfunction unknownDraft(\n intent: UnknownMintIntent,\n evidenceRecordIds: readonly RecordId[],\n job: CommitCurationJob,\n): BundleDraft {\n const payload = intent.kind === 'thrash'\n ? {\n kind: intent.kind,\n triggerKey: intent.triggerKey,\n windowOpenOrdinal: intent.windowOpenOrdinal,\n windowCloseOrdinal: intent.windowCloseOrdinal,\n evidenceRecordIds,\n }\n : {\n kind: intent.kind,\n scopeKey: intent.triggerKey,\n windowOpenOrdinal: intent.windowOpenOrdinal,\n windowCloseOrdinal: intent.windowCloseOrdinal,\n firstSeenCount: intent.firstSeenCount,\n evidenceRecordIds,\n }\n return {\n kind: 'unknown',\n anchors: [{ t: 'flow', name: intent.marker }],\n scope: intent.scope,\n summary: intent.kind === 'thrash'\n ? `Memory disabled for churning anchor ${intent.triggerKey}`\n : `High-cardinality restructuring detected for ${intent.triggerKey}`,\n body: canonicalJson(payload),\n distilledEvidenceRef: {\n id: `${intent.kind}:${job.candidateId}`,\n sha: job.candidateId,\n },\n originStage: 'run-curation',\n }\n}\n\ninterface PreparedUnknownMintIntent {\n intent: UnknownMintIntent\n publication: PreparedBundlePublication\n}\n\nfunction prepareUnknownMintIntent(\n deps: CommitCurationDependencies,\n job: CommitCurationJob,\n checkpoint: AuthoredDeltaCheckpoint,\n intent: UnknownMintIntent,\n committedBundleId: RecordId,\n): PreparedUnknownMintIntent {\n const evidenceRecordIds = unknownEvidenceRecordIds(intent, committedBundleId)\n const deterministicAuthorship = {\n path: 'deterministic-fallback' as const,\n executionContext: checkpoint.authorship.executionContext,\n }\n const delta: Extract<Delta, { kind: 'MintUnknown' }> = {\n kind: 'MintUnknown',\n origin: 'system',\n scope: intent.scope,\n citedIds: [...evidenceRecordIds],\n conflict: { recordIds: [...evidenceRecordIds], kind: 'drift' },\n authorship: deterministicAuthorship,\n }\n const draft = unknownDraft(intent, evidenceRecordIds, job)\n const config = storeConfig(deps, intent.scope.key, job.leaseId)\n const publication = prepareBundlePublication(deps, config, {\n draft,\n discriminant: discriminant(draft, delta, []),\n originClass: originClass(delta),\n createdAtOrdinal: job.payload.buildOrdinal,\n screenStates: [],\n initialEvents: [confirmedEvent(job, delta)],\n relations: evidenceRecordIds.map((targetId) => ({\n type: 'conflicts-with' as const,\n targetId,\n addedAtOrdinal: job.payload.buildOrdinal,\n curationJobId: job.candidateId,\n })),\n provenance: {\n mode: 'run-linked',\n runId: job.payload.sourceRunId,\n testId: job.payload.attributingObservationId,\n stepIndex: job.payload.distilledObservations[0]?.step.ordinal ?? 0,\n curationJobId: job.candidateId,\n sourceBuildOrdinal: job.payload.buildOrdinal,\n authorship: deterministicAuthorship,\n },\n evidenceMarkdown: `${draft.body}\\n`,\n distilledObservations: [],\n artifacts: [],\n })\n return { intent, publication }\n}\n\nfunction commitUnknownMintIntentWithinCurrentAuthority(\n deps: CommitCurationDependencies,\n job: CommitCurationJob,\n prepared: PreparedUnknownMintIntent,\n): CommitCurationOutcome | undefined {\n const published = finalizePreparedPublicationWithinCurrentAuthority(\n deps,\n job.leaseId,\n prepared.publication,\n )\n if (published.kind === 'identity-collision') {\n return {\n kind: 'failed',\n reason: 'identity-collision',\n collisionReason: published.reason,\n }\n }\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n knowledgeRoot: deps.knowledgeRoot,\n bundleId: published.id,\n product: prepared.intent.scope.key,\n })\n return undefined\n}\n\nfunction commitUnknownResolutionIntent(\n deps: CommitCurationDependencies,\n job: CommitCurationJob,\n intent: UnknownResolutionIntent,\n target: ProductQualifiedBundleDir,\n): CommitCurationOutcome | undefined {\n const config = storeConfig(deps, target.product, job.leaseId)\n const evidenceToken = asEvidenceToken(\n sha256hex(canonicalJson({\n token: job.payload.evidenceToken,\n event: intent.reason,\n targetId: intent.targetId,\n })),\n )\n // The intent is armed disposition-side as maintenance origin `system`; the\n // autonomous-deprecate guard blocks only agent-origin removals.\n const appended = appendOutcomeEvent(config, intent.targetId, {\n type: 'deprecated',\n evidenceToken,\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n reason: intent.reason,\n })\n const failure = appendFailure(appended)\n if (failure !== undefined) return failure\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n knowledgeRoot: deps.knowledgeRoot,\n bundleId: intent.targetId,\n product: target.product,\n })\n return undefined\n}\n\nfunction resolveExistingTarget(\n knowledgeRoot: string,\n bundleId: RecordId,\n product: string | undefined,\n): ProductQualifiedBundleDir {\n return resolveProductQualifiedBundleDir({\n knowledgeRoot,\n recordId: bundleId,\n ...(product === undefined ? {} : { product }),\n })\n}\n\n/**\n * 381-47: derive the delta-noop cause from the checkpoint authorship commit already holds\n * (disposition stays authorship-blind). Absent fallbackReason on a fallback-path checkpoint\n * predates the stamp and maps to 'fallback-malformed' — the historical dominant cause\n * (F-381-45-1: three rejected proposals).\n */\nfunction deriveEmptyDeltaCause(\n authorship: AuthoredDeltaCheckpoint['authorship'],\n): EmptyDeltaCause {\n if (authorship.path === 'deterministic-fallback') {\n return `fallback-${authorship.fallbackReason ?? 'malformed'}`\n }\n return 'authored-noop'\n}\n\nfunction markDone(deps: CommitCurationDependencies, job: CommitCurationJob): void {\n if (deps.deferCompletion === true) return\n writeJobState({\n knowledgeRoot: deps.knowledgeRoot,\n candidateId: job.candidateId,\n authority: { leaseId: job.leaseId, epoch: deps.epoch },\n lifecycle: 'done',\n })\n}\n\nfunction markDoneWithinCurrentAuthority(\n deps: CommitCurationDependencies,\n job: CommitCurationJob,\n): void {\n if (deps.deferCompletion === true) return\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot: deps.knowledgeRoot,\n candidateId: job.candidateId,\n authority: { leaseId: job.leaseId, epoch: deps.epoch },\n lifecycle: 'done',\n })\n}\n\nfunction finishCommitWithinCurrentAuthority(\n deps: CommitCurationDependencies,\n job: CommitCurationJob,\n observation: CurationObservation,\n projectSuccessfulPrefix = true,\n completeClaim = true,\n): void {\n for (const effect of observation.effects) {\n if (!isCurationEffectCommitted(deps.knowledgeRoot, job.candidateId, effect)) continue\n // Failure can leave a successful prefix whose normal index tail was never reached.\n if (projectSuccessfulPrefix) applyIndexDeltaForBundleWithinCurrentAuthority({ knowledgeRoot: deps.knowledgeRoot,\n bundleId: effect.recordId, product: effect.product,\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n })\n writeCurationEffectReceiptWithinCurrentAuthority({ knowledgeRoot: deps.knowledgeRoot,\n authority: { leaseId: job.leaseId, epoch: deps.epoch },\n receipt: receiptForEffect(job.candidateId, observation, effect),\n })\n }\n deps.hooks?.afterEffectReceiptsWritten?.()\n clearCommitIntent(deps.knowledgeRoot, job.candidateId)\n deps.hooks?.afterIntentCleared?.()\n // Retriable failures preserve the claim for drain to requeue its authored checkpoint.\n if (completeClaim) markDoneWithinCurrentAuthority(deps, job)\n}\n\nfunction appendFailure(\n outcome:\n | ReturnType<typeof appendMeasurementObservation>\n | ReturnType<typeof appendOutcomeEvent>\n | ReturnType<typeof appendOutcomeEventWithEnrichment>\n | ReturnType<typeof appendPromotionReceipt>\n | ReturnType<typeof appendRelation>,\n): CommitCurationOutcome | undefined {\n if (outcome.kind === 'not-found') return { kind: 'failed', reason: 'append-failed' }\n return undefined\n}\n\nfunction appendMeasurementObservationOnce(\n config: BundleStoreConfig,\n victim: ProductQualifiedBundleDir,\n observation: Parameters<typeof appendMeasurementObservation>[2],\n): ReturnType<typeof appendMeasurementObservation> {\n const existing = readMeasurements(victim.dir)\n const consumed = existing?.observations.find(\n (candidate) =>\n candidate.evidenceToken === observation.evidenceToken\n && candidate.curationJobId === observation.curationJobId,\n )\n if (consumed !== undefined) {\n if (canonicalJson(consumed) !== canonicalJson(observation)) {\n throw new TypeError('measurement observation identity resolved to different canonical bytes')\n }\n return { kind: 'duplicate' }\n }\n return appendMeasurementObservation(config, victim.recordId as RecordId, observation)\n}\n\nfunction mutationTarget(delta: Delta): RecordId | undefined {\n if (delta.kind === 'Confirm' || delta.kind === 'Deprecate') return delta.targetId\n if (delta.kind === 'Supersede') return delta.victimId\n return undefined\n}\n\n/**\n * The one serialized mutation boundary: fresh epoch, disposition, intent, fresh epoch, publish,\n * append-only lifecycle, canonical index projection, intent clear, and queue completion.\n */\nexport function commitCurationDelta(\n deps: CommitCurationDependencies,\n job: CommitCurationJob,\n checkpoint: AuthoredDeltaCheckpoint,\n): CommitCurationOutcome {\n deps = { ...deps, ...(deps.priors === undefined ? {} : { priors: snapshotTrustPriors(deps.priors) }) }\n const beforeWork = staleEpoch(deps)\n if (beforeWork !== undefined) return beforeWork\n\n const disposed = disposeDelta({\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n delta: checkpoint.delta,\n checkpoint,\n profile: deps.profile,\n knowledgeRoot: deps.knowledgeRoot,\n candidate: {\n anchors: job.payload.anchors,\n scope: job.payload.scope,\n buildOrdinal: job.payload.buildOrdinal,\n curationJobId: job.candidateId,\n ...(measurementSeedValue(job) === undefined\n ? {}\n : { measurementValue: measurementSeedValue(job) }),\n // 381-03: procedure deltas are validated against durable queue evidence, so the\n // extraction wall receives the payload's code-derived facts (never LLM text).\n ...(job.payload.kind === 'procedure'\n ? {\n procedureEvidence: {\n distilledObservations: job.payload.distilledObservations,\n },\n }\n : {}),\n },\n drainState: deps.drainState,\n })\n if (disposed.kind === 'requeue-resynthesis') return disposed\n if (disposed.kind === 'noop') {\n markDone(deps, job)\n // Only the delta-noop mint is authorship-derived; every other noop reason\n // (evidence-token dedup, the extraction-wall rejects) stays causeless.\n if (disposed.reason === 'delta-noop') {\n return { ...disposed, emptyDeltaCause: deriveEmptyDeltaCause(checkpoint.authorship) }\n }\n return disposed\n }\n\n const delta = disposed.delta\n const relationRows = relations(disposed.relationIntents ?? [], delta, job)\n const draft = draftForDelta(delta, job)\n const structuralProcedureStepKeys = (() => {\n if (draft?.kind !== 'procedure') return []\n const payload = parseProcedureBody(draft.body)\n return payload === undefined ? undefined : procedureStepKeys(payload)\n })()\n if (structuralProcedureStepKeys === undefined) {\n // Defense in depth over disposition's matching refusal: an authored procedure\n // can never fall back to evidence prose for identity, including in sibling deltas.\n markDone(deps, job)\n return { kind: 'noop', reason: 'procedure-body-unparseable' }\n }\n const productKey = delta.scope.key\n const existingTargetIds = new Set<RecordId>()\n const directTarget = mutationTarget(delta)\n if (directTarget !== undefined) existingTargetIds.add(directTarget)\n if (disposed.measurementAppend !== undefined) {\n existingTargetIds.add(disposed.measurementAppend.victimId)\n }\n for (const intent of disposed.unknownResolutionIntents ?? []) {\n existingTargetIds.add(intent.targetId)\n }\n // Resolve every existing mutation target before publishing an intent or appending any bytes.\n // Scope keys are not storage products: use upstream product authority or require uniqueness.\n const existingTargets = new Map<RecordId, ProductQualifiedBundleDir>()\n for (const targetId of [...existingTargetIds].sort()) {\n existingTargets.set(\n targetId,\n resolveExistingTarget(\n deps.knowledgeRoot,\n targetId,\n job.targetProducts?.[targetId],\n ),\n )\n }\n let bundleId: RecordId\n let bundleDir: string | undefined\n let bundleProduct = productKey\n let publishInput: PublishBundleInput | undefined\n let preparedPublication: PreparedBundlePublication | undefined\n let preparedUnknownMintIntents: PreparedUnknownMintIntent[] = []\n const preflightDir = join(job.candidateDir, `.commit-artifacts-${randomUUID()}`)\n\n writeJobState({\n knowledgeRoot: deps.knowledgeRoot,\n candidateId: job.candidateId,\n authority: { leaseId: job.leaseId, epoch: deps.epoch },\n lifecycle: 'bundling',\n // Persist the parseable widened singleton so crash recovery replays through the\n // one authoredCheckpointSchema recovery boundary.\n authored: widenAuthoredDeltaCheckpoint(checkpoint),\n })\n\n try {\n if (draft !== undefined) {\n const preCopy = preCopyArtifacts(job, preflightDir)\n const identityDelta =\n disposed.kind === 'downgraded'\n && disposed.original.kind === 'Supersede'\n && (\n disposed.reason === 'propose-only'\n || (draft.kind === 'fact' && draft.subtype === 'measurement')\n )\n // D-02 propose-only keeps the replacement candidate distinct from its victim. The\n // downgraded Add is still the Supersede's new validity window, so it keeps the\n // original evidence token in its discriminant (D-58): a same-anchor correction never\n // lands on the victim's id, and a later acceptance converges on the id a local\n // Supersede of the same delta mints.\n ? disposed.original\n : delta\n const renderInput: RenderBundlePartsInput = {\n draft,\n discriminant: discriminant(\n draft,\n identityDelta,\n structuralProcedureStepKeys,\n ),\n originClass: originClass(delta),\n createdAtOrdinal: job.payload.buildOrdinal,\n screenStates: job.screenStates ?? [],\n initialEvents: [confirmedEvent(job, delta)],\n relations: relationRows,\n provenance: {\n mode: 'run-linked',\n runId: job.payload.sourceRunId,\n testId: job.payload.attributingObservationId,\n stepIndex: job.payload.distilledObservations[0]?.step.ordinal ?? 0,\n curationJobId: job.candidateId,\n sourceBuildOrdinal: job.payload.buildOrdinal,\n authorship: checkpoint.authorship,\n ...((draft as CheckpointDraft).needsEnrichment === true\n ? { needsEnrichment: true }\n : {}),\n },\n copiedArtifacts: preCopy,\n evidenceIncomplete: preCopy.evidenceIncomplete,\n evidenceMarkdown: evidenceMarkdown(job),\n distilledObservations: job.payload.distilledObservations,\n }\n const rendered = renderBundleParts(renderInput)\n bundleId = rendered.id\n publishInput = {\n ...renderInput,\n artifacts: publisherArtifacts(preCopy, preflightDir),\n preSkippedArtifacts: preCopy.skipped,\n }\n } else {\n const target = mutationTarget(delta)\n if (target === undefined) {\n markDone(deps, job)\n return { kind: 'failed', reason: 'append-failed' }\n }\n bundleId = target\n const resolved = existingTargets.get(target)\n if (resolved === undefined) {\n throw new Error(`bundle target ${target} was not resolved during preflight`)\n }\n bundleDir = resolved.dir\n bundleProduct = resolved.product\n }\n\n if (publishInput !== undefined) {\n preparedPublication = prepareBundlePublication(\n deps,\n storeConfig(deps, productKey, job.leaseId),\n publishInput,\n )\n }\n preparedUnknownMintIntents = (disposed.unknownMintIntents ?? []).map((intent) =>\n prepareUnknownMintIntent(deps, job, checkpoint, intent, bundleId),\n )\n\n // Cheap early abandon only. The load-bearing check is the tail's authority entry, which\n // reads lease identity and epoch inside the transaction it then holds.\n const beforeAuthorityEntry = staleEpoch(deps)\n if (beforeAuthorityEntry !== undefined) return beforeAuthorityEntry\n deps.hooks?.beforeCommitAuthorityEntry?.()\n const authority = { leaseId: job.leaseId, epoch: deps.epoch }\n const authorityHooks = {\n ...(deps.hooks?.afterFinalAuthorityCompare === undefined\n ? {}\n : { afterFinalAuthorityCompare: deps.hooks.afterFinalAuthorityCompare }),\n ...(deps.hooks?.mutationLockTakeoverMs === undefined\n ? {}\n : { mutationLockTakeoverMs: deps.hooks.mutationLockTakeoverMs }),\n }\n try {\n return withCurrentWriterAuthority(\n deps.knowledgeRoot,\n authority,\n () => {\n /**\n * CR-09: the committing transition and the durable intent are the first writes of\n * the held section, not the last writes before it. A superseded writer is refused\n * by the entry ladder above and therefore cannot publish either, so no intent can\n * exist that was not authored under live, exact authority. Both use the\n * within-held forms: re-entering withCurrentWriterAuthority here would open a\n * second connection against the BEGIN IMMEDIATE this callback already runs under.\n */\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot: deps.knowledgeRoot,\n candidateId: job.candidateId,\n authority,\n lifecycle: 'committing',\n authored: widenAuthoredDeltaCheckpoint(checkpoint),\n })\n const effect = (\n recordId: string,\n product: string,\n change: CurationEffect['change'],\n evidenceToken = job.payload.evidenceToken,\n ): CurationEffect => ({\n recordId, product, change, evidenceToken, atOrdinal: job.payload.buildOrdinal,\n })\n const publicationChange = (id: string, product: string): 'added' | 'confirmed' => {\n // A resumed publication by this same candidate is still its original Add.\n let existing: LoadedBundle | undefined\n try {\n const target = resolveProductQualifiedBundleDir({\n knowledgeRoot: deps.knowledgeRoot, product, recordId: id,\n })\n const loaded = loadBundle(target.dir)\n if (loaded.kind === 'loaded') existing = loaded.bundle\n } catch (error) {\n if (!(error instanceof BundleTargetResolutionError) || error.reason !== 'not-found') {\n throw error\n }\n }\n return existing === undefined || (\n existing.provenance.mode === 'run-linked'\n && existing.provenance.curationJobId === job.candidateId\n )\n ? 'added' : 'confirmed'\n }\n const effects: CurationEffect[] = [effect(bundleId, bundleProduct,\n draft !== undefined\n ? publicationChange(bundleId, bundleProduct)\n : delta.kind === 'Deprecate' ? 'deprecated' : 'confirmed',\n delta.kind === 'Confirm' ? delta.evidenceToken : job.payload.evidenceToken,\n )]\n if (delta.kind === 'Supersede') {\n effects.push({\n ...effect(delta.victimId, existingTargets.get(delta.victimId)!.product,\n 'superseded', delta.evidenceToken),\n byRecordId: bundleId,\n })\n }\n for (const prepared of preparedUnknownMintIntents) {\n const publication = prepared.publication\n const id = publication.kind === 'canonical' && 'id' in publication.outcome\n ? publication.outcome.id : undefined\n if (id !== undefined) {\n effects.push(effect(id, prepared.intent.scope.key,\n publicationChange(id, prepared.intent.scope.key)))\n }\n }\n for (const resolution of disposed.unknownResolutionIntents ?? []) {\n effects.push(effect(resolution.targetId, existingTargets.get(resolution.targetId)!.product,\n 'deprecated', asEvidenceToken(sha256hex(canonicalJson({\n token: job.payload.evidenceToken,\n event: resolution.reason,\n targetId: resolution.targetId,\n }))),\n ))\n }\n const curationObservation: CurationObservation = {\n schemaVersion: 2, sourceRunId: job.payload.sourceRunId,\n observationId: job.payload.attributingObservationId,\n originalDeltaKind: originalDispositionDelta(disposed).kind,\n appliedDeltaKind: delta.kind, disposition: disposed.kind,\n ...(disposed.kind === 'downgraded' ? { downgradeReason: disposed.reason } : {}), effects,\n }\n writeCommitIntent(deps.knowledgeRoot, {\n schemaVersion: COMMIT_INTENT_SCHEMA_VERSION,\n candidateId: job.candidateId,\n bundleId,\n deltaKind: delta.kind,\n ...(mutationTarget(delta) === undefined\n ? {}\n : { targetRecordId: mutationTarget(delta) }),\n epoch: deps.epoch,\n observation: curationObservation,\n })\n deps.hooks?.afterIntentWritten?.()\n let convertedConfirm = false\n let confirmedEventDuplicate = false\n let measurementAppendDuplicate = false\n let tailMutationAppended = false\n let freshlyPublished = false\n let promotionHoldReason: PromotionGateHoldReason | undefined\n let promotionPath: PromotionPath | undefined\n const config = storeConfig(deps, productKey, job.leaseId)\n if (preparedPublication !== undefined) {\n const published = finalizePreparedPublicationWithinCurrentAuthority(\n deps,\n job.leaseId,\n preparedPublication,\n )\n if (published.kind === 'identity-collision') {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation)\n return {\n kind: 'failed',\n reason: 'identity-collision',\n collisionReason: published.reason,\n }\n }\n if (published.kind === 'already-exists') {\n const existingTarget = resolveProductQualifiedBundleDir({\n knowledgeRoot: deps.knowledgeRoot,\n product: productKey,\n recordId: published.id,\n })\n bundleDir = existingTarget.dir\n bundleProduct = existingTarget.product\n const existingConfig = storeConfig(\n deps,\n existingTarget.product,\n job.leaseId,\n )\n const capableEnrichment =\n delta.kind === 'Add'\n && checkpoint.authorship.path !== 'deterministic-fallback'\n && draft !== undefined\n ? {\n summary: draft.summary,\n body: draft.body,\n authorship: checkpoint.authorship,\n }\n : undefined\n const appended = capableEnrichment === undefined\n ? appendOutcomeEvent(\n existingConfig,\n published.id,\n confirmedEvent(job, delta),\n )\n : appendOutcomeEventWithEnrichment(\n existingConfig,\n published.id,\n confirmedEvent(job, delta),\n capableEnrichment,\n )\n const failure = appendFailure(appended)\n if (failure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, failure.kind !== 'failed')\n return failure\n }\n if (\n appended.kind === 'duplicate'\n && (!('enriched' in appended) || appended.enriched === false)\n ) {\n const hasDeterministicTail =\n disposed.measurementAppend !== undefined\n || (disposed.kind === 'apply' && disposed.bornActive === true)\n || (\n deps.profile.mode === 'drain-to-active'\n && !(disposed.kind === 'apply' && disposed.bornActive === true)\n )\n || (disposed.unknownMintIntents?.length ?? 0) > 0\n || (disposed.unknownResolutionIntents?.length ?? 0) > 0\n if (!hasDeterministicTail) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, false)\n return { kind: 'noop', reason: 'evidence-token-consumed' }\n }\n confirmedEventDuplicate = true\n }\n convertedConfirm = true\n } else {\n bundleDir = published.dir\n bundleProduct = productKey\n freshlyPublished = true\n }\n\n if (\n deps.profile.mode === 'drain-to-active'\n && !(disposed.kind === 'apply' && disposed.bornActive === true)\n ) {\n /**\n * D-16: candidate is the exception bucket, not a waiting room. Admission\n * always writes candidate first; this immediate stricter re-check makes\n * clean facts active in the same drain. D-02 is flat: propose-only never\n * reaches this branch, and promote() re-evaluates posture at call time.\n */\n const promotionBundleDir = bundleDir\n const loaded = promotionBundleDir === undefined\n ? { kind: 'not-found' as const }\n : loadBundle(promotionBundleDir)\n if (loaded.kind !== 'loaded' || promotionBundleDir === undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, false)\n return { kind: 'failed', reason: 'append-failed' }\n }\n // 416-DOOR: door-3 gate\n const gate = evaluatePromotionGate(assemblePromotionGateInput({\n knowledgeRoot: deps.knowledgeRoot,\n bundleDir: promotionBundleDir,\n bundle: loaded.bundle,\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n ...(deps.resolvePromotionPosture === undefined\n ? {}\n : { resolvePromotionPosture: deps.resolvePromotionPosture }),\n }))\n if (gate.verdict === 'promote') {\n const promoted = appendOutcomeEvent(config, published.id, {\n // 416-DOOR: door-3 promoted\n type: 'promoted',\n evidenceToken: derivePromotedEvidenceToken(job.payload.evidenceToken),\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n })\n const promotedFailure = appendFailure(promoted)\n if (promotedFailure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, promotedFailure.kind !== 'failed')\n return promotedFailure\n }\n tailMutationAppended ||= promoted.kind === 'appended'\n const receipt = appendPromotionReceipt(config, published.id, {\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION,\n kind: 'promotion',\n candidateId: published.id,\n promotionPath: gate.promotionPath,\n citedReceiptDigests: gate.citedReceiptDigests,\n producedAtOrdinal: job.payload.buildOrdinal,\n producedBy: { jobId: job.candidateId },\n })\n const receiptFailure = appendFailure(receipt)\n if (receiptFailure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, receiptFailure.kind !== 'failed')\n return receiptFailure\n }\n tailMutationAppended ||= receipt.kind === 'appended'\n promotionPath = gate.promotionPath\n } else {\n promotionHoldReason = gate.reason\n }\n }\n\n const measurementValue = numericMeasurementSeed(job)\n if (\n draft?.kind === 'fact'\n && draft.subtype === 'measurement'\n && measurementValue !== undefined\n ) {\n const baseline = writeMeasurementBaseline(config, published.id, {\n mu0: measurementValue,\n sigma0: 0,\n n0: 1,\n openedAtOrdinal: job.payload.buildOrdinal,\n })\n const baselineFailure = appendFailure(baseline)\n if (baselineFailure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, baselineFailure.kind !== 'failed')\n return baselineFailure\n }\n tailMutationAppended ||= baseline.kind === 'appended'\n }\n\n if (disposed.kind === 'apply' && disposed.bornActive === true) {\n if (delta.kind !== 'Supersede') {\n throw new TypeError('born-active disposition requires a Supersede delta')\n }\n // §5.5.5 carve-out: a deterministic drift Supersede is exempt from candidate-gating\n // and born active. Only drain-to-active disposition can set this D-02 marker.\n const promoted = appendOutcomeEvent(config, published.id, {\n // 416-DOOR: born-active promoted\n type: 'promoted',\n evidenceToken: derivePromotedEvidenceToken(delta.evidenceToken),\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n })\n const promotedFailure = appendFailure(promoted)\n if (promotedFailure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, promotedFailure.kind !== 'failed')\n return promotedFailure\n }\n tailMutationAppended ||= promoted.kind === 'appended'\n }\n if (freshlyPublished) deps.hooks?.afterBundlePublished?.(published.id)\n if (disposed.kind === 'apply' && disposed.bornActive === true) {\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n knowledgeRoot: deps.knowledgeRoot,\n bundleId: published.id,\n product: bundleProduct,\n })\n }\n } else if (delta.kind === 'Confirm') {\n const target = existingTargets.get(delta.targetId)\n if (target === undefined) {\n throw new Error(`bundle target ${delta.targetId} was not resolved during preflight`)\n }\n const targetConfig = storeConfig(\n deps,\n target.product,\n job.leaseId,\n )\n const appended = appendOutcomeEvent(\n targetConfig,\n delta.targetId,\n confirmedEvent(job, delta, delta.evidenceToken),\n )\n const failure = appendFailure(appended)\n if (failure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, failure.kind !== 'failed')\n return failure\n }\n if (appended.kind === 'duplicate') {\n if (disposed.measurementAppend === undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, false)\n return { kind: 'noop', reason: 'evidence-token-consumed' }\n }\n confirmedEventDuplicate = true\n }\n } else if (delta.kind === 'Deprecate') {\n const target = existingTargets.get(delta.targetId)\n if (target === undefined) {\n throw new Error(`bundle target ${delta.targetId} was not resolved during preflight`)\n }\n const targetConfig = storeConfig(\n deps,\n target.product,\n job.leaseId,\n )\n const appended = appendOutcomeEvent(targetConfig, delta.targetId, {\n type: 'deprecated',\n evidenceToken: asEvidenceToken(job.payload.evidenceToken),\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n reason: delta.reason,\n })\n const failure = appendFailure(appended)\n if (failure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, failure.kind !== 'failed')\n return failure\n }\n }\n\n if (disposed.measurementAppend !== undefined) {\n const { victimId, observation } = disposed.measurementAppend\n const victim = existingTargets.get(victimId)\n if (victim === undefined) {\n throw new Error(`bundle target ${victimId} was not resolved during preflight`)\n }\n const measurementConfig = storeConfig(\n deps,\n victim.product,\n job.leaseId,\n )\n const appended = appendMeasurementObservationOnce(\n measurementConfig,\n victim,\n observation,\n )\n const failure = appendFailure(appended)\n if (failure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, failure.kind !== 'failed')\n return failure\n }\n measurementAppendDuplicate = appended.kind === 'duplicate'\n tailMutationAppended ||= appended.kind === 'appended'\n }\n\n const canonicalConfig = storeConfig(\n deps,\n bundleProduct,\n job.leaseId,\n )\n for (const relation of relationRows) {\n const appended = appendRelation(canonicalConfig, bundleId, relation)\n const failure = appendFailure(appended)\n if (failure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, failure.kind !== 'failed')\n return failure\n }\n tailMutationAppended ||= appended.kind === 'appended'\n }\n\n if (delta.kind === 'Supersede') {\n const victim = existingTargets.get(delta.victimId)\n if (victim === undefined) {\n throw new Error(`bundle target ${delta.victimId} was not resolved during preflight`)\n }\n const victimConfig = storeConfig(\n deps,\n victim.product,\n job.leaseId,\n )\n const superseded = appendOutcomeEvent(victimConfig, delta.victimId, {\n type: 'superseded',\n evidenceToken: delta.evidenceToken,\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n byRecordId: bundleId,\n })\n const supersededFailure = appendFailure(superseded)\n if (supersededFailure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, supersededFailure.kind !== 'failed')\n return supersededFailure\n }\n tailMutationAppended ||= superseded.kind === 'appended'\n const closeToken = asEvidenceToken(\n sha256hex(canonicalJson({ token: delta.evidenceToken, event: 'window-close' })),\n )\n const closed = appendOutcomeEvent(victimConfig, delta.victimId, {\n type: 'window-close',\n evidenceToken: closeToken,\n curationJobId: job.candidateId,\n buildOrdinal: job.payload.buildOrdinal,\n closedAtOrdinal: job.payload.buildOrdinal,\n })\n const closeFailure = appendFailure(closed)\n if (closeFailure !== undefined) {\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, true, closeFailure.kind !== 'failed')\n return closeFailure\n }\n tailMutationAppended ||= closed.kind === 'appended'\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n knowledgeRoot: deps.knowledgeRoot,\n bundleId: delta.victimId,\n product: victim.product,\n })\n }\n\n const evidenceTokenConsumed =\n confirmedEventDuplicate\n && !tailMutationAppended\n && (\n disposed.measurementAppend === undefined\n || measurementAppendDuplicate\n )\n && (disposed.unknownMintIntents?.length ?? 0) === 0\n && (disposed.unknownResolutionIntents?.length ?? 0) === 0\n if (evidenceTokenConsumed) {\n // A completed replay must not rewrite an unchanged FTS projection.\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, false)\n return { kind: 'noop', reason: 'evidence-token-consumed' }\n }\n\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(deps.priors === undefined ? {} : { priors: deps.priors }),\n knowledgeRoot: deps.knowledgeRoot,\n bundleId,\n product: bundleProduct,\n })\n\n if (disposed.firstSeenRegistration !== undefined) {\n recordFirstSeenBundle(deps.drainState, disposed.firstSeenRegistration, bundleId)\n }\n\n for (const prepared of preparedUnknownMintIntents) {\n const failure = commitUnknownMintIntentWithinCurrentAuthority(deps, job, prepared)\n if (failure !== undefined) return failure\n }\n for (const intent of disposed.unknownResolutionIntents ?? []) {\n const target = existingTargets.get(intent.targetId)\n if (target === undefined) {\n throw new Error(`bundle target ${intent.targetId} was not resolved during preflight`)\n }\n const failure = commitUnknownResolutionIntent(deps, job, intent, target)\n if (failure !== undefined) return failure\n }\n deps.hooks?.afterIndexApplied?.(bundleId)\n finishCommitWithinCurrentAuthority(deps, job, curationObservation, false)\n\n const result: CommittedBundleResult = {\n bundleId,\n bundleDir: bundleDir ?? '',\n deltaKind: delta.kind,\n ...(promotionHoldReason === undefined ? {} : { promotionHoldReason }),\n ...(promotionPath === undefined ? {} : { promotionPath }),\n }\n if (convertedConfirm && disposed.kind !== 'downgraded') {\n return { kind: 'converted-confirm', ...result }\n }\n return disposed.kind === 'downgraded'\n ? { kind: 'downgraded', reason: disposed.reason, original: disposed.original, ...result }\n : { kind: 'applied', ...result }\n },\n authorityHooks,\n )\n } catch (error) {\n if (error instanceof WriterAuthorityLostError) {\n return { kind: 'abandoned-stale-epoch', observedEpoch: error.observedEpoch }\n }\n throw error\n }\n } finally {\n if (preparedPublication !== undefined) {\n discardPreparedPublication(preparedPublication)\n }\n for (const prepared of preparedUnknownMintIntents) {\n discardPreparedPublication(prepared.publication)\n }\n rmSync(preflightDir, { recursive: true, force: true })\n }\n}\n","import {\n canonicalJson,\n decideMeasurementDrift,\n isReplayableActionShape,\n parseProcedureBody,\n foldMeasurements,\n normalizeAnchor,\n supersessionKey as schemaSupersessionKey,\n type Anchor,\n type BundleDraft,\n type BundleStatus,\n type Delta,\n type DeltaOrigin,\n type DistilledObservation,\n type MeasurementObservation,\n type ProcedureBodyPayload,\n type RecordId,\n type ScopeKey,\n type TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport {\n deriveBundleTrust,\n loadBundle,\n readMeasurements,\n type LoadedBundle,\n} from '../bundle-read.js'\nimport { enumerateBundleDirs } from '../bundle-scan.js'\nimport { snapshotTrustPriors } from '../promotion-gate-input.js'\nimport type { AuthoredDeltaCheckpoint, DispositionProfile } from './author-contract.js'\nimport {\n SCOPE_BURST_THRESHOLD,\n SCOPE_BURST_WINDOW_BUILDS,\n STABLE_WINDOW_BUILDS,\n THRASH_MAX_SUPERSESSIONS,\n THRASH_WINDOW_BUILDS,\n anchorScopeKey,\n foldFirstSeenAnchorsByScope,\n foldSupersessionLineage,\n scanCanonicalBundles,\n type CanonicalBundleSnapshot,\n} from './lineage-fold.js'\n\n/** Provisional §7.3.1 cap. Phase 379 may retune it only through an explicit constant edit. */\nexport const BLAST_RADIUS_MAX_SUPERSEDES_PER_ANCHOR_PER_DRAIN = 1\n\n// 407-04 (D-08/D-10): `canaryOutcomeObservationId` MOVED to `../serving/canary-observation-id.js`\n// and is re-exported here so every writer-side caller keeps its import path. The reader entry must\n// recompute the identity the writer stamped, and this file cannot be on that entry — it names the\n// bundle store and the curation queue payloads. One implementation, two\n// import paths: a second spelling would be a silent attribution failure, not a compile error.\nexport { canaryOutcomeObservationId } from '../serving/canary-observation-id.js'\n\n/**\n * 381-03 (PROC-01 D-02/D-03): the verified queue evidence the procedure-extraction wall\n * validates against. It is code-derived queue truth — distilled observations — never LLM text.\n */\nexport interface ProcedureDispositionEvidence {\n distilledObservations: readonly DistilledObservation[]\n}\n\nexport interface DispositionCandidateContext {\n anchors: readonly Anchor[]\n scope: ScopeKey\n buildOrdinal: number\n /** Durable queue address used as the observation's idempotency identity. */\n curationJobId?: string\n /** Original measurement seed value; prose authored by a model is never parsed for authority. */\n measurementValue?: string\n /** Present only for procedure-extraction jobs; procedure deltas fail closed without it. */\n procedureEvidence?: ProcedureDispositionEvidence\n}\n\nexport interface RelationIntent {\n type: 'proposed-supersession-of' | 'renamed-from'\n targetId: RecordId\n}\n\nexport interface DispositionDrainState {\n supersedesSeenByAnchorKey: Map<string, number>\n /** 379 Open Question 3: one canonical O(store) scan, lazily cached per drain. */\n canonicalBundles?: CanonicalBundleSnapshot[]\n /** Test-only observability seam for proving the canonical scan runs once. */\n onCanonicalBundleScan?: () => void\n /** Prevent two jobs in one drain from arming the same not-yet-published unknown. */\n unknownMarkersSeen?: Set<string>\n /** New anchor groups observed by earlier jobs after the once-per-drain snapshot. */\n firstSeenAnchorsByScope?: Map<string, Map<string, {\n buildOrdinal: number\n recordId?: RecordId\n }>>\n}\n\nexport interface FirstSeenRegistration {\n scopeKey: string\n supersessionKey: string\n buildOrdinal: number\n}\n\nexport interface UnknownMintIntent {\n kind: 'thrash' | 'scope-burst'\n marker: string\n triggerKey: string\n scope: ScopeKey\n windowOpenOrdinal: number\n windowCloseOrdinal: number\n evidenceRecordIds: RecordId[]\n includeCommittedBundle: boolean\n firstSeenCount?: number\n}\n\nexport interface UnknownResolutionIntent {\n targetId: RecordId\n reason: 'thrash-stable-window'\n}\n\nexport interface DisposeDeltaInput {\n delta: Delta\n checkpoint: AuthoredDeltaCheckpoint\n profile: DispositionProfile\n knowledgeRoot: string\n priors?: TrustPriorTable\n /**\n * Verified queue evidence needed for anchor and new-ordinal checks. Optional only for the\n * non-mutating delta shapes; Add and Supersede fail closed when it is absent.\n */\n candidate?: DispositionCandidateContext\n drainState: DispositionDrainState\n}\n\nexport type DispositionOutcome =\n | {\n kind: 'apply'\n delta: Delta\n relationIntents?: RelationIntent[]\n bornActive?: true\n measurementAppend?: { victimId: RecordId; observation: MeasurementObservation }\n unknownMintIntents?: UnknownMintIntent[]\n unknownResolutionIntents?: UnknownResolutionIntent[]\n firstSeenRegistration?: FirstSeenRegistration\n }\n | {\n kind: 'downgraded'\n delta: Delta\n reason: string\n original: Delta\n relationIntents?: RelationIntent[]\n measurementAppend?: { victimId: RecordId; observation: MeasurementObservation }\n unknownMintIntents?: UnknownMintIntent[]\n unknownResolutionIntents?: UnknownResolutionIntent[]\n firstSeenRegistration?: FirstSeenRegistration\n }\n | { kind: 'requeue-resynthesis'; reason: string }\n | { kind: 'noop'; reason: string }\n\n/** Classification observation only: disposal remains the sole policy decision. */\nexport function originalDispositionDelta(disposed: Extract<DispositionOutcome, { delta: Delta }>): Delta {\n return disposed.kind === 'downgraded' ? disposed.original : disposed.delta\n}\n\ninterface BundleTruth {\n dir: string\n bundle: LoadedBundle\n status: BundleStatus\n openedAtOrdinal: number\n currentOrdinal: number\n}\n\ntype TruthLookup = (id: RecordId) => BundleTruth | undefined\n\ntype CheckFailure =\n | { kind: 'downgrade'; reason: string; fallback?: 'drift-unknown' }\n | { kind: 'requeue'; reason: string }\n /**\n * REFUSE the delta outright rather than degrade it into something else.\n *\n * The arm carries the failing `recordId` because the other two do not need one and this one\n * does: the refusal is reported to a person who addressed a specific record, and \"the citation\n * check failed\" without saying which id it failed on is an answer they cannot act on. It\n * carries the `condition` for the same reason one level down — which of the four ways the\n * store cannot stand behind that id fired.\n */\n | {\n kind: 'refuse'\n reason: string\n recordId: RecordId\n condition: CitedIdIntegrityCondition\n }\n\ntype CheckVerdict = { kind: 'pass' } | CheckFailure\n\ninterface EvaluationState {\n renameBridge?: RelationIntent\n blastRadiusAnchorKey?: string\n unknownMintIntents?: UnknownMintIntent[]\n unknownResolutionIntents?: UnknownResolutionIntent[]\n firstSeenRegistration?: FirstSeenRegistration\n}\n\nconst PASS: CheckVerdict = { kind: 'pass' }\n\nfunction sameScope(left: ScopeKey, right: ScopeKey): boolean {\n return left.tier === right.tier && left.key === right.key\n}\n\nfunction sameAnchor(left: Anchor, right: Anchor): boolean {\n return canonicalJson(normalizeAnchor(left)) === canonicalJson(normalizeAnchor(right))\n}\n\nfunction primaryAnchor(anchors: readonly Anchor[]): Anchor | undefined {\n return anchors[0]\n}\n\nfunction deltaTargetIds(delta: Delta): RecordId[] {\n const ids = new Set<RecordId>(delta.citedIds)\n switch (delta.kind) {\n case 'Confirm':\n case 'Deprecate':\n ids.add(delta.targetId)\n break\n case 'Supersede':\n ids.add(delta.victimId)\n break\n case 'MintUnknown':\n for (const id of delta.conflict.recordIds) ids.add(id)\n break\n case 'Add':\n case 'Noop':\n break\n }\n return [...ids]\n}\n\nfunction truthLookup(knowledgeRoot: string, priors?: TrustPriorTable): TruthLookup {\n const cache = new Map<RecordId, BundleTruth | undefined>()\n return (id) => {\n if (cache.has(id)) return cache.get(id)\n\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded' || loaded.bundle.manifest.id !== id) continue\n // BundleTruth consumes lifecycle and validity ordinals only, never numerical trust.\n // Still carry the caller's snapshot so extending this projection cannot mix defaults.\n const trust = deriveBundleTrust(loaded.bundle, priors)\n const truth: BundleTruth = {\n dir: entry.dir,\n bundle: loaded.bundle,\n status: trust.status,\n openedAtOrdinal: trust.validity.openedAtOrdinal,\n currentOrdinal:\n trust.validity.closedAtOrdinal ?? trust.validity.openedAtOrdinal,\n }\n cache.set(id, truth)\n return truth\n }\n\n cache.set(id, undefined)\n return undefined\n }\n}\n\nfunction canonicalBundles(input: DisposeDeltaInput): readonly CanonicalBundleSnapshot[] {\n if (input.drainState.canonicalBundles === undefined) {\n input.drainState.onCanonicalBundleScan?.()\n // The lineage scan projects status/events/identity only; no numerical trust enters checks.\n input.drainState.canonicalBundles = scanCanonicalBundles(input.knowledgeRoot)\n }\n return input.drainState.canonicalBundles\n}\n\nfunction flowMarker(bundle: CanonicalBundleSnapshot): string | undefined {\n const primary = bundle.anchors[0]\n return primary?.t === 'flow' ? primary.name : undefined\n}\n\nfunction unresolvedUnknownsWithPrefix(\n input: DisposeDeltaInput,\n prefix: string,\n): CanonicalBundleSnapshot[] {\n return canonicalBundles(input).filter((bundle) =>\n bundle.kind === 'unknown'\n && bundle.status !== 'deprecated'\n && bundle.status !== 'superseded'\n && flowMarker(bundle)?.startsWith(prefix) === true,\n )\n}\n\nfunction unknownMarkerAlreadyArmed(input: DisposeDeltaInput, marker: string): boolean {\n if (input.drainState.unknownMarkersSeen?.has(marker) === true) return true\n return canonicalBundles(input).some((bundle) =>\n bundle.kind === 'unknown'\n && flowMarker(bundle) === marker,\n )\n}\n\nfunction armUnknownMarker(input: DisposeDeltaInput, marker: string): void {\n input.drainState.unknownMarkersSeen ??= new Set<string>()\n input.drainState.unknownMarkersSeen.add(marker)\n}\n\nfunction pushUnknownMint(state: EvaluationState, intent: UnknownMintIntent): void {\n state.unknownMintIntents = [...(state.unknownMintIntents ?? []), intent]\n}\n\nfunction pushUnknownResolution(\n state: EvaluationState,\n intent: UnknownResolutionIntent,\n): void {\n state.unknownResolutionIntents = [...(state.unknownResolutionIntents ?? []), intent]\n}\n\n/**\n * D-07/D-08: the tripping Supersede remains the applied write. The unresolved\n * unknown is a second deterministic commit intent; it suppresses serving later,\n * never this writer path.\n */\nfunction armThrashTripAndClosure(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n state: EvaluationState,\n): void {\n const buildOrdinal = input.candidate?.buildOrdinal\n if (buildOrdinal === undefined) return\n const bundles = canonicalBundles(input)\n\n if (input.delta.kind === 'Supersede' && input.profile.mode === 'drain-to-active') {\n const victim = lookup(input.delta.victimId)\n if (victim === undefined) return\n const victimAnchors = victim.bundle.frontmatter.anchors.map(\n ({ normalized }) => normalized,\n )\n const triggerKey = schemaSupersessionKey(victimAnchors)\n const folded = foldSupersessionLineage(bundles, {\n windowBuilds: THRASH_WINDOW_BUILDS,\n asOfBuildOrdinal: buildOrdinal,\n }).get(triggerKey)\n const depthAfterCommit = (folded?.supersededDepthInWindow ?? 0) + 1\n if (depthAfterCommit < THRASH_MAX_SUPERSESSIONS) return\n\n const prefix = `thrash:${triggerKey}:window:`\n if (unresolvedUnknownsWithPrefix(input, prefix).length > 0) return\n const windowOpenOrdinal = folded?.windowOpenOrdinal\n ?? Math.max(1, buildOrdinal - THRASH_WINDOW_BUILDS + 1)\n const marker = `${prefix}${windowOpenOrdinal}`\n if (unknownMarkerAlreadyArmed(input, marker)) return\n\n pushUnknownMint(state, {\n kind: 'thrash',\n marker,\n triggerKey,\n scope: input.delta.scope,\n windowOpenOrdinal,\n windowCloseOrdinal: buildOrdinal,\n evidenceRecordIds: [\n ...(folded?.chainRecordIds ?? []),\n input.delta.victimId,\n ].filter((id, index, values) => values.indexOf(id) === index).sort(),\n includeCommittedBundle: true,\n })\n armUnknownMarker(input, marker)\n return\n }\n\n if (input.delta.kind !== 'Confirm') return\n const target = lookup(input.delta.targetId)\n if (target === undefined) return\n const targetAnchors = target.bundle.frontmatter.anchors.map(\n ({ normalized }) => normalized,\n )\n const triggerKey = schemaSupersessionKey(targetAnchors)\n const folded = foldSupersessionLineage(bundles, {\n windowBuilds: Number.MAX_SAFE_INTEGER,\n asOfBuildOrdinal: buildOrdinal,\n }).get(triggerKey)\n const latest = folded?.latestSupersessionOrdinal\n if (latest === undefined || buildOrdinal - latest < STABLE_WINDOW_BUILDS) return\n\n for (const unknown of unresolvedUnknownsWithPrefix(input, `thrash:${triggerKey}:window:`)) {\n pushUnknownResolution(state, {\n targetId: unknown.recordId,\n reason: 'thrash-stable-window',\n })\n }\n}\n\nfunction createdAnchors(delta: Delta): readonly Anchor[] | undefined {\n if (delta.kind === 'Add') return delta.bundle.anchors\n if (delta.kind === 'Supersede') return delta.newBundle.anchors\n return undefined\n}\n\n/**\n * D-09/Open Question 3: evaluate the O(store) first-seen fold once per drain,\n * then increment it with committed jobs carried in drain state. Crossing the\n * provisional threshold arms one scope/window unknown without rewriting the\n * triggering Add or Supersede.\n */\nfunction armScopeBurst(\n input: DisposeDeltaInput,\n state: EvaluationState,\n): void {\n const anchors = createdAnchors(input.delta)\n const buildOrdinal = input.candidate?.buildOrdinal\n if (anchors === undefined || buildOrdinal === undefined) return\n\n const scopeKey = anchorScopeKey(anchors)\n if (scopeKey === undefined) return\n const candidateKey = schemaSupersessionKey(anchors)\n const bundles = canonicalBundles(input)\n const matchingCanonical = bundles.filter((bundle) =>\n bundle.kind !== 'unknown'\n && schemaSupersessionKey(bundle.anchors) === candidateKey,\n )\n const replayedCandidate = matchingCanonical.find((bundle) =>\n input.candidate?.curationJobId !== undefined\n && bundle.curationJobId === input.candidate.curationJobId,\n )\n if (matchingCanonical.some((bundle) => bundle !== replayedCandidate)) return\n const baselineBundles = replayedCandidate === undefined\n ? bundles\n : bundles.filter((bundle) => bundle.recordId !== replayedCandidate.recordId)\n\n input.drainState.firstSeenAnchorsByScope ??= new Map()\n const entries = input.drainState.firstSeenAnchorsByScope.get(scopeKey) ?? new Map()\n input.drainState.firstSeenAnchorsByScope.set(scopeKey, entries)\n if (entries.has(candidateKey)) return\n\n const baseline = foldFirstSeenAnchorsByScope(baselineBundles, {\n windowBuilds: SCOPE_BURST_WINDOW_BUILDS,\n asOfBuildOrdinal: buildOrdinal,\n }).get(scopeKey)\n const windowOpenOrdinal = baseline?.windowOpenOrdinal\n ?? Math.max(1, buildOrdinal - SCOPE_BURST_WINDOW_BUILDS + 1)\n const inWindowEntries = [...entries.entries()].filter(\n ([, entry]) => entry.buildOrdinal >= windowOpenOrdinal,\n )\n const countBefore = (baseline?.firstSeenCount ?? 0) + inWindowEntries.length\n entries.set(candidateKey, {\n buildOrdinal,\n ...(replayedCandidate === undefined ? {} : { recordId: replayedCandidate.recordId }),\n })\n state.firstSeenRegistration = {\n scopeKey,\n supersessionKey: candidateKey,\n buildOrdinal,\n }\n const countAfter = countBefore + 1\n if (countBefore > SCOPE_BURST_THRESHOLD || countAfter <= SCOPE_BURST_THRESHOLD) return\n\n const marker = `scope-burst:${scopeKey}:window:${windowOpenOrdinal}`\n if (unknownMarkerAlreadyArmed(input, marker)) return\n pushUnknownMint(state, {\n kind: 'scope-burst',\n marker,\n triggerKey: scopeKey,\n scope: input.delta.scope,\n windowOpenOrdinal,\n windowCloseOrdinal: buildOrdinal,\n firstSeenCount: countAfter,\n evidenceRecordIds: [\n ...(baseline?.recordIds ?? []),\n ...inWindowEntries.flatMap(([, entry]) =>\n entry.recordId === undefined ? [] : [entry.recordId],\n ),\n ].filter((id, index, values) => values.indexOf(id) === index).sort(),\n includeCommittedBundle: true,\n })\n armUnknownMarker(input, marker)\n}\n\ninterface MeasurementDisposition {\n input: DisposeDeltaInput\n measurementAppend?: { victimId: RecordId; observation: MeasurementObservation }\n confirmedDriftSupersede: boolean\n}\n\n/**\n * RATIFICATION A6: non-numeric measurement values retain the existing inequality-supersede\n * semantics outside the drift tree. Otherwise string-valued measurements could never widen.\n */\nfunction finiteMeasurementValue(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/**\n * Mechanism #9: discipline measurement Confirm/Supersede deltas against canonical bundle truth\n * before the six existing checks compose their final verdict.\n */\nfunction disposeMeasurementDrift(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n): MeasurementDisposition {\n const delta = input.delta\n if (delta.kind !== 'Confirm' && delta.kind !== 'Supersede') {\n return { input, confirmedDriftSupersede: false }\n }\n const victimId = delta.kind === 'Confirm' ? delta.targetId : delta.victimId\n\n const victim = lookup(victimId)\n if (\n victim === undefined\n || victim.bundle.frontmatter.kind !== 'fact'\n || victim.bundle.frontmatter.subtype !== 'measurement'\n ) {\n return { input, confirmedDriftSupersede: false }\n }\n\n const value = finiteMeasurementValue(input.candidate?.measurementValue)\n if (value === undefined) {\n return { input, confirmedDriftSupersede: false }\n }\n if (input.candidate?.curationJobId === undefined) {\n throw new TypeError('numeric measurement disposition requires a durable curation job id')\n }\n\n const measurements = readMeasurements(victim.dir)\n if (measurements === undefined) {\n throw new TypeError('numeric measurement disposition requires a stored baseline')\n }\n const observation: MeasurementObservation = {\n value,\n buildOrdinal: input.candidate.buildOrdinal,\n evidenceToken: delta.evidenceToken,\n curationJobId: input.candidate.curationJobId,\n }\n const consumed = measurements.observations.find(\n (candidate) =>\n candidate.evidenceToken === observation.evidenceToken\n && candidate.curationJobId === observation.curationJobId,\n )\n if (consumed !== undefined && canonicalJson(consumed) !== canonicalJson(observation)) {\n throw new TypeError('measurement observation identity resolved to different canonical bytes')\n }\n const observations = consumed === undefined\n ? [...measurements.observations, observation]\n : measurements.observations\n const decision = decideMeasurementDrift({\n baseline: measurements.baseline,\n state: foldMeasurements(measurements.baseline, observations),\n windowBuilds: { observations },\n })\n\n if (delta.kind === 'Confirm') {\n // Confirm carries observation authority but no replacement draft. Keep accumulating canonical\n // evidence so a later measurement Supersede can realize a confirmed regime change.\n return {\n input,\n measurementAppend: { victimId, observation },\n confirmedDriftSupersede: false,\n }\n }\n\n if (decision.decision === 'supersede') {\n return { input, confirmedDriftSupersede: true }\n }\n\n // Pitfall 5: a widen emits no superseded event and therefore never feeds the thrash counter.\n const confirm: Delta = {\n kind: 'Confirm',\n ...envelope(delta),\n targetId: victimId,\n evidenceToken: delta.evidenceToken,\n }\n return {\n input: { ...input, delta: confirm },\n measurementAppend: { victimId, observation },\n confirmedDriftSupersede: false,\n }\n}\n\n/**\n * Every way `checkCitedIdIntegrity` can decide this store cannot stand behind a cited id.\n *\n * The registry exists so the count stops being something a comment or a corpus has to keep in\n * step. Round 2 measured what happens when it is not one: the check's second return is a\n * three-way disjunction, the corpus and the doc comment both said \"three conditions\", and\n * carving `scope-mismatch` out of the refusal for every origin left 3 files / 70 tests green.\n * A fifth member added here is a compile error at `citedIdIntegrityFailure`'s derivation and at\n * the corpus's `satisfies Record<CitedIdIntegrityCondition, …>` fixture table.\n */\nexport const CITED_ID_INTEGRITY_CONDITIONS = [\n 'not-a-persisted-neighbor',\n 'missing-from-disk',\n 'deprecated',\n 'scope-mismatch',\n] as const\n\nexport type CitedIdIntegrityCondition = (typeof CITED_ID_INTEGRITY_CONDITIONS)[number]\n\n/**\n * The typed refusal a USER-authored delta receives when its cited-id integrity check fails.\n *\n * Thrown rather than returned, and out of the check funnel rather than out of the commit, so it\n * fires before any canonical byte moves for this delta: `disposeDelta` runs `checkCitedIdIntegrity`\n * first of the six §7.3.1 checks, ahead of every append, projection and promotion.\n * `applyReview`'s `commitAndPublish` catches it, restores the proposal to pending and rethrows,\n * which is how the caller gets a typed answer instead of a receipt for work nobody did.\n *\n * WHAT MAKES \"NOTHING MOVED\" TRUE, and it is not this sentence. The previous version of this\n * comment asserted whole-store neutrality as free-standing prose, naming no mechanism, and the\n * round-2 verifier measured that claim FALSE: the delta had already reached disposition through\n * `knowledge-store.ts`'s bridge, which materialized a claimed curation candidate on disk before\n * `commitWithProfile` ever called into the commit, and the throw left it there for the next\n * drain's reconcile to requeue (CR-02″). Two mechanisms now establish the claim, and each of them\n * reds if it is removed:\n *\n * 1. `bridgeDelta` is WRITE-FREE (`curator/knowledge-store.ts`). It computes the candidate's\n * address and materializes nothing, so a check that throws at any position has nothing to\n * leave behind. Reintroducing its two write statements reds the case in (2).\n * 2. `review/__tests__/apply-review.test.ts` asserts `hashTree(knowledgeRoot)` and the tree's\n * full entry listing — QUEUE TREE INCLUDED — are identical across a refused `accept`, with\n * a potency control proving the digest is falsifiable over that exact root.\n *\n * The scope of the guarantee is the knowledge root. The writer lease's own fencing state\n * (`.epoch`, `.writer-authority.sqlite`) advances on acquisition regardless of what the caller\n * then does, which is why the case above holds the lease across its measurement rather than\n * excusing those two names.\n */\nexport class UserDeltaCitationIntegrityError extends Error {\n constructor(\n readonly recordId: RecordId,\n readonly deltaKind: Delta['kind'],\n readonly condition: CitedIdIntegrityCondition,\n ) {\n super(\n `The record ${recordId} this ${deltaKind} cites is one this store cannot stand behind ` +\n `(${condition}), so the instruction is REFUSED rather than converted into minted ` +\n 'content. Nothing was committed and the record is unchanged.',\n )\n this.name = 'UserDeltaCitationIntegrityError'\n }\n}\n\n/**\n * What a cited-id-integrity failure falls back to, decided by WHO authored the delta.\n *\n * Total over the origin vocabulary by construction: the `satisfies` below makes a fifth origin\n * member a compile error AT THIS TABLE, so no future member can silently inherit a fallback\n * nobody chose for it. That is the whole mechanism — the class of defect this closes is \"a guard\n * scoped to the members somebody happened to think of\", and the only fix that class cannot\n * reopen is handing the enumeration to something that cannot forget a member.\n *\n * WHY each member is what it is:\n *\n * agent — the curation pipeline proposed this change from its own observations. A broken\n * citation means the pipeline reasoned over a record that no longer stands, and\n * degrading its proposal into a clarification candidate a person can adjudicate is\n * exactly the right answer. This is the drain path's long-standing behaviour and it\n * is PRESERVED unchanged.\n * import — bulk-ingested content, pipeline-authored in every sense that matters here: nobody\n * is waiting on a typed answer for one record, and a clarification candidate is the\n * reviewable artifact the importer wants.\n * system — maintenance deltas (rollback's Deprecate, the canary Confirm). Same reasoning:\n * machine-authored content, and a refusal would turn a maintenance sweep into a hard\n * failure over one stale citation.\n * user — a human INSTRUCTION about records that already exist. There is no content here to\n * degrade: minting from it publishes a verbatim clone of the cited record under a\n * fresh content address as a `candidate`, which serving re-admits — so an `accept`\n * over a record the same person had already rejected RESURRECTED the fact they\n * removed and reported success (CR-02′). The store cannot grant the instruction, so\n * it says so.\n */\nconst CITED_ID_INTEGRITY_FALLBACK_BY_ORIGIN = {\n agent: 'mint-unknown',\n import: 'mint-unknown',\n system: 'mint-unknown',\n user: 'refuse',\n} as const satisfies Record<DeltaOrigin, 'mint-unknown' | 'refuse'>\n\n/**\n * The ONE site the fallback mapping is consulted, shared by every failure condition the check\n * has. Deliberately not inlined at either return site: the check fails for the four reasons\n * `CITED_ID_INTEGRITY_CONDITIONS` enumerates, and they are ONE failure domain (\"this delta cites\n * something this store cannot stand behind\"). Discriminating at one of them and not the others is\n * the same one-axis-out mistake as scoping a guard to one verb of a set.\n *\n * The `condition` is carried THROUGH this site rather than derived here, and that is what keeps\n * the funnel a funnel: the caller knows which disjunct fired, this function knows what to do\n * about it, and neither has to learn the other's job.\n */\nfunction citedIdIntegrityFailure(\n delta: Delta,\n recordId: RecordId,\n condition: CitedIdIntegrityCondition,\n): CheckFailure {\n return CITED_ID_INTEGRITY_FALLBACK_BY_ORIGIN[delta.origin] === 'refuse'\n ? { kind: 'refuse', reason: 'cited-id-integrity', recordId, condition }\n : { kind: 'downgrade', reason: 'cited-id-integrity' }\n}\n\nfunction checkCitedIdIntegrity(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n): CheckVerdict {\n const persistedNeighbors = new Set<RecordId>(input.checkpoint.neighborIds)\n for (const id of deltaTargetIds(input.delta)) {\n if (!persistedNeighbors.has(id)) {\n return citedIdIntegrityFailure(input.delta, id, 'not-a-persisted-neighbor')\n }\n const truth = lookup(id)\n // The second return's three disjuncts, named in the order they are tested. Splitting them\n // only this far is deliberate: the ANSWER stays one answer (the funnel above), and all that\n // is recovered here is which fact produced it — which the refusal then has to say out loud,\n // because \"tombstoned or unresolvable\" was false for the third disjunct and sent operators\n // looking for a tombstone a scope-mismatched record does not have.\n if (truth === undefined) {\n return citedIdIntegrityFailure(input.delta, id, 'missing-from-disk')\n }\n if (truth.status === 'deprecated') {\n return citedIdIntegrityFailure(input.delta, id, 'deprecated')\n }\n if (!sameScope(truth.bundle.frontmatter.scope, input.delta.scope)) {\n return citedIdIntegrityFailure(input.delta, id, 'scope-mismatch')\n }\n }\n return PASS\n}\n\nfunction hasSharedAnchor(\n left: readonly Anchor[],\n right: readonly Anchor[],\n type: Anchor['t'],\n): boolean {\n return left\n .filter((anchor) => anchor.t === type)\n .some((anchor) =>\n right.some((candidate) => candidate.t === type && sameAnchor(anchor, candidate)),\n )\n}\n\n/**\n * 379 D-22 / RATIFICATION A3: `renamed-from` is the concrete realization of\n * memory.md §9.6's alias edge. It already round-trips from relations.json into\n * graph_edges and is traversed by retrieval expansion, so no synonym edge type\n * is added.\n */\nfunction renameBridge(\n newAnchors: readonly Anchor[],\n victimAnchors: readonly Anchor[],\n victimId: RecordId,\n): RelationIntent | undefined {\n const next = primaryAnchor(newAnchors)\n const previous = primaryAnchor(victimAnchors)\n if (next?.t !== 'el' || previous?.t !== 'el') return undefined\n const normalizedNext = normalizeAnchor(next)\n const normalizedPrevious = normalizeAnchor(previous)\n if (normalizedNext.t !== 'el' || normalizedPrevious.t !== 'el') return undefined\n if (\n normalizedNext.role !== normalizedPrevious.role\n || normalizedNext.name === normalizedPrevious.name\n ) {\n return undefined\n }\n if (\n !hasSharedAnchor(newAnchors, victimAnchors, 'page')\n || !hasSharedAnchor(newAnchors, victimAnchors, 'selector')\n ) {\n return undefined\n }\n return { type: 'renamed-from', targetId: victimId }\n}\n\nfunction candidateMatchesBundle(\n input: DisposeDeltaInput,\n anchors: readonly Anchor[],\n scope: ScopeKey,\n): boolean {\n if (!sameScope(scope, input.delta.scope)) return false\n if (input.candidate === undefined) return false\n const claimedPrimary = primaryAnchor(anchors)\n const verifiedPrimary = primaryAnchor(input.candidate.anchors)\n return (\n claimedPrimary !== undefined\n && verifiedPrimary !== undefined\n && sameAnchor(claimedPrimary, verifiedPrimary)\n )\n}\n\nfunction checkAnchorConsistency(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n state: EvaluationState,\n): CheckVerdict {\n if (input.delta.kind === 'Add') {\n return candidateMatchesBundle(input, input.delta.bundle.anchors, input.delta.bundle.scope)\n ? PASS\n : { kind: 'downgrade', reason: 'anchor-consistency' }\n }\n if (input.delta.kind !== 'Supersede') return PASS\n if (\n !candidateMatchesBundle(\n input,\n input.delta.newBundle.anchors,\n input.delta.newBundle.scope,\n )\n ) {\n return { kind: 'downgrade', reason: 'anchor-consistency' }\n }\n\n const victim = lookup(input.delta.victimId)\n if (victim === undefined) {\n return { kind: 'downgrade', reason: 'anchor-consistency' }\n }\n const victimAnchors = victim.bundle.frontmatter.anchors.map(({ normalized }) => normalized)\n const nextPrimary = primaryAnchor(input.delta.newBundle.anchors)\n const previousPrimary = primaryAnchor(victimAnchors)\n if (nextPrimary === undefined || previousPrimary === undefined) {\n return { kind: 'downgrade', reason: 'anchor-consistency' }\n }\n if (sameAnchor(nextPrimary, previousPrimary)) return PASS\n\n const bridge = renameBridge(\n input.delta.newBundle.anchors,\n victimAnchors,\n input.delta.victimId,\n )\n if (bridge === undefined) {\n return { kind: 'downgrade', reason: 'anchor-consistency' }\n }\n state.renameBridge = bridge\n return PASS\n}\n\nfunction checkSupersessionKey(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n state: EvaluationState,\n): CheckVerdict {\n if (input.delta.kind !== 'Supersede') return PASS\n const victim = lookup(input.delta.victimId)\n if (victim === undefined || input.candidate === undefined) {\n return { kind: 'downgrade', reason: 'supersession-key' }\n }\n\n const victimAnchors = victim.bundle.frontmatter.anchors.map(({ normalized }) => normalized)\n if (\n state.renameBridge === undefined\n && schemaSupersessionKey(input.delta.newBundle.anchors)\n !== schemaSupersessionKey(victimAnchors)\n ) {\n return { kind: 'downgrade', reason: 'supersession-key' }\n }\n if (input.candidate.buildOrdinal <= victim.openedAtOrdinal) {\n return { kind: 'downgrade', reason: 'supersession-key' }\n }\n return PASS\n}\n\n/**\n * Who may tombstone a record this store is currently standing behind, decided per origin.\n *\n * MECHANISM, stated so the claim can be reded rather than believed: totality is the `satisfies`\n * clause below — a fifth member of `DeltaOrigin` is a compile error AT THIS TABLE — and the\n * BEHAVIOUR of each member is pinned by the DELTA_ORIGINS walk in disposition.test.ts, whose\n * expectations are declared independently of this literal. Neither half is prose: dropping a\n * member fails `tsc`, flipping a member's value reds a named row.\n *\n * This replaces a hand-picked single-member origin comparison — one literal origin named inline,\n * every other member admitted by omission — that sat eleven lines from\n * `CITED_ID_INTEGRITY_FALLBACK_BY_ORIGIN`, whose own rationale calls `import` machine-authored.\n * The file's two origin discriminations therefore disagreed about the same word. They now share\n * one idiom and one vocabulary, which is what stops them drifting apart again.\n *\n * The retired comparison is DESCRIBED rather than quoted on purpose: a `grep -c` for its literal\n * text is a live guard against it coming back, and a quotation kept here for colour would disarm\n * that guard permanently (387-17 D-4).\n *\n * WHY each member is what it is:\n *\n * agent — the autonomy floor itself: a model may PROPOSE removing standing knowledge but may\n * not perform it, so the Deprecate degrades into a reviewable candidate. Long-standing\n * behaviour, PRESERVED unchanged.\n * import — machine-authored by the same reasoning the fallback table above applies to it\n * (\"bulk-ingested content, pipeline-authored in every sense that matters here\"). An\n * importer that emits a Deprecate is a pipeline nominating a removal, which is\n * precisely what the floor exists to hold. This is the one BEHAVIOUR change here, and\n * it is latent: no production site mints `origin: 'import'` today, which is the\n * condition under which the old member-pick would have been wrong silently.\n * system — mechanical maintenance deltas, and they must pass. `appendInverseDeprecate` in\n * rollback.ts is the written case: its comment records that `agent` \"would be\n * downgraded for an active target, while `user` would incorrectly make this lifecycle\n * choice sovereign and permanent\", and it throws if disposition does not return\n * `apply`. Downgrading `system` here would turn every rollback into a hard failure.\n * user — the human decision the review verbs exist to carry. `reject` and `forget` emit\n * user-origin Deprecates over active records and depend on reaching `apply`;\n * downgrading them would silently convert a person's removal into a candidate the\n * store keeps serving.\n *\n * NOT the same question as `AUTHORED_CHECKPOINT_ORIGIN_ADMISSION` in author-contract.ts, which\n * asks which origins may arrive as DRAIN-AUTHORED curator output. `system` is allowed here and\n * rejected there without contradiction: rollback and the canary reach `disposeDelta` through\n * in-process checkpoints (`maintenanceCheckpoint`, `bridgeDelta`), never through the drain's\n * authored-checkpoint recovery boundary.\n */\nconst AUTONOMOUS_DEPRECATE_BY_ORIGIN = {\n agent: 'downgrade',\n import: 'downgrade',\n system: 'allow',\n user: 'allow',\n} as const satisfies Record<DeltaOrigin, 'downgrade' | 'allow'>\n\nfunction checkAutonomousDeprecate(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n): CheckVerdict {\n if (input.delta.kind !== 'Deprecate') return PASS\n if (AUTONOMOUS_DEPRECATE_BY_ORIGIN[input.delta.origin] === 'allow') return PASS\n return lookup(input.delta.targetId)?.status === 'active'\n ? { kind: 'downgrade', reason: 'autonomous-deprecate' }\n : PASS\n}\n\nfunction checkCompareAndSet(\n input: DisposeDeltaInput,\n lookup: TruthLookup,\n): CheckVerdict {\n for (const precondition of input.checkpoint.preconditions) {\n const current = lookup(precondition.recordId)\n if (\n current === undefined\n || current.status !== precondition.observedStatus\n || current.currentOrdinal !== precondition.observedOrdinal\n ) {\n return { kind: 'requeue', reason: 'compare-and-set' }\n }\n }\n return PASS\n}\n\nfunction checkBlastRadius(\n input: DisposeDeltaInput,\n state: EvaluationState,\n): CheckVerdict {\n if (input.delta.kind !== 'Supersede') return PASS\n const candidateScope = input.candidate?.scope ?? input.delta.newBundle.scope\n if (!sameScope(candidateScope, input.delta.scope)) {\n return { kind: 'downgrade', reason: 'blast-radius-scope' }\n }\n if (input.profile.mode === 'propose-only') return PASS\n\n const anchorKey = schemaSupersessionKey(\n input.candidate?.anchors ?? input.delta.newBundle.anchors,\n )\n const seen = input.drainState.supersedesSeenByAnchorKey.get(anchorKey) ?? 0\n if (seen >= BLAST_RADIUS_MAX_SUPERSEDES_PER_ANCHOR_PER_DRAIN) {\n return {\n kind: 'downgrade',\n reason: 'blast-radius-cap',\n fallback: 'drift-unknown',\n }\n }\n state.blastRadiusAnchorKey = anchorKey\n return PASS\n}\n\nfunction envelope(delta: Delta): Pick<Delta, 'origin' | 'scope' | 'citedIds'> & {\n precondition?: Delta['precondition']\n authorship?: Delta['authorship']\n} {\n return {\n origin: delta.origin,\n scope: delta.scope,\n citedIds: [...delta.citedIds],\n ...(delta.precondition === undefined ? {} : { precondition: [...delta.precondition] }),\n ...(delta.authorship === undefined ? {} : { authorship: delta.authorship }),\n }\n}\n\nfunction addCandidate(delta: Extract<Delta, { kind: 'Supersede' }>): Delta {\n return {\n kind: 'Add',\n ...envelope(delta),\n bundle: delta.newBundle,\n }\n}\n\nfunction mintUnknown(\n delta: Delta,\n reason: string,\n conflictKind: 'contradiction' | 'drift' | 'clarification',\n): Delta {\n return {\n kind: 'MintUnknown',\n ...envelope(delta),\n citedIds: reason === 'cited-id-integrity' ? [] : [...delta.citedIds],\n conflict: {\n recordIds: reason === 'cited-id-integrity' ? [] : deltaTargetIds(delta),\n kind: conflictKind,\n },\n }\n}\n\nfunction downgraded(\n delta: Delta,\n failure: Extract<CheckFailure, { kind: 'downgrade' }>,\n): DispositionOutcome {\n const fallback =\n failure.fallback === 'drift-unknown'\n ? mintUnknown(delta, failure.reason, 'drift')\n : delta.kind === 'Supersede'\n ? addCandidate(delta)\n : mintUnknown(delta, failure.reason, 'clarification')\n return {\n kind: 'downgraded',\n delta: fallback,\n reason: failure.reason,\n original: delta,\n }\n}\n\nfunction procedureDraft(delta: Delta): BundleDraft | undefined {\n if (delta.kind === 'Add' && delta.bundle.kind === 'procedure') return delta.bundle\n if (delta.kind === 'Supersede' && delta.newBundle.kind === 'procedure') {\n return delta.newBundle\n }\n return undefined\n}\n\ninterface CoveredProcedureStep {\n step: ProcedureBodyPayload['steps'][number]\n observation: DistilledObservation\n}\n\n/**\n * §7.1 candidacy mapping: the emit fold's step natural key is instruction text, which may\n * legitimately repeat within a flow. Resolve coverage by a contiguous ordinal window with\n * per-position instruction equality instead of grouping by text, which falsely rejected valid\n * repeated instructions (G6/WR-05). Candidate starts are sorted so the lowest matching window\n * wins deterministically; no complete window means missing PASS evidence and fails closed.\n */\nfunction coveredProcedureSteps(\n payload: ProcedureBodyPayload,\n observations: readonly DistilledObservation[],\n): CoveredProcedureStep[] | undefined {\n const byOrdinal = new Map<number, DistilledObservation>()\n for (const observation of observations) {\n if (byOrdinal.has(observation.step.ordinal)) return undefined\n byOrdinal.set(observation.step.ordinal, observation)\n }\n\n const candidateStarts = [...byOrdinal.keys()].sort((left, right) => left - right)\n for (const startOrdinal of candidateStarts) {\n const covered: CoveredProcedureStep[] = []\n for (const [index, step] of payload.steps.entries()) {\n const observation = byOrdinal.get(startOrdinal + index)\n if (observation === undefined || observation.step.naturalKey !== step.instruction) {\n break\n }\n covered.push({ step, observation })\n }\n if (covered.length === payload.steps.length) return covered\n }\n return undefined\n}\n\n/**\n * Preserve the established non-contiguous rejection when the full instruction sequence exists\n * in ordinal order but only with gaps. Coverage itself is still granted exclusively by the\n * contiguous-window matcher above.\n */\nfunction hasOrderedNonContiguousProcedureSpan(\n payload: ProcedureBodyPayload,\n observations: readonly DistilledObservation[],\n): boolean {\n const [firstStep] = payload.steps\n if (firstStep === undefined) return false\n\n const ordered = [...observations].sort(\n (left, right) => left.step.ordinal - right.step.ordinal,\n )\n for (let startIndex = 0; startIndex < ordered.length; startIndex += 1) {\n const start = ordered[startIndex]!\n if (start.step.naturalKey !== firstStep.instruction) continue\n\n let observationIndex = startIndex + 1\n let previousOrdinal = start.step.ordinal\n let matched = true\n let hasGap = false\n for (const step of payload.steps.slice(1)) {\n let observation: DistilledObservation | undefined\n while (observationIndex < ordered.length) {\n const candidate = ordered[observationIndex++]!\n if (\n candidate.step.ordinal > previousOrdinal &&\n candidate.step.naturalKey === step.instruction\n ) {\n observation = candidate\n break\n }\n }\n if (observation === undefined) {\n matched = false\n break\n }\n if (observation.step.ordinal !== previousOrdinal + 1) hasGap = true\n previousOrdinal = observation.step.ordinal\n }\n if (matched && hasGap) return true\n }\n return false\n}\n\n/**\n * 381-03 (PROC-01): the deterministic procedure-extraction wall — D-02 candidacy (contiguous\n * verified-PASS span with resolved elements + coherent anchors) and Pitfall 6 replayability\n * (the ONE shared schema exclusion list, never a fork). Any failed check disposes the delta\n * as a structured Noop with a machine-readable reason; nothing here reads LLM prose for\n * authority — the body decode is fail-closed and evidence comes from the durable queue payload.\n */\nfunction disposeProcedureExtraction(input: DisposeDeltaInput): string | undefined {\n const draft = procedureDraft(input.delta)\n if (draft === undefined) return undefined\n const evidence = input.candidate?.procedureEvidence\n if (evidence === undefined) return 'procedure-evidence-missing'\n\n const payload = parseProcedureBody(draft.body)\n if (payload === undefined) return 'procedure-body-unparseable'\n\n const covered = coveredProcedureSteps(payload, evidence.distilledObservations)\n if (covered === undefined) {\n return hasOrderedNonContiguousProcedureSpan(payload, evidence.distilledObservations)\n ? 'procedure-span-non-contiguous'\n : 'procedure-step-coverage'\n }\n for (let index = 1; index < covered.length; index += 1) {\n const previous = covered[index - 1]!.observation.step.ordinal\n if (covered[index]!.observation.step.ordinal !== previous + 1) {\n return 'procedure-span-non-contiguous'\n }\n }\n if (covered.some(({ observation }) => observation.element === undefined)) {\n return 'procedure-step-unresolved-element'\n }\n\n if (draft.anchors.filter((anchor) => anchor.t === 'flow').length !== 1) {\n return 'procedure-flow-anchor'\n }\n const coveredSurfaces = new Set(\n covered.flatMap(({ observation }) =>\n observation.surface === undefined ? [] : [observation.surface.naturalKey],\n ),\n )\n const pageRoutes = [\n ...draft.anchors.flatMap((anchor) => (anchor.t === 'page' ? [anchor.route] : [])),\n ...payload.steps.map((step) => step.guard.pageAnchor.route),\n ]\n if (pageRoutes.some((route) => !coveredSurfaces.has(route))) {\n return 'procedure-page-anchor-disjoint'\n }\n\n for (const { step } of covered) {\n const shapeKeys = [\n ...Object.keys(step.action.targets),\n ...Object.keys(step.action.values),\n ]\n if (!isReplayableActionShape(step.action.type, shapeKeys)) {\n return 'procedure-non-replayable-action'\n }\n }\n\n const secretReject = procedureSecretLiteralReject(covered)\n if (secretReject !== undefined) return secretReject\n\n const bindingReject = procedureBindingIntegrityReject(payload)\n if (bindingReject !== undefined) return bindingReject\n\n return undefined\n}\n\n/**\n * 2026-10-15 (441-64, WR-C01): a declared secret is the `[secret:NAME]` marker or an unexpanded\n * `{{secret:...}}` template; a test variable is a `{{env:...}}` template. The emit fold labels\n * value sources on this same contract; any such observed value surviving as a committed literal\n * is a D-03 structural reject — the secret param type only protects values that stay `{ param }`\n * referenced (T-381-02/07).\n */\nconst MASKED_SECRET_VALUE_PATTERN = /\\[secret:\\w+\\]|\\{\\{\\s*secret:/\nconst TEST_VARIABLE_VALUE_PATTERN = /\\{\\{\\s*env:/\n\n/**\n * D-03 rule 2: a literal whose own content matches the masking contract fails closed.\n * 2026-10-15 (441-25, D-28): the field a value was typed into never makes it secret.\n */\nfunction procedureSecretLiteralReject(\n covered: readonly CoveredProcedureStep[],\n): string | undefined {\n for (const { step } of covered) {\n for (const slot of Object.values(step.action.values)) {\n if (typeof slot !== 'string') continue\n if (MASKED_SECRET_VALUE_PATTERN.test(slot)) return 'procedure-masked-secret-literal'\n if (TEST_VARIABLE_VALUE_PATTERN.test(slot)) return 'procedure-test-variable-literal'\n }\n }\n return undefined\n}\n\n/**\n * D-03 rule 1: every `{ param }` ref must resolve to a declared parameter, and every\n * declared parameter must be referenced by at least one step value slot. (Param types\n * outside the closed string/number/boolean/secret union are unreachable here by\n * construction — `parseProcedureBody` already refused them at the decode wall.)\n */\nfunction procedureBindingIntegrityReject(\n payload: ProcedureBodyPayload,\n): string | undefined {\n const declared = new Set(payload.parameters.map(({ name }) => name))\n const referenced = new Set<string>()\n for (const step of payload.steps) {\n for (const slot of Object.values(step.action.values)) {\n if (typeof slot !== 'object' || !('param' in slot)) continue\n if (!declared.has(slot.param)) return 'procedure-param-undeclared'\n referenced.add(slot.param)\n }\n }\n if (payload.parameters.some(({ name }) => !referenced.has(name))) {\n return 'procedure-param-unreferenced'\n }\n return undefined\n}\n\n/**\n * Run memory.md §7.3.1's six checks in order. The function is deliberately synchronous: every\n * decision is made from the persisted checkpoint and canonical bundle tree, never an index row.\n */\nexport function disposeDelta(input: DisposeDeltaInput): DispositionOutcome {\n const priors = snapshotTrustPriors(input.priors)\n const procedureReject = disposeProcedureExtraction(input)\n if (procedureReject !== undefined) {\n return { kind: 'noop', reason: procedureReject }\n }\n const lookup = truthLookup(input.knowledgeRoot, priors)\n const measurement = disposeMeasurementDrift(input, lookup)\n const dispositionInput = measurement.input\n const state: EvaluationState = {}\n const checks = [\n () => checkCitedIdIntegrity(dispositionInput, lookup),\n () => checkAnchorConsistency(dispositionInput, lookup, state),\n () => checkSupersessionKey(dispositionInput, lookup, state),\n () => checkAutonomousDeprecate(dispositionInput, lookup),\n () => checkCompareAndSet(dispositionInput, lookup),\n () => checkBlastRadius(dispositionInput, state),\n ]\n\n for (const check of checks) {\n const verdict = check()\n if (verdict.kind === 'requeue') {\n return { kind: 'requeue-resynthesis', reason: verdict.reason }\n }\n if (verdict.kind === 'refuse') {\n // No outcome arm carries a refusal on purpose: `DispositionOutcome` is the vocabulary of\n // things that CHANGE the store, and a refusal changes nothing. Throwing keeps the caller\n // from having to remember to check for a fifth arm — the mistake that produced the defect\n // this refusal exists for.\n throw new UserDeltaCitationIntegrityError(\n verdict.recordId,\n dispositionInput.delta.kind,\n verdict.condition,\n )\n }\n if (verdict.kind === 'downgrade') {\n return {\n ...downgraded(dispositionInput.delta, verdict),\n ...(measurement.measurementAppend === undefined\n ? {}\n : { measurementAppend: measurement.measurementAppend }),\n }\n }\n }\n\n if (dispositionInput.delta.kind === 'Noop') return { kind: 'noop', reason: 'delta-noop' }\n if (\n dispositionInput.profile.mode === 'propose-only'\n && (\n dispositionInput.delta.kind === 'Supersede'\n || dispositionInput.delta.kind === 'Deprecate'\n )\n ) {\n // D-02 flat invariant: propose-only has zero exceptions. Even deterministically confirmed\n // drift remains a candidate plus proposed-supersession relation in CI and cloud contexts.\n const fallback = dispositionInput.delta.kind === 'Supersede'\n ? addCandidate(dispositionInput.delta)\n : mintUnknown(dispositionInput.delta, 'propose-only', 'clarification')\n if (fallback.kind === 'Add') {\n armScopeBurst({ ...dispositionInput, delta: fallback }, state)\n }\n return {\n kind: 'downgraded',\n delta: fallback,\n reason: 'propose-only',\n original: dispositionInput.delta,\n ...(dispositionInput.delta.kind === 'Supersede'\n ? {\n relationIntents: [\n {\n type: 'proposed-supersession-of' as const,\n targetId: dispositionInput.delta.victimId,\n },\n ...(state.renameBridge === undefined ? [] : [state.renameBridge]),\n ],\n }\n : {}),\n ...(state.unknownMintIntents === undefined\n ? {}\n : { unknownMintIntents: state.unknownMintIntents }),\n ...(state.firstSeenRegistration === undefined\n ? {}\n : { firstSeenRegistration: state.firstSeenRegistration }),\n }\n }\n\n armThrashTripAndClosure(dispositionInput, lookup, state)\n armScopeBurst(dispositionInput, state)\n if (state.blastRadiusAnchorKey !== undefined) {\n const seen = input.drainState.supersedesSeenByAnchorKey.get(state.blastRadiusAnchorKey) ?? 0\n input.drainState.supersedesSeenByAnchorKey.set(state.blastRadiusAnchorKey, seen + 1)\n }\n return {\n kind: 'apply',\n delta: dispositionInput.delta,\n ...(state.renameBridge === undefined ? {} : { relationIntents: [state.renameBridge] }),\n ...(measurement.measurementAppend === undefined\n ? {}\n : { measurementAppend: measurement.measurementAppend }),\n ...(state.unknownMintIntents === undefined\n ? {}\n : { unknownMintIntents: state.unknownMintIntents }),\n ...(state.unknownResolutionIntents === undefined\n ? {}\n : { unknownResolutionIntents: state.unknownResolutionIntents }),\n ...(state.firstSeenRegistration === undefined\n ? {}\n : { firstSeenRegistration: state.firstSeenRegistration }),\n ...(measurement.confirmedDriftSupersede\n && dispositionInput.profile.mode === 'drain-to-active'\n ? { bornActive: true as const }\n : {}),\n }\n}\n","// The canary observation identity, in a module the READ face may import (Phase 407, D-08/D-10).\n//\n// MOVED from `curator/disposition.ts` rather than copied. The writer stamps this id onto the\n// outcome event it appends and the reader recomputes it to find that event again, so a second\n// spelling would be a silent attribution failure — a run's canary line would render \"not yet\n// attributed\" forever while its evidence sat on disk — rather than a compile error. There is\n// exactly one implementation and `curator/disposition.ts` re-exports it, so every writer-side\n// caller is unchanged.\n//\n// WHY IT HAD TO MOVE. `disposition.ts` imports the bundle store, the egress checkpoint and the\n// curation queue payloads; a reader-entry module that reached into it would pull the whole write\n// path behind the physically read-only entry. This file imports schema types and two pure\n// helpers, and nothing else.\n\nimport { canonicalJson, sha256hex } from '@vostride/agent-qa-schema'\nimport type { CanaryOutcome } from '@vostride/agent-qa-schema'\n\n/**\n * D-22: bind one canary observation to the served candidate and attributed step. The schema\n * evidence-token recipe adds the exercised anchor and build ordinal; together those fields are\n * the complete replay identity required by §7.5.1.\n */\nexport function canaryOutcomeObservationId(\n outcome: Pick<\n CanaryOutcome,\n 'candidateId' | 'runId' | 'testId' | 'testIndex' | 'stepIndex'\n >,\n): string {\n return `canary-outcome:${sha256hex(canonicalJson({\n candidateId: outcome.candidateId,\n runId: outcome.runId,\n testId: outcome.testId,\n testIndex: outcome.testIndex,\n stepIndex: outcome.stepIndex,\n }))}`\n}\n","import { existsSync, readFileSync } from 'node:fs'\n\nimport {\n canonicalJson,\n asRecordId,\n type BundleKind,\n type CanaryOutcome,\n type ExecutionContext,\n type FactSubtype,\n type IndexEntry,\n type PromotionGateHoldReason,\n type PromotionPath,\n type ResolvePromotionPosture,\n type TrustPriorTable,\n type CurationSnapshot,\n type CurationSnapshotChange,\n} from '@vostride/agent-qa-schema'\nimport { foldCurationSnapshot, readCurationEffectsForRun } from './curation-snapshot.js'\n\nimport { openKnowledgeReader, type KnowledgeReader } from '../index-reader.js'\nimport {\n indexDbPath,\n openIndexReaderConnection,\n readIndexMaintenanceState,\n} from '../index-open.js'\nimport { rebuildIndex, removeBundleProjectionRows } from '../index-rebuild.js'\nimport {\n acquireEmbedder,\n type AcquireEmbedderOutcome,\n} from '../embedder-acquire.js'\nimport { runKnowledgeGc } from '../gc.js'\nimport { readRebuildRequest } from '../rebuild-marker.js'\nimport { buildRetrievalQuery, type RetrievalQueryInput } from '../query-helper.js'\nimport { retrieve } from '../retrieve.js'\nimport {\n reconcileOnDrainStart,\n type ReconcileReport,\n} from '../journal/reconcile.js'\nimport type { CommitIntent } from '../journal/intent-journal.js'\nimport {\n acquireWriterLease,\n heartbeatLease,\n releaseLease,\n WriterAuthorityLostError,\n type CurrentWriterAuthority,\n type HeartbeatLeaseOutcome,\n type WriterLease,\n} from '../lease/writer-lease.js'\nimport {\n claimNextJob,\n countRemainingCurationWork,\n quarantineClaimed,\n requeueClaimed,\n type CurationQuarantineReason,\n type CurationRemainingWork,\n type ClaimedCurationJob,\n type ClaimNextJobOutcome,\n type MalformedClaimedCurationJob,\n} from '../queue/curation-queue.js'\nimport {\n canaryOutcomeContentAddress,\n readQueuedCanaryPayload,\n} from '../queue/canary-payload.js'\nimport {\n persistAuthoredCheckpoint,\n readJobState,\n writeJobState,\n writeJobStateWithinCurrentAuthority,\n} from '../queue/job-state.js'\nimport type { CurationCandidatePayload } from '../queue/queue-payload.js'\nimport {\n AUTHORED_CHECKPOINT_SCHEMA_VERSION,\n parseAuthoredCheckpoint,\n resolveDispositionProfile,\n sliceAuthoredCheckpoint,\n type AuthoredCheckpoint,\n type CurationJobView,\n type CuratorAuthor,\n type NeighborRecord,\n} from './author-contract.js'\nimport {\n applyIndexDeltaForBundle,\n commitCurationDelta,\n deriveIndexRowFromBundle,\n type CommitCurationOutcome,\n type EmptyDeltaCause,\n} from './commit.js'\nimport type { DispositionDrainState } from './disposition.js'\nimport { constructFallbackDeltas } from './fallback.js'\nimport { createLocalKnowledgeStore } from './knowledge-store.js'\nimport { snapshotTrustPriors } from '../promotion-gate-input.js'\nimport type { CanaryAuthorityHooks } from './knowledge-store.js'\nimport {\n runMaintenanceTail,\n type GcPassReport,\n type MaintenanceOperations,\n type WriterPassReport,\n} from './maintenance.js'\n\nexport type { GcPassReport, WriterPassReport } from './maintenance.js'\n\n/** Ratified M2 one-shot budget. A run's tail aborts an author request in flight at its end. */\nexport const DRAIN_BUDGET_MS = 60_000\n\n/** Provisional §7.4 cap over distinct search-before-create query targets. */\nexport const SEARCH_BEFORE_CREATE_MAX_QUERIES = 5\n\n/** Provisional 376 D-14 per-job breaker before a vector-deferred commit is forced. */\nexport const EMBED_CRASH_VECTORLESS_THRESHOLD = 2\n\nconst SEARCH_BEFORE_CREATE_RESULTS_PER_QUERY = 8\nconst SEARCH_BEFORE_CREATE_MAX_NEIGHBORS = 12\n\nexport type DrainFailureStage =\n | 'lease'\n | 'reconcile'\n | 'claim'\n | 'heartbeat'\n | 'job-state'\n | 'search'\n | 'author'\n | 'checkpoint'\n | 'commit'\n | 'quarantine'\n | 'requeue'\n | 'release'\n | 'writer-pass'\n | 'gc'\n\nexport interface DrainFailure {\n stage: DrainFailureStage\n message: string\n candidateId?: string\n}\n\n/**\n * A commit that decided there was nothing to apply. Legitimate reasons exist (evidence-token\n * dedup), so a noop is never a failure — but dropping it on the floor made live procedure\n * extraction die silently for 13 UAT runs (G-381-1). Visibility, never a gate.\n */\nexport interface DrainNoop {\n candidateId: string\n reason: string\n /**\n * 381-47: present only on delta-noop entries — distinguishes a defeated extraction\n * (`fallback-*`) from a deliberate authored Noop; benign dedup carries no cause.\n */\n emptyDeltaCause?: EmptyDeltaCause\n}\n\nexport interface DrainPromotionOutcome {\n candidateId: string\n promotionPath?: PromotionPath\n promotionHoldReason?: PromotionGateHoldReason\n}\n\ninterface DrainReportBase {\n /** Actual surviving effects for the requested run, also present on incomplete drains. */\n effects?: readonly CurationSnapshotChange[]\n /** Certified only after a complete drain; absent for historical missing receipts. */\n snapshot?: CurationSnapshot\n /**\n * The effects committed; only the projection over them failed, so `snapshot` is absent. Never a\n * failure: the drain stays complete and nothing is retried or refolded.\n */\n snapshotFoldFailed?: true\n jobsProcessed: number\n committed: number\n // 2026-10-19 (444.1-16, D-25): the canary evidence commits in `committed`; no bucket counts them.\n evidenceCommitted?: number\n /**\n * Committed deltas whose kind was `Deprecate` (388-02).\n *\n * OPTIONAL because the drain report is constructed by fault-injection fakes across four\n * packages and a required field would make every one of them a compile error over a number\n * they have no opinion about. The real drain always sets it, so a production report saying\n * `deprecated: 0` is a measurement rather than an absence — which is what the post-run\n * chain's notification (D-11) needs in order to tell a drain that deprecated nothing apart\n * from a drain that never ran at all.\n */\n deprecated?: number\n /** Optional for fault-injection fakes; the real drain always sets this measurement. */\n promotions?: readonly DrainPromotionOutcome[]\n downgraded: number\n withheld: number\n quarantined: number\n requeued: number\n failures: number\n failureDetails: DrainFailure[]\n noops: number\n noopDetails: DrainNoop[]\n reconcile: ReconcileReport | undefined\n writerPass: WriterPassReport\n gc: GcPassReport\n /** Visibility only: every durable disposition that still prevents queue completion. */\n remaining: number\n /** Durable remainder partition. The current writer's nonterminal claim is included. */\n remainingWork: CurationRemainingWork\n}\n\ninterface MutableDrainReport extends DrainReportBase {\n promotions: DrainPromotionOutcome[]\n evidenceCommitted: number\n}\n\nexport type DrainReport = DrainReportBase &\n (\n | { kind: 'drained' | 'aborted' }\n | { kind: 'handed-off'; holder: WriterLease }\n )\n\nexport type CurationDrainLifecycleEvent =\n | { readonly kind: 'job-claimed'; readonly candidateId: string }\n | { readonly kind: 'job-completed'; readonly candidateId: string }\n\n/**\n * Internal capability table used by focused fault-injection tests. Production callers omit it;\n * every default delegates directly to the shipped queue, lease, retrieval, commit, and rebuild\n * authorities.\n */\nexport interface DrainOperations extends MaintenanceOperations {\n acquireWriterLease: typeof acquireWriterLease\n heartbeatLease: typeof heartbeatLease\n releaseLease: typeof releaseLease\n reconcileOnDrainStart: typeof reconcileOnDrainStart\n claimNextJob: typeof claimNextJob\n quarantineClaimed: typeof quarantineClaimed\n requeueClaimed: typeof requeueClaimed\n readJobState: typeof readJobState\n writeJobState: typeof writeJobState\n persistAuthoredCheckpoint: typeof persistAuthoredCheckpoint\n openKnowledgeReader: typeof openKnowledgeReader\n buildRetrievalQuery: typeof buildRetrievalQuery\n retrieve: typeof retrieve\n commitCurationDelta: typeof commitCurationDelta\n /** The canonical commit already projects dense work as pending; the breaker selects this seam. */\n commitCurationDeltaVectorless: typeof commitCurationDelta\n hasIndexRow(knowledgeRoot: string, bundleId: string): boolean\n applyIndexDeltaForBundle: typeof applyIndexDeltaForBundle\n deriveIndexRowFromBundle: typeof deriveIndexRowFromBundle\n /** CR-02 takeover barriers for the canary branch; production omits them. */\n canaryAuthorityHooks?: CanaryAuthorityHooks\n}\n\nexport interface DrainOptions {\n /** A per-run reader request, independent of which queued jobs this drain claims. */\n sourceRunId?: string\n observationIds?: readonly string[]\n knowledgeRoot: string\n /** `unbounded` is reserved for a standing host whose process lifetime is the boundary. */\n budgetMs?: number | 'unbounded'\n /** Standing writer authority owned by the caller; drainQueue never mutates its lifecycle. */\n lease?: { leaseId: string; epoch: number }\n author: CuratorAuthor\n executionContext: ExecutionContext\n /** Host-resolved posture; daemon sessions pass worker-required capability here. */\n embeddingCapability?: AcquireEmbedderOutcome\n /** Built once per drain on the host; synchronous per candidate inside the gate. */\n resolvePromotionPosture?: ResolvePromotionPosture\n /** Already-resolved host snapshot; the host retains this data across queue retries. */\n priors?: TrustPriorTable\n /** Default inline preserves one-shot behavior; daemon sessions skip for their own cadence. */\n maintenance?: 'inline' | 'skip'\n signal?: AbortSignal\n /** Synchronous durable-boundary observer; daemon hosts append these facts before proceeding. */\n onJobLifecycle?: (event: CurationDrainLifecycleEvent) => void\n /** D-06 test seam. Production uses the one wall clock only at drain boundaries. */\n now?: () => number\n /** Fault-injection seam; production callers must omit it. */\n operations?: Partial<DrainOperations>\n}\n\nconst BUNDLE_KINDS = new Set<BundleKind>([\n 'fact',\n 'procedure',\n 'caution',\n 'unknown',\n 'policy',\n])\nconst FACT_SUBTYPES = new Set<FactSubtype>([\n 'selector',\n 'behavioral',\n 'navigational',\n 'measurement',\n 'content',\n])\n\nfunction hasIndexRow(knowledgeRoot: string, bundleId: string): boolean {\n if (!existsSync(indexDbPath(knowledgeRoot))) return false\n let reader: ReturnType<typeof openIndexReaderConnection> | undefined\n try {\n reader = openIndexReaderConnection(knowledgeRoot)\n return reader.db.prepare('SELECT 1 FROM records WHERE bundle_id = ?').get(bundleId)\n !== undefined\n } catch {\n return false\n } finally {\n reader?.db.close()\n }\n}\n\nconst DEFAULT_OPERATIONS: DrainOperations = {\n acquireWriterLease,\n heartbeatLease,\n releaseLease,\n reconcileOnDrainStart,\n claimNextJob,\n quarantineClaimed,\n requeueClaimed,\n readJobState,\n writeJobState,\n persistAuthoredCheckpoint,\n openKnowledgeReader,\n buildRetrievalQuery,\n retrieve,\n commitCurationDelta,\n commitCurationDeltaVectorless: commitCurationDelta,\n readRebuildRequest,\n readIndexMaintenanceState,\n acquireEmbedder,\n rebuildIndex,\n runKnowledgeGc,\n removeBundleProjectionRows,\n hasIndexRow,\n applyIndexDeltaForBundle,\n deriveIndexRowFromBundle,\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction readClaimedCanaryOutcome(\n claimed: MalformedClaimedCurationJob,\n): CanaryOutcome | undefined {\n try {\n const read = readQueuedCanaryPayload(\n JSON.parse(readFileSync(claimed.payloadPath, 'utf8')),\n )\n if (read.kind === 'refused') return undefined\n if (canaryOutcomeContentAddress(read.payload) !== claimed.candidateId) {\n return undefined\n }\n return {\n candidateId: asRecordId(read.payload.candidateId),\n runOutcome: read.payload.outcome,\n benefit: read.payload.benefit,\n stateValidity: read.payload.stateValidity,\n ...(read.payload.corpusDigest === undefined ? {} : { corpusDigest: read.payload.corpusDigest }),\n ...(read.payload.observedStateDigest === undefined ? {} : { observedStateDigest: read.payload.observedStateDigest }),\n ...(read.payload.ablation === undefined ? {} : { ablation: read.payload.ablation }),\n runId: read.payload.runId,\n testId: read.payload.testId,\n testIndex: read.payload.testIndex,\n buildOrdinal: read.payload.buildOrdinal,\n stepIndex: read.payload.stepIndex,\n briefDigest: read.payload.briefDigest,\n attribution: read.payload.attribution,\n exercisedAnchor: read.payload.exercisedAnchor,\n }\n } catch {\n return undefined\n }\n}\n\nfunction isEmbeddingCrash(error: unknown, seen = new Set<object>()): boolean {\n if (typeof error !== 'object' || error === null || seen.has(error)) return false\n seen.add(error)\n const value = error as { name?: unknown; message?: unknown; cause?: unknown }\n const attribution = `${String(value.name ?? '')} ${String(value.message ?? '')}`\n return /(?:embedder|embedding|embeddings|embedDocument|FloorEmbedding|NativeEmbedding)/i\n .test(attribution)\n || isEmbeddingCrash(value.cause, seen)\n}\n\nfunction emptyReport(): MutableDrainReport {\n return {\n jobsProcessed: 0,\n committed: 0,\n evidenceCommitted: 0,\n deprecated: 0,\n promotions: [],\n downgraded: 0,\n withheld: 0,\n quarantined: 0,\n requeued: 0,\n failures: 0,\n failureDetails: [],\n noops: 0,\n noopDetails: [],\n reconcile: undefined,\n writerPass: { kind: 'not-requested' },\n gc: { kind: 'not-run' },\n remaining: 0,\n remainingWork: { queued: 0, claimedNonterminal: 0, quarantined: 0 },\n }\n}\n\nfunction updateRemaining(\n report: DrainReportBase,\n knowledgeRoot: string,\n currentLeaseId?: string,\n): void {\n const remainingWork = countRemainingCurationWork(\n knowledgeRoot,\n currentLeaseId === undefined ? {} : { currentLeaseId },\n )\n report.remainingWork = remainingWork\n report.remaining =\n remainingWork.queued\n + remainingWork.claimedNonterminal\n + remainingWork.quarantined\n}\n\nfunction recordFailure(\n report: DrainReportBase,\n stage: DrainFailureStage,\n error: unknown,\n candidateId?: string,\n): void {\n report.failures += 1\n report.failureDetails.push({\n stage,\n message: errorMessage(error),\n ...(candidateId === undefined ? {} : { candidateId }),\n })\n}\n\nfunction jobView(\n payload: CurationCandidatePayload,\n fallbackExecutionContext: ExecutionContext,\n): CurationJobView {\n return {\n candidateId: payload.candidateId,\n kind: payload.kind,\n ...(payload.subtype === undefined ? {} : { subtype: payload.subtype }),\n ...(payload.rootCauseClass === undefined\n ? {}\n : { rootCauseClass: payload.rootCauseClass }),\n anchors: payload.anchors,\n summarySeed: payload.summarySeed,\n bodySeed: payload.bodySeed,\n distilledObservations: payload.distilledObservations,\n scope: payload.scope,\n buildOrdinal: payload.buildOrdinal,\n attributingObservationId: payload.attributingObservationId,\n executionContext: payload.executionContext ?? fallbackExecutionContext,\n }\n}\n\nfunction addTargetedQuery(\n queries: RetrievalQueryInput[],\n seen: Set<string>,\n query: RetrievalQueryInput,\n): void {\n if (queries.length >= SEARCH_BEFORE_CREATE_MAX_QUERIES) return\n const key = canonicalJson({ intent: query.intent, anchors: query.anchors })\n if (seen.has(key)) return\n seen.add(key)\n queries.push(query)\n}\n\nfunction targetedQueries(payload: CurationCandidatePayload): RetrievalQueryInput[] {\n const primary = payload.anchors[0]!\n const queries: RetrievalQueryInput[] = []\n const seen = new Set<string>()\n addTargetedQuery(queries, seen, {\n intent: payload.summarySeed,\n anchors: [primary],\n })\n\n for (const anchor of payload.anchors) {\n if (anchor.t === 'error') {\n addTargetedQuery(queries, seen, {\n intent: anchor.message,\n anchors: [primary, anchor],\n })\n } else if (anchor.t === 'flow') {\n addTargetedQuery(queries, seen, {\n intent: anchor.name,\n anchors: [primary, anchor],\n })\n }\n }\n for (const observation of payload.distilledObservations) {\n if (observation.error !== undefined) {\n addTargetedQuery(queries, seen, {\n intent: observation.error.naturalKey,\n anchors: [\n primary,\n { t: 'error', message: observation.error.naturalKey },\n ],\n })\n }\n if (observation.flow !== undefined) {\n addTargetedQuery(queries, seen, {\n intent: observation.flow.name,\n anchors: [primary, { t: 'flow', name: observation.flow.name }],\n })\n }\n }\n return queries\n}\n\nfunction retrievalOptions(\n payload: CurationCandidatePayload,\n embeddingCapability: AcquireEmbedderOutcome | undefined,\n) {\n return {\n n: SEARCH_BEFORE_CREATE_RESULTS_PER_QUERY,\n product: payload.scope.key,\n ...(payload.scope.tier === 'test' ? { testKey: payload.scope.key } : {}),\n ...(payload.scope.tier === 'suite' ? { suiteKey: payload.scope.key } : {}),\n includeSuperseded: true,\n ...(embeddingCapability === undefined ? {} : { embeddingCapability }),\n }\n}\n\nfunction neighborFromEntry(entry: IndexEntry, alias: number): NeighborRecord | undefined {\n if (!BUNDLE_KINDS.has(entry.kind as BundleKind) || entry.audit === undefined) return undefined\n const kind = entry.kind as BundleKind\n const observedOrdinal = entry.audit.closedAtOrdinal ?? entry.audit.openedAtOrdinal\n const base = {\n alias,\n recordId: entry.id,\n summary: entry.summary,\n anchors: entry.anchors,\n observedStatus: entry.audit.status,\n observedOrdinal,\n }\n if (kind === 'fact') {\n if (!FACT_SUBTYPES.has(entry.subtype as FactSubtype)) return undefined\n return { ...base, kind, subtype: entry.subtype as FactSubtype }\n }\n return { ...base, kind }\n}\n\nasync function searchBeforeCreate(\n operations: DrainOperations,\n payload: CurationCandidatePayload,\n knowledgeRoot: string,\n embeddingCapability: AcquireEmbedderOutcome | undefined,\n): Promise<NeighborRecord[]> {\n let reader: KnowledgeReader | undefined\n try {\n reader = operations.openKnowledgeReader(knowledgeRoot)\n const byRecordId = new Map<string, IndexEntry>()\n for (const query of targetedQueries(payload)) {\n // The explicit build call fixes normalization/query classification at this boundary; the\n // retrieve pipeline consumes the same structured input through its public entry point.\n operations.buildRetrievalQuery(query)\n const hits = await operations.retrieve(\n reader,\n query,\n retrievalOptions(payload, embeddingCapability),\n )\n for (const hit of hits) {\n if (!byRecordId.has(hit.id)) byRecordId.set(hit.id, hit)\n }\n }\n\n const neighbors: NeighborRecord[] = []\n for (const hit of byRecordId.values()) {\n const neighbor = neighborFromEntry(hit, neighbors.length + 1)\n if (neighbor !== undefined) neighbors.push(neighbor)\n if (neighbors.length >= SEARCH_BEFORE_CREATE_MAX_NEIGHBORS) break\n }\n return neighbors\n } finally {\n reader?.close()\n }\n}\n\nfunction checkpointFromAuthored(\n deltas: AuthoredCheckpoint['deltas'],\n authorship: AuthoredCheckpoint['authorship'],\n neighbors: readonly NeighborRecord[],\n): AuthoredCheckpoint {\n const seen = new Set<string>()\n const preconditions = deltas\n .flatMap((delta) => delta.precondition ?? [])\n .filter((cas) => {\n const key = canonicalJson(cas)\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n return parseAuthoredCheckpoint({\n schemaVersion: AUTHORED_CHECKPOINT_SCHEMA_VERSION,\n deltas,\n neighborIds: neighbors.map(({ recordId }) => recordId),\n preconditions,\n authorship,\n })\n}\n\nasync function authorCheckpoint(\n options: DrainOptions,\n operations: DrainOperations,\n job: ClaimedCurationJob,\n): Promise<AuthoredCheckpoint> {\n const view = jobView(job.payload, options.executionContext)\n const neighbors = await searchBeforeCreate(\n operations,\n job.payload,\n options.knowledgeRoot,\n options.embeddingCapability,\n )\n const outcome = await options.author(view, neighbors)\n if (outcome.kind === 'authored') {\n if (outcome.deltas.length === 0) {\n throw new Error('authored outcome must carry at least one delta')\n }\n return checkpointFromAuthored(outcome.deltas, outcome.authorship, neighbors)\n }\n\n const fallback = constructFallbackDeltas(view, neighbors, outcome.reason)\n if (fallback.length !== 1 || fallback[0] === undefined) {\n throw new Error('deterministic fallback must produce exactly one delta')\n }\n const authorship = fallback[0].authorship\n if (authorship === undefined || authorship.path !== 'deterministic-fallback') {\n throw new Error('deterministic fallback omitted its authorship stamp')\n }\n return checkpointFromAuthored(fallback, authorship, neighbors)\n}\n\nfunction claimedExecutionContext(\n claimed: ClaimNextJobOutcome,\n fallback: ExecutionContext,\n): ExecutionContext {\n return claimed.kind === 'claimed'\n ? claimed.payload.executionContext ?? fallback\n : fallback\n}\n\nfunction persistCheckpoint(\n operations: DrainOperations,\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n candidateId: string,\n checkpoint: AuthoredCheckpoint,\n): void {\n const persisted = operations.persistAuthoredCheckpoint({\n knowledgeRoot,\n candidateId,\n authority,\n authored: checkpoint,\n })\n if (persisted.kind !== 'persisted') {\n throw new Error('cannot persist authored checkpoint over malformed job state')\n }\n}\n\nfunction clearCheckpointAndRequeue(\n operations: DrainOperations,\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n job: ClaimedCurationJob,\n): number {\n return clearCandidateAndRequeue(\n operations,\n knowledgeRoot,\n authority,\n job.candidateId,\n )\n}\n\nfunction clearCandidateAndRequeue(\n operations: DrainOperations,\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n candidateId: string,\n): number {\n const state = operations.readJobState(knowledgeRoot, candidateId)\n operations.writeJobState({\n knowledgeRoot,\n candidateId,\n authority,\n lifecycle: 'queued',\n embedCrashCount: state.kind === 'parsed' ? state.state.embedCrashCount : 0,\n })\n const requeued = operations.requeueClaimed({\n knowledgeRoot,\n leaseId: authority.leaseId,\n authority,\n })\n if (!requeued.includes(candidateId)) {\n throw new Error(`failed candidate ${candidateId} was not requeued`)\n }\n return requeued.length\n}\n\nfunction quarantineMalformedClaim(\n report: DrainReportBase,\n operations: DrainOperations,\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n candidateId: string,\n reason: CurationQuarantineReason,\n): boolean {\n try {\n operations.quarantineClaimed({\n knowledgeRoot,\n leaseId: authority.leaseId,\n candidateId,\n authority,\n reason,\n })\n report.quarantined += 1\n return true\n } catch (error) {\n recordFailure(report, 'quarantine', error, candidateId)\n return false\n }\n}\n\nfunction preserveAuthoredCheckpointAndRequeue(\n operations: DrainOperations,\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n job: ClaimedCurationJob,\n checkpoint: AuthoredCheckpoint,\n embedCrashCount: number,\n failureLabel: string,\n): number {\n operations.writeJobState({\n knowledgeRoot,\n candidateId: job.candidateId,\n authority,\n lifecycle: 'authored',\n embedCrashCount,\n authored: checkpoint,\n })\n const requeued = operations.requeueClaimed({\n knowledgeRoot,\n leaseId: authority.leaseId,\n authority,\n })\n if (!requeued.includes(job.candidateId)) {\n throw new Error(`${failureLabel} candidate ${job.candidateId} was not requeued`)\n }\n return requeued.length\n}\n\nfunction incrementEmbedCrashAndRequeue(\n operations: DrainOperations,\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n job: ClaimedCurationJob,\n checkpoint: AuthoredCheckpoint,\n embedCrashCount: number,\n): number {\n return preserveAuthoredCheckpointAndRequeue(\n operations,\n knowledgeRoot,\n authority,\n job,\n checkpoint,\n embedCrashCount + 1,\n 'embed-crashed',\n )\n}\n\n/** A commit that landed a `Deprecate` delta retired a record; nothing else did. */\nfunction countDeprecation(report: DrainReportBase, deltaKind: string): void {\n if (deltaKind === 'Deprecate') report.deprecated = (report.deprecated ?? 0) + 1\n}\n\nfunction mapCommitOutcome(\n report: MutableDrainReport,\n outcome: CommitCurationOutcome,\n job: ClaimedCurationJob,\n operations: DrainOperations,\n options: DrainOptions,\n authority: CurrentWriterAuthority,\n): 'continue' | 'stop' {\n if ((outcome.kind === 'applied' || outcome.kind === 'converted-confirm' || outcome.kind === 'downgraded')\n && (outcome.promotionPath !== undefined || outcome.promotionHoldReason !== undefined)) {\n report.promotions.push({\n candidateId: job.candidateId,\n ...(outcome.promotionPath === undefined ? {} : { promotionPath: outcome.promotionPath }),\n ...(outcome.promotionHoldReason === undefined ? {} : { promotionHoldReason: outcome.promotionHoldReason }),\n })\n }\n switch (outcome.kind) {\n case 'applied':\n case 'converted-confirm':\n report.committed += 1\n countDeprecation(report, outcome.deltaKind)\n return 'continue'\n case 'downgraded':\n report.committed += 1\n report.downgraded += 1\n countDeprecation(report, outcome.deltaKind)\n return 'continue'\n case 'noop':\n // Counted and named, never fatal — the complete predicate must not gate on this.\n report.noops += 1\n report.noopDetails.push({\n candidateId: job.candidateId,\n reason: outcome.reason,\n ...(outcome.emptyDeltaCause === undefined\n ? {}\n : { emptyDeltaCause: outcome.emptyDeltaCause }),\n })\n return 'continue'\n case 'failed':\n recordFailure(report, 'commit', outcome.reason, job.candidateId)\n return 'continue'\n case 'abandoned-stale-epoch':\n recordFailure(\n report,\n 'commit',\n `writer epoch became stale (observed ${outcome.observedEpoch})`,\n job.candidateId,\n )\n return 'stop'\n case 'requeue-resynthesis':\n try {\n clearCheckpointAndRequeue(\n operations,\n options.knowledgeRoot,\n authority,\n job,\n )\n report.requeued += 1\n } catch (error) {\n recordFailure(report, 'requeue', error, job.candidateId)\n }\n // Fresh neighbors belong to the next drain; reclaiming immediately could livelock on the\n // same lexicographically-first candidate.\n return 'stop'\n }\n}\n\nfunction isSuccessfulTerminalCommitOutcome(outcome: CommitCurationOutcome): boolean {\n // These kinds return only after markDone for a non-deferred delta. `failed` also describes\n // branches that can exit before queue completion, so its name alone is not sufficient evidence\n // for a lifecycle fact.\n switch (outcome.kind) {\n case 'applied':\n case 'converted-confirm':\n case 'downgraded':\n case 'noop':\n return true\n case 'failed':\n case 'abandoned-stale-epoch':\n case 'requeue-resynthesis':\n return false\n }\n}\n\nfunction reconcileDependencies(\n operations: DrainOperations,\n knowledgeRoot: string,\n writerAuthority: CurrentWriterAuthority,\n priors?: TrustPriorTable,\n) {\n return {\n knowledgeRoot,\n writerAuthority,\n hasIndexRow: (bundleId: string) => operations.hasIndexRow(knowledgeRoot, bundleId),\n applyIndexDelta: (intent: CommitIntent) => {\n operations.applyIndexDeltaForBundle({ knowledgeRoot, bundleId: intent.bundleId,\n ...(priors === undefined ? {} : { priors }) })\n },\n deriveIndexRowFromBundle: (bundleId: string) => {\n operations.deriveIndexRowFromBundle({ knowledgeRoot, bundleId,\n ...(priors === undefined ? {} : { priors }) })\n },\n }\n}\n\nfunction budgetMs(options: DrainOptions): number {\n const value = options.budgetMs ?? DRAIN_BUDGET_MS\n if (value === 'unbounded') return Number.POSITIVE_INFINITY\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(\"budgetMs must be a finite non-negative number or 'unbounded'\")\n }\n return value\n}\n\n/**\n * Lease-gated one-shot Curator drain. It owns no provider: authoring is injected, serialized, and\n * durably checkpointed before the deterministic commit tail. Abort and budget are checked at job\n * boundaries; an in-flight model request is cut off only by the host's own author signal.\n */\nexport async function drainQueue(options: DrainOptions): Promise<DrainReport> {\n const priors = snapshotTrustPriors(options.priors)\n const operations: DrainOperations = { ...DEFAULT_OPERATIONS, ...options.operations }\n const now = options.now ?? Date.now\n const startedAt = now()\n const limit = budgetMs(options)\n const report = emptyReport()\n const drainOwnsLease = options.lease === undefined\n let lease: CurrentWriterAuthority\n if (options.lease !== undefined) {\n lease = options.lease\n } else {\n const acquired = operations.acquireWriterLease(options.knowledgeRoot)\n if (acquired.kind === 'held') {\n report.writerPass = { kind: 'skipped', reason: 'lease-held' }\n report.gc = { kind: 'skipped', reason: 'lease-held' }\n updateRemaining(report, options.knowledgeRoot)\n return { ...report, kind: 'handed-off', holder: acquired.holder }\n }\n if (acquired.kind === 'refused') throw acquired.error\n lease = acquired\n }\n\n const result: MutableDrainReport & { kind: 'drained' | 'aborted' } = {\n ...report,\n kind: 'drained',\n }\n const drainState: DispositionDrainState = { supersedesSeenByAnchorKey: new Map() }\n const completedCandidateIds = new Set<string>()\n const emitCompleted = (candidateId: string): void => {\n if (completedCandidateIds.has(candidateId)) return\n completedCandidateIds.add(candidateId)\n options.onJobLifecycle?.({ kind: 'job-completed', candidateId })\n }\n try {\n try {\n result.reconcile = operations.reconcileOnDrainStart(\n reconcileDependencies(operations, options.knowledgeRoot, lease, priors),\n )\n } catch (error) {\n recordFailure(result, 'reconcile', error)\n return result\n }\n\n while (true) {\n if (now() - startedAt >= limit) break\n if (options.signal?.aborted === true) {\n result.kind = 'aborted'\n break\n }\n\n let claimed\n try {\n claimed = operations.claimNextJob({\n knowledgeRoot: options.knowledgeRoot,\n leaseId: lease.leaseId,\n authority: lease,\n })\n } catch (error) {\n recordFailure(result, 'claim', error)\n break\n }\n if (claimed === undefined) break\n options.onJobLifecycle?.({\n kind: 'job-claimed',\n candidateId: claimed.candidateId,\n })\n result.jobsProcessed += 1\n const executionContext = claimedExecutionContext(claimed, options.executionContext)\n\n if (drainOwnsLease) {\n // A beat that throws (the lease guard stayed busy for its whole wait, or was refused) is\n // a heartbeat failure like a refusal, never a throw out of the loop (WR-11).\n let heartbeat: HeartbeatLeaseOutcome\n try {\n heartbeat = operations.heartbeatLease({\n knowledgeRoot: options.knowledgeRoot,\n leaseId: lease.leaseId,\n })\n } catch (error) {\n recordFailure(result, 'heartbeat', error, claimed.candidateId)\n break\n }\n if (heartbeat.kind === 'refused') {\n recordFailure(result, 'heartbeat', heartbeat.reason, claimed.candidateId)\n break\n }\n }\n\n if (claimed.kind === 'malformed') {\n // D-22: the strict sibling payload branches before checkpoint lookup, retrieval, or\n // author construction. A canary job therefore has no control-flow path to an LLM and\n // consumes none of the search-before-create query budget.\n const canaryOutcome = readClaimedCanaryOutcome(claimed)\n if (canaryOutcome === undefined) {\n recordFailure(\n result,\n 'job-state',\n 'claimed candidate payload is malformed',\n claimed.candidateId,\n )\n if (!quarantineMalformedClaim(\n result,\n operations,\n options.knowledgeRoot,\n lease,\n claimed.candidateId,\n 'malformed-payload',\n )) break\n continue\n }\n try {\n const store = createLocalKnowledgeStore({\n knowledgeRoot: options.knowledgeRoot,\n executionContext,\n epoch: lease.epoch,\n sourceBuildOrdinal: canaryOutcome.buildOrdinal,\n sourceRunId: canaryOutcome.runId,\n sourceJobId: claimed.candidateId,\n writerLeaseId: lease.leaseId,\n ...(priors === undefined ? {} : { resolveTrustPriors: () => priors }),\n ...(options.resolvePromotionPosture === undefined\n ? {}\n : { resolvePromotionPosture: options.resolvePromotionPosture }),\n onPromotionOutcome: outcome => result.promotions.push(outcome),\n /**\n * CR-02: the terminal transition joins the canary tail's own held section through\n * the within-held form. Calling the fenced writeJobState here would re-enter\n * withCurrentWriterAuthority against a BEGIN IMMEDIATE the tail already holds and\n * deadlock (the Plan 25/28 within-held idiom).\n */\n onCanaryTailWithinCurrentAuthority: () => {\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot: options.knowledgeRoot,\n candidateId: claimed.candidateId,\n authority: lease,\n lifecycle: 'done',\n })\n },\n ...(operations.canaryAuthorityHooks === undefined\n ? {}\n : { canaryAuthorityHooks: operations.canaryAuthorityHooks }),\n })\n await store.recordCanaryOutcome(canaryOutcome)\n } catch (error) {\n recordFailure(result, 'commit', error, claimed.candidateId)\n if (error instanceof WriterAuthorityLostError) break\n try {\n result.requeued += clearCandidateAndRequeue(\n operations,\n options.knowledgeRoot,\n lease,\n claimed.candidateId,\n )\n } catch (requeueError) {\n recordFailure(result, 'requeue', requeueError, claimed.candidateId)\n }\n break\n }\n emitCompleted(claimed.candidateId)\n result.committed += 1\n result.evidenceCommitted += 1\n continue\n }\n\n let checkpoint: AuthoredCheckpoint\n const state = operations.readJobState(options.knowledgeRoot, claimed.candidateId)\n if (state.kind === 'malformed') {\n recordFailure(result, 'job-state', 'job lifecycle state is malformed', claimed.candidateId)\n if (!quarantineMalformedClaim(\n result,\n operations,\n options.knowledgeRoot,\n lease,\n claimed.candidateId,\n 'malformed-job-state',\n )) break\n continue\n }\n const embedCrashCount = state.kind === 'parsed' ? state.state.embedCrashCount : 0\n if (state.kind === 'parsed' && state.state.authored !== undefined) {\n try {\n checkpoint = parseAuthoredCheckpoint(state.state.authored)\n } catch (error) {\n recordFailure(result, 'checkpoint', error, claimed.candidateId)\n if (!quarantineMalformedClaim(\n result,\n operations,\n options.knowledgeRoot,\n lease,\n claimed.candidateId,\n 'malformed-authored-checkpoint',\n )) break\n continue\n }\n } else {\n try {\n checkpoint = await authorCheckpoint(options, operations, claimed)\n } catch (error) {\n recordFailure(result, 'author', error, claimed.candidateId)\n try {\n result.requeued += clearCheckpointAndRequeue(\n operations,\n options.knowledgeRoot,\n lease,\n claimed,\n )\n } catch (requeueError) {\n recordFailure(result, 'requeue', requeueError, claimed.candidateId)\n }\n break\n }\n try {\n persistCheckpoint(\n operations,\n options.knowledgeRoot,\n lease,\n claimed.candidateId,\n checkpoint,\n )\n } catch (error) {\n recordFailure(result, 'checkpoint', error, claimed.candidateId)\n if (error instanceof WriterAuthorityLostError) break\n try {\n result.requeued += clearCheckpointAndRequeue(\n operations,\n options.knowledgeRoot,\n lease,\n claimed,\n )\n } catch (requeueError) {\n recordFailure(result, 'requeue', requeueError, claimed.candidateId)\n }\n break\n }\n }\n\n // D-02: dispose each authored delta independently through the one commit boundary.\n // Only the final delta completes the queue job so earlier disposals keep the claimed\n // candidate directory (and its artifacts) available.\n const vectorless = embedCrashCount >= EMBED_CRASH_VECTORLESS_THRESHOLD\n const slices = sliceAuthoredCheckpoint(checkpoint)\n let stopDrain = false\n /**\n * Sibling-failure invariant: no later slice may complete a job after any slice fails.\n * Preserve the whole authored checkpoint so successful siblings coalesce on retry while\n * the missing slice can land without re-invoking the author.\n */\n let anySliceFailed = false\n for (const [sliceIndex, slice] of slices.entries()) {\n const finalDelta = sliceIndex === slices.length - 1\n let outcome: CommitCurationOutcome\n try {\n const commit = vectorless\n ? operations.commitCurationDeltaVectorless\n : operations.commitCurationDelta\n outcome = commit(\n {\n knowledgeRoot: options.knowledgeRoot,\n epoch: lease.epoch,\n profile: resolveDispositionProfile(executionContext),\n drainState,\n ...(priors === undefined ? {} : { priors }),\n ...(options.resolvePromotionPosture === undefined\n ? {}\n : { resolvePromotionPosture: options.resolvePromotionPosture }),\n ...(!finalDelta || anySliceFailed ? { deferCompletion: true } : {}),\n },\n claimed,\n slice,\n )\n } catch (error) {\n if (!vectorless && isEmbeddingCrash(error)) {\n recordFailure(result, 'commit', error, claimed.candidateId)\n try {\n result.requeued += incrementEmbedCrashAndRequeue(\n operations,\n options.knowledgeRoot,\n lease,\n claimed,\n checkpoint,\n embedCrashCount,\n )\n } catch (requeueError) {\n recordFailure(result, 'requeue', requeueError, claimed.candidateId)\n }\n // A requeued crash is deliberately a next-drain retry. At the durable threshold that\n // retry uses the vectorless seam and lands the canonical bundle with dense work\n // pending. Already-committed sibling deltas coalesce as Confirm on the retry.\n stopDrain = true\n break\n }\n anySliceFailed = true\n recordFailure(result, 'commit', error, claimed.candidateId)\n continue\n }\n if (outcome.kind === 'failed') anySliceFailed = true\n const mapped = mapCommitOutcome(\n result,\n outcome,\n claimed,\n operations,\n options,\n lease,\n )\n if (\n finalDelta\n && !anySliceFailed\n && isSuccessfulTerminalCommitOutcome(outcome)\n ) {\n emitCompleted(claimed.candidateId)\n }\n if (mapped === 'stop') {\n stopDrain = true\n break\n }\n }\n if (anySliceFailed && !stopDrain) {\n try {\n result.requeued += preserveAuthoredCheckpointAndRequeue(\n operations,\n options.knowledgeRoot,\n lease,\n claimed,\n checkpoint,\n embedCrashCount,\n 'partially failed',\n )\n } catch (error) {\n recordFailure(result, 'requeue', error, claimed.candidateId)\n }\n // Reclaiming the same lexicographically-first candidate in this drain can livelock;\n // the durable checkpoint retry deliberately belongs to the next drain.\n stopDrain = true\n }\n if (stopDrain) break\n }\n\n if (result.kind === 'aborted') {\n result.writerPass = { kind: 'skipped', reason: 'aborted' }\n result.gc = { kind: 'skipped', reason: 'aborted' }\n } else if (now() - startedAt >= limit) {\n result.writerPass = { kind: 'skipped', reason: 'budget-exhausted' }\n result.gc = { kind: 'skipped', reason: 'budget-exhausted' }\n } else if (options.maintenance === 'skip') {\n result.writerPass = { kind: 'skipped', reason: 'daemon-cadence' }\n result.gc = { kind: 'skipped', reason: 'daemon-cadence' }\n } else {\n const maintenance = await runMaintenanceTail({\n knowledgeRoot: options.knowledgeRoot,\n ...(priors === undefined ? {} : { priors }),\n lease,\n ...(options.embeddingCapability === undefined\n ? {}\n : { embeddingCapability: options.embeddingCapability }),\n operations,\n budget: { now, startedAtMs: startedAt, limitMs: limit },\n surfaceAuthorityLoss: false,\n })\n result.writerPass = maintenance.writerPass\n result.gc = maintenance.gc\n for (const failure of maintenance.failures) {\n recordFailure(result, failure.stage, failure.error)\n }\n }\n return result\n } finally {\n // Stays true unless the read proves no store change belongs to the run: lost receipts never fold to zero.\n let runLinked = true\n if (options.sourceRunId !== undefined) {\n try {\n const read = readCurationEffectsForRun({ knowledgeRoot: options.knowledgeRoot,\n sourceRunId: options.sourceRunId, observationIds: options.observationIds })\n result.effects = read.effects\n runLinked = read.runLinked\n } catch {\n recordFailure(result, 'commit', 'curation effect read incomplete')\n }\n }\n if (drainOwnsLease) {\n try {\n const released = operations.releaseLease({\n knowledgeRoot: options.knowledgeRoot,\n leaseId: lease.leaseId,\n })\n if (released.kind === 'refused') recordFailure(result, 'release', released.reason)\n } catch (error) {\n recordFailure(result, 'release', error)\n }\n }\n updateRemaining(result, options.knowledgeRoot, lease.leaseId)\n if (result.kind === 'drained' && result.failures === 0 && result.requeued === 0\n && result.remaining === 0 && result.effects !== undefined\n && (result.effects.length > 0 || runLinked === false)) {\n // Not recordFailure: a failure count would make a committed drain incomplete and retry it.\n try {\n result.snapshot = foldCurationSnapshot(result.effects)\n } catch {\n result.snapshotFoldFailed = true\n }\n }\n }\n}\n","/**\n * Deterministic recovery before a writer starts draining.\n *\n * The caller acquires the writer lease first, which bumps the fencing epoch on stale takeover.\n * This module then reclaims every non-current claim, resolves journal state against canonical\n * bundle truth, and delegates projection work through injected index functions. It deliberately\n * has no author/model dependency: recovery can replay only the persisted deterministic tail.\n */\nimport {\n existsSync,\n readdirSync,\n rmdirSync,\n rmSync,\n} from 'node:fs'\nimport { basename, join } from 'node:path'\n\nimport { enumerateBundleDirs } from '../bundle-scan.js'\nimport { loadBundle } from '../bundle-read.js'\nimport {\n withCurrentWriterAuthority,\n type CurrentWriterAuthority,\n} from '../lease/writer-lease.js'\nimport {\n claimedCandidateDir,\n queuedCandidateDir,\n} from '../queue/queue-layout.js'\nimport {\n listClaimedLeases,\n requeueClaimedWithinCurrentAuthority,\n} from '../queue/curation-queue.js'\nimport {\n readJobState,\n writeJobStateWithinCurrentAuthority,\n} from '../queue/job-state.js'\nimport {\n clearCommitIntent,\n listCommitIntents,\n quarantineStaleCommitIntent,\n readReconciledEpoch,\n writeReconciledEpochWithinCurrentAuthority,\n type CommitIntent,\n type ListedCommitIntent,\n} from './intent-journal.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport { recoverExpiredBundleMutations } from './bundle-mutation.js'\nimport {\n isCurationEffectCommitted,\n receiptForEffect,\n writeCurationEffectReceiptWithinCurrentAuthority,\n} from './curation-effect-receipt.js'\n\nexport interface ReconcileOnDrainStartHooks {\n /**\n * Fires immediately before a stale intent is renamed aside. The only seam that can reproduce\n * the race a second reconciler on another host creates: it removes the intent file between our\n * listing and our rename.\n */\n beforeStaleQuarantine?(candidateId: string, epoch: number): void\n}\n\nexport interface ReconcileOnDrainStartDependencies {\n knowledgeRoot: string\n writerAuthority: CurrentWriterAuthority\n hasIndexRow(bundleId: string): boolean\n applyIndexDelta(intent: CommitIntent): void\n deriveIndexRowFromBundle(bundleId: string): void\n hooks?: ReconcileOnDrainStartHooks\n}\n\nexport interface ReconcileReport {\n intentsCleared: number\n intentsReplayed: number\n intentsDiscarded: number\n /** Intents authored before the reconciled-epoch watermark: renamed aside, never replayed. */\n intentsQuarantinedStale: number\n jobsRequeued: number\n orphansRemoved: number\n /** Present on production reconciliation; optional keeps injected legacy test reports compatible. */\n mutationsRecovered?: number\n malformed: number\n}\n\nfunction childDirectories(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 (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n}\n\nfunction stagingRoots(root: string): string[] {\n const roots: string[] = []\n const visit = (dir: string): void => {\n for (const name of childDirectories(dir)) {\n const child = join(dir, name)\n if (name === '.staging') {\n roots.push(child)\n } else {\n visit(child)\n }\n }\n }\n visit(root)\n return roots.sort()\n}\n\nfunction stagingEntryBelongsToLease(entryName: string, leaseId: string): boolean {\n return (\n entryName === leaseId ||\n entryName.startsWith(`${leaseId}-`) ||\n entryName.endsWith(`-${leaseId}`) ||\n entryName.includes(`-${leaseId}-`)\n )\n}\n\nfunction removeEmptyDirectory(dir: string): void {\n try {\n rmdirSync(dir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n}\n\nfunction removeExpiredLeaseStaging(\n knowledgeRoot: string,\n expiredLeaseIds: ReadonlySet<string>,\n): number {\n let removed = 0\n if (expiredLeaseIds.size === 0) return removed\n\n for (const stagingRoot of stagingRoots(knowledgeRoot)) {\n assertWithinKnowledgeRoot(knowledgeRoot, stagingRoot)\n for (const entryName of childDirectories(stagingRoot)) {\n if (\n [...expiredLeaseIds].some((leaseId) =>\n stagingEntryBelongsToLease(entryName, leaseId),\n )\n ) {\n rmSync(join(stagingRoot, entryName), { recursive: true, force: true })\n removed += 1\n }\n }\n removeEmptyDirectory(stagingRoot)\n }\n return removed\n}\n\nfunction requeueCandidate(\n knowledgeRoot: string,\n candidateId: string,\n requeued: Set<string>,\n writerAuthority: CurrentWriterAuthority,\n): void {\n for (const leaseId of listClaimedLeases(knowledgeRoot)) {\n if (!existsSync(claimedCandidateDir(knowledgeRoot, leaseId, candidateId))) continue\n for (const movedCandidateId of requeueClaimedWithinCurrentAuthority({\n knowledgeRoot,\n leaseId,\n authority: writerAuthority,\n })) {\n requeued.add(movedCandidateId)\n }\n }\n\n if (!existsSync(queuedCandidateDir(knowledgeRoot, candidateId))) return\n const state = readJobState(knowledgeRoot, candidateId)\n if (state.kind === 'parsed' && state.state.lifecycle === 'queued') return\n writeJobStateWithinCurrentAuthority({\n knowledgeRoot,\n candidateId,\n authority: writerAuthority,\n lifecycle: 'queued',\n embedCrashCount: state.kind === 'parsed' ? state.state.embedCrashCount : 0,\n ...(state.kind === 'parsed' && state.state.authored !== undefined\n ? { authored: state.state.authored }\n : {}),\n })\n requeued.add(candidateId)\n}\n\nfunction loadedBundleIds(knowledgeRoot: string): Map<string, string> {\n const loaded = new Map<string, string>()\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const outcome = loadBundle(entry.dir)\n if (outcome.kind !== 'loaded') continue\n loaded.set(outcome.bundle.manifest.id, entry.dir)\n }\n return loaded\n}\n\n/**\n * Reconcile the root after lease acquisition and before the first queue claim.\n *\n * Index writes are caller-injected so Plan 378-10 and this recovery path share one projection\n * authority. A thrown apply/derive operation intentionally leaves the intent in place for retry.\n */\nfunction reconcileOnDrainStartWithinCurrentAuthority(\n deps: ReconcileOnDrainStartDependencies,\n): ReconcileReport {\n const report: ReconcileReport = {\n intentsCleared: 0,\n intentsReplayed: 0,\n intentsDiscarded: 0,\n intentsQuarantinedStale: 0,\n jobsRequeued: 0,\n orphansRemoved: 0,\n mutationsRecovered: 0,\n malformed: 0,\n }\n const requeued = new Set<string>()\n const expiredLeaseIds = new Set<string>()\n\n for (const leaseId of listClaimedLeases(deps.knowledgeRoot)) {\n if (deps.writerAuthority.leaseId === leaseId) continue\n expiredLeaseIds.add(leaseId)\n for (const candidateId of requeueClaimedWithinCurrentAuthority({\n knowledgeRoot: deps.knowledgeRoot,\n leaseId,\n authority: deps.writerAuthority,\n })) {\n requeued.add(candidateId)\n }\n }\n report.mutationsRecovered = recoverExpiredBundleMutations(\n deps.knowledgeRoot,\n [...expiredLeaseIds],\n ).mutationsRecovered\n report.orphansRemoved = removeExpiredLeaseStaging(\n deps.knowledgeRoot,\n expiredLeaseIds,\n )\n\n /**\n * An intent authored before the last completed reconciliation belongs to a generation this\n * writer has already superseded: replaying it would apply obsolete index work or requeue a\n * candidate the successor already completed. Keyed off the watermark rather than bare epoch\n * inequality, because the crash journal a successor legitimately inherits is written at a\n * lower epoch too and must still replay.\n */\n const reconciledEpoch = readReconciledEpoch(deps.knowledgeRoot)\n const entries: ListedCommitIntent[] = []\n for (const entry of listCommitIntents(deps.knowledgeRoot)) {\n if ('parsed' in entry && entry.parsed.epoch < reconciledEpoch) {\n deps.hooks?.beforeStaleQuarantine?.(entry.parsed.candidateId, entry.parsed.epoch)\n const outcome = quarantineStaleCommitIntent(\n deps.knowledgeRoot,\n entry.parsed.candidateId,\n entry.parsed.epoch,\n )\n // An intent that vanished under us was already handled by whoever removed it; the pass\n // must not count it and must not die on it — it is running inside the held section.\n if (outcome.kind === 'quarantined') report.intentsQuarantinedStale += 1\n continue\n }\n entries.push(entry)\n }\n const bundleIdsWithIntent = new Set(\n entries.flatMap((entry) => ('parsed' in entry ? [entry.parsed.bundleId] : [])),\n )\n const bundles = loadedBundleIds(deps.knowledgeRoot)\n\n for (const entry of entries) {\n if ('malformed' in entry) {\n requeueCandidate(\n deps.knowledgeRoot,\n entry.candidateId,\n requeued,\n deps.writerAuthority,\n )\n clearCommitIntent(deps.knowledgeRoot, entry.candidateId)\n report.intentsDiscarded += 1\n report.malformed += 1\n continue\n }\n\n const { parsed: intent } = entry\n if (intent.observation !== undefined) {\n let committed = 0\n for (const effect of intent.observation.effects) {\n if (!isCurationEffectCommitted(deps.knowledgeRoot, intent.candidateId, effect)) continue\n // The main bundle may have published while its victim/maintenance suffix did not.\n // Replay only projections of independently verified canonical effects.\n deps.applyIndexDelta({ ...intent, bundleId: effect.recordId })\n writeCurationEffectReceiptWithinCurrentAuthority({\n knowledgeRoot: deps.knowledgeRoot,\n authority: deps.writerAuthority,\n receipt: receiptForEffect(intent.candidateId, intent.observation, effect),\n })\n committed += 1\n }\n if (committed < intent.observation.effects.length) {\n requeueCandidate(deps.knowledgeRoot, intent.candidateId, requeued, deps.writerAuthority)\n }\n clearCommitIntent(deps.knowledgeRoot, intent.candidateId)\n if (committed > 0) {\n report.intentsReplayed += 1\n report.intentsCleared += 1\n } else {\n report.intentsDiscarded += 1\n }\n continue\n }\n if (!bundles.has(intent.bundleId)) {\n requeueCandidate(\n deps.knowledgeRoot,\n intent.candidateId,\n requeued,\n deps.writerAuthority,\n )\n clearCommitIntent(deps.knowledgeRoot, intent.candidateId)\n report.intentsDiscarded += 1\n continue\n }\n\n deps.applyIndexDelta(intent)\n report.intentsReplayed += 1\n clearCommitIntent(deps.knowledgeRoot, intent.candidateId)\n report.intentsCleared += 1\n }\n\n for (const [bundleId, dir] of bundles) {\n if (bundleIdsWithIntent.has(bundleId) || deps.hasIndexRow(bundleId)) continue\n const outcome = loadBundle(dir)\n if (outcome.kind !== 'loaded' || basename(dir) !== outcome.bundle.manifest.id) continue\n deps.deriveIndexRowFromBundle(bundleId)\n }\n\n // Last step of the held section: the watermark advances only for a pass that completed.\n writeReconciledEpochWithinCurrentAuthority(\n deps.knowledgeRoot,\n deps.writerAuthority.epoch,\n )\n report.jobsRequeued = requeued.size\n return report\n}\n\nexport function reconcileOnDrainStart(\n deps: ReconcileOnDrainStartDependencies,\n): ReconcileReport {\n return withCurrentWriterAuthority(\n deps.knowledgeRoot,\n deps.writerAuthority,\n () => reconcileOnDrainStartWithinCurrentAuthority(deps),\n )\n}\n","import {\n canonicalJson,\n deriveEvidenceToken,\n normalizeAnchor,\n supersessionKey,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n BundleDraft,\n CurationAuthorship,\n CurationFallbackReason,\n Delta,\n ScopeKey,\n} from '@vostride/agent-qa-schema'\n\nimport type { CurationJobView, NeighborRecord } from './author-contract.js'\n\nexport const RESTRICTED_FALLBACK_DELTA_KINDS = [\n 'Add',\n 'Confirm',\n 'Supersede',\n 'Noop',\n] as const\n\ntype RestrictedFallbackKind = (typeof RESTRICTED_FALLBACK_DELTA_KINDS)[number]\ntype RestrictedFallbackDelta = Extract<Delta, { kind: RestrictedFallbackKind }>\ntype FallbackBundleDraft = BundleDraft & { needsEnrichment?: true }\n\nfunction cloneAnchor(anchor: Anchor): Anchor {\n switch (anchor.t) {\n case 'page':\n return { t: anchor.t, route: anchor.route }\n case 'flow':\n return { t: anchor.t, name: anchor.name }\n case 'el':\n return {\n t: anchor.t,\n role: anchor.role,\n name: anchor.name,\n ...(anchor.ordinal === undefined ? {} : { ordinal: anchor.ordinal }),\n }\n case 'platform':\n return { t: anchor.t, platform: anchor.platform }\n case 'selector':\n return { t: anchor.t, literal: anchor.literal }\n case 'error':\n return { t: anchor.t, message: anchor.message }\n }\n}\n\nfunction cloneScope(scope: ScopeKey): ScopeKey {\n return { tier: scope.tier, key: scope.key }\n}\n\nfunction assertStructurallyPossibleJob(job: CurationJobView): void {\n if (!/^[0-9a-f]{64}$/.test(job.candidateId)) {\n throw new TypeError('fallback requires a guarded candidate content address')\n }\n if (job.anchors.length === 0) {\n throw new TypeError('fallback requires a verified primary anchor')\n }\n if (job.attributingObservationId.length === 0) {\n throw new TypeError('fallback requires an attributing observation id')\n }\n if (job.kind === 'fact' && job.subtype === undefined) {\n throw new TypeError('fallback fact candidates require a subtype')\n }\n if (job.kind !== 'fact' && job.subtype !== undefined) {\n throw new TypeError('fallback non-fact candidates cannot carry a fact subtype')\n }\n}\n\nfunction requiresCapableModelEnrichment(job: CurationJobView): boolean {\n const evidenceFullyDerivable =\n (\n job.kind === 'fact'\n && (job.subtype === 'selector' || job.subtype === 'measurement')\n )\n || (\n job.kind === 'caution'\n && job.rootCauseClass !== undefined\n && job.distilledObservations.some(\n (observation) => observation.error?.rootCauseClass === job.rootCauseClass,\n )\n )\n return !evidenceFullyDerivable || job.summarySeed.trim() === ''\n}\n\nfunction fallbackAuthorship(\n job: CurationJobView,\n fallbackReason: CurationFallbackReason,\n): CurationAuthorship {\n return {\n path: 'deterministic-fallback',\n executionContext: job.executionContext,\n fallbackReason,\n }\n}\n\nfunction fallbackDraft(job: CurationJobView): FallbackBundleDraft {\n const needsEnrichment = requiresCapableModelEnrichment(job)\n\n // Deterministic fallback and capable-model authoring share these identity fields. Because prose\n // is excluded from the content address, later capable re-processing enriches THE SAME bundle\n // rather than minting a duplicate.\n return {\n kind: job.kind,\n ...(job.subtype === undefined ? {} : { subtype: job.subtype }),\n anchors: job.anchors.map(cloneAnchor),\n scope: cloneScope(job.scope),\n summary: job.summarySeed,\n body: job.bodySeed,\n distilledEvidenceRef: {\n id: `curation-candidate-${job.candidateId}`,\n sha: job.candidateId,\n },\n originStage: 'run-curation',\n ...(needsEnrichment ? { needsEnrichment: true as const } : {}),\n }\n}\n\nfunction normalizedAnchorKey(anchor: Anchor): string {\n return canonicalJson(normalizeAnchor(anchor))\n}\n\nfunction exactPrimaryAnchorNeighbor(\n primaryAnchor: Anchor,\n neighbors: readonly NeighborRecord[],\n): NeighborRecord | undefined {\n const primaryKey = normalizedAnchorKey(primaryAnchor)\n return [...neighbors]\n .filter((neighbor) => {\n const neighborPrimary = neighbor.anchors[0]\n return neighborPrimary !== undefined && normalizedAnchorKey(neighborPrimary) === primaryKey\n })\n .sort(\n (left, right) =>\n left.alias - right.alias || String(left.recordId).localeCompare(String(right.recordId)),\n )[0]\n}\n\nfunction citedEnvelope(\n job: CurationJobView,\n fallbackReason: CurationFallbackReason,\n neighbor?: NeighborRecord,\n) {\n return {\n origin: 'agent' as const,\n scope: cloneScope(job.scope),\n citedIds: neighbor === undefined ? [] : [neighbor.recordId],\n ...(neighbor === undefined\n ? {}\n : {\n precondition: [\n {\n recordId: neighbor.recordId,\n observedStatus: neighbor.observedStatus,\n observedOrdinal: neighbor.observedOrdinal,\n },\n ],\n }),\n authorship: fallbackAuthorship(job, fallbackReason),\n }\n}\n\n/**\n * Construct the pure §7.9 fallback projection from one guarded queue job and its presented\n * neighbors. No model, filesystem, clock, or ambient process state participates.\n *\n * D-06 note: the restricted fallback NEVER authors procedures — segmentation and\n * parameterization are capable-model judgments, and a seed-draft procedure body would commit\n * a non-codec payload. A procedure-extraction job therefore falls back to a one-element Noop\n * (zero procedure deltas); content-addressed re-emission on a later drain retries extraction.\n */\nexport function constructFallbackDeltas(\n job: CurationJobView,\n neighbors: NeighborRecord[],\n fallbackReason: CurationFallbackReason,\n): Delta[] {\n assertStructurallyPossibleJob(job)\n if (job.kind === 'procedure') {\n return [{ ...citedEnvelope(job, fallbackReason), kind: 'Noop' }]\n }\n const primaryAnchor = job.anchors[0]!\n const exactNeighbor = exactPrimaryAnchorNeighbor(primaryAnchor, neighbors)\n const evidenceToken = deriveEvidenceToken({\n attributingObservationId: job.attributingObservationId,\n anchor: primaryAnchor,\n buildOrdinal: job.buildOrdinal,\n })\n\n if (\n job.kind === 'fact' &&\n job.subtype === 'measurement' &&\n exactNeighbor?.kind === 'fact' &&\n exactNeighbor.subtype === 'measurement' &&\n supersessionKey(job.anchors) === supersessionKey(exactNeighbor.anchors)\n ) {\n return [\n {\n ...citedEnvelope(job, fallbackReason, exactNeighbor),\n kind: 'Supersede',\n victimId: exactNeighbor.recordId,\n newBundle: fallbackDraft(job),\n evidenceToken,\n },\n ]\n }\n\n if (exactNeighbor !== undefined) {\n return [\n {\n ...citedEnvelope(job, fallbackReason, exactNeighbor),\n kind: 'Confirm',\n targetId: exactNeighbor.recordId,\n evidenceToken,\n },\n ]\n }\n\n return [\n {\n ...citedEnvelope(job, fallbackReason),\n kind: 'Add',\n bundle: fallbackDraft(job),\n },\n ]\n}\n\n/** Refuse any model-judgment mutation masquerading as deterministic fallback authorship. */\nexport function assertRestrictedFallbackDelta(\n delta: Delta,\n): asserts delta is RestrictedFallbackDelta {\n switch (delta.kind) {\n case 'Add':\n case 'Confirm':\n case 'Noop':\n return\n case 'Supersede':\n if (delta.newBundle.kind === 'fact' && delta.newBundle.subtype === 'measurement') return\n throw new TypeError('deterministic fallback may supersede measurement facts only')\n case 'Deprecate':\n case 'MintUnknown':\n throw new TypeError(`deterministic fallback cannot emit ${delta.kind}`)\n }\n}\n","import { join } from 'node:path'\n\nimport type { KnowledgePort } from '@vostride/agent-qa-agent'\nimport {\n asEvidenceToken,\n asRecordId,\n canonicalJson,\n deriveEvidenceToken,\n evaluatePromotionGate,\n eventDedupKey,\n foldBundleTrust,\n GATE_RECEIPT_SCHEMA_VERSION,\n GateReceiptSchema,\n GATE2_DEFAULT_STALE_CONFIRMATIONS,\n isPromotionReceipt,\n receiptDigestOf,\n sha256hex,\n stampReceiptDigest,\n survivingOutcomeEvents,\n strongestPromotionPath,\n strongerPromotionPath,\n} from '@vostride/agent-qa-schema'\nimport type {\n BundleDraft,\n CanaryOutcome,\n CurationAuthorship,\n Delta,\n ExecutionContext,\n GateReceipt,\n GateReceiptRecordOutcome,\n PromotionGateHoldReason,\n PromotionOutcome,\n PromotionPath,\n RecordId,\n ResolvePromotionPosture,\n ScreenState,\n TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport { appendGateReceipt, appendOutcomeEvent, appendPromotionReceipt, type AppendOutcome } from '../bundle-append.js'\nimport { deriveBundleTrust, loadBundle, readGateReceipts } from '../bundle-read.js'\nimport type { LoadedBundle } from '../bundle-read.js'\nimport type { BundleStoreConfig } from '../bundle-publish.js'\nimport {\n BundleTargetResolutionError,\n resolveProductQualifiedBundleDir,\n} from '../bundle-scan.js'\nimport { readCurrentEpoch, withCurrentWriterAuthority } from '../lease/writer-lease.js'\nimport { claimedCandidateDir } from '../queue/queue-layout.js'\nimport { snapshotTrustPriors } from '../promotion-gate-input.js'\nimport {\n CURATION_QUEUE_SCHEMA_VERSION,\n buildCurationCandidateAddressFields,\n candidateContentAddress,\n} from '../queue/queue-payload.js'\nimport type {\n CurationCandidateAddressFields,\n CurationCandidatePayload,\n} from '../queue/queue-payload.js'\nimport { AUTHORED_CHECKPOINT_SCHEMA_VERSION, resolveDispositionProfile } from './author-contract.js'\nimport type { AuthoredDeltaCheckpoint, DispositionProfile } from './author-contract.js'\nimport {\n applyIndexDeltaForBundleWithinCurrentAuthority,\n assemblePromotionGateInput,\n commitCurationDelta,\n derivePromotedEvidenceToken,\n} from './commit.js'\nimport { canaryOutcomeObservationId } from './disposition.js'\nimport type {\n CommitCurationDependencies,\n CommitCurationJob,\n CommitCurationOutcome,\n} from './commit.js'\n\n/**\n * CR-02 takeover barriers. Test-only seams naming the three points at which a canary flow is\n * about to make canonical state durable; production callers omit them.\n *\n * The two entry barriers fire OUTSIDE the held section, which is what lets a schedule complete a\n * real takeover there and then observe the resumed writer's refusal. `beforeIndexProjection` fires\n * INSIDE it, so its schedule observes a contender blocked behind the tail instead.\n */\nexport interface CanaryAuthorityHooks {\n /** Immediately before the negative arm enters its held section. */\n beforeNegativeAppend?: () => void\n /** Immediately before the positive arm enters its held promotion section. */\n beforePromotionAppend?: () => void\n /** Inside the negative arm's held section, between its append and its projection. */\n beforeIndexProjection?: () => void\n}\n\nexport interface CreateLocalKnowledgeStoreConfig {\n knowledgeRoot: string\n executionContext: ExecutionContext\n /** The holder's fresh lease epoch. Defaults to a fresh disk read for composition roots. */\n epoch?: number\n /**\n * The caller's real writer-lease id, paired with `epoch`.\n *\n * CR-02: every canonical append, promotion, and index projection this store performs carries\n * this identity into `withCurrentWriterAuthority`, so a store constructed by someone who is not\n * the published holder is refused at its first canonical mutation instead of laundering a\n * fabricated id. It is required precisely so no code path can omit it and fall back to one.\n */\n writerLeaseId: string\n /** Port calls lack a run ordinal; callers with run context should supply it. */\n sourceBuildOrdinal?: number\n sourceRunId?: string\n /** 2026-09-07, 418 D-07: queue entry identity stamped as producedBy.jobId. */\n sourceJobId?: string\n screenStates?: readonly ScreenState[]\n resolvePromotionPosture?: ResolvePromotionPosture\n /** Resolved once at construction; only neutral immutable data reaches folds and projections. */\n resolveTrustPriors?: () => TrustPriorTable | undefined\n onPromotionOutcome?: (report: PromotionOutcomeReport) => void\n /** Fault-injection seam; production callers must omit it. */\n canaryAuthorityHooks?: CanaryAuthorityHooks\n /**\n * Joins the caller's own terminal work to the canary tail's held section. The drain's `done`\n * job-state write uses this so the append, the projection, and the lifecycle transition are one\n * indivisible section; implementations must use within-held write forms only.\n */\n onCanaryTailWithinCurrentAuthority?: () => void\n operations?: {\n /** Test/chaos seam; production always uses commitCurationDelta. */\n commitCurationDelta?: typeof commitCurationDelta\n }\n}\n\nexport interface PromotionOutcomeReport {\n candidateId: RecordId\n promotionPath?: PromotionPath\n promotionHoldReason?: PromotionGateHoldReason\n}\n\n/**\n * @deprecated `recordCanaryOutcome` is implemented. The exported class remains only so code\n * compiled against the pre-380 package surface does not lose its named import.\n */\nexport class KnowledgeStoreNotImplementedError extends Error {\n readonly operation: 'recordCanaryOutcome'\n\n constructor(operation: 'recordCanaryOutcome', _retiredOwnerPhase?: 380) {\n super(`${operation} compatibility error is retired because the operation is implemented`)\n this.name = 'KnowledgeStoreNotImplementedError'\n this.operation = operation\n }\n}\n\nexport type KnowledgePromotionErrorReason =\n | PromotionGateHoldReason\n | 'propose-only'\n | 'not-found'\n\n/** Typed refusal for the evidence-gated promote port; callers never receive a force path. */\nexport class KnowledgePromotionError extends Error {\n readonly candidateId: RecordId\n readonly reason: KnowledgePromotionErrorReason\n\n constructor(candidateId: RecordId, reason: KnowledgePromotionErrorReason) {\n super(`knowledge promotion refused for ${candidateId}: ${reason}`)\n this.name = 'KnowledgePromotionError'\n this.candidateId = candidateId\n this.reason = reason\n }\n}\n\nexport class KnowledgeCommitError extends Error {\n readonly outcome: CommitCurationOutcome\n\n constructor(outcome: CommitCurationOutcome) {\n super(`local knowledge commit did not complete: ${outcome.kind}`)\n this.name = 'KnowledgeCommitError'\n this.outcome = outcome\n }\n}\n\n/** Typed WR-02 refusal for procedure drafts that require evidence this port cannot carry. */\nexport class KnowledgeUnsupportedDeltaError extends Error {\n readonly deltaKind: Delta['kind']\n readonly reason: 'procedure-evidence-unsupported'\n\n constructor(deltaKind: Delta['kind']) {\n super(\n `local KnowledgePort cannot author ${deltaKind} procedure drafts: the public port carries no durable trajectory/capture evidence; use the evidence-bearing curation queue/drainer`,\n )\n this.name = 'KnowledgeUnsupportedDeltaError'\n this.deltaKind = deltaKind\n this.reason = 'procedure-evidence-unsupported'\n }\n}\n\ninterface ResolvedTruth {\n id: RecordId\n bundle: LoadedBundle\n bundleDir: string\n product: string\n observedStatus: string\n observedOrdinal: number\n}\n\nfunction resolveTruth(knowledgeRoot: string, id: RecordId, priors?: TrustPriorTable): ResolvedTruth | undefined {\n let target: ReturnType<typeof resolveProductQualifiedBundleDir>\n try {\n target = resolveProductQualifiedBundleDir({ knowledgeRoot, recordId: id })\n } catch (error) {\n if (\n error instanceof BundleTargetResolutionError\n && error.reason === 'not-found'\n ) return undefined\n throw error\n }\n const loaded = loadBundle(target.dir)\n if (loaded.kind !== 'loaded' || loaded.bundle.manifest.id !== id) return undefined\n const trust = deriveBundleTrust(loaded.bundle, priors)\n return {\n id,\n bundle: loaded.bundle,\n bundleDir: target.dir,\n product: target.product,\n observedStatus: trust.status,\n observedOrdinal: trust.validity.closedAtOrdinal ?? trust.validity.openedAtOrdinal,\n }\n}\n\nfunction targetId(delta: Delta): RecordId | undefined {\n switch (delta.kind) {\n case 'Confirm':\n case 'Deprecate':\n return delta.targetId\n case 'Supersede':\n return delta.victimId\n case 'MintUnknown':\n return delta.conflict.recordIds[0]\n case 'Add':\n case 'Noop':\n return undefined\n }\n}\n\nfunction draft(delta: Delta): BundleDraft | undefined {\n if (delta.kind === 'Add') return delta.bundle\n if (delta.kind === 'Supersede') return delta.newBundle\n return undefined\n}\n\n/**\n * @internal The evidence token the port bridge stamps on a delta's committed event. Exported\n * only so the review writer can recognise an explicit change that already landed (432-06).\n */\nexport function syntheticEvidenceToken(delta: Delta): string {\n if (delta.kind === 'Confirm' || delta.kind === 'Supersede') return delta.evidenceToken\n return sha256hex(canonicalJson({ delta, source: 'knowledge-port' }))\n}\n\nfunction addressFields(\n config: CreateLocalKnowledgeStoreConfig,\n delta: Delta,\n target: ResolvedTruth | undefined,\n buildOrdinal: number,\n): CurationCandidateAddressFields {\n const authored = draft(delta)\n const kind = authored?.kind ?? target?.bundle.frontmatter.kind ?? 'unknown'\n const subtype = authored?.subtype ?? target?.bundle.frontmatter.subtype\n const anchors = authored?.anchors\n ?? target?.bundle.frontmatter.anchors.map(({ raw }) => raw)\n ?? [{ t: 'error' as const, message: `unresolved knowledge-port ${delta.kind}` }]\n return buildCurationCandidateAddressFields({\n schemaVersion: CURATION_QUEUE_SCHEMA_VERSION,\n sourceRunId: config.sourceRunId ?? 'knowledge-port',\n scope: delta.scope,\n buildOrdinal,\n executionContext: config.executionContext,\n kind,\n ...(kind === 'fact'\n ? { subtype: subtype ?? 'content' }\n : {}),\n anchors,\n summarySeed: authored?.summary ?? target?.bundle.summary ?? `KnowledgePort ${delta.kind}`,\n bodySeed: authored?.body ?? target?.bundle.body ?? canonicalJson(delta),\n distilledObservations: [],\n evidenceToken: syntheticEvidenceToken(delta),\n attributingObservationId: `knowledge-port:${sha256hex(canonicalJson(delta))}`,\n artifactInventory: [],\n emittedAt: '1970-01-01T00:00:00.000Z',\n })\n}\n\nfunction syntheticAuthorship(\n config: CreateLocalKnowledgeStoreConfig,\n delta: Delta,\n): CurationAuthorship {\n return delta.authorship ?? {\n path: 'llm',\n model: { id: 'knowledge-port-bridge' },\n executionContext: config.executionContext,\n }\n}\n\n/** The one authority every canonical mutation in this file carries; never synthesized. */\nfunction currentAuthority(\n config: CreateLocalKnowledgeStoreConfig,\n): { leaseId: string; epoch: number } {\n return {\n leaseId: config.writerLeaseId,\n epoch: config.epoch ?? readCurrentEpoch(config.knowledgeRoot),\n }\n}\n\n/**\n * Bridge one port delta into the commit path's job shape — computing the claimed-candidate\n * ADDRESS and materializing NOTHING.\n *\n * WHY THE BRIDGE WRITES NOTHING (CR-02″). This function used to create the candidate's artifacts\n * directory and write its `payload.json` before returning (those two statements, and this file's\n * whole `node:fs` import with them, are gone — the corpus greps this file for a filesystem write\n * and expects to find none), and `commitWithProfile` calls it BEFORE `operation(...)` — which is\n * where `disposeDelta` runs the\n * §7.3.1 checks. So a delta the store REFUSES had already left a claimed curation candidate on\n * disk, seeded from `addressFields` with the cited record's own `summarySeed`, `anchors`,\n * `bodySeed` and `kind`. Nothing unwound it on the throw: `reconcileOnDrainStart` requeued that\n * directory under the next lease (`requeueClaimedWithinCurrentAuthority` takes every\n * `/^[0-9a-f]{64}$/` name with no provenance filter) and the curator re-authored the fact a\n * reviewer had just removed, one drain later, as `origin: 'agent'`.\n *\n * The repair is NOT an unwind. An unwind enumerates the artifacts today's bridge happens to\n * write, so the next check that throws from a new position leaks whatever the enumeration missed\n * — the same one-axis-out shape this phase has paid for repeatedly. Writing nothing is a\n * property of the path instead of a property of a cleanup: a thrown check at ANY position now\n * leaves no residue, because there was never anything to leave.\n *\n * WHAT MAKES IT SAFE — the port path has no on-disk consumer of the claimed form, each half\n * verified by reading:\n * - disposition reads no `job.candidateDir` (441-53), and procedure drafts are refused by\n * `commitWithProfile` BEFORE this function is called, pinned by knowledge-store.test.ts's\n * \"rejects before materializing any claimed candidate\" case;\n * - `addressFields` sets `artifactInventory: []`, so `commit.ts`'s `artifactInputs` maps over\n * an empty list and `preCopyArtifacts` copies nothing;\n * - every completed outcome ends in `markDone` → `writeJobState('done')` →\n * `removeClaimedCandidate`, whose `rmSync(…, { force: true })` and `removeEmptyDir` are both\n * no-ops on an absent directory.\n * The job keeps `candidateDir` / `payloadPath` / `artifactsDir` because `CommitCurationJob`'s\n * type requires them and the drain's own run-sourced candidates — which DO exist on disk — flow\n * through the same shape. Here they name an address, not a file.\n *\n * THE MECHANISM THAT REDS THIS. The claim above is not prose: reintroducing the two write\n * statements reds `apply-review.test.ts`'s \"a refused accept leaves the WHOLE knowledge root\n * byte-identical (CR-02″)\" with the leaked `memory/queue/claimed/…/payload.json` printed in the\n * diff, and reds its sibling adoption case with `jobsRequeued` back at 1. Probe m1 of 387-17 is\n * exactly that mutation, run and recorded.\n */\nfunction bridgeDelta(\n config: CreateLocalKnowledgeStoreConfig,\n delta: Delta,\n priors?: TrustPriorTable,\n): { job: CommitCurationJob; checkpoint: AuthoredDeltaCheckpoint } {\n const neighbors = delta.citedIds\n .map((id) => resolveTruth(config.knowledgeRoot, id, priors))\n .filter((truth): truth is ResolvedTruth => truth !== undefined)\n const target = targetId(delta)\n const targetTruth = target === undefined\n ? undefined\n : neighbors.find(({ id }) => id === target) ?? resolveTruth(config.knowledgeRoot, target, priors)\n const observedOrdinals = [...neighbors, ...(targetTruth === undefined ? [] : [targetTruth])]\n .map(({ observedOrdinal }) => observedOrdinal)\n const buildOrdinal = config.sourceBuildOrdinal\n ?? (observedOrdinals.length === 0 ? 0 : Math.max(...observedOrdinals) + 1)\n const fields = addressFields(config, delta, targetTruth, buildOrdinal)\n const candidateId = candidateContentAddress(fields)\n const leaseId = config.writerLeaseId\n const candidateDir = claimedCandidateDir(config.knowledgeRoot, leaseId, candidateId)\n const artifactsDir = join(candidateDir, 'artifacts')\n const payload: CurationCandidatePayload = { candidateId, ...fields }\n\n const authorship = syntheticAuthorship(config, delta)\n return {\n job: {\n kind: 'claimed',\n candidateId,\n leaseId,\n payload,\n candidateDir,\n payloadPath: join(candidateDir, 'payload.json'),\n artifactsDir,\n targetProducts: Object.fromEntries(\n [...neighbors, ...(targetTruth === undefined ? [] : [targetTruth])]\n .map((truth) => [truth.id, truth.product]),\n ),\n ...(config.screenStates === undefined ? {} : { screenStates: config.screenStates }),\n },\n checkpoint: {\n schemaVersion: AUTHORED_CHECKPOINT_SCHEMA_VERSION,\n delta,\n neighborIds: neighbors.map(({ id }) => id),\n preconditions: neighbors.map(({ id, observedStatus, observedOrdinal }) => ({\n recordId: id,\n observedStatus,\n observedOrdinal,\n })),\n authorship,\n },\n }\n}\n\nfunction completed(outcome: CommitCurationOutcome): boolean {\n return outcome.kind === 'applied'\n || outcome.kind === 'downgraded'\n || outcome.kind === 'converted-confirm'\n || outcome.kind === 'noop'\n}\n\nfunction promotionBuildOrdinal(\n config: CreateLocalKnowledgeStoreConfig,\n bundle: LoadedBundle,\n): number {\n return config.sourceBuildOrdinal ?? Math.max(\n bundle.frontmatter.createdAtOrdinal,\n ...bundle.events.map(({ buildOrdinal }) => buildOrdinal),\n )\n}\n\nfunction expectedPromotionHold(error: unknown): error is KnowledgePromotionError & {\n reason: PromotionGateHoldReason | 'propose-only'\n} {\n return error instanceof KnowledgePromotionError && error.reason !== 'not-found'\n}\n\nfunction unreachableCanaryOutcome(outcome: never): never {\n throw new TypeError(`unsupported canary outcome: ${canonicalJson(outcome)}`)\n}\n\n/**\n * Who is asking for this write. `automatic` is the curator and the agent port, whose authority\n * follows the run's execution context (432 D-08: ci/cloud stay proposed). `explicit` is a\n * person's mark, accept, reject or forget, which is authority in every context (D-04/D-05).\n */\ntype WriteAuthority = 'automatic' | 'explicit'\n\nconst EXPLICIT_PROFILE: DispositionProfile = Object.freeze({ mode: 'drain-to-active' })\n\n/**\n * The one place write authority becomes a disposition profile. Explicit authority skips only the\n * automatic propose-only downgrade: the store still records the actual execution context, and\n * delta validation and every promotion gate apply unchanged.\n */\nfunction dispositionProfileFor(\n config: CreateLocalKnowledgeStoreConfig,\n authority: WriteAuthority,\n): DispositionProfile {\n return authority === 'explicit' ? EXPLICIT_PROFILE : resolveDispositionProfile(config.executionContext)\n}\n\n/** The write face an explicit review needs: commit, gated promotion and gate receipts only. */\nexport type ExplicitReviewStore = Pick<KnowledgePort, 'commit' | 'promote' | 'recordGateReceipt'>\n\n/**\n * Realizes the agent write port over the canonical mutation path. D-08 propose-only is a\n * disposition profile inside commitCurationDelta, never a second mutation path. Because the port\n * carries bare deltas, this bridge materializes the smallest queue/checkpoint envelope and resolves\n * cited neighbor truth from canonical bundles before entering disposition.\n */\nexport function createLocalKnowledgeStore(\n config: CreateLocalKnowledgeStoreConfig,\n): KnowledgePort {\n return buildLocalKnowledgeStore(config, 'automatic')\n}\n\n/**\n * @internal The narrow explicit-authority entry for the review writer (432-06). Not on the\n * package barrel: only `applyReview` / `applyExplicitReview` construct it, under the caller's\n * writer lease. Canary and proposal-only doors are deliberately absent from its face.\n */\nexport function createExplicitReviewStore(\n config: CreateLocalKnowledgeStoreConfig,\n): ExplicitReviewStore {\n const { commit, promote, recordGateReceipt } = buildLocalKnowledgeStore(config, 'explicit')\n return { commit, promote, recordGateReceipt }\n}\n\nfunction buildLocalKnowledgeStore(\n config: CreateLocalKnowledgeStoreConfig,\n authority: WriteAuthority,\n): KnowledgePort {\n const priors = snapshotTrustPriors(config.resolveTrustPriors?.())\n const operation = config.operations?.commitCurationDelta ?? commitCurationDelta\n\n function bundleStoreConfig(productKey: string): BundleStoreConfig {\n return {\n knowledgeRoot: config.knowledgeRoot,\n productKey,\n commitArtifacts: 'none',\n writerLeaseId: config.writerLeaseId,\n }\n }\n\n function checkedAppend(candidateId: RecordId, appended: AppendOutcome): GateReceiptRecordOutcome {\n if (appended.kind === 'not-found') throw new KnowledgePromotionError(candidateId, appended.kind)\n return appended\n }\n\n function reportHold(error: unknown): void {\n if (expectedPromotionHold(error) && error.reason !== 'propose-only') {\n config.onPromotionOutcome?.({ candidateId: error.candidateId, promotionHoldReason: error.reason })\n }\n }\n\n /**\n * @internal The caller must already hold withCurrentWriterAuthority for this root. Every\n * append and projection below is irreversible canonical work, so the whole gate-and-write\n * body lives in one section rather than re-entering the fence per unit.\n */\n function promoteWithinCurrentAuthority(\n candidateId: RecordId,\n profile: DispositionProfile = dispositionProfileFor(config, 'automatic'),\n ): PromotionOutcome {\n /**\n * D-17: later callers add evidence first, then ask this same gate to judge it. The\n * execution posture is resolved at call time; canary evidence is always automatic, and\n * only `promote` passes the store's own authority.\n */\n if (profile.mode === 'propose-only') {\n throw new KnowledgePromotionError(candidateId, 'propose-only')\n }\n\n const resolved = resolveTruth(config.knowledgeRoot, candidateId, priors)\n if (resolved === undefined) {\n throw new KnowledgePromotionError(candidateId, 'not-found')\n }\n const appendConfig = bundleStoreConfig(resolved.product)\n if (resolved.observedStatus === 'active') {\n /**\n * CR-01: the active fast path is a gate re-validation, never a bypass. A crash\n * between a rollback's confirmation retraction and its Plan-23 promotion cascade\n * leaves canonical active-with-zero-support until replay; attesting success over\n * that stale authority would launder a rolled-back promotion. The same pure gate\n * (D-17) is re-evaluated over the promoted-set-aside status: the status the record\n * would hold if its promoted authority were set aside.\n */\n const gateInput = assemblePromotionGateInput({\n knowledgeRoot: config.knowledgeRoot,\n bundleDir: resolved.bundleDir,\n bundle: resolved.bundle,\n resolvePromotionPosture: config.resolvePromotionPosture,\n ...(priors === undefined ? {} : { priors }),\n })\n const setAside = foldBundleTrust(\n survivingOutcomeEvents(resolved.bundle.events)\n .filter(({ type }) => type !== 'promoted'),\n {\n originClass: resolved.bundle.frontmatter.originClass,\n evidenceIncomplete: resolved.bundle.manifest.evidenceIncomplete,\n createdAtOrdinal: resolved.bundle.frontmatter.createdAtOrdinal,\n },\n priors,\n )\n // 416-DOOR: door-1-2 revalidation\n const revalidated = evaluatePromotionGate({ ...gateInput, status: setAside.status })\n if (revalidated.verdict === 'promote') {\n // Receipt strength can grow without granting a second lifecycle authority event.\n const onDisk = strongestPromotionPath(readGateReceipts(resolved.bundleDir, candidateId) ?? [])\n if (onDisk === undefined || (revalidated.promotionPath !== onDisk\n && strongerPromotionPath(revalidated.promotionPath, onDisk) === revalidated.promotionPath)) {\n checkedAppend(candidateId, appendPromotionReceipt(appendConfig, candidateId, {\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION, kind: 'promotion', candidateId,\n promotionPath: revalidated.promotionPath,\n citedReceiptDigests: revalidated.citedReceiptDigests,\n producedAtOrdinal: promotionBuildOrdinal(config, resolved.bundle),\n producedBy: { opId: 'promote' },\n }))\n }\n // Still authorized: heal append-before-projection retries.\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(priors === undefined ? {} : { priors }),\n knowledgeRoot: config.knowledgeRoot,\n bundleId: candidateId,\n product: resolved.product,\n })\n const promotionPath = strongestPromotionPath(readGateReceipts(resolved.bundleDir, candidateId) ?? [])\n config.onPromotionOutcome?.({ candidateId, ...(promotionPath === undefined ? {} : { promotionPath }) })\n return { kind: 'already-active', ...(promotionPath === undefined ? {} : { promotionPath }) }\n }\n // Stale authority: append-only retraction of every surviving promoted event under a\n // deterministic replay-safe identity, then re-project and refuse with the gate's\n // hold reason. History is never rewritten; replayed heals dedup to no-ops.\n const survivingPromoted = survivingOutcomeEvents(resolved.bundle.events)\n .filter(({ type }) => type === 'promoted')\n const healReceiptId = `promote-heal:${candidateId}`\n for (const promoted of survivingPromoted) {\n const appended = appendOutcomeEvent(appendConfig, candidateId, {\n type: 'retracted',\n evidenceToken: asEvidenceToken(sha256hex(canonicalJson({\n healedPromotedEventKey: eventDedupKey(promoted),\n candidateId,\n }))),\n curationJobId: healReceiptId,\n buildOrdinal: promotionBuildOrdinal(config, resolved.bundle),\n retractsEvidenceToken: promoted.evidenceToken,\n retractsCurationJobId: promoted.curationJobId,\n rollbackReceiptId: healReceiptId,\n })\n if (appended.kind === 'not-found') {\n throw new KnowledgePromotionError(candidateId, appended.kind)\n }\n }\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(priors === undefined ? {} : { priors }),\n knowledgeRoot: config.knowledgeRoot,\n bundleId: candidateId,\n product: resolved.product,\n })\n throw new KnowledgePromotionError(candidateId, revalidated.reason)\n }\n\n // 416-DOOR: door-1-2 gate\n const gate = evaluatePromotionGate(assemblePromotionGateInput({\n knowledgeRoot: config.knowledgeRoot,\n bundleDir: resolved.bundleDir,\n bundle: resolved.bundle,\n resolvePromotionPosture: config.resolvePromotionPosture,\n ...(priors === undefined ? {} : { priors }),\n }))\n if (gate.verdict === 'hold') {\n throw new KnowledgePromotionError(candidateId, gate.reason)\n }\n // Keep v51's first-promotion identity, but do not reuse authority that the\n // append-only fold has retracted. A recovery episode is keyed by the durable\n // retractions of earlier promotions, so retries share an identity and a later\n // hold/recovery gets a new one. Ordinary path upgrades still append no event.\n const promotedKeys = new Set(resolved.bundle.events\n .filter(event => event.type === 'promoted').map(eventDedupKey))\n const recoveryBoundary = [...new Set(resolved.bundle.events.flatMap(event =>\n event.type === 'retracted'\n && promotedKeys.has(eventDedupKey({ ...event,\n evidenceToken: event.retractsEvidenceToken, curationJobId: event.retractsCurationJobId }))\n ? [eventDedupKey(event)] : [],\n ))].sort()\n const promotionSource = recoveryBoundary.length === 0 ? candidateId\n : canonicalJson({ candidateId, retractedPromotionEvents: recoveryBoundary })\n const appended = appendOutcomeEvent(appendConfig, candidateId, {\n // 416-DOOR: door-1-2 promoted\n type: 'promoted',\n evidenceToken: derivePromotedEvidenceToken(promotionSource),\n curationJobId: `promote:${candidateId}`,\n buildOrdinal: promotionBuildOrdinal(config, resolved.bundle),\n })\n if (appended.kind === 'not-found') {\n throw new KnowledgePromotionError(candidateId, appended.kind)\n }\n const receipt = appendPromotionReceipt(appendConfig, candidateId, {\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION,\n kind: 'promotion',\n candidateId,\n promotionPath: gate.promotionPath,\n citedReceiptDigests: gate.citedReceiptDigests,\n producedAtOrdinal: promotionBuildOrdinal(config, resolved.bundle),\n producedBy: { opId: 'promote' },\n })\n if (receipt.kind === 'not-found') throw new KnowledgePromotionError(candidateId, receipt.kind)\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(priors === undefined ? {} : { priors }),\n knowledgeRoot: config.knowledgeRoot,\n bundleId: candidateId,\n product: resolved.product,\n })\n config.onPromotionOutcome?.({ candidateId, promotionPath: gate.promotionPath })\n return { kind: 'promoted', promotionPath: gate.promotionPath, citedReceiptDigests: gate.citedReceiptDigests }\n }\n\n // 419-COMMIT-DOOR: curator profile pipeline\n async function commitWithProfile(\n deltas: Delta[],\n profile: DispositionProfile,\n ): Promise<void> {\n const drainState: CommitCurationDependencies['drainState'] = {\n supersedesSeenByAnchorKey: new Map(),\n }\n for (const delta of deltas) {\n /**\n * WR-02 / D-02: this bridge intentionally has no durable procedure observations or\n * capture artifacts. Disposition would therefore return a guaranteed procedure Noop,\n * which completed() would otherwise launder into a resolved void. Reject before\n * bridgeDelta materializes a claimed queue envelope; evidence carriage remains M4 scope.\n */\n if (draft(delta)?.kind === 'procedure') {\n throw new KnowledgeUnsupportedDeltaError(delta.kind)\n }\n const { job, checkpoint } = bridgeDelta(config, delta, priors)\n const outcome = operation(\n {\n knowledgeRoot: config.knowledgeRoot,\n epoch: currentAuthority(config).epoch,\n profile,\n drainState,\n ...(priors === undefined ? {} : { priors }),\n ...(config.resolvePromotionPosture === undefined\n ? {}\n : { resolvePromotionPosture: config.resolvePromotionPosture }),\n },\n job,\n checkpoint,\n )\n if (!completed(outcome)) throw new KnowledgeCommitError(outcome)\n }\n }\n\n function gate2ReceiptFor(outcome: CanaryOutcome, verdict: 'pass' | 'fail' | 'abstain') {\n if (outcome.corpusDigest === undefined) throw new TypeError('Gate-2 receipt requires a corpus digest')\n return stampReceiptDigest({\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION, gate: 2 as const, candidateId: outcome.candidateId,\n verdict, producedAtOrdinal: outcome.buildOrdinal,\n producedBy: { ...(config.sourceJobId === undefined ? {} : { jobId: config.sourceJobId }),\n opId: 'canary.record' },\n attributedObservationId: canaryOutcomeObservationId(outcome),\n corpusVersion: { corpusDigest: outcome.corpusDigest },\n benefit: outcome.runOutcome === 'negative' ? 'exercised-harmed' as const : outcome.benefit,\n stateValidity: outcome.stateValidity,\n runId: outcome.runId, testIndex: outcome.testIndex, stepIndex: outcome.stepIndex,\n attribution: outcome.attribution,\n ...(outcome.observedStateDigest === undefined ? {} : { observedStateDigest: outcome.observedStateDigest }),\n ...(outcome.ablation === undefined ? {} : {\n crossCheck: outcome.ablation.crossCheck,\n samples: { k: outcome.ablation.k, seeds: outcome.ablation.seeds,\n seedHonored: outcome.ablation.seedHonored, modelCalls: outcome.ablation.spend.modelCalls },\n spend: outcome.ablation.spend,\n }),\n })\n }\n\n const store: KnowledgePort = {\n proposeDeltas(deltas: Delta[]): Promise<void> {\n // 419-COMMIT-DOOR: curator propose-only\n return commitWithProfile(deltas, { mode: 'propose-only' })\n },\n commit(deltas: Delta[]): Promise<void> {\n // 419-COMMIT-DOOR: curator disposition\n return commitWithProfile(deltas, dispositionProfileFor(config, authority))\n },\n async recordCanaryOutcome(outcome: CanaryOutcome): Promise<void> {\n const resolved = resolveTruth(config.knowledgeRoot, outcome.candidateId, priors)\n if (resolved === undefined) {\n throw new KnowledgePromotionError(outcome.candidateId, 'not-found')\n }\n\n const observationId = canaryOutcomeObservationId(outcome)\n const evidenceToken = deriveEvidenceToken({\n attributingObservationId: observationId,\n anchor: outcome.exercisedAnchor,\n buildOrdinal: outcome.buildOrdinal,\n })\n\n switch (outcome.runOutcome) {\n case 'positive': {\n // D-22: the LLM never re-enters candidate lifecycle disposition. The one commit path\n // appends the replay-safe Confirm before the existing promotion gate re-evaluates it.\n const confirm: Extract<Delta, { kind: 'Confirm' }> = {\n kind: 'Confirm',\n origin: 'system',\n scope: resolved.bundle.frontmatter.scope,\n citedIds: [outcome.candidateId],\n targetId: outcome.candidateId,\n evidenceToken,\n authorship: {\n path: 'deterministic-fallback',\n executionContext: config.executionContext,\n },\n }\n // 419-COMMIT-DOOR: curator canary confirm\n await store.commit([confirm])\n /**\n * CR-02: the Confirm has its own fenced commit pipeline; the promotion tail that\n * follows it is a second, separate held section which the caller's terminal job-state\n * write joins. A takeover between the two leaves the durable Confirm as valid replay\n * evidence, which is exactly what lets the successor's drain finish the candidate.\n */\n config.canaryAuthorityHooks?.beforePromotionAppend?.()\n withCurrentWriterAuthority(config.knowledgeRoot, currentAuthority(config), () => {\n // 2026-09-07, 418 D-05/D-06/D-07: retain evidence regardless of Gate-1 state.\n // The observation supplies its ordinal; the shared routine decides order and reports holds.\n if (outcome.benefit === 'exercised-benefited' && outcome.corpusDigest !== undefined) {\n const receipt = gate2ReceiptFor(outcome, 'pass')\n const appendConfig = bundleStoreConfig(resolved.product)\n checkedAppend(outcome.candidateId, appendGateReceipt(appendConfig, outcome.candidateId, receipt))\n }\n try {\n promoteWithinCurrentAuthority(outcome.candidateId)\n } catch (error) {\n // A gate hold or propose-only posture means \"not yet\". The durable Confirm remains\n // valid evidence and must not turn a crash replay into a permanently failing job.\n if (!expectedPromotionHold(error)) throw error\n // 2026-09-30, 432-10 D-05: the hold is reported from evidence and nothing is filed.\n reportHold(error)\n }\n config.onCanaryTailWithinCurrentAuthority?.()\n })\n return\n }\n case 'negative': {\n // D-22: negative canary evidence joins the canonical outcome log and therefore reuses\n // the existing deterministic trust/status fold; no parallel lifecycle logic is added.\n const appendConfig = bundleStoreConfig(resolved.product)\n /**\n * CR-02: contradicted evidence is trust/status currency, so the append, the projection\n * it implies, and the caller's terminal job-state write are ONE held section. A\n * takeover completed at the barrier below therefore finds nothing of this writer\n * landed, and a contender arriving after entry is told who holds the tail instead.\n */\n config.canaryAuthorityHooks?.beforeNegativeAppend?.()\n withCurrentWriterAuthority(config.knowledgeRoot, currentAuthority(config), () => {\n // 2026-09-07, 418 D-08/D-12: digest-less BYOM keeps v51's single-sample\n // law BEFORE stale policy. State validity is independent of eval-root presence:\n // retain truthful stale evidence, but never await a receipt we cannot write.\n // Valid/unknown states likewise keep single-sample contradiction.\n if (outcome.corpusDigest !== undefined && outcome.stateValidity === 'stale') {\n const current = resolveTruth(config.knowledgeRoot, outcome.candidateId, priors)\n if (current === undefined) throw new KnowledgePromotionError(outcome.candidateId, 'not-found')\n const validity = deriveBundleTrust(current.bundle, priors).validity\n const insideWindow = (ordinal: number) => ordinal >= validity.openedAtOrdinal\n && (validity.closedAtOrdinal === undefined || ordinal <= validity.closedAtOrdinal)\n const priorRuns = new Set((readGateReceipts(current.bundleDir, outcome.candidateId) ?? [])\n .flatMap(receipt => !isPromotionReceipt(receipt) && receipt.gate === 2\n && receipt.verdict === 'abstain' && receipt.stateValidity === 'stale'\n && receipt.benefit === 'exercised-harmed' && receipt.runId !== undefined\n && receipt.runId !== outcome.runId && insideWindow(receipt.producedAtOrdinal)\n ? [receipt.runId] : []))\n if (!insideWindow(outcome.buildOrdinal) || priorRuns.size + 1 < GATE2_DEFAULT_STALE_CONFIRMATIONS) {\n const receipt = gate2ReceiptFor(outcome, 'abstain')\n checkedAppend(outcome.candidateId, appendGateReceipt(appendConfig, outcome.candidateId, receipt))\n config.onCanaryTailWithinCurrentAuthority?.()\n return\n }\n }\n const appended = appendOutcomeEvent(appendConfig, outcome.candidateId, {\n type: 'contradicted',\n evidenceToken,\n curationJobId: observationId,\n buildOrdinal: outcome.buildOrdinal,\n observationOrdinal: outcome.stepIndex,\n observationId,\n origin: 'agent-verified',\n })\n if (appended.kind === 'not-found') {\n throw new KnowledgePromotionError(outcome.candidateId, appended.kind)\n }\n if (outcome.corpusDigest !== undefined) {\n const receipt = gate2ReceiptFor(outcome, 'fail')\n checkedAppend(outcome.candidateId, appendGateReceipt(appendConfig, outcome.candidateId, receipt))\n try {\n promoteWithinCurrentAuthority(outcome.candidateId)\n } catch (error) {\n if (!expectedPromotionHold(error)) throw error\n reportHold(error)\n }\n }\n config.canaryAuthorityHooks?.beforeIndexProjection?.()\n applyIndexDeltaForBundleWithinCurrentAuthority({\n ...(priors === undefined ? {} : { priors }),\n knowledgeRoot: config.knowledgeRoot,\n bundleId: outcome.candidateId,\n product: resolved.product,\n })\n config.onCanaryTailWithinCurrentAuthority?.()\n })\n return\n }\n default:\n return unreachableCanaryOutcome(outcome.runOutcome)\n }\n },\n async promote(candidateId: RecordId, receipts?: readonly GateReceipt[]): Promise<PromotionOutcome> {\n return withCurrentWriterAuthority(config.knowledgeRoot, currentAuthority(config), () => {\n const profile = dispositionProfileFor(config, authority)\n if (profile.mode === 'propose-only') {\n throw new KnowledgePromotionError(candidateId, 'propose-only')\n }\n const resolved = resolveTruth(config.knowledgeRoot, candidateId, priors)\n if (resolved === undefined) throw new KnowledgePromotionError(candidateId, 'not-found')\n // Validate the entire batch before its first append; a later malformed item must not\n // leave earlier caller evidence durable. Appenders independently repeat these checks.\n const validated = (receipts ?? []).map(receipt => {\n const parsed = GateReceiptSchema.parse(receipt)\n if (parsed.candidateId !== candidateId) throw new TypeError('foreign candidateId')\n if (receiptDigestOf(parsed) !== parsed.receiptDigest) throw new TypeError('receiptDigest mismatch')\n return parsed\n })\n const appendConfig = bundleStoreConfig(resolved.product)\n for (const receipt of validated) checkedAppend(candidateId, appendGateReceipt(appendConfig, candidateId, receipt))\n try {\n return promoteWithinCurrentAuthority(candidateId, profile)\n } catch (error) {\n reportHold(error)\n throw error\n }\n })\n },\n async recordGateReceipt(receipt: GateReceipt): Promise<GateReceiptRecordOutcome> {\n return withCurrentWriterAuthority(config.knowledgeRoot, currentAuthority(config), () => {\n const candidateId = asRecordId(receipt.candidateId)\n const resolved = resolveTruth(config.knowledgeRoot, candidateId, priors)\n if (resolved === undefined) throw new KnowledgePromotionError(candidateId, 'not-found')\n return checkedAppend(candidateId, appendGateReceipt(bundleStoreConfig(resolved.product), candidateId, receipt))\n })\n },\n }\n return store\n}\n","import type { TrustPriorTable } from '@vostride/agent-qa-schema'\nimport { snapshotTrustPriors } from '../promotion-gate-input.js'\nimport {\n acquireEmbedder,\n type AcquireEmbedderOutcome,\n} from '../embedder-acquire.js'\nimport {\n runKnowledgeGc,\n type GcSummary,\n type RunKnowledgeGcHooks,\n} from '../gc.js'\nimport { readIndexMaintenanceState, type IndexMaintenanceState } from '../index-open.js'\nimport {\n rebuildIndex,\n removeBundleProjectionRows,\n type RebuildReport,\n} from '../index-rebuild.js'\nimport {\n WriterAuthorityLostError,\n type WriterLeaseAuthority,\n} from '../lease/writer-lease.js'\nimport {\n readRebuildRequest,\n type RebuildRequest,\n} from '../rebuild-marker.js'\n\nexport type MaintenanceSkipReason =\n | 'lease-held'\n | 'budget-exhausted'\n | 'aborted'\n | 'daemon-cadence'\n\nexport type WriterPassReport =\n | { kind: 'not-requested' }\n | { kind: 'skipped'; reason: MaintenanceSkipReason }\n | {\n kind: 'rebuilt'\n request?: RebuildRequest\n rebuild: RebuildReport\n }\n | { kind: 'failed'; message: string }\n\nexport type GcPassReport =\n | { kind: 'not-run' }\n | { kind: 'skipped'; reason: MaintenanceSkipReason }\n | {\n kind: 'completed'\n summary: GcSummary\n /** WR-01: projection rows removed by the same-tail scoped cleanup; absent on zero-trim. */\n projectionRowsRemoved?: number\n }\n | { kind: 'failed'; message: string }\n\nexport interface MaintenanceOperations {\n readRebuildRequest: typeof readRebuildRequest\n readIndexMaintenanceState: typeof readIndexMaintenanceState\n acquireEmbedder: typeof acquireEmbedder\n rebuildIndex: typeof rebuildIndex\n runKnowledgeGc: typeof runKnowledgeGc\n removeBundleProjectionRows: typeof removeBundleProjectionRows\n beforeGcRemoval?: RunKnowledgeGcHooks['beforeGcRemoval']\n}\n\nexport interface MaintenanceBudget {\n now: () => number\n startedAtMs: number\n limitMs: number\n}\n\nexport interface RunMaintenanceTailOptions {\n knowledgeRoot: string\n /** Same host-resolved data supplied to drains and review stores. */\n priors?: TrustPriorTable\n lease: { leaseId: string; epoch: number }\n /** Host-resolved posture; daemon callers pass worker-required, one-shot callers omit it. */\n embeddingCapability?: AcquireEmbedderOutcome\n /** Omit for daemon cadence; one-shot drains provide their 60 s boundary explicitly. */\n budget?: MaintenanceBudget\n /** Fault-injection seam; production callers must omit it. */\n operations?: Partial<MaintenanceOperations>\n /** One-shot drains fold authority loss into their report; daemon callers surface it by default. */\n surfaceAuthorityLoss?: boolean\n}\n\nexport interface MaintenanceTailFailure {\n stage: 'writer-pass' | 'gc'\n error: unknown\n}\n\nexport interface MaintenanceTailResult {\n writerPass: WriterPassReport\n gc: GcPassReport\n failures: MaintenanceTailFailure[]\n}\n\nconst DEFAULT_OPERATIONS: MaintenanceOperations = {\n readRebuildRequest,\n readIndexMaintenanceState,\n acquireEmbedder,\n rebuildIndex,\n runKnowledgeGc,\n removeBundleProjectionRows,\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction hasIndexMaintenanceDebt(state: IndexMaintenanceState): boolean {\n return state.indexAbsent\n || state.pendingEmbeddings > 0\n || state.renderingEpochStale\n || state.vectorReconciliationOutstanding\n}\n\nfunction budgetExhausted(budget: MaintenanceBudget | undefined): boolean {\n return budget !== undefined && budget.now() - budget.startedAtMs >= budget.limitMs\n}\n\nasync function runWriterPass(\n options: RunMaintenanceTailOptions,\n operations: MaintenanceOperations,\n): Promise<WriterPassReport> {\n const marker = operations.readRebuildRequest(options.knowledgeRoot)\n const maintenance = operations.readIndexMaintenanceState(options.knowledgeRoot)\n if (!marker.present && !hasIndexMaintenanceDebt(maintenance)) {\n return { kind: 'not-requested' }\n }\n\n const capability = options.embeddingCapability\n ?? await operations.acquireEmbedder({ allowDownload: false })\n const injectedRebuild = options.operations?.rebuildIndex !== undefined\n const rebuild = await operations.rebuildIndex({\n knowledgeRoot: options.knowledgeRoot,\n ...(options.priors === undefined ? {} : { priors: options.priors }),\n ...(capability.kind === 'ready' ? { embedder: capability.embedder } : {}),\n // Production rebuilds retain Phase 385's fresh authority fence at every mutation boundary.\n // Fault-injection rebuilds keep their historical call shape and own their injected behavior.\n ...(injectedRebuild\n ? {}\n : {\n writerAuthority: {\n knowledgeRoot: options.knowledgeRoot,\n leaseId: options.lease.leaseId,\n epoch: options.lease.epoch,\n },\n }),\n })\n return {\n kind: 'rebuilt',\n ...(marker.present && marker.request !== undefined ? { request: marker.request } : {}),\n rebuild,\n }\n}\n\nfunction shouldSurfaceAuthorityLoss(\n options: RunMaintenanceTailOptions,\n error: unknown,\n): boolean {\n return options.surfaceAuthorityLoss !== false && error instanceof WriterAuthorityLostError\n}\n\n/**\n * Run the writer-repair and canonical-GC tail as one host-independent callable.\n *\n * Daemon callers omit budget and receive stale authority errors unchanged. The one-shot drain\n * supplies its existing wall-clock boundary and folds typed failures into DrainReport.\n */\nexport async function runMaintenanceTail(\n options: RunMaintenanceTailOptions,\n): Promise<MaintenanceTailResult> {\n const priors = snapshotTrustPriors(options.priors)\n options = { ...options, ...(priors === undefined ? {} : { priors }) }\n const operations: MaintenanceOperations = {\n ...DEFAULT_OPERATIONS,\n ...options.operations,\n }\n const failures: MaintenanceTailFailure[] = []\n let writerPass: WriterPassReport\n let gc: GcPassReport = { kind: 'not-run' }\n\n try {\n writerPass = await runWriterPass(options, operations)\n } catch (error) {\n if (shouldSurfaceAuthorityLoss(options, error)) throw error\n failures.push({ stage: 'writer-pass', error })\n writerPass = { kind: 'failed', message: errorMessage(error) }\n }\n\n if (budgetExhausted(options.budget)) {\n return {\n writerPass,\n gc: { kind: 'skipped', reason: 'budget-exhausted' },\n failures,\n }\n }\n\n try {\n /**\n * D-13 M2 has no gate receipts. Phase 380 adds live canary-reference exclusions; M3 supplies\n * the real ordinal horizon through this seam. Budget gates the start only and never\n * interrupts whole-dir trims.\n */\n const writerAuthority: WriterLeaseAuthority = {\n knowledgeRoot: options.knowledgeRoot,\n leaseId: options.lease.leaseId,\n epoch: options.lease.epoch,\n }\n const summary = operations.runKnowledgeGc(\n {\n knowledgeRoot: options.knowledgeRoot,\n horizon: { kind: 'none' },\n },\n writerAuthority,\n { beforeGcRemoval: operations.beforeGcRemoval },\n )\n const completed: Extract<GcPassReport, { kind: 'completed' }> = {\n kind: 'completed',\n summary,\n }\n gc = completed\n if (summary.trimmedRecordIds.length > 0) {\n try {\n completed.projectionRowsRemoved = operations.removeBundleProjectionRows(\n options.knowledgeRoot,\n summary.trimmedRecordIds,\n writerAuthority,\n )\n } catch (error) {\n if (shouldSurfaceAuthorityLoss(options, error)) throw error\n // Canonical truth was already trimmed; preserve the projection debt as a typed failure.\n failures.push({ stage: 'gc', error })\n }\n }\n } catch (error) {\n if (shouldSurfaceAuthorityLoss(options, error)) throw error\n failures.push({ stage: 'gc', error })\n gc = { kind: 'failed', message: errorMessage(error) }\n }\n\n return { writerPass, gc, failures }\n}\n","/**\n * D-14's one true-delete exemption for confirmed-sensitive material.\n *\n * This library function owns only local store surfaces. It performs no git operation and never\n * attempts to rewrite repository history; Phase 382's sovereign CLI binding leaves that\n * destructive, repository-wide decision with the human operator.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport {\n existsSync,\n linkSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport type { Dirent } from 'node:fs'\nimport { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'\n\nimport {\n canonicalJson,\n committedFileText,\n createVersionGuard,\n recordGraphNode,\n} from '@vostride/agent-qa-schema'\nimport type { RecordId } from '@vostride/agent-qa-schema'\nimport { z } from 'zod'\n\nimport { assertWithinKnowledgeRoot } from './knowledge-containment.js'\nimport { loadBundle } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\nimport { canaryOutcomePayloadSchema } from './canary-emit.js'\nimport { fsyncDirectory, fsyncFile } from './durable-fs.js'\nimport {\n deleteRecordFromAllSchemaVecTables,\n indexDbPath,\n openIndexWriter,\n} from './index-open.js'\nimport { refreshWriterLeaseAuthority } from './lease/writer-lease.js'\nimport type { WriterLeaseAuthority } from './lease/writer-lease.js'\nimport { jobStatePath, queueRoot } from './queue/queue-layout.js'\nimport { curationCandidatePayloadSchema } from './queue/queue-payload.js'\nimport {\n PURGE_RECEIPT_SCHEMA_VERSION,\n PURGE_SAFE_RECORD_ID as SAFE_RECORD_ID,\n PurgeReceiptSchema,\n guardPurgeReceipt,\n guardPurgeReceiptForFile,\n parseCanonicalPurgeReceiptFileName,\n purgeReceiptRelativePathSchema as receiptRelativePathSchema,\n} from './purge-receipt.js'\nimport type { PurgeReceipt } from './purge-receipt.js'\n\nexport {\n PURGE_RECEIPT_SCHEMA_VERSION,\n PurgeReceiptSchema,\n guardPurgeReceipt,\n purgeReceiptSchema,\n} from './purge-receipt.js'\nexport type { PurgeReceipt } from './purge-receipt.js'\n\n/**\n * Queue entries use 64-hex content addresses; prefixed maintenance receipt ids are not queue\n * identities.\n */\nconst QUEUE_CANDIDATE_ID = /^[0-9a-f]{64}$/\nconst PURGE_SAFE_PATH_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\nexport interface PurgeAffectedBundleTarget {\n product: string\n bundleDir: string\n kind: LoadedBundle['frontmatter']['kind']\n affectedPaths: string[]\n}\n\nexport interface PurgeAffectedQueueTarget {\n candidateId: string\n candidateDir: string\n jobStatePath: string\n}\n\n/**\n * Content-free, deterministic statement of every local surface one purge operation will affect.\n * This is the single planning shape shared by preview, the under-lease recheck, and destructive\n * execution.\n */\nexport interface PurgeAffectedSet {\n recordId: string\n state: 'live' | 'resume' | 'already-purged' | 'not-found'\n bundles: PurgeAffectedBundleTarget[]\n receiptAffectedPaths: string[]\n projectionTargets: string[]\n embedCacheAction: 'clear-all'\n queueTargets: PurgeAffectedQueueTarget[]\n intentPath: string\n receiptPath: string\n}\n\nconst PurgeAffectedBundleTargetSchema = z.object({\n product: z.string().min(1),\n bundleDir: receiptRelativePathSchema,\n kind: z.enum(['fact', 'procedure', 'caution', 'unknown', 'policy']),\n affectedPaths: z.array(receiptRelativePathSchema),\n}).strict()\n\nconst PurgeAffectedQueueTargetSchema = z.object({\n candidateId: z.string().regex(QUEUE_CANDIDATE_ID),\n candidateDir: receiptRelativePathSchema,\n jobStatePath: receiptRelativePathSchema,\n}).strict()\n\nconst PurgeAffectedSetSchema = z.object({\n recordId: z.string().regex(SAFE_RECORD_ID),\n state: z.enum(['live', 'resume', 'already-purged', 'not-found']),\n bundles: z.array(PurgeAffectedBundleTargetSchema),\n receiptAffectedPaths: z.array(receiptRelativePathSchema),\n projectionTargets: z.array(z.string()),\n embedCacheAction: z.literal('clear-all'),\n queueTargets: z.array(PurgeAffectedQueueTargetSchema),\n intentPath: receiptRelativePathSchema,\n receiptPath: receiptRelativePathSchema,\n}).strict()\n\nexport const PURGE_INTENT_SCHEMA_VERSION = 2\n\n/**\n * D-14/CR-04: the durable, content-free purge intent published before the first irreversible\n * mutation. It embeds the complete receipt payload plus the exact resolved bundle dirs, queue\n * candidate ids, and queue payload dirs, so a retry after a crash replays destruction from\n * persisted identities and completes to byte-identical receipt publication instead of returning\n * not-found over half-destroyed state. Every list is deterministically sorted at construction;\n * purged prose, anchors, observations, and vectors have no representable field.\n *\n * The intent also embeds its receipt cycle and the canonical affected set.\n */\nexport const PurgeIntentSchema = z.object({\n schemaVersion: z.literal(PURGE_INTENT_SCHEMA_VERSION),\n purgedRecordId: z.string().regex(SAFE_RECORD_ID),\n receipt: PurgeReceiptSchema,\n receiptCycle: z.number().int().positive(),\n bundleDirs: z.array(receiptRelativePathSchema).min(1),\n queueCandidateIds: z.array(z.string().regex(QUEUE_CANDIDATE_ID)),\n queuePayloadDirs: z.array(receiptRelativePathSchema),\n affectedSet: PurgeAffectedSetSchema,\n}).strict()\n\n/** Lower-camel schema alias follows the existing knowledge-local committed-file convention. */\nexport const purgeIntentSchema = PurgeIntentSchema\nexport type PurgeIntent = z.infer<typeof PurgeIntentSchema>\n\nconst guardPurgeIntentVersion = createVersionGuard<PurgeIntent>({\n name: 'PurgeIntent',\n current: PURGE_INTENT_SCHEMA_VERSION,\n migrations: {},\n})\n\nexport function guardPurgeIntent(value: unknown): PurgeIntent {\n return PurgeIntentSchema.parse(guardPurgeIntentVersion(value))\n}\n\nexport interface PurgeRecordInput {\n knowledgeRoot: string\n recordId: RecordId\n /** Caller-owned sovereign identity; Phase 382 supplies the confirmed user identity. */\n initiator: string\n /** Runtime-counter reservation used for a fresh destruction receipt; resumes reuse intent. */\n purgedAtOrdinal?: number\n /** Governed maintenance callers fence this exact lease at every mutation boundary. */\n writerAuthority?: WriterLeaseAuthority\n /** Fingerprint of the caller's preview; drift must fail before any mutation. */\n expectedAffectedSetFingerprint?: string\n /** Test/chaos seam between purge phases; production callers omit it (commit.ts precedent). */\n hooks?: {\n /** Immediately after the durable intent publication. */\n afterIntentWritten?: () => void\n /** After the transactional projection purge. */\n afterProjectionPurge?: () => void\n /** After every committed bundle tree removal. */\n afterBundleRemoval?: () => void\n /** After the queue payload sweep. */\n afterQueueSweep?: () => void\n /** Immediately before the completion receipt publication. */\n beforeReceiptPublish?: () => void\n }\n}\n\nexport type PurgeRecordOutcome =\n | { kind: 'purged'; receipt: PurgeReceipt }\n | { kind: 'already-purged'; receipt: PurgeReceipt }\n | { kind: 'not-found' }\n\ninterface ResolvedBundle {\n product: string\n dir: string\n bundle: LoadedBundle\n}\n\nexport class PurgeTargetChangedError extends Error {\n readonly code = 'purge-target-changed'\n\n constructor(\n readonly expectedFingerprint: string,\n readonly actualFingerprint: string,\n ) {\n super('purge target set changed after the preview')\n this.name = 'PurgeTargetChangedError'\n }\n}\n\nexport class PurgeTargetIntegrityError extends Error {\n readonly code = 'purge-target-integrity'\n\n constructor(readonly targetPath: string, readonly reason: string) {\n super(`purge target ${targetPath} is not safely readable: ${reason}`)\n this.name = 'PurgeTargetIntegrityError'\n }\n}\n\nexport class PurgeQueueIdentityError extends Error {\n readonly code = 'purge-queue-identity'\n\n constructor(readonly targetPath: string, readonly reason: string) {\n super(`purge cannot establish queue identity at ${targetPath}: ${reason}`)\n this.name = 'PurgeQueueIdentityError'\n }\n}\n\nexport class PurgeCompletionVerificationError extends Error {\n readonly code = 'purge-completion-verification'\n\n constructor(readonly survivingSurface: string) {\n super(`purge completion verification found a surviving surface: ${survivingSurface}`)\n this.name = 'PurgeCompletionVerificationError'\n }\n}\n\nexport class PurgeChronologyRequiredError extends Error {\n readonly code = 'purge-chronology-required'\n\n constructor() {\n super('fresh purge requires a runtime-counter purgedAtOrdinal reservation')\n this.name = 'PurgeChronologyRequiredError'\n }\n}\n\nfunction assertInput(input: PurgeRecordInput): void {\n if (!isAbsolute(input.knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n if (input.initiator.trim() === '') {\n throw new TypeError('initiator must be a non-empty caller-supplied identity')\n }\n if (!SAFE_RECORD_ID.test(input.recordId)) {\n throw new TypeError('recordId must be a safe path segment')\n }\n if (\n input.expectedAffectedSetFingerprint !== undefined\n && !/^[0-9a-f]{64}$/u.test(input.expectedAffectedSetFingerprint)\n ) {\n throw new TypeError('expectedAffectedSetFingerprint must be a lowercase SHA-256 hex digest')\n }\n if (\n input.purgedAtOrdinal !== undefined\n && (!Number.isSafeInteger(input.purgedAtOrdinal) || input.purgedAtOrdinal < 0)\n ) {\n throw new RangeError('purgedAtOrdinal must be a non-negative safe integer')\n }\n if (\n input.writerAuthority !== undefined\n && input.writerAuthority.knowledgeRoot !== input.knowledgeRoot\n ) {\n throw new TypeError('writerAuthority must belong to knowledgeRoot')\n }\n}\n\nfunction fenceWriterAuthority(input: PurgeRecordInput): void {\n if (input.writerAuthority === undefined) return\n if (input.writerAuthority.knowledgeRoot !== input.knowledgeRoot) {\n throw new TypeError('writerAuthority must belong to knowledgeRoot')\n }\n refreshWriterLeaseAuthority(input.writerAuthority)\n}\n\nfunction resolveBundles(knowledgeRoot: string, recordId: RecordId): ResolvedBundle[] {\n const matches: ResolvedBundle[] = []\n const memoryRoot = join(knowledgeRoot, 'memory')\n let entries: Dirent<string>[]\n try {\n entries = readdirSync(memoryRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {\n if (\n entry.name.startsWith('.')\n || entry.name === 'index'\n || entry.name === 'queue'\n || entry.name === 'receipts'\n ) continue\n const targetRelativePath = `memory/${entry.name}/bundles/${recordId}`\n const targetDir = join(knowledgeRoot, targetRelativePath)\n let targetStat\n try {\n targetStat = lstatSync(targetDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue\n throw error\n }\n if (\n !PURGE_SAFE_PATH_SEGMENT.test(entry.name)\n || entry.name === '.'\n || entry.name === '..'\n ) {\n throw new PurgeTargetIntegrityError(targetRelativePath, 'non-canonical product path')\n }\n assertNoSymlinkComponents(knowledgeRoot, targetRelativePath)\n if (!targetStat.isDirectory()) {\n throw new PurgeTargetIntegrityError(targetRelativePath, 'target is not a directory')\n }\n const loaded = loadBundle(targetDir)\n if (loaded.kind !== 'loaded') {\n throw new PurgeTargetIntegrityError(targetRelativePath, loaded.kind)\n }\n if (loaded.bundle.manifest.id !== recordId) {\n throw new PurgeTargetIntegrityError(\n targetRelativePath,\n `manifest identifies ${loaded.bundle.manifest.id}`,\n )\n }\n matches.push({ product: entry.name, dir: targetDir, bundle: loaded.bundle })\n }\n return matches\n}\n\nfunction transaction(operation: () => void, db: ReturnType<typeof openIndexWriter>['db']): void {\n db.exec('BEGIN IMMEDIATE')\n try {\n operation()\n db.exec('COMMIT')\n } catch (error) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // Preserve the deletion failure that caused the rollback.\n }\n throw error\n }\n}\n\n/** Reuse removeMissingBundles' total five-statement deletion set for one known record. */\nfunction purgeIndexSurfaces(\n knowledgeRoot: string,\n recordId: RecordId,\n kind?: LoadedBundle['frontmatter']['kind'],\n): void {\n if (!existsSync(indexDbPath(knowledgeRoot))) return\n\n const writer = openIndexWriter(knowledgeRoot)\n try {\n const row = writer.db\n .prepare('SELECT record_rowid, kind FROM records WHERE bundle_id = ?')\n .get(recordId)\n // A resume over destroyed bundles derives the graph identity from the projection row; when\n // both are gone the pre-removal projection purge already committed and only the idempotent\n // orphan-node and cache cleanup remains.\n const resolvedKind =\n kind\n ?? (row === undefined\n ? undefined\n : (String(row.kind) as LoadedBundle['frontmatter']['kind']))\n const recordNode =\n resolvedKind === undefined ? undefined : recordGraphNode(resolvedKind, recordId)\n\n transaction(() => {\n if (row !== undefined && recordNode !== undefined) {\n const recordRowid = Number(row.record_rowid)\n deleteRecordFromAllSchemaVecTables(writer.db, recordRowid)\n writer.db.prepare('DELETE FROM fts_records WHERE rowid = ?').run(recordRowid)\n writer.db.prepare('DELETE FROM anchors WHERE record_rowid = ?').run(recordRowid)\n writer.db.prepare(`\n DELETE FROM graph_edges\n WHERE record_rowid = ? OR src_node_id = ? OR dst_node_id = ?\n `).run(recordRowid, recordNode.nodeId, recordNode.nodeId)\n writer.db.prepare('DELETE FROM records WHERE record_rowid = ?').run(recordRowid)\n } else if (recordNode !== undefined) {\n // A stale graph projection can outlive a missing records row; remove both directions.\n writer.db.prepare(`\n DELETE FROM graph_edges\n WHERE src_node_id = ? OR dst_node_id = ?\n `).run(recordNode.nodeId, recordNode.nodeId)\n }\n\n writer.db.exec(`\n DELETE FROM graph_nodes\n WHERE node_id NOT IN (\n SELECT src_node_id FROM graph_edges\n UNION\n SELECT dst_node_id FROM graph_edges\n )\n `)\n\n /**\n * RATIFICATION A4 / RESEARCH Pitfall 9: clear the entire cache rather than guessing every\n * historical rendering hash. The table is a pure auto-rebuilt cache; sovereignty over the\n * invertible-vector channel outranks cache warmth.\n */\n const cachePresent = writer.db\n .prepare(`\n SELECT 1\n FROM sqlite_master\n WHERE type = 'table' AND name = 'embed_cache'\n `)\n .get()\n if (cachePresent !== undefined) {\n writer.db.prepare('DELETE FROM embed_cache').run()\n }\n }, writer.db)\n } finally {\n writer.close()\n }\n}\n\nfunction payloadDirectories(root: string): string[] {\n const found: string[] = []\n\n function visit(dir: string): void {\n let entries: Dirent<string>[]\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n\n if (entries.some((entry) => entry.isFile() && entry.name === 'payload.json')) {\n found.push(dir)\n return\n }\n for (const entry of entries) {\n if (entry.isDirectory()) visit(join(dir, entry.name))\n }\n }\n\n visit(root)\n return found.sort()\n}\n\nfunction removeEmptyQueueParents(\n candidateDir: string,\n root: string,\n beforeMutation?: () => void,\n): void {\n let current = dirname(candidateDir)\n while (current !== root && current.startsWith(`${root}${sep}`)) {\n try {\n beforeMutation?.()\n rmdirSync(current)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n current = dirname(current)\n continue\n }\n if (code === 'ENOTEMPTY' || code === 'EEXIST') return\n throw error\n }\n current = dirname(current)\n }\n}\n\n/** One exact queue deletion decided before any destruction (CR-03). */\nexport interface QueueSweepTarget {\n candidateDir: string\n /** Queue-entry identity used by the transport and job-state store, not payload lineage. */\n candidateId: string\n}\n\nfunction lineageCandidateIds(matches: readonly ResolvedBundle[]): Set<string> {\n const ids = new Set<string>(matches.map(({ bundle }) => bundle.manifest.id))\n for (const { bundle } of matches) {\n const jobIds = [\n ...(bundle.provenance.mode === 'run-linked'\n && bundle.provenance.curationJobId !== undefined\n ? [bundle.provenance.curationJobId]\n : []),\n ...bundle.events.map((event) => event.curationJobId),\n ...bundle.relations.relations.map((relation) => relation.curationJobId),\n ]\n for (const jobId of jobIds) {\n if (QUEUE_CANDIDATE_ID.test(jobId)) ids.add(jobId)\n }\n }\n return ids\n}\n\nfunction contentSeeds(matches: readonly ResolvedBundle[]): Set<string> {\n const seeds = new Set<string>()\n for (const { bundle } of matches) {\n if (bundle.summary !== '') seeds.add(bundle.summary)\n if (bundle.body !== '') seeds.add(bundle.body)\n }\n return seeds\n}\n\nfunction artifactDigests(matches: readonly ResolvedBundle[]): Set<string> {\n const digests = new Set<string>()\n for (const { bundle } of matches) {\n for (const digest of Object.values(bundle.manifest.contentHashes)) {\n digests.add(digest)\n }\n }\n return digests\n}\n\nfunction looselyCarriesPurgedContent(\n payload: unknown,\n seeds: ReadonlySet<string>,\n digests: ReadonlySet<string>,\n): boolean {\n if (typeof payload !== 'object' || payload === null) return false\n const loose = payload as Record<string, unknown>\n const seedMatch = [loose['summarySeed'], loose['bodySeed']].some(\n (seed) => typeof seed === 'string' && seeds.has(seed),\n )\n const inventory: unknown[] = Array.isArray(loose['artifactInventory'])\n ? loose['artifactInventory']\n : []\n return seedMatch || inventory.some((artifact) => {\n if (typeof artifact !== 'object' || artifact === null) return false\n const digest = (artifact as Record<string, unknown>)['sha256']\n return typeof digest === 'string' && digests.has(digest)\n })\n}\n\n/**\n * D-14/CR-03 deletion authority: a queue payload is destroyed iff it carries the purged content\n * or curation-job lineage — candidateId lineage, exact seed equality, or artifact digest\n * intersection. Anchor overlap never selects. The full set is resolved before any irreversible\n * mutation so the exact deletion intent exists ahead of destruction.\n */\nexport function resolveQueueSweepTargets(\n knowledgeRoot: string,\n matches: readonly ResolvedBundle[],\n): QueueSweepTarget[] {\n const lineage = lineageCandidateIds(matches)\n const seeds = contentSeeds(matches)\n const digests = artifactDigests(matches)\n\n const targets: QueueSweepTarget[] = []\n for (const candidateDir of payloadDirectories(queueRoot(knowledgeRoot))) {\n const candidateId = basename(candidateDir)\n if (!QUEUE_CANDIDATE_ID.test(candidateId)) {\n throw new PurgeQueueIdentityError(candidateDir, 'non-canonical candidate directory')\n }\n if (lineage.has(candidateId)) {\n targets.push({ candidateDir, candidateId })\n continue\n }\n\n let payload: unknown\n try {\n payload = JSON.parse(readFileSync(join(candidateDir, 'payload.json'), 'utf8'))\n } catch (error) {\n throw new PurgeQueueIdentityError(\n candidateDir,\n error instanceof Error ? error.message : 'malformed JSON payload',\n )\n }\n\n const curationCandidate = curationCandidatePayloadSchema.safeParse(payload)\n if (curationCandidate.success) {\n const {\n candidateId: lineageId,\n summarySeed,\n bodySeed,\n artifactInventory,\n } = curationCandidate.data\n const carriesPurgedIdentity =\n lineage.has(lineageId)\n || seeds.has(summarySeed)\n || seeds.has(bodySeed)\n || artifactInventory.some((artifact) => digests.has(artifact.sha256))\n if (carriesPurgedIdentity) targets.push({ candidateDir, candidateId })\n continue\n }\n\n const canaryOutcome = canaryOutcomePayloadSchema.safeParse(payload)\n if (canaryOutcome.success && lineage.has(canaryOutcome.data.candidateId)) {\n targets.push({ candidateDir, candidateId })\n continue\n }\n\n const payloadCandidateId = (\n typeof payload === 'object'\n && payload !== null\n && 'candidateId' in payload\n && typeof payload.candidateId === 'string'\n ) ? payload.candidateId : undefined\n if (payloadCandidateId !== undefined && lineage.has(payloadCandidateId)) {\n targets.push({ candidateDir, candidateId })\n continue\n }\n\n // A payload matching no current schema, including one stamped at another version, is read\n // loosely for the purged content and otherwise left in place.\n if (\n !curationCandidate.success\n && !canaryOutcome.success\n && looselyCarriesPurgedContent(payload, seeds, digests)\n ) {\n targets.push({ candidateDir, candidateId })\n }\n }\n return targets.sort((left, right) =>\n left.candidateDir < right.candidateDir\n ? -1\n : left.candidateDir > right.candidateDir\n ? 1\n : 0,\n )\n}\n\n/** Pure destruction pass over the pre-resolved exact deletion set. */\nfunction sweepQueuePayloads(\n input: PurgeRecordInput,\n targets: readonly QueueSweepTarget[],\n): void {\n const root = queueRoot(input.knowledgeRoot)\n for (const target of targets) {\n // 261003-mqc: never delete through a queue directory linked out of the knowledge root.\n assertWithinKnowledgeRoot(input.knowledgeRoot, target.candidateDir)\n assertWithinKnowledgeRoot(input.knowledgeRoot,\n dirname(jobStatePath(input.knowledgeRoot, target.candidateId)))\n fenceWriterAuthority(input)\n rmSync(target.candidateDir, { recursive: true, force: true })\n fenceWriterAuthority(input)\n rmSync(jobStatePath(input.knowledgeRoot, target.candidateId), { force: true })\n removeEmptyQueueParents(\n target.candidateDir,\n root,\n () => fenceWriterAuthority(input),\n )\n }\n}\n\nfunction assertPurgePathAbsent(knowledgeRoot: string, relativePath: string): void {\n try {\n lstatSync(join(knowledgeRoot, relativePath))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new PurgeCompletionVerificationError(relativePath)\n}\n\nfunction verifyPurgedIndexSurfaces(knowledgeRoot: string, recordId: RecordId): void {\n if (!existsSync(indexDbPath(knowledgeRoot))) return\n const writer = openIndexWriter(knowledgeRoot)\n try {\n if (writer.db.prepare('SELECT 1 FROM records WHERE bundle_id = ?').get(recordId)) {\n throw new PurgeCompletionVerificationError(`index records/${recordId}`)\n }\n const nodeIds = ['fact', 'procedure', 'caution', 'unknown', 'policy']\n .map((kind) => recordGraphNode(\n kind as LoadedBundle['frontmatter']['kind'],\n recordId,\n ).nodeId)\n for (const nodeId of nodeIds) {\n if (writer.db.prepare('SELECT 1 FROM graph_nodes WHERE node_id = ?').get(nodeId)) {\n throw new PurgeCompletionVerificationError(`index graph_nodes/${nodeId}`)\n }\n if (writer.db.prepare(`\n SELECT 1 FROM graph_edges WHERE src_node_id = ? OR dst_node_id = ?\n `).get(nodeId, nodeId)) {\n throw new PurgeCompletionVerificationError(`index graph_edges/${nodeId}`)\n }\n }\n } finally {\n writer.close()\n }\n}\n\n/** Fail closed immediately before receipt publication if any selected surface still exists. */\nfunction verifyPurgeCompletion(input: PurgeRecordInput, intent: PurgeIntent): void {\n const rediscoveredBundles = resolveBundles(input.knowledgeRoot, input.recordId)\n if (rediscoveredBundles.length > 0) {\n throw new PurgeCompletionVerificationError(\n toReceiptPath(input.knowledgeRoot, rediscoveredBundles[0]!.dir),\n )\n }\n for (const path of intent.bundleDirs) assertPurgePathAbsent(input.knowledgeRoot, path)\n for (const path of intent.queuePayloadDirs) assertPurgePathAbsent(input.knowledgeRoot, path)\n for (const candidateId of intent.queueCandidateIds) {\n assertPurgePathAbsent(\n input.knowledgeRoot,\n `memory/queue/jobs/${candidateId}.state.json`,\n )\n }\n const candidateIds = new Set(intent.queueCandidateIds)\n for (const dir of payloadDirectories(queueRoot(input.knowledgeRoot))) {\n if (candidateIds.has(basename(dir))) {\n throw new PurgeCompletionVerificationError(toReceiptPath(input.knowledgeRoot, dir))\n }\n }\n verifyPurgedIndexSurfaces(input.knowledgeRoot, input.recordId)\n}\n\n/**\n * The append-only receipt series: cycle 1 IS the pre-existing base receipt path, cycle N >= 2\n * lives beside it with the cycle number suffixed. Each destruction of a record id is its own\n * auditable event; earlier cycles' bytes never change.\n */\nfunction receiptCycleRelativePath(recordId: RecordId, cycle: number): string {\n return cycle === 1\n ? `memory/receipts/purge-${recordId}.json`\n : `memory/receipts/purge-${recordId}.${cycle}.json`\n}\n\nfunction receiptCyclePath(knowledgeRoot: string, recordId: RecordId, cycle: number): string {\n const fileName = receiptCycleRelativePath(recordId, cycle).split('/').at(-1)!\n return join(knowledgeRoot, 'memory', 'receipts', fileName)\n}\n\n/** The intent lives beside the receipt series it completes into. */\nfunction intentPath(knowledgeRoot: string, recordId: RecordId): string {\n return join(knowledgeRoot, 'memory', 'receipts', `purge-${recordId}.intent.json`)\n}\n\nfunction readReceiptAtCycle(\n knowledgeRoot: string,\n recordId: RecordId,\n cycle: number,\n): PurgeReceipt | undefined {\n const file = receiptCyclePath(knowledgeRoot, recordId, cycle)\n if (!existsSync(file)) return undefined\n return guardPurgeReceiptForFile(\n JSON.parse(readFileSync(file, 'utf8')),\n basename(file),\n { recordId, cycle },\n )\n}\n\ninterface ReceiptSeries {\n /** The most recent destruction receipt, undefined when the series is empty. */\n latestReceipt: PurgeReceipt | undefined\n /** The first free cycle slot; cycles are dense from 1 by construction. */\n nextCycle: number\n}\n\n/**\n * Probe the durable series upward from the base path. Cycles are published exclusively and in\n * order, so the first missing slot is the next cycle and the slot before it holds the latest\n * receipt — the derivation is deterministic over store state alone.\n */\nfunction resolveReceiptSeries(knowledgeRoot: string, recordId: RecordId): ReceiptSeries {\n let cycle = 1\n while (existsSync(receiptCyclePath(knowledgeRoot, recordId, cycle))) cycle += 1\n const latestCycle = cycle - 1\n return {\n latestReceipt:\n latestCycle === 0\n ? undefined\n : readReceiptAtCycle(knowledgeRoot, recordId, latestCycle),\n nextCycle: cycle,\n }\n}\n\nfunction assertCanonicalPurgeReceiptHistory(knowledgeRoot: string): void {\n const receiptsDir = join(knowledgeRoot, 'memory', 'receipts')\n let files: string[]\n try {\n files = readdirSync(receiptsDir, { withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .sort()\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n\n for (const file of files) {\n const canonicalName = parseCanonicalPurgeReceiptFileName(file)\n if (canonicalName === undefined) continue\n guardPurgeReceiptForFile(\n JSON.parse(readFileSync(join(receiptsDir, file), 'utf8')),\n file,\n canonicalName,\n )\n }\n}\n\nfunction assertNoSymlinkComponents(knowledgeRoot: string, relativePath: string): void {\n let current = knowledgeRoot\n for (const segment of relativePath.split('/')) {\n current = join(current, segment)\n try {\n if (lstatSync(current).isSymbolicLink()) {\n throw new TypeError(`purge authority path crosses a symbolic link: ${relativePath}`)\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n }\n}\n\nfunction assertUnique(values: readonly string[], label: string): void {\n if (new Set(values).size !== values.length) {\n throw new TypeError(`${label} must not contain duplicate identities`)\n }\n}\n\nfunction sorted(values: readonly string[]): string[] {\n return [...values].sort()\n}\n\nfunction assertSameIdentities(\n actual: readonly string[],\n expected: readonly string[],\n label: string,\n): void {\n assertUnique(actual, label)\n assertUnique(expected, label)\n if (canonicalJson(sorted(actual)) !== canonicalJson(sorted(expected))) {\n throw new TypeError(`${label} does not match the executable purge identities`)\n }\n}\n\nfunction bundleAuthority(\n relativePath: string,\n recordId: RecordId,\n): { product: string; bundleDir: string } {\n const segments = relativePath.split('/')\n if (\n segments.length !== 4\n || segments[0] !== 'memory'\n || !PURGE_SAFE_PATH_SEGMENT.test(segments[1]!)\n || segments[1] === '.'\n || segments[1] === '..'\n || segments[2] !== 'bundles'\n || segments[3] !== recordId\n ) {\n throw new TypeError(\n `purge bundle authority must be memory/<product>/bundles/${recordId}`,\n )\n }\n return { product: segments[1]!, bundleDir: relativePath }\n}\n\nfunction queueAuthority(relativePath: string): { candidateId: string } {\n const segments = relativePath.split('/')\n const queued = segments.length === 4\n && segments[0] === 'memory'\n && segments[1] === 'queue'\n && segments[2] === 'queued'\n const claimed = segments.length === 5\n && segments[0] === 'memory'\n && segments[1] === 'queue'\n && segments[2] === 'claimed'\n && PURGE_SAFE_PATH_SEGMENT.test(segments[3]!)\n && segments[3] !== '.'\n && segments[3] !== '..'\n const candidateId = segments.at(-1) ?? ''\n if ((!queued && !claimed) || !QUEUE_CANDIDATE_ID.test(candidateId)) {\n throw new TypeError('purge queue authority must name one canonical queued/claimed candidate')\n }\n return { candidateId }\n}\n\nfunction assertBundleAffectedPaths(\n bundleDir: string,\n paths: readonly string[],\n label: string,\n): void {\n if (paths.length === 0 || paths.some((path) => (\n path !== bundleDir && !path.startsWith(`${bundleDir}/`)\n ))) {\n throw new TypeError(`${label} must stay within its canonical bundle directory`)\n }\n assertUnique(paths, label)\n}\n\n/**\n * Convert schema-valid persisted bytes into deletion authority only after every redundant\n * identity agrees with the requested record and canonical filesystem layout.\n */\nfunction guardPurgeIntentForRequest(\n knowledgeRoot: string,\n requestedRecordId: RecordId,\n value: unknown,\n): PurgeIntent {\n const intent = guardPurgeIntent(value)\n if (\n intent.purgedRecordId !== requestedRecordId\n || intent.receipt.purgedRecordId !== requestedRecordId\n ) {\n throw new TypeError('purge intent record identity does not match the requested record')\n }\n\n assertUnique(intent.bundleDirs, 'purge intent bundleDirs')\n for (const path of intent.bundleDirs) bundleAuthority(path, requestedRecordId)\n const queueTargets = intent.queuePayloadDirs.map((path) => ({\n ...queueAuthority(path),\n candidateDir: path,\n }))\n assertSameIdentities(\n queueTargets.map(({ candidateId }) => candidateId),\n intent.queueCandidateIds,\n 'purge intent queue candidates',\n )\n for (const path of [\n ...intent.bundleDirs,\n ...intent.queuePayloadDirs,\n ...intent.queueCandidateIds.map((candidateId) =>\n `memory/queue/jobs/${candidateId}.state.json`,\n ),\n receiptCycleRelativePath(requestedRecordId, intent.receiptCycle),\n ]) {\n assertNoSymlinkComponents(knowledgeRoot, path)\n }\n for (const path of intent.receipt.affectedPaths) {\n const owner = intent.bundleDirs.find((bundleDir) => (\n path === bundleDir || path.startsWith(`${bundleDir}/`)\n ))\n if (owner === undefined) {\n throw new TypeError('purge receipt affectedPaths escape the persisted bundle authorities')\n }\n }\n\n const affected = intent.affectedSet\n if (affected.recordId !== requestedRecordId || affected.state !== 'resume') {\n throw new TypeError('purge affected set does not identify the resumable requested record')\n }\n if (\n affected.intentPath !== `memory/receipts/purge-${requestedRecordId}.intent.json`\n || affected.receiptPath\n !== receiptCycleRelativePath(requestedRecordId, intent.receiptCycle)\n ) {\n throw new TypeError('purge affected-set audit paths do not match the requested receipt slot')\n }\n assertSameIdentities(\n affected.bundles.map(({ bundleDir }) => bundleDir),\n intent.bundleDirs,\n 'purge affected-set bundles',\n )\n for (const bundle of affected.bundles) {\n const authority = bundleAuthority(bundle.bundleDir, requestedRecordId)\n if (bundle.product !== authority.product) {\n throw new TypeError('purge affected-set product does not match its bundle path')\n }\n assertBundleAffectedPaths(\n bundle.bundleDir,\n bundle.affectedPaths,\n 'purge affected-set bundle paths',\n )\n }\n assertSameIdentities(\n affected.bundles.flatMap(({ affectedPaths }) => affectedPaths),\n intent.receipt.affectedPaths,\n 'purge affected-set bundle contents',\n )\n assertSameIdentities(\n affected.receiptAffectedPaths,\n intent.receipt.affectedPaths,\n 'purge affected-set receipt paths',\n )\n const expectedQueueTargets = queueTargets.map(({ candidateId, candidateDir }) =>\n canonicalJson({\n candidateId,\n candidateDir,\n jobStatePath: `memory/queue/jobs/${candidateId}.state.json`,\n }),\n )\n assertSameIdentities(\n affected.queueTargets.map((target) => canonicalJson(target)),\n expectedQueueTargets,\n 'purge affected-set queue targets',\n )\n assertSameIdentities(\n affected.projectionTargets,\n PURGE_PROJECTION_TARGETS,\n 'purge affected-set projections',\n )\n return intent\n}\n\nfunction readExistingIntent(knowledgeRoot: string, recordId: RecordId): PurgeIntent | undefined {\n const file = intentPath(knowledgeRoot, recordId)\n if (!existsSync(file)) return undefined\n assertNoSymlinkComponents(\n knowledgeRoot,\n `memory/receipts/purge-${recordId}.intent.json`,\n )\n return guardPurgeIntentForRequest(\n knowledgeRoot,\n recordId,\n JSON.parse(readFileSync(file, 'utf8')),\n )\n}\n\nfunction toReceiptPath(knowledgeRoot: string, absolutePath: string): string {\n return relative(knowledgeRoot, absolutePath).split(sep).join('/')\n}\n\nfunction affectedPaths(knowledgeRoot: string, matches: readonly ResolvedBundle[]): string[] {\n const paths = new Set<string>()\n for (const match of matches) {\n const bundleDir = toReceiptPath(knowledgeRoot, match.dir)\n paths.add(bundleDir)\n for (const relPath of Object.keys(match.bundle.manifest.contentHashes)) {\n paths.add(`${bundleDir}/${relPath}`)\n }\n paths.add(`${bundleDir}/manifest.json`)\n }\n return [...paths].sort()\n}\n\nconst PURGE_PROJECTION_TARGETS = ['records', 'anchors', 'fts', 'vec', 'graph'] as const\n\ninterface ResolvedPurgeTargets {\n affectedSet: PurgeAffectedSet\n intent: PurgeIntent | undefined\n matches: ResolvedBundle[]\n queueSweepTargets: QueueSweepTarget[]\n series: ReceiptSeries | undefined\n}\n\nfunction baseAffectedSet(\n knowledgeRoot: string,\n recordId: RecordId,\n state: PurgeAffectedSet['state'],\n receiptCycle: number,\n): PurgeAffectedSet {\n return {\n recordId,\n state,\n bundles: [],\n receiptAffectedPaths: [],\n projectionTargets: [...PURGE_PROJECTION_TARGETS],\n embedCacheAction: 'clear-all',\n queueTargets: [],\n intentPath: toReceiptPath(knowledgeRoot, intentPath(knowledgeRoot, recordId)),\n receiptPath: receiptCycleRelativePath(recordId, receiptCycle),\n }\n}\n\n/**\n * The sole selector for purge preview and execution. New resolutions inspect every loadable\n * bundle and matching queue payload; resumptions use only the durable plan embedded in the\n * standing intent, even when some selected paths have already disappeared.\n */\nfunction resolvePurgeTargets(\n knowledgeRoot: string,\n recordId: RecordId,\n): ResolvedPurgeTargets {\n assertCanonicalPurgeReceiptHistory(knowledgeRoot)\n const persistedIntent = readExistingIntent(knowledgeRoot, recordId)\n if (persistedIntent !== undefined) {\n return {\n affectedSet: persistedIntent.affectedSet,\n intent: persistedIntent,\n matches: [],\n queueSweepTargets: [],\n series: undefined,\n }\n }\n\n const matches = resolveBundles(knowledgeRoot, recordId)\n const series = resolveReceiptSeries(knowledgeRoot, recordId)\n if (matches.length === 0) {\n const state = series.latestReceipt === undefined ? 'not-found' : 'already-purged'\n const receiptCycle = series.latestReceipt === undefined\n ? series.nextCycle\n : series.nextCycle - 1\n return {\n affectedSet: baseAffectedSet(knowledgeRoot, recordId, state, receiptCycle),\n intent: undefined,\n matches,\n queueSweepTargets: [],\n series,\n }\n }\n\n const queueSweepTargets = resolveQueueSweepTargets(knowledgeRoot, matches)\n const affectedSet: PurgeAffectedSet = {\n ...baseAffectedSet(knowledgeRoot, recordId, 'live', series.nextCycle),\n bundles: matches\n .map((match) => ({\n product: match.product,\n bundleDir: toReceiptPath(knowledgeRoot, match.dir),\n kind: match.bundle.frontmatter.kind,\n affectedPaths: affectedPaths(knowledgeRoot, [match]),\n }))\n .sort((left, right) => left.bundleDir.localeCompare(right.bundleDir)),\n receiptAffectedPaths: affectedPaths(knowledgeRoot, matches),\n queueTargets: queueSweepTargets\n .map((target) => ({\n candidateId: target.candidateId,\n candidateDir: toReceiptPath(knowledgeRoot, target.candidateDir),\n jobStatePath: toReceiptPath(\n knowledgeRoot,\n jobStatePath(knowledgeRoot, target.candidateId),\n ),\n }))\n .sort((left, right) => left.candidateDir.localeCompare(right.candidateDir)),\n }\n return {\n affectedSet: PurgeAffectedSetSchema.parse(affectedSet) as PurgeAffectedSet,\n intent: undefined,\n matches,\n queueSweepTargets,\n series,\n }\n}\n\nexport function resolvePurgeAffectedSet(input: {\n knowledgeRoot: string\n recordId: RecordId\n}): PurgeAffectedSet {\n if (!isAbsolute(input.knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n if (!SAFE_RECORD_ID.test(input.recordId)) {\n throw new TypeError('recordId must be a safe path segment')\n }\n const resolved = resolvePurgeTargets(input.knowledgeRoot, input.recordId)\n return resolved.affectedSet\n}\n\nexport function purgeAffectedSetFingerprint(affectedSet: PurgeAffectedSet): string {\n return createHash('sha256').update(canonicalJson(affectedSet)).digest('hex')\n}\n\nfunction assertExpectedAffectedSet(\n expectedFingerprint: string | undefined,\n affectedSet: PurgeAffectedSet,\n): void {\n if (expectedFingerprint === undefined) return\n const actualFingerprint = purgeAffectedSetFingerprint(affectedSet)\n if (actualFingerprint !== expectedFingerprint) {\n throw new PurgeTargetChangedError(expectedFingerprint, actualFingerprint)\n }\n}\n\nfunction firstCommittedOrdinal(matches: readonly ResolvedBundle[]): number {\n return Math.min(...matches.map(({ bundle }) =>\n bundle.provenance.mode === 'run-linked'\n ? (bundle.provenance.sourceBuildOrdinal ?? bundle.manifest.createdAtOrdinal)\n : bundle.manifest.createdAtOrdinal,\n ))\n}\n\nfunction freshPurgeOrdinal(input: PurgeRecordInput): number {\n if (input.purgedAtOrdinal === undefined) throw new PurgeChronologyRequiredError()\n return input.purgedAtOrdinal\n}\n\nfunction buildReceipt(\n input: PurgeRecordInput,\n matches: readonly ResolvedBundle[],\n occurrenceOrdinal: number,\n): PurgeReceipt {\n return PurgeReceiptSchema.parse({\n schemaVersion: PURGE_RECEIPT_SCHEMA_VERSION,\n purgedRecordId: input.recordId,\n purgedAtOrdinal: occurrenceOrdinal,\n initiator: input.initiator,\n affectedPaths: affectedPaths(input.knowledgeRoot, matches),\n firstCommittedOrdinal: firstCommittedOrdinal(matches),\n })\n}\n\n/**\n * Publish one complete durable artifact without exposing partial bytes and without ever\n * overwriting an existing audit fact. The hard link is the exclusive atomic visibility step; the\n * temp file is fsynced first and resides in the same directory. Intent and receipt publication\n * share this one pattern.\n */\nfunction writeDurableExclusive(\n finalPath: string,\n text: string,\n beforeMutation?: () => void,\n): 'written' | 'already-exists' {\n const directory = dirname(finalPath)\n beforeMutation?.()\n mkdirSync(directory, { recursive: true })\n const temporary = `${finalPath}.tmp-${randomUUID()}`\n try {\n beforeMutation?.()\n writeFileSync(temporary, text, { encoding: 'utf8', flag: 'wx' })\n fsyncFile(temporary)\n fsyncDirectory(directory)\n try {\n beforeMutation?.()\n linkSync(temporary, finalPath)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') return 'already-exists'\n throw error\n }\n fsyncDirectory(directory)\n return 'written'\n } finally {\n rmSync(temporary, { force: true })\n fsyncDirectory(directory)\n }\n}\n\n/** Persist the complete destruction authority as one deterministically sorted intent payload. */\nfunction buildIntent(\n input: PurgeRecordInput,\n receipt: PurgeReceipt,\n receiptCycle: number,\n matches: readonly ResolvedBundle[],\n targets: readonly QueueSweepTarget[],\n affectedSet: PurgeAffectedSet,\n): PurgeIntent {\n return PurgeIntentSchema.parse({\n schemaVersion: PURGE_INTENT_SCHEMA_VERSION,\n purgedRecordId: input.recordId,\n receipt,\n receiptCycle,\n bundleDirs: matches\n .map((match) => toReceiptPath(input.knowledgeRoot, match.dir))\n .sort(),\n queueCandidateIds: targets.map((target) => target.candidateId).sort(),\n queuePayloadDirs: targets\n .map((target) => toReceiptPath(input.knowledgeRoot, target.candidateDir))\n .sort(),\n affectedSet: {\n ...affectedSet,\n state: 'resume',\n },\n })\n}\n\n/** Remove the fulfilled intent; the durable receipt is now the sole audit fact. */\nfunction retireIntent(input: PurgeRecordInput): void {\n const file = intentPath(input.knowledgeRoot, input.recordId)\n if (!existsSync(file)) return\n fenceWriterAuthority(input)\n rmSync(file, { force: true })\n fsyncDirectory(dirname(file))\n}\n\n/** Publish the completion receipt exclusively at its cycle path, then retire the intent. */\nfunction publishReceiptAndRetire(\n input: PurgeRecordInput,\n receiptText: string,\n receipt: PurgeReceipt,\n receiptCycle: number,\n): PurgeRecordOutcome {\n input.hooks?.beforeReceiptPublish?.()\n // 261003-mqc: `memory/receipts/` linked out of the knowledge root is refused before writing.\n assertWithinKnowledgeRoot(input.knowledgeRoot,\n dirname(receiptCyclePath(input.knowledgeRoot, input.recordId, receiptCycle)))\n const writeOutcome = writeDurableExclusive(\n receiptCyclePath(input.knowledgeRoot, input.recordId, receiptCycle),\n receiptText,\n () => fenceWriterAuthority(input),\n )\n if (writeOutcome === 'already-exists') {\n const racedReceipt = readReceiptAtCycle(input.knowledgeRoot, input.recordId, receiptCycle)\n if (racedReceipt === undefined) {\n throw new Error('purge receipt disappeared during exclusive publication')\n }\n retireIntent(input)\n return { kind: 'already-purged', receipt: racedReceipt }\n }\n retireIntent(input)\n return { kind: 'purged', receipt }\n}\n\n/**\n * A crash at or after the intent may leave any prefix of the bundle removals applied. Any\n * surviving intent bundle still carries the record kind for the projection purge; when none\n * survives, bundle removal started, which proves the preceding projection purge committed.\n */\nfunction survivingBundleKind(\n knowledgeRoot: string,\n intent: PurgeIntent,\n): LoadedBundle['frontmatter']['kind'] | undefined {\n for (const dir of intent.bundleDirs) {\n const loaded = loadBundle(join(knowledgeRoot, dir))\n if (loaded.kind === 'loaded') return loaded.bundle.frontmatter.kind\n }\n return undefined\n}\n\n/**\n * Replay the irreversible phase from the intent's persisted identities only — never a second\n * resolution over destroyed state. Every deletion is idempotent and the receipt publishes\n * byte-identically from the embedded payload at the intent's OWN receiptCycle (never recomputed).\n *\n * A fulfilled intent (its receipt already published; a crash lost only the retirement) resolves\n * here too: the exclusive publish returns already-exists at the exact cycle path, yielding\n * already-purged plus intent retirement. A revival racing into that tiny publish-to-retirement\n * window may be swept by this resume — that sweep is still truthfully receipted, because the\n * content address means the revived bundle occupies the identical paths the intent persisted.\n */\nfunction resumeFromIntent(input: PurgeRecordInput, intent: PurgeIntent): PurgeRecordOutcome {\n fenceWriterAuthority(input)\n purgeIndexSurfaces(\n input.knowledgeRoot,\n input.recordId,\n survivingBundleKind(input.knowledgeRoot, intent),\n )\n input.hooks?.afterProjectionPurge?.()\n for (const dir of intent.bundleDirs) {\n assertWithinKnowledgeRoot(input.knowledgeRoot, join(input.knowledgeRoot, dir))\n fenceWriterAuthority(input)\n rmSync(join(input.knowledgeRoot, dir), { recursive: true, force: true })\n input.hooks?.afterBundleRemoval?.()\n }\n const root = queueRoot(input.knowledgeRoot)\n for (const dir of intent.queuePayloadDirs) {\n const candidateDir = join(input.knowledgeRoot, dir)\n assertWithinKnowledgeRoot(input.knowledgeRoot, candidateDir)\n fenceWriterAuthority(input)\n rmSync(candidateDir, { recursive: true, force: true })\n removeEmptyQueueParents(candidateDir, root, () => fenceWriterAuthority(input))\n }\n for (const candidateId of intent.queueCandidateIds) {\n fenceWriterAuthority(input)\n rmSync(jobStatePath(input.knowledgeRoot, candidateId), { force: true })\n }\n input.hooks?.afterQueueSweep?.()\n verifyPurgeCompletion(input, intent)\n return publishReceiptAndRetire(\n input,\n committedFileText(intent.receipt),\n intent.receipt,\n intent.receiptCycle,\n )\n}\n\n/**\n * Hard-remove one confirmed-sensitive record from every recoverable local-store surface.\n *\n * Recovery invariant (CR-04): nothing irreversible ever precedes a durable intent, so a retry\n * either re-resolves intact state (crash before the intent) or replays the intent's persisted\n * identities to the identical completion receipt (crash at any later boundary).\n *\n * Revival ratification (SC-4/DCAY-05, option a): bundle ids are deterministic content addresses,\n * so purged-then-re-learned content re-mints the SAME record id. Receipt-exists-but-live-surfaces\n * therefore runs a FRESH destruction cycle publishing the next append-only versioned receipt in\n * the series; original audit receipts are never rewritten, and already-purged is attested only\n * over verified-dead surfaces (live resolution always precedes any receipt-based attestation).\n */\nexport function purgeRecord(input: PurgeRecordInput): PurgeRecordOutcome {\n assertInput(input)\n\n // Preview and execution share this one resolution. The caller's preview fingerprint is\n // checked before durable intent creation or destructive mutation.\n const resolved = resolvePurgeTargets(input.knowledgeRoot, input.recordId)\n assertExpectedAffectedSet(input.expectedAffectedSetFingerprint, resolved.affectedSet)\n\n // An existing intent is the standing durable destruction authority — resume it before any\n // fresh work (this also retires fulfilled intents left by a crash after publication).\n if (resolved.intent !== undefined) return resumeFromIntent(input, resolved.intent)\n\n // Resolve live surfaces BEFORE consulting the receipt series, so every attestation below\n // reflects actually-resolved state, never a stale audit fact.\n const matches = resolved.matches\n const series = resolved.series!\n if (matches.length === 0) {\n // Verified-dead surfaces: attest already-purged carrying the LATEST series receipt, or\n // not-found when no destruction was ever receipted. Nothing mutates on this path.\n return series.latestReceipt === undefined\n ? { kind: 'not-found' }\n : { kind: 'already-purged', receipt: series.latestReceipt }\n }\n\n // Live surfaces run a fresh destruction cycle REGARDLESS of existing receipts (option a).\n const receiptCycle = series.nextCycle\n const occurrenceOrdinal = freshPurgeOrdinal(input)\n const receipt = buildReceipt(input, matches, occurrenceOrdinal)\n const receiptText = committedFileText(receipt)\n const kind = matches[0]!.bundle.frontmatter.kind\n\n // The exact queue deletion set came from the same canonical resolution shown to the caller.\n const queueSweepTargets = resolved.queueSweepTargets\n\n // The intent publication is the LAST act before the first irreversible mutation (CR-04).\n const intent = buildIntent(\n input,\n receipt,\n receiptCycle,\n matches,\n queueSweepTargets,\n resolved.affectedSet,\n )\n assertWithinKnowledgeRoot(input.knowledgeRoot, dirname(intentPath(input.knowledgeRoot, input.recordId)))\n const intentOutcome = writeDurableExclusive(\n intentPath(input.knowledgeRoot, input.recordId),\n committedFileText(intent),\n () => fenceWriterAuthority(input),\n )\n if (intentOutcome === 'already-exists') {\n // A concurrent purge published its intent first; that durable authority wins.\n const publishedIntent = readExistingIntent(input.knowledgeRoot, input.recordId)\n if (publishedIntent === undefined) {\n throw new Error('purge intent disappeared during exclusive publication')\n }\n assertExpectedAffectedSet(\n input.expectedAffectedSetFingerprint,\n publishedIntent.affectedSet,\n )\n return resumeFromIntent(input, publishedIntent)\n }\n input.hooks?.afterIntentWritten?.()\n\n // Projection cleanup must prove every materialized vec table was writable before any\n // irreversible bundle, queue, or receipt mutation can attest success.\n fenceWriterAuthority(input)\n purgeIndexSurfaces(input.knowledgeRoot, input.recordId, kind)\n input.hooks?.afterProjectionPurge?.()\n\n // Capture metadata above before the only true-delete operation removes the committed tree.\n for (const match of matches) {\n assertWithinKnowledgeRoot(input.knowledgeRoot, match.dir)\n fenceWriterAuthority(input)\n rmSync(match.dir, { recursive: true, force: true })\n input.hooks?.afterBundleRemoval?.()\n }\n\n sweepQueuePayloads(input, queueSweepTargets)\n input.hooks?.afterQueueSweep?.()\n\n verifyPurgeCompletion(input, intent)\n return publishReceiptAndRetire(input, receiptText, receipt, receiptCycle)\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n INSPECT_RECORD_VIEW_SCHEMA_VERSION,\n InspectFilterSchema,\n InspectRecordViewSchema,\n canonicalJson,\n normalizeAnchor,\n survivingOutcomeEvents,\n} from '@vostride/agent-qa-schema'\nimport type {\n Anchor,\n DerivedTrustState,\n InspectFilter,\n InspectRecordView,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\nimport { isServable } from './bundle-scan.js'\nimport type { EnumeratedBundleDir } from './bundle-scan.js'\nimport {\n enumerateMaintenanceBundleDirs,\n loadMaintenanceBundle,\n} from './maintenance-scan.js'\n\nexport interface InspectRecordsOptions {\n knowledgeRoot: string\n filter: InspectFilter\n}\n\n// Maintenance exposes lifecycle and evidence counts, never the numerical trust scalar.\ntype InspectionTrustState = Pick<DerivedTrustState, 'status' | 'counters' | 'validity'>\n\nconst TRUST_NARRATIVE_REL_PATH = 'evidence/evidence.md'\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n}\n\nfunction parsedAnchor(value: string): Anchor | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return undefined\n }\n const record = objectRecord(parsed)\n if (record === undefined || typeof record.t !== 'string') return undefined\n\n switch (record.t) {\n case 'page':\n return typeof record.route === 'string' ? { t: 'page', route: record.route } : undefined\n case 'flow':\n return typeof record.name === 'string' ? { t: 'flow', name: record.name } : undefined\n case 'el':\n return typeof record.role === 'string' && typeof record.name === 'string'\n ? {\n t: 'el',\n role: record.role,\n name: record.name,\n ...(typeof record.ordinal === 'number' ? { ordinal: record.ordinal } : {}),\n }\n : undefined\n case 'platform':\n return typeof record.platform === 'string'\n ? parsed as Anchor\n : undefined\n case 'selector':\n return typeof record.literal === 'string'\n ? { t: 'selector', literal: record.literal }\n : undefined\n case 'error':\n return typeof record.message === 'string'\n ? { t: 'error', message: record.message }\n : undefined\n default:\n return undefined\n }\n}\n\nfunction scalarAnchorMatches(anchor: Anchor, filter: string): boolean {\n switch (anchor.t) {\n case 'page':\n return canonicalJson(normalizeAnchor({ t: 'page', route: filter }))\n === canonicalJson(anchor)\n case 'flow':\n return canonicalJson(normalizeAnchor({ t: 'flow', name: filter }))\n === canonicalJson(anchor)\n case 'el': {\n const normalizedName = normalizeAnchor({\n t: 'el',\n role: anchor.role,\n name: filter,\n })\n return normalizedName.t === 'el' && normalizedName.name === anchor.name\n }\n case 'platform':\n return filter.trim().toLowerCase() === anchor.platform\n case 'selector':\n return canonicalJson(normalizeAnchor({ t: 'selector', literal: filter }))\n === canonicalJson(anchor)\n case 'error':\n return canonicalJson(normalizeAnchor({ t: 'error', message: filter }))\n === canonicalJson(anchor)\n }\n}\n\nfunction anchorMatches(bundle: LoadedBundle, filter: string | undefined): boolean {\n if (filter === undefined) return true\n const normalizedAnchors = bundle.frontmatter.anchors.map(({ raw }) => normalizeAnchor(raw))\n const structured = parsedAnchor(filter)\n if (structured !== undefined) {\n const canonicalFilter = canonicalJson(normalizeAnchor(structured))\n return normalizedAnchors.some((anchor) => canonicalJson(anchor) === canonicalFilter)\n }\n return normalizedAnchors.some((anchor) => scalarAnchorMatches(anchor, filter))\n}\n\nfunction readTrustNarrative(dir: string, bundle: LoadedBundle): string | undefined {\n if (!(TRUST_NARRATIVE_REL_PATH in bundle.manifest.contentHashes)) return undefined\n const file = join(dir, TRUST_NARRATIVE_REL_PATH)\n return existsSync(file) ? readFileSync(file, 'utf8') : undefined\n}\n\n/**\n * Project ONE loaded bundle and its already-derived trust into the maintenance view.\n *\n * Extracted from the fold below so `showRecord` renders the SAME view rather than a second\n * one built to the same description. The two would have agreed on the day they were written;\n * the first field to disagree afterwards would have been one nobody compares, and a reviewer\n * reading a record's detail page beside a record's row would have had no way to tell which of\n * the two was lying. `bundle.events` is taken as given, so an as-of caller passes the bundle\n * with its visible events already narrowed and this function has no opinion about time.\n */\nexport function toInspectRecordView(\n entry: EnumeratedBundleDir,\n bundle: LoadedBundle,\n trust: InspectionTrustState,\n): InspectRecordView {\n const survivingEvents = survivingOutcomeEvents(bundle.events)\n const evidenceTokens = [...new Set(\n survivingEvents.map((event) => String(event.evidenceToken)),\n )].sort(compareText)\n const lastEventOrdinal = survivingEvents.reduce(\n (latest, event) => Math.max(latest, event.buildOrdinal),\n bundle.manifest.createdAtOrdinal,\n )\n const trustNarrative = readTrustNarrative(entry.dir, bundle)\n\n return InspectRecordViewSchema.parse({\n schemaVersion: INSPECT_RECORD_VIEW_SCHEMA_VERSION,\n recordId: bundle.manifest.id,\n product: entry.product,\n scope: bundle.frontmatter.scope.key,\n kind: bundle.frontmatter.kind,\n status: trust.status,\n confirmations: trust.counters.confirmed,\n contradictions: trust.counters.contradicted,\n evidenceTokens,\n lastEventOrdinal,\n openedAtOrdinal: trust.validity.openedAtOrdinal,\n ...(trust.validity.closedAtOrdinal === undefined\n ? {}\n : { closedAtOrdinal: trust.validity.closedAtOrdinal }),\n anchors: bundle.frontmatter.anchors\n .map(({ raw }) => canonicalJson(normalizeAnchor(raw)))\n .sort(compareText),\n ...(trustNarrative === undefined ? {} : { trustNarrative }),\n })\n}\n\n/**\n * Fold canonical committed bundles into maintenance views. Explicit non-live status filters and\n * as-of queries enable audit visibility; an unqualified query retains the serving firewall.\n */\nexport function inspectRecords(options: InspectRecordsOptions): InspectRecordView[] {\n const filter = InspectFilterSchema.parse(options.filter)\n const records: InspectRecordView[] = []\n const auditVisibility = filter.asOfBuild !== undefined\n || filter.status === 'superseded'\n || filter.status === 'deprecated'\n\n for (const entry of enumerateMaintenanceBundleDirs(options.knowledgeRoot)) {\n if (filter.product !== undefined && filter.product !== entry.product) continue\n const bundle = loadMaintenanceBundle(entry)\n const asOfBuild = filter.asOfBuild\n if (\n asOfBuild !== undefined\n && bundle.manifest.createdAtOrdinal > asOfBuild\n ) continue\n const visibleEvents = asOfBuild === undefined\n ? bundle.events\n : bundle.events.filter((event) => event.buildOrdinal <= asOfBuild)\n const visibleBundle = visibleEvents === bundle.events\n ? bundle\n : { ...bundle, events: visibleEvents }\n const trust: InspectionTrustState = deriveBundleTrust(visibleBundle)\n if (!auditVisibility && !isServable(trust)) continue\n if (filter.scope !== undefined && filter.scope !== bundle.frontmatter.scope.key) continue\n if (filter.kind !== undefined && filter.kind !== bundle.frontmatter.kind) continue\n if (filter.status !== undefined && filter.status !== trust.status) continue\n if (filter.recordId !== undefined && filter.recordId !== bundle.manifest.id) continue\n if (!anchorMatches(bundle, filter.anchor)) continue\n if (filter.unresolvedOnly === true && (\n bundle.frontmatter.kind !== 'unknown' || !isServable(trust)\n )) continue\n\n records.push(toInspectRecordView(entry, visibleBundle, trust))\n }\n\n return records.sort((left, right) => (\n compareText(left.recordId, right.recordId)\n || compareText(left.product, right.product)\n ))\n}\n","import {\n KnowledgeRecordShowResultSchema,\n type KnowledgeRecordShowResult,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust } from './bundle-read.js'\nimport { toInspectRecordView } from './inspect.js'\nimport { enumerateMaintenanceBundleDirs, loadMaintenanceBundle } from './maintenance-scan.js'\n\nexport interface ShowRecordsOptions {\n knowledgeRoot: string\n recordIds: readonly string[]\n}\n\n/**\n * Resolve exact identities in first-request order with one maintenance enumeration.\n * Missing records are data; incomplete scans retain KnowledgeMaintenanceScanError so\n * callers can report scanIncomplete instead of presenting a partial set as clean misses.\n * Like the single-record read, this bypasses serving filters and never opens an index.\n */\nexport function showRecords(options: ShowRecordsOptions): readonly KnowledgeRecordShowResult[] {\n const recordIds = [...new Set(options.recordIds)]\n if (recordIds.length === 0) return []\n const pending = new Set(recordIds)\n const found = new Map<string, KnowledgeRecordShowResult>()\n\n for (const entry of enumerateMaintenanceBundleDirs(options.knowledgeRoot)) {\n const bundle = loadMaintenanceBundle(entry)\n if (!pending.has(bundle.manifest.id)) continue\n found.set(bundle.manifest.id, KnowledgeRecordShowResultSchema.parse({\n kind: 'found',\n schemaVersion: 2,\n record: toInspectRecordView(entry, bundle, deriveBundleTrust(bundle)),\n provenance: bundle.provenance,\n summary: bundle.summary,\n body: bundle.body,\n }))\n pending.delete(bundle.manifest.id)\n // Preserve the single-record read's first matching bundle and error boundary.\n if (pending.size === 0) break\n }\n\n return recordIds.map(recordId => found.get(recordId) ?? KnowledgeRecordShowResultSchema.parse({\n kind: 'not-found',\n schemaVersion: 2,\n recordId,\n }))\n}\n","// `showRecord` — one committed record with the provenance that justifies it (Phase 387, KREV-01).\n//\n// WIRING, in the sense KREV-01's claim requires: every value here is read off the bundle the\n// maintenance scanner already loads, and the view is the SAME projection `inspectRecords`\n// renders (`toInspectRecordView`), not a second one written to the same description. No index\n// is opened, no query is run, and nothing about trust is recomputed — `deriveBundleTrust` is\n// the one fold and this module calls it exactly as its sibling does.\n//\n// Two decisions are worth stating because they are not the obvious ones.\n//\n// ABSENCE IS A RESULT. A record id that names no committed bundle is an ordinary reviewer\n// question — an id pasted out of a stale issue, a record forgotten between two reads — and it\n// has to be distinguishable from a store that could not be read at all. So the miss is a typed\n// arm and the unreadable store still throws.\n//\n// THE SERVING FIREWALL DOES NOT APPLY. `inspectRecords` withholds non-servable records from an\n// UNQUALIFIED query, which is right for a listing. Addressing one record by its exact id is not\n// an unqualified query: it is the explicit gesture that function's own contract admits, and\n// D-04's law is that a permanent address always resolves to something whose status says what\n// happened to it. Hiding a superseded record from someone who named it would answer \"there is\n// no such record\" about a record that plainly exists.\n\nimport type { KnowledgeRecordShowResult } from '@vostride/agent-qa-schema'\nimport { showRecords } from './show-records.js'\n\nexport interface ShowRecordOptions {\n knowledgeRoot: string\n recordId: string\n}\n\n/**\n * Show one record, or report by name that nothing is committed under that id.\n *\n * A knowledge root with no bundles — or no `memory/` directory at all — is an ordinary\n * `not-found`, because the enumerator already treats a missing tree as empty. That is the\n * FUNC-04 empty edge: an empty store answers, it does not throw.\n */\nexport function showRecord(options: ShowRecordOptions): KnowledgeRecordShowResult {\n return showRecords({ knowledgeRoot: options.knowledgeRoot, recordIds: [options.recordId] })[0]!\n}\n","// Resolve a review target and compute the deltas a change writes (Phase 387, KREV-01 / D-17 · D-19).\n//\n// Every function in this module is a READ of the knowledge store. Nothing here imports the curator,\n// `commit`, `publishBundle`, `appendOutcomeEvent`, the index, or the writer lease — there is no\n// handle in this file through which a byte of the knowledge store could change. `apply-review.ts`\n// holds the one write path and calls in here for the target and the deltas.\n//\n// 2026-10-01 (432-17, D-05/D-22): the propose half that minted proposal files into\n// `<agentQaRoot>/proposals/` is deleted with the inbox. A change applies in the call through\n// `applyExplicitReview`; old proposal files are never read again. The module keeps its name so its\n// history stays addressable.\n\nimport { asRecordId, canonicalJson, KnowledgeMarkInputSchema } from '@vostride/agent-qa-schema'\nimport type {\n BundleProvenance,\n Delta,\n KnowledgeAcceptInput,\n KnowledgeForgetInput,\n KnowledgeMarkInput,\n KnowledgeProjection,\n KnowledgeRejectInput,\n KnowledgeTargetRef,\n ScopeKey,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle } from '../bundle-read.js'\nimport { enumerateBundleDirs } from '../bundle-scan.js'\n\n/**\n * The §7.7 projections a forget in THIS store actually scrubs, enumerated honestly.\n *\n * `KNOWLEDGE_PROJECTIONS` declares four — `fts`, `vec`, `graph`, `exemplar` — and a receipt\n * claiming all four would be a receipt nobody can trust. `scrubDeadRecallRows` (index-rebuild.ts)\n * deletes the FTS row, deletes the record from every materialised vec table, and deletes the\n * record's graph edges plus the nodes those edges orphaned. It does NOT touch the exemplar\n * ranking, and it should not: an exemplar in this system is a TEST reference drawn from the\n * run-outcome projection (`serving/get-authoring-brief.ts`), not a knowledge record, so a\n * forgotten record has no exemplar row to scrub. Listing `exemplar` anyway would be the receipt\n * asserting work nobody did — which is worse than a receipt that says less, because a shorter\n * true list can be lengthened and a false one cannot be believed.\n *\n * When the exemplar ranking gains knowledge-record rows, this constant is the one place that\n * fact is recorded, and the receipt widens with it.\n */\nexport const FORGET_SCRUBBED_PROJECTIONS: readonly KnowledgeProjection[] = ['fts', 'vec', 'graph']\n\n/** Resolves a `MEM-` short-ID to the machine id it addresses, or `undefined` (D-01/D-04). */\nexport type ResolveBundleShortId = (shortId: string) => string | undefined\n\n/** A validated mark, accept, reject or forget, in the shape the review verbs take. */\nexport interface ReviewChangeRequest {\n readonly verb: 'accept' | 'reject' | 'forget' | 'mark'\n readonly input: KnowledgeAcceptInput | KnowledgeRejectInput | KnowledgeForgetInput | KnowledgeMarkInput\n}\n\nexport class MarkPlanIntegrityError extends Error {\n constructor(readonly recordId: string) {\n super('mark plan does not match its user-authored target and stamp')\n this.name = 'MarkPlanIntegrityError'\n }\n}\n\nexport interface ResolvedReviewTarget {\n readonly recordId: string\n readonly product: string\n readonly scope: ScopeKey\n readonly provenance: BundleProvenance\n readonly status: string\n readonly summary: string\n}\n\n/**\n * Find the canonical record a target ref names.\n *\n * The two grains differ by ADDRESSING, not by cardinality: a `MEM-` short-ID goes through the\n * addressing ledger to a machine id, and a record id is that machine id already. In this store a\n * bundle directory's name IS its one canonical record id (`records` is keyed one row per\n * `bundle_id`), so \"forgetting a bundle lists every member record\" is total by construction here\n * rather than by an enumeration that could miss one — and the moment a bundle carries more than\n * one record, this function is where that enumeration lands.\n */\nexport function resolveReviewTarget(\n knowledgeRoot: string,\n target: KnowledgeTargetRef,\n resolveBundleShortId?: ResolveBundleShortId,\n): ResolvedReviewTarget | undefined {\n const machineId = target.grain === 'record'\n ? target.recordId\n : resolveBundleShortId?.(target.shortId)\n if (machineId === undefined) return undefined\n\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const outcome = loadBundle(entry.dir)\n if (outcome.kind !== 'loaded') continue\n // EXACT equality: this is addressing, never search.\n if (outcome.bundle.manifest.id !== machineId) continue\n return {\n recordId: outcome.bundle.manifest.id,\n product: entry.product,\n scope: outcome.bundle.frontmatter.scope,\n provenance: outcome.bundle.provenance,\n status: deriveBundleTrust(outcome.bundle).status,\n summary: outcome.bundle.summary,\n }\n }\n return undefined\n}\n\n/**\n * The deltas a change commits.\n *\n * `origin: 'user'` on all three, and it is the load-bearing field rather than boilerplate: a\n * review verb exists because a PERSON decided something about a record, and `agent` origin is\n * downgraded by disposition's autonomy floor precisely so an agent cannot make this call for\n * itself. Attributing a human's accept to the agent would launder the decision.\n *\n * `authorship` is deliberately UNSET, and the reason is a real gap rather than a preference.\n * `CurationAuthorshipPath` is `llm | llm-repaired | deterministic-fallback` — there is no member\n * meaning \"a person decided this\". `deterministic-fallback` is the closest in spirit, but it names\n * the code-built fallback, which never authors a `Deprecate`, so claiming it would misstate who\n * decided. So the deltas carry no authorship and the bridge's own default applies, and\n * the human attribution lives where it is actually true: `origin: 'user'` on the committed delta. Widening the authorship vocabulary is a\n * curator-contract change with a trust-fold blast radius; 391, which owns the review engine and\n * the standing-grant model, is where a `human` path belongs. Recorded in `.planning/WINDOWS.md`.\n *\n * Forget is a `Deprecate` and not a new delta kind. §7.7's law is tombstone-never-destroy plus\n * scrub-every-projection, and that is exactly what a deprecation already does in this store: the\n * outcome event is appended (history is never rewritten), the derived status becomes `deprecated`,\n * and the projection unit's `scrubDeadRecallRows` removes the lexical, dense and graph recall rows\n * on the next projection. A new kind would have been a SECOND write vocabulary reaching the same\n * machinery — and the destructive verb, `purgeRecord`, is D-14's true-delete exemption which\n * forget is explicitly not (D-19).\n *\n * `changeId` is the stable identity of the change, derived from the caller's operation identity\n * (432-06). Accept's evidence\n * token and forget's reason are derived from it, so a retried change is the same change.\n */\nexport function reviewDeltasFor(\n request: ReviewChangeRequest,\n resolved: ResolvedReviewTarget,\n changeId: string,\n): Delta[] {\n const envelope = {\n origin: 'user' as const,\n scope: resolved.scope,\n citedIds: [asRecordId(resolved.recordId)],\n }\n switch (request.verb) {\n case 'mark': {\n const parsed = KnowledgeMarkInputSchema.safeParse(request.input)\n if (!parsed.success) throw new MarkPlanIntegrityError(resolved.recordId)\n const { plan, mark } = parsed.data\n if (plan.markId !== mark.markId || plan.fix !== mark.fix\n || plan.feedbackSource.runId !== mark.runId || plan.runTraceRef.runId !== mark.runId\n || plan.feedbackSource.testIndex !== mark.testIndex\n || plan.feedbackSource.stepIndex !== mark.stepIndex || plan.feedbackSource.kind !== mark.kind\n || canonicalJson(plan.target) !== canonicalJson(parsed.data.target)\n || plan.deltas.some((delta) => delta.origin !== 'user'\n || canonicalJson(delta.scope) !== canonicalJson(resolved.scope)\n || !delta.citedIds.includes(asRecordId(resolved.recordId)))) {\n throw new MarkPlanIntegrityError(resolved.recordId)\n }\n return plan.deltas\n }\n case 'accept':\n return [{\n ...envelope,\n kind: 'Confirm',\n targetId: asRecordId(resolved.recordId),\n // The evidence for a human accept IS the change identity: deriving the token from it\n // makes the confirmation replay-safe (a second apply of the same change is the same\n // token, which the append dedups).\n evidenceToken: `review-accept:${changeId}`,\n } as Delta]\n case 'reject':\n return [{\n ...envelope,\n kind: 'Deprecate',\n targetId: asRecordId(resolved.recordId),\n reason: (request.input as KnowledgeRejectInput).reason,\n } as Delta]\n case 'forget':\n return [{\n ...envelope,\n kind: 'Deprecate',\n targetId: asRecordId(resolved.recordId),\n reason: `forget:${changeId}`,\n } as Delta]\n }\n}\n","// Apply: the ONE path a knowledge change's bytes take (Phase 387, KREV-01 / D-17 · D-18; 432-06).\n//\n// An explicit mark, accept, reject or forget applies in the call (432 D-04/D-05). The caller's stable\n// operation identity is the change identity, so a retry is the same change: its evidence tokens,\n// receipts and record ids repeat and nothing lands twice. Every change routes its deltas through the\n// Curator's `commit()` — the same epoch-fenced path every curation write takes — and the receipt is\n// assembled around the commit from the disposition outcome plus post-commit reads.\n//\n// LEASE ROUTING (D-18) is decided by `acquireWriterLease` itself rather than by a classification\n// this module performs first. That is deliberate: a read-then-decide would have a window between\n// the read and the acquire, and the primitive already refuses a fresh holder. So \"the lease is\n// held by somebody alive\" arrives here as an ordinary `held` outcome, and the caller delegates the\n// same validated request and identity to the holder, bounded. There is no code path in this file\n// that acquires when a live holder exists, because there is no second acquisition primitive.\n//\n// An explicit change is authority in every execution context, so it writes through the store's\n// narrow explicit entry, which skips only the automatic propose-only downgrade and keeps the actual\n// ExecutionContext on every durable record. Delta validation and every promotion gate still apply.\n//\n// 2026-10-01 (432-17, D-05/D-22): the proposal door is deleted with the inbox — the claim by atomic\n// rename, the applied/rejected publication, the in-flight wait and the restore-to-pending on failure.\n// Old proposal files are never read again.\n\nimport { existsSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport {\n COMMIT_RECEIPT_SCHEMA_VERSION,\n FORGET_RECEIPT_SCHEMA_VERSION,\n GATE_RECEIPT_SCHEMA_VERSION,\n KnowledgeAcceptInputSchema,\n KnowledgeForgetInputSchema,\n KnowledgeMarkInputSchema,\n KnowledgeChangeIdSchema,\n KnowledgeRejectInputSchema,\n asEvidenceToken,\n asRecordId,\n canonicalJson,\n deriveMarkStepId,\n stampReceiptDigest,\n} from '@vostride/agent-qa-schema'\n\nimport type {\n Delta,\n CommitReceipt,\n ExecutionContext,\n Gate3Receipt,\n ForgetReceiptV1,\n KnowledgeMarkInput,\n KnowledgeProjection,\n KnowledgeReviewVerb,\n KnowledgeTargetRef,\n MarkChangeStamp,\n ResolvePromotionPosture,\n TrustPriorTable,\n} from '@vostride/agent-qa-schema'\n\nimport { deriveBundleTrust, loadBundle, readGateReceipts } from '../bundle-read.js'\nimport { enumerateBundleDirs } from '../bundle-scan.js'\nimport {\n createExplicitReviewStore,\n KnowledgePromotionError,\n syntheticEvidenceToken,\n} from '../curator/knowledge-store.js'\nimport { snapshotTrustPriors } from '../promotion-gate-input.js'\nimport { diffSince } from '../diff-since.js'\nimport { materializePolicy, policyShelfPath, PolicyTextRefusedError } from '../policy/materialize.js'\nimport { acquireWriterLease, withCurrentWriterAuthority } from '../lease/writer-lease.js'\nimport { releaseLeaseAfterWork } from '../lease/under-writer-lease.js'\nimport type { WriterLease } from '../lease/writer-lease.js'\nimport { memoryStatusForBundle } from '../memory-status.js'\nimport { readRecordedForgetReceipt, recordForgetReceipt } from './forget-receipt-journal.js'\nimport { FORGET_SCRUBBED_PROJECTIONS, resolveReviewTarget, reviewDeltasFor } from './propose-review.js'\nimport type { ResolveBundleShortId, ReviewChangeRequest } from './propose-review.js'\n\n/**\n * How long a delegating process waits for the leaseholder to finish an apply (D-18).\n *\n * PINNED, not configured, on the `LEASE_HEARTBEAT_TTL_MS` idiom. 30s is chosen as \"longer than any\n * commit this store performs, shorter than a person's patience\": a commit is a handful of file\n * appends plus one bundle re-projection, all local. RETUNE from an observed apply that legitimately\n * exceeded it — never from a flaky test, which is a symptom of a wedged holder rather than a slow\n * one, and the wedged holder is exactly what this bound exists to refuse rather than wait out.\n */\nexport const APPLY_DELEGATE_TIMEOUT_MS = 30_000\n\n/** The typed refusal a bounded wait produces. Never a generic timeout, never a takeover. */\nexport class ApplyDelegateTimeoutError extends Error {\n constructor(readonly changeId: string, readonly timeoutMs: number) {\n super(\n `The writer-lease holder did not answer the change ${changeId} within ${timeoutMs}ms. ` +\n 'Retrying with the same operation identity is the same change; the lease was neither taken nor stolen.',\n )\n this.name = 'ApplyDelegateTimeoutError'\n }\n}\n\n/** The typed refusal when a live holder exists and this host was given no way to reach it. */\nexport class ApplyDelegateUnavailableError extends Error {\n constructor(readonly changeId: string, readonly holder: WriterLease) {\n super(\n `The writer lease for this knowledge root is held by pid ${holder.pid} (lease ` +\n `${holder.leaseId}, epoch ${holder.epoch}) and this host has no delegate transport, so ` +\n `${changeId} cannot be applied here. Lease-stealing is structurally refused (386 D-14).`,\n )\n this.name = 'ApplyDelegateUnavailableError'\n }\n}\n\n/** The record a change addresses left the store between resolution and commit. */\nexport class ReviewTargetVanishedError extends Error {\n constructor(readonly changeId: string) {\n super(`The record ${changeId} addresses is no longer in the store; nothing was committed.`)\n this.name = 'ReviewTargetVanishedError'\n }\n}\n\n/**\n * One review change: a validated direct request (432-06). `id` is the receipt identity, derived from\n * the caller's stable operation identity.\n */\ninterface ReviewChange {\n readonly id: string\n readonly verb: KnowledgeReviewVerb\n readonly deltas: readonly Delta[]\n readonly mark?: MarkChangeStamp\n}\n\n/** The write context. The execution context is the actual one, never spoofed. */\ninterface ReviewWriter {\n readonly knowledgeRoot: string\n readonly executionContext: ExecutionContext\n /** Stamped as a Gate-3 receipt's `producedBy.opId`: the op that made this explicit change. */\n readonly opId: string\n readonly resolvePromotionPosture?: ResolvePromotionPosture\n readonly resolveTrustPriors?: () => TrustPriorTable | undefined\n readonly now?: () => number\n}\n\ninterface WriterAuthority {\n readonly leaseId: string\n readonly epoch: number\n}\n\n/** What a review change did to the store, before any door-specific publication. */\ntype ReviewEffect =\n | {\n readonly kind: 'applied'\n readonly recordIds: readonly string[]\n readonly commitReceipt?: CommitReceipt\n readonly forgetReceipt?: ForgetReceiptV1\n }\n | { readonly kind: 'policy-materialize-refused' }\n\n/**\n * The delta kind a review verb emits when it means \"this record stops standing\".\n *\n * BOTH `reject` and `forget` emit it (propose-review.ts:183-195 — identical `Deprecate` deltas\n * differing only in the recorded reason), so the guard below is keyed on the kind rather than on\n * either verb's name.\n *\n * WHAT THE GUARD BELOW IS, and the previous version of this comment got it wrong, so it is\n * stated plainly: it is an IDEMPOTENCY short-circuit. A deprecating change over an already\n * tombstoned target has nothing left to destroy, and the honest answer is a receipt naming the\n * state that already holds rather than a second destructive change (FUNC-04's adjacency edge,\n * D-19's \"nothing silently partial\").\n *\n * WHAT IT IS NOT: the owner of the unauthored-mint hazard. This comment used to claim the guard's\n * kind-scoping was what stopped a clone being minted, and round 1's verifier measured that claim\n * false by reproducing the identical mint through `accept` — which emits a `Confirm` and walks\n * straight past everything in this file. The hazard lives one layer down, at the curator's\n * `checkCitedIdIntegrity`, whose id domain is `deltaTargetIds` = cited ids ∪ target/victim/\n * conflict ids — strictly wider than `targetRecordIds` below, which reads only `delta.targetId`.\n * Every review delta of every verb passes through that one check funnel regardless of its kind,\n * which is why the closure had to land there and not here: see\n * `UserDeltaCitationIntegrityError` and the origin-keyed fallback table beside it in\n * `curator/disposition.ts`, where a user-authored delta whose citation cannot be honoured is\n * refused by type instead of degraded into minted content.\n */\nconst DEPRECATE_DELTA_KIND = 'Deprecate'\n\n/** Whether a change's deltas deprecate anything. */\nfunction deprecatesRecords(change: ReviewChange): boolean {\n return change.deltas.some((delta) => delta.kind === DEPRECATE_DELTA_KIND)\n}\n\nfunction locateRecord(knowledgeRoot: string, recordId: string) {\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const outcome = loadBundle(entry.dir)\n if (outcome.kind !== 'loaded') continue\n if (outcome.bundle.manifest.id !== recordId) continue\n return {\n dir: entry.dir,\n product: entry.product,\n // Record lookup reads lifecycle only; numerical trust is neither returned nor consulted.\n status: deriveBundleTrust(outcome.bundle).status,\n provenance: outcome.bundle.provenance,\n bundle: outcome.bundle,\n }\n }\n return undefined\n}\n\n/**\n * Whether every record a deprecating change addresses is ALREADY tombstoned.\n *\n * `every`, not `some`: a bundle-grained verb over a partially-tombstoned set still has work to\n * do, and treating it as complete would be the silent partiality D-19 forbids.\n *\n * Judged through the SHARED mapping (387-11) rather than a table local to this module. The local\n * table this replaced named `withdrawn` and `retired` — neither is a `BundleStatus` member, so\n * both were dead weight — and the shared one is `satisfies Record<BundleStatus, …>`, which makes\n * a fifth member a compile error here instead of a status that silently reads as untombstoned.\n */\nfunction alreadyTombstoned(knowledgeRoot: string, change: ReviewChange): boolean {\n const ids = targetRecordIds(change)\n if (ids.length === 0) return false\n return ids.every((recordId) => {\n const located = locateRecord(knowledgeRoot, recordId)\n return located !== undefined && memoryStatusForBundle(located.status) === 'tombstoned'\n })\n}\n\n/** Whether every record a forget names carries the tombstone this very change committed. */\nfunction tombstonedByThisForget(knowledgeRoot: string, change: ReviewChange): boolean {\n const reason = `forget:${change.id}`\n const ids = targetRecordIds(change)\n return ids.length > 0 && ids.every((recordId) =>\n (locateRecord(knowledgeRoot, recordId)?.bundle.events ?? [])\n .some((event) => event.type === 'deprecated' && event.reason === reason))\n}\n\n/** Every record id a change's deltas name — the enumeration a forget receipt is built over. */\nfunction targetRecordIds(change: ReviewChange): string[] {\n const ids = new Set<string>()\n for (const delta of change.deltas as readonly (Delta & { targetId?: string })[]) {\n if (typeof delta.targetId === 'string') ids.add(delta.targetId)\n }\n return [...ids].sort()\n}\n\n/**\n * The effects of a Confirm or Add change that already landed (432-06 retry), or `undefined`.\n *\n * Each delta's committed event carries an evidence token derived from the delta itself, but the\n * curation job id that dedups the append is derived from the build ordinal, so a retried change\n * would land as a second, distinct event. A plain read: the caller already holds the writer\n * lease, so nothing can land in between, and entering the authority fence here would move lease\n * bookkeeping on a change that then refuses. Partial effects are refused by type, exactly as a\n * partial supersession is.\n */\nfunction landedEffects(\n knowledgeRoot: string,\n change: ReviewChange,\n): { recordIds: string[]; ordinal: number } | undefined {\n if (change.deltas.length === 0\n || !change.deltas.every(delta => delta.kind === 'Confirm' || delta.kind === 'Add')) return undefined\n const found: { id: string; ordinal: number }[] = []\n for (const delta of change.deltas) {\n const token = syntheticEvidenceToken(delta)\n const hits = delta.kind === 'Confirm'\n ? (locateRecord(knowledgeRoot, delta.targetId)?.bundle.events ?? [])\n .filter(event => event.type === 'confirmed' && event.evidenceToken === token)\n .map(event => ({ id: delta.targetId as string, ordinal: event.buildOrdinal }))\n : enumerateBundleDirs(knowledgeRoot).flatMap(entry => {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded') return []\n return loaded.bundle.events\n .filter(event => event.type === 'confirmed' && event.evidenceToken === token)\n .map(event => ({ id: loaded.bundle.manifest.id as string, ordinal: event.buildOrdinal }))\n })\n if (hits.length > 1) throw new ReviewTargetVanishedError(change.id)\n if (hits.length === 1) found.push(hits[0]!)\n }\n if (found.length === 0) return undefined\n if (found.length !== change.deltas.length || new Set(found.map(row => row.ordinal)).size !== 1) {\n throw new ReviewTargetVanishedError(change.id)\n }\n return { recordIds: [...new Set(found.map(row => row.id))].sort(), ordinal: found[0]!.ordinal }\n}\n\n/**\n * Build the forget receipt from POST-COMMIT reads, never from the preview.\n *\n * The preview says what would happen; the receipt must say what did. Copying the preview forward\n * would have produced a receipt that is always right by construction and therefore evidence of\n * nothing — including in the one case that matters, where the commit tombstoned less than the\n * preview predicted.\n *\n * `projectionsScrubbed` is a PARAMETER for the same reason (WR-02). It used to be the constant\n * scrub set spliced in unconditionally, which made the receipt right by construction on the one\n * path where it was wrong: the short-circuit runs no commit, so no projection is rebuilt and no\n * recall row is removed, and a receipt naming three scrubs there asserts work nobody performed.\n * `scrubSetSchema` (schema/src/knowledge/change.ts) declares this field a SUBSET of the\n * scrub set with no minimum length, so the empty list is the honest, already-legal answer.\n */\nfunction assembleForgetReceipt(\n knowledgeRoot: string,\n change: ReviewChange,\n forgottenAt: number,\n projectionsScrubbed: readonly KnowledgeProjection[],\n): ForgetReceiptV1 {\n const tombstonedRecords: ForgetReceiptV1['tombstonedRecords'] = []\n let resultingBundleStatus: ForgetReceiptV1['resultingBundleStatus'] = 'forgotten'\n for (const recordId of targetRecordIds(change)) {\n const located = locateRecord(knowledgeRoot, recordId)\n if (located === undefined) {\n // Tombstone-never-destroy (§7.7): the bundle file survives a forget, so a record that\n // cannot be read back after the commit is a fact about the STORE, not about this verb, and\n // reporting a tombstone for it would be the receipt asserting work nobody can verify.\n throw new ReviewTargetVanishedError(change.id)\n }\n tombstonedRecords.push({ recordId, provenance: located.provenance })\n resultingBundleStatus = memoryStatusForBundle(located.status)\n }\n return {\n schemaVersion: FORGET_RECEIPT_SCHEMA_VERSION,\n proposalId: change.id,\n tombstonedRecords,\n projectionsScrubbed: [...projectionsScrubbed],\n resultingBundleStatus,\n forgottenAt,\n }\n}\n\nfunction reviewStore(\n writer: ReviewWriter,\n change: ReviewChange,\n lease: WriterAuthority,\n sourceBuildOrdinal?: number,\n) {\n return createExplicitReviewStore({\n knowledgeRoot: writer.knowledgeRoot,\n executionContext: writer.executionContext,\n epoch: lease.epoch,\n writerLeaseId: lease.leaseId,\n ...(change.mark === undefined ? {} : { sourceRunId: change.mark.runId }),\n ...(sourceBuildOrdinal === undefined ? {} : { sourceBuildOrdinal }),\n ...(writer.resolvePromotionPosture === undefined\n ? {}\n : { resolvePromotionPosture: writer.resolvePromotionPosture }),\n ...(writer.resolveTrustPriors === undefined\n ? {}\n : { resolveTrustPriors: writer.resolveTrustPriors }),\n })\n}\n\nasync function commitInProcess(\n writer: ReviewWriter,\n change: ReviewChange,\n lease: WriterAuthority,\n sourceBuildOrdinal?: number,\n) {\n const store = reviewStore(writer, change, lease, sourceBuildOrdinal)\n // THE one write path. Not `proposeDeltas` (which is the propose-only disposition profile and\n // would commit nothing), not a direct append, not a projection call — `commit`, exactly as any\n // curation write reaches it, through the store's explicit entry: a person's change is not\n // downgraded by the automatic propose-only profile, and every other check still applies.\n // 419-COMMIT-DOOR: commitInProcess\n await store.commit([...change.deltas])\n return store\n}\n\n/** The local bridge has no global counter. Fence this commit above every persisted ordinal. */\nfunction currentOrdinal(knowledgeRoot: string): number {\n let ordinal = 0\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded') continue\n ordinal = Math.max(ordinal, loaded.bundle.manifest.createdAtOrdinal,\n ...loaded.bundle.events.map(event => event.buildOrdinal),\n ...(readGateReceipts(entry.dir, loaded.bundle.manifest.id) ?? []).map(line => line.producedAtOrdinal))\n }\n return ordinal\n}\n\n/** commit() returns void: read the committed additions/confirmations, excluding retired victims. */\nfunction readBackCommittedIds(knowledgeRoot: string, preOrdinal: number, change: ReviewChange): string[] {\n const ids = new Set(change.deltas.flatMap(delta => delta.kind === 'Confirm' ? [delta.targetId] : []))\n // diffSince projects surviving events and receipts into change/identity; it does not fold trust.\n for (const row of diffSince({ knowledgeRoot, sinceOrdinal: preOrdinal })) {\n if (row.change === 'added' || row.change === 'confirmed' || row.change === 'superseded') {\n ids.add(asRecordId(row.recordId))\n }\n }\n return [...ids].filter(id => {\n const record = locateRecord(knowledgeRoot, id)\n return record !== undefined && memoryStatusForBundle(record.status) !== 'tombstoned'\n }).sort()\n}\n\nfunction mintGate3Receipt(\n candidateId: string, writer: ReviewWriter, change: ReviewChange, producedAtOrdinal: number,\n): Gate3Receipt {\n if (change.mark === undefined) throw new TypeError('mark change has no mark stamp')\n return stampReceiptDigest({\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION, gate: 3, candidateId, verdict: 'pass', producedAtOrdinal,\n producedBy: { opId: writer.opId }, runId: change.mark.runId,\n ...(change.mark.stepIndex === undefined ? {} : {\n stepId: deriveMarkStepId(change.mark.testIndex, change.mark.stepIndex),\n }),\n mark: change.mark.kind,\n })\n}\n\nasync function applyMarkArm(\n writer: ReviewWriter, change: ReviewChange, authority: WriterAuthority,\n): Promise<ReviewEffect> {\n const recovered = completedMarkSupersession(writer, change, authority)\n ?? landedEffects(writer.knowledgeRoot, change)\n const preOrdinal = currentOrdinal(writer.knowledgeRoot)\n const store = recovered === undefined\n ? await commitInProcess(writer, change, authority, preOrdinal + 1)\n : reviewStore(writer, change, authority)\n const recordIds = recovered?.recordIds ?? readBackCommittedIds(writer.knowledgeRoot, preOrdinal, change)\n const committedAtOrdinal = recovered?.ordinal ?? currentOrdinal(writer.knowledgeRoot)\n const commitReceipt: CommitReceipt = {\n schemaVersion: COMMIT_RECEIPT_SCHEMA_VERSION, proposalId: change.id, markId: change.mark!.markId,\n committedAtOrdinal, recordIds, gate3: [], promoted: [], held: [],\n }\n for (const candidateId of recordIds) {\n const receipt = mintGate3Receipt(candidateId, writer, change, committedAtOrdinal)\n try {\n const outcome = await store.promote(asRecordId(candidateId), [receipt])\n if (outcome.promotionPath !== undefined) {\n commitReceipt.promoted.push({ candidateId, promotionPath: outcome.promotionPath })\n }\n } catch (error) {\n if (!(error instanceof KnowledgePromotionError)\n || error.reason === 'propose-only' || error.reason === 'not-found') throw error\n commitReceipt.held.push({ candidateId, reason: error.reason })\n }\n commitReceipt.gate3.push({ candidateId, receiptDigest: receipt.receiptDigest })\n }\n return { kind: 'applied', recordIds, commitReceipt }\n}\n\n/** A retry is not another lineage transition. Recover exact mark Supersede effects before commit. */\nfunction completedMarkSupersession(\n writer: ReviewWriter, change: ReviewChange, authority: WriterAuthority,\n): { recordIds: string[]; ordinal: number } | undefined {\n if (change.deltas.length === 0 || !change.deltas.every(delta => delta.kind === 'Supersede')) return undefined\n return withCurrentWriterAuthority(writer.knowledgeRoot, authority, () => {\n const found: { id: string; ordinal: number }[] = []\n for (const delta of change.deltas) {\n if (delta.kind !== 'Supersede') throw new Error('Expected mark Supersede')\n const victim = locateRecord(writer.knowledgeRoot, delta.victimId)\n const matches = victim?.bundle.events.filter(row => row.type === 'superseded'\n && row.evidenceToken === delta.evidenceToken) ?? []\n if (matches.length === 0) {\n // No own effects: the normal commit path retains its exact citation-integrity refusal.\n continue\n }\n const event = matches.length === 1 ? matches[0] : undefined\n if (event?.type !== 'superseded' || delta.evidenceToken !== `mark:${change.mark!.markId}`) {\n throw new ReviewTargetVanishedError(change.id)\n }\n const replacement = locateRecord(writer.knowledgeRoot, event.byRecordId)\n if (replacement === undefined || memoryStatusForBundle(replacement.status) === 'tombstoned'\n || replacement.bundle.frontmatter.kind !== delta.newBundle.kind\n || replacement.bundle.frontmatter.subtype !== delta.newBundle.subtype\n || replacement.bundle.body !== delta.newBundle.body\n || canonicalJson(replacement.bundle.frontmatter.scope) !== canonicalJson(delta.newBundle.scope)\n || canonicalJson(replacement.bundle.frontmatter.anchors.map(anchor => anchor.raw)) !== canonicalJson(delta.newBundle.anchors)\n || !replacement.bundle.events.some(row => row.type === 'confirmed' && row.evidenceToken === delta.evidenceToken\n && row.buildOrdinal === event.buildOrdinal && row.curationJobId === event.curationJobId)\n || !replacement.bundle.relations.relations.some(row => row.type === 'supersedes' && row.targetId === delta.victimId\n && row.addedAtOrdinal === event.buildOrdinal && row.curationJobId === event.curationJobId)\n || !victim!.bundle.events.some(row => row.type === 'window-close' && row.closedAtOrdinal === event.buildOrdinal\n && row.curationJobId === event.curationJobId)) throw new ReviewTargetVanishedError(change.id)\n found.push({ id: event.byRecordId, ordinal: event.buildOrdinal })\n }\n if (found.length === 0) return undefined\n if (found.length !== change.deltas.length || new Set(found.map(row => row.ordinal)).size !== 1) {\n throw new ReviewTargetVanishedError(change.id)\n }\n return { recordIds: [...new Set(found.map(row => row.id))].sort(), ordinal: found[0]!.ordinal }\n })\n}\n\nasync function applyPolicyArm(\n writer: ReviewWriter, change: ReviewChange, authority: WriterAuthority,\n recordId: string, record: NonNullable<ReturnType<typeof locateRecord>>,\n): Promise<ReviewEffect> {\n if (memoryStatusForBundle(record.status) === 'tombstoned') {\n return recoverPolicyArm(writer, change, authority, recordId)\n }\n const { bundle } = record\n const scope = bundle.frontmatter.scope\n let materialized\n try {\n materialized = materializePolicy({ knowledgeRoot: writer.knowledgeRoot, recordId,\n scope: scope.tier === 'global' ? 'global' : scope.key, ruleText: bundle.body,\n title: bundle.summary, writerAuthority: authority })\n } catch (error) {\n if (!(error instanceof PolicyTextRefusedError)) throw error\n }\n if (materialized === undefined) return { kind: 'policy-materialize-refused' }\n const reference: Delta = {\n kind: 'Supersede', origin: 'user', scope, citedIds: [asRecordId(recordId)],\n victimId: asRecordId(recordId), evidenceToken: asEvidenceToken(`policy-materialize:${change.id}`),\n newBundle: { kind: 'policy', summary: bundle.body.split('\\n')[0] ?? bundle.summary,\n body: `${materialized.relPath}#agent-qa:policy ${recordId}`,\n anchors: bundle.frontmatter.anchors.map(({ raw }) => raw), scope,\n distilledEvidenceRef: { id: recordId, sha: bundle.manifest.contentHashes['record.md']! },\n originStage: 'run-curation' },\n }\n const preOrdinal = currentOrdinal(writer.knowledgeRoot)\n const store = await commitInProcess(writer, { ...change, deltas: [...change.deltas, reference] },\n authority, preOrdinal + 1)\n // Select the replacement by lifecycle/identity; the DTO's computed trust is never consumed.\n const superseded = diffSince({ knowledgeRoot: writer.knowledgeRoot, sinceOrdinal: preOrdinal })\n .find(row => row.recordId === recordId && row.change === 'superseded')\n const replacement = superseded?.byRecordId === undefined ? undefined\n : locateRecord(writer.knowledgeRoot, superseded.byRecordId)\n if (replacement?.bundle.frontmatter.kind !== 'policy' || replacement.bundle.body !== reference.newBundle.body) {\n throw new ReviewTargetVanishedError(change.id)\n }\n const committedAtOrdinal = currentOrdinal(writer.knowledgeRoot)\n const receipt = stampReceiptDigest({\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION, gate: 3, candidateId: recordId,\n verdict: 'pass', producedAtOrdinal: committedAtOrdinal,\n producedBy: { opId: writer.opId },\n policyApproval: { proposalId: change.id, recordId },\n } as const)\n await store.recordGateReceipt(receipt)\n const commitReceipt: CommitReceipt = { schemaVersion: COMMIT_RECEIPT_SCHEMA_VERSION, proposalId: change.id,\n committedAtOrdinal, recordIds: [recordId], gate3: [{ candidateId: recordId, receiptDigest: receipt.receiptDigest }],\n promoted: [], held: [], policy: { recordId, scope: scope.tier === 'global' ? 'global' : scope.key,\n relPath: materialized.relPath, outcome: materialized.kind } }\n return { kind: 'applied', recordIds: [recordId], commitReceipt }\n}\n\n/** Recover only this change's fully committed effects; a closed target alone proves nothing. */\nasync function recoverPolicyArm(\n writer: ReviewWriter, change: ReviewChange, authority: WriterAuthority, recordId: string,\n): Promise<ReviewEffect> {\n const committed = withCurrentWriterAuthority(writer.knowledgeRoot, authority, () => {\n const victim = locateRecord(writer.knowledgeRoot, recordId)\n const token = `policy-materialize:${change.id}`\n const events = victim?.bundle.events.filter(event => event.type === 'superseded' && event.evidenceToken === token)\n const event = events?.length === 1 ? events[0] : undefined\n if (victim === undefined || event?.type !== 'superseded') throw new ReviewTargetVanishedError(change.id)\n const replacement = locateRecord(writer.knowledgeRoot, event.byRecordId)\n const scope = victim.bundle.frontmatter.scope\n const shelfScope = scope.tier === 'global' ? 'global' : scope.key\n const relPath = relative(writer.knowledgeRoot, policyShelfPath(writer.knowledgeRoot, shelfScope))\n if (replacement?.bundle.frontmatter.kind !== 'policy'\n || memoryStatusForBundle(replacement.status) === 'tombstoned'\n || replacement.bundle.body !== `${relPath}#agent-qa:policy ${recordId}`\n || canonicalJson(replacement.bundle.frontmatter.scope) !== canonicalJson(scope)\n || replacement.bundle.manifest.createdAtOrdinal !== event.buildOrdinal\n || !replacement.bundle.events.some(row => row.type === 'confirmed' && row.evidenceToken === token\n && row.buildOrdinal === event.buildOrdinal && row.curationJobId === event.curationJobId)\n || !replacement.bundle.relations.relations.some(row => row.type === 'supersedes' && row.targetId === recordId\n && row.addedAtOrdinal === event.buildOrdinal && row.curationJobId === event.curationJobId)\n || !victim.bundle.events.some(row => row.type === 'window-close' && row.closedAtOrdinal === event.buildOrdinal\n && row.curationJobId === event.curationJobId)\n || !change.deltas.every(delta => delta.kind === 'Confirm' && delta.targetId === recordId\n && victim.bundle.events.some(row => row.type === 'confirmed' && row.evidenceToken === delta.evidenceToken\n && row.buildOrdinal === event.buildOrdinal))) throw new ReviewTargetVanishedError(change.id)\n const receipt = stampReceiptDigest({\n schemaVersion: GATE_RECEIPT_SCHEMA_VERSION, gate: 3, candidateId: recordId,\n verdict: 'pass', producedAtOrdinal: event.buildOrdinal,\n producedBy: { opId: writer.opId },\n policyApproval: { proposalId: change.id, recordId },\n } as const)\n const gates = readGateReceipts(victim.dir, recordId)\n if (gates === undefined && existsSync(join(victim.dir, 'evidence/gates.jsonl'))) {\n throw new Error('Policy approval evidence is unreadable')\n }\n const prior = (gates ?? []).filter(row => 'gate' in row && row.gate === 3\n && row.policyApproval?.proposalId === change.id)\n if (prior.length > 1 || (prior.length === 1 && canonicalJson(prior[0]) !== canonicalJson(receipt))) {\n throw new Error('Policy approval evidence does not match the committed supersession')\n }\n return { victim, shelfScope, relPath, receipt, hasReceipt: prior.length === 1 }\n })\n const materialized = materializePolicy({ knowledgeRoot: writer.knowledgeRoot, recordId,\n scope: committed.shelfScope, ruleText: committed.victim.bundle.body,\n title: committed.victim.bundle.summary, writerAuthority: authority, existingOnly: true })\n if (materialized.kind !== 'unchanged') throw new Error('Committed policy section is unavailable')\n if (!committed.hasReceipt) await reviewStore(writer, change, authority).recordGateReceipt(committed.receipt)\n const commitReceipt: CommitReceipt = { schemaVersion: COMMIT_RECEIPT_SCHEMA_VERSION, proposalId: change.id,\n committedAtOrdinal: committed.receipt.producedAtOrdinal, recordIds: [recordId],\n gate3: [{ candidateId: recordId, receiptDigest: committed.receipt.receiptDigest }], promoted: [], held: [],\n policy: { recordId, scope: committed.shelfScope, relPath: committed.relPath, outcome: materialized.kind } }\n return { kind: 'applied', recordIds: [recordId], commitReceipt }\n}\n\n/** Apply one change under authority the caller already holds. Publishes nothing beyond the commit. */\nasync function writeReviewChange(\n writer: ReviewWriter, change: ReviewChange, authority: WriterAuthority,\n): Promise<ReviewEffect> {\n if (change.verb === 'mark') return await applyMarkArm(writer, change, authority)\n if (change.verb === 'accept') {\n for (const recordId of targetRecordIds(change)) {\n const record = locateRecord(writer.knowledgeRoot, recordId)\n if (record?.bundle.frontmatter.kind === 'policy') {\n return await applyPolicyArm(writer, change, authority, recordId, record)\n }\n }\n }\n // FUNC-04's adjacency edge, decided BEFORE the commit rather than hoped for after it.\n //\n // Deprecating an already-tombstoned record must be \"a receipt naming the already-tombstoned\n // state, never a second destructive change\", and that is ALL this branch does. Idempotency\n // lives here, over the target's STATE rather than only over the change id, because rejecting\n // the same record twice is the most ordinary repetition a review invites.\n //\n // CORRECTED, because the earlier version of this comment claimed more than it delivers: this\n // branch is NOT what stops an unauthored clone being minted. It cannot be — it is reachable\n // only for a change that deprecates, and round 1's verifier reproduced the identical mint\n // through `accept`, whose `Confirm` never enters here. The mint is the curator's response to\n // a cited-id-integrity failure, and it is refused at that check now, for every review delta\n // of every kind, by `UserDeltaCitationIntegrityError`. What is true and worth keeping: the\n // clone really is a verbatim copy of the target's anchors, scope and summary republished as\n // a fresh `candidate`, which `isEligibleCandidate` (serving/brief-selection.ts:142-151)\n // re-admits into serving — that is why the refusal, not merely a no-op, is the right answer.\n if (deprecatesRecords(change) && alreadyTombstoned(writer.knowledgeRoot, change)) {\n const recordIds = targetRecordIds(change)\n // reject carries no receipt on any path; the record ids are the whole answer.\n if (change.verb !== 'forget') return { kind: 'applied', recordIds }\n // 2026-10-02 (quick 261002-lse, 432-16 #3): a retry of the SAME change answers the receipt its\n // first application recorded, byte for byte, as reject's retry already answers its record ids.\n const recorded = readRecordedForgetReceipt(writer.knowledgeRoot, change.id)\n const recordedIds = recorded?.tombstonedRecords.map(row => row.recordId)\n if (recorded !== undefined && canonicalJson(recordedIds) === canonicalJson(recordIds)) {\n return { kind: 'applied', recordIds, forgetReceipt: recorded }\n }\n // WR-02: when something ELSE tombstoned these records, no commit ran for this change, so no\n // projection was rebuilt and no recall row was removed. The scrub list is EMPTY because that\n // is what happened. A tombstone this change itself committed (its receipt was never recorded)\n // did scrub them, and says so.\n const scrubbed = tombstonedByThisForget(writer.knowledgeRoot, change)\n ? FORGET_SCRUBBED_PROJECTIONS\n : []\n const forgetReceipt = assembleForgetReceipt(\n writer.knowledgeRoot, change, (writer.now ?? Date.now)(), scrubbed)\n recordForgetReceipt(writer.knowledgeRoot, authority, forgetReceipt)\n return { kind: 'applied', recordIds, forgetReceipt }\n }\n\n if (landedEffects(writer.knowledgeRoot, change) === undefined) {\n await commitInProcess(writer, change, authority)\n }\n const recordIds = targetRecordIds(change)\n if (change.verb !== 'forget') return { kind: 'applied', recordIds }\n const forgetReceipt = assembleForgetReceipt(\n writer.knowledgeRoot,\n change,\n (writer.now ?? Date.now)(),\n FORGET_SCRUBBED_PROJECTIONS,\n )\n recordForgetReceipt(writer.knowledgeRoot, authority, forgetReceipt)\n return { kind: 'applied', recordIds, forgetReceipt }\n}\n\n/**\n * A leaseholder never delegates, and the input may not claim to be both (WR-04).\n *\n * The two fields are mutually exclusive by MEANING: `writerAuthority` says \"I hold the lease and\n * will commit in this process\", `delegate` says \"somebody else holds it and here is how to reach\n * them\". Supplying both was previously refused only by reading the code — the authority branch\n * is taken first and returns, so a caller that passed both silently got the in-process commit and\n * never learned its delegate was ignored. A source-scan-only rule is one refactor away from being\n * untrue; this makes it structural, and it fires before any lease is asked for.\n */\nfunction assertSingleWritePath(\n input: { readonly writerAuthority?: unknown; readonly delegate?: unknown },\n entry: 'applyExplicitReview',\n): void {\n if (input.writerAuthority !== undefined && input.delegate !== undefined) {\n throw new TypeError(\n `${entry} received both \\`writerAuthority\\` and \\`delegate\\`. A leaseholder never ` +\n 'delegates: holding the writer lease is exactly what makes an in-process commit the ' +\n 'only available path, so supply one or the other and never both.',\n )\n }\n}\n\n/**\n * Wait bounded for the delegate, and REFUSE rather than hang.\n *\n * `Promise.race` against a timer rather than an abort signal, because the transport is injected and\n * this module cannot assume it is cancellable. The consequence is stated rather than hidden: a\n * wedged holder's answer may still arrive after the refusal, and it is discarded — nothing was\n * applied here either way, so the worst case is a retry that finds the work already done. A hang\n * has no such worst case.\n */\nasync function withBoundedWait<T>(\n changeId: string,\n delegateTimeoutMs: number | undefined,\n call: () => Promise<T>,\n): Promise<T> {\n const timeoutMs = delegateTimeoutMs ?? APPLY_DELEGATE_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n call(),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(new ApplyDelegateTimeoutError(changeId, timeoutMs)),\n timeoutMs,\n )\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\n// ---- 432-06: the direct door ------------------------------------------------------------------\n\n/** A validated mark, accept, reject or forget, in the shape the review verbs already take. */\nexport type ExplicitReviewRequest = ReviewChangeRequest\n\n/** What the writer-lease holder is handed: the same request and the same stable identity. */\nexport interface ExplicitReviewDelegation {\n readonly request: ExplicitReviewRequest\n readonly operationId: string\n}\n\n/**\n * Hand the direct request to the leaseholder and wait bounded for its answer (D-18). Injected as\n * an optional operation rather than built here: `knowledge-local` neither knows nor may know that a\n * unix socket exists. A host supplies its transport; the leaseholder's own composition supplies\n * nothing, which makes delegation recursion impossible by construction.\n */\nexport type ExplicitReviewDelegate = (delegation: ExplicitReviewDelegation) => Promise<ExplicitReviewResult>\n\nexport interface ApplyExplicitReviewInput {\n readonly agentQaRoot: string\n readonly knowledgeRoot: string\n readonly request: ExplicitReviewRequest\n /**\n * The caller's stable identity for this change, such as a mark intent's UUID. A retry with the\n * same identity is the same change: its evidence tokens, receipts and record ids repeat.\n */\n readonly operationId: string\n /** The op making the change, stamped on Gate-3 receipts as `producedBy.opId`. */\n readonly opId: string\n /** The caller's actual context. Recorded as-is; explicit authority never rewrites it. */\n readonly executionContext: ExecutionContext\n readonly resolveBundleShortId?: ResolveBundleShortId\n readonly delegate?: ExplicitReviewDelegate\n readonly writerAuthority?: WriterAuthority\n readonly resolvePromotionPosture?: ResolvePromotionPosture\n readonly resolveTrustPriors?: () => TrustPriorTable | undefined\n readonly now?: () => number\n readonly delegateTimeoutMs?: number\n}\n\nexport type ExplicitReviewResult =\n | {\n readonly outcome: 'applied'\n readonly verb: KnowledgeReviewVerb\n readonly changeId: string\n /** The records the change added, confirmed or tombstoned, read back after the write. */\n readonly recordIds: readonly string[]\n readonly commitReceipt?: CommitReceipt\n readonly forgetReceipt?: ForgetReceiptV1\n }\n | {\n readonly outcome: 'target-not-found'\n readonly verb: KnowledgeReviewVerb\n readonly changeId: string\n readonly target: KnowledgeTargetRef\n }\n | {\n readonly outcome: 'policy-materialize-refused'\n readonly verb: KnowledgeReviewVerb\n readonly changeId: string\n }\n\n/** Validate at the boundary, before any lease is asked for or any request is delegated. */\nfunction validatedRequest(request: ExplicitReviewRequest): ExplicitReviewRequest {\n switch (request.verb) {\n case 'accept':\n return { verb: 'accept', input: KnowledgeAcceptInputSchema.parse(request.input) }\n case 'reject':\n return { verb: 'reject', input: KnowledgeRejectInputSchema.parse(request.input) }\n case 'forget':\n return { verb: 'forget', input: KnowledgeForgetInputSchema.parse(request.input) }\n case 'mark':\n return { verb: 'mark', input: KnowledgeMarkInputSchema.parse(request.input) }\n default:\n throw new TypeError('an explicit knowledge change names accept, reject, forget or mark')\n }\n}\n\n/**\n * The change identity receipts carry, derived from the caller's operation identity. It keeps the\n * receipt id shape, so the same UUID a mark intent already holds names the same change here.\n */\nfunction explicitChangeId(operationId: string): string {\n const parsed = typeof operationId === 'string'\n ? KnowledgeChangeIdSchema.safeParse(`prop_${operationId.toLowerCase()}`)\n : undefined\n if (parsed?.success !== true) {\n throw new TypeError(\n 'operationId must be a stable identity of letters, digits and single hyphens, such as a UUID',\n )\n }\n return parsed.data\n}\n\nasync function applyExplicitAsHolder(\n writer: ReviewWriter,\n request: ExplicitReviewRequest,\n changeId: string,\n authority: WriterAuthority,\n resolveBundleShortId: ResolveBundleShortId | undefined,\n): Promise<ExplicitReviewResult> {\n const target = request.input.target\n const resolved = resolveReviewTarget(writer.knowledgeRoot, target, resolveBundleShortId)\n if (resolved === undefined) return { outcome: 'target-not-found', verb: request.verb, changeId, target }\n const change: ReviewChange = {\n id: changeId,\n verb: request.verb,\n deltas: reviewDeltasFor(request, resolved, changeId),\n ...(request.verb === 'mark' ? { mark: (request.input as KnowledgeMarkInput).mark } : {}),\n }\n const effect = await writeReviewChange(writer, change, authority)\n if (effect.kind === 'policy-materialize-refused') {\n return { outcome: 'policy-materialize-refused', verb: request.verb, changeId }\n }\n return {\n outcome: 'applied',\n verb: request.verb,\n changeId,\n recordIds: [...effect.recordIds],\n ...(effect.commitReceipt === undefined ? {} : { commitReceipt: effect.commitReceipt }),\n ...(effect.forgetReceipt === undefined ? {} : { forgetReceipt: effect.forgetReceipt }),\n }\n}\n\n/**\n * Apply an explicit knowledge change in the call (432-06, D-04/D-05/D-09/D-11).\n *\n * No envelope is written, claimed or reloaded. A holder commits with its own authority, a free lease is acquired and released, and a live holder is\n * handed the same validated request and identity, bounded, and is never stolen from. Retrying\n * the same `operationId` lands nothing twice and answers the same record ids.\n */\nexport async function applyExplicitReview(input: ApplyExplicitReviewInput): Promise<ExplicitReviewResult> {\n assertSingleWritePath(input, 'applyExplicitReview')\n const request = validatedRequest(input.request)\n const changeId = explicitChangeId(input.operationId)\n if (typeof input.opId !== 'string' || input.opId.length === 0) {\n throw new TypeError('applyExplicitReview needs the op id that makes the change')\n }\n const priors = snapshotTrustPriors(input.resolveTrustPriors?.())\n const writer: ReviewWriter = {\n knowledgeRoot: input.knowledgeRoot,\n executionContext: input.executionContext,\n opId: input.opId,\n ...(input.resolvePromotionPosture === undefined\n ? {}\n : { resolvePromotionPosture: input.resolvePromotionPosture }),\n ...(input.resolveTrustPriors === undefined ? {} : { resolveTrustPriors: () => priors }),\n ...(input.now === undefined ? {} : { now: input.now }),\n }\n if (input.writerAuthority !== undefined) {\n return await applyExplicitAsHolder(writer, request, changeId, input.writerAuthority,\n input.resolveBundleShortId)\n }\n const acquired = acquireWriterLease(input.knowledgeRoot)\n if (acquired.kind === 'held') {\n const delegate = input.delegate\n if (delegate === undefined) throw new ApplyDelegateUnavailableError(changeId, acquired.holder)\n return await withBoundedWait(changeId, input.delegateTimeoutMs,\n () => delegate({ request, operationId: input.operationId }))\n }\n if (acquired.kind !== 'acquired') throw acquired.error\n try {\n return await applyExplicitAsHolder(writer, request, changeId, acquired, input.resolveBundleShortId)\n } finally {\n // An applied change is never reported as failed because the release after it threw (WR-11).\n releaseLeaseAfterWork({ knowledgeRoot: input.knowledgeRoot, leaseId: acquired.leaseId })\n }\n}\n","import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join, relative } from 'node:path'\nimport { slugBranch } from '@vostride/agent-qa-schema'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport { withCurrentWriterAuthority, type CurrentWriterAuthority } from '../lease/writer-lease.js'\nimport { stripPolicyHtmlComments } from '../serving/policy-ladder.js'\n\nexport class PolicyTextRefusedError extends Error {\n constructor() {\n super('Policy text must not contain HTML comment delimiters or invalid marker identity')\n this.name = 'PolicyTextRefusedError'\n }\n}\n\nexport function policySectionMarkers(recordId: string): { open: string; close: string } {\n if (!/^[A-Za-z0-9_.:-]+$/.test(recordId)) throw new PolicyTextRefusedError()\n return { open: `<!-- agent-qa:policy ${recordId} -->`, close: `<!-- /agent-qa:policy ${recordId} -->` }\n}\n\nexport function policyShelfPath(knowledgeRoot: string, scope: string): string {\n return join(knowledgeRoot, 'policies', `${slugBranch(scope)}.md`)\n}\n\nexport interface MaterializePolicyInput {\n writerAuthority: CurrentWriterAuthority\n knowledgeRoot: string\n recordId: string\n scope: string\n ruleText: string\n title?: string\n /** Recovery validates a previously authored section and must never recreate a missing one. */\n existingOnly?: boolean\n}\n\nexport type MaterializeOutcome = { kind: 'written' | 'unchanged'; relPath: string; sectionBytes: number }\n\n/**\n * The authored shelf is append-only under the caller's writer lease. An existing section ID\n * always wins, including when its human-edited body differs. Never rewrite that body.\n * commitArtifacts governs binary bundle artifacts, not policy text or git commits.\n * The authored text is written as given; no detector scans it (Phase 441, D-15).\n */\nexport function materializePolicy(input: MaterializePolicyInput): MaterializeOutcome {\n return withCurrentWriterAuthority(input.knowledgeRoot, input.writerAuthority, () => materializeUnderAuthority(input))\n}\n\nfunction materializeUnderAuthority(input: MaterializePolicyInput): MaterializeOutcome {\n if ([input.ruleText, input.title ?? '', input.scope].some(text => /<!--|-->/.test(text))) {\n throw new PolicyTextRefusedError()\n }\n const { open, close } = policySectionMarkers(input.recordId)\n const path = policyShelfPath(input.knowledgeRoot, input.scope)\n // 261003-mqc: a `policies/` linked out of the knowledge root is refused before any write.\n assertWithinKnowledgeRoot(input.knowledgeRoot, dirname(path))\n const relPath = relative(input.knowledgeRoot, path)\n const section = `\\n${open}\\n${input.title ? `### ${input.title}\\n` : ''}${input.ruleText.trim()}\\n${close}\\n`\n const sectionBytes = Buffer.byteLength(section)\n const exists = existsSync(path)\n const previous = exists ? readFileSync(path) : Buffer.alloc(0)\n const source = previous.toString('utf8')\n // Validate every existing section, including removed/other IDs, before trusting idempotency.\n // The serving parser also rejects nested and incomplete HTML comments.\n try { stripPolicyHtmlComments(source, relPath) } catch { throw new PolicyTextRefusedError() }\n const seen = new Set<string>()\n let pending: string | undefined\n for (const line of source.split(/\\r?\\n/)) {\n if (!line.includes('agent-qa:policy')) continue\n const marker = /^<!-- (\\/?)agent-qa:policy ([A-Za-z0-9_.:-]+) -->$/.exec(line)\n if (marker === null) throw new PolicyTextRefusedError()\n const id = marker[2]!\n if (marker[1] === '') {\n if (pending !== undefined || seen.has(id)) throw new PolicyTextRefusedError()\n pending = id\n } else {\n if (pending !== id) throw new PolicyTextRefusedError()\n pending = undefined\n seen.add(id)\n }\n }\n if (pending !== undefined) throw new PolicyTextRefusedError()\n if (seen.has(input.recordId)) return { kind: 'unchanged', relPath, sectionBytes }\n if (input.existingOnly) throw new PolicyTextRefusedError()\n const text = `${exists ? '' : `# Policies — ${input.scope}\\n`}${section}`\n // 419-POLICY-WRITER: materialize directory\n mkdirSync(dirname(path), { recursive: true })\n const staged = `${path}.pending`\n let fd: number | undefined\n try {\n // Serialized by the existing writer transaction; a prior interrupted stage is replaceable.\n // 419-POLICY-WRITER: materialize stage\n fd = openSync(staged, 'w', 0o600)\n writeFileSync(fd, Buffer.concat([previous, Buffer.from(text)]))\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // 419-POLICY-WRITER: materialize\n renameSync(staged, path)\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(staged, { force: true })\n }\n return { kind: 'written', relPath, sectionBytes }\n}\n","/**\n * The receipt each forget answered, recorded under its change id (quick 261002-lse, 432-16 #3).\n *\n * A retry of the same operation identity is the same change, so it must answer the same receipt,\n * byte for byte. `forgottenAt` is a wall-clock instant nothing else in the store records, so the\n * first answer is kept here, beside the commit intents and completed-effect receipts: gitignored\n * operational state under `memory/queue/`, written atomically inside the writer's authority. The\n * text is the answer's own serialization, so a retry parses back the same keys in the same order.\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join } from 'node:path'\n\nimport {\n ForgetReceiptV1Schema,\n KnowledgeChangeIdSchema,\n type ForgetReceiptV1,\n} from '@vostride/agent-qa-schema'\n\nimport { fsyncDirectory } from '../durable-fs.js'\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\nimport { JOURNAL_SUBDIR } from '../journal/intent-journal.js'\nimport { withCurrentWriterAuthority, type CurrentWriterAuthority } from '../lease/writer-lease.js'\n\nexport const FORGET_RECEIPTS_SUBDIR = `${JOURNAL_SUBDIR}/forget-receipts`\n\nfunction receiptFile(knowledgeRoot: string, changeId: string): string {\n if (!isAbsolute(knowledgeRoot)) throw new TypeError('knowledgeRoot must be absolute')\n const name = `${KnowledgeChangeIdSchema.parse(changeId)}.json`\n return join(knowledgeRoot, FORGET_RECEIPTS_SUBDIR, name)\n}\n\n/** The receipt a change's earlier application answered, or `undefined` when none is readable. */\nexport function readRecordedForgetReceipt(\n knowledgeRoot: string,\n changeId: string,\n): ForgetReceiptV1 | undefined {\n let text: string\n try {\n text = readFileSync(receiptFile(knowledgeRoot, changeId), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return undefined\n }\n // Validated, but the parsed value itself is answered so its key order is the recorded one.\n const parsed = ForgetReceiptV1Schema.safeParse(value)\n if (!parsed.success || parsed.data.proposalId !== changeId) return undefined\n return value as ForgetReceiptV1\n}\n\n/** Record the receipt a forget is answering; a later application of the change replaces it. */\nexport function recordForgetReceipt(\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n receipt: ForgetReceiptV1,\n): void {\n const file = receiptFile(knowledgeRoot, ForgetReceiptV1Schema.parse(receipt).proposalId)\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(file))\n const text = `${JSON.stringify(receipt)}\\n`\n withCurrentWriterAuthority(knowledgeRoot, authority, () => {\n mkdirSync(dirname(file), { recursive: true })\n fsyncDirectory(dirname(dirname(file)))\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n fsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n })\n}\n","// The durable draft-receipts store (Phase 393, D-19 · WTST-02).\n//\n// A KEEP-GATE EVALUATION IS A DECISION SOMEBODY HAS TO BE ABLE TO READ BACK. The op returns the\n// receipt AND persists it, because 394's accept flow carries it as evidence refs and the author of\n// a rejected draft is owed the exact reason days later — neither of which survives in memory. So\n// this is the proposals-store idiom (387 D-17 / 391 D-10) applied to a second kind of durable\n// record: one `<contentDigest>.json` per draft under a gitignored `<agentQaRoot>/draft-receipts/`,\n// a sibling of `proposals/`, written atomically through a `.tmp` name that is never enumerated.\n//\n// KEYED BY THE DRAFT'S CONTENT DIGEST, not by its path or its test id. That is what makes a\n// receipt mean \"this evaluation is about THESE bytes\": an author who edits the draft mints a new\n// digest and therefore cannot inherit the verdict earned by the version that was actually run. It\n// is also why the store needs no versioning of its own — a superseding evaluation of the SAME\n// bytes replaces the record, and an evaluation of different bytes is a different record.\n//\n// WHAT IT WILL NOT HOLD. Receipts are refs plus findings, never run payloads and never resolved\n// secrets (D-19, map-not-territory). That is enforced structurally rather than by convention:\n// `DraftReceiptSchema` is `.strict()` and is parsed on the way OUT as well as on the way in, so a\n// payload smuggled onto a receipt is a typed refusal at the moment of writing rather than a field\n// somebody notices in a durable file months later (T-393-02).\n//\n// STAMP AND HARD-FAIL. The schema pins `schemaVersion` as a literal. A record written under a\n// future shape is refused loudly here rather than reinterpreted under today's — the house\n// convention `AddressingLedgerSchemaVersionError` and `QuarantineLedgerVersionError` already set,\n// and the only safe answer for a store whose whole purpose is to say what was decided.\n\nimport { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n CURRENT_DRAFT_RECEIPT_SCHEMA_VERSION,\n DraftReceiptSchema,\n} from '@vostride/agent-qa-schema'\nimport type { DraftReceipt } from '@vostride/agent-qa-schema'\n\nimport { durableRename, fsyncDirectory, fsyncFile } from '../durable-fs.js'\n\n/** The one directory name receipts live under, beneath the agent-qa runtime root. */\nexport const DRAFT_RECEIPTS_DIR_NAME = 'draft-receipts'\n\n/** The durable name shape, and the in-flight sibling that is never a receipt. */\nconst RECEIPT_SUFFIX = '.json'\nconst TEMP_SUFFIX = '.tmp'\n\n/**\n * The digest shapes this store will turn into a path.\n *\n * IN-03, applied where the joining happens (the proposals-store precedent: the shape check lives\n * in the module that calls `join`, not only in the function layer one package away). A\n * `contentDigest` arrives from a caller and becomes a filename two lines later, so a value\n * carrying `../` is a caller-supplied arbitrary-path primitive on both the read and the write\n * verb. Deliberately WIDER than sha256-hex — the DTO promises only a non-empty string, and a\n * store that refused a legitimate digest of another width would be enforcing a rule the\n * vocabulary does not make — but narrow enough that no member of it can name a path separator, a\n * parent directory, or a hidden file.\n */\nconst SAFE_DIGEST = /^[A-Za-z0-9_-]{1,128}$/\n\n/** Thrown when a content digest could not be safely turned into a filename. */\nexport class DraftReceiptDigestError extends Error {\n constructor(readonly contentDigest: string) {\n super(\n 'A draft receipt content digest must be 1-128 characters of [A-Za-z0-9_-]; '\n + `refusing to address ${JSON.stringify(contentDigest)}`,\n )\n this.name = 'DraftReceiptDigestError'\n }\n}\n\n/** Thrown when a persisted receipt was written under a different schema version. */\nexport class DraftReceiptSchemaVersionError extends Error {\n constructor(\n readonly path: string,\n readonly foundVersion: unknown,\n ) {\n super(\n `Draft receipt at ${path} declares schemaVersion ${String(foundVersion)}, but this build `\n + `reads version ${CURRENT_DRAFT_RECEIPT_SCHEMA_VERSION}`,\n )\n this.name = 'DraftReceiptSchemaVersionError'\n }\n}\n\nexport interface DraftReceiptsStoreOptions {\n /**\n * Where receipts are durable — `<configDir>/.agent-qa`. A FACTORY on the `createProposalsInbox`\n * precedent: the CLI resolves its root asynchronously and per call, so closing over one resolved\n * value would cache a fact this module does not own.\n */\n readonly resolveAgentQaRoot: () => Promise<string> | string\n}\n\nexport interface DraftReceiptsStore {\n /** Persist a receipt under its own `draftRef.contentDigest`. Create-on-first-write. */\n put(receipt: DraftReceipt): Promise<void>\n /** The receipt for these draft bytes, or `undefined` if none was ever written. */\n get(contentDigest: string): Promise<DraftReceipt | undefined>\n /** Every stored receipt, ordered by digest so two calls render the same table. */\n list(): Promise<DraftReceipt[]>\n}\n\nexport function draftReceiptsDir(agentQaRoot: string): string {\n return join(agentQaRoot, DRAFT_RECEIPTS_DIR_NAME)\n}\n\nfunction receiptPath(agentQaRoot: string, contentDigest: string): string {\n if (!SAFE_DIGEST.test(contentDigest)) throw new DraftReceiptDigestError(contentDigest)\n return join(draftReceiptsDir(agentQaRoot), `${contentDigest}${RECEIPT_SUFFIX}`)\n}\n\n/**\n * Write bytes atomically: full content to a pid-suffixed sibling, fsync, rename.\n *\n * Verbatim the proposals-store posture, and the pid is the same load-bearing detail — a shared\n * temp name would make the rename's atomicity irrelevant, because the bytes being renamed could be\n * half of another process's document.\n */\nfunction writeFileAtomically(path: string, contents: string): void {\n const temp = `${path}.${process.pid}${TEMP_SUFFIX}`\n writeFileSync(temp, contents, 'utf8')\n fsyncFile(temp)\n durableRename(temp, path)\n}\n\n/**\n * Parse one durable record, refusing a foreign schema version by name.\n *\n * The version is checked BEFORE the schema parse even though `DraftReceiptSchema` pins the literal\n * and would refuse it anyway. The difference is the answer a caller gets: a typed\n * `DraftReceiptSchemaVersionError` naming the file and the version it found is actionable, and a\n * generic validation error listing a literal mismatch among other issues is not. Stamp and\n * hard-fail is only useful if the failure says what happened.\n */\nfunction parseReceipt(path: string, raw: unknown): DraftReceipt {\n const version = (raw as { schemaVersion?: unknown } | null)?.schemaVersion\n if (version !== CURRENT_DRAFT_RECEIPT_SCHEMA_VERSION) {\n throw new DraftReceiptSchemaVersionError(path, version)\n }\n return DraftReceiptSchema.parse(raw)\n}\n\nfunction readReceiptIfPresent(path: string): DraftReceipt | undefined {\n let bytes: string\n try {\n bytes = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n return parseReceipt(path, JSON.parse(bytes) as unknown)\n}\n\n/**\n * Bind the three receipt verbs over one agent-qa runtime root.\n *\n * Nothing opens here and nothing is created until the first write, which is what lets a\n * composition root bind this unconditionally without deciding whether a project has ever\n * evaluated a draft — an absent directory and an empty store are the same answer.\n */\nexport function createDraftReceiptsStore(\n options: DraftReceiptsStoreOptions,\n): DraftReceiptsStore {\n async function root(): Promise<string> {\n return await options.resolveAgentQaRoot()\n }\n\n return {\n async put(receipt: DraftReceipt): Promise<void> {\n const agentQaRoot = await root()\n // VALIDATED ON THE WAY OUT, before any syscall. A receipt is read back by a different\n // process — possibly a different build — so the boundary that matters is the file, and a\n // check performed only on read would let a malformed document be written today and\n // discovered by whoever needed it most.\n const validated = DraftReceiptSchema.parse(receipt)\n const path = receiptPath(agentQaRoot, validated.draftRef.contentDigest)\n const directory = draftReceiptsDir(agentQaRoot)\n mkdirSync(directory, { recursive: true })\n writeFileAtomically(path, `${JSON.stringify(validated, undefined, 2)}\\n`)\n fsyncDirectory(directory)\n },\n\n async get(contentDigest: string): Promise<DraftReceipt | undefined> {\n return readReceiptIfPresent(receiptPath(await root(), contentDigest))\n },\n\n async list(): Promise<DraftReceipt[]> {\n const directory = draftReceiptsDir(await root())\n let names: readonly string[]\n try {\n names = readdirSync(directory)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n const receipts: DraftReceipt[] = []\n // DETERMINISTIC ORDER. `readdirSync` order is a filesystem fact that differs between\n // machines and between two calls after a rename, so a listing that inherited it would render\n // two different tables from one store.\n for (const name of [...names].sort()) {\n // An in-flight temp is NOISE, never a receipt: it sits beside a durable name that either\n // is already in this listing or is about to be, and reading half a document would fail the\n // schema parse on a file nobody asked about.\n if (name.endsWith(TEMP_SUFFIX) || !name.endsWith(RECEIPT_SUFFIX)) continue\n const receipt = readReceiptIfPresent(join(directory, name))\n if (receipt !== undefined) receipts.push(receipt)\n }\n return receipts\n },\n }\n}\n","/**\n * D-15 provenance-keyed rollback.\n *\n * Resolution is derived exclusively from canonical bundle files. Disposable records rows are\n * never consulted, so deleting or rebuilding the local index cannot change the affected set.\n * Task 2 attaches the append-only inverse emitter to this resolution authority.\n */\nimport { isAbsolute } from 'node:path'\n\nimport {\n asEvidenceToken,\n asRecordId,\n canonicalJson,\n eventDedupKey,\n sha256hex,\n supersessionKey,\n survivingOutcomeEvents,\n type BundleOutcomeEvent,\n type Delta,\n type OriginClass,\n type RecordId,\n} from '@vostride/agent-qa-schema'\n\nimport { appendOutcomeEvent } from './bundle-append.js'\nimport { deriveBundleTrust, loadBundle } from './bundle-read.js'\nimport type { LoadedBundle } from './bundle-read.js'\nimport type { BundleStoreConfig } from './bundle-publish.js'\nimport { enumerateBundleDirs } from './bundle-scan.js'\nimport { applyIndexDeltaForBundle } from './curator/commit.js'\nimport { AUTHORED_CHECKPOINT_SCHEMA_VERSION } from './curator/author-contract.js'\nimport type { AuthoredDeltaCheckpoint } from './curator/author-contract.js'\nimport { disposeDelta } from './curator/disposition.js'\nimport { refreshWriterLeaseAuthority } from './lease/writer-lease.js'\nimport type { WriterLeaseAuthority } from './lease/writer-lease.js'\n\nexport type RollbackKind = 'job' | 'campaign'\n\nexport interface RollbackCounterEvent {\n recordId: RecordId\n evidenceToken: string\n curationJobId: string\n type: 'confirmed' | 'deprecated' | 'superseded' | 'promoted'\n}\n\nexport type RollbackPlannedEffect =\n | {\n kind: 'deprecate-bundle'\n product: string\n recordId: RecordId\n }\n | {\n kind: 'retract-counter' | 'retract-window-close' | 'retract-promotion'\n product: string\n recordId: RecordId\n eventKey: string\n evidenceToken: string\n curationJobId: string\n }\n\nexport interface RollbackBundleTarget {\n product: string\n recordId: RecordId\n}\n\nexport interface RollbackAffectedSet {\n operationId: string\n /** Compatibility summary; plannedEffects is the product-qualified mutation authority. */\n mintedBundleIds: RecordId[]\n counterEvents: RollbackCounterEvent[]\n plannedEffects: RollbackPlannedEffect[]\n /** Projection healing targets; these never require a new rollback ordinal on their own. */\n projectionTargets: RollbackBundleTarget[]\n products: string[]\n}\n\nexport interface RollbackReport {\n receiptId: string\n inverseCount: number\n restoredVictims: RecordId[]\n deprecatedBundles: RecordId[]\n /** Bundles whose surviving promoted events were cascade-retracted after support loss. */\n retractedPromotions: RecordId[]\n /** Auditable exact resolution that drove inverse construction. */\n affected: RollbackAffectedSet\n}\n\nexport type RollbackMutationKind = 'append' | 'projection'\n\nexport interface RollbackHooks {\n /** Test/chaos seam after canonical resolution and causal preflight, before the first write. */\n afterResolution?: () => void\n /** Test/chaos seam after one actual append or projection mutation completes. */\n afterMutation?: (kind: RollbackMutationKind, recordId: RecordId) => void\n}\n\ninterface RollbackBaseInput {\n knowledgeRoot: string\n resolvedAtOrdinal: number\n /** Governed maintenance callers fence this exact lease at every mutation boundary. */\n writerAuthority?: WriterLeaseAuthority\n /** Preview fingerprint revalidated by the mutator immediately before its first write. */\n expectedAffectedSetFingerprint?: string\n hooks?: RollbackHooks\n}\n\nexport interface RollbackCurationJobInput extends RollbackBaseInput {\n curationJobId: string\n}\n\nexport interface RollbackCampaignInput extends RollbackBaseInput {\n fromOrdinal?: number\n toOrdinal?: number\n anchorClusterKey?: string\n originClass?: OriginClass\n}\n\ninterface CanonicalRollbackBundle {\n recordId: RecordId\n product: string\n dir: string\n bundle: LoadedBundle\n}\n\ninterface ResolvedCounterEvent extends RollbackCounterEvent {\n event: BundleOutcomeEvent\n product: string\n}\n\ninterface ResolvedRetractionEvent {\n recordId: RecordId\n product: string\n event: BundleOutcomeEvent\n effectKind: Extract<\n RollbackPlannedEffect['kind'],\n 'retract-window-close' | 'retract-promotion'\n >\n}\n\ninterface RollbackResolution {\n receiptId: string\n mintedBundles: CanonicalRollbackBundle[]\n counterEvents: ResolvedCounterEvent[]\n windowCloseEvents: ResolvedRetractionEvent[]\n promotionEvents: ResolvedRetractionEvent[]\n projectionTargets: RollbackBundleTarget[]\n affected: RollbackAffectedSet\n}\n\nexport type ResolveRollbackAffectedSetInput =\n | RollbackCurationJobInput\n | RollbackCampaignInput\n\n/**\n * CR-02: a rollback must never attest success at a resolution ordinal that is powerless to\n * change lifecycle status. At equal buildOrdinal the trust fold's fixed STATUS_PRECEDENCE keeps\n * active above deprecated, and an older event can never replace a newer status, so a\n * non-strictly-later resolvedAtOrdinal cannot causally invert a minted bundle.\n */\nexport class RollbackCausalityError extends Error {\n readonly offendingRecordIds: RecordId[]\n readonly minimumRequiredOrdinal: number\n\n constructor(offendingRecordIds: RecordId[], minimumRequiredOrdinal: number) {\n super(\n `rollback resolvedAtOrdinal must be at least ${minimumRequiredOrdinal} `\n + `to invert ${offendingRecordIds.join(', ')}`,\n )\n this.name = 'RollbackCausalityError'\n this.offendingRecordIds = offendingRecordIds\n this.minimumRequiredOrdinal = minimumRequiredOrdinal\n }\n}\n\nexport class RollbackPlanChangedError extends Error {\n override readonly name = 'RollbackPlanChangedError'\n readonly expectedFingerprint: string\n readonly actualFingerprint: string\n\n constructor(expectedFingerprint: string, actualFingerprint: string) {\n super('rollback affected set changed before mutation; rerun to see the new preview')\n this.expectedFingerprint = expectedFingerprint\n this.actualFingerprint = actualFingerprint\n }\n}\n\nconst ORIGIN_CLASSES = new Set<OriginClass>([\n 'user',\n 'agent-verified',\n 'agent-observed',\n 'import',\n])\nconst ANCHOR_CLUSTER_KEY = /^[0-9a-f]{64}$/\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction assertOrdinal(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${label} must be a non-negative safe integer`)\n }\n}\n\nfunction assertBaseInput(input: RollbackBaseInput): void {\n if (!isAbsolute(input.knowledgeRoot)) {\n throw new TypeError('rollback knowledgeRoot must be absolute')\n }\n if (\n input.writerAuthority !== undefined\n && input.writerAuthority.knowledgeRoot !== input.knowledgeRoot\n ) {\n throw new TypeError('rollback writerAuthority must belong to knowledgeRoot')\n }\n assertOrdinal(input.resolvedAtOrdinal, 'rollback resolvedAtOrdinal')\n}\n\nfunction fenceWriterAuthority(input: RollbackBaseInput): void {\n if (input.writerAuthority === undefined) return\n if (input.writerAuthority.knowledgeRoot !== input.knowledgeRoot) {\n throw new TypeError('rollback writerAuthority must belong to knowledgeRoot')\n }\n refreshWriterLeaseAuthority(input.writerAuthority)\n}\n\nfunction campaignKeys(input: RollbackCampaignInput): Readonly<Record<string, unknown>> {\n if (input.fromOrdinal !== undefined) {\n assertOrdinal(input.fromOrdinal, 'rollback fromOrdinal')\n }\n if (input.toOrdinal !== undefined) {\n assertOrdinal(input.toOrdinal, 'rollback toOrdinal')\n }\n if (\n input.fromOrdinal !== undefined\n && input.toOrdinal !== undefined\n && input.fromOrdinal > input.toOrdinal\n ) {\n throw new RangeError('rollback fromOrdinal must be less than or equal to toOrdinal')\n }\n if (\n input.anchorClusterKey !== undefined\n && !ANCHOR_CLUSTER_KEY.test(input.anchorClusterKey)\n ) {\n throw new TypeError('rollback anchorClusterKey must be a canonical 64-hex key')\n }\n if (\n input.originClass !== undefined\n && !ORIGIN_CLASSES.has(input.originClass)\n ) {\n throw new TypeError('rollback originClass is not recognized')\n }\n if (\n input.fromOrdinal === undefined\n && input.toOrdinal === undefined\n && input.anchorClusterKey === undefined\n && input.originClass === undefined\n ) {\n throw new TypeError('rollbackCampaign requires at least one campaign predicate')\n }\n\n return {\n ...(input.fromOrdinal === undefined ? {} : { fromOrdinal: input.fromOrdinal }),\n ...(input.toOrdinal === undefined ? {} : { toOrdinal: input.toOrdinal }),\n ...(input.anchorClusterKey === undefined\n ? {}\n : { anchorClusterKey: input.anchorClusterKey }),\n ...(input.originClass === undefined ? {} : { originClass: input.originClass }),\n }\n}\n\n/** Stable identity for one selector and its product-qualified source-effect universe. */\nexport function rollbackReceiptId(\n kind: RollbackKind,\n keys: Readonly<Record<string, unknown>>,\n effectKeys: readonly string[] = [],\n): string {\n return `rollback:${sha256hex(canonicalJson({\n kind,\n keys,\n effectKeys: [...effectKeys].sort(compareText),\n }))}`\n}\n\nfunction canonicalBundles(knowledgeRoot: string): CanonicalRollbackBundle[] {\n const bundles: CanonicalRollbackBundle[] = []\n for (const entry of enumerateBundleDirs(knowledgeRoot)) {\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded') continue\n bundles.push({\n recordId: asRecordId(loaded.bundle.manifest.id),\n product: entry.product,\n dir: entry.dir,\n bundle: loaded.bundle,\n })\n }\n return bundles\n}\n\nfunction isCounterEvent(\n event: BundleOutcomeEvent,\n): event is BundleOutcomeEvent & { type: RollbackCounterEvent['type'] } {\n return event.type === 'confirmed'\n || event.type === 'deprecated'\n || event.type === 'superseded'\n || event.type === 'promoted'\n}\n\nfunction publicAffectedSet(resolution: RollbackResolution): RollbackAffectedSet {\n return resolution.affected\n}\n\nexport function rollbackAffectedSetFingerprint(affected: RollbackAffectedSet): string {\n return canonicalJson(affected)\n}\n\n/** Resolve the canonical rollback preview without appending inverse events or touching indexes. */\nexport function resolveRollbackAffectedSet(\n input: ResolveRollbackAffectedSetInput,\n): RollbackAffectedSet {\n return publicAffectedSet(\n 'curationJobId' in input\n ? resolveCurationJob(input)\n : resolveCampaign(input),\n )\n}\n\nfunction counterEventsFor(\n bundles: readonly CanonicalRollbackBundle[],\n mintedTargets: ReadonlySet<string>,\n predicate: (bundle: CanonicalRollbackBundle, event: BundleOutcomeEvent) => boolean,\n): ResolvedCounterEvent[] {\n const events: ResolvedCounterEvent[] = []\n for (const bundle of bundles) {\n // A minted bundle is inverted as a whole. Its initial confirmation is part of that Add,\n // Supersede, or MintUnknown effect and must not be independently retracted.\n if (mintedTargets.has(bundleTargetKey(bundle.product, bundle.recordId))) continue\n for (const event of bundle.bundle.events) {\n if (!isCounterEvent(event) || event.curationJobId.startsWith('rollback:')) continue\n if (!predicate(bundle, event)) continue\n events.push({\n recordId: bundle.recordId,\n evidenceToken: event.evidenceToken,\n curationJobId: event.curationJobId,\n type: event.type,\n event,\n product: bundle.product,\n })\n }\n }\n return events.sort((left, right) =>\n compareText(left.product, right.product)\n || compareText(left.recordId, right.recordId)\n || compareText(left.evidenceToken, right.evidenceToken)\n || compareText(left.curationJobId, right.curationJobId)\n || compareText(left.type, right.type),\n )\n}\n\nfunction bundleTargetKey(product: string, recordId: RecordId): string {\n return `${product}\\0${recordId}`\n}\n\nfunction eventEffectKey(\n kind: RollbackPlannedEffect['kind'],\n product: string,\n recordId: RecordId,\n event?: BundleOutcomeEvent,\n): string {\n return canonicalJson({\n kind,\n product,\n recordId,\n ...(event === undefined ? {} : { eventKey: eventDedupKey(event) }),\n })\n}\n\nfunction eventSurvivalKeys(bundle: LoadedBundle): Set<string> {\n return new Set(survivingOutcomeEvents(bundle.events).map(eventDedupKey))\n}\n\nfunction hasExactRetraction(\n bundle: LoadedBundle,\n receiptId: string,\n targetRecordId: RecordId,\n target: BundleOutcomeEvent,\n): boolean {\n const targetKey = eventDedupKey(target)\n const token = inverseEvidenceToken(receiptId, targetRecordId, targetKey)\n return bundle.events.some((event) =>\n event.type === 'retracted'\n && event.evidenceToken === token\n && event.curationJobId === receiptId\n && event.retractsEvidenceToken === target.evidenceToken\n && event.retractsCurationJobId === target.curationJobId,\n )\n}\n\nfunction windowCloseFor(\n bundle: CanonicalRollbackBundle,\n superseded: ResolvedCounterEvent,\n): ResolvedRetractionEvent | undefined {\n const closeToken = asEvidenceToken(sha256hex(canonicalJson({\n token: superseded.evidenceToken,\n event: 'window-close',\n })))\n const event = bundle.bundle.events.find((candidate) =>\n candidate.type === 'window-close'\n && candidate.evidenceToken === closeToken\n && candidate.curationJobId === superseded.curationJobId,\n )\n return event === undefined\n ? undefined\n : {\n recordId: bundle.recordId,\n product: bundle.product,\n event,\n effectKind: 'retract-window-close',\n }\n}\n\nfunction promotionCascadeUniverse(\n bundles: readonly CanonicalRollbackBundle[],\n counters: readonly ResolvedCounterEvent[],\n): ResolvedRetractionEvent[] {\n const selectedConfirmations = new Map<string, Set<string>>()\n const directlySelectedEvents = new Set(counters.map(({ product, recordId, event }) =>\n `${bundleTargetKey(product, recordId)}\\0${eventDedupKey(event)}`,\n ))\n for (const counter of counters) {\n if (counter.type !== 'confirmed') continue\n const key = bundleTargetKey(counter.product, counter.recordId)\n const selected = selectedConfirmations.get(key) ?? new Set<string>()\n selected.add(eventDedupKey(counter.event))\n selectedConfirmations.set(key, selected)\n }\n\n const cascades: ResolvedRetractionEvent[] = []\n for (const bundle of bundles) {\n const selected = selectedConfirmations.get(\n bundleTargetKey(bundle.product, bundle.recordId),\n )\n if (selected === undefined) continue\n const surviving = survivingOutcomeEvents(bundle.bundle.events)\n if (surviving.some((event) =>\n event.type === 'confirmed' && !selected.has(eventDedupKey(event)),\n )) continue\n for (const event of bundle.bundle.events) {\n const selectedEventKey = [\n bundleTargetKey(bundle.product, bundle.recordId),\n eventDedupKey(event),\n ].join('\\0')\n if (event.type !== 'promoted' || directlySelectedEvents.has(selectedEventKey)) continue\n cascades.push({\n recordId: bundle.recordId,\n product: bundle.product,\n event,\n effectKind: 'retract-promotion',\n })\n }\n }\n return cascades.sort((left, right) =>\n compareText(left.product, right.product)\n || compareText(left.recordId, right.recordId)\n || compareText(eventDedupKey(left.event), eventDedupKey(right.event)),\n )\n}\n\nfunction buildResolution(input: {\n kind: RollbackKind\n keys: Readonly<Record<string, unknown>>\n bundles: readonly CanonicalRollbackBundle[]\n mintedUniverse: readonly CanonicalRollbackBundle[]\n counterUniverse: readonly ResolvedCounterEvent[]\n}): RollbackResolution {\n const byTarget = new Map(input.bundles.map((bundle) => [\n bundleTargetKey(bundle.product, bundle.recordId),\n bundle,\n ]))\n const windowCloseUniverse = input.counterUniverse.flatMap((counter) => {\n if (counter.type !== 'superseded') return []\n const bundle = byTarget.get(bundleTargetKey(counter.product, counter.recordId))\n if (bundle === undefined) return []\n const close = windowCloseFor(bundle, counter)\n return close === undefined ? [] : [close]\n })\n const promotionUniverse = promotionCascadeUniverse(input.bundles, input.counterUniverse)\n const operationEffectKeys = [\n ...input.mintedUniverse.map((bundle) =>\n eventEffectKey('deprecate-bundle', bundle.product, bundle.recordId),\n ),\n ...input.counterUniverse.map((counter) =>\n eventEffectKey('retract-counter', counter.product, counter.recordId, counter.event),\n ),\n ...windowCloseUniverse.map((effect) =>\n eventEffectKey(effect.effectKind, effect.product, effect.recordId, effect.event),\n ),\n ...promotionUniverse.map((effect) =>\n eventEffectKey(effect.effectKind, effect.product, effect.recordId, effect.event),\n ),\n ].sort(compareText)\n const receiptId = rollbackReceiptId(input.kind, input.keys, operationEffectKeys)\n const survivingByTarget = new Map(input.bundles.map((bundle) => [\n bundleTargetKey(bundle.product, bundle.recordId),\n eventSurvivalKeys(bundle.bundle),\n ]))\n const mintedHasExactInverse = (bundle: CanonicalRollbackBundle) => {\n const token = inverseEvidenceToken(receiptId, bundle.recordId, 'minted-bundle')\n return bundle.bundle.events.some((event) =>\n event.evidenceToken === token && event.curationJobId === receiptId,\n )\n }\n const mintedBundles = input.mintedUniverse.filter((bundle) =>\n deriveBundleTrust(bundle.bundle).status !== 'deprecated'\n && !mintedHasExactInverse(bundle),\n )\n const hasAppliedRetraction = (\n effect: ResolvedCounterEvent | ResolvedRetractionEvent,\n ): boolean => {\n const bundle = byTarget.get(bundleTargetKey(effect.product, effect.recordId))\n return bundle !== undefined\n && hasExactRetraction(bundle.bundle, receiptId, effect.recordId, effect.event)\n }\n const pending = <T extends ResolvedCounterEvent | ResolvedRetractionEvent>(effect: T) => {\n const bundle = byTarget.get(bundleTargetKey(effect.product, effect.recordId))\n const surviving = survivingByTarget.get(bundleTargetKey(effect.product, effect.recordId))\n return bundle !== undefined\n && surviving?.has(eventDedupKey(effect.event)) === true\n && !hasExactRetraction(bundle.bundle, receiptId, effect.recordId, effect.event)\n }\n const counterEvents = input.counterUniverse.filter(pending)\n const windowCloseEvents = windowCloseUniverse.filter(pending)\n const promotionEvents = promotionUniverse.filter(pending)\n const plannedEffects: RollbackPlannedEffect[] = [\n ...mintedBundles.map(({ product, recordId }) => ({\n kind: 'deprecate-bundle' as const,\n product,\n recordId,\n })),\n ...counterEvents.map((effect) => ({\n kind: 'retract-counter' as const,\n product: effect.product,\n recordId: effect.recordId,\n eventKey: eventDedupKey(effect.event),\n evidenceToken: effect.evidenceToken,\n curationJobId: effect.curationJobId,\n })),\n ...windowCloseEvents.map((effect) => ({\n kind: effect.effectKind,\n product: effect.product,\n recordId: effect.recordId,\n eventKey: eventDedupKey(effect.event),\n evidenceToken: effect.event.evidenceToken,\n curationJobId: effect.event.curationJobId,\n })),\n ...promotionEvents.map((effect) => ({\n kind: effect.effectKind,\n product: effect.product,\n recordId: effect.recordId,\n eventKey: eventDedupKey(effect.event),\n evidenceToken: effect.event.evidenceToken,\n curationJobId: effect.event.curationJobId,\n })),\n ].sort((left, right) => compareText(canonicalJson(left), canonicalJson(right)))\n const projectionTargetMap = new Map<string, RollbackBundleTarget>()\n const includeProjection = (product: string, recordId: RecordId) => {\n projectionTargetMap.set(bundleTargetKey(product, recordId), { product, recordId })\n }\n for (const bundle of input.mintedUniverse) {\n if (mintedBundles.includes(bundle) || mintedHasExactInverse(bundle)) {\n includeProjection(bundle.product, bundle.recordId)\n }\n }\n for (const effect of [\n ...input.counterUniverse,\n ...windowCloseUniverse,\n ...promotionUniverse,\n ]) {\n if (pending(effect) || hasAppliedRetraction(effect)) {\n includeProjection(effect.product, effect.recordId)\n }\n }\n const projectionTargets = [...projectionTargetMap.values()].sort((left, right) =>\n compareText(left.product, right.product) || compareText(left.recordId, right.recordId),\n )\n const products = [...new Set([\n ...plannedEffects.map(({ product }) => product),\n ...projectionTargets.map(({ product }) => product),\n ])].sort(compareText)\n const affected: RollbackAffectedSet = {\n operationId: receiptId,\n mintedBundleIds: mintedBundles.map(({ recordId }) => recordId).sort(compareText),\n counterEvents: counterEvents.map((event) => ({\n recordId: event.recordId,\n evidenceToken: event.evidenceToken,\n curationJobId: event.curationJobId,\n type: event.type,\n })),\n plannedEffects,\n projectionTargets,\n products,\n }\n return {\n receiptId,\n mintedBundles,\n counterEvents,\n windowCloseEvents,\n promotionEvents,\n projectionTargets,\n affected,\n }\n}\n\nfunction resolveCurationJob(input: RollbackCurationJobInput): RollbackResolution {\n assertBaseInput(input)\n if (input.curationJobId.trim() === '') {\n throw new TypeError('rollback curationJobId must be non-empty')\n }\n const bundles = canonicalBundles(input.knowledgeRoot)\n const mintedUniverse = bundles.filter(({ bundle }) =>\n bundle.provenance.mode === 'run-linked'\n && bundle.provenance.curationJobId === input.curationJobId,\n )\n const mintedTargets = new Set(mintedUniverse.map(({ product, recordId }) =>\n bundleTargetKey(product, recordId),\n ))\n return buildResolution({\n kind: 'job',\n keys: { curationJobId: input.curationJobId },\n bundles,\n mintedUniverse,\n counterUniverse: counterEventsFor(\n bundles,\n mintedTargets,\n (_bundle, event) => event.curationJobId === input.curationJobId,\n ),\n })\n}\n\nfunction ordinalMatches(\n ordinal: number,\n input: RollbackCampaignInput,\n): boolean {\n return (input.fromOrdinal === undefined || ordinal >= input.fromOrdinal)\n && (input.toOrdinal === undefined || ordinal <= input.toOrdinal)\n}\n\nfunction bundleAxesMatch(\n bundle: CanonicalRollbackBundle,\n input: RollbackCampaignInput,\n): boolean {\n return (\n input.anchorClusterKey === undefined\n || supersessionKey(bundle.bundle.frontmatter.anchors.map(({ normalized }) => normalized))\n === input.anchorClusterKey\n ) && (\n input.originClass === undefined\n || bundle.bundle.frontmatter.originClass === input.originClass\n )\n}\n\nfunction resolveCampaign(input: RollbackCampaignInput): RollbackResolution {\n assertBaseInput(input)\n const keys = campaignKeys(input)\n const bundles = canonicalBundles(input.knowledgeRoot)\n const mintedUniverse = bundles.filter((bundle) =>\n bundle.bundle.provenance.mode === 'run-linked'\n && bundle.bundle.provenance.sourceBuildOrdinal !== undefined\n && ordinalMatches(bundle.bundle.provenance.sourceBuildOrdinal, input)\n && bundleAxesMatch(bundle, input),\n )\n const mintedTargets = new Set(mintedUniverse.map(({ product, recordId }) =>\n bundleTargetKey(product, recordId),\n ))\n return buildResolution({\n kind: 'campaign',\n keys,\n bundles,\n mintedUniverse,\n counterUniverse: counterEventsFor(\n bundles,\n mintedTargets,\n (bundle, event) => ordinalMatches(event.buildOrdinal, input)\n && bundleAxesMatch(bundle, input),\n ),\n })\n}\n\nfunction bundleConfig(\n input: RollbackBaseInput,\n productKey: string,\n): BundleStoreConfig {\n return {\n knowledgeRoot: input.knowledgeRoot,\n productKey,\n commitArtifacts: 'none',\n ...(input.writerAuthority === undefined\n ? {}\n : { writerLeaseId: input.writerAuthority.leaseId }),\n }\n}\n\n/**\n * Every inverse token binds the receipt, target, and exact effect key. The existing\n * (recordId, evidenceToken, curationJobId) append dedup therefore makes a repeated rollback a\n * byte-level noop while a different selector/effect universe receives a different audit identity.\n */\nfunction inverseEvidenceToken(\n receiptId: string,\n targetRecordId: RecordId,\n retractedKey: string,\n) {\n return asEvidenceToken(sha256hex(canonicalJson({\n rollbackReceiptId: receiptId,\n targetRecordId,\n retractedKey,\n })))\n}\n\nfunction appendedOrThrow(\n outcome: ReturnType<typeof appendOutcomeEvent>,\n targetRecordId: RecordId,\n): boolean {\n switch (outcome.kind) {\n case 'appended':\n return true\n case 'duplicate':\n return false\n case 'not-found':\n throw new Error(`rollback target ${targetRecordId} disappeared during commit`)\n }\n}\n\nfunction appendRollbackEvent(\n input: RollbackBaseInput,\n product: string,\n targetRecordId: RecordId,\n event: BundleOutcomeEvent,\n): boolean {\n fenceWriterAuthority(input)\n const appended = appendedOrThrow(\n appendOutcomeEvent(bundleConfig(input, product), targetRecordId, event),\n targetRecordId,\n )\n if (appended) input.hooks?.afterMutation?.('append', targetRecordId)\n return appended\n}\n\nfunction maintenanceCheckpoint(delta: Delta, targetRecordId: RecordId): AuthoredDeltaCheckpoint {\n const authorship = {\n path: 'deterministic-fallback' as const,\n executionContext: 'local-interactive' as const,\n }\n return {\n schemaVersion: AUTHORED_CHECKPOINT_SCHEMA_VERSION,\n delta,\n neighborIds: [targetRecordId],\n preconditions: [],\n authorship,\n }\n}\n\n/**\n * RATIFICATION / Pitfall 8: inverse Deprecates are mechanical maintenance deltas with origin\n * `system`. They pass the ordinary deterministic disposition floor; `agent` would be downgraded\n * for an active target, while `user` would incorrectly make this lifecycle choice sovereign and\n * permanent. The disposed delta is then emitted through the canonical append + projection tail.\n */\nfunction appendInverseDeprecate(\n input: RollbackBaseInput,\n resolution: RollbackResolution,\n target: CanonicalRollbackBundle,\n): boolean {\n const delta: Extract<Delta, { kind: 'Deprecate' }> = {\n kind: 'Deprecate',\n origin: 'system',\n scope: target.bundle.frontmatter.scope,\n citedIds: [],\n targetId: target.recordId,\n reason: `rollback:${resolution.receiptId}`,\n authorship: {\n path: 'deterministic-fallback',\n executionContext: 'local-interactive',\n },\n }\n const targetAlreadyDeprecated = deriveBundleTrust(target.bundle).status === 'deprecated'\n const disposed = targetAlreadyDeprecated\n ? { kind: 'apply' as const, delta }\n : disposeDelta({\n delta,\n checkpoint: maintenanceCheckpoint(delta, target.recordId),\n profile: { mode: 'drain-to-active' },\n knowledgeRoot: input.knowledgeRoot,\n drainState: { supersedesSeenByAnchorKey: new Map() },\n })\n if (disposed.kind !== 'apply' || disposed.delta.kind !== 'Deprecate') {\n throw new Error(\n `rollback maintenance Deprecate for ${target.recordId} did not pass disposition`,\n )\n }\n\n return appendRollbackEvent(\n input,\n target.product,\n target.recordId,\n {\n type: 'deprecated',\n evidenceToken: inverseEvidenceToken(\n resolution.receiptId,\n target.recordId,\n 'minted-bundle',\n ),\n curationJobId: resolution.receiptId,\n buildOrdinal: input.resolvedAtOrdinal,\n reason: disposed.delta.reason,\n },\n )\n}\n\nfunction appendRetraction(\n input: RollbackBaseInput,\n resolution: RollbackResolution,\n target: ResolvedCounterEvent | ResolvedRetractionEvent,\n): boolean {\n const retractedKey = eventDedupKey(target.event)\n return appendRollbackEvent(\n input,\n target.product,\n target.recordId,\n {\n type: 'retracted',\n evidenceToken: inverseEvidenceToken(\n resolution.receiptId,\n target.recordId,\n retractedKey,\n ),\n curationJobId: resolution.receiptId,\n buildOrdinal: input.resolvedAtOrdinal,\n retractsEvidenceToken: target.event.evidenceToken,\n retractsCurationJobId: target.event.curationJobId,\n rollbackReceiptId: resolution.receiptId,\n },\n )\n}\n\nfunction latestSurvivingLifecycleOrdinal(bundle: LoadedBundle): number {\n let latest = bundle.manifest.createdAtOrdinal\n for (const event of survivingOutcomeEvents(bundle.events)) {\n // Window-close and observation events never derive status, so they cannot gate causality.\n if (\n (event.type === 'promoted' || event.type === 'superseded' || event.type === 'deprecated')\n && event.buildOrdinal > latest\n ) {\n latest = event.buildOrdinal\n }\n }\n return latest\n}\n\n/**\n * Atomic strictly-later causal preflight (CR-02). Runs before ANY append or projection write:\n * every minted bundle in the resolved set must be invertible at input.resolvedAtOrdinal. A\n * bundle is admitted when its surviving fold status is already deprecated (the inverse\n * end-state already holds) or when its log already carries this receipt's exact\n * inverse-deprecate identity (byte replay). Otherwise the resolution must be strictly later\n * than the bundle's latest surviving lifecycle ordinal — at an equal ordinal the fold's fixed\n * status precedence makes the inverse deprecation lose, so success would be a lie. All\n * violators are collected first and reported in one throw; no partial mutation ever precedes it.\n */\nfunction assertCausalResolution(\n input: RollbackBaseInput,\n resolution: RollbackResolution,\n): void {\n const offenders: { recordId: RecordId; latestOrdinal: number }[] = []\n for (const minted of resolution.mintedBundles) {\n if (deriveBundleTrust(minted.bundle).status === 'deprecated') continue\n const inverseToken = inverseEvidenceToken(\n resolution.receiptId,\n minted.recordId,\n 'minted-bundle',\n )\n const alreadyInverted = minted.bundle.events.some((event) =>\n event.evidenceToken === inverseToken\n && event.curationJobId === resolution.receiptId,\n )\n if (alreadyInverted) continue\n const latestOrdinal = latestSurvivingLifecycleOrdinal(minted.bundle)\n if (input.resolvedAtOrdinal > latestOrdinal) continue\n offenders.push({ recordId: minted.recordId, latestOrdinal })\n }\n if (offenders.length === 0) return\n throw new RollbackCausalityError(\n offenders.map(({ recordId }) => recordId).sort(compareText),\n 1 + Math.max(...offenders.map(({ latestOrdinal }) => latestOrdinal)),\n )\n}\n\nfunction emitRollback(\n input: RollbackBaseInput,\n resolution: RollbackResolution,\n resolveAgain: () => RollbackResolution,\n): RollbackReport {\n const initialFingerprint = rollbackAffectedSetFingerprint(resolution.affected)\n if (\n input.expectedAffectedSetFingerprint !== undefined\n && input.expectedAffectedSetFingerprint !== initialFingerprint\n ) {\n throw new RollbackPlanChangedError(\n input.expectedAffectedSetFingerprint,\n initialFingerprint,\n )\n }\n assertCausalResolution(input, resolution)\n input.hooks?.afterResolution?.()\n const revalidated = resolveAgain()\n const revalidatedFingerprint = rollbackAffectedSetFingerprint(revalidated.affected)\n if (revalidatedFingerprint !== initialFingerprint) {\n throw new RollbackPlanChangedError(initialFingerprint, revalidatedFingerprint)\n }\n assertCausalResolution(input, revalidated)\n resolution = revalidated\n\n let inverseCount = 0\n const touched = new Map<string, { recordId: RecordId; product: string }>(\n resolution.projectionTargets.map((target) => [\n bundleTargetKey(target.product, target.recordId),\n target,\n ]),\n )\n const restoredVictims = new Set<RecordId>()\n const retractedPromotions = new Set<RecordId>()\n\n for (const minted of resolution.mintedBundles) {\n if (appendInverseDeprecate(input, resolution, minted)) inverseCount += 1\n touched.set(`${minted.product}\\0${minted.recordId}`, minted)\n }\n\n for (const counter of resolution.counterEvents) {\n if (appendRetraction(\n input,\n resolution,\n counter,\n )) {\n inverseCount += 1\n }\n touched.set(`${counter.product}\\0${counter.recordId}`, counter)\n if (counter.type === 'superseded') restoredVictims.add(counter.recordId)\n }\n\n for (const close of resolution.windowCloseEvents) {\n if (appendRetraction(input, resolution, close)) inverseCount += 1\n touched.set(bundleTargetKey(close.product, close.recordId), close)\n restoredVictims.add(close.recordId)\n }\n\n for (const promoted of resolution.promotionEvents) {\n if (appendRetraction(input, resolution, promoted)) inverseCount += 1\n touched.set(bundleTargetKey(promoted.product, promoted.recordId), promoted)\n retractedPromotions.add(promoted.recordId)\n }\n\n // Re-project every touched bundle even on duplicate replay. This is the same healing property\n // as commitCurationDelta's append-before-index recovery: canonical truth always wins.\n for (const target of [...touched.values()].sort((left, right) =>\n compareText(left.product, right.product) || compareText(left.recordId, right.recordId),\n )) {\n fenceWriterAuthority(input)\n applyIndexDeltaForBundle({\n knowledgeRoot: input.knowledgeRoot,\n bundleId: target.recordId,\n product: target.product,\n })\n input.hooks?.afterMutation?.('projection', target.recordId)\n }\n\n return {\n receiptId: resolution.receiptId,\n inverseCount,\n restoredVictims: [...restoredVictims].sort(compareText),\n deprecatedBundles: resolution.mintedBundles\n .map(({ recordId }) => recordId)\n .sort(compareText),\n retractedPromotions: [...retractedPromotions].sort(compareText),\n affected: publicAffectedSet(resolution),\n }\n}\n\n/** Resolve and append the ratified inverse map for one curation job. */\nexport function rollbackCurationJob(input: RollbackCurationJobInput): RollbackReport {\n return emitRollback(input, resolveCurationJob(input), () => resolveCurationJob(input))\n}\n\n/** Resolve and append the inverse map for an AND-composed provenance campaign. */\nexport function rollbackCampaign(input: RollbackCampaignInput): RollbackReport {\n return emitRollback(input, resolveCampaign(input), () => resolveCampaign(input))\n}\n","// 2026-09-07, 418 D-13/D-14: bundle-local DATA only; no eligibility decisions.\nimport {\n asRecordId, isPromotionReceipt, standingReceiptsByGate, strongestPromotionPath,\n survivingOutcomeEvents, type GateReceipt, type ScopeKey, type TrustPriorTable,\n} from '@vostride/agent-qa-schema'\nimport { deriveBundleTrust, readGateReceipts } from '../bundle-read.js'\nimport { enumerateMaintenanceBundleDirs, loadMaintenanceBundle } from '../maintenance-scan.js'\n\nexport type CanaryPostureFacts = {\n kind: 'found'\n gate1PassOrdinal?: number\n gate1PassDigest?: string\n /** Existing active authority cites this Gate-1 receipt; not admission eligibility. */\n lowerTrustActiveGate1Digest?: string\n latestAttributionOrdinal?: number\n latestGate2Ordinal?: number\n activeInScope: number\n lowerTrustActiveInScope: number\n} | { kind: 'not-found' }\n\nexport interface StandingReceiptDigest {\n candidateId: string\n gate: GateReceipt['gate']\n verdict: GateReceipt['verdict']\n /** Gate 3 is user evidence and has no corpus citation. */\n corpusDigest?: string\n producedAtOrdinal: number\n}\n\nexport interface LowerTrustShare { product: string; active: number; lowerTrust: number }\n\nfunction readBundles(knowledgeRoot: string, resolveTrustPriors?: () => TrustPriorTable | undefined) {\n // Unlike the tolerant catalog listing, this strict walk cannot undercount a cap\n // or publish a clean share when a bundle's committed evidence is unreadable.\n return enumerateMaintenanceBundleDirs(knowledgeRoot).map(entry => {\n const bundle = loadMaintenanceBundle(entry)\n const lines = readGateReceipts(entry.dir, bundle.manifest.id) ?? []\n return { ...entry, bundle, lines, active: deriveBundleTrust(bundle, resolveTrustPriors?.()).status === 'active' }\n })\n}\n\nfunction latest(ordinals: number[]): number | undefined {\n return ordinals.length === 0 ? undefined : Math.max(...ordinals)\n}\n\n// 2026-09-30, 432-10 D-05/D-22: bundle evidence only. The legacy proposal inbox is never read;\n// a contradiction in the standing receipts is held by the promotion gate itself.\nexport function canaryPostureFactsFor(input: {\n knowledgeRoot: string; candidateId: string; scope: ScopeKey\n resolveTrustPriors?: () => TrustPriorTable | undefined\n}): CanaryPostureFacts {\n const id = asRecordId(input.candidateId)\n const rows = readBundles(input.knowledgeRoot, input.resolveTrustPriors)\n const candidate = rows.find(row => row.bundle.manifest.id === id)\n if (candidate === undefined) return { kind: 'not-found' }\n const scope = candidate.bundle.frontmatter.scope\n // The rare-path cap is defined only for the candidate's product-tier scope.\n if (scope.tier !== 'product' || input.scope.tier !== 'product'\n || scope.key !== input.scope.key) return { kind: 'not-found' }\n const receipts = candidate.lines.filter((line): line is GateReceipt => !isPromotionReceipt(line))\n const pass = standingReceiptsByGate(receipts).find(row => row.gate === 1 && row.verdict === 'pass')\n const lowerTrustActiveGate1Digest = candidate.active\n && strongestPromotionPath(candidate.lines) === 'gate1-lower-trust'\n && survivingOutcomeEvents(candidate.bundle.events).some(event => event.type === 'promoted')\n && pass !== undefined\n && candidate.lines.some(line => isPromotionReceipt(line)\n && line.promotionPath === 'gate1-lower-trust'\n && line.citedReceiptDigests.includes(pass.receiptDigest))\n ? pass.receiptDigest : undefined\n const latestAttributionOrdinal = latest(survivingOutcomeEvents(candidate.bundle.events)\n .filter(event => ['confirmed', 'contradicted', 'helpful', 'harmful'].includes(event.type))\n .map(event => event.buildOrdinal))\n const latestGate2Ordinal = latest(receipts.filter(row => row.gate === 2).map(row => row.producedAtOrdinal))\n const active = rows.filter(row => row.active && row.product === candidate.product\n && row.bundle.frontmatter.scope.tier === 'product' && row.bundle.frontmatter.scope.key === scope.key)\n return {\n kind: 'found',\n ...(pass === undefined ? {} : { gate1PassOrdinal: pass.producedAtOrdinal, gate1PassDigest: pass.receiptDigest }),\n ...(lowerTrustActiveGate1Digest === undefined ? {} : { lowerTrustActiveGate1Digest }),\n ...(latestAttributionOrdinal === undefined ? {} : { latestAttributionOrdinal }),\n ...(latestGate2Ordinal === undefined ? {} : { latestGate2Ordinal }),\n activeInScope: active.length,\n lowerTrustActiveInScope: active.filter(row => strongestPromotionPath(row.lines) === 'gate1-lower-trust').length,\n }\n}\n\nexport function standingReceiptDigestsFor(input: { knowledgeRoot: string }): StandingReceiptDigest[] {\n return readBundles(input.knowledgeRoot).flatMap(row => standingReceiptsByGate(\n row.lines.filter((line): line is GateReceipt => !isPromotionReceipt(line)),\n ).map(receipt => ({\n candidateId: receipt.candidateId, gate: receipt.gate, verdict: receipt.verdict,\n ...('corpusVersion' in receipt ? { corpusDigest: receipt.corpusVersion.corpusDigest } : {}),\n producedAtOrdinal: receipt.producedAtOrdinal,\n })))\n}\n\nexport function lowerTrustSharesFor(input: { knowledgeRoot: string; resolveTrustPriors?: () => TrustPriorTable | undefined }): LowerTrustShare[] {\n const products = new Map<string, LowerTrustShare>()\n for (const row of readBundles(input.knowledgeRoot, input.resolveTrustPriors)) {\n const share = products.get(row.product) ?? { product: row.product, active: 0, lowerTrust: 0 }\n products.set(row.product, share)\n if (!row.active) continue\n share.active += 1\n if (strongestPromotionPath(row.lines) === 'gate1-lower-trust') share.lowerTrust += 1\n }\n return [...products.values()]\n}\n","// 2026-09-08, 419 D-02/D-07/D-12: mechanical drafting over recorded data only.\nimport {\n IMPROVEMENT_PLAN_SCHEMA_VERSION,\n ImprovementPlanSchema,\n MARK_QUARANTINE_CLASSES,\n actionDidNotFail,\n asEvidenceToken,\n asRecordId,\n type Anchor,\n type ArtifactRef,\n type BundleDraft,\n type BundleKind,\n type CompletedRunHandoff,\n type Delta,\n type FactSubtype,\n type ImprovementPlan,\n type Mark,\n type MarkQuarantineClass,\n type MarkReceipt,\n type NoDraftableFixChecked,\n type OriginStage,\n type PerTestOutcome,\n type ScopeKey,\n type StepEvidence,\n type VerdictClass,\n} from '@vostride/agent-qa-schema'\nimport { floorProse } from './floor-prose.js'\n\nexport type MarkTriage =\n | { kind: 'quarantined'; class: MarkQuarantineClass; producer: string }\n | { kind: 'learnable'; rootCause?: { class: VerdictClass; producer: string } }\n\nexport function triageMark(member: PerTestOutcome): MarkTriage {\n const root = member.rootCause\n const quarantine = MARK_QUARANTINE_CLASSES.find((value) => value === root?.class)\n if (quarantine !== undefined && root !== undefined) {\n return { kind: 'quarantined', class: quarantine, producer: root.producer }\n }\n return { kind: 'learnable', ...(root === undefined ? {} : {\n rootCause: { class: root.class, producer: root.producer },\n }) }\n}\n\nexport function servedIdsOn(step: StepEvidence): string[] {\n return [...new Set([...step.servedBrief.channel1, ...step.servedBrief.channel3]\n .map((line) => line.id))]\n}\n\nexport function procedureReadOn(member: PerTestOutcome, stepIndex: number): string | undefined {\n return member.steps.filter((step) => step.stepIndex <= stepIndex)\n .flatMap((step) => step.servedBrief.channel2)[0]?.id\n}\n\nexport function assertionDrift(member: PerTestOutcome, step: StepEvidence): boolean {\n // Every sub-action did not fail (actionDidNotFail): a skipped tap sent no input but did not fail.\n return member.rootCause?.class === 'test_bug'\n || (step.verifierVerdict.pass === false\n && step.subActions.every((action) => actionDidNotFail(action.result)))\n}\n\nexport interface ServedRecordFacts {\n recordId: string\n kind: BundleKind\n subtype?: FactSubtype\n anchors: Anchor[]\n scope: ScopeKey\n summary: string\n distilledEvidenceRef: ArtifactRef\n originStage: OriginStage\n}\n\nexport type FixSelection =\n | { fix: 'fact' | 'caution'; target: ServedRecordFacts }\n | { fix: 'procedure-hint'; target: ServedRecordFacts }\n | { fix: 'test-edit' }\n | { fix: 'none'; checked: NoDraftableFixChecked }\n\nexport function selectFixKind(input: {\n kind: Mark\n member: PerTestOutcome\n step: StepEvidence\n stepIndex: number\n served: ServedRecordFacts[]\n procedure?: ServedRecordFacts\n}): FixSelection {\n if (input.kind === 'confirmed-bug') throw new TypeError('confirmed-bug has no drafted fix')\n const target = input.served[0]\n if (target !== undefined && input.kind === 'false-fail'\n && (target.kind !== 'fact' || target.subtype === undefined)) {\n // A recorded caution/unknown does not establish any fact subtype. Do not offer\n // a broad draft that the actual kind-specific commit contract cannot accept.\n return { fix: 'none', checked: { servedRecords: input.served.length,\n procedureReads: input.procedure === undefined ? 0 : 1,\n assertionDrift: assertionDrift(input.member, input.step),\n ...(input.member.rootCause === undefined ? {} : { rootCause: input.member.rootCause.class }),\n } }\n }\n if (target !== undefined) return { fix: input.kind === 'false-fail' ? 'fact' : 'caution', target }\n if (input.procedure !== undefined) return { fix: 'procedure-hint', target: input.procedure }\n if (assertionDrift(input.member, input.step)) return { fix: 'test-edit' }\n return { fix: 'none', checked: {\n servedRecords: input.served.length, procedureReads: 0, assertionDrift: false,\n ...(input.member.rootCause === undefined ? {} : { rootCause: input.member.rootCause.class }),\n } }\n}\n\nexport interface ApplyFeedbackInput {\n mark: Pick<MarkReceipt, 'markId' | 'runId' | 'runSlug' | 'testIndex' | 'testId' | 'stepIndex' | 'kind' | 'note'>\n handoff: CompletedRunHandoff\n resolvedStepIndex: number\n served: ServedRecordFacts[]\n procedure?: ServedRecordFacts\n testRef?: string\n}\n\nexport function applyFeedback(input: ApplyFeedbackInput): ImprovementPlan {\n const { mark } = input\n const members = input.handoff.tests.filter((member) => member.testIndex === mark.testIndex)\n const member = members[0]\n if (input.handoff.runId !== mark.runId || members.length !== 1 || member === undefined\n || (mark.testId !== undefined && mark.testId !== member.testId)) {\n throw new TypeError('mark does not address the supplied handoff member')\n }\n const steps = member.steps.filter((step) => step.stepIndex === input.resolvedStepIndex)\n const step = steps[0]\n if (steps.length !== 1 || step === undefined\n || (mark.stepIndex !== undefined && mark.stepIndex !== step.stepIndex)) {\n throw new TypeError('mark does not address the supplied step')\n }\n if (triageMark(member).kind === 'quarantined') throw new TypeError('quarantined marks cannot draft')\n const selection = selectFixKind({ ...input, kind: mark.kind, member, step,\n stepIndex: input.resolvedStepIndex })\n const base = {\n schemaVersion: IMPROVEMENT_PLAN_SCHEMA_VERSION, markId: mark.markId,\n feedbackSource: { runId: mark.runId, testIndex: mark.testIndex, kind: mark.kind,\n ...(mark.testId === undefined ? {} : { testId: mark.testId }),\n ...(mark.stepIndex === undefined ? {} : { stepIndex: mark.stepIndex }) },\n runTraceRef: { runId: mark.runId, runSlug: mark.runSlug },\n }\n if (selection.fix === 'none') {\n return ImprovementPlanSchema.parse({ ...base, kind: 'no-draftable-fix', checked: selection.checked })\n }\n if (selection.fix === 'test-edit') {\n const testRef = input.testRef || (member.filePath && member.testName\n ? `${member.filePath}::${member.testName}` : undefined)\n if (testRef === undefined) {\n // The closed checked contract records drift but cannot carry an address-missing reason.\n return ImprovementPlanSchema.parse({ ...base, kind: 'no-draftable-fix', checked: {\n servedRecords: 0, procedureReads: 0, assertionDrift: true,\n ...(member.rootCause === undefined ? {} : { rootCause: member.rootCause.class }),\n } })\n }\n return ImprovementPlanSchema.parse({ ...base, kind: 'test-edit', fix: 'test-edit', testRef,\n intent: floorProse({ kind: mark.kind, fix: 'fact', stepText: step.stepText,\n verifierReasoning: step.verifierVerdict.reasoning, note: mark.note }).body, wording: 'floor' })\n }\n const target = selection.target\n const prose = floorProse({ kind: mark.kind, fix: selection.fix, stepText: step.stepText,\n verifierReasoning: step.verifierVerdict.reasoning, servedSummary: target.summary, note: mark.note })\n const bundle: BundleDraft = {\n kind: selection.fix === 'caution' ? 'caution' : 'fact',\n ...(selection.fix === 'procedure-hint' ? { subtype: 'navigational' as const }\n : selection.fix === 'fact' && target.subtype !== undefined ? { subtype: target.subtype } : {}),\n anchors: target.anchors, scope: target.scope, ...prose,\n distilledEvidenceRef: step.subActions.find((action) => action.decisionScreenshotRef !== undefined)\n ?.decisionScreenshotRef ?? target.distilledEvidenceRef,\n // OriginStage is closed to run-curation; user authorship lives on the delta envelope.\n originStage: target.originStage,\n }\n const envelope = { origin: 'user' as const, scope: target.scope, citedIds: [asRecordId(target.recordId)] }\n const delta: Delta = selection.fix === 'fact'\n ? { ...envelope, kind: 'Supersede', victimId: asRecordId(target.recordId), newBundle: bundle,\n evidenceToken: asEvidenceToken(`mark:${mark.markId}`) }\n : { ...envelope, kind: 'Add', bundle }\n return ImprovementPlanSchema.parse({ ...base, kind: 'knowledge', fix: selection.fix,\n target: { grain: 'record', recordId: target.recordId }, deltas: [delta], wording: 'floor' })\n}\n","// §7.9 floor law: this blunter prose ships on a no-model host and is the fallback\n// for every failed wording call. Producer text stays text; renderers own masking.\nimport type { Mark } from '@vostride/agent-qa-schema'\n\nexport interface FloorProseInput {\n kind: Mark\n fix: 'fact' | 'caution' | 'procedure-hint'\n stepText: string\n verifierReasoning: string\n servedSummary?: string\n note?: string\n}\n\nfunction bounded(text: string, limit: number): string {\n if (text.length <= limit) return text\n const prefix = text.slice(0, limit - 1)\n const boundary = prefix.search(/\\s+\\S*$/)\n return `${(boundary > 0 ? prefix.slice(0, boundary) : prefix).trimEnd()}…`\n}\n\nexport function floorProse(input: FloorProseInput): { summary: string; body: string } {\n const { kind, fix, stepText, verifierReasoning, servedSummary } = input\n const reading = kind === 'confirmed-bug' ? 'Confirmed' : 'Overturned'\n const claim = servedSummary === undefined ? '' : `\\nSuperseded claim: ${servedSummary}`\n let summary: string\n if (fix === 'procedure-hint') {\n summary = `Path to \"${stepText}\": ${servedSummary ?? 'review the recorded route'}`\n } else if (kind === 'false-pass') {\n summary = `\"${stepText}\" is not done when ${verifierReasoning.split(/[.;\\n]/)[0]}`\n } else if (kind === 'false-fail') {\n summary = `On \"${stepText}\", the observed state is the expected outcome`\n } else {\n summary = `On \"${stepText}\", the observed failure is confirmed`\n }\n const body = `${kind} / ${fix}: ${stepText}\\n${reading} verifier reading: ${verifierReasoning}${claim}`\n // Reserve space for the final user-note line, even when the recorded reading is long.\n const note = input.note === undefined ? '' : bounded(`User note: ${input.note}`, 1100)\n return {\n summary: bounded(summary, 160),\n body: note === '' ? bounded(body, 1200)\n : `${bounded(body, 1200 - note.length - 1)}\\n${note}`,\n }\n}\n","// 2026-09-08, 419 D-04/D-09/D-10: append evidence under the caller's authority.\n// 2026-09-15, 423 D-16: executes the shared read-only plan; only the append half stays here.\nimport { asRecordId, type CompletedRunHandoff, type ExecutionContext, type MarkReceipt } from '@vostride/agent-qa-schema'\nimport { appendOutcomeEvent } from '../bundle-append.js'\nimport type { BundleStoreConfig } from '../bundle-publish.js'\nimport { withCurrentWriterAuthority } from '../lease/writer-lease.js'\nimport { markEvidenceEvent, planMarkEvidence, type AppendMarkEvidenceOutcome } from './mark-evidence-plan.js'\n\nexport { MARK_EVIDENCE_TOKEN_PREFIX, type AppendMarkEvidenceOutcome } from './mark-evidence-plan.js'\n\nexport interface AppendMarkEvidenceInput {\n knowledgeRoot: string\n executionContext: ExecutionContext\n lease: { leaseId: string; epoch: number }\n mark: Pick<MarkReceipt, 'markId' | 'runId' | 'kind'>\n servedRecordIds: readonly string[]\n /** Historical observation hashes require the original member/step coordinates. */\n handoff?: CompletedRunHandoff\n /** Host-derived chainJobIdsForRun(runId, idSource).curateMemory; never guessed here. */\n curationJobIds?: readonly string[]\n /** Resuming one mark reports its complete logical effect, including already durable events. */\n includeAlreadyAppended?: boolean\n}\n\nexport async function appendMarkEvidence(input: AppendMarkEvidenceInput): Promise<AppendMarkEvidenceOutcome> {\n if (input.handoff !== undefined && input.handoff.runId !== input.mark.runId) {\n throw new TypeError('mark evidence handoff belongs to another run')\n }\n return withCurrentWriterAuthority(input.knowledgeRoot, input.lease, () => {\n // Plan under the lease so the appended effects are the ones the current bundles support.\n const plan = planMarkEvidence({ knowledgeRoot: input.knowledgeRoot,\n mark: { runId: input.mark.runId, kind: input.mark.kind }, servedRecordIds: input.servedRecordIds,\n ...(input.handoff === undefined ? {} : { handoff: input.handoff }),\n ...(input.curationJobIds === undefined ? {} : { curationJobIds: input.curationJobIds }) })\n const result: AppendMarkEvidenceOutcome = { confirmed: 0, overturned: 0, skipped: [],\n ...(plan.correlationIncomplete === true ? { correlationIncomplete: true as const } : {}) }\n for (const target of plan.targets) {\n if (target.kind === 'unreadable') {\n result.skipped.push({ recordId: target.recordId, reason: 'bundle-unreadable' })\n continue\n }\n const config: BundleStoreConfig = { knowledgeRoot: input.knowledgeRoot, productKey: target.productKey,\n commitArtifacts: 'none', writerLeaseId: input.lease.leaseId, writerEpoch: input.lease.epoch }\n let changed = false\n for (const effect of target.effects) {\n const outcome = appendOutcomeEvent(config, asRecordId(target.recordId),\n markEvidenceEvent(effect, input.mark.markId, target.buildOrdinal))\n // Do not misreport a lost target as a successful mark.\n if (outcome.kind !== 'appended' && outcome.kind !== 'duplicate') {\n throw new Error(`mark evidence append refused: ${outcome.kind}`)\n }\n if (outcome.kind === 'duplicate' && input.includeAlreadyAppended !== true) continue\n if (effect.direction === 'confirm') result.confirmed += 1\n else result.overturned += 1\n changed = true\n }\n if (!changed) result.skipped.push({ recordId: target.recordId, reason: 'already-appended' })\n }\n return result\n })\n}\n","// 2026-09-15, 423 D-16: the read/planning half of mark evidence. No lease, append or markId mint.\nimport { basename } from 'node:path'\nimport { asEvidenceToken, asRecordId, deriveEvidenceToken, eventDedupKey, exercisedAnchors, isPromotionReceipt,\n type BundleOutcomeEvent, type CompletedRunHandoff, type EvidenceToken, type MarkReceipt } from '@vostride/agent-qa-schema'\nimport { loadBundle, readGateReceipts, verifyBundleIntegrity } from '../bundle-read.js'\nimport { BundleTargetResolutionError, enumerateBundleDirs, resolveProductQualifiedBundleDir } from '../bundle-scan.js'\nimport { canaryOutcomeObservationId } from '../serving/canary-observation-id.js'\n\nexport const MARK_EVIDENCE_TOKEN_PREFIX = 'mark:'\n\nexport interface PlanMarkEvidenceInput {\n knowledgeRoot: string\n /** markId is optional: a preview plans ephemeral effects; a resumed writer supplies it to see durable ones. */\n mark: Pick<MarkReceipt, 'runId' | 'kind'> & { markId?: string }\n servedRecordIds: readonly string[]\n /** Historical observation hashes require the original member/step coordinates. */\n handoff?: CompletedRunHandoff\n /** Host-derived chainJobIdsForRun(runId, idSource).curateMemory; never guessed here. */\n curationJobIds?: readonly string[]\n}\n\nexport type MarkEvidenceEffect =\n | { direction: 'confirm'; alreadyAppended: boolean }\n | { direction: 'overturn'; overturnsEvidenceToken: EvidenceToken; overturnsCurationJobId: string;\n alreadyAppended: boolean }\n\nexport type MarkEvidenceTarget =\n | { recordId: string; kind: 'unreadable' }\n | { recordId: string; kind: 'effects'; productKey: string; served: boolean; buildOrdinal: number;\n effects: MarkEvidenceEffect[] }\n\nexport interface MarkEvidencePlan {\n targets: MarkEvidenceTarget[]\n /** Without the handoff, opaque historical canary hashes cannot all be correlated. */\n correlationIncomplete?: true\n}\n\nexport type AppendMarkEvidenceOutcome = {\n confirmed: number\n overturned: number\n skipped: { recordId: string; reason: 'bundle-unreadable' | 'already-appended' }[]\n /** Without the handoff, opaque historical canary hashes cannot all be correlated. */\n correlationIncomplete?: true\n}\n\nexport function markEvidenceEvent(effect: MarkEvidenceEffect, markId: string, buildOrdinal: number): BundleOutcomeEvent {\n const token = `${MARK_EVIDENCE_TOKEN_PREFIX}${markId}`\n if (effect.direction === 'confirm') {\n return { type: 'confirmed', evidenceToken: asEvidenceToken(token), curationJobId: token, buildOrdinal, origin: 'user' }\n }\n // Include BOTH target identity fields: the same token may name two distinct jobs.\n return { type: 'overturned', markId, evidenceToken: asEvidenceToken(\n `${token}:${effect.overturnsEvidenceToken}:${effect.overturnsCurationJobId}`),\n curationJobId: token, buildOrdinal, overturnsEvidenceToken: effect.overturnsEvidenceToken,\n overturnsCurationJobId: effect.overturnsCurationJobId }\n}\n\nexport function planMarkEvidence(input: PlanMarkEvidenceInput): MarkEvidencePlan {\n if (input.handoff !== undefined && input.handoff.runId !== input.mark.runId) {\n throw new TypeError('mark evidence handoff belongs to another run')\n }\n const plan: MarkEvidencePlan = { targets: [],\n ...(input.mark.kind === 'false-pass' && input.handoff === undefined ? { correlationIncomplete: true as const } : {}) }\n const served = new Set(input.servedRecordIds)\n const targets = new Set([...served, ...(input.mark.kind === 'false-pass'\n ? enumerateBundleDirs(input.knowledgeRoot).map(entry => basename(entry.dir)) : [])])\n for (const recordId of targets) {\n let entry\n try {\n entry = resolveProductQualifiedBundleDir({ knowledgeRoot: input.knowledgeRoot, recordId })\n } catch (error) {\n if (!(error instanceof BundleTargetResolutionError)) throw error\n plan.targets.push({ recordId, kind: 'unreadable' })\n continue\n }\n const loaded = loadBundle(entry.dir)\n if (loaded.kind !== 'loaded' || !verifyBundleIntegrity(entry.dir).ok) {\n plan.targets.push({ recordId, kind: 'unreadable' })\n continue\n }\n const bundle = loaded.bundle\n const observations = new Set<string>()\n const evidenceTokens = new Set<string>()\n const bundleAnchors = bundle.frontmatter.anchors.map(({ raw }) => raw)\n for (const member of input.handoff?.tests ?? []) {\n for (const step of member.steps) {\n const canaryId = canaryOutcomeObservationId({ candidateId: asRecordId(recordId),\n runId: input.mark.runId, testId: member.testId, testIndex: member.testIndex,\n stepIndex: step.stepIndex })\n observations.add(canaryId)\n // The deterministic emitter's persisted observation address (emit-candidates.ts).\n observations.add(`${input.mark.runId}:test-${member.testIndex}:step-${step.stepIndex}`)\n // Positive canary Confirm goes through the knowledge-port bridge, which changes\n // observationId but preserves this canonical run/anchor/build evidence token.\n for (const anchor of [...bundleAnchors, ...exercisedAnchors(step)]) {\n evidenceTokens.add(deriveEvidenceToken({ attributingObservationId: canaryId,\n anchor, buildOrdinal: input.handoff!.buildOrdinal }))\n }\n }\n }\n // Gate-2 receipts preserve run + observation identity even when the handoff is gone.\n for (const receipt of readGateReceipts(entry.dir, asRecordId(recordId)) ?? []) {\n if (!isPromotionReceipt(receipt) && receipt.gate === 2 && receipt.runId === input.mark.runId) {\n observations.add(receipt.attributedObservationId)\n for (const anchor of bundleAnchors) {\n evidenceTokens.add(deriveEvidenceToken({ attributingObservationId: receipt.attributedObservationId,\n anchor, buildOrdinal: receipt.producedAtOrdinal }))\n }\n }\n }\n const jobs = new Set(input.curationJobIds ?? [])\n const provenance = bundle.provenance\n if (provenance.mode === 'run-linked' && provenance.runId === input.mark.runId\n && provenance.curationJobId !== undefined) jobs.add(provenance.curationJobId)\n const hits = bundle.events.filter((event) => (event.type === 'helpful' || event.type === 'confirmed')\n && ((event.observationId !== undefined && observations.has(event.observationId))\n || evidenceTokens.has(event.evidenceToken) || jobs.has(event.curationJobId)))\n if (!served.has(recordId) && hits.length === 0) continue\n const buildOrdinal = Math.max(bundle.manifest.createdAtOrdinal,\n ...bundle.events.map((event) => event.buildOrdinal)) + 1\n // Mirror the append-time dedup key sequence. Durable log keys only matter for a known markId;\n // collisions inside one plan do not depend on the id, so a preview uses an empty stand-in.\n const seen = new Set(input.mark.markId === undefined ? [] : bundle.events.map(eventDedupKey))\n const effects: MarkEvidenceEffect[] = []\n const add = (effect: MarkEvidenceEffect) => {\n const key = eventDedupKey(markEvidenceEvent(effect, input.mark.markId ?? '', buildOrdinal))\n effects.push({ ...effect, alreadyAppended: seen.has(key) })\n seen.add(key)\n }\n if (served.has(recordId)) add({ direction: 'confirm', alreadyAppended: false })\n if (input.mark.kind === 'false-pass') {\n for (const hit of hits) {\n add({ direction: 'overturn', overturnsEvidenceToken: hit.evidenceToken,\n overturnsCurationJobId: hit.curationJobId, alreadyAppended: false })\n }\n }\n plan.targets.push({ recordId, kind: 'effects', productKey: entry.product, served: served.has(recordId),\n buildOrdinal, effects })\n }\n return plan\n}\n\n/** The outcome an append executing this plan reports, with duplicates counted only on resume. */\nexport function projectMarkEvidenceOutcome(plan: MarkEvidencePlan,\n options: { includeAlreadyAppended: boolean }): AppendMarkEvidenceOutcome {\n const result: AppendMarkEvidenceOutcome = { confirmed: 0, overturned: 0, skipped: [],\n ...(plan.correlationIncomplete === true ? { correlationIncomplete: true as const } : {}) }\n for (const target of plan.targets) {\n if (target.kind === 'unreadable') {\n result.skipped.push({ recordId: target.recordId, reason: 'bundle-unreadable' })\n continue\n }\n let changed = false\n for (const effect of target.effects) {\n if (effect.alreadyAppended && !options.includeAlreadyAppended) continue\n if (effect.direction === 'confirm') result.confirmed += 1\n else result.overturned += 1\n changed = true\n }\n if (!changed) result.skipped.push({ recordId: target.recordId, reason: 'already-appended' })\n }\n return result\n}\n"],"mappings":";AAAA;AAAA,EACE,iBAAAA;AAAA,EAAe;AAAA,EAA4B;AAAA,EAAkC;AAAA,EAC7E;AAAA,EAA8B,gCAAAC;AAAA,EAA8B,0BAAAC;AAAA,OAEvD;;;ACJP,SAAS,mBAAmB;AAC5B,SAAS,QAAAC,aAAY;;;ACIrB,SAAS,kBAAkB;AAC3B,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,UAAU,YAAY;AAE/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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;AAAA,QAAC;AAEnE,YAAI,QAAQ,SAAS,cAAc,QAAQ,SAAS,aAAa;AAC/D,gBAAM,IAAI,MAAM,iCAAiC,QAAQ,IAAI,EAAE;AAAA,QACjE;AACA,YAAI,QAAQ,SAAS,eAAe,MAAM,2BAA2B,KAAM;AAC3E,YAAI,OAAO,cAAc,UAAW,QAAO,aAAa;AAAA,YACnD,QAAO,cAAc;AAC1B,kBAAU;AAAA,MACZ;AACA,UAAI,CAAC,QAAS,QAAO,QAAQ,KAAK,EAAE,UAAU,OAAO,UAAU,QAAQ,mBAAmB,CAAC;AAAA,IAC7F;AACA,WAAO;AAAA,EACT,CAAC;AACH;","names":["canonicalJson","RECORD_CHANGE_SCHEMA_VERSION","survivingOutcomeEvents","join","bundleDir","relations","primaryAnchor","mutableStateHash","join","randomUUID","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","readdirSync","renameSync","rmSync","writeFileSync","dirname","isAbsolute","join","canonicalJson","z","readdirSync","join","join","part","closeSync","existsSync","fsyncSync","lstatSync","openSync","readdirSync","readFileSync","renameSync","basename","dirname","isAbsolute","join","basename","isAbsolute","join","openSync","fsyncSync","closeSync","readFileSync","current","readdirSync","existsSync","dirname","renameSync","errnoOf","lstatSync","error","readdirSync","basename","join","canonicalJson","readdirSync","join","bundleDir","canonicalJson","basename","z","canonicalJson","isAbsolute","join","readdirSync","readFileSync","dirname","existsSync","mkdirSync","randomUUID","openSync","writeFileSync","fsyncSync","closeSync","renameSync","rmSync","readFileSync","readdirSync","join","VersionGuardError","z","compareText","join","readdirSync","readFileSync","survivingOutcomeEvents","RECORD_CHANGE_SCHEMA_VERSION","canonicalJson","latest","randomUUID","mkdirSync","rmSync","join","z","canonicalJson","sha256hex","z","closeSync","existsSync","fsyncSync","mkdirSync","openSync","renameSync","rmdirSync","writeFileSync","dirname","isAbsolute","join","assertAbsoluteKnowledgeRoot","bestEffortFsyncDirectory","z","digest","sha256hex","canonicalJson","join","randomUUID","mkdirSync","bestEffortFsyncDirectory","rmSync","mkdirSync","dirname","DatabaseSync","mkdirSync","dirname","join","DatabaseSync","DEFAULT_EMBEDDING_PROFILE","existsSync","mkdirSync","dirname","join","DatabaseSync","canonicalJson","join","existsSync","DatabaseSync","canonicalJson","dirname","mkdirSync","isSlugAddressedKind","part","SCHEMA_STATEMENTS","join","toNumber","dirname","mkdirSync","DatabaseSync","immediateTransaction","DEFAULT_EMBEDDING_PROFILE","immediateTransaction","toNumber","asRecordId","canonicalJson","supersessionKey","existsSync","statSync","basename","join","canonicalJson","normalizeAnchor","randomUUID","existsSync","mkdirSync","readFileSync","renameSync","rmSync","writeFileSync","dirname","join","z","z","join","dirname","mkdirSync","existsSync","request","randomUUID","writeFileSync","renameSync","rmSync","readFileSync","existsSync","readFileSync","basename","dirname","join","canonicalJson","isPromotionReceipt","survivingOutcomeEvents","supersessionKey","normalizeAnchor","survivingOutcomeEvents","latest","survivingOutcomeEvents","normalizeAnchor","bundleDir","join","existsSync","readFileSync","supersessionKey","canonicalJson","candidate","survivingOutcomeEvents","basename","dirname","isPromotionReceipt","createHash","canonicalJson","guardTrustPriorTable","digest","errorMessage","basename","join","bundleDir","candidate","normalizeAnchor","denseVec0","queryBlob","denseBrute","canonicalJson","reader","existsSync","statSync","canonicalJson","normalizeAnchor","normalizeAnchor","canonicalJson","normalizeAnchor","canonicalJson","compareText","candidate","candidate","canonicalJson","normalizeAnchor","dirname","DEFAULT_EMBEDDING_PROFILE","STATIC_FLOOR_EMBEDDING_PROFILE","createHash","resolve","embed","createHash","existsSync","readFileSync","statSync","dirname","join","errorMessage","sep","join","sep","embed","randomUUID","createHash","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","realpathSync","renameSync","rmSync","unlinkSync","writeFileSync","basename","dirname","join","z","bestEffortFsyncDirectory","openSync","fsyncSync","closeSync","atomicRewrite","dirname","mkdirSync","randomUUID","writeFileSync","renameSync","rmSync","readFileSync","existsSync","fsyncDirectory","unlinkSync","envelope","z","candidate","dirname","STATIC_FLOOR_EMBEDDING_PROFILE","DEFAULT_EMBEDDING_PROFILE","MAX_SQL_LIMIT","queryLimit","compareBundleIds","float32View","cosineDistance","candidate","canonicalJson","normalizeAnchor","supersessionKey","compareBundleIds","supersessionKey","count","supersessionKey","readFileSync","join","isRecord","latest","candidate","supersessionKey","MAX_SQL_LIMIT","compareText","canonicalJson","candidate","supersessionKey","asRecordId","anchorMatches","anchor","candidate","sighting","relative","relative","mkdirSync","readFileSync","join","canonicalJson","join","readFileSync","canonicalJson","mkdirSync","CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION","CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION","CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION","QUARANTINE_UNASSIGNED_OWNER","MS_PER_DAY","QUARANTINE_UNASSIGNED_OWNER","CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION","createHash","existsSync","mkdirSync","readFileSync","writeFileSync","join","byteSha","createHash","canonicalJson","computeMutableStateHash","normalizeAnchor","renderEmbeddingInput","draft","discriminant","originClass","primaryAnchor","relations","randomUUID","existsSync","mkdirSync","readFileSync","rmdirSync","rmSync","writeFileSync","dirname","isAbsolute","join","canonicalJson","guardBundleManifest","slugBranch","verifyManifestIdentity","guardBundleManifest","readFileSync","join","verifyManifestIdentity","canonicalJson","rmdirSync","rmSync","existsSync","part","mkdirSync","dirname","writeFileSync","isAbsolute","slugBranch","randomUUID","createHash","existsSync","readFileSync","isAbsolute","join","BUNDLE_SCHEMA_VERSION","BundleOutcomeEventSchema","isPromotionReceipt","receiptDigestOf","canonicalJson","committedFileText","computeMutableStateHash","emitRecordMarkdown","guardBundleManifest","guardBundleProvenance","guardBundleRelations","measurementBaselineSchema","measurementObservationSchema","parseRecordMarkdown","renderEmbeddingInput","slugBranch","createHash","randomUUID","existsSync","mkdirSync","readFileSync","readdirSync","rmdirSync","rmSync","writeFileSync","basename","dirname","isAbsolute","join","relative","resolve","sep","canonicalJson","slugBranch","z","z","createHash","candidate","relative","resolve","sep","isAbsolute","bundleDir","slugBranch","basename","join","dirname","readFileSync","canonicalJson","readdirSync","randomUUID","writeFileSync","existsSync","rmSync","removeEmptyStagingRoot","rmdirSync","mkdirSync","receiptDigestOf","join","existsSync","readFileSync","canonicalJson","isPromotionReceipt","OUTCOMES_REL_PATH","MEASUREMENTS_REL_PATH","RELATIONS_REL_PATH","ARTIFACTS_INDEX_REL_PATH","textSha","createHash","isAbsolute","slugBranch","guardBundleManifest","computeMutableStateHash","committedFileText","parseOutcomeLog","BundleOutcomeEventSchema","candidate","measurementBaselineSchema","measurementObservationSchema","guardBundleProvenance","parseRecordMarkdown","emitRecordMarkdown","renderEmbeddingInput","guardBundleRelations","BUNDLE_SCHEMA_VERSION","basename","basename","existsSync","basename","asRecordId","canonicalJson","isVettedCandidate","normalizeAnchor","slugBranch","strongestPromotionPath","canonicalJson","createServingAdmissionState","normalizeAnchor","servingRecordMetadata","tryAdmitServingRecord","isVettedCandidate","normalizeAnchor","normalizeAnchor","candidate","isVettedCandidate","validityClass","originClass","canonicalJson","normalizeAnchor","createServingAdmissionState","candidate","servingRecordMetadata","tryAdmitServingRecord","canonicalJson","normalizeAnchor","survivingOutcomeEvents","normalizedAnchorKey","candidate","servingRecordMetadata","compareRecordId","rendered","servingRecordMetadata","readFileSync","join","slugBranch","CHARS_PER_TOKEN_ESTIMATE","compareText","normalizedRecordCap","slugBranch","existsSync","basename","isVettedCandidate","strongestPromotionPath","asRecordId","normalizedAnchorKey","canonicalJson","normalizeAnchor","anchorMatches","overlapsRange","auditMode","candidate","openKnowledgeReader","existsSync","identityTupleKey","normalizeAnchor","slugBranch","asRecordId","canonicalJson","createServingAdmissionState","EMPTY_PROCEDURE_BINDING_AVAILABILITY","normalizeAnchor","servingRecordMetadata","tryAdmitServingRecord","normalizedAnchorKey","canonicalJson","normalizeAnchor","compareText","lexicalRelevance","EMPTY_PROCEDURE_BINDING_AVAILABILITY","part","candidate","servingRecordMetadata","asRecordId","createServingAdmissionState","tryAdmitServingRecord","identityTupleKey","existsSync","slugBranch","normalizeAnchor","candidate","DEFAULT_EMBEDDING_PROFILE","DEFAULT_EMBEDDING_PROFILE","existsSync","readFileSync","basename","join","anchorGraphNode","canonicalJson","guardDistilledObservation","guardTrustPriorTable","recordGraphNode","compareCandidates","compareText","errorMessage","canonicalJson","node","digest","recordGraphNode","anchorGraphNode","guardTrustPriorTable","bundleDir","basename","join","existsSync","readFileSync","guardDistilledObservation","readFileSync","readdirSync","join","canonicalJson","normalizeAnchor","slugBranch","statSync","parseLastOutcomes","slugBranch","canonicalJson","normalizeAnchor","readFileSync","join","readdirSync","rmSync","isAbsolute","asRecordId","survivingOutcomeEvents","compareText","isAbsolute","asRecordId","latest","survivingOutcomeEvents","candidate","rmSync","errorMessage","transaction","candidate","z","canonicalJson","sha256hex","z","sha256hex","canonicalJson","randomUUID","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","readdirSync","renameSync","rmSync","basename","isAbsolute","join","canonicalJson","randomUUID","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","renameSync","rmdirSync","rmSync","writeFileSync","dirname","canonicalJson","z","z","bestEffortFsyncDirectory","openSync","fsyncSync","closeSync","removeEmptyDir","rmdirSync","atomicRewrite","mkdirSync","dirname","randomUUID","writeFileSync","canonicalJson","renameSync","rmSync","readFileSync","existsSync","readdirSync","join","readFileSync","existsSync","basename","mkdirSync","renameSync","bestEffortFsyncDirectory","rmSync","canonicalJson","randomUUID","isAbsolute","compareText","openSync","fsyncSync","closeSync","randomUUID","closeSync","fsyncSync","mkdirSync","openSync","readFileSync","readdirSync","renameSync","rmSync","writeFileSync","dirname","isAbsolute","join","canonicalJson","z","CANDIDATE_ID","z","isAbsolute","join","bestEffortFsyncDirectory","openSync","fsyncSync","closeSync","atomicRewrite","mkdirSync","dirname","randomUUID","writeFileSync","renameSync","rmSync","canonicalJson","readFileSync","readdirSync","asRecordId","z","scopeSchema","anchorSchema","artifactRefSchema","bundleKindSchema","factSubtypeSchema","randomUUID","existsSync","rmSync","join","asEvidenceToken","canonicalJson","parseProcedureBody","sha256hex","canonicalJson","parseProcedureBody","normalizeAnchor","canonicalJson","sha256hex","canonicalJson","normalizeAnchor","triggerKey","folded","windowOpenOrdinal","latest","candidate","deltaKind","draft","parseProcedureBody","asEvidenceToken","sha256hex","canonicalJson","draft","join","existsSync","targetId","candidate","parseProcedureBody","bundleDir","randomUUID","rmSync","existsSync","readFileSync","canonicalJson","asRecordId","existsSync","readdirSync","rmdirSync","rmSync","basename","join","childDirectories","readdirSync","join","rmdirSync","rmSync","existsSync","basename","canonicalJson","normalizeAnchor","supersessionKey","normalizedAnchorKey","canonicalJson","normalizeAnchor","primaryAnchor","supersessionKey","join","asEvidenceToken","asRecordId","canonicalJson","deriveEvidenceToken","evaluatePromotionGate","eventDedupKey","foldBundleTrust","GATE_RECEIPT_SCHEMA_VERSION","GateReceiptSchema","isPromotionReceipt","receiptDigestOf","sha256hex","stampReceiptDigest","survivingOutcomeEvents","strongestPromotionPath","deltaKind","sha256hex","canonicalJson","join","foldBundleTrust","survivingOutcomeEvents","evaluatePromotionGate","strongestPromotionPath","GATE_RECEIPT_SCHEMA_VERSION","appended","asEvidenceToken","eventDedupKey","stampReceiptDigest","deriveEvidenceToken","isPromotionReceipt","GateReceiptSchema","receiptDigestOf","asRecordId","errorMessage","completed","existsSync","DEFAULT_OPERATIONS","errorMessage","readFileSync","asRecordId","canonicalJson","deltaKind","createHash","randomUUID","existsSync","linkSync","lstatSync","mkdirSync","readFileSync","readdirSync","rmdirSync","rmSync","writeFileSync","basename","dirname","isAbsolute","join","relative","sep","canonicalJson","committedFileText","createVersionGuard","recordGraphNode","z","z","createVersionGuard","isAbsolute","join","readdirSync","lstatSync","transaction","existsSync","recordGraphNode","dirname","sep","rmdirSync","digest","basename","readFileSync","rmSync","intentPath","canonicalJson","bundleDir","affectedPaths","relative","createHash","mkdirSync","randomUUID","writeFileSync","linkSync","committedFileText","existsSync","readFileSync","join","canonicalJson","normalizeAnchor","survivingOutcomeEvents","compareText","canonicalJson","normalizeAnchor","anchorMatches","join","existsSync","readFileSync","survivingOutcomeEvents","latest","asRecordId","canonicalJson","request","envelope","asRecordId","canonicalJson","existsSync","join","relative","GATE_RECEIPT_SCHEMA_VERSION","KnowledgeMarkInputSchema","KnowledgeChangeIdSchema","asEvidenceToken","asRecordId","canonicalJson","stampReceiptDigest","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","renameSync","rmSync","writeFileSync","dirname","join","relative","slugBranch","join","slugBranch","text","dirname","relative","existsSync","readFileSync","mkdirSync","openSync","writeFileSync","fsyncSync","closeSync","renameSync","rmSync","randomUUID","closeSync","fsyncSync","mkdirSync","openSync","readFileSync","renameSync","rmSync","writeFileSync","dirname","isAbsolute","join","isAbsolute","join","readFileSync","dirname","mkdirSync","randomUUID","openSync","writeFileSync","fsyncSync","closeSync","renameSync","rmSync","asRecordId","stampReceiptDigest","GATE_RECEIPT_SCHEMA_VERSION","canonicalJson","asEvidenceToken","event","relative","existsSync","join","recordIds","forgetReceipt","request","KnowledgeMarkInputSchema","KnowledgeChangeIdSchema","mkdirSync","readdirSync","readFileSync","writeFileSync","join","join","writeFileSync","parseReceipt","readFileSync","mkdirSync","readdirSync","isAbsolute","asEvidenceToken","asRecordId","canonicalJson","eventDedupKey","sha256hex","supersessionKey","survivingOutcomeEvents","compareText","isAbsolute","fenceWriterAuthority","sha256hex","canonicalJson","canonicalBundles","asRecordId","eventDedupKey","survivingOutcomeEvents","asEvidenceToken","candidate","supersessionKey","latest","asRecordId","isPromotionReceipt","strongestPromotionPath","survivingOutcomeEvents","asRecordId","candidate","isPromotionReceipt","strongestPromotionPath","survivingOutcomeEvents","asEvidenceToken","asRecordId","member","step","envelope","asRecordId","asEvidenceToken","asRecordId","basename","asEvidenceToken","asRecordId","deriveEvidenceToken","eventDedupKey","exercisedAnchors","isPromotionReceipt","asEvidenceToken","basename","asRecordId","exercisedAnchors","deriveEvidenceToken","isPromotionReceipt","eventDedupKey","asRecordId"]}