@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.
- package/LICENSE.md +105 -0
- package/NOTICE.md +15 -0
- package/assets/potion-retrieval-32m/LICENSE +29 -0
- package/assets/potion-retrieval-32m/golden-vectors.json +4144 -0
- package/assets/potion-retrieval-32m/manifest.json +37 -0
- package/assets/potion-retrieval-32m/potion-retrieval-32m.i8bin +0 -0
- package/assets/potion-retrieval-32m/tokenizer.json +63241 -0
- package/dist/embedder-worker/worker-entry.cjs +1424 -0
- package/dist/embedder-worker/worker-entry.cjs.map +1 -0
- package/dist/embedder-worker/worker-entry.d.cts +18 -0
- package/dist/embedder-worker/worker-entry.d.ts +18 -0
- package/dist/embedder-worker/worker-entry.js +1426 -0
- package/dist/embedder-worker/worker-entry.js.map +1 -0
- package/dist/index.cjs +21491 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3983 -0
- package/dist/index.d.ts +3983 -0
- package/dist/index.js +21612 -0
- package/dist/index.js.map +1 -0
- package/dist/mark-evidence-plan-BCkYN07i.d.cts +1014 -0
- package/dist/mark-evidence-plan-BCkYN07i.d.ts +1014 -0
- package/dist/reader.cjs +5829 -0
- package/dist/reader.cjs.map +1 -0
- package/dist/reader.d.cts +107 -0
- package/dist/reader.d.ts +107 -0
- package/dist/reader.js +5951 -0
- package/dist/reader.js.map +1 -0
- package/dist/worker-registration-C-9spEsf.d.cts +78 -0
- package/dist/worker-registration-C-9spEsf.d.ts +78 -0
- package/package.json +69 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reader.ts","../src/serving/reader.ts","../src/bundle-read.ts","../src/bundle-scan.ts","../src/canary-emit.ts","../src/anchor-schema.ts","../src/knowledge-containment.ts","../src/queue-transport.ts","../src/index-open.ts","../src/sqlite-vec-loadable.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/retrieval/pre-filter.ts","../src/serving/get-cautions.ts","../src/serving/brief-selection.ts","../src/retrieval/rerank.ts","../src/retrieval/constants.ts","../src/retrieval/validity.ts","../src/build-ordinal-read.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/quarantine/ledger.ts","../src/quarantine/identity.ts","../src/retrieve.ts","../src/query-helper.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/serving/get-authoring-brief.ts","../src/inspect.ts","../src/maintenance-scan.ts","../src/diff-since.ts","../src/purge-receipt.ts","../src/list-bundles.ts","../src/show-records.ts","../src/show-record.ts","../src/quarantine/detection.ts","../src/serving/canary-attribution.ts","../src/serving/canary-observation-id.ts","../src/gates/gate-receipt-read.ts","../src/gates/candidate-injection.ts","../src/gates/canary-posture-facts.ts","../src/feedback/mark-evidence-plan.ts"],"sourcesContent":["export {\n KnowledgeRecordNotFoundError,\n hydrateRows,\n openKnowledgeReader,\n readIndexRows,\n} from './serving/reader.js'\nexport type {\n HydratedEntry,\n IndexRow,\n OpenServingKnowledgeReaderConfig,\n} from './serving/reader.js'\nexport {\n AUTHORING_BRIEF_DEFAULT_BUDGET,\n AUTHORING_DENSE_K,\n createAuthoringReader,\n} from './serving/authoring-reader.js'\nexport type { AuthoringReaderDependencies } from './serving/authoring-reader.js'\nexport { inspectRecords } from './inspect.js'\nexport type { InspectRecordsOptions } from './inspect.js'\nexport { diffSince } from './diff-since.js'\nexport type { DiffSinceOptions } from './diff-since.js'\nexport { listBundles } from './list-bundles.js'\n// 387 KREV-01: the show verb's read half. On the READER entry beside its three siblings\n// because it opens nothing, writes nothing and holds no lease — it reads committed bundle\n// files and projects them, which is the whole of what the read half of the review family is.\nexport { showRecord } from './show-record.js'\nexport type { ShowRecordOptions } from './show-record.js'\nexport { showRecords } from './show-records.js'\nexport type { ShowRecordsOptions } from './show-records.js'\n// 390 D-01/D-11: the committed quarantine ledger's READ half. On the reader entry beside its\n// siblings because it opens nothing, writes nothing and holds no lease — it reads one committed\n// text file and folds it purely. The append half stays on the main entry: it performs a committed\n// write through the egress checkpoint, which is exactly the power this entry withholds.\nexport {\n QUARANTINE_LEDGER_FILENAME,\n foldQuarantineLedgerState,\n quarantineLedgerPath,\n readQuarantineLedger,\n} from './quarantine/ledger.js'\nexport type { QuarantineLedgerRead, RefusedQuarantineLine } from './quarantine/ledger.js'\n// 390-30: the gate's TWO TOTAL TABLES, on this entry for the same reason the ledger's read half is\n// here — they open nothing, write nothing and hold no lease. They are frozen constant maps from a\n// closed verdict vocabulary to a decision, and reading them decides nothing on its own:\n// `autoQuarantines` (main entry) is what turns them into an admission, and it stays there.\n//\n// The consumer is the curation tail's withheld-line render, which must branch its remedy on\n// ADMISSIBILITY — an escalate-only class is told no run admits it, an authored-required class is\n// told it needs an analyst, and only the floor-eligible classes are told the next applied run may\n// admit them. That render and the gate must read ONE vocabulary or the line's promise and the\n// refusal drift apart per class, which is how the shipped line came to promise relief no fold\n// grants. Publishing the tables — rather than restating them at the render — is what makes the\n// drift impossible rather than merely unlikely.\nexport {\n QUARANTINE_CLASS_DISPOSITIONS,\n QUARANTINE_FLOOR_ELIGIBILITY,\n} from './quarantine/detection.js'\nexport type {\n QuarantineDisposition,\n QuarantineFloorEligibility,\n} from './quarantine/detection.js'\n// 407 D-08: the attribution read — what became of the canary lines a run served. On the READER\n// entry because it opens nothing, writes nothing and holds no lease: it walks committed bundle\n// files, recomputes each served tuple's observation id and reports the surviving outcome carrying\n// it. The append half of a canary outcome stays behind the writer lease on the main entry, which\n// is exactly the power this entry withholds — a read that could mint the outcome it reports would\n// be the tampering hazard rather than its mitigation (T-407-11).\nexport { canaryAttributionsFor } from './serving/canary-attribution.js'\nexport type {\n CanaryAttributionOutcome,\n CanaryAttributionRow,\n CanaryAttributionTuple,\n CanaryAttributionsForOptions,\n CanaryAttributionsResult,\n} from './serving/canary-attribution.js'\n// 407-25: the JOIN KEY ITSELF, published beside the read that recomputes it.\n//\n// It belongs on this entry for the same reason `canaryAttributionsFor` does, and for one more.\n// The reason it shares: it is a pure derivation over five fields of a served tuple — it opens\n// nothing, writes nothing and holds no lease, so publishing it grants none of the power this\n// entry withholds (T-407-25-04). The reason that is its own: the READ side recomputes this id\n// rather than reading a stored copy, which is what makes the attribution join evidence instead\n// of a claim — and a harness that must PLANT the outcome event the reader will find has to\n// recompute it the same way. Reaching for a second spelling there would produce a plant the\n// reader never finds, and a green agreement over an empty set. There is exactly one\n// implementation; `curator/disposition.ts` re-exports it for the writer side.\nexport { canaryOutcomeObservationId } from './serving/canary-observation-id.js'\nexport { KnowledgeMaintenanceScanError } from './maintenance-scan.js'\nexport type { KnowledgeMaintenanceScanIssue } from './maintenance-scan.js'\nexport type { BuildRange, ReadOptions, SearchOptions } from '@vostride/agent-qa-schema'\n// 2026-09-06, 416 D-17: gate history and the live verdict. This read walks committed\n// bundle files and folds their evidence, opening no write authority or derived index.\nexport { gateReceiptsFor } from './gates/gate-receipt-read.js'\nexport type { GateReceiptsForOptions } from './gates/gate-receipt-read.js'\n// 2026-09-07, 417 D-01: candidate brief DATA from committed bundles, with no write authority.\nexport { candidateInjectionFor } from './gates/candidate-injection.js'\nexport type { CandidateInjectionForOptions } from './gates/candidate-injection.js'\n\n// 2026-09-07, 418 D-13/D-14: read-only canary posture data.\nexport { canaryPostureFactsFor, standingReceiptDigestsFor, lowerTrustSharesFor,\n type CanaryPostureFacts, type StandingReceiptDigest, type LowerTrustShare,\n} from './gates/canary-posture-facts.js'\n// 2026-09-15, 423 D-16: the mark evidence PLANNING half. It resolves and folds committed bundles,\n// takes no lease and mints no markId; appendMarkEvidence executes the same plan on the main entry.\nexport { MARK_EVIDENCE_TOKEN_PREFIX, markEvidenceEvent, planMarkEvidence, projectMarkEvidenceOutcome }\n from './feedback/mark-evidence-plan.js'\nexport type { MarkEvidenceEffect, MarkEvidencePlan, MarkEvidenceTarget, PlanMarkEvidenceInput }\n from './feedback/mark-evidence-plan.js'\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","// 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","/**\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 { 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","/**\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","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","/**\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","/**\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 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","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","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","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 * 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","// 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","// 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","/**\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 * 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","/**\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","/**\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","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 { 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","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","// 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","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","// 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","// What became of the canary lines a run served (Phase 407, LERN-02 · D-08).\n//\n// A canary has two halves that never live in the same place. The SERVING half — \"this brief line\n// was offered as a canary\" — is a fact about the run and is read from its evidence. The\n// ATTRIBUTED half — \"and it was confirmed\" — is a fact about the committed knowledge store and\n// lives in a bundle's outcomes log, written long after the run ended, by the curation drain.\n// `canaryOutcomeObservationId` is the only thing that spans them: the writer stamps it onto the\n// event it appends, and this module RECOMPUTES it from the run's own tuples to find that event\n// again. Recomputing rather than reading is what makes the join evidence instead of a claim —\n// there is no second copy of the id to drift.\n//\n// READS ONLY. No writer lease is taken, no event is appended, no file is written. That is the\n// T-407-11 mitigation and it is the reason this module can sit on the physically read-only\n// `/reader` entry beside `diffSince` and `showRecord`: asking what became of a line must not be\n// a way of deciding what becomes of it.\n//\n// ABSENCE IS A ROW, NOT A GAP. A tuple whose candidate has no committed bundle, or whose\n// observation has been retracted, still answers a row carrying its observation id and no\n// `outcome` key. The caller renders \"not yet attributed\" from that, which is a different and\n// more honest thing than a missing row — a missing row is indistinguishable from a tuple the\n// caller forgot to ask about. The same reasoning skips a bundle that will not LOAD (407-14,\n// CR-03): an unreadable bundle can attribute nothing, so it must not be allowed to deny the rows\n// of the bundles that read cleanly. A store this walker cannot fully load is still a store it can\n// answer honestly about the readable part of; a store it cannot LIST is not, and still throws.\n//\n// A SKIPPED BUNDLE IS COUNTED, NEVER SILENTLY ABSORBED (407-19, REVIEW WR-03). \"Confirmed\n// nowhere\" and \"the bundle that would have confirmed it could not be read\" are different\n// instructions to a reader, and this walk is the only place that knows which one applies — so the\n// partiality travels ON the return value as `skippedBundles`, not as something a caller infers\n// from a sibling read happening to fail on the same file. That inference is exactly what used to\n// carry the signal, and it does not survive the two reads seeing different stores. The integrity\n// arm of the skip is the T-407-11 hazard class: bytes that parse but no longer hash to what the\n// manifest committed must never read back as a clean, positive `not attributed`.\n\nimport { asRecordId, survivingOutcomeEvents } from '@vostride/agent-qa-schema'\n\nimport {\n KnowledgeMaintenanceScanError,\n enumerateMaintenanceBundleDirs,\n loadMaintenanceBundle,\n} from '../maintenance-scan.js'\nimport { canaryOutcomeObservationId } from './canary-observation-id.js'\n\n/** The four observation words. A lifecycle event carrying the same id attributes nothing. */\nconst ATTRIBUTING_EVENT_TYPES = [\n 'confirmed',\n 'contradicted',\n 'helpful',\n 'harmful',\n] as const\n\nexport type CanaryAttributionOutcome = (typeof ATTRIBUTING_EVENT_TYPES)[number]\n\n/** One served canary line, addressed the way the run recorded it. */\nexport interface CanaryAttributionTuple {\n candidateId: string\n testId: string\n testIndex: number\n stepIndex: number\n}\n\nexport interface CanaryAttributionRow {\n candidateId: string\n testIndex: number\n stepIndex: number\n observationId: string\n outcome?: CanaryAttributionOutcome\n}\n\n/**\n * The attribution answer, with the partiality of the walk that produced it.\n *\n * `skippedBundles > 0` means the answer is PARTIAL — some bundle in the store failed\n * `loadMaintenanceBundle` (load or integrity) and was skipped. A caller that renders\n * `not attributed` from an absent `outcome` must consult this first: on a partial walk the\n * absence means \"not found in the part of the store I could read\", which is not the same claim\n * (REVIEW WR-03; the T-407-11 hazard class is the integrity arm).\n */\nexport interface CanaryAttributionsResult {\n rows: CanaryAttributionRow[]\n skippedBundles: number\n}\n\nexport interface CanaryAttributionsForOptions {\n knowledgeRoot: string\n runId: string\n tuples: readonly CanaryAttributionTuple[]\n}\n\nfunction isAttributingType(type: string): type is CanaryAttributionOutcome {\n return (ATTRIBUTING_EVENT_TYPES as readonly string[]).includes(type)\n}\n\n/**\n * Index the surviving attributing observations of every candidate the caller asked about.\n *\n * The walk follows `showRecord`'s idiom — enumerate, load, compare `manifest.id` — because the\n * manifest is the only place a bundle's identity is verified, and matching on a directory name\n * would trust a filesystem convention no contract states. Bundles outside the candidate set are\n * enumerated but their outcomes are never folded.\n *\n * A BUNDLE THAT WILL NOT LOAD ATTRIBUTES NOTHING, AND DENIES NOTHING (407-14, CR-03). One corrupt,\n * truncated or tampered directory — quite possibly one the asking run never served a line from —\n * used to throw straight through this walk and turn the caller's whole read into a failure. It is\n * SKIPPED instead: it can contribute no outcome (that is what \"will not load\" means), and it has\n * no standing to withhold the outcomes of the bundles that do load. Skipping is not forgiving the\n * corruption either — the maintenance scanner beside this one still refuses to answer for such a\n * store, which is where a maintainer's fail-closed question belongs.\n *\n * ENUMERATE-LEVEL ERRORS STILL THROW. A product or bundle entry that is not a canonical directory\n * means the walker cannot even LIST the store, and a store it cannot list is not one it can answer\n * partially for — there is no way to know what was missed, so an empty-looking answer would be a\n * guess. The distinction is exactly \"I read everything readable\" versus \"I do not know what is\n * here\".\n *\n * AND IT SAYS HOW MANY IT SKIPPED. Every skip increments `skippedBundles`, which rides back out on\n * the return value so the caller can tell the two absences apart (407-19, REVIEW WR-03). The count\n * covers bundles OUTSIDE the candidate set too: a bundle that will not load has no readable\n * manifest id, so there is no honest way to decide it was irrelevant.\n */\nfunction attributingOutcomesByObservationId(\n knowledgeRoot: string,\n candidateIds: ReadonlySet<string>,\n): { outcomes: Map<string, CanaryAttributionOutcome>; skippedBundles: number } {\n const outcomes = new Map<string, CanaryAttributionOutcome>()\n let skippedBundles = 0\n for (const entry of enumerateMaintenanceBundleDirs(knowledgeRoot)) {\n let bundle\n try {\n bundle = loadMaintenanceBundle(entry)\n } catch (error) {\n if (error instanceof KnowledgeMaintenanceScanError) {\n skippedBundles += 1\n continue\n }\n throw error\n }\n if (!candidateIds.has(bundle.manifest.id)) continue\n for (const event of survivingOutcomeEvents(bundle.events)) {\n if (event.observationId === undefined) continue\n if (!isAttributingType(event.type)) continue\n // First-wins, matching the dedupe law the surviving-events fold already applies: one\n // observation identity has one outcome, and a replayed line does not get a second vote.\n if (outcomes.has(event.observationId)) continue\n outcomes.set(event.observationId, event.type)\n }\n }\n return { outcomes, skippedBundles }\n}\n\n/**\n * Answer, per served canary tuple, the observation id it would have been attributed under and the\n * committed outcome carrying that id — when one survives.\n *\n * The answer carries `skippedBundles` beside the rows so the caller never has to infer the\n * partiality of this walk from some other read (REVIEW WR-03).\n *\n * An empty tuple list answers no rows and no skips without touching the store: there is nothing to\n * look up, and a walk that could fail on an unrelated bundle would turn \"you asked about nothing\"\n * into an error.\n */\nexport function canaryAttributionsFor(\n options: CanaryAttributionsForOptions,\n): CanaryAttributionsResult {\n if (options.tuples.length === 0) return { rows: [], skippedBundles: 0 }\n\n const { outcomes, skippedBundles } = attributingOutcomesByObservationId(\n options.knowledgeRoot,\n new Set(options.tuples.map((tuple) => tuple.candidateId)),\n )\n\n const rows = options.tuples.map((tuple) => {\n const observationId = canaryOutcomeObservationId({\n candidateId: asRecordId(tuple.candidateId),\n runId: options.runId,\n testId: tuple.testId,\n testIndex: tuple.testIndex,\n stepIndex: tuple.stepIndex,\n })\n const outcome = outcomes.get(observationId)\n return {\n candidateId: tuple.candidateId,\n testIndex: tuple.testIndex,\n stepIndex: tuple.stepIndex,\n observationId,\n ...(outcome === undefined ? {} : { outcome }),\n }\n })\n\n return { rows, skippedBundles }\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","// 2026-09-06, 416 D-17/D-18: READS ONLY. This answer derives from committed\n// receipt history and the pure gate. ABSENCE IS A ROW; unreadable data still throws.\nimport { asRecordId, evaluatePromotionGate, isPromotionReceipt, KnowledgeGatesListResultSchema,\n standingReceiptsByGate, strongestPromotionPath,\n type GateReceipt, type KnowledgeGatesListResult, type ResolvePromotionPosture } from '@vostride/agent-qa-schema'\nimport { deriveBundleTrust, readGateReceipts } from '../bundle-read.js'\nimport { enumerateMaintenanceBundleDirs, loadMaintenanceBundle } from '../maintenance-scan.js'\nimport { assemblePromotionGateInput } from '../promotion-gate-input.js'\n\nexport interface GateReceiptsForOptions {\n knowledgeRoot: string\n candidateId: string\n /** Resolved per candidate by the same assembly used by the promotion doors. */\n resolvePromotionPosture?: ResolvePromotionPosture\n}\nexport function gateReceiptsFor(options: GateReceiptsForOptions): KnowledgeGatesListResult {\n const id = asRecordId(options.candidateId)\n for (const entry of enumerateMaintenanceBundleDirs(options.knowledgeRoot)) {\n const bundle = loadMaintenanceBundle(entry)\n if (bundle.manifest.id !== id) continue\n const lines = readGateReceipts(entry.dir, id) ?? []\n const standing = standingReceiptsByGate(\n lines.filter((line): line is GateReceipt => !isPromotionReceipt(line)),\n )\n const path = strongestPromotionPath(lines)\n const gateInput = assemblePromotionGateInput({\n knowledgeRoot: options.knowledgeRoot, bundleDir: entry.dir, bundle,\n resolvePromotionPosture: options.resolvePromotionPosture,\n })\n return KnowledgeGatesListResultSchema.parse({\n kind: 'found', recordId: id, product: entry.product,\n recordKind: bundle.frontmatter.kind, status: deriveBundleTrust(bundle).status,\n ...(path === undefined ? {} : { strongestPromotionPath: path }),\n lines, standing,\n // 416-DOOR: read live-verdict\n live: evaluatePromotionGate(gateInput),\n // 'resolved' and 'unavailable' describe the actual posture the gate judged.\n posture: gateInput.gatePosture?.kind ?? 'absent',\n })\n }\n return { kind: 'not-found', recordId: options.candidateId }\n}\n","// 2026-09-07, 417 D-01: READS ONLY. The candidate enters replay as brief DATA —\n// one rendered line, never a prompt or code edit. ABSENCE IS A ROW; unreadable data throws.\nimport {\n asRecordId,\n KnowledgeCandidateInjectionResultSchema,\n survivingOutcomeEvents,\n type IndexEntry,\n type KnowledgeCandidateInjectionResult,\n type TrustPriorTable,\n} from '@vostride/agent-qa-schema'\nimport { renderObservationLine } from '@vostride/agent-qa-runner'\nimport { deriveBundleTrust } from '../bundle-read.js'\nimport { enumerateMaintenanceBundleDirs, loadMaintenanceBundle } from '../maintenance-scan.js'\nimport { candidateProvenanceOf } from '../promotion-gate-input.js'\nimport { renderBriefLine } from '../serving/brief-render.js'\n\nexport interface CandidateInjectionForOptions {\n knowledgeRoot: string\n candidateId: string\n priors?: TrustPriorTable\n}\n\nexport function candidateInjectionFor(\n options: CandidateInjectionForOptions,\n): KnowledgeCandidateInjectionResult {\n const id = asRecordId(options.candidateId)\n for (const entry of enumerateMaintenanceBundleDirs(options.knowledgeRoot)) {\n const bundle = loadMaintenanceBundle(entry)\n if (bundle.manifest.id !== id) continue\n const frontmatter = bundle.frontmatter\n const trust = deriveBundleTrust(bundle, options.priors)\n const stampedEntry = {\n id, kind: frontmatter.kind, title: bundle.summary, summary: bundle.summary,\n trust: trust.trust, status: trust.status,\n anchors: frontmatter.anchors.map(({ normalized }) => normalized),\n scope: frontmatter.scope,\n validity: trust.validity.closedAtOrdinal === undefined ? 'current'\n : `${trust.validity.openedAtOrdinal}:${trust.validity.closedAtOrdinal}`,\n servedAsCanary: false, originClass: frontmatter.originClass,\n } satisfies IndexEntry & { originClass: typeof frontmatter.originClass }\n // The serving renderer applies tierForEntry to this same origin-stamped input.\n const line = renderBriefLine(stampedEntry).briefLine\n const target = bundle.provenance.mode === 'run-linked' ? {\n runId: bundle.provenance.runId,\n stepIndex: bundle.provenance.stepIndex,\n testId: bundle.provenance.testId,\n ...(bundle.provenance.sourceBuildOrdinal === undefined ? {} : {\n sourceBuildOrdinal: bundle.provenance.sourceBuildOrdinal,\n }),\n } : undefined\n return KnowledgeCandidateInjectionResultSchema.parse({\n kind: 'found', injection: {\n candidateId: id, kind: frontmatter.kind, product: entry.product,\n scope: frontmatter.scope, anchors: frontmatter.anchors, status: trust.status,\n line, renderedLine: renderObservationLine(line),\n provenance: candidateProvenanceOf(entry.dir, bundle),\n ...(target === undefined ? {} : { target }),\n latestOrdinal: Math.max(frontmatter.createdAtOrdinal,\n ...survivingOutcomeEvents(bundle.events).map(event => event.buildOrdinal)),\n },\n })\n }\n return KnowledgeCandidateInjectionResultSchema.parse({\n kind: 'not-found', recordId: options.candidateId,\n })\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-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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAC,mBAA2B;AAC3B,IAAAC,qBAAyB;AAGzB,6BAAoC;AACpC,IAAAC,2BAmBO;;;ACnBP,yBAA2B;AAC3B,qBAAmD;AACnD,uBAA+B;AAE/B,6BAiBO;AAwCP,IAAM,oBAAoB;AACnB,IAAM,iBAAiB;AAC9B,IAAM,wBAAwB;AAC9B,IAAM,qBAAqB;AAC3B,IAAM,2BAA2B;AACjC,IAAM,oBAAoB;AAE1B,SAAS,aAAa,OAAwB;AAC5C,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,cAAc,UAAoC;AACzD,SAAO,OAAO,KAAK,SAAS,aAAa,EACtC,QAAQ,CAAC,YAAY;AACpB,UAAM,QAAQ,kBAAkB,KAAK,OAAO;AAC5C,WAAO,UAAU,OAAO,CAAC,IAAI,CAAC,EAAE,SAAS,WAAW,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC;AAAA,EACxE,CAAC,EACA,KAAK,CAAC,MAAM,UAAU,KAAK,YAAY,MAAM,SAAS,EACtD,IAAI,CAAC,EAAE,QAAQ,MAAM,OAAO;AACjC;AAEA,SAAS,gBACP,MAC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,MAAM;AAAA,MAAW,YAAY,MAAM;AAAA,MAAS,QAAQ,OAAO,IAAI,QAAQ;AAAA,MACnG;AAAA,MAAc;AAAA,IAAQ,CAAC;AAAA,EAC3B;AACA,SAAO;AACT;AAGO,SAAS,2BAA2B,MACzC,SAAyE;AACzE,QAAM,SAAoC;AAAA,IAAE,WAAW;AAAA,IAAG,YAAY;AAAA,IAAG,SAAS,CAAC;AAAA,IACjF,GAAI,KAAK,0BAA0B,OAAO,EAAE,uBAAuB,KAAc,IAAI,CAAC;AAAA,EAAG;AAC3F,aAAW,UAAU,KAAK,SAAS;AACjC,QAAI,OAAO,SAAS,cAAc;AAChC,aAAO,QAAQ,KAAK,EAAE,UAAU,OAAO,UAAU,QAAQ,oBAAoB,CAAC;AAC9E;AAAA,IACF;AACA,QAAI,UAAU;AACd,eAAW,UAAU,OAAO,SAAS;AACnC,UAAI,OAAO,mBAAmB,CAAC,QAAQ,uBAAwB;AAC/D,UAAI,OAAO,cAAc,UAAW,QAAO,aAAa;AAAA,UACnD,QAAO,cAAc;AAC1B,gBAAU;AAAA,IACZ;AACA,QAAI,CAAC,QAAS,QAAO,QAAQ,KAAK,EAAE,UAAU,OAAO,UAAU,QAAQ,mBAAmB,CAAC;AAAA,EAC7F;AACA,SAAO;AACT;","names":["openKnowledgeReader","import_node_fs","import_node_path","import_agent_qa_schema","import_node_fs","import_node_path","import_agent_qa_schema","import_node_crypto","import_node_fs","import_node_path","import_zod","import_agent_qa_schema","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_fs","import_node_path","import_agent_qa_schema","import_node_fs","import_node_path","import_agent_qa_schema","import_node_crypto","import_node_fs","import_node_path","import_zod","request","import_node_fs","import_node_path","import_agent_qa_schema","import_agent_qa_schema","import_node_crypto","import_agent_qa_schema","digest","errorMessage","denseVec0","queryBlob","denseBrute","reader","errorMessage","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","count","import_agent_qa_schema","import_node_fs","import_node_path","latest","import_agent_qa_schema","import_agent_qa_schema","normalizedAnchorKey","import_agent_qa_runner","import_agent_qa_schema","compareRecordId","rendered","import_node_fs","import_node_path","import_agent_qa_schema","CHARS_PER_TOKEN_ESTIMATE","compareText","normalizedRecordCap","normalizedAnchorKey","anchorMatches","overlapsRange","openKnowledgeReader","import_node_fs","import_agent_qa_schema","import_node_fs","import_node_path","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","import_node_path","import_agent_qa_schema","import_node_crypto","resolve","embed","import_node_crypto","import_node_fs","import_node_path","import_node_url","isRecord","errorMessage","import_node_path","import_node_path","embed","import_node_crypto","import_node_fs","import_node_os","import_node_path","import_zod","bestEffortFsyncDirectory","bestEffortFsyncDirectory","MAX_SQL_LIMIT","queryLimit","float32View","cosineDistance","queryLimit","import_agent_qa_schema","normalizedAnchorKey","compareText","lexicalRelevance","import_node_fs","import_node_path","import_agent_qa_schema","import_node_fs","import_node_path","compareText","anchorMatches","latest","import_node_fs","import_node_path","import_agent_qa_schema","import_agent_qa_schema","import_zod","compareText","import_node_path","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_schema","import_agent_qa_runner","import_agent_qa_schema","import_node_path","import_agent_qa_schema"]}
|