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

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/embedder-worker/worker-entry.ts","../../src/embedder-acquire.ts","../../src/embedder-floor.ts","../../src/embedder-native.ts","../../src/model-cache-dir.ts","../../src/embedder-worker/worker-registration.ts","../../src/index-open.ts","../../src/sqlite-vec-loadable.ts","../../src/lease/writer-lease.ts","../../src/embedder-worker/worker-incarnation.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { chmodSync, rmSync } from 'node:fs'\nimport {\n createServer,\n type IncomingMessage,\n type Server,\n type ServerResponse,\n} from 'node:http'\nimport { connect } from 'node:net'\nimport { basename, resolve } from 'node:path'\n\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\n\nimport { resolveEmbedderCapability } from '../embedder-acquire.js'\nimport type { EmbedderPort } from '../embedder-port.js'\nimport { ownEmbedderWorkerIncarnation } from './worker-incarnation.js'\nimport {\n asEmbeddingProfile,\n embedderWorkerAgentQaRoot,\n embedderWorkerRequestSchema,\n embedderWorkerSocketPath,\n EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION,\n EMBEDDER_WORKER_REGISTRATION_SCHEMA_VERSION,\n embeddingProfileSchema,\n MAX_EMBEDDER_WORKER_BODY_BYTES,\n prepareEmbedderWorkerSocketParent,\n removeEmbedderWorkerRegistration,\n writeEmbedderWorkerRegistration,\n type EmbedderWorkerRegistration,\n type EmbedderWorkerRequest,\n} from './worker-registration.js'\n\nclass EmbedderWorkerRequestError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'EmbedderWorkerRequestError'\n }\n}\n\nasync function readRequestBody(request: IncomingMessage): Promise<string> {\n const chunks: Buffer[] = []\n let bytes = 0\n for await (const chunk of request) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n bytes += buffer.byteLength\n if (bytes > MAX_EMBEDDER_WORKER_BODY_BYTES) {\n throw new EmbedderWorkerRequestError(\n `Embedder request exceeds ${MAX_EMBEDDER_WORKER_BODY_BYTES} bytes`,\n )\n }\n chunks.push(buffer)\n }\n return Buffer.concat(chunks).toString('utf8')\n}\n\nasync function parseRequest(request: IncomingMessage): Promise<EmbedderWorkerRequest> {\n let parsedJson: unknown\n try {\n parsedJson = JSON.parse(await readRequestBody(request)) as unknown\n } catch (error) {\n if (error instanceof EmbedderWorkerRequestError) throw error\n throw new EmbedderWorkerRequestError(\n `Embedder request body must be valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n\n const parsed = embedderWorkerRequestSchema.safeParse(parsedJson)\n if (!parsed.success) {\n throw new EmbedderWorkerRequestError(\n parsed.error.issues\n .map((issue) => `${issue.path.map(String).join('.') || '<root>'}: ${issue.message}`)\n .join('; '),\n )\n }\n return parsed.data\n}\n\nfunction json(response: ServerResponse, statusCode: number, body: unknown): void {\n const payload = JSON.stringify(body)\n response.writeHead(statusCode, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(payload),\n })\n response.end(payload)\n}\n\nasync function embedOne(\n embedder: EmbedderPort,\n request: Extract<EmbedderWorkerRequest, { method: 'embedDocument' | 'embedQuery' }>,\n): Promise<Float32Array> {\n return request.method === 'embedDocument'\n ? embedder.embedDocument(request.rendering)\n : embedder.embedQuery(request.rendering)\n}\n\nasync function serveEmbeddingRequest(\n embedder: EmbedderPort,\n request: EmbedderWorkerRequest,\n): Promise<readonly Float32Array[]> {\n if (request.method === 'embedBatch') {\n return Promise.all(request.requests.map((item) => embedOne(embedder, item)))\n }\n return [await embedOne(embedder, request)]\n}\n\nfunction createEmbedderServer(embedder: EmbedderPort): Server {\n return createServer((request, response) => {\n void (async () => {\n if (request.method !== 'POST' || request.url !== '/embed') {\n json(response, 404, { error: 'not-found' })\n return\n }\n\n try {\n const envelope = await parseRequest(request)\n const vectors = await serveEmbeddingRequest(embedder, envelope)\n json(response, 200, {\n schemaVersion: EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION,\n vectors: vectors.map((vector) => Array.from(vector)),\n })\n } catch (error) {\n const statusCode = error instanceof EmbedderWorkerRequestError ? 400 : 500\n json(response, statusCode, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n })()\n })\n}\n\nfunction listen(server: Server, socketPath: string): Promise<void> {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (error: Error): void => {\n server.off('listening', onListening)\n rejectListen(error)\n }\n const onListening = (): void => {\n server.off('error', onError)\n resolveListen()\n }\n server.once('error', onError)\n server.once('listening', onListening)\n server.listen(socketPath)\n })\n}\n\nfunction probeSocket(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\nasync function listenWithStaleRecovery(server: Server, socketPath: string): Promise<void> {\n try {\n await listen(server, socketPath)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n (code !== 'EADDRINUSE' && code !== 'EINVAL')\n || process.platform === 'win32'\n ) {\n throw error\n }\n if (await probeSocket(socketPath)) {\n throw new Error(`Embedder worker socket is already live: ${socketPath}`)\n }\n rmSync(socketPath)\n await listen(server, socketPath)\n }\n}\n\nfunction closeServer(server: Server): Promise<void> {\n return new Promise((resolveClose, rejectClose) => {\n server.close((error) => {\n if (error !== undefined) rejectClose(error)\n else resolveClose()\n })\n })\n}\n\nasync function acquireProcessLocalEmbedder(profile: EmbeddingProfile): Promise<EmbedderPort> {\n const outcome = await resolveEmbedderCapability({\n preferredProfile: profile,\n allowDownload: false,\n probes: {\n discoverWorker: () => Promise.resolve({ kind: 'no-worker' }),\n },\n })\n if (outcome.kind !== 'ready') {\n throw new Error(`Embedder worker could not resolve profile: ${outcome.kind}`)\n }\n return outcome.embedder\n}\n\nexport interface RunEmbedderWorkerOptions {\n readonly projectRoot: string\n readonly profile: EmbeddingProfile\n /** Host-minted generation identity; standalone workers mint their own nonce. */\n readonly instanceId?: string\n}\n\nexport interface EmbedderWorkerHandle {\n readonly registration: EmbedderWorkerRegistration\n close(): Promise<void>\n}\n\n/** Start the child worker after resolving its process-local embedder through the normal ladder. */\nexport async function runEmbedderWorker(\n options: RunEmbedderWorkerOptions,\n): Promise<EmbedderWorkerHandle> {\n const projectRoot = resolve(options.projectRoot)\n const agentQaRoot = embedderWorkerAgentQaRoot(projectRoot)\n const instanceId = options.instanceId ?? randomUUID()\n const socketPath = embedderWorkerSocketPath(agentQaRoot, projectRoot, instanceId)\n const embedder = await acquireProcessLocalEmbedder(options.profile)\n const server = createEmbedderServer(embedder)\n prepareEmbedderWorkerSocketParent(socketPath)\n await listenWithStaleRecovery(server, socketPath)\n\n const registration: EmbedderWorkerRegistration = {\n schemaVersion: EMBEDDER_WORKER_REGISTRATION_SCHEMA_VERSION,\n instanceId,\n pid: process.pid,\n socketPath,\n profile: options.profile,\n startedAtMs: Date.now(),\n incarnation: ownEmbedderWorkerIncarnation(),\n }\n try {\n if (process.platform !== 'win32') chmodSync(socketPath, 0o600)\n writeEmbedderWorkerRegistration(agentQaRoot, registration)\n } catch (error) {\n await closeServer(server).catch(() => undefined)\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n if (process.platform !== 'win32') rmSync(socketPath, { force: true })\n throw error\n }\n\n let closePromise: Promise<void> | undefined\n return {\n registration,\n close() {\n closePromise ??= (async () => {\n try {\n await closeServer(server)\n } finally {\n try {\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n } finally {\n if (process.platform !== 'win32') rmSync(socketPath, { force: true })\n }\n }\n })()\n return closePromise\n },\n }\n}\n\nfunction parseProfile(raw: string | undefined): EmbeddingProfile {\n if (raw === undefined) throw new Error('Embedder worker requires a profile JSON argument')\n return asEmbeddingProfile(embeddingProfileSchema.parse(JSON.parse(raw) as unknown))\n}\n\nasync function main(): Promise<void> {\n const projectRoot = process.argv[2]\n if (projectRoot === undefined) throw new Error('Embedder worker requires a project root argument')\n const handle = await runEmbedderWorker({\n projectRoot,\n profile: parseProfile(process.argv[3]),\n ...(process.argv[4] === undefined ? {} : { instanceId: process.argv[4] }),\n })\n\n let stopping = false\n const stop = (exitCode: number): void => {\n if (stopping) return\n stopping = true\n void handle.close().then(\n () => process.exit(exitCode),\n (error: unknown) => {\n process.stderr.write(\n `Embedder worker cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n process.exit(1)\n },\n )\n }\n process.once('SIGTERM', () => stop(0))\n process.once('SIGINT', () => stop(0))\n}\n\nconst entryBasename = process.argv[1] === undefined ? undefined : basename(process.argv[1])\nif (entryBasename === 'worker-entry.js' || entryBasename === 'worker-entry.cjs') {\n void main().catch((error: unknown) => {\n process.stderr.write(\n `Embedder worker failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n process.exitCode = 1\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","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 * 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 * Epoch-fenced writer-role primitives for the gitignored knowledge root.\n *\n * This module never touches the curation queue. Plan 378-05 composes stale-holder requeue and\n * journal reconciliation around these lease decisions. Lease and epoch replacements are each\n * file-fsync'd and atomically renamed so a process kill can expose only old or new bytes.\n */\nimport { spawnSync } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants as fsConstants,\n existsSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmdirSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport type { Dirent, Stats } from 'node:fs'\nimport { basename, dirname, isAbsolute, join } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\nimport { threadId } from 'node:worker_threads'\n\nimport { z } from 'zod'\n\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\n\nexport const LEASE_FILE = '.lease'\nexport const EPOCH_FILE = '.epoch'\n\n/** Provisional writer-heartbeat TTL; retune from operational evidence without adding config. */\nexport const LEASE_HEARTBEAT_TTL_MS = 30_000\n\n/** Bounded mutation-lock takeover; retune from operational evidence without adding config. */\nexport const MUTATION_LOCK_TAKEOVER_MS = 45_000\n\n/** Authority-store filename is pinned; retune only through a data-migration plan. */\nexport const WRITER_AUTHORITY_DB_FILE = '.writer-authority.sqlite'\n\n/**\n * Provisional SQLite contention window; retune from operational evidence without adding config.\n *\n * The takeover deadline remains separate: this short timeout makes each failed write attempt\n * observable so the contender can apply the lease and verified-termination policy.\n */\nexport const MUTATION_LOCK_BUSY_TIMEOUT_MS = 2_000\n\n/**\n * Provisional acquisition deadline; retune from operational evidence without adding config.\n *\n * V-02: the retry loop's only exits used to be facts about the lease and the lock, and a state the\n * phase itself models — an epoch-invalid lease kept fresh by a renewal sidecar while a live owner\n * holds the authority transaction — satisfies none of them. A contender then spins on the caller's\n * main thread forever, which is what `agent-qa daemon` startup and `agent-qa knowledge drain` do.\n *\n * The bound is therefore anchored OUTSIDE that vocabulary: a monotonic clock reading taken at loop\n * entry plus an attempt counter, neither of which any on-disk value can influence. Deliberately\n * greater than MUTATION_LOCK_TAKEOVER_MS so a legitimate escalated takeover still fits inside the\n * budget and the deadline never pre-empts a reclaim that was going to succeed.\n */\nexport const ACQUIRE_WRITER_LEASE_DEADLINE_MS = 60_000\n\n/** Provisional cap on one `ps` incarnation fork; retune from operational evidence without config. */\nconst PROCESS_INCARNATION_PS_TIMEOUT_MS = 1_000\n\n/** Provisional floor for that cap — the bounded overshoot argued for at `psIncarnationCapMs`. */\nconst PROCESS_INCARNATION_PS_FLOOR_MS = 250\n\nconst PROCESS_INCARNATION_PS_PATH = '/bin/ps'\nconst PROCESS_INCARNATION_PS_ENV = Object.freeze({ LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' })\n\nconst MUTATION_LOCK_TERMINATION_POLL_MS = 10\nconst MUTATION_LOCK_TERMINATION_TIMEOUT_MS = 5_000\nconst MUTATION_LOCK_TERMINATION_WAIT = new Int32Array(\n new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),\n)\n\n/**\n * Transient guard serializing the beat's read-check-write with release's read-check-delete.\n *\n * A directory holding exactly one `owner-<token>` file, published whole by renaming a staged\n * directory into place. It lives under `memory/queue/`, which every scaffolded knowledge\n * `.gitignore` already ignores, so neither a guard in use nor one a crash left behind is ever a\n * commit-visible file in a user's knowledge repository (261002-lse follow-up; the user's\n * `.gitignore` is never rewritten, D-22).\n */\nexport const LEASE_GUARD_DIR = 'memory/queue/lease-guard'\n\nconst LEASE_GUARD_OWNER_PREFIX = 'owner-'\n\n/** A guard older than this cannot belong to a live section (each is one read and one write). */\nexport const LEASE_GUARD_STALE_MS = 10_000\n\n/**\n * How long a waiter keeps trying for the guard: deliberately LONGER than the residue bound.\n *\n * 2026-10-03 (quick 261003-lgd, Phase 432 review WR-11): the wait used to reuse the 2 s\n * MUTATION_LOCK_BUSY_TIMEOUT_MS, shorter than the 10 s bound. A guard left by a thread terminated\n * inside its section carries this live process's pid, so only the age bound can judge it residue,\n * and no waiter ever lived long enough to see it cross: every beat and release after a terminated\n * beat worker threw. The bound is kept and the wait made to outlast it, rather than the bound cut\n * below the wait, because a bound short enough to fit a 2 s wait could cut a live section short\n * under heavy load. Measured whole calls (stage, claim, section, release), 400 beats and 100\n * releases at load 4 on 12 cores: beat p50 12 ms, p99 15 ms, max 21 ms; release p50 9 ms, p99\n * 13 ms. Load 126-255 is about 10-21 times oversubscribed, so even a p99 stretched that far stays\n * well under the 10 s bound. Live contention still clears in milliseconds; only a residue costs a\n * waiter up to the bound, once.\n */\nexport const LEASE_GUARD_WAIT_MS = LEASE_GUARD_STALE_MS + 2_000\n\n/** A staging directory lives at most as long as its waiter, so one older than this is a leak. */\nconst LEASE_GUARD_STAGING_STALE_MS = LEASE_GUARD_WAIT_MS + LEASE_GUARD_STALE_MS\n\nconst LEASE_GUARD_STAGING_PREFIX = `${basename(LEASE_GUARD_DIR)}.tmp-`\n\nconst LEASE_GUARD_RESIDUE_PREFIX = `${basename(LEASE_GUARD_DIR)}.residue-`\n\nconst LEASE_GUARD_POLL_MS = 2\n\nconst writerLeaseSchema = z\n .object({\n leaseId: z.string().uuid(),\n pid: z.number().int().positive(),\n epoch: z.number().int().positive(),\n heartbeatAtMs: z.number().int().nonnegative(),\n })\n .strict()\n\nexport type WriterLease = z.infer<typeof writerLeaseSchema>\n\n/** What the contender could observe about the owner it gave up on; never an authority claim. */\nexport interface UnreclaimableMutationLockOwner {\n pid: number\n acquiredAtMs: number\n generationToken: string\n /** False when the row carries no incarnation, which is why escalation could never fire. */\n incarnationAttributed: boolean\n}\n\nexport type AcquireWriterLeaseOutcome =\n | { kind: 'held'; holder: WriterLease }\n | { kind: 'acquired'; leaseId: string; epoch: number; reclaimed?: WriterLease }\n | {\n kind: 'refused'\n reason: 'corrupt-epoch-state'\n error: CorruptEpochStateError\n }\n | {\n /**\n * CR-01 (round 5): the lease file's own sibling of `corrupt-epoch-state`.\n *\n * `code` is the raw errno so an operator sees EACCES rather than a contender that silently\n * spun to its deadline over an authority state nobody can evaluate; `error` keeps this arm\n * inside the union's stated contract that every refusal is rethrowable.\n */\n kind: 'refused'\n reason: 'unreadable-lease-state'\n code: string\n error: UnreadableWriterLeaseStateError\n }\n | {\n kind: 'refused'\n reason: 'mutation-lock-unreclaimable'\n /**\n * Both refusal arms carry a thrown-shaped `error` ON PURPOSE.\n *\n * Every caller of this union already renders `refused` as `[reason]: error.message` or\n * rethrows it, so a new arm that also carries one is surfaced by name at every entry point —\n * including any added later — without a list of call sites to keep in step. Naming the\n * refusal is the requirement; enumerating the callers who must name it is the failure mode\n * this phase keeps rediscovering.\n */\n error: WriterLeaseUnreclaimableError\n attempts: number\n waitedMs: number\n observedOwner?: UnreclaimableMutationLockOwner\n observedLease?: WriterLease\n }\n\nexport interface LeaseOperationOptions {\n knowledgeRoot: string\n leaseId: string\n}\n\n/** Test/chaos seam on the lease-file guard taken by `heartbeatLease` and `releaseLease`. */\nexport interface LeaseGuardHooks {\n /** Fires once, when the guard is first found held by a live section other than this caller's. */\n onLeaseGuardContended?: () => void\n /** Fires each time a guard has been judged residue, before this caller reclaims it. */\n beforeLeaseGuardReclaim?: () => void\n /** Fires inside a reclaim, after its first step and before its last. */\n duringLeaseGuardReclaim?: () => void\n}\n\nexport type HeartbeatLeaseOutcome =\n | { kind: 'heartbeated'; holder: WriterLease }\n | {\n kind: 'refused'\n reason:\n | 'lease-missing'\n | 'lease-malformed'\n /** CR-01: the lease exists and could not be opened — never write over what you cannot read. */\n | 'lease-unreadable'\n | 'lease-id-mismatch'\n | 'stale-epoch'\n | 'corrupt-epoch-state'\n holder?: WriterLease\n observedEpoch?: number\n error?: CorruptEpochStateError\n }\n\nexport type ReleaseLeaseOutcome =\n | { kind: 'released' }\n | {\n kind: 'refused'\n reason: 'lease-missing' | 'lease-malformed' | 'lease-unreadable' | 'lease-id-mismatch'\n holder?: WriterLease\n }\n\nexport interface AssertEpochCurrentOptions {\n knowledgeRoot: string\n epoch: number\n}\n\nexport type AssertEpochCurrentOutcome =\n | { current: true }\n | { current: false; observedEpoch: number }\n\n/** Exact writer identity carried by governed maintenance mutators. */\nexport interface WriterLeaseAuthority extends LeaseOperationOptions {\n epoch: number\n}\n\nexport type WriterAuthorityLostReason =\n | Extract<HeartbeatLeaseOutcome, { kind: 'refused' }>['reason']\n | 'epoch-mismatch-before-heartbeat'\n | 'epoch-mismatch-after-heartbeat'\n | 'mutation-lock-generation-lost'\n\n/** Fail-closed maintenance refusal with the holder and fresh disk epoch attached. */\nexport class WriterAuthorityLostError extends Error {\n override readonly name = 'WriterAuthorityLostError'\n readonly authority: WriterLeaseAuthority\n readonly reason: WriterAuthorityLostReason\n readonly observedEpoch: number\n\n constructor(\n authority: WriterLeaseAuthority,\n reason: WriterAuthorityLostReason,\n observedEpoch: number,\n ) {\n super(\n `writer authority lost (${reason}); held epoch ${authority.epoch}, observed ${observedEpoch}`,\n )\n this.authority = authority\n this.reason = reason\n this.observedEpoch = observedEpoch\n }\n}\n\nexport type CorruptEpochStateReason = 'unreadable' | 'malformed' | 'overflow'\n\n/** Fail-closed authority-state error; callers must never substitute epoch zero for this state. */\nexport class CorruptEpochStateError extends Error {\n override readonly name = 'CorruptEpochStateError'\n readonly path: string\n readonly reason: CorruptEpochStateReason\n readonly rawPreview: string\n\n constructor(path: string, reason: CorruptEpochStateReason, rawPreview: string) {\n super(`writer epoch state is corrupt (${reason}) at ${path}`)\n this.path = path\n this.reason = reason\n this.rawPreview = rawPreview\n }\n}\n\n/**\n * Fail-closed acquisition refusal after the deadline; carries why the wait could not end well.\n *\n * A contender that gives up is reporting a fact about the SYSTEM, not about itself, so the\n * diagnostics travel with the error: the owner it kept losing to, whether that owner was even\n * attributable (an unattributed row can never be escalated against, which is usually the whole\n * story), and the lease it kept reading. `agent-qa daemon` prints this and exits non-zero where it\n * previously hung with no output at all.\n */\nexport class WriterLeaseUnreclaimableError extends Error {\n override readonly name = 'WriterLeaseUnreclaimableError'\n readonly reason = 'mutation-lock-unreclaimable' as const\n readonly attempts: number\n readonly waitedMs: number\n readonly observedOwner?: UnreclaimableMutationLockOwner\n readonly observedLease?: WriterLease\n\n constructor(\n attempts: number,\n waitedMs: number,\n observedOwner?: UnreclaimableMutationLockOwner,\n observedLease?: WriterLease,\n ) {\n super(\n `writer lease acquisition refused (mutation-lock-unreclaimable) after ${attempts} `\n + `attempts over ${Math.round(waitedMs)}ms; `\n + (observedOwner === undefined\n ? 'no mutation-lock owner was readable'\n : `mutation lock held by pid ${observedOwner.pid} (generation `\n + `${observedOwner.generationToken}, incarnation `\n + `${observedOwner.incarnationAttributed ? 'attributed' : 'unattributed'})`)\n + '; '\n + (observedLease === undefined\n ? 'no parseable lease on disk'\n : `lease ${observedLease.leaseId} at epoch ${observedLease.epoch} held by pid `\n + `${observedLease.pid}`),\n )\n this.attempts = attempts\n this.waitedMs = waitedMs\n if (observedOwner !== undefined) this.observedOwner = observedOwner\n if (observedLease !== undefined) this.observedLease = observedLease\n }\n}\n\n/**\n * The lease file's sibling of `CorruptEpochStateError`, for a read that produced no throwable.\n *\n * `readFileSync` threw, but the value that reaches a consumer is a kinded outcome rather than an\n * exception, and `AcquireWriterLeaseOutcome`'s own contract is that EVERY refusal arm carries a\n * thrown-shaped `error` — three call sites rethrow or render it without knowing which arm they\n * hold (`drain.ts:842` among them). A refusal that carried only an errno string would have made\n * that contract a list of call sites to keep in step, which is the failure mode this module keeps\n * rediscovering. Deliberately not re-exported from the package index (IN-04): the refusal is fully\n * legible from `reason`, `code` and `error.message`.\n */\nexport class UnreadableWriterLeaseStateError extends Error {\n override readonly name = 'UnreadableWriterLeaseStateError'\n readonly path: string\n readonly code: string\n\n constructor(path: string, code: string) {\n super(`writer lease state is unreadable (${code}) at ${path}`)\n this.path = path\n this.code = code\n }\n}\n\n/**\n * The authority-file read verdict, and it has four values rather than three.\n *\n * Round-5 CR-01: `unreadable` is the sibling of the epoch read's\n * `CorruptEpochStateError(…, 'unreadable', …)`. A file that EXISTS and could not be opened is a\n * different fact from a file that is not there and from a file whose bytes were read and failed to\n * parse, and the previous three arms had nowhere to put it — so EACCES, EIO, EMFILE and ENFILE all\n * landed on `malformed`, which every consumer reads as \"nobody holds authority\". `code` carries\n * the errno so the refusal that follows can name the cause to an operator.\n */\nexport type ReadWriterLeaseOutcome =\n | { kind: 'absent' }\n | { kind: 'malformed' }\n | { kind: 'unreadable'; code: string }\n | { kind: 'parsed'; lease: WriterLease }\n\nfunction assertAbsoluteKnowledgeRoot(knowledgeRoot: string): void {\n if (!isAbsolute(knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n}\n\nfunction leasePath(knowledgeRoot: string): string {\n return join(knowledgeRoot, LEASE_FILE)\n}\n\nfunction epochPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, EPOCH_FILE)\n}\n\nfunction writerAuthorityDbPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, WRITER_AUTHORITY_DB_FILE)\n}\n\nfunction bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n code !== 'ENOENT' &&\n code !== 'EINVAL' &&\n code !== 'EISDIR' &&\n code !== 'EPERM' &&\n code !== 'ENOTSUP'\n ) {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\ninterface MutationLockOwner {\n pid: number\n acquiredAtMs: number\n generationToken: string\n /** OS-reported start-time token of the process that created this row; absent when unresolvable. */\n incarnation?: string\n}\n\n/**\n * Opaque process-incarnation token for one pid, anchored OUTSIDE any value this module writes.\n *\n * CR-04: a durable row's pid is not an identity. Once the recorded process dies, the kernel is\n * free to hand that number to a stranger, and every later decision keyed on the number alone\n * (above all `SIGKILL`) targets whoever holds it now. The one fact that distinguishes them is\n * assigned by the OS and cannot be forged from inside the store: when the process at that pid\n * started.\n *\n * Linux reads field 22 (`starttime`) of `/proc/<pid>/stat`, counted from the LAST `)` because the\n * `comm` field is parenthesised and may itself contain spaces and parentheses. Other POSIX hosts\n * read `/bin/ps -p <pid> -o lstart=` in the C locale and UTC, so every reader renders one start\n * time as one token. Windows has no equivalent builtin, so it resolves to `undefined` and every\n * incarnation check there fails closed.\n *\n * Returns `undefined` — never throws — whenever the pid cannot be attributed. `undefined` means\n * \"do not signal\", never \"safe to signal\".\n *\n * WR-04: `timeoutMs` bounds the POSIX arm's `ps` fork, which is the last wait beneath the\n * acquisition deadline that used to be able to outlive it — a wedged `ps` never returns, and this\n * resolution sits directly on the pre-signal path. A cap that expires resolves\n * through the SAME funnel every other failure uses (`undefined`), so a timed-out resolution is\n * unverifiable and therefore signal-ineligible. Callers with no budget of their own omit it.\n *\n * 386-32 consumes this same helper for the embedder-worker signal path, so both kill paths speak\n * one incarnation vocabulary.\n */\nexport function resolveProcessIncarnation(\n pid: number,\n timeoutMs?: number,\n psExecutable?: string,\n): string | undefined {\n if (!Number.isSafeInteger(pid) || pid <= 0) return undefined\n try {\n if (process.platform === 'win32') return undefined\n return process.platform === 'linux'\n ? resolveLinuxProcessIncarnation(pid)\n : resolvePosixProcessIncarnation(pid, timeoutMs, psExecutable)\n } catch {\n return undefined\n }\n}\n\nexport function incarnationFormat(token: string): string {\n const separator = token.indexOf(':')\n return separator < 0 ? '' : token.slice(0, separator)\n}\n\nfunction resolveLinuxProcessIncarnation(pid: number): string | undefined {\n let raw: string\n try {\n raw = readFileSync(`/proc/${pid}/stat`, 'utf8')\n } catch {\n return undefined\n }\n const commEnd = raw.lastIndexOf(')')\n if (commEnd < 0) return undefined\n // The first field after `comm` is `state` (field 3), so `starttime` (field 22) sits at index 19.\n const startTime = raw.slice(commEnd + 1).trim().split(/\\s+/)[19]\n return startTime !== undefined && /^\\d+$/.test(startTime)\n ? `proc-starttime:${startTime}`\n : undefined\n}\n\nfunction resolvePosixProcessIncarnation(\n pid: number,\n timeoutMs?: number,\n psExecutable: string = PROCESS_INCARNATION_PS_PATH,\n): string | undefined {\n // 2026-10-16 (442-14, GAP-D1): one rendering for every reader; the caller's PATH, TZ and\n // locale never reach ps.\n const observed = spawnSync(psExecutable, ['-p', String(pid), '-o', 'lstart='], {\n encoding: 'utf8',\n env: PROCESS_INCARNATION_PS_ENV,\n windowsHide: true,\n // `spawnSync` reads 0 as \"no timeout\", so an exhausted budget must never arrive here as 0.\n ...(timeoutMs === undefined ? {} : { timeout: Math.max(1, Math.ceil(timeoutMs)) }),\n })\n if (observed.error !== undefined || observed.status !== 0) return undefined\n const lstart = (observed.stdout ?? '').trim()\n return lstart === '' ? undefined : `ps-lstart-utc:${lstart}`\n}\n\nconst OWN_INCARNATION_UNRESOLVED = Symbol('own-incarnation-unresolved')\n/**\n * Only ever a RESOLVED token or the sentinel — `undefined` is deliberately not representable here.\n *\n * That is the whole of round-5 regression 2 in one type: storing `undefined` made \"the process\n * table did not answer this once\" indistinguishable from \"the process table answered, and the\n * answer is that there is nothing to say\", and the second reading is permanent.\n */\nlet ownIncarnation: string | typeof OWN_INCARNATION_UNRESOLVED = OWN_INCARNATION_UNRESOLVED\n\n/**\n * This process's own incarnation, resolved once SUCCESSFULLY and retried until then.\n *\n * A pid's start time is fixed for the life of the process, and this process is alive by\n * definition, so a resolved value cannot go stale. Memoising it keeps the per-claim cost off the\n * hot mutation path (the POSIX arm shells out to `ps`), and the accepting control in the corpus\n * asserts the hit path still forks exactly once per process.\n *\n * Two things this function's previous comment stated, both of which the call site contradicted:\n *\n * 1. It claimed the fork \"is not spending an escalation budget\". It is. The sole call site is\n * `withMutationLock`, which `acquireWriterLease` enters under `deadlineAtNs`, so a wedged\n * `ps` here spends the acquisition deadline exactly as the pre-signal fork does. WR-04's\n * clamp therefore applies to BOTH forks: `psIncarnationCapMs` degrades to the same flat\n * `PROCESS_INCARNATION_PS_TIMEOUT_MS` when the caller has no budget, so the heartbeat and\n * governed-mutation paths are unchanged, while a budgeted acquisition now caps this fork at\n * `clamp(remaining, FLOOR, TIMEOUT)` like every other wait beneath it.\n * 2. It memoised a MISS. One timed-out fork at startup then wrote `undefined` into the memo for\n * the life of the process, so every `mutation_lock` row that daemon ever wrote carried no\n * incarnation, `verifyMutationLockOwnerIdentity` answered `unverifiable` for all of them, and\n * no contender could ever escalate against it. Degraded liveness forever, from one fork.\n *\n * A miss is now a per-call answer: `undefined` is returned, the sentinel is left in place, and the\n * NEXT claim resolves again. There is no retry loop inside one call (that would spend the budget\n * this change exists to protect), no alternative resolver, and no default token — only a token the\n * OS assigned may replace the sentinel. The observer fires on every attempted resolution, because\n * a retry is a real `ps` fork and the cost being bounded has to stay countable.\n */\nfunction ownProcessIncarnation(escalation: MutationEscalationContext = {}): string | undefined {\n if (ownIncarnation !== OWN_INCARNATION_UNRESOLVED) return ownIncarnation\n const resolved = resolveProcessIncarnation(\n process.pid,\n psIncarnationCapMs(escalation),\n escalation.psExecutable,\n )\n escalation.onIncarnationResolved?.(process.pid)\n if (resolved === undefined) return undefined\n ownIncarnation = resolved\n return resolved\n}\n\nexport interface MutationLockOptions {\n /** Test/chaos seam after the claim is committed and before the held transaction begins. */\n afterMutationLockClaimed?: (generationToken: string) => void\n afterMutationLockAcquired?: () => void\n /** Test/chaos seam inside acquisition, after the epoch rewrite and before lease publication. */\n afterEpochRewrite?: () => void\n mutationLockTakeoverMs?: number\n /**\n * Test-only observation of every process-incarnation resolution the escalation path performs.\n *\n * Purely an observer, never a replacement: the production resolver still runs, so what a test\n * counts is what a daemon pays. It exists because the cost being bounded (a `ps` fork per\n * resolution, on the caller's main thread) is invisible to any assertion about outcomes.\n */\n onProcessIncarnationResolved?: (pid: number) => void\n // Test-only replacement for `/bin/ps`, for a wedged process table; production never sets it.\n psExecutable?: string\n}\n\n/**\n * The caller's remaining budget and observation hooks, threaded down the escalation path.\n *\n * W-05: the escalation is reached from `acquireWriterLease`, which owns a deadline; every wait it\n * performs is therefore spending someone else's time. Passing that fact down — rather than letting\n * each wait consult its own pinned constant — is what makes the deadline a real bound instead of\n * an approximate one. The relationship must hold structurally: the current constants happen to\n * satisfy it arithmetically (45 s takeover + 5 s termination < 60 s deadline), but an assertion\n * that rests on that coincidence would survive any retuning that broke it.\n */\ninterface MutationEscalationContext {\n /** Absolute monotonic instant past which no escalation wait may continue; absent = no budget. */\n readonly deadlineAtNs?: bigint\n readonly onIncarnationResolved?: (pid: number) => void\n readonly psExecutable?: string\n}\n\nexport interface AcquireWriterLeaseOptions extends MutationLockOptions {\n /**\n * Test/chaos seam for the pinned acquisition deadline; production never sets it.\n *\n * The same shape as `mutationLockTakeoverMs` and the heartbeat supervisor's `stopTimeoutMs`: a\n * real unreclaimable wait is 60 s, which no test can afford to sit through, and shortening the\n * window is the only way to reach the refusal branch (D-15 — a seam, never a config key).\n */\n acquireDeadlineMs?: number\n}\n\nexport interface CurrentWriterAuthority {\n leaseId: string\n epoch: number\n}\n\nexport interface CurrentWriterAuthorityHooks extends MutationLockOptions {\n /** Test/chaos seam after the lock-held epoch comparison and before mutation. */\n afterFinalAuthorityCompare?: () => void\n}\n\nclass MutationLockBusyError extends Error {\n override readonly name = 'MutationLockBusyError'\n readonly owner?: MutationLockOwner\n\n constructor(owner?: MutationLockOwner) {\n super('writer lease mutation lock is busy')\n this.owner = owner\n }\n}\n\nclass MutationLockGenerationLostError extends Error {\n override readonly name = 'MutationLockGenerationLostError'\n}\n\nclass LeaseGuardBusyError extends Error {\n override readonly name = 'LeaseGuardBusyError'\n}\n\nfunction mutationLockNowMs(): number {\n return new Date().getTime()\n}\n\n/**\n * Elapsed milliseconds from a `process.hrtime.bigint()` reading, immune to wall-clock movement.\n *\n * The acquisition deadline must not be extendable by anything the contended state can influence,\n * and a wall clock can be stepped backwards by NTP or by a test's own `Date.now` stub. This is the\n * external anchor the bound is measured against.\n */\nfunction monotonicElapsedMs(startedAtNs: bigint): number {\n return Number(process.hrtime.bigint() - startedAtNs) / 1e6\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ESRCH') return false\n if (code === 'EPERM') return true\n throw error\n }\n}\n\nfunction isSqliteBusy(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /database is (?:locked|busy)/i.test((error as Error).message)\n}\n\nfunction openWriterAuthorityDb(knowledgeRoot: string): DatabaseSync {\n mkdirSync(knowledgeRoot, { recursive: true })\n const db = new DatabaseSync(writerAuthorityDbPath(knowledgeRoot), {\n timeout: MUTATION_LOCK_BUSY_TIMEOUT_MS,\n })\n try {\n db.exec('PRAGMA journal_mode = WAL')\n db.exec(`PRAGMA busy_timeout = ${MUTATION_LOCK_BUSY_TIMEOUT_MS}`)\n db.exec(`\n CREATE TABLE IF NOT EXISTS mutation_lock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n generation_token TEXT NOT NULL,\n pid INTEGER NOT NULL CHECK (pid > 0),\n acquired_at_ms INTEGER NOT NULL CHECK (acquired_at_ms >= 0),\n incarnation TEXT\n ) STRICT\n `)\n upgradeMutationLockSchema(db)\n return db\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/**\n * Add the incarnation column to a store created before CR-04 shipped.\n *\n * The authority database is transient lock state, not knowledge, so this needs no data-migration\n * plan: an inherited row keeps a NULL incarnation and is therefore unattributed, which fails the\n * signal check closed. That is the correct reading — nothing on disk can say which process wrote\n * a row that predates the column.\n *\n * W-06: the check and the ALTER are not one transaction and cannot be, because the ALTER is itself\n * the schema change every reader would have to serialize behind. Two daemons starting against one\n * legacy store therefore both decide the column is missing, and the loser's ALTER — which blocks on\n * the winner's write lock and then re-prepares against the new schema — fails with\n * `duplicate column name`. `isSqliteBusy` does not match that message, so it used to escape as a\n * raw SqliteError and kill a starting daemon over a race whose OUTCOME WAS ALREADY CORRECT: the\n * column exists, which is the entire postcondition. Losing this race is success, so it is reported\n * as success. Every other error still propagates.\n */\nfunction upgradeMutationLockSchema(db: DatabaseSync): void {\n const columns = db.prepare(`\n SELECT name FROM pragma_table_info('mutation_lock')\n `).all() as { name: string }[]\n if (columns.some((column) => column.name === 'incarnation')) return\n try {\n db.exec('ALTER TABLE mutation_lock ADD COLUMN incarnation TEXT')\n } catch (error) {\n if (!isDuplicateMutationLockColumn(error)) throw error\n }\n}\n\n/** Classified by message beside `isMissingMutationLockTable`, which node:sqlite likewise untypes. */\nfunction isDuplicateMutationLockColumn(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /duplicate column name/i.test((error as Error).message)\n}\n\nfunction parseMutationLockOwner(value: unknown): MutationLockOwner | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const row = value as Record<string, unknown>\n return typeof row.pid === 'number'\n && Number.isSafeInteger(row.pid)\n && row.pid > 0\n && typeof row.acquired_at_ms === 'number'\n && Number.isSafeInteger(row.acquired_at_ms)\n && row.acquired_at_ms >= 0\n && typeof row.generation_token === 'string'\n && row.generation_token !== ''\n ? {\n pid: row.pid,\n acquiredAtMs: row.acquired_at_ms,\n generationToken: row.generation_token,\n // A row written before the incarnation column existed, or by a claimant that could not\n // resolve its own start time, is deliberately left unattributed rather than guessed at.\n ...(typeof row.incarnation === 'string' && row.incarnation !== ''\n ? { incarnation: row.incarnation }\n : {}),\n }\n : undefined\n}\n\nfunction readMutationLockOwner(db: DatabaseSync): MutationLockOwner | undefined {\n // `SELECT *` so a store that predates the incarnation column still reads through a read-only\n // connection, which has no opportunity to upgrade the schema.\n return parseMutationLockOwner(db.prepare(`\n SELECT * FROM mutation_lock WHERE id = 1\n `).get())\n}\n\n/**\n * Read the committed lock owner as a TYPED ABSENCE, never as a throw.\n *\n * Contract: every reason the owner cannot be read answers `undefined` — absent store, table not\n * created yet, and (WR-05) a store too busy to answer. Both callers already read `undefined` as\n * \"no attributable owner\": the busy-catch in `withMutationLock` puts it on a\n * `MutationLockBusyError`, and the acquisition deadline puts it on the typed\n * `mutation-lock-unreclaimable` refusal. A raw `SqliteError` escaping here therefore reached\n * neither of those promises — it propagated out of `acquireWriterLease` uncaught and killed a\n * starting daemon over contention, which is exactly the state the refusal exists to name.\n * Every other error still propagates.\n */\nfunction readCommittedMutationLockOwner(\n knowledgeRoot: string,\n): MutationLockOwner | undefined {\n try {\n const db = new DatabaseSync(writerAuthorityDbPath(knowledgeRoot), {\n readOnly: true,\n timeout: 0,\n })\n try {\n return readMutationLockOwner(db)\n } finally {\n db.close()\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n // A store file whose `mutation_lock` table does not exist yet reads exactly like an absent\n // store: nobody has committed a claim. This is reachable — `openWriterAuthorityDb` creates\n // the store file before `CREATE TABLE`, so a contender that loses the write lock in that\n // window arrives here and used to crash the daemon with a raw SQL logic error instead of\n // reporting contention.\n if (isMissingMutationLockTable(error)) return undefined\n // A store whose write lock is held by someone else answers nothing about who committed a\n // claim. `timeout: 0` is deliberate — this read is diagnostics on a path that has already\n // decided to refuse, so waiting on it would spend budget to learn a detail.\n if (isSqliteBusy(error)) return undefined\n throw error\n }\n}\n\nfunction isMissingMutationLockTable(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /no such table: mutation_lock/i.test((error as Error).message)\n}\n\nfunction mutationLockGenerationIsCurrent(\n db: DatabaseSync,\n generationToken: string,\n): boolean {\n return readMutationLockOwner(db)?.generationToken === generationToken\n}\n\nfunction compareAndSwapMutationLock(\n db: DatabaseSync,\n expected: MutationLockOwner,\n replacement: MutationLockOwner,\n): boolean {\n const result = db.prepare(`\n UPDATE mutation_lock\n SET generation_token = ?, pid = ?, acquired_at_ms = ?, incarnation = ?\n WHERE id = 1 AND generation_token = ?\n `).run(\n replacement.generationToken,\n replacement.pid,\n replacement.acquiredAtMs,\n replacement.incarnation ?? null,\n expected.generationToken,\n )\n return result.changes === 1\n}\n\n/** What the caller has left of its acquisition budget, or `undefined` when it declared none. */\nfunction remainingEscalationBudgetMs(escalation: MutationEscalationContext): number | undefined {\n if (escalation.deadlineAtNs === undefined) return undefined\n return Math.max(Number(escalation.deadlineAtNs - process.hrtime.bigint()) / 1e6, 0)\n}\n\n/**\n * Poll a signalled owner's disappearance, bounded by the CALLER'S remaining budget (W-05).\n *\n * The wait is synchronous on the caller's main thread, so its cost is charged to whoever asked for\n * the lock. Bounding it by MUTATION_LOCK_TERMINATION_TIMEOUT_MS alone let an acquisition overrun\n * its own deadline by that whole window, and the overrun was not hypothetical: SIGKILL cannot be\n * survived, but a killed child of a process that never returns to its event loop is never reaped,\n * so `kill(pid, 0)` keeps answering \"alive\" indefinitely. A daemon spinning synchronously on its\n * main thread is exactly the V-02 shape this phase reproduced, and its children are exactly those.\n *\n * The bound is therefore the MINIMUM of the pinned window and the time the caller has left. An\n * exhausted budget waits not at all and reports that the exit was NOT confirmed — a refusal to\n * reclaim, never a licence to CAS over an owner whose death was never observed. Elapsed time is\n * measured from `process.hrtime.bigint()` for the same reason the acquisition deadline is: a wall\n * clock can be stepped, and this loop's only exit must not be steppable.\n */\nfunction waitForVerifiedProcessExit(\n pid: number,\n escalation: MutationEscalationContext,\n): boolean {\n const startedAtNs = process.hrtime.bigint()\n const remainingMs = remainingEscalationBudgetMs(escalation)\n const boundMs = remainingMs === undefined\n ? MUTATION_LOCK_TERMINATION_TIMEOUT_MS\n : Math.min(MUTATION_LOCK_TERMINATION_TIMEOUT_MS, remainingMs)\n while (processIsAlive(pid)) {\n if (monotonicElapsedMs(startedAtNs) >= boundMs) return false\n Atomics.wait(\n MUTATION_LOCK_TERMINATION_WAIT,\n 0,\n 0,\n MUTATION_LOCK_TERMINATION_POLL_MS,\n )\n }\n return true\n}\n\ntype MutationLockOwnerIdentity = 'match' | 'mismatch' | 'unverifiable'\n\n/**\n * The `ps` fork's share of the caller's remaining budget (WR-04).\n *\n * The caller's remainder is the ceiling, which is what stops one fork from spending a deadline it\n * does not own. The FLOOR is the part that had to be argued for, because it is the one place this\n * cap can overshoot: an acquisition whose busy-timeout already consumed the whole deadline arrives\n * here with nothing left, and a zero-length cap would mean the identity of a genuinely stale owner\n * can never be re-read at all — turning \"the wait is budgeted\" (W-05) into \"the verified kill is\n * cancelled\", which is a different decision and one 386-40 pinned in the other direction.\n *\n * So the fork always gets one short, PINNED allowance: the overshoot is bounded by that constant\n * rather than by however long a wedged `ps` feels like taking, which is the whole subject of WR-04.\n * A zero-length cap would also be worse than useless mechanically — `spawnSync` reads 0 as \"no\n * timeout\" and would UNBOUND the fork entirely.\n *\n * What the floor does NOT do is buy permission: an expired cap still answers `undefined`, which\n * still answers `unverifiable`, which is still a refusal to signal. No default token, no retry.\n */\nfunction psIncarnationCapMs(escalation: MutationEscalationContext): number {\n const remainingMs = remainingEscalationBudgetMs(escalation)\n return Math.max(PROCESS_INCARNATION_PS_FLOOR_MS, Math.min(\n PROCESS_INCARNATION_PS_TIMEOUT_MS,\n remainingMs ?? PROCESS_INCARNATION_PS_TIMEOUT_MS,\n ))\n}\n\n/**\n * Compare the row's recorded incarnation against the pid's CURRENT occupant.\n *\n * An unattributed row (legacy bytes, or a claimant that could not resolve its own start time) and\n * an unresolvable pid both answer `unverifiable`, which is a refusal to signal — never a licence.\n * WR-04: a pid the process table will not report on INSIDE the caller's budget joins that second\n * class rather than extending the deadline, because the resolution sits on the pre-signal path.\n */\nfunction verifyMutationLockOwnerIdentity(\n owner: MutationLockOwner,\n escalation: MutationEscalationContext,\n): MutationLockOwnerIdentity {\n if (owner.incarnation === undefined) return 'unverifiable'\n const occupant = resolveProcessIncarnation(\n owner.pid,\n psIncarnationCapMs(escalation),\n escalation.psExecutable,\n )\n escalation.onIncarnationResolved?.(owner.pid)\n if (occupant === undefined) return 'unverifiable'\n if (incarnationFormat(occupant) !== incarnationFormat(owner.incarnation)) return 'unverifiable'\n return occupant === owner.incarnation ? 'match' : 'mismatch'\n}\n\n/**\n * CR-04: the generation token authenticates the ROW, not the process now occupying its pid.\n *\n * The pid's current incarnation is therefore re-resolved immediately before the signal, and the\n * three answers are genuinely different outcomes:\n *\n * match the process that created this row is still there — SIGKILL and confirm ESRCH,\n * exactly the Plan 20 verified-termination semantics.\n * mismatch the recorded process is gone and a stranger inherited its pid. A reused pid is\n * EVIDENCE OF DEATH, not a target: report success so the caller's generation\n * re-read and CAS reclaim the row with no signal delivered at all.\n * unverifiable fail closed. Refusing escalation can wedge a contender until the occupant really\n * exits (T-386-31-02); signalling an unattributable pid is local arbitrary-process\n * termination. Only one of those is recoverable.\n */\nfunction terminateExactMutationLockOwner(\n owner: MutationLockOwner,\n escalation: MutationEscalationContext,\n): boolean {\n if (owner.pid === process.pid) return false\n const identity = verifyMutationLockOwnerIdentity(owner, escalation)\n if (identity === 'unverifiable') return false\n if (identity === 'mismatch') return true\n try {\n process.kill(owner.pid, 'SIGKILL')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ESRCH') {\n if (code === 'EPERM') return false\n throw error\n }\n }\n return waitForVerifiedProcessExit(owner.pid, escalation)\n}\n\n/**\n * Escalation ends in SIGKILL, so this consumer names `unknown` AND `unreadable` as refusals.\n *\n * A wrong kill is unrecoverable; a contender that declines to kill is not. `reclaimable` is the\n * only verdict that permits, which means a live holder is escalated against exactly when its lease\n * has genuinely aged out or names a superseded epoch — never because the epoch could not be read,\n * and never because the lease could not be read.\n *\n * CR-01 (round 5): the read arms are an exhaustive ladder rather than a `!== 'parsed'`\n * short-circuit. That short-circuit was a fourth conjunct sitting one line ABOVE the derivation\n * the same round moved the third conjunct INTO, and it permitted the kill for the one input class\n * the derivation exists to refuse. `absent` and `malformed` still permit — a lease file that is\n * missing, or whose bytes were read and are not a lease, is recovery input — but a file that\n * exists and could not be opened is no evidence at all.\n *\n * This veto is the LAST lease guard on the governed-mutation contention path: a contender that\n * enters through `withCurrentWriterAuthority` (a fenced-out writer retrying its commit) claims the\n * mutation lock before it reads any lease, so `acquireWriterLease`'s pre-check never runs for it.\n * That path is what makes this gate reachable, and it is pinned by a corpus case that reddens when\n * the veto is removed (WINDOWS #46).\n */\nfunction leasePermitsEscalation(knowledgeRoot: string, owner: MutationLockOwner): boolean {\n if (!processIsAlive(owner.pid)) return true\n const lease = readWriterLease(knowledgeRoot)\n switch (lease.kind) {\n case 'absent':\n case 'malformed':\n return true\n case 'unreadable':\n return false\n case 'parsed':\n return deriveWriterLeaseFreshness(\n knowledgeRoot,\n lease.lease,\n mutationLockNowMs(),\n ).kind === 'reclaimable'\n }\n}\n\nfunction tryEscalatedMutationLockTakeover(\n db: DatabaseSync,\n knowledgeRoot: string,\n expected: MutationLockOwner,\n replacement: MutationLockOwner,\n takeoverMs: number,\n escalation: MutationEscalationContext,\n): boolean {\n if (mutationLockNowMs() - expected.acquiredAtMs < takeoverMs) return false\n if (!leasePermitsEscalation(knowledgeRoot, expected)) return false\n if (\n processIsAlive(expected.pid)\n && !terminateExactMutationLockOwner(expected, escalation)\n ) {\n return false\n }\n\n const observedAfterTermination = readMutationLockOwner(db)\n if (observedAfterTermination?.generationToken !== expected.generationToken) return false\n try {\n return compareAndSwapMutationLock(db, expected, replacement)\n } catch (error) {\n // A mismatched incarnation reclaims without killing anything, so the write lock can still be\n // held by whoever made the store busy. That is an ordinary retry, not a failure to surface.\n if (isSqliteBusy(error)) return false\n throw error\n }\n}\n\nfunction claimMutationLock(\n db: DatabaseSync,\n knowledgeRoot: string,\n owner: MutationLockOwner,\n takeoverMs: number,\n escalation: MutationEscalationContext,\n): void {\n try {\n const inserted = db.prepare(`\n INSERT INTO mutation_lock (id, generation_token, pid, acquired_at_ms, incarnation)\n VALUES (1, ?, ?, ?, ?)\n ON CONFLICT(id) DO NOTHING\n `).run(\n owner.generationToken,\n owner.pid,\n owner.acquiredAtMs,\n owner.incarnation ?? null,\n )\n if (inserted.changes === 1) return\n } catch (error) {\n if (!isSqliteBusy(error)) throw error\n const current = readMutationLockOwner(db)\n if (\n current !== undefined\n && tryEscalatedMutationLockTakeover(\n db,\n knowledgeRoot,\n current,\n owner,\n takeoverMs,\n escalation,\n )\n ) {\n return\n }\n throw new MutationLockBusyError(current)\n }\n\n const current = readMutationLockOwner(db)\n if (current === undefined) {\n throw new MutationLockBusyError()\n }\n\n const ownerIsDead = !processIsAlive(current.pid)\n const ownerPastDeadline =\n mutationLockNowMs() - current.acquiredAtMs >= takeoverMs\n if (!ownerIsDead && !ownerPastDeadline) {\n throw new MutationLockBusyError(current)\n }\n\n try {\n if (compareAndSwapMutationLock(db, current, owner)) return\n } catch (error) {\n if (!isSqliteBusy(error)) throw error\n if (\n tryEscalatedMutationLockTakeover(\n db,\n knowledgeRoot,\n current,\n owner,\n takeoverMs,\n escalation,\n )\n ) {\n return\n }\n throw new MutationLockBusyError(current)\n }\n throw new MutationLockBusyError(readMutationLockOwner(db))\n}\n\nfunction releaseMutationLock(db: DatabaseSync, generationToken: string): void {\n db.prepare(`\n DELETE FROM mutation_lock\n WHERE id = 1 AND generation_token = ?\n `).run(generationToken)\n}\n\nfunction withMutationLock<T>(\n knowledgeRoot: string,\n mutate: (generationToken: string, db: DatabaseSync) => T,\n options: MutationLockOptions = {},\n /**\n * The caller's acquisition deadline, when it has one.\n *\n * Only `acquireWriterLease` does: a heartbeat or a governed mutation is not racing a bound, so\n * omitting it leaves those paths on the pinned termination window exactly as before.\n */\n deadlineAtNs?: bigint,\n): T {\n const escalation: MutationEscalationContext = {\n ...(deadlineAtNs === undefined ? {} : { deadlineAtNs }),\n ...(options.onProcessIncarnationResolved === undefined\n ? {}\n : { onIncarnationResolved: options.onProcessIncarnationResolved }),\n ...(options.psExecutable === undefined ? {} : { psExecutable: options.psExecutable }),\n }\n let db: DatabaseSync\n try {\n db = openWriterAuthorityDb(knowledgeRoot)\n } catch (error) {\n if (isSqliteBusy(error)) {\n throw new MutationLockBusyError(\n readCommittedMutationLockOwner(knowledgeRoot),\n )\n }\n throw error\n }\n const claimantIncarnation = ownProcessIncarnation(escalation)\n const owner: MutationLockOwner = {\n pid: process.pid,\n acquiredAtMs: mutationLockNowMs(),\n generationToken: randomUUID(),\n // A claimant that cannot prove its own incarnation records none, accepting that its row may\n // then only ever be reclaimed after it really dies. Never a fabricated token.\n ...(claimantIncarnation === undefined ? {} : { incarnation: claimantIncarnation }),\n }\n const takeoverMs = options.mutationLockTakeoverMs ?? MUTATION_LOCK_TAKEOVER_MS\n let claimed = false\n let transactionOpen = false\n try {\n claimMutationLock(db, knowledgeRoot, owner, takeoverMs, escalation)\n claimed = true\n options.afterMutationLockClaimed?.(owner.generationToken)\n try {\n db.exec('BEGIN IMMEDIATE')\n transactionOpen = true\n } catch (error) {\n if (isSqliteBusy(error)) throw new MutationLockBusyError(readMutationLockOwner(db))\n throw error\n }\n\n if (!mutationLockGenerationIsCurrent(db, owner.generationToken)) {\n throw new MutationLockGenerationLostError()\n }\n options.afterMutationLockAcquired?.()\n const result = mutate(owner.generationToken, db)\n db.exec('COMMIT')\n transactionOpen = false\n return result\n } finally {\n if (transactionOpen) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // The original failure is authoritative.\n }\n }\n if (claimed) {\n try {\n releaseMutationLock(db, owner.generationToken)\n } catch {\n // A crashed/contended cleanup leaves a CAS-recoverable row.\n }\n }\n db.close()\n }\n}\n\nfunction sweepStagedEpochsBefore(knowledgeRoot: string, epoch: number): void {\n const memoryRoot = join(knowledgeRoot, 'memory')\n let products: Dirent<string>[]\n try {\n products = readdirSync(memoryRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n\n for (const product of products) {\n if (!product.isDirectory()) continue\n const bundlesDir = join(memoryRoot, product.name, 'bundles')\n const stagingRoot = join(bundlesDir, '.staging')\n let staged: Dirent<string>[]\n try {\n staged = readdirSync(stagingRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue\n throw error\n }\n for (const entry of staged) {\n if (!entry.isDirectory()) continue\n const match = /^\\.staged-epoch-(\\d+)-[A-Za-z0-9._-]+$/.exec(entry.name)\n if (match === null) continue\n const stagedEpoch = Number(match[1])\n if (!Number.isSafeInteger(stagedEpoch) || stagedEpoch >= epoch) continue\n rmSync(join(stagingRoot, entry.name), { recursive: true, force: true })\n }\n if (existsSync(stagingRoot)) bestEffortFsyncDirectory(stagingRoot)\n try {\n rmdirSync(stagingRoot)\n bestEffortFsyncDirectory(bundlesDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n }\n}\n\nfunction atomicRewrite(file: string, text: string): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n bestEffortFsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\nconst leaseGuardOwnerSchema = z\n .object({\n pid: z.number().int().positive(),\n threadId: z.number().int().nonnegative(),\n token: z.string().uuid(),\n claimedAtNs: z.string().regex(/^[0-9]+$/),\n })\n .strict()\n\ntype LeaseGuardOwner = z.infer<typeof leaseGuardOwnerSchema>\n\ntype ObservedLeaseGuard =\n | { kind: 'vacant' }\n | { kind: 'held'; ownerFile: string; owner?: LeaseGuardOwner }\n\nfunction ignoreErrno(run: () => void, codes: readonly string[]): void {\n try {\n run()\n } catch (error) {\n if (!codes.includes((error as NodeJS.ErrnoException).code ?? '')) throw error\n }\n}\n\nfunction errnoOf(error: unknown): string {\n return (error as NodeJS.ErrnoException).code ?? ''\n}\n\n/** `lstat` that answers `undefined` for a missing entry; it never follows a link. */\nfunction lstatOrAbsent(path: string): Stats | undefined {\n try {\n return lstatSync(path)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return undefined\n throw error\n }\n}\n\n/** Move a directory nothing can attribute aside, whole: its entries are never ours to delete. */\nfunction moveLeaseGuardAside(guard: string): void {\n const aside = join(dirname(guard), `${LEASE_GUARD_RESIDUE_PREFIX}${randomUUID()}`)\n ignoreErrno(() => renameSync(guard, aside), ['ENOENT'])\n}\n\n/** Read an owner file without following a link or blocking on a special file. */\nfunction readLeaseGuardOwner(path: string, name: string): LeaseGuardOwner | undefined {\n const fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK)\n let raw: string\n try {\n raw = readFileSync(fd, 'utf8')\n } finally {\n closeSync(fd)\n }\n try {\n const parsed = leaseGuardOwnerSchema.safeParse(JSON.parse(raw))\n return parsed.success && `${LEASE_GUARD_OWNER_PREFIX}${parsed.data.token}` === name\n ? parsed.data\n : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe the guard path without ever reaching through it (CR-01).\n *\n * A guard is only ever a real directory holding one regular `owner-<token>` file. Anything else at\n * the path, a symlink wherever it points or a plain file, is removed as an entry: `unlink` removes\n * a link, never its target. A directory nothing can attribute (entries but no owner, or an owner\n * that is not a regular file) is moved aside whole and its entries are never unlinked; no live\n * guard can look like that, because a guard is only published by renaming a staged directory onto\n * an empty one.\n */\nfunction observeLeaseGuard(guard: string): ObservedLeaseGuard {\n const stat = lstatOrAbsent(guard)\n if (stat === undefined) return { kind: 'vacant' }\n if (!stat.isDirectory()) {\n ignoreErrno(() => unlinkSync(guard), ['ENOENT', 'EISDIR', 'EPERM'])\n return { kind: 'vacant' }\n }\n let names: string[]\n try {\n names = readdirSync(guard)\n } catch (error) {\n // Replaced between the two calls: the next observation judges whatever is there now.\n if (errnoOf(error) === 'ENOENT' || errnoOf(error) === 'ENOTDIR') return { kind: 'vacant' }\n throw error\n }\n if (names.length === 0) {\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n return { kind: 'vacant' }\n }\n const ownerFile = names.filter((name) => name.startsWith(LEASE_GUARD_OWNER_PREFIX)).sort()[0]\n const ownerStat = ownerFile === undefined ? undefined : lstatOrAbsent(join(guard, ownerFile))\n if (ownerFile === undefined || (ownerStat !== undefined && !ownerStat.isFile())) {\n moveLeaseGuardAside(guard)\n return { kind: 'vacant' }\n }\n if (ownerStat === undefined) return { kind: 'vacant' }\n let owner: LeaseGuardOwner | undefined\n try {\n owner = readLeaseGuardOwner(join(guard, ownerFile), ownerFile)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return { kind: 'vacant' }\n if (errnoOf(error) === 'ELOOP') {\n moveLeaseGuardAside(guard)\n return { kind: 'vacant' }\n }\n throw error\n }\n return owner === undefined ? { kind: 'held', ownerFile } : { kind: 'held', ownerFile, owner }\n}\n\n/**\n * Sweep staging directories a holder leaked by dying between staging and claiming (IN-24).\n *\n * A staging directory is exactly one owner file in a real directory, and lives no longer than its\n * waiter, so one is swept only when its owner is residue under that longer bound (or its process\n * is gone). The sweep is the same compare-and-swap as a reclaim: the owner's own name, then\n * `rmdir`. A link, or a directory holding anything else, is left exactly as it is. Housekeeping\n * only: nothing here may fail the section.\n */\nfunction sweepLeakedLeaseGuardStaging(parent: string, ownStaged: string): void {\n let names: string[]\n try {\n names = readdirSync(parent)\n } catch {\n return\n }\n for (const name of names) {\n if (!name.startsWith(LEASE_GUARD_STAGING_PREFIX)) continue\n const dir = join(parent, name)\n if (dir === ownStaged) continue\n try {\n sweepLeakedStagingDirectory(dir)\n } catch {\n // Left for a later sweep.\n }\n }\n}\n\nfunction sweepLeakedStagingDirectory(dir: string): void {\n const stat = lstatOrAbsent(dir)\n if (stat === undefined || !stat.isDirectory()) return\n const entries = readdirSync(dir)\n // Wall clock, not `Date.now()`: the beat's only `Date.now()` is a seam the race cells use.\n const nowMs = mutationLockNowMs()\n if (entries.length === 0) {\n // Staged, not yet written: judged by its own age only.\n if (nowMs - stat.mtimeMs >= LEASE_GUARD_STAGING_STALE_MS) {\n ignoreErrno(() => rmdirSync(dir), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n }\n return\n }\n const ownerFile = entries[0]!\n if (entries.length !== 1 || !ownerFile.startsWith(LEASE_GUARD_OWNER_PREFIX)) return\n const ownerPath = join(dir, ownerFile)\n const ownerStat = lstatOrAbsent(ownerPath)\n if (ownerStat === undefined || !ownerStat.isFile()) return\n const owner = readLeaseGuardOwner(ownerPath, ownerFile)\n // An owner being written can read as nothing yet, so unattributable bytes wait out the bound.\n const residue = owner === undefined\n ? nowMs - ownerStat.mtimeMs >= LEASE_GUARD_STAGING_STALE_MS\n : leaseGuardOwnerIsResidue(owner, LEASE_GUARD_STAGING_STALE_MS)\n if (!residue) return\n ignoreErrno(() => unlinkSync(ownerPath), ['ENOENT'])\n ignoreErrno(() => rmdirSync(dir), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n}\n\n/**\n * True when no live section can still be behind the guard.\n *\n * Unattributable owner bytes are residue. So is a claim from a dead process, one older than the\n * bound (a thread terminated inside its section leaves its live process's pid behind), and one\n * stamped ahead of this monotonic clock, which can only come from a previous boot.\n */\nfunction leaseGuardIsResidue(owner: LeaseGuardOwner | undefined): boolean {\n if (owner === undefined) return true\n return leaseGuardOwnerIsResidue(owner, LEASE_GUARD_STALE_MS)\n}\n\nfunction leaseGuardOwnerIsResidue(owner: LeaseGuardOwner, staleMs: number): boolean {\n const ageMs = Number(process.hrtime.bigint() - BigInt(owner.claimedAtNs)) / 1e6\n if (ageMs < 0 || ageMs >= staleMs) return true\n return owner.pid !== process.pid && !processIsAlive(owner.pid)\n}\n\n/**\n * Reclaim a stale guard by compare-and-swap, never by moving whatever sits at the path.\n *\n * The compare is the owner file's NAME: only the stale owner's own file is unlinked. The swap is\n * `rmdir`, which removes the directory only if that left it empty. A live guard is a different\n * owner name inside a non-empty directory, so a second reclaimer of the same stale owner, however\n * late, removes nothing of it (261002-lse follow-up).\n */\nfunction reclaimLeaseGuard(guard: string, ownerFile: string, hooks: LeaseGuardHooks): void {\n ignoreErrno(() => unlinkSync(join(guard, ownerFile)), ['ENOENT'])\n hooks.duringLeaseGuardReclaim?.()\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n}\n\nfunction releaseLeaseGuard(guard: string, ownerFile: string): void {\n try {\n unlinkSync(join(guard, ownerFile))\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n } catch {\n // Whatever is left is residue, and the age bound reclaims it.\n }\n}\n\n/**\n * Run one lease-file section under the guard shared by `heartbeatLease` and `releaseLease`.\n *\n * Claiming is renaming a staged directory onto the guard path, which succeeds only where no guard\n * or an empty one sits. Governed mutations and acquisitions never take the guard, so a mutation of\n * any length cannot starve the beat (CR-03 stands) and a beat cannot block an acquisition. Waiting\n * is bounded by LEASE_GUARD_WAIT_MS, which outlasts the residue bound so that a guard left by a\n * terminated thread of this process is always reclaimed in time (WR-11); a guard held by an\n * enclosing section on this very thread can never be let go by waiting, so that claim fails at\n * once. Nothing here reaches through a link or out of the knowledge root (CR-01).\n */\nfunction withLeaseGuard<T>(\n knowledgeRoot: string,\n section: () => T,\n hooks: LeaseGuardHooks = {},\n): T {\n const guard = join(knowledgeRoot, LEASE_GUARD_DIR)\n // CR-01: nothing is created, claimed or removed through a chain that leaves the root.\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(guard))\n const claimedAtNs = process.hrtime.bigint()\n const token = randomUUID()\n const ownerFile = `${LEASE_GUARD_OWNER_PREFIX}${token}`\n const raw = `${JSON.stringify({\n pid: process.pid,\n threadId,\n token,\n claimedAtNs: String(claimedAtNs),\n })}\\n`\n const parent = dirname(guard)\n // `memory/queue/` and `memory/` are created only when absent, and removed again only by `rmdir`\n // (so only while empty), keeping a lease round-trip from leaving anything under `memory/`.\n const createdAncestors = [parent, dirname(parent)].filter((dir) => !existsSync(dir))\n const staged = `${guard}.tmp-${randomUUID()}`\n let contended = false\n try {\n try {\n while (true) {\n mkdirSync(parent, { recursive: true })\n try {\n mkdirSync(staged)\n break\n } catch (error) {\n // Another section's cleanup removed the empty parent between the two calls.\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n }\n writeFileSync(join(staged, ownerFile), raw, { encoding: 'utf8', flag: 'wx' })\n while (true) {\n try {\n renameSync(staged, guard)\n break\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOTEMPTY' && code !== 'EEXIST' && code !== 'ENOTDIR') throw error\n }\n const observed = observeLeaseGuard(guard)\n if (observed.kind === 'vacant') continue\n const owner = observed.owner\n if (leaseGuardIsResidue(owner)) {\n hooks.beforeLeaseGuardReclaim?.()\n reclaimLeaseGuard(guard, observed.ownerFile, hooks)\n continue\n }\n if (owner?.pid === process.pid && owner.threadId === threadId) {\n throw new LeaseGuardBusyError(\n 'writer lease guard is held by an enclosing section on this thread',\n )\n }\n if (!contended) {\n contended = true\n hooks.onLeaseGuardContended?.()\n }\n if (monotonicElapsedMs(claimedAtNs) >= LEASE_GUARD_WAIT_MS) {\n throw new LeaseGuardBusyError(\n `writer lease guard stayed held by pid ${owner?.pid ?? 'unknown'} for `\n + `${LEASE_GUARD_WAIT_MS}ms`,\n )\n }\n Atomics.wait(MUTATION_LOCK_TERMINATION_WAIT, 0, 0, LEASE_GUARD_POLL_MS)\n }\n } finally {\n // After a successful claim the staged directory IS the guard, so nothing is left to remove.\n rmSync(staged, { recursive: true, force: true })\n }\n try {\n sweepLeakedLeaseGuardStaging(parent, staged)\n return section()\n } finally {\n releaseLeaseGuard(guard, ownerFile)\n }\n } finally {\n for (const dir of createdAncestors) {\n try {\n rmdirSync(dir)\n } catch {\n // Not empty, already gone, or not ours to judge: left as it is.\n }\n }\n }\n}\n\n/**\n * Read and strictly validate current writer authority without acquiring or refreshing it.\n *\n * CR-01 (round 5): ENOENT is the only read failure that is evidence of absence, and NO read\n * failure is evidence of corruption. This is `readEpoch`'s rule applied to the file it was not\n * applied to — the derivation's own W-01 note says the guard belongs at the READ, so that\n * consumers inherit it rather than each re-deriving it, and this read has three consumers that\n * select SIGKILL, epoch minting and registration deletion from its answer.\n *\n * The `existsSync` fallback that used to sit here is deleted rather than kept beside the errno\n * test: under fd exhaustion it fails for the same reason the open did, so it degraded an EMFILE\n * read from `malformed` to `absent` — the strongest possible statement that nobody holds the\n * lease, produced by the weakest possible evidence.\n */\nexport function readWriterLease(knowledgeRoot: string): ReadWriterLeaseOutcome {\n const file = leasePath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { kind: 'absent' }\n return { kind: 'unreadable', code: code ?? 'unknown-read-error' }\n }\n\n try {\n const parsed = writerLeaseSchema.safeParse(JSON.parse(raw))\n return parsed.success ? { kind: 'parsed', lease: parsed.data } : { kind: 'malformed' }\n } catch {\n return { kind: 'malformed' }\n }\n}\n\nfunction previewEpochState(raw: string): string {\n const preview = raw.slice(0, 64).replaceAll('\\r', '\\\\r').replaceAll('\\n', '\\\\n')\n return preview === '' ? '<empty>' : preview\n}\n\nfunction readEpoch(knowledgeRoot: string): number {\n const file = epochPath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return 0\n throw new CorruptEpochStateError(file, 'unreadable', code ?? 'unknown-read-error')\n }\n const canonical = raw.endsWith('\\n') ? raw.slice(0, -1) : raw\n if (!/^(0|[1-9][0-9]*)$/.test(canonical)) {\n throw new CorruptEpochStateError(file, 'malformed', previewEpochState(raw))\n }\n const epoch = Number(canonical)\n if (!Number.isSafeInteger(epoch)) {\n throw new CorruptEpochStateError(file, 'overflow', previewEpochState(raw))\n }\n return epoch\n}\n\n/** Fresh-read the monotonic disk epoch; only an absent file is pre-acquire epoch zero. */\nexport function readCurrentEpoch(knowledgeRoot: string): number {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n return readEpoch(knowledgeRoot)\n}\n\n/**\n * An epoch-stale write is refused AT THE MUTATION BOUNDARY. Plan 378-10 calls this immediately\n * before the intent-journal write and again immediately before the publish rename; a stale result\n * abandons the in-flight job without mutation. Every call re-reads disk and never caches the epoch.\n */\nexport function assertEpochCurrent(\n opts: AssertEpochCurrentOptions,\n): AssertEpochCurrentOutcome {\n const observedEpoch = readCurrentEpoch(opts.knowledgeRoot)\n return observedEpoch === opts.epoch\n ? { current: true }\n : { current: false, observedEpoch }\n}\n\nfunction nextEpoch(current: number): number {\n if (current === Number.MAX_SAFE_INTEGER) {\n throw new RangeError('writer lease epoch exhausted')\n }\n return current + 1\n}\n\n/** Purely classify a guarded or untrusted lease value against one explicit wall-clock instant. */\nexport function isLeaseStale(lease: unknown, nowMs: number): boolean {\n const parsed = writerLeaseSchema.safeParse(lease)\n if (!parsed.success || !Number.isFinite(nowMs)) return true\n return nowMs - parsed.data.heartbeatAtMs >= LEASE_HEARTBEAT_TTL_MS\n}\n\n/**\n * The one freshness answer, and it has three values rather than two.\n *\n * CR-01: the previous derivation returned a boolean, so every way of failing to READ the epoch\n * collapsed into the same value a genuinely expired lease produces. `readEpoch` raises\n * `CorruptEpochStateError(…, 'unreadable', …)` for EACCES, EIO, EMFILE and ENFILE, not only for\n * corrupt bytes, and fd exhaustion produces both that failure and the daemon identity-handshake\n * failure at once. A live, healthy holder therefore became de-registrable and SIGKILL-eligible on\n * a transient read error.\n *\n * `unknown` is deliberately NOT resolved to either boolean here. Resolving it toward \"fresh\" makes\n * a permanently unreadable epoch an immortal phantom holder no contender can ever reclaim;\n * resolving it toward \"reclaimable\" is the kill this closes. It is returned to the consumers so\n * each of them names what it does with it, and so a fourth consumer added later cannot inherit a\n * default it never chose.\n *\n * W-01: the epoch conjunct lives HERE, in the derivation, not at the consumers. Three surfaces\n * classify recoverability from this verdict — `leasePermitsEscalation`, the acquisition\n * pre-check, and `classifyDaemonRegistration` in the CLI — and a fix applied consumer by consumer\n * is a list that the next surface joins without joining the guard. A lease naming a superseded\n * epoch is recovery input no matter how fresh its bytes are: nobody can still be inside a\n * transaction for an epoch that has already been replaced.\n *\n * WR-04: a crash between the epoch rewrite and the lease rewrite leaves a lease naming the\n * previous epoch. Reporting that lease as held manufactures a phantom holder no TTL sweep ever\n * reclaims, so an epoch-invalid lease is recovery input rather than an answer.\n *\n * The inputs are the disk epoch and the lease value, and nothing else. There is no second\n * freshness channel and no further conjunct: three conjuncts produced three defects.\n */\nexport type WriterLeaseFreshness =\n | { kind: 'fresh' }\n | { kind: 'reclaimable' }\n | { kind: 'unknown'; error: CorruptEpochStateError }\n\nexport function deriveWriterLeaseFreshness(\n knowledgeRoot: string,\n lease: WriterLease,\n nowMs: number,\n): WriterLeaseFreshness {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) return { kind: 'unknown', error }\n throw error\n }\n if (lease.epoch !== observedEpoch) return { kind: 'reclaimable' }\n return isLeaseStale(lease, nowMs) ? { kind: 'reclaimable' } : { kind: 'fresh' }\n}\n\n/** Return a live holder or atomically mint a new, monotonically fenced writer identity. */\nexport function acquireWriterLease(\n knowledgeRoot: string,\n hooks?: AcquireWriterLeaseOptions,\n): AcquireWriterLeaseOutcome {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n const beforeLock = readWriterLease(knowledgeRoot)\n if (beforeLock.kind === 'parsed') {\n // This consumer names `unknown` as the typed refusal it already had for corrupt epoch bytes:\n // an authority state that cannot be read is not a licence to mint a new one.\n const verdict = deriveWriterLeaseFreshness(\n knowledgeRoot,\n beforeLock.lease,\n mutationLockNowMs(),\n )\n if (verdict.kind === 'unknown') {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error: verdict.error }\n }\n if (verdict.kind === 'fresh') return { kind: 'held', holder: beforeLock.lease }\n } else if (beforeLock.kind === 'unreadable') {\n // CR-01: a lease that exists and cannot be opened is not a licence to mint over it. Refusing\n // here is what keeps the loop below — and therefore the escalation surface underneath it —\n // out of reach for this input class entirely.\n return {\n kind: 'refused',\n reason: 'unreadable-lease-state',\n code: beforeLock.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), beforeLock.code),\n }\n } else {\n // With no lease to derive from, the epoch is still read before any acquisition: unreadable or\n // corrupt authority state refuses here exactly as it does through the verdict above.\n try {\n readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error }\n }\n throw error\n }\n }\n\n const deadlineMs = hooks?.acquireDeadlineMs ?? ACQUIRE_WRITER_LEASE_DEADLINE_MS\n const startedAtNs = process.hrtime.bigint()\n /**\n * W-05: the same instant the loop's own exit is measured against, handed to everything that\n * waits beneath it.\n *\n * Escalation waits are spent on this budget, not beside it. Deriving the instant once here and\n * threading it down means no wait can be extended by retuning a constant it happens to sit\n * under, and none of them needs to know what the others cost.\n */\n const deadlineAtNs = startedAtNs + BigInt(Math.round(deadlineMs * 1e6))\n let attempts = 0\n\n while (true) {\n attempts += 1\n try {\n return withMutationLock(knowledgeRoot, () => {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return { kind: 'refused' as const, reason: 'corrupt-epoch-state' as const, error }\n }\n throw error\n }\n const current = readWriterLease(knowledgeRoot)\n const nowMs = Date.now()\n if (current.kind === 'unreadable') {\n // The in-lock repeat of the pre-lock arm: a lease that turned unopenable while this\n // contender waited for the lock is still not evidence that nobody holds it.\n return {\n kind: 'refused' as const,\n reason: 'unreadable-lease-state' as const,\n code: current.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), current.code),\n }\n }\n if (current.kind === 'parsed') {\n const verdict = deriveWriterLeaseFreshness(knowledgeRoot, current.lease, nowMs)\n if (verdict.kind === 'unknown') {\n return {\n kind: 'refused' as const,\n reason: 'corrupt-epoch-state' as const,\n error: verdict.error,\n }\n }\n if (verdict.kind === 'fresh' && current.lease.epoch === observedEpoch) {\n return { kind: 'held', holder: current.lease }\n }\n }\n const reclaimed = current.kind === 'parsed' ? current.lease : undefined\n\n const epoch = nextEpoch(observedEpoch)\n const holder = writerLeaseSchema.parse({\n leaseId: randomUUID(),\n pid: process.pid,\n epoch,\n heartbeatAtMs: nowMs,\n })\n atomicRewrite(epochPath(knowledgeRoot), `${epoch}\\n`)\n hooks?.afterEpochRewrite?.()\n sweepStagedEpochsBefore(knowledgeRoot, epoch)\n atomicRewrite(leasePath(knowledgeRoot), `${JSON.stringify(holder)}\\n`)\n return {\n kind: 'acquired',\n leaseId: holder.leaseId,\n epoch: holder.epoch,\n ...(reclaimed === undefined ? {} : { reclaimed }),\n }\n }, hooks, deadlineAtNs)\n } catch (error) {\n if (!(error instanceof MutationLockBusyError)) throw error\n /**\n * Contention answers 'held' only for an epoch-valid lease. Staleness deliberately does NOT\n * disqualify a holder here: the lock is busy, so the published holder is inside its own\n * serialized section and a stale heartbeat is exactly the fencing case DAEM-09 protects\n * (a paused drainer must be reported as holding, not stolen from). An epoch-mismatched\n * lease is different in kind — nobody can still be inside a transaction for a superseded\n * epoch — so it is recovery input and the loop keeps waiting for the lock.\n *\n * An epoch that cannot be READ is a third case and no longer hides inside the mismatch arm:\n * the contender surfaces the typed refusal by name instead of spinning silently to its\n * deadline over an authority state nobody can evaluate.\n */\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'unreadable') {\n // A lease that cannot be READ is a fourth case here for the same reason an unreadable\n // epoch is a third one: the contender surfaces it by name instead of spinning to its\n // deadline over an authority state nobody can evaluate.\n return {\n kind: 'refused',\n reason: 'unreadable-lease-state',\n code: current.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), current.code),\n }\n }\n if (current.kind === 'parsed') {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (epochError) {\n if (epochError instanceof CorruptEpochStateError) {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error: epochError }\n }\n throw epochError\n }\n if (current.lease.epoch === observedEpoch) {\n return { kind: 'held', holder: current.lease }\n }\n }\n /**\n * The outermost exit, and the only one anchored outside this module's own vocabulary.\n *\n * It is checked AFTER the `held` narrow above, so a contender that could have answered\n * `held` always does; the deadline never converts a good answer into a refusal. It is also\n * strictly larger than MUTATION_LOCK_TAKEOVER_MS, so a reclaim that was going to happen has\n * already had its chance by the time this fires.\n */\n const waitedMs = monotonicElapsedMs(startedAtNs)\n if (waitedMs >= deadlineMs) {\n const observedOwner = readCommittedMutationLockOwner(knowledgeRoot)\n const error = new WriterLeaseUnreclaimableError(\n attempts,\n waitedMs,\n observedOwner === undefined ? undefined : {\n pid: observedOwner.pid,\n acquiredAtMs: observedOwner.acquiredAtMs,\n generationToken: observedOwner.generationToken,\n incarnationAttributed: observedOwner.incarnation !== undefined,\n },\n current.kind === 'parsed' ? current.lease : undefined,\n )\n return {\n kind: 'refused',\n reason: 'mutation-lock-unreclaimable',\n error,\n attempts,\n waitedMs,\n ...(error.observedOwner === undefined ? {} : { observedOwner: error.observedOwner }),\n ...(error.observedLease === undefined ? {} : { observedLease: error.observedLease }),\n }\n }\n Atomics.wait(\n MUTATION_LOCK_TERMINATION_WAIT,\n 0,\n 0,\n MUTATION_LOCK_TERMINATION_POLL_MS,\n )\n }\n }\n}\n\n/**\n * Compare one exact writer authority and run its mutation under the same generation lock.\n * The generation check after the failpoint prevents an expired owner from resuming after a\n * bounded takeover. Mutation implementations must keep irreversible work inside `mutate`.\n */\nexport function withCurrentWriterAuthority<T>(\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n mutate: () => T,\n hooks: CurrentWriterAuthorityHooks = {},\n): T {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n const fullAuthority: WriterLeaseAuthority = { knowledgeRoot, ...authority }\n try {\n return withMutationLock(knowledgeRoot, (generationToken, db) => {\n const observedEpoch = readCurrentEpoch(knowledgeRoot)\n if (observedEpoch !== authority.epoch) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'epoch-mismatch-before-heartbeat',\n observedEpoch,\n )\n }\n /**\n * CR-01: the epoch alone is guessable, and release deliberately never advances it, so an\n * epoch-only guard admits both a fabricated identity and a holder that already released.\n * The lease is therefore read INSIDE the held transaction — the same serialization boundary\n * as the epoch and generation checks — and must match the supplied authority exactly. This\n * is heartbeatLease's presence/id/epoch ladder, applied where mutation actually happens.\n */\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'absent') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-missing', observedEpoch)\n }\n if (current.kind === 'malformed') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-malformed', observedEpoch)\n }\n // CR-01: authority that cannot be re-read inside the transaction is authority that cannot be\n // proven, and this is the fence that keeps a fenced-out writer from committing.\n if (current.kind === 'unreadable') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-unreadable', observedEpoch)\n }\n if (current.lease.leaseId !== authority.leaseId) {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-id-mismatch', observedEpoch)\n }\n if (current.lease.epoch !== authority.epoch) {\n throw new WriterAuthorityLostError(fullAuthority, 'stale-epoch', observedEpoch)\n }\n hooks.afterFinalAuthorityCompare?.()\n if (!mutationLockGenerationIsCurrent(db, generationToken)) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'mutation-lock-generation-lost',\n readCurrentEpoch(knowledgeRoot),\n )\n }\n return mutate()\n }, hooks)\n } catch (error) {\n if (\n error instanceof MutationLockBusyError\n || error instanceof MutationLockGenerationLostError\n ) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'mutation-lock-generation-lost',\n readCurrentEpoch(knowledgeRoot),\n )\n }\n throw error\n }\n}\n\n/**\n * Refresh the matching current-epoch holder without entering the mutation lock.\n *\n * CR-03 dissolves here rather than being worked around. The beat used to share\n * `withMutationLock` with every governed write, and it runs in a worker THREAD, so the daemon's\n * long synchronous mutation on the main thread held the lock while the worker blocked on it: the\n * holder starved its own heartbeat, crossed the TTL and became a takeover target. Writing `.lease`\n * directly means a governed mutation of any length cannot starve the beat at all, so heartbeat\n * independence is structural instead of a fallback that has to be maintained beside the real path.\n *\n * What the lock used to buy was check-then-write atomicity of the identity/epoch ladder below\n * against a concurrent reclaim, and dropping it opens exactly one race: a holder resuming from a\n * >=TTL wedge can land its read-check-write astride a contender's reclaim and clobber the\n * successor's lease. That is contained rather than prevented, and the containment is the epoch\n * fence: a reclaim rewrites `.epoch` strictly BEFORE it publishes its lease, both inside the lock,\n * so any lease clobbered afterwards names a superseded epoch. Every classifier reads it as\n * recovery input, no store write is admitted under it (the epoch fence at the store verbs), and\n * the successor's next authority check surfaces WriterAuthorityLostError, after which a fresh\n * acquisition reclaims at the next epoch. The worst case is one successor bounce in a microsecond\n * window after a 30 s wedge — a liveness hiccup, never minted authority. During the exact schedule\n * this lock-free write exists for (the holder's own mutation in flight) no contender can be\n * mid-reclaim at all, because a reclaim requires the very lock that mutation is holding.\n *\n * 2026-08-01 W-02 re-scope: `MUTATION_LOCK_TAKEOVER_MS` now governs reclaim from DEAD and\n * whole-process-STOPPED owners, which write no beats and cross the TTL. Auto-takeover of a LIVE\n * holder whose beat thread is still ticking is deliberately impossible; a wedged-forever live\n * daemon surfaces at every contender as the typed `mutation-lock-unreclaimable` refusal naming its\n * pid. That is an operator kill rather than an automated one, which is this module's own law: a\n * wrong kill is unrecoverable, a wedged contender is not.\n *\n * Identity is still proven first, and every refusal below leaves `.lease` byte-identical.\n *\n * 2026-10-02 (quick 261002-lse, 432-19 #7): the ladder and the write run under the lease-file\n * guard `releaseLease` also takes. Without it a beat that read before a release wrote after it,\n * and since release deliberately keeps the epoch, the resurrected lease named the CURRENT epoch:\n * the fence above contains a reclaim but not a release, and the next acquire answered `held`.\n * The guard is not the mutation lock, so everything said above about CR-03 still holds.\n */\nexport function heartbeatLease(\n opts: LeaseOperationOptions,\n hooks: LeaseGuardHooks = {},\n): HeartbeatLeaseOutcome {\n assertAbsoluteKnowledgeRoot(opts.knowledgeRoot)\n // Nothing to resurrect and nothing to guard: absence is answered before any guard is staged.\n if (readWriterLease(opts.knowledgeRoot).kind === 'absent') {\n return { kind: 'refused', reason: 'lease-missing' }\n }\n return withLeaseGuard(opts.knowledgeRoot, (): HeartbeatLeaseOutcome => {\n const current = readWriterLease(opts.knowledgeRoot)\n if (current.kind === 'absent') return { kind: 'refused', reason: 'lease-missing' }\n if (current.kind === 'malformed') return { kind: 'refused', reason: 'lease-malformed' }\n // CR-01: a beat that cannot read the lease cannot prove it owns it, so it may not rewrite it.\n if (current.kind === 'unreadable') return { kind: 'refused', reason: 'lease-unreadable' }\n if (current.lease.leaseId !== opts.leaseId) {\n return { kind: 'refused', reason: 'lease-id-mismatch', holder: current.lease }\n }\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(opts.knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return {\n kind: 'refused',\n reason: 'corrupt-epoch-state',\n holder: current.lease,\n error,\n }\n }\n throw error\n }\n if (current.lease.epoch !== observedEpoch) {\n return {\n kind: 'refused',\n reason: 'stale-epoch',\n holder: current.lease,\n observedEpoch,\n }\n }\n\n const holder = writerLeaseSchema.parse({\n ...current.lease,\n heartbeatAtMs: Date.now(),\n })\n atomicRewrite(leasePath(opts.knowledgeRoot), `${JSON.stringify(holder)}\\n`)\n return { kind: 'heartbeated', holder }\n }, hooks)\n}\n\n/**\n * Refresh one exact maintenance writer at a non-mutating boundary.\n *\n * The epoch reads deliberately bracket the heartbeat: the first rejects an already-reclaimed\n * holder, while the second detects a reclaim race after the lease rewrite. The authority-store\n * transaction is released before this function returns, so this is NOT a mutation fence. Any\n * irreversible mutation must instead run inside `withCurrentWriterAuthority`.\n */\nexport function refreshWriterLeaseAuthority(\n authority: WriterLeaseAuthority,\n): WriterLeaseAuthority {\n const beforeHeartbeat = assertEpochCurrent(authority)\n if (!beforeHeartbeat.current) {\n throw new WriterAuthorityLostError(\n authority,\n 'epoch-mismatch-before-heartbeat',\n beforeHeartbeat.observedEpoch,\n )\n }\n\n const heartbeat = heartbeatLease(authority)\n if (heartbeat.kind === 'refused') {\n if (heartbeat.reason === 'corrupt-epoch-state' && heartbeat.error !== undefined) {\n throw heartbeat.error\n }\n throw new WriterAuthorityLostError(\n authority,\n heartbeat.reason,\n readCurrentEpoch(authority.knowledgeRoot),\n )\n }\n\n const afterHeartbeat = assertEpochCurrent(authority)\n if (!afterHeartbeat.current) {\n throw new WriterAuthorityLostError(\n authority,\n 'epoch-mismatch-after-heartbeat',\n afterHeartbeat.observedEpoch,\n )\n }\n\n return authority\n}\n\n/**\n * Remove only the matching lease file; the monotonic epoch is deliberately retained forever.\n *\n * The read and the deletion run under the lease-file guard, taken inside the mutation lock, so a\n * heartbeat in flight finishes before the lease is read and any later beat finds it gone\n * (261002-lse). The guard is always taken second, and the beat never takes the mutation lock, so\n * the two cannot wait on each other.\n */\nexport function releaseLease(\n opts: LeaseOperationOptions,\n hooks: LeaseGuardHooks = {},\n): ReleaseLeaseOutcome {\n assertAbsoluteKnowledgeRoot(opts.knowledgeRoot)\n return withMutationLock(opts.knowledgeRoot, () => {\n const outcome = withLeaseGuard(opts.knowledgeRoot, (): ReleaseLeaseOutcome => {\n const current = readWriterLease(opts.knowledgeRoot)\n if (current.kind === 'absent') return { kind: 'refused', reason: 'lease-missing' }\n if (current.kind === 'malformed') return { kind: 'refused', reason: 'lease-malformed' }\n // CR-01: release is a deletion. An unreadable lease could belong to anybody, including a\n // successor that reclaimed while this caller was away, so it is never removed unseen.\n if (current.kind === 'unreadable') return { kind: 'refused', reason: 'lease-unreadable' }\n if (current.lease.leaseId !== opts.leaseId) {\n return { kind: 'refused', reason: 'lease-id-mismatch', holder: current.lease }\n }\n\n rmSync(leasePath(opts.knowledgeRoot), { force: true })\n return { kind: 'released' }\n }, hooks)\n if (outcome.kind === 'released') bestEffortFsyncDirectory(opts.knowledgeRoot)\n return outcome\n })\n}\n","/**\n * The embedder worker's half of the one process-identity vocabulary in this package.\n *\n * This is a separate module from `worker-registration.ts` on purpose. Registration reading and\n * socket probing are reachable from the read-only serving entry, and `reader-import-closure`\n * forbids that closure from crossing into `lease/`. The *signal decision* is a writer-side concern\n * that the reader never makes, so it lives here — which lets both kill paths in this package share\n * CR-04's single `resolveProcessIncarnation` definition instead of growing a second, subtly\n * different identity scheme.\n */\nimport { incarnationFormat, resolveProcessIncarnation } from '../lease/writer-lease.js'\n\nimport {\n EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION,\n type EmbedderWorkerIncarnationVerdict,\n type EmbedderWorkerRegistration,\n} from './worker-registration.js'\n\nexport { resolveProcessIncarnation }\n\n/**\n * The token a worker records about ITSELF at registration time.\n *\n * The worker is the only party that can attribute the registration without a race: it is the\n * process being described, and it is alive while describing itself. A worker that cannot resolve\n * its own start time records the sentinel rather than fabricating a value, accepting that it will\n * later be replaced without a signal instead of terminated.\n */\nexport function ownEmbedderWorkerIncarnation(): string {\n return resolveProcessIncarnation(process.pid) ?? EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION\n}\n\n/**\n * Compare the registration's recorded incarnation against the pid's CURRENT occupant.\n *\n * CR-05: a schema-valid registration naming a live pid whose socket has stopped answering is not\n * proof that the worker is still there. Once the worker died, the kernel is free to hand its pid to\n * a stranger, and every decision keyed on that number alone targets whoever holds it now. The one\n * fact that separates them is assigned by the OS and cannot be forged from inside the file: when\n * the process at that pid started.\n *\n * `mismatch` means the registered worker is provably gone; `unverifiable` means we cannot say, and\n * that is a refusal rather than a default-allow. Neither may be signalled — and neither needs to\n * be, because generation-specific sockets (Plan 24) let a fresh worker take a clean address without\n * the old pid ever being touched.\n */\nexport function verifyEmbedderWorkerIncarnation(\n registration: EmbedderWorkerRegistration,\n): EmbedderWorkerIncarnationVerdict {\n if (registration.incarnation === EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION) {\n return 'unverifiable'\n }\n const occupant = resolveProcessIncarnation(registration.pid)\n if (occupant === undefined) return 'unverifiable'\n if (incarnationFormat(occupant) !== incarnationFormat(registration.incarnation)) {\n return 'unverifiable'\n }\n return occupant === registration.incarnation ? 'match' : 'mismatch'\n}\n"],"mappings":";AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,aAAAC,YAAW,UAAAC,eAAc;AACl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;AACA,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACA,UAAQ,KAAK,WAAW,MAAM,KAAK,CAAC,CAAC;AACrC,UAAQ,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC;AACtC;AAEA,IAAM,gBAAgB,QAAQ,KAAK,CAAC,MAAM,SAAY,SAAYI,UAAS,QAAQ,KAAK,CAAC,CAAC;AAC1F,IAAI,kBAAkB,qBAAqB,kBAAkB,oBAAoB;AAC/E,OAAK,KAAK,EAAE,MAAM,CAAC,UAAmB;AACpC,YAAQ,OAAO;AAAA,MACb,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA;AAAA,IACnF;AACA,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;","names":["randomUUID","chmodSync","rmSync","connect","basename","resolve","dirname","DEFAULT_EMBEDDING_PROFILE","STATIC_FLOOR_EMBEDDING_PROFILE","join","embed","createHash","existsSync","readFileSync","dirname","join","createHash","join","dirname","readFileSync","existsSync","dirname","STATIC_FLOOR_EMBEDDING_PROFILE","DEFAULT_EMBEDDING_PROFILE","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","renameSync","rmSync","unlinkSync","writeFileSync","basename","dirname","join","DatabaseSync","z","basename","z","readFileSync","z","request","connect","rmSync","resolve","randomUUID","chmodSync","basename"]}
1
+ {"version":3,"sources":["../../src/embedder-worker/worker-entry.ts","../../src/embedder-acquire.ts","../../src/embedder-floor.ts","../../src/embedder-native.ts","../../src/model-cache-dir.ts","../../src/embedder-worker/worker-registration.ts","../../src/index-open.ts","../../src/sqlite-vec-loadable.ts","../../src/lease/writer-lease.ts","../../src/embedder-worker/worker-incarnation.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { chmodSync, rmSync } from 'node:fs'\nimport {\n createServer,\n type IncomingMessage,\n type Server,\n type ServerResponse,\n} from 'node:http'\nimport { connect } from 'node:net'\nimport { basename, resolve } from 'node:path'\n\nimport type { EmbeddingProfile } from '@vostride/agent-qa-schema'\n\nimport { resolveEmbedderCapability } from '../embedder-acquire.js'\nimport type { EmbedderPort } from '../embedder-port.js'\nimport { ownEmbedderWorkerIncarnation } from './worker-incarnation.js'\nimport {\n asEmbeddingProfile,\n embedderWorkerAgentQaRoot,\n embedderWorkerRequestSchema,\n embedderWorkerSocketPath,\n EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION,\n EMBEDDER_WORKER_REGISTRATION_SCHEMA_VERSION,\n embeddingProfileSchema,\n MAX_EMBEDDER_WORKER_BODY_BYTES,\n prepareEmbedderWorkerSocketParent,\n removeEmbedderWorkerRegistration,\n writeEmbedderWorkerRegistration,\n type EmbedderWorkerRegistration,\n type EmbedderWorkerRequest,\n} from './worker-registration.js'\n\nclass EmbedderWorkerRequestError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'EmbedderWorkerRequestError'\n }\n}\n\nasync function readRequestBody(request: IncomingMessage): Promise<string> {\n const chunks: Buffer[] = []\n let bytes = 0\n for await (const chunk of request) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n bytes += buffer.byteLength\n if (bytes > MAX_EMBEDDER_WORKER_BODY_BYTES) {\n throw new EmbedderWorkerRequestError(\n `Embedder request exceeds ${MAX_EMBEDDER_WORKER_BODY_BYTES} bytes`,\n )\n }\n chunks.push(buffer)\n }\n return Buffer.concat(chunks).toString('utf8')\n}\n\nasync function parseRequest(request: IncomingMessage): Promise<EmbedderWorkerRequest> {\n let parsedJson: unknown\n try {\n parsedJson = JSON.parse(await readRequestBody(request)) as unknown\n } catch (error) {\n if (error instanceof EmbedderWorkerRequestError) throw error\n throw new EmbedderWorkerRequestError(\n `Embedder request body must be valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n\n const parsed = embedderWorkerRequestSchema.safeParse(parsedJson)\n if (!parsed.success) {\n throw new EmbedderWorkerRequestError(\n parsed.error.issues\n .map((issue) => `${issue.path.map(String).join('.') || '<root>'}: ${issue.message}`)\n .join('; '),\n )\n }\n return parsed.data\n}\n\nfunction json(response: ServerResponse, statusCode: number, body: unknown): void {\n const payload = JSON.stringify(body)\n response.writeHead(statusCode, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(payload),\n })\n response.end(payload)\n}\n\nasync function embedOne(\n embedder: EmbedderPort,\n request: Extract<EmbedderWorkerRequest, { method: 'embedDocument' | 'embedQuery' }>,\n): Promise<Float32Array> {\n return request.method === 'embedDocument'\n ? embedder.embedDocument(request.rendering)\n : embedder.embedQuery(request.rendering)\n}\n\nasync function serveEmbeddingRequest(\n embedder: EmbedderPort,\n request: EmbedderWorkerRequest,\n): Promise<readonly Float32Array[]> {\n if (request.method === 'embedBatch') {\n return Promise.all(request.requests.map((item) => embedOne(embedder, item)))\n }\n return [await embedOne(embedder, request)]\n}\n\nfunction createEmbedderServer(embedder: EmbedderPort): Server {\n return createServer((request, response) => {\n void (async () => {\n if (request.method !== 'POST' || request.url !== '/embed') {\n json(response, 404, { error: 'not-found' })\n return\n }\n\n try {\n const envelope = await parseRequest(request)\n const vectors = await serveEmbeddingRequest(embedder, envelope)\n json(response, 200, {\n schemaVersion: EMBEDDER_WORKER_PROTOCOL_SCHEMA_VERSION,\n vectors: vectors.map((vector) => Array.from(vector)),\n })\n } catch (error) {\n const statusCode = error instanceof EmbedderWorkerRequestError ? 400 : 500\n json(response, statusCode, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n })()\n })\n}\n\nfunction listen(server: Server, socketPath: string): Promise<void> {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (error: Error): void => {\n server.off('listening', onListening)\n rejectListen(error)\n }\n const onListening = (): void => {\n server.off('error', onError)\n resolveListen()\n }\n server.once('error', onError)\n server.once('listening', onListening)\n server.listen(socketPath)\n })\n}\n\nfunction probeSocket(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\nasync function listenWithStaleRecovery(server: Server, socketPath: string): Promise<void> {\n try {\n await listen(server, socketPath)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n (code !== 'EADDRINUSE' && code !== 'EINVAL')\n || process.platform === 'win32'\n ) {\n throw error\n }\n if (await probeSocket(socketPath)) {\n throw new Error(`Embedder worker socket is already live: ${socketPath}`)\n }\n rmSync(socketPath)\n await listen(server, socketPath)\n }\n}\n\nfunction closeServer(server: Server): Promise<void> {\n return new Promise((resolveClose, rejectClose) => {\n server.close((error) => {\n if (error !== undefined) rejectClose(error)\n else resolveClose()\n })\n })\n}\n\nasync function acquireProcessLocalEmbedder(profile: EmbeddingProfile): Promise<EmbedderPort> {\n const outcome = await resolveEmbedderCapability({\n preferredProfile: profile,\n allowDownload: false,\n probes: {\n discoverWorker: () => Promise.resolve({ kind: 'no-worker' }),\n },\n })\n if (outcome.kind !== 'ready') {\n throw new Error(`Embedder worker could not resolve profile: ${outcome.kind}`)\n }\n return outcome.embedder\n}\n\nexport interface RunEmbedderWorkerOptions {\n readonly projectRoot: string\n readonly profile: EmbeddingProfile\n /** Host-minted generation identity; standalone workers mint their own nonce. */\n readonly instanceId?: string\n}\n\nexport interface EmbedderWorkerHandle {\n readonly registration: EmbedderWorkerRegistration\n close(): Promise<void>\n}\n\n/** Start the child worker after resolving its process-local embedder through the normal ladder. */\nexport async function runEmbedderWorker(\n options: RunEmbedderWorkerOptions,\n): Promise<EmbedderWorkerHandle> {\n const projectRoot = resolve(options.projectRoot)\n const agentQaRoot = embedderWorkerAgentQaRoot(projectRoot)\n const instanceId = options.instanceId ?? randomUUID()\n const socketPath = embedderWorkerSocketPath(agentQaRoot, projectRoot, instanceId)\n const embedder = await acquireProcessLocalEmbedder(options.profile)\n const server = createEmbedderServer(embedder)\n prepareEmbedderWorkerSocketParent(socketPath)\n await listenWithStaleRecovery(server, socketPath)\n\n const registration: EmbedderWorkerRegistration = {\n schemaVersion: EMBEDDER_WORKER_REGISTRATION_SCHEMA_VERSION,\n instanceId,\n pid: process.pid,\n socketPath,\n profile: options.profile,\n startedAtMs: Date.now(),\n incarnation: ownEmbedderWorkerIncarnation(),\n }\n try {\n if (process.platform !== 'win32') chmodSync(socketPath, 0o600)\n writeEmbedderWorkerRegistration(agentQaRoot, registration)\n } catch (error) {\n await closeServer(server).catch(() => undefined)\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n if (process.platform !== 'win32') rmSync(socketPath, { force: true })\n throw error\n }\n\n let closePromise: Promise<void> | undefined\n return {\n registration,\n close() {\n closePromise ??= (async () => {\n try {\n await closeServer(server)\n } finally {\n try {\n removeEmbedderWorkerRegistration(agentQaRoot, registration)\n } finally {\n if (process.platform !== 'win32') rmSync(socketPath, { force: true })\n }\n }\n })()\n return closePromise\n },\n }\n}\n\nfunction parseProfile(raw: string | undefined): EmbeddingProfile {\n if (raw === undefined) throw new Error('Embedder worker requires a profile JSON argument')\n return asEmbeddingProfile(embeddingProfileSchema.parse(JSON.parse(raw) as unknown))\n}\n\nasync function main(): Promise<void> {\n const projectRoot = process.argv[2]\n if (projectRoot === undefined) throw new Error('Embedder worker requires a project root argument')\n const handle = await runEmbedderWorker({\n projectRoot,\n profile: parseProfile(process.argv[3]),\n ...(process.argv[4] === undefined ? {} : { instanceId: process.argv[4] }),\n })\n\n let stopping = false\n const stop = (exitCode: number): void => {\n if (stopping) return\n stopping = true\n void handle.close().then(\n () => process.exit(exitCode),\n (error: unknown) => {\n process.stderr.write(\n `Embedder worker cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n process.exit(1)\n },\n )\n }\n process.once('SIGTERM', () => stop(0))\n process.once('SIGINT', () => stop(0))\n}\n\nconst entryBasename = process.argv[1] === undefined ? undefined : basename(process.argv[1])\nif (entryBasename === 'worker-entry.js' || entryBasename === 'worker-entry.cjs') {\n void main().catch((error: unknown) => {\n process.stderr.write(\n `Embedder worker failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n process.exitCode = 1\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// Test-only: production callers omit it so rung selection reflects the host.\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 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 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// Rooted in the hosted project, not the 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// Memoised per profile; injected test seams get an isolated memo.\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","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// Loads at the first acquisition, never at import; a failed load is dropped so the next 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 // The tokenizer metadata probe (get_tokenizer_files) ignores the load 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 // The option-dropping tokenizer metadata lookup can collapse an empty local\n // directory into a generic TypeError. The model loader keeps 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// One download per machine: an explicit override wins, then the XDG cache, then the home cache.\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\nexport const EMBEDDER_WORKER_REQUEST_TIMEOUT_MS = 30_000\n\nexport const EMBEDDER_WORKER_START_TIMEOUT_MS = 15_000\n\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","// The index lives in the gitignored `memory/index`, so its writes skip the committed egress gate.\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// Bump only when contextual-rendering bytes change; a stale stamp forces one full render pass.\nexport const INDEX_RENDERING_SCHEMA_VERSION = 2\n\n// An absent or stale epoch forces one full invalidation, in the same transaction as the marker.\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\nexport const WRITER_BUSY_TIMEOUT_MS = 2000\n\nexport const READER_BUSY_TIMEOUT_MS = 500\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 // Test seam; production resolves sqlite-vec's pinned prebuild.\n vecLoadablePath?: string\n}\n\nexport interface IndexReaderOpenOptions extends IndexOpenOptions {\n // Opens `immutable=1` when no `-wal` exists, so a probe makes no sidecars; serving never sets it.\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// Absent, unknown or pre-bootstrap metadata falls back to the default profile.\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// Disposable and rebuilt from run handoffs, so not in `REQUIRED_INDEX_TABLES`; holds no test file.\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 -- run_id and build_ordinal are what the fold's newest-evidence-wins replacement compares on.\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 -- One fold-semantics stamp for the tables above; an absent row reads as a mismatch.\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// Invalidates before the stamp in one transaction; a brute connection leaves vec cleanup pending.\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","// Native-extension resolution stays behind this boundary; `index-open` owns load failures.\nexport { getLoadablePath } from 'sqlite-vec'\n","// Lease and epoch files are fsync'd then renamed, so a kill exposes only the old or the new bytes.\nimport { spawnSync } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants as fsConstants,\n existsSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmdirSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport type { Dirent, Stats } from 'node:fs'\nimport { basename, dirname, isAbsolute, join } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\nimport { threadId } from 'node:worker_threads'\n\nimport { z } from 'zod'\n\nimport { assertWithinKnowledgeRoot } from '../knowledge-containment.js'\n\nexport const LEASE_FILE = '.lease'\nexport const EPOCH_FILE = '.epoch'\n\n/** Provisional writer-heartbeat TTL; retune from operational evidence without adding config. */\nexport const LEASE_HEARTBEAT_TTL_MS = 30_000\n\n/** Bounded mutation-lock takeover; retune from operational evidence without adding config. */\nexport const MUTATION_LOCK_TAKEOVER_MS = 45_000\n\n/** Authority-store filename is pinned; retune only through a data-migration plan. */\nexport const WRITER_AUTHORITY_DB_FILE = '.writer-authority.sqlite'\n\n/**\n * Provisional SQLite contention window; retune from operational evidence without adding config.\n *\n * The takeover deadline remains separate: this short timeout makes each failed write attempt\n * observable so the contender can apply the lease and verified-termination policy.\n */\nexport const MUTATION_LOCK_BUSY_TIMEOUT_MS = 2_000\n\n// A monotonic deadline no on-disk value can move; above the takeover bound, so a reclaim fits.\nexport const ACQUIRE_WRITER_LEASE_DEADLINE_MS = 60_000\n\n/** Provisional cap on one `ps` incarnation fork; retune from operational evidence without config. */\nconst PROCESS_INCARNATION_PS_TIMEOUT_MS = 1_000\n\n/** Provisional floor for that cap — the bounded overshoot argued for at `psIncarnationCapMs`. */\nconst PROCESS_INCARNATION_PS_FLOOR_MS = 250\n\nconst PROCESS_INCARNATION_PS_PATH = '/bin/ps'\nconst PROCESS_INCARNATION_PS_ENV = Object.freeze({ LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' })\n\nconst MUTATION_LOCK_TERMINATION_POLL_MS = 10\nconst MUTATION_LOCK_TERMINATION_TIMEOUT_MS = 5_000\nconst MUTATION_LOCK_TERMINATION_WAIT = new Int32Array(\n new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),\n)\n\n// Under `memory/queue/`, already gitignored, so a guard a crash leaves behind is never committed.\nexport const LEASE_GUARD_DIR = 'memory/queue/lease-guard'\n\nconst LEASE_GUARD_OWNER_PREFIX = 'owner-'\n\n/** A guard older than this cannot belong to a live section (each is one read and one write). */\nexport const LEASE_GUARD_STALE_MS = 10_000\n\n// Longer than the stale bound: a killed thread's guard carries a live pid, so only age clears it.\nexport const LEASE_GUARD_WAIT_MS = LEASE_GUARD_STALE_MS + 2_000\n\n/** A staging directory lives at most as long as its waiter, so one older than this is a leak. */\nconst LEASE_GUARD_STAGING_STALE_MS = LEASE_GUARD_WAIT_MS + LEASE_GUARD_STALE_MS\n\nconst LEASE_GUARD_STAGING_PREFIX = `${basename(LEASE_GUARD_DIR)}.tmp-`\n\nconst LEASE_GUARD_RESIDUE_PREFIX = `${basename(LEASE_GUARD_DIR)}.residue-`\n\nconst LEASE_GUARD_POLL_MS = 2\n\nconst writerLeaseSchema = z\n .object({\n leaseId: z.string().uuid(),\n pid: z.number().int().positive(),\n epoch: z.number().int().positive(),\n heartbeatAtMs: z.number().int().nonnegative(),\n })\n .strict()\n\nexport type WriterLease = z.infer<typeof writerLeaseSchema>\n\n/** What the contender could observe about the owner it gave up on; never an authority claim. */\nexport interface UnreclaimableMutationLockOwner {\n pid: number\n acquiredAtMs: number\n generationToken: string\n /** False when the row carries no incarnation, which is why escalation could never fire. */\n incarnationAttributed: boolean\n}\n\nexport type AcquireWriterLeaseOutcome =\n | { kind: 'held'; holder: WriterLease }\n | { kind: 'acquired'; leaseId: string; epoch: number; reclaimed?: WriterLease }\n | {\n kind: 'refused'\n reason: 'corrupt-epoch-state'\n error: CorruptEpochStateError\n }\n | {\n // `code` is the raw errno, so an operator sees `EACCES`, not a silent spin.\n kind: 'refused'\n reason: 'unreadable-lease-state'\n code: string\n error: UnreadableWriterLeaseStateError\n }\n | {\n kind: 'refused'\n reason: 'mutation-lock-unreclaimable'\n // Both refusal arms carry an `error`, so every caller renders a new arm by name.\n error: WriterLeaseUnreclaimableError\n attempts: number\n waitedMs: number\n observedOwner?: UnreclaimableMutationLockOwner\n observedLease?: WriterLease\n }\n\nexport interface LeaseOperationOptions {\n knowledgeRoot: string\n leaseId: string\n}\n\n/** Test/chaos seam on the lease-file guard taken by `heartbeatLease` and `releaseLease`. */\nexport interface LeaseGuardHooks {\n /** Fires once, when the guard is first found held by a live section other than this caller's. */\n onLeaseGuardContended?: () => void\n /** Fires each time a guard has been judged residue, before this caller reclaims it. */\n beforeLeaseGuardReclaim?: () => void\n /** Fires inside a reclaim, after its first step and before its last. */\n duringLeaseGuardReclaim?: () => void\n}\n\nexport type HeartbeatLeaseOutcome =\n | { kind: 'heartbeated'; holder: WriterLease }\n | {\n kind: 'refused'\n reason:\n | 'lease-missing'\n | 'lease-malformed'\n // The lease exists and could not be opened; nothing writes over what it cannot read.\n | 'lease-unreadable'\n | 'lease-id-mismatch'\n | 'stale-epoch'\n | 'corrupt-epoch-state'\n holder?: WriterLease\n observedEpoch?: number\n error?: CorruptEpochStateError\n }\n\nexport type ReleaseLeaseOutcome =\n | { kind: 'released' }\n | {\n kind: 'refused'\n reason: 'lease-missing' | 'lease-malformed' | 'lease-unreadable' | 'lease-id-mismatch'\n holder?: WriterLease\n }\n\nexport interface AssertEpochCurrentOptions {\n knowledgeRoot: string\n epoch: number\n}\n\nexport type AssertEpochCurrentOutcome =\n | { current: true }\n | { current: false; observedEpoch: number }\n\n/** Exact writer identity carried by governed maintenance mutators. */\nexport interface WriterLeaseAuthority extends LeaseOperationOptions {\n epoch: number\n}\n\nexport type WriterAuthorityLostReason =\n | Extract<HeartbeatLeaseOutcome, { kind: 'refused' }>['reason']\n | 'epoch-mismatch-before-heartbeat'\n | 'epoch-mismatch-after-heartbeat'\n | 'mutation-lock-generation-lost'\n\n/** Fail-closed maintenance refusal with the holder and fresh disk epoch attached. */\nexport class WriterAuthorityLostError extends Error {\n override readonly name = 'WriterAuthorityLostError'\n readonly authority: WriterLeaseAuthority\n readonly reason: WriterAuthorityLostReason\n readonly observedEpoch: number\n\n constructor(\n authority: WriterLeaseAuthority,\n reason: WriterAuthorityLostReason,\n observedEpoch: number,\n ) {\n super(\n `writer authority lost (${reason}); held epoch ${authority.epoch}, observed ${observedEpoch}`,\n )\n this.authority = authority\n this.reason = reason\n this.observedEpoch = observedEpoch\n }\n}\n\nexport type CorruptEpochStateReason = 'unreadable' | 'malformed' | 'overflow'\n\n/** Fail-closed authority-state error; callers must never substitute epoch zero for this state. */\nexport class CorruptEpochStateError extends Error {\n override readonly name = 'CorruptEpochStateError'\n readonly path: string\n readonly reason: CorruptEpochStateReason\n readonly rawPreview: string\n\n constructor(path: string, reason: CorruptEpochStateReason, rawPreview: string) {\n super(`writer epoch state is corrupt (${reason}) at ${path}`)\n this.path = path\n this.reason = reason\n this.rawPreview = rawPreview\n }\n}\n\n// Fail-closed refusal after the deadline; carries the owner it kept losing to and the lease read.\nexport class WriterLeaseUnreclaimableError extends Error {\n override readonly name = 'WriterLeaseUnreclaimableError'\n readonly reason = 'mutation-lock-unreclaimable' as const\n readonly attempts: number\n readonly waitedMs: number\n readonly observedOwner?: UnreclaimableMutationLockOwner\n readonly observedLease?: WriterLease\n\n constructor(\n attempts: number,\n waitedMs: number,\n observedOwner?: UnreclaimableMutationLockOwner,\n observedLease?: WriterLease,\n ) {\n super(\n `writer lease acquisition refused (mutation-lock-unreclaimable) after ${attempts} `\n + `attempts over ${Math.round(waitedMs)}ms; `\n + (observedOwner === undefined\n ? 'no mutation-lock owner was readable'\n : `mutation lock held by pid ${observedOwner.pid} (generation `\n + `${observedOwner.generationToken}, incarnation `\n + `${observedOwner.incarnationAttributed ? 'attributed' : 'unattributed'})`)\n + '; '\n + (observedLease === undefined\n ? 'no parseable lease on disk'\n : `lease ${observedLease.leaseId} at epoch ${observedLease.epoch} held by pid `\n + `${observedLease.pid}`),\n )\n this.attempts = attempts\n this.waitedMs = waitedMs\n if (observedOwner !== undefined) this.observedOwner = observedOwner\n if (observedLease !== undefined) this.observedLease = observedLease\n }\n}\n\n// Every refusal arm carries a throwable `error`; callers rethrow it without knowing the arm.\nexport class UnreadableWriterLeaseStateError extends Error {\n override readonly name = 'UnreadableWriterLeaseStateError'\n readonly path: string\n readonly code: string\n\n constructor(path: string, code: string) {\n super(`writer lease state is unreadable (${code}) at ${path}`)\n this.path = path\n this.code = code\n }\n}\n\n// `unreadable` (exists, cannot be opened) stays apart from `malformed`, which reads as no holder.\nexport type ReadWriterLeaseOutcome =\n | { kind: 'absent' }\n | { kind: 'malformed' }\n | { kind: 'unreadable'; code: string }\n | { kind: 'parsed'; lease: WriterLease }\n\nfunction assertAbsoluteKnowledgeRoot(knowledgeRoot: string): void {\n if (!isAbsolute(knowledgeRoot)) {\n throw new TypeError('knowledgeRoot must be absolute')\n }\n}\n\nfunction leasePath(knowledgeRoot: string): string {\n return join(knowledgeRoot, LEASE_FILE)\n}\n\nfunction epochPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, EPOCH_FILE)\n}\n\nfunction writerAuthorityDbPath(knowledgeRoot: string): string {\n return join(knowledgeRoot, WRITER_AUTHORITY_DB_FILE)\n}\n\nfunction bestEffortFsyncDirectory(dir: string): void {\n let fd: number | undefined\n try {\n fd = openSync(dir, 'r')\n fsyncSync(fd)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (\n code !== 'ENOENT' &&\n code !== 'EINVAL' &&\n code !== 'EISDIR' &&\n code !== 'EPERM' &&\n code !== 'ENOTSUP'\n ) {\n throw error\n }\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\ninterface MutationLockOwner {\n pid: number\n acquiredAtMs: number\n generationToken: string\n /** OS-reported start-time token of the process that created this row; absent when unresolvable. */\n incarnation?: string\n}\n\n// A pid can be reused, so the start time names the process; `undefined` means do not signal.\nexport function resolveProcessIncarnation(\n pid: number,\n timeoutMs?: number,\n psExecutable?: string,\n): string | undefined {\n if (!Number.isSafeInteger(pid) || pid <= 0) return undefined\n try {\n if (process.platform === 'win32') return undefined\n return process.platform === 'linux'\n ? resolveLinuxProcessIncarnation(pid)\n : resolvePosixProcessIncarnation(pid, timeoutMs, psExecutable)\n } catch {\n return undefined\n }\n}\n\nexport function incarnationFormat(token: string): string {\n const separator = token.indexOf(':')\n return separator < 0 ? '' : token.slice(0, separator)\n}\n\nfunction resolveLinuxProcessIncarnation(pid: number): string | undefined {\n let raw: string\n try {\n raw = readFileSync(`/proc/${pid}/stat`, 'utf8')\n } catch {\n return undefined\n }\n const commEnd = raw.lastIndexOf(')')\n if (commEnd < 0) return undefined\n // The first field after `comm` is `state` (field 3), so `starttime` (field 22) sits at index 19.\n const startTime = raw.slice(commEnd + 1).trim().split(/\\s+/)[19]\n return startTime !== undefined && /^\\d+$/.test(startTime)\n ? `proc-starttime:${startTime}`\n : undefined\n}\n\nfunction resolvePosixProcessIncarnation(\n pid: number,\n timeoutMs?: number,\n psExecutable: string = PROCESS_INCARNATION_PS_PATH,\n): string | undefined {\n // One rendering for every reader: the caller's `PATH`, `TZ` and locale never reach `ps`.\n const observed = spawnSync(psExecutable, ['-p', String(pid), '-o', 'lstart='], {\n encoding: 'utf8',\n env: PROCESS_INCARNATION_PS_ENV,\n windowsHide: true,\n // `spawnSync` reads 0 as \"no timeout\", so an exhausted budget must never arrive here as 0.\n ...(timeoutMs === undefined ? {} : { timeout: Math.max(1, Math.ceil(timeoutMs)) }),\n })\n if (observed.error !== undefined || observed.status !== 0) return undefined\n const lstart = (observed.stdout ?? '').trim()\n return lstart === '' ? undefined : `ps-lstart-utc:${lstart}`\n}\n\nconst OWN_INCARNATION_UNRESOLVED = Symbol('own-incarnation-unresolved')\n// A resolved token or the sentinel: memoising `undefined` would make one missed fork permanent.\nlet ownIncarnation: string | typeof OWN_INCARNATION_UNRESOLVED = OWN_INCARNATION_UNRESOLVED\n\n// Memoises only a resolved token; a miss returns `undefined` and the next claim forks `ps` again.\nfunction ownProcessIncarnation(escalation: MutationEscalationContext = {}): string | undefined {\n if (ownIncarnation !== OWN_INCARNATION_UNRESOLVED) return ownIncarnation\n const resolved = resolveProcessIncarnation(\n process.pid,\n psIncarnationCapMs(escalation),\n escalation.psExecutable,\n )\n escalation.onIncarnationResolved?.(process.pid)\n if (resolved === undefined) return undefined\n ownIncarnation = resolved\n return resolved\n}\n\nexport interface MutationLockOptions {\n /** Test/chaos seam after the claim is committed and before the held transaction begins. */\n afterMutationLockClaimed?: (generationToken: string) => void\n afterMutationLockAcquired?: () => void\n /** Test/chaos seam inside acquisition, after the epoch rewrite and before lease publication. */\n afterEpochRewrite?: () => void\n mutationLockTakeoverMs?: number\n /**\n * Test-only observation of every process-incarnation resolution the escalation path performs.\n *\n * Purely an observer, never a replacement: the production resolver still runs, so what a test\n * counts is what a daemon pays. It exists because the cost being bounded (a `ps` fork per\n * resolution, on the caller's main thread) is invisible to any assertion about outcomes.\n */\n onProcessIncarnationResolved?: (pid: number) => void\n // Test-only replacement for `/bin/ps`, for a wedged process table; production never sets it.\n psExecutable?: string\n}\n\n// Escalation waits spend the caller's acquisition deadline, so the budget is passed down.\ninterface MutationEscalationContext {\n /** Absolute monotonic instant past which no escalation wait may continue; absent = no budget. */\n readonly deadlineAtNs?: bigint\n readonly onIncarnationResolved?: (pid: number) => void\n readonly psExecutable?: string\n}\n\nexport interface AcquireWriterLeaseOptions extends MutationLockOptions {\n // Test seam that shortens the acquisition deadline; production never sets it.\n acquireDeadlineMs?: number\n}\n\nexport interface CurrentWriterAuthority {\n leaseId: string\n epoch: number\n}\n\nexport interface CurrentWriterAuthorityHooks extends MutationLockOptions {\n /** Test/chaos seam after the lock-held epoch comparison and before mutation. */\n afterFinalAuthorityCompare?: () => void\n}\n\nclass MutationLockBusyError extends Error {\n override readonly name = 'MutationLockBusyError'\n readonly owner?: MutationLockOwner\n\n constructor(owner?: MutationLockOwner) {\n super('writer lease mutation lock is busy')\n this.owner = owner\n }\n}\n\nclass MutationLockGenerationLostError extends Error {\n override readonly name = 'MutationLockGenerationLostError'\n}\n\nclass LeaseGuardBusyError extends Error {\n override readonly name = 'LeaseGuardBusyError'\n}\n\nfunction mutationLockNowMs(): number {\n return new Date().getTime()\n}\n\n/**\n * Elapsed milliseconds from a `process.hrtime.bigint()` reading, immune to wall-clock movement.\n *\n * The acquisition deadline must not be extendable by anything the contended state can influence,\n * and a wall clock can be stepped backwards by NTP or by a test's own `Date.now` stub. This is the\n * external anchor the bound is measured against.\n */\nfunction monotonicElapsedMs(startedAtNs: bigint): number {\n return Number(process.hrtime.bigint() - startedAtNs) / 1e6\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ESRCH') return false\n if (code === 'EPERM') return true\n throw error\n }\n}\n\nfunction isSqliteBusy(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /database is (?:locked|busy)/i.test((error as Error).message)\n}\n\nfunction openWriterAuthorityDb(knowledgeRoot: string): DatabaseSync {\n mkdirSync(knowledgeRoot, { recursive: true })\n const db = new DatabaseSync(writerAuthorityDbPath(knowledgeRoot), {\n timeout: MUTATION_LOCK_BUSY_TIMEOUT_MS,\n })\n try {\n db.exec('PRAGMA journal_mode = WAL')\n db.exec(`PRAGMA busy_timeout = ${MUTATION_LOCK_BUSY_TIMEOUT_MS}`)\n db.exec(`\n CREATE TABLE IF NOT EXISTS mutation_lock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n generation_token TEXT NOT NULL,\n pid INTEGER NOT NULL CHECK (pid > 0),\n acquired_at_ms INTEGER NOT NULL CHECK (acquired_at_ms >= 0),\n incarnation TEXT\n ) STRICT\n `)\n upgradeMutationLockSchema(db)\n return db\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n// Racing daemons both run the `ALTER`; the loser's `duplicate column name` means success.\nfunction upgradeMutationLockSchema(db: DatabaseSync): void {\n const columns = db.prepare(`\n SELECT name FROM pragma_table_info('mutation_lock')\n `).all() as { name: string }[]\n if (columns.some((column) => column.name === 'incarnation')) return\n try {\n db.exec('ALTER TABLE mutation_lock ADD COLUMN incarnation TEXT')\n } catch (error) {\n if (!isDuplicateMutationLockColumn(error)) throw error\n }\n}\n\n/** Classified by message beside `isMissingMutationLockTable`, which node:sqlite likewise untypes. */\nfunction isDuplicateMutationLockColumn(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /duplicate column name/i.test((error as Error).message)\n}\n\nfunction parseMutationLockOwner(value: unknown): MutationLockOwner | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const row = value as Record<string, unknown>\n return typeof row.pid === 'number'\n && Number.isSafeInteger(row.pid)\n && row.pid > 0\n && typeof row.acquired_at_ms === 'number'\n && Number.isSafeInteger(row.acquired_at_ms)\n && row.acquired_at_ms >= 0\n && typeof row.generation_token === 'string'\n && row.generation_token !== ''\n ? {\n pid: row.pid,\n acquiredAtMs: row.acquired_at_ms,\n generationToken: row.generation_token,\n // A row written before the incarnation column existed, or by a claimant that could not\n // resolve its own start time, is deliberately left unattributed rather than guessed at.\n ...(typeof row.incarnation === 'string' && row.incarnation !== ''\n ? { incarnation: row.incarnation }\n : {}),\n }\n : undefined\n}\n\nfunction readMutationLockOwner(db: DatabaseSync): MutationLockOwner | undefined {\n // `SELECT *` so a store that predates the incarnation column still reads through a read-only\n // connection, which has no opportunity to upgrade the schema.\n return parseMutationLockOwner(db.prepare(`\n SELECT * FROM mutation_lock WHERE id = 1\n `).get())\n}\n\n// Absent store, missing table and busy store answer `undefined`, which callers read as no owner.\nfunction readCommittedMutationLockOwner(\n knowledgeRoot: string,\n): MutationLockOwner | undefined {\n try {\n const db = new DatabaseSync(writerAuthorityDbPath(knowledgeRoot), {\n readOnly: true,\n timeout: 0,\n })\n try {\n return readMutationLockOwner(db)\n } finally {\n db.close()\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n // The store file exists before its `CREATE TABLE`, so a missing table means no committed claim.\n if (isMissingMutationLockTable(error)) return undefined\n // A store whose write lock is held by someone else answers nothing about who committed a\n // claim. `timeout: 0` is deliberate — this read is diagnostics on a path that has already\n // decided to refuse, so waiting on it would spend budget to learn a detail.\n if (isSqliteBusy(error)) return undefined\n throw error\n }\n}\n\nfunction isMissingMutationLockTable(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === 'ERR_SQLITE_ERROR'\n && /no such table: mutation_lock/i.test((error as Error).message)\n}\n\nfunction mutationLockGenerationIsCurrent(\n db: DatabaseSync,\n generationToken: string,\n): boolean {\n return readMutationLockOwner(db)?.generationToken === generationToken\n}\n\nfunction compareAndSwapMutationLock(\n db: DatabaseSync,\n expected: MutationLockOwner,\n replacement: MutationLockOwner,\n): boolean {\n const result = db.prepare(`\n UPDATE mutation_lock\n SET generation_token = ?, pid = ?, acquired_at_ms = ?, incarnation = ?\n WHERE id = 1 AND generation_token = ?\n `).run(\n replacement.generationToken,\n replacement.pid,\n replacement.acquiredAtMs,\n replacement.incarnation ?? null,\n expected.generationToken,\n )\n return result.changes === 1\n}\n\n/** What the caller has left of its acquisition budget, or `undefined` when it declared none. */\nfunction remainingEscalationBudgetMs(escalation: MutationEscalationContext): number | undefined {\n if (escalation.deadlineAtNs === undefined) return undefined\n return Math.max(Number(escalation.deadlineAtNs - process.hrtime.bigint()) / 1e6, 0)\n}\n\n// Bounded by the caller's budget: a killed child of a blocked process is never reaped.\nfunction waitForVerifiedProcessExit(\n pid: number,\n escalation: MutationEscalationContext,\n): boolean {\n const startedAtNs = process.hrtime.bigint()\n const remainingMs = remainingEscalationBudgetMs(escalation)\n const boundMs = remainingMs === undefined\n ? MUTATION_LOCK_TERMINATION_TIMEOUT_MS\n : Math.min(MUTATION_LOCK_TERMINATION_TIMEOUT_MS, remainingMs)\n while (processIsAlive(pid)) {\n if (monotonicElapsedMs(startedAtNs) >= boundMs) return false\n Atomics.wait(\n MUTATION_LOCK_TERMINATION_WAIT,\n 0,\n 0,\n MUTATION_LOCK_TERMINATION_POLL_MS,\n )\n }\n return true\n}\n\ntype MutationLockOwnerIdentity = 'match' | 'mismatch' | 'unverifiable'\n\n// Floored: `spawnSync` reads a zero timeout as none. An expired cap still refuses to signal.\nfunction psIncarnationCapMs(escalation: MutationEscalationContext): number {\n const remainingMs = remainingEscalationBudgetMs(escalation)\n return Math.max(PROCESS_INCARNATION_PS_FLOOR_MS, Math.min(\n PROCESS_INCARNATION_PS_TIMEOUT_MS,\n remainingMs ?? PROCESS_INCARNATION_PS_TIMEOUT_MS,\n ))\n}\n\n// An unattributed row or an unresolvable pid answers `unverifiable`, which refuses the signal.\nfunction verifyMutationLockOwnerIdentity(\n owner: MutationLockOwner,\n escalation: MutationEscalationContext,\n): MutationLockOwnerIdentity {\n if (owner.incarnation === undefined) return 'unverifiable'\n const occupant = resolveProcessIncarnation(\n owner.pid,\n psIncarnationCapMs(escalation),\n escalation.psExecutable,\n )\n escalation.onIncarnationResolved?.(owner.pid)\n if (occupant === undefined) return 'unverifiable'\n if (incarnationFormat(occupant) !== incarnationFormat(owner.incarnation)) return 'unverifiable'\n return occupant === owner.incarnation ? 'match' : 'mismatch'\n}\n\n// Re-checks the incarnation before `SIGKILL`; a reused pid proves death and is never signalled.\nfunction terminateExactMutationLockOwner(\n owner: MutationLockOwner,\n escalation: MutationEscalationContext,\n): boolean {\n if (owner.pid === process.pid) return false\n const identity = verifyMutationLockOwnerIdentity(owner, escalation)\n if (identity === 'unverifiable') return false\n if (identity === 'mismatch') return true\n try {\n process.kill(owner.pid, 'SIGKILL')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ESRCH') {\n if (code === 'EPERM') return false\n throw error\n }\n }\n return waitForVerifiedProcessExit(owner.pid, escalation)\n}\n\n// Only `reclaimable` permits the kill; an unknown epoch or an unreadable lease refuses it.\nfunction leasePermitsEscalation(knowledgeRoot: string, owner: MutationLockOwner): boolean {\n if (!processIsAlive(owner.pid)) return true\n const lease = readWriterLease(knowledgeRoot)\n switch (lease.kind) {\n case 'absent':\n case 'malformed':\n return true\n case 'unreadable':\n return false\n case 'parsed':\n return deriveWriterLeaseFreshness(\n knowledgeRoot,\n lease.lease,\n mutationLockNowMs(),\n ).kind === 'reclaimable'\n }\n}\n\nfunction tryEscalatedMutationLockTakeover(\n db: DatabaseSync,\n knowledgeRoot: string,\n expected: MutationLockOwner,\n replacement: MutationLockOwner,\n takeoverMs: number,\n escalation: MutationEscalationContext,\n): boolean {\n if (mutationLockNowMs() - expected.acquiredAtMs < takeoverMs) return false\n if (!leasePermitsEscalation(knowledgeRoot, expected)) return false\n if (\n processIsAlive(expected.pid)\n && !terminateExactMutationLockOwner(expected, escalation)\n ) {\n return false\n }\n\n const observedAfterTermination = readMutationLockOwner(db)\n if (observedAfterTermination?.generationToken !== expected.generationToken) return false\n try {\n return compareAndSwapMutationLock(db, expected, replacement)\n } catch (error) {\n // A mismatched incarnation reclaims without killing anything, so the write lock can still be\n // held by whoever made the store busy. That is an ordinary retry, not a failure to surface.\n if (isSqliteBusy(error)) return false\n throw error\n }\n}\n\nfunction claimMutationLock(\n db: DatabaseSync,\n knowledgeRoot: string,\n owner: MutationLockOwner,\n takeoverMs: number,\n escalation: MutationEscalationContext,\n): void {\n try {\n const inserted = db.prepare(`\n INSERT INTO mutation_lock (id, generation_token, pid, acquired_at_ms, incarnation)\n VALUES (1, ?, ?, ?, ?)\n ON CONFLICT(id) DO NOTHING\n `).run(\n owner.generationToken,\n owner.pid,\n owner.acquiredAtMs,\n owner.incarnation ?? null,\n )\n if (inserted.changes === 1) return\n } catch (error) {\n if (!isSqliteBusy(error)) throw error\n const current = readMutationLockOwner(db)\n if (\n current !== undefined\n && tryEscalatedMutationLockTakeover(\n db,\n knowledgeRoot,\n current,\n owner,\n takeoverMs,\n escalation,\n )\n ) {\n return\n }\n throw new MutationLockBusyError(current)\n }\n\n const current = readMutationLockOwner(db)\n if (current === undefined) {\n throw new MutationLockBusyError()\n }\n\n const ownerIsDead = !processIsAlive(current.pid)\n const ownerPastDeadline =\n mutationLockNowMs() - current.acquiredAtMs >= takeoverMs\n if (!ownerIsDead && !ownerPastDeadline) {\n throw new MutationLockBusyError(current)\n }\n\n try {\n if (compareAndSwapMutationLock(db, current, owner)) return\n } catch (error) {\n if (!isSqliteBusy(error)) throw error\n if (\n tryEscalatedMutationLockTakeover(\n db,\n knowledgeRoot,\n current,\n owner,\n takeoverMs,\n escalation,\n )\n ) {\n return\n }\n throw new MutationLockBusyError(current)\n }\n throw new MutationLockBusyError(readMutationLockOwner(db))\n}\n\nfunction releaseMutationLock(db: DatabaseSync, generationToken: string): void {\n db.prepare(`\n DELETE FROM mutation_lock\n WHERE id = 1 AND generation_token = ?\n `).run(generationToken)\n}\n\nfunction withMutationLock<T>(\n knowledgeRoot: string,\n mutate: (generationToken: string, db: DatabaseSync) => T,\n options: MutationLockOptions = {},\n /**\n * The caller's acquisition deadline, when it has one.\n *\n * Only `acquireWriterLease` does: a heartbeat or a governed mutation is not racing a bound, so\n * omitting it leaves those paths on the pinned termination window exactly as before.\n */\n deadlineAtNs?: bigint,\n): T {\n const escalation: MutationEscalationContext = {\n ...(deadlineAtNs === undefined ? {} : { deadlineAtNs }),\n ...(options.onProcessIncarnationResolved === undefined\n ? {}\n : { onIncarnationResolved: options.onProcessIncarnationResolved }),\n ...(options.psExecutable === undefined ? {} : { psExecutable: options.psExecutable }),\n }\n let db: DatabaseSync\n try {\n db = openWriterAuthorityDb(knowledgeRoot)\n } catch (error) {\n if (isSqliteBusy(error)) {\n throw new MutationLockBusyError(\n readCommittedMutationLockOwner(knowledgeRoot),\n )\n }\n throw error\n }\n const claimantIncarnation = ownProcessIncarnation(escalation)\n const owner: MutationLockOwner = {\n pid: process.pid,\n acquiredAtMs: mutationLockNowMs(),\n generationToken: randomUUID(),\n // A claimant that cannot prove its own incarnation records none, accepting that its row may\n // then only ever be reclaimed after it really dies. Never a fabricated token.\n ...(claimantIncarnation === undefined ? {} : { incarnation: claimantIncarnation }),\n }\n const takeoverMs = options.mutationLockTakeoverMs ?? MUTATION_LOCK_TAKEOVER_MS\n let claimed = false\n let transactionOpen = false\n try {\n claimMutationLock(db, knowledgeRoot, owner, takeoverMs, escalation)\n claimed = true\n options.afterMutationLockClaimed?.(owner.generationToken)\n try {\n db.exec('BEGIN IMMEDIATE')\n transactionOpen = true\n } catch (error) {\n if (isSqliteBusy(error)) throw new MutationLockBusyError(readMutationLockOwner(db))\n throw error\n }\n\n if (!mutationLockGenerationIsCurrent(db, owner.generationToken)) {\n throw new MutationLockGenerationLostError()\n }\n options.afterMutationLockAcquired?.()\n const result = mutate(owner.generationToken, db)\n db.exec('COMMIT')\n transactionOpen = false\n return result\n } finally {\n if (transactionOpen) {\n try {\n db.exec('ROLLBACK')\n } catch {\n // The original failure is authoritative.\n }\n }\n if (claimed) {\n try {\n releaseMutationLock(db, owner.generationToken)\n } catch {\n // A crashed/contended cleanup leaves a CAS-recoverable row.\n }\n }\n db.close()\n }\n}\n\nfunction sweepStagedEpochsBefore(knowledgeRoot: string, epoch: number): void {\n const memoryRoot = join(knowledgeRoot, 'memory')\n let products: Dirent<string>[]\n try {\n products = readdirSync(memoryRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n\n for (const product of products) {\n if (!product.isDirectory()) continue\n const bundlesDir = join(memoryRoot, product.name, 'bundles')\n const stagingRoot = join(bundlesDir, '.staging')\n let staged: Dirent<string>[]\n try {\n staged = readdirSync(stagingRoot, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue\n throw error\n }\n for (const entry of staged) {\n if (!entry.isDirectory()) continue\n const match = /^\\.staged-epoch-(\\d+)-[A-Za-z0-9._-]+$/.exec(entry.name)\n if (match === null) continue\n const stagedEpoch = Number(match[1])\n if (!Number.isSafeInteger(stagedEpoch) || stagedEpoch >= epoch) continue\n rmSync(join(stagingRoot, entry.name), { recursive: true, force: true })\n }\n if (existsSync(stagingRoot)) bestEffortFsyncDirectory(stagingRoot)\n try {\n rmdirSync(stagingRoot)\n bestEffortFsyncDirectory(bundlesDir)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error\n }\n }\n}\n\nfunction atomicRewrite(file: string, text: string): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.tmp-${randomUUID()}`\n let fd: number | undefined\n try {\n fd = openSync(temporary, 'wx')\n writeFileSync(fd, text, 'utf8')\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n renameSync(temporary, file)\n bestEffortFsyncDirectory(dirname(file))\n } finally {\n if (fd !== undefined) closeSync(fd)\n rmSync(temporary, { force: true })\n }\n}\n\nconst leaseGuardOwnerSchema = z\n .object({\n pid: z.number().int().positive(),\n threadId: z.number().int().nonnegative(),\n token: z.string().uuid(),\n claimedAtNs: z.string().regex(/^[0-9]+$/),\n })\n .strict()\n\ntype LeaseGuardOwner = z.infer<typeof leaseGuardOwnerSchema>\n\ntype ObservedLeaseGuard =\n | { kind: 'vacant' }\n | { kind: 'held'; ownerFile: string; owner?: LeaseGuardOwner }\n\nfunction ignoreErrno(run: () => void, codes: readonly string[]): void {\n try {\n run()\n } catch (error) {\n if (!codes.includes((error as NodeJS.ErrnoException).code ?? '')) throw error\n }\n}\n\nfunction errnoOf(error: unknown): string {\n return (error as NodeJS.ErrnoException).code ?? ''\n}\n\n/** `lstat` that answers `undefined` for a missing entry; it never follows a link. */\nfunction lstatOrAbsent(path: string): Stats | undefined {\n try {\n return lstatSync(path)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return undefined\n throw error\n }\n}\n\n/** Move a directory nothing can attribute aside, whole: its entries are never ours to delete. */\nfunction moveLeaseGuardAside(guard: string): void {\n const aside = join(dirname(guard), `${LEASE_GUARD_RESIDUE_PREFIX}${randomUUID()}`)\n ignoreErrno(() => renameSync(guard, aside), ['ENOENT'])\n}\n\n/** Read an owner file without following a link or blocking on a special file. */\nfunction readLeaseGuardOwner(path: string, name: string): LeaseGuardOwner | undefined {\n const fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK)\n let raw: string\n try {\n raw = readFileSync(fd, 'utf8')\n } finally {\n closeSync(fd)\n }\n try {\n const parsed = leaseGuardOwnerSchema.safeParse(JSON.parse(raw))\n return parsed.success && `${LEASE_GUARD_OWNER_PREFIX}${parsed.data.token}` === name\n ? parsed.data\n : undefined\n } catch {\n return undefined\n }\n}\n\n// `unlink` removes a link, never its target; an unattributable directory is moved aside whole.\nfunction observeLeaseGuard(guard: string): ObservedLeaseGuard {\n const stat = lstatOrAbsent(guard)\n if (stat === undefined) return { kind: 'vacant' }\n if (!stat.isDirectory()) {\n ignoreErrno(() => unlinkSync(guard), ['ENOENT', 'EISDIR', 'EPERM'])\n return { kind: 'vacant' }\n }\n let names: string[]\n try {\n names = readdirSync(guard)\n } catch (error) {\n // Replaced between the two calls: the next observation judges whatever is there now.\n if (errnoOf(error) === 'ENOENT' || errnoOf(error) === 'ENOTDIR') return { kind: 'vacant' }\n throw error\n }\n if (names.length === 0) {\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n return { kind: 'vacant' }\n }\n const ownerFile = names.filter((name) => name.startsWith(LEASE_GUARD_OWNER_PREFIX)).sort()[0]\n const ownerStat = ownerFile === undefined ? undefined : lstatOrAbsent(join(guard, ownerFile))\n if (ownerFile === undefined || (ownerStat !== undefined && !ownerStat.isFile())) {\n moveLeaseGuardAside(guard)\n return { kind: 'vacant' }\n }\n if (ownerStat === undefined) return { kind: 'vacant' }\n let owner: LeaseGuardOwner | undefined\n try {\n owner = readLeaseGuardOwner(join(guard, ownerFile), ownerFile)\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return { kind: 'vacant' }\n if (errnoOf(error) === 'ELOOP') {\n moveLeaseGuardAside(guard)\n return { kind: 'vacant' }\n }\n throw error\n }\n return owner === undefined ? { kind: 'held', ownerFile } : { kind: 'held', ownerFile, owner }\n}\n\n// Housekeeping that never fails the section; it sweeps by owner name then `rmdir`, like a reclaim.\nfunction sweepLeakedLeaseGuardStaging(parent: string, ownStaged: string): void {\n let names: string[]\n try {\n names = readdirSync(parent)\n } catch {\n return\n }\n for (const name of names) {\n if (!name.startsWith(LEASE_GUARD_STAGING_PREFIX)) continue\n const dir = join(parent, name)\n if (dir === ownStaged) continue\n try {\n sweepLeakedStagingDirectory(dir)\n } catch {\n // Left for a later sweep.\n }\n }\n}\n\nfunction sweepLeakedStagingDirectory(dir: string): void {\n const stat = lstatOrAbsent(dir)\n if (stat === undefined || !stat.isDirectory()) return\n const entries = readdirSync(dir)\n // Wall clock, not `Date.now()`: the beat's only `Date.now()` is a seam the race cells use.\n const nowMs = mutationLockNowMs()\n if (entries.length === 0) {\n // Staged, not yet written: judged by its own age only.\n if (nowMs - stat.mtimeMs >= LEASE_GUARD_STAGING_STALE_MS) {\n ignoreErrno(() => rmdirSync(dir), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n }\n return\n }\n const ownerFile = entries[0]!\n if (entries.length !== 1 || !ownerFile.startsWith(LEASE_GUARD_OWNER_PREFIX)) return\n const ownerPath = join(dir, ownerFile)\n const ownerStat = lstatOrAbsent(ownerPath)\n if (ownerStat === undefined || !ownerStat.isFile()) return\n const owner = readLeaseGuardOwner(ownerPath, ownerFile)\n // An owner being written can read as nothing yet, so unattributable bytes wait out the bound.\n const residue = owner === undefined\n ? nowMs - ownerStat.mtimeMs >= LEASE_GUARD_STAGING_STALE_MS\n : leaseGuardOwnerIsResidue(owner, LEASE_GUARD_STAGING_STALE_MS)\n if (!residue) return\n ignoreErrno(() => unlinkSync(ownerPath), ['ENOENT'])\n ignoreErrno(() => rmdirSync(dir), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n}\n\n/**\n * True when no live section can still be behind the guard.\n *\n * Unattributable owner bytes are residue. So is a claim from a dead process, one older than the\n * bound (a thread terminated inside its section leaves its live process's pid behind), and one\n * stamped ahead of this monotonic clock, which can only come from a previous boot.\n */\nfunction leaseGuardIsResidue(owner: LeaseGuardOwner | undefined): boolean {\n if (owner === undefined) return true\n return leaseGuardOwnerIsResidue(owner, LEASE_GUARD_STALE_MS)\n}\n\nfunction leaseGuardOwnerIsResidue(owner: LeaseGuardOwner, staleMs: number): boolean {\n const ageMs = Number(process.hrtime.bigint() - BigInt(owner.claimedAtNs)) / 1e6\n if (ageMs < 0 || ageMs >= staleMs) return true\n return owner.pid !== process.pid && !processIsAlive(owner.pid)\n}\n\n// Unlinks only the stale owner's file, then `rmdir`, so a late reclaimer removes nothing live.\nfunction reclaimLeaseGuard(guard: string, ownerFile: string, hooks: LeaseGuardHooks): void {\n ignoreErrno(() => unlinkSync(join(guard, ownerFile)), ['ENOENT'])\n hooks.duringLeaseGuardReclaim?.()\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n}\n\nfunction releaseLeaseGuard(guard: string, ownerFile: string): void {\n try {\n unlinkSync(join(guard, ownerFile))\n ignoreErrno(() => rmdirSync(guard), ['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'])\n } catch {\n // Whatever is left is residue, and the age bound reclaims it.\n }\n}\n\n// Mutations and acquisitions never take this guard, so no mutation can starve the beat.\nfunction withLeaseGuard<T>(\n knowledgeRoot: string,\n section: () => T,\n hooks: LeaseGuardHooks = {},\n): T {\n const guard = join(knowledgeRoot, LEASE_GUARD_DIR)\n assertWithinKnowledgeRoot(knowledgeRoot, dirname(guard))\n const claimedAtNs = process.hrtime.bigint()\n const token = randomUUID()\n const ownerFile = `${LEASE_GUARD_OWNER_PREFIX}${token}`\n const raw = `${JSON.stringify({\n pid: process.pid,\n threadId,\n token,\n claimedAtNs: String(claimedAtNs),\n })}\\n`\n const parent = dirname(guard)\n // `memory/queue/` and `memory/` are created only when absent, and removed again only by `rmdir`\n // (so only while empty), keeping a lease round-trip from leaving anything under `memory/`.\n const createdAncestors = [parent, dirname(parent)].filter((dir) => !existsSync(dir))\n const staged = `${guard}.tmp-${randomUUID()}`\n let contended = false\n try {\n try {\n while (true) {\n mkdirSync(parent, { recursive: true })\n try {\n mkdirSync(staged)\n break\n } catch (error) {\n // Another section's cleanup removed the empty parent between the two calls.\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n }\n writeFileSync(join(staged, ownerFile), raw, { encoding: 'utf8', flag: 'wx' })\n while (true) {\n try {\n renameSync(staged, guard)\n break\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'ENOTEMPTY' && code !== 'EEXIST' && code !== 'ENOTDIR') throw error\n }\n const observed = observeLeaseGuard(guard)\n if (observed.kind === 'vacant') continue\n const owner = observed.owner\n if (leaseGuardIsResidue(owner)) {\n hooks.beforeLeaseGuardReclaim?.()\n reclaimLeaseGuard(guard, observed.ownerFile, hooks)\n continue\n }\n if (owner?.pid === process.pid && owner.threadId === threadId) {\n throw new LeaseGuardBusyError(\n 'writer lease guard is held by an enclosing section on this thread',\n )\n }\n if (!contended) {\n contended = true\n hooks.onLeaseGuardContended?.()\n }\n if (monotonicElapsedMs(claimedAtNs) >= LEASE_GUARD_WAIT_MS) {\n throw new LeaseGuardBusyError(\n `writer lease guard stayed held by pid ${owner?.pid ?? 'unknown'} for `\n + `${LEASE_GUARD_WAIT_MS}ms`,\n )\n }\n Atomics.wait(MUTATION_LOCK_TERMINATION_WAIT, 0, 0, LEASE_GUARD_POLL_MS)\n }\n } finally {\n // After a successful claim the staged directory IS the guard, so nothing is left to remove.\n rmSync(staged, { recursive: true, force: true })\n }\n try {\n sweepLeakedLeaseGuardStaging(parent, staged)\n return section()\n } finally {\n releaseLeaseGuard(guard, ownerFile)\n }\n } finally {\n for (const dir of createdAncestors) {\n try {\n rmdirSync(dir)\n } catch {\n // Not empty, already gone, or not ours to judge: left as it is.\n }\n }\n }\n}\n\n// Only `ENOENT` means absent; any other read failure is `unreadable`, never absent or malformed.\nexport function readWriterLease(knowledgeRoot: string): ReadWriterLeaseOutcome {\n const file = leasePath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { kind: 'absent' }\n return { kind: 'unreadable', code: code ?? 'unknown-read-error' }\n }\n\n try {\n const parsed = writerLeaseSchema.safeParse(JSON.parse(raw))\n return parsed.success ? { kind: 'parsed', lease: parsed.data } : { kind: 'malformed' }\n } catch {\n return { kind: 'malformed' }\n }\n}\n\nfunction previewEpochState(raw: string): string {\n const preview = raw.slice(0, 64).replaceAll('\\r', '\\\\r').replaceAll('\\n', '\\\\n')\n return preview === '' ? '<empty>' : preview\n}\n\nfunction readEpoch(knowledgeRoot: string): number {\n const file = epochPath(knowledgeRoot)\n let raw: string\n try {\n raw = readFileSync(file, 'utf8')\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return 0\n throw new CorruptEpochStateError(file, 'unreadable', code ?? 'unknown-read-error')\n }\n const canonical = raw.endsWith('\\n') ? raw.slice(0, -1) : raw\n if (!/^(0|[1-9][0-9]*)$/.test(canonical)) {\n throw new CorruptEpochStateError(file, 'malformed', previewEpochState(raw))\n }\n const epoch = Number(canonical)\n if (!Number.isSafeInteger(epoch)) {\n throw new CorruptEpochStateError(file, 'overflow', previewEpochState(raw))\n }\n return epoch\n}\n\n/** Fresh-read the monotonic disk epoch; only an absent file is pre-acquire epoch zero. */\nexport function readCurrentEpoch(knowledgeRoot: string): number {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n return readEpoch(knowledgeRoot)\n}\n\n// Every call re-reads the disk epoch; a cached epoch would miss a reclaim.\nexport function assertEpochCurrent(\n opts: AssertEpochCurrentOptions,\n): AssertEpochCurrentOutcome {\n const observedEpoch = readCurrentEpoch(opts.knowledgeRoot)\n return observedEpoch === opts.epoch\n ? { current: true }\n : { current: false, observedEpoch }\n}\n\nfunction nextEpoch(current: number): number {\n if (current === Number.MAX_SAFE_INTEGER) {\n throw new RangeError('writer lease epoch exhausted')\n }\n return current + 1\n}\n\n/** Purely classify a guarded or untrusted lease value against one explicit wall-clock instant. */\nexport function isLeaseStale(lease: unknown, nowMs: number): boolean {\n const parsed = writerLeaseSchema.safeParse(lease)\n if (!parsed.success || !Number.isFinite(nowMs)) return true\n return nowMs - parsed.data.heartbeatAtMs >= LEASE_HEARTBEAT_TTL_MS\n}\n\n// An unreadable epoch is `unknown`: as fresh it makes a phantom holder, as stale a wrong kill.\nexport type WriterLeaseFreshness =\n | { kind: 'fresh' }\n | { kind: 'reclaimable' }\n | { kind: 'unknown'; error: CorruptEpochStateError }\n\nexport function deriveWriterLeaseFreshness(\n knowledgeRoot: string,\n lease: WriterLease,\n nowMs: number,\n): WriterLeaseFreshness {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) return { kind: 'unknown', error }\n throw error\n }\n if (lease.epoch !== observedEpoch) return { kind: 'reclaimable' }\n return isLeaseStale(lease, nowMs) ? { kind: 'reclaimable' } : { kind: 'fresh' }\n}\n\n/** Return a live holder or atomically mint a new, monotonically fenced writer identity. */\nexport function acquireWriterLease(\n knowledgeRoot: string,\n hooks?: AcquireWriterLeaseOptions,\n): AcquireWriterLeaseOutcome {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n const beforeLock = readWriterLease(knowledgeRoot)\n if (beforeLock.kind === 'parsed') {\n // This consumer names `unknown` as the typed refusal it already had for corrupt epoch bytes:\n // an authority state that cannot be read is not a licence to mint a new one.\n const verdict = deriveWriterLeaseFreshness(\n knowledgeRoot,\n beforeLock.lease,\n mutationLockNowMs(),\n )\n if (verdict.kind === 'unknown') {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error: verdict.error }\n }\n if (verdict.kind === 'fresh') return { kind: 'held', holder: beforeLock.lease }\n } else if (beforeLock.kind === 'unreadable') {\n // A lease that exists but cannot be opened is never minted over.\n return {\n kind: 'refused',\n reason: 'unreadable-lease-state',\n code: beforeLock.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), beforeLock.code),\n }\n } else {\n // With no lease to derive from, the epoch is still read before any acquisition: unreadable or\n // corrupt authority state refuses here exactly as it does through the verdict above.\n try {\n readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error }\n }\n throw error\n }\n }\n\n const deadlineMs = hooks?.acquireDeadlineMs ?? ACQUIRE_WRITER_LEASE_DEADLINE_MS\n const startedAtNs = process.hrtime.bigint()\n // Escalation waits spend this one budget, so no constant beneath it extends the deadline.\n const deadlineAtNs = startedAtNs + BigInt(Math.round(deadlineMs * 1e6))\n let attempts = 0\n\n while (true) {\n attempts += 1\n try {\n return withMutationLock(knowledgeRoot, () => {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return { kind: 'refused' as const, reason: 'corrupt-epoch-state' as const, error }\n }\n throw error\n }\n const current = readWriterLease(knowledgeRoot)\n const nowMs = Date.now()\n if (current.kind === 'unreadable') {\n // The in-lock repeat of the pre-lock arm: a lease that turned unopenable while this\n // contender waited for the lock is still not evidence that nobody holds it.\n return {\n kind: 'refused' as const,\n reason: 'unreadable-lease-state' as const,\n code: current.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), current.code),\n }\n }\n if (current.kind === 'parsed') {\n const verdict = deriveWriterLeaseFreshness(knowledgeRoot, current.lease, nowMs)\n if (verdict.kind === 'unknown') {\n return {\n kind: 'refused' as const,\n reason: 'corrupt-epoch-state' as const,\n error: verdict.error,\n }\n }\n if (verdict.kind === 'fresh' && current.lease.epoch === observedEpoch) {\n return { kind: 'held', holder: current.lease }\n }\n }\n const reclaimed = current.kind === 'parsed' ? current.lease : undefined\n\n const epoch = nextEpoch(observedEpoch)\n const holder = writerLeaseSchema.parse({\n leaseId: randomUUID(),\n pid: process.pid,\n epoch,\n heartbeatAtMs: nowMs,\n })\n atomicRewrite(epochPath(knowledgeRoot), `${epoch}\\n`)\n hooks?.afterEpochRewrite?.()\n sweepStagedEpochsBefore(knowledgeRoot, epoch)\n atomicRewrite(leasePath(knowledgeRoot), `${JSON.stringify(holder)}\\n`)\n return {\n kind: 'acquired',\n leaseId: holder.leaseId,\n epoch: holder.epoch,\n ...(reclaimed === undefined ? {} : { reclaimed }),\n }\n }, hooks, deadlineAtNs)\n } catch (error) {\n if (!(error instanceof MutationLockBusyError)) throw error\n // A stale heartbeat still answers `held`: a paused holder is never stolen from.\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'unreadable') {\n // A lease that cannot be READ is a fourth case here for the same reason an unreadable\n // epoch is a third one: the contender surfaces it by name instead of spinning to its\n // deadline over an authority state nobody can evaluate.\n return {\n kind: 'refused',\n reason: 'unreadable-lease-state',\n code: current.code,\n error: new UnreadableWriterLeaseStateError(leasePath(knowledgeRoot), current.code),\n }\n }\n if (current.kind === 'parsed') {\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(knowledgeRoot)\n } catch (epochError) {\n if (epochError instanceof CorruptEpochStateError) {\n return { kind: 'refused', reason: 'corrupt-epoch-state', error: epochError }\n }\n throw epochError\n }\n if (current.lease.epoch === observedEpoch) {\n return { kind: 'held', holder: current.lease }\n }\n }\n /**\n * The outermost exit, and the only one anchored outside this module's own vocabulary.\n *\n * It is checked AFTER the `held` narrow above, so a contender that could have answered\n * `held` always does; the deadline never converts a good answer into a refusal. It is also\n * strictly larger than MUTATION_LOCK_TAKEOVER_MS, so a reclaim that was going to happen has\n * already had its chance by the time this fires.\n */\n const waitedMs = monotonicElapsedMs(startedAtNs)\n if (waitedMs >= deadlineMs) {\n const observedOwner = readCommittedMutationLockOwner(knowledgeRoot)\n const error = new WriterLeaseUnreclaimableError(\n attempts,\n waitedMs,\n observedOwner === undefined ? undefined : {\n pid: observedOwner.pid,\n acquiredAtMs: observedOwner.acquiredAtMs,\n generationToken: observedOwner.generationToken,\n incarnationAttributed: observedOwner.incarnation !== undefined,\n },\n current.kind === 'parsed' ? current.lease : undefined,\n )\n return {\n kind: 'refused',\n reason: 'mutation-lock-unreclaimable',\n error,\n attempts,\n waitedMs,\n ...(error.observedOwner === undefined ? {} : { observedOwner: error.observedOwner }),\n ...(error.observedLease === undefined ? {} : { observedLease: error.observedLease }),\n }\n }\n Atomics.wait(\n MUTATION_LOCK_TERMINATION_WAIT,\n 0,\n 0,\n MUTATION_LOCK_TERMINATION_POLL_MS,\n )\n }\n }\n}\n\n/**\n * Compare one exact writer authority and run its mutation under the same generation lock.\n * The generation check after the failpoint prevents an expired owner from resuming after a\n * bounded takeover. Mutation implementations must keep irreversible work inside `mutate`.\n */\nexport function withCurrentWriterAuthority<T>(\n knowledgeRoot: string,\n authority: CurrentWriterAuthority,\n mutate: () => T,\n hooks: CurrentWriterAuthorityHooks = {},\n): T {\n assertAbsoluteKnowledgeRoot(knowledgeRoot)\n const fullAuthority: WriterLeaseAuthority = { knowledgeRoot, ...authority }\n try {\n return withMutationLock(knowledgeRoot, (generationToken, db) => {\n const observedEpoch = readCurrentEpoch(knowledgeRoot)\n if (observedEpoch !== authority.epoch) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'epoch-mismatch-before-heartbeat',\n observedEpoch,\n )\n }\n // Release keeps the epoch, so the lease is re-read here and must match exactly.\n const current = readWriterLease(knowledgeRoot)\n if (current.kind === 'absent') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-missing', observedEpoch)\n }\n if (current.kind === 'malformed') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-malformed', observedEpoch)\n }\n // Authority that cannot be re-read here cannot be proven, so the commit is fenced.\n if (current.kind === 'unreadable') {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-unreadable', observedEpoch)\n }\n if (current.lease.leaseId !== authority.leaseId) {\n throw new WriterAuthorityLostError(fullAuthority, 'lease-id-mismatch', observedEpoch)\n }\n if (current.lease.epoch !== authority.epoch) {\n throw new WriterAuthorityLostError(fullAuthority, 'stale-epoch', observedEpoch)\n }\n hooks.afterFinalAuthorityCompare?.()\n if (!mutationLockGenerationIsCurrent(db, generationToken)) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'mutation-lock-generation-lost',\n readCurrentEpoch(knowledgeRoot),\n )\n }\n return mutate()\n }, hooks)\n } catch (error) {\n if (\n error instanceof MutationLockBusyError\n || error instanceof MutationLockGenerationLostError\n ) {\n throw new WriterAuthorityLostError(\n fullAuthority,\n 'mutation-lock-generation-lost',\n readCurrentEpoch(knowledgeRoot),\n )\n }\n throw error\n }\n}\n\n// Lock-free so a long mutation cannot starve the beat; a clobbered lease names a stale epoch.\nexport function heartbeatLease(\n opts: LeaseOperationOptions,\n hooks: LeaseGuardHooks = {},\n): HeartbeatLeaseOutcome {\n assertAbsoluteKnowledgeRoot(opts.knowledgeRoot)\n // Nothing to resurrect and nothing to guard: absence is answered before any guard is staged.\n if (readWriterLease(opts.knowledgeRoot).kind === 'absent') {\n return { kind: 'refused', reason: 'lease-missing' }\n }\n return withLeaseGuard(opts.knowledgeRoot, (): HeartbeatLeaseOutcome => {\n const current = readWriterLease(opts.knowledgeRoot)\n if (current.kind === 'absent') return { kind: 'refused', reason: 'lease-missing' }\n if (current.kind === 'malformed') return { kind: 'refused', reason: 'lease-malformed' }\n // A beat that cannot read the lease cannot prove it owns it.\n if (current.kind === 'unreadable') return { kind: 'refused', reason: 'lease-unreadable' }\n if (current.lease.leaseId !== opts.leaseId) {\n return { kind: 'refused', reason: 'lease-id-mismatch', holder: current.lease }\n }\n let observedEpoch: number\n try {\n observedEpoch = readEpoch(opts.knowledgeRoot)\n } catch (error) {\n if (error instanceof CorruptEpochStateError) {\n return {\n kind: 'refused',\n reason: 'corrupt-epoch-state',\n holder: current.lease,\n error,\n }\n }\n throw error\n }\n if (current.lease.epoch !== observedEpoch) {\n return {\n kind: 'refused',\n reason: 'stale-epoch',\n holder: current.lease,\n observedEpoch,\n }\n }\n\n const holder = writerLeaseSchema.parse({\n ...current.lease,\n heartbeatAtMs: Date.now(),\n })\n atomicRewrite(leasePath(opts.knowledgeRoot), `${JSON.stringify(holder)}\\n`)\n return { kind: 'heartbeated', holder }\n }, hooks)\n}\n\n/**\n * Refresh one exact maintenance writer at a non-mutating boundary.\n *\n * The epoch reads deliberately bracket the heartbeat: the first rejects an already-reclaimed\n * holder, while the second detects a reclaim race after the lease rewrite. The authority-store\n * transaction is released before this function returns, so this is NOT a mutation fence. Any\n * irreversible mutation must instead run inside `withCurrentWriterAuthority`.\n */\nexport function refreshWriterLeaseAuthority(\n authority: WriterLeaseAuthority,\n): WriterLeaseAuthority {\n const beforeHeartbeat = assertEpochCurrent(authority)\n if (!beforeHeartbeat.current) {\n throw new WriterAuthorityLostError(\n authority,\n 'epoch-mismatch-before-heartbeat',\n beforeHeartbeat.observedEpoch,\n )\n }\n\n const heartbeat = heartbeatLease(authority)\n if (heartbeat.kind === 'refused') {\n if (heartbeat.reason === 'corrupt-epoch-state' && heartbeat.error !== undefined) {\n throw heartbeat.error\n }\n throw new WriterAuthorityLostError(\n authority,\n heartbeat.reason,\n readCurrentEpoch(authority.knowledgeRoot),\n )\n }\n\n const afterHeartbeat = assertEpochCurrent(authority)\n if (!afterHeartbeat.current) {\n throw new WriterAuthorityLostError(\n authority,\n 'epoch-mismatch-after-heartbeat',\n afterHeartbeat.observedEpoch,\n )\n }\n\n return authority\n}\n\n// The epoch is kept forever; the guard is always taken second, so release and beat cannot deadlock.\nexport function releaseLease(\n opts: LeaseOperationOptions,\n hooks: LeaseGuardHooks = {},\n): ReleaseLeaseOutcome {\n assertAbsoluteKnowledgeRoot(opts.knowledgeRoot)\n return withMutationLock(opts.knowledgeRoot, () => {\n const outcome = withLeaseGuard(opts.knowledgeRoot, (): ReleaseLeaseOutcome => {\n const current = readWriterLease(opts.knowledgeRoot)\n if (current.kind === 'absent') return { kind: 'refused', reason: 'lease-missing' }\n if (current.kind === 'malformed') return { kind: 'refused', reason: 'lease-malformed' }\n // An unreadable lease may belong to a successor, so it is never removed unseen.\n if (current.kind === 'unreadable') return { kind: 'refused', reason: 'lease-unreadable' }\n if (current.lease.leaseId !== opts.leaseId) {\n return { kind: 'refused', reason: 'lease-id-mismatch', holder: current.lease }\n }\n\n rmSync(leasePath(opts.knowledgeRoot), { force: true })\n return { kind: 'released' }\n }, hooks)\n if (outcome.kind === 'released') bestEffortFsyncDirectory(opts.knowledgeRoot)\n return outcome\n })\n}\n","// Separate from `worker-registration.ts` because the reader closure must not reach `lease/`.\nimport { incarnationFormat, resolveProcessIncarnation } from '../lease/writer-lease.js'\n\nimport {\n EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION,\n type EmbedderWorkerIncarnationVerdict,\n type EmbedderWorkerRegistration,\n} from './worker-registration.js'\n\nexport { resolveProcessIncarnation }\n\n/**\n * The token a worker records about ITSELF at registration time.\n *\n * The worker is the only party that can attribute the registration without a race: it is the\n * process being described, and it is alive while describing itself. A worker that cannot resolve\n * its own start time records the sentinel rather than fabricating a value, accepting that it will\n * later be replaced without a signal instead of terminated.\n */\nexport function ownEmbedderWorkerIncarnation(): string {\n return resolveProcessIncarnation(process.pid) ?? EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION\n}\n\n// A reused pid can belong to a stranger, so `mismatch` and `unverifiable` are never signalled.\nexport function verifyEmbedderWorkerIncarnation(\n registration: EmbedderWorkerRegistration,\n): EmbedderWorkerIncarnationVerdict {\n if (registration.incarnation === EMBEDDER_WORKER_UNVERIFIABLE_INCARNATION) {\n return 'unverifiable'\n }\n const occupant = resolveProcessIncarnation(registration.pid)\n if (occupant === undefined) return 'unverifiable'\n if (incarnationFormat(occupant) !== incarnationFormat(registration.incarnation)) {\n return 'unverifiable'\n }\n return occupant === registration.incarnation ? 'match' : 'mismatch'\n}\n"],"mappings":";AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,aAAAC,YAAW,UAAAC,eAAc;AAClC;AAAA,EACE;AAAA,OAIK;AACP,SAAS,WAAAC,gBAAe;AACxB,SAAS,YAAAC,WAAU,WAAAC,gBAAe;;;ACTlC,SAAS,WAAAC,gBAAe;AAGxB;AAAA,EACE,6BAAAC;AAAA,EACA,kCAAAC;AAAA,OAEK;;;ACPP,SAAS,kBAAkB;AAC3B,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAM9B,IAAM,eAAe;AACrB,IAAM,kBAAkB;AACxB,IAAM,cAAc;AACpB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,WAAW;AACjB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,uBAAuB;AAC7B,IAAM,wBAAwB;AAC9B,IAAM,kBAAkB;AACxB,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB,OAAO;AAClC,IAAM,sBAAsB,KAAK,OAAO;AACxC,IAAM,mBAAmB,IAAI,OAAO;AACpC,IAAM,YAAY;AAYX,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACpC;AAAA,EAET,YAAY,MAA+B,SAAiB,SAAwB;AAClF,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAOO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACpC;AAAA,EAET,YAAY,MAA+B,SAAiB,SAAwB;AAClF,UAAM,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,EAAE,YAAY,QAAQ,KAAK,CAAC,EAAE;AAAA,EACzE,CAAC;AAED,MAAI,WAAW;AACf,QAAM,OAAO,CAAC,aAA2B;AACvC,QAAI,SAAU;AACd,eAAW;AACX,SAAK,OAAO,MAAM,EAAE;AAAA,MAClB,MAAM,QAAQ,KAAK,QAAQ;AAAA,MAC3B,CAAC,UAAmB;AAClB,gBAAQ,OAAO;AAAA,UACb,mCAAmC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA;AAAA,QAC3F;AACA,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACA,UAAQ,KAAK,WAAW,MAAM,KAAK,CAAC,CAAC;AACrC,UAAQ,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC;AACtC;AAEA,IAAM,gBAAgB,QAAQ,KAAK,CAAC,MAAM,SAAY,SAAYI,UAAS,QAAQ,KAAK,CAAC,CAAC;AAC1F,IAAI,kBAAkB,qBAAqB,kBAAkB,oBAAoB;AAC/E,OAAK,KAAK,EAAE,MAAM,CAAC,UAAmB;AACpC,YAAQ,OAAO;AAAA,MACb,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA;AAAA,IACnF;AACA,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;","names":["randomUUID","chmodSync","rmSync","connect","basename","resolve","dirname","DEFAULT_EMBEDDING_PROFILE","STATIC_FLOOR_EMBEDDING_PROFILE","join","embed","createHash","existsSync","readFileSync","dirname","join","createHash","join","dirname","readFileSync","existsSync","dirname","STATIC_FLOOR_EMBEDDING_PROFILE","DEFAULT_EMBEDDING_PROFILE","closeSync","existsSync","fsyncSync","mkdirSync","openSync","readFileSync","renameSync","rmSync","unlinkSync","writeFileSync","basename","dirname","join","DatabaseSync","z","basename","z","readFileSync","z","request","connect","rmSync","resolve","randomUUID","chmodSync","basename"]}