@codemem/core 0.47.1 → 0.47.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/better-sqlite-coordinator-store.d.ts +1 -0
- package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
- package/dist/coordinator-api.d.ts.map +1 -1
- package/dist/coordinator-device-ownership-evidence-queries.d.ts +6 -0
- package/dist/coordinator-device-ownership-evidence-queries.d.ts.map +1 -1
- package/dist/coordinator-device-ownership-evidence.d.ts.map +1 -1
- package/dist/coordinator-peer-discovery.d.ts +1 -1
- package/dist/coordinator-peer-discovery.d.ts.map +1 -1
- package/dist/coordinator-store-contract.d.ts +1 -0
- package/dist/coordinator-store-contract.d.ts.map +1 -1
- package/dist/d1-coordinator-store.d.ts +1 -0
- package/dist/d1-coordinator-store.d.ts.map +1 -1
- package/dist/diagnostic-store-snapshot.d.ts +4 -0
- package/dist/diagnostic-store-snapshot.d.ts.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9394 -9180
- package/dist/index.js.map +1 -1
- package/dist/ingest-prompts.d.ts.map +1 -1
- package/dist/internal/cloudflare-coordinator.js +7 -2
- package/dist/internal/cloudflare-coordinator.js.map +1 -1
- package/dist/legacy-team-candidate.d.ts.map +1 -1
- package/dist/legacy-team-setup-completion-manifest.d.ts +3 -0
- package/dist/legacy-team-setup-completion-manifest.d.ts.map +1 -1
- package/dist/legacy-team-setup-diagnosis.d.ts +46 -0
- package/dist/legacy-team-setup-diagnosis.d.ts.map +1 -0
- package/dist/{owner-enrollment-start-XwN1p7du.js → owner-enrollment-start-DHh8A5hh.js} +1602 -1590
- package/dist/owner-enrollment-start-DHh8A5hh.js.map +1 -0
- package/dist/scope-membership-cache.d.ts.map +1 -1
- package/dist/semantic-worker-entry.js +1 -1
- package/dist/{semantic-worker-job-a7S-qbRH.js → semantic-worker-job-2fm4JmaO.js} +2 -2
- package/dist/{semantic-worker-job-a7S-qbRH.js.map → semantic-worker-job-2fm4JmaO.js.map} +1 -1
- package/dist/{semantic-worker-ranking-hRyoWJtp.js → semantic-worker-ranking-D9bhmrS_.js} +8 -2
- package/dist/{semantic-worker-ranking-hRyoWJtp.js.map → semantic-worker-ranking-D9bhmrS_.js.map} +1 -1
- package/dist/{workspace-identity-C2g2-ZRR.js → workspace-identity-nF_U-y6A.js} +1432 -1391
- package/dist/workspace-identity-nF_U-y6A.js.map +1 -0
- package/package.json +3 -3
- package/dist/owner-enrollment-start-XwN1p7du.js.map +0 -1
- package/dist/workspace-identity-C2g2-ZRR.js.map +0 -1
package/dist/{semantic-worker-ranking-hRyoWJtp.js.map → semantic-worker-ranking-D9bhmrS_.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"semantic-worker-ranking-hRyoWJtp.js","names":[],"sources":["../src/memory-local-capture.ts","../src/memory-source-identity.ts","../src/memory-creation-provenance.ts","../src/home.ts","../src/observer-config.ts","../src/database-runtime-primitives.ts","../src/memory-retirement-delivery-schema.ts","../src/memory-scope-retirement.ts","../src/memory-ownership-recovery-schema.ts","../src/repository-discovery-index.ts","../src/summary-memory.ts","../src/test-schema.generated.ts","../src/usage-aggregate-index.ts","../src/vector-corpus-epoch.ts","../src/schema-bootstrap.ts","../src/db.ts","../src/schema.ts","../src/sync-identity.ts","../src/project.ts","../src/coordinator-auth-browser-schema-upgrade.ts","../src/coordinator-device-ownership-schema.ts","../src/better-sqlite-coordinator-store.ts","../src/coordinator-sync-config.ts","../src/recipient-policy-deny-overlay.ts","../src/scope-membership-snapshot.ts","../src/scope-membership-evidence.ts","../src/sync-auth.ts","../src/sync-http-client.ts","../src/scope-membership-cache.ts","../src/wildcard-match.ts","../src/scope-resolution.ts","../src/filters.ts","../src/embeddings.ts","../src/semantic-query.ts","../src/vector-layout.ts","../src/semantic/semantic-ranking.ts","../src/semantic/validated-vector-index-state.ts","../src/semantic/validated-vector-index-statements.ts","../src/semantic/validated-vector-index-mutations.ts","../src/semantic/validated-vector-index-audit.ts","../src/same-actor-peers.ts","../src/semantic/validated-vector-index.ts","../src/semantic/semantic-worker-ranking.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"./db.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface CaptureBirth {\n\tcapture_id: string;\n}\n\ninterface DeviceTuple {\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n}\n\nexport interface LocalCreationContext {\n\texpectedPublicKey?: string;\n\tloadExpectedPublicKey?: () => string | undefined;\n}\n\nexport interface LocalCaptureAdoptionContext extends LocalCreationContext {\n\tactorId?: string;\n\truntimeDeviceId?: string;\n}\n\nexport function assertLocalCaptureAdoptionActors(\n\tdb: Database,\n\tdeviceId: string,\n\tactorId?: string,\n): void {\n\tif (!hasTable(db, \"actors\")) return;\n\tconst conflict = db\n\t\t.prepare(`SELECT 1 FROM actors WHERE actor_id IN (?, ?, ?)\n\t\tAND (is_local <> 1 OR status <> 'active' OR merged_into_actor_id IS NOT NULL) LIMIT 1`)\n\t\t.get(\"local:local\", `local:${deviceId}`, actorId ?? `local:${deviceId}`);\n\tif (conflict) throw new Error(\"device_adoption_actor_conflict\");\n}\n\nfunction hasTable(db: Database, name: string): boolean {\n\treturn (\n\t\tdb.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\").get(name) !==\n\t\tundefined\n\t);\n}\n\n/** Schema only: the unsigned identity is born in the first genuine creation transaction. */\nexport function ensureMemoryLocalCaptureSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_local_capture (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tcapture_id TEXT NOT NULL UNIQUE,\n\t\tcreated_at TEXT NOT NULL\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_local_capture_adoption (\n\t\tcapture_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_local_capture(capture_id),\n\t\tdevice_id TEXT NOT NULL,\n\t\tpublic_key TEXT NOT NULL,\n\t\tfingerprint TEXT NOT NULL,\n\t\tcreated_at TEXT NOT NULL\n\t);`);\n\tfor (const table of [\"memory_local_capture\", \"memory_local_capture_adoption\"]) {\n\t\tdb.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_no_update\n\t\t\tBEFORE UPDATE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_delete\n\t\t\tBEFORE DELETE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_replace\n\t\t\tBEFORE INSERT ON ${table}\n\t\t\tWHEN EXISTS (SELECT 1 FROM ${table})\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;`);\n\t}\n}\n\nfunction captureBirth(db: Database): CaptureBirth | null {\n\tif (!hasTable(db, \"memory_local_capture\")) return null;\n\treturn (\n\t\t(db.prepare(\"SELECT capture_id FROM memory_local_capture WHERE id = 1\").get() as\n\t\t\t| CaptureBirth\n\t\t\t| undefined) ?? null\n\t);\n}\n\n/** An explicit ensure may finish a pending birth, but never reassociate an adopted one. */\nexport function hasPendingLocalCapture(db: Database): boolean {\n\tconst birth = captureBirth(db);\n\tif (!birth || !hasTable(db, \"memory_local_capture_adoption\")) return false;\n\treturn !db\n\t\t.prepare(\"SELECT 1 FROM memory_local_capture_adoption WHERE capture_id = ?\")\n\t\t.get(birth.capture_id);\n}\n\nfunction deviceTuple(db: Database): DeviceTuple | null {\n\tif (!hasTable(db, \"sync_device\")) return null;\n\tconst rows = db\n\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t.all() as DeviceTuple[];\n\treturn rows.length === 1 ? (rows[0] ?? null) : null;\n}\n\nfunction publicKeyBytes(value: string): string | null {\n\tconst [type, bytes] = value.trim().split(/\\s+/u);\n\treturn type === \"ssh-ed25519\" && bytes ? `${type} ${bytes}` : null;\n}\n\nexport function matchesLocalCaptureRuntime(\n\ttuple: DeviceTuple,\n\tdeviceId: string,\n\tpublicKey: string | undefined,\n): boolean {\n\tconst stored = publicKeyBytes(tuple.public_key);\n\treturn (\n\t\ttuple.device_id === deviceId &&\n\t\tstored !== null &&\n\t\tpublicKey !== undefined &&\n\t\tpublicKeyBytes(publicKey) === stored &&\n\t\tfingerprintPublicKey(tuple.public_key) === tuple.fingerprint\n\t);\n}\n\n/** Never called by reads, imports, bootstrap, or replication. */\nexport function getOrCreateLocalCaptureId(db: Database): string {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst birth = captureBirth(db);\n\tif (birth) return birth.capture_id;\n\tensureMemoryLocalCaptureSchema(db);\n\tconst captureId = `local-capture-v1:${randomUUID()}`;\n\tdb.prepare(\"INSERT INTO memory_local_capture(id, capture_id, created_at) VALUES (1, ?, ?)\").run(\n\t\tcaptureId,\n\t\tnew Date().toISOString(),\n\t);\n\treturn captureId;\n}\n\n/** Retain a one-time association, without renaming any immutable source binding. */\nexport function adoptLocalCapture(\n\tdb: Database,\n\tdeviceId: string,\n\tcontext: LocalCaptureAdoptionContext,\n): void {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst birth = captureBirth(db);\n\tif (!birth) return;\n\tif (\n\t\tcontext.runtimeDeviceId &&\n\t\tcontext.runtimeDeviceId !== \"local\" &&\n\t\tcontext.runtimeDeviceId !== deviceId\n\t)\n\t\treturn;\n\tconst tuple = deviceTuple(db);\n\tconst publicKey = context.expectedPublicKey ?? context.loadExpectedPublicKey?.();\n\tif (!tuple || !matchesLocalCaptureRuntime(tuple, deviceId, publicKey)) return;\n\tconst existing = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, public_key, fingerprint FROM memory_local_capture_adoption WHERE capture_id = ?\",\n\t\t)\n\t\t.get(birth.capture_id) as DeviceTuple | undefined;\n\tif (existing) {\n\t\tif (\n\t\t\texisting.device_id !== tuple.device_id ||\n\t\t\texisting.public_key !== tuple.public_key ||\n\t\t\texisting.fingerprint !== tuple.fingerprint\n\t\t)\n\t\t\tthrow new Error(\"memory_local_capture_adoption_conflict\");\n\t\treturn;\n\t}\n\tassertLocalCaptureAdoptionActors(db, deviceId, context.actorId);\n\tdb.prepare(`INSERT INTO memory_local_capture_adoption(capture_id, device_id, public_key, fingerprint, created_at)\n\t\tVALUES (?, ?, ?, ?, ?)`).run(\n\t\tbirth.capture_id,\n\t\ttuple.device_id,\n\t\ttuple.public_key,\n\t\ttuple.fingerprint,\n\t\tnew Date().toISOString(),\n\t);\n}\n\n/** Read-only: no DDL, key generation, identity repair, actor union, or origin inference. */\nexport function localCreationSourceIds(\n\tdb: Database,\n\tdeviceId: string,\n\tcontext: LocalCreationContext = {},\n): string[] {\n\tif (\n\t\t!hasTable(db, \"memory_source_bindings\") ||\n\t\t!db\n\t\t\t.prepare(\"SELECT 1 FROM memory_source_bindings WHERE evidence = 'local_creation' LIMIT 1\")\n\t\t\t.get()\n\t)\n\t\treturn [];\n\tconst birth = captureBirth(db);\n\tconst tuple = deviceTuple(db);\n\tif (!tuple) {\n\t\tconst noDevice =\n\t\t\t!hasTable(db, \"sync_device\") || !db.prepare(\"SELECT 1 FROM sync_device LIMIT 1\").get();\n\t\tconst adopted =\n\t\t\thasTable(db, \"memory_local_capture_adoption\") &&\n\t\t\tdb.prepare(\"SELECT 1 FROM memory_local_capture_adoption LIMIT 1\").get();\n\t\treturn noDevice && !adopted && deviceId === \"local\" && birth ? [birth.capture_id] : [];\n\t}\n\tif (tuple.device_id !== deviceId) return [];\n\tconst publicKey = context.expectedPublicKey ?? context.loadExpectedPublicKey?.();\n\tif (!matchesLocalCaptureRuntime(tuple, deviceId, publicKey)) return [];\n\tconst sources = [deviceId];\n\tif (!birth || !hasTable(db, \"memory_local_capture_adoption\")) return sources;\n\tconst adoption = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, public_key, fingerprint FROM memory_local_capture_adoption WHERE capture_id = ?\",\n\t\t)\n\t\t.get(birth.capture_id) as DeviceTuple | undefined;\n\tif (\n\t\tadoption &&\n\t\tadoption.device_id === tuple.device_id &&\n\t\tadoption.public_key === tuple.public_key &&\n\t\tadoption.fingerprint === tuple.fingerprint\n\t)\n\t\tsources.push(birth.capture_id);\n\treturn sources;\n}\n\nexport function hasLocalCreationBinding(\n\tdb: Database,\n\tentityId: string,\n\tsourceIds: readonly string[],\n): boolean {\n\tif (!sourceIds.length || !hasTable(db, \"memory_source_bindings\")) return false;\n\tconst binding = db\n\t\t.prepare(\"SELECT source_device_id, evidence FROM memory_source_bindings WHERE entity_id = ?\")\n\t\t.get(entityId) as { source_device_id: string; evidence: string } | undefined;\n\treturn binding?.evidence === \"local_creation\" && sourceIds.includes(binding.source_device_id);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"./db.js\";\nimport {\n\tgetOrCreateLocalCaptureId,\n\ttype LocalCreationContext,\n\tmatchesLocalCaptureRuntime,\n} from \"./memory-local-capture.js\";\n\nconst PREFIX = \"memory-source-v1:\";\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;\n\nexport interface VerifiedMemorySource {\n\tentityId: string;\n\tsourceDeviceId: string;\n\tevidence: \"local_creation\" | \"authenticated_namespace\";\n}\n\n/** Additive prerequisite only; no existing capture or wire protocol is switched on here. */\nexport function ensureMemorySourceIdentitySchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_source_bindings (\n\t\tentity_id TEXT PRIMARY KEY,\n\t\tsource_device_id TEXT NOT NULL,\n\t\tevidence TEXT NOT NULL CHECK(evidence IN ('local_creation', 'authenticated_namespace')),\n\t\tcreated_at TEXT NOT NULL\n\t);\n\tCREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_update\n\tBEFORE UPDATE ON memory_source_bindings\n\tBEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_delete\n\tBEFORE DELETE ON memory_source_bindings\n\tBEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_replace\n\tBEFORE INSERT ON memory_source_bindings\n\tWHEN EXISTS (SELECT 1 FROM memory_source_bindings WHERE entity_id = NEW.entity_id)\n\tBEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;`);\n}\n\nfunction validDeviceId(value: string): boolean {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\n/** Parsing is not authentication. It identifies the namespace a verified sender must own. */\nexport function memorySourceNamespace(entityId: string): string | null {\n\tif (typeof entityId !== \"string\" || entityId.length > 1500 || !entityId.startsWith(PREFIX))\n\t\treturn null;\n\tconst [encoded, nonce, extra] = entityId.slice(PREFIX.length).split(\":\");\n\tif (!encoded || !nonce || extra !== undefined || !UUID.test(nonce)) return null;\n\tconst source = Buffer.from(encoded, \"base64url\").toString(\"utf8\");\n\tif (!validDeviceId(source) || Buffer.from(source).toString(\"base64url\") !== encoded) return null;\n\treturn source;\n}\n\nexport function getVerifiedMemorySource(\n\tdb: Database,\n\tentityId: string,\n): VerifiedMemorySource | null {\n\tconst row = db\n\t\t.prepare(\"SELECT source_device_id, evidence FROM memory_source_bindings WHERE entity_id = ?\")\n\t\t.get(entityId) as\n\t\t| { source_device_id: string; evidence: VerifiedMemorySource[\"evidence\"] }\n\t\t| undefined;\n\tif (!row) return null;\n\treturn { entityId, sourceDeviceId: row.source_device_id, evidence: row.evidence };\n}\n\nfunction persistBinding(db: Database, binding: VerifiedMemorySource): VerifiedMemorySource {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst existing = getVerifiedMemorySource(db, binding.entityId);\n\tif (existing) {\n\t\tif (existing.sourceDeviceId !== binding.sourceDeviceId)\n\t\t\tthrow new Error(\"memory_source_binding_conflict\");\n\t\treturn existing;\n\t}\n\tdb.prepare(`INSERT INTO memory_source_bindings(entity_id, source_device_id, evidence, created_at)\n\t\tVALUES (?, ?, ?, ?)`).run(\n\t\tbinding.entityId,\n\t\tbinding.sourceDeviceId,\n\t\tbinding.evidence,\n\t\tnew Date().toISOString(),\n\t);\n\treturn binding;\n}\n\n/** Allocate inside the transaction creating a new memory/copy; never rename a historical UUID. */\nexport function allocateLocalMemorySource(db: Database): VerifiedMemorySource {\n\tconst rows = db.prepare(\"SELECT device_id FROM sync_device\").all() as Array<{\n\t\tdevice_id: string;\n\t}>;\n\tconst source = rows[0]?.device_id;\n\tif (rows.length !== 1 || !source || !validDeviceId(source))\n\t\tthrow new Error(\"memory_source_local_device_required\");\n\tconst entityId = `${PREFIX}${Buffer.from(source).toString(\"base64url\")}:${randomUUID()}`;\n\treturn persistBinding(db, { entityId, sourceDeviceId: source, evidence: \"local_creation\" });\n}\n\n/** Genuine new captures only. Unsigned capture namespaces are never network-authenticated. */\nexport function allocateLocalCaptureMemorySource(\n\tdb: Database,\n\truntimeDeviceId: string,\n\tcontext: LocalCreationContext = {},\n): VerifiedMemorySource | null {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tlet rows: Array<{\n\t\tdevice_id: string;\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t}> = [];\n\tif (db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sync_device'\").get())\n\t\trows = db\n\t\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t\t.all() as typeof rows;\n\tif (rows.length > 0) {\n\t\tconst tuple = rows[0];\n\t\tif (\n\t\t\trows.length !== 1 ||\n\t\t\t!tuple ||\n\t\t\ttuple.device_id !== runtimeDeviceId ||\n\t\t\t!validDeviceId(runtimeDeviceId)\n\t\t)\n\t\t\treturn null;\n\t\tconst publicKey = context.expectedPublicKey ?? context.loadExpectedPublicKey?.();\n\t\tif (!matchesLocalCaptureRuntime(tuple, runtimeDeviceId, publicKey)) return null;\n\t\treturn allocateLocalMemorySource(db);\n\t}\n\tif (runtimeDeviceId !== \"local\") return null;\n\tconst sourceDeviceId = getOrCreateLocalCaptureId(db);\n\treturn persistBinding(db, {\n\t\tentityId: `memory-local-capture-v1:${Buffer.from(sourceDeviceId).toString(\"base64url\")}:${randomUUID()}`,\n\t\tsourceDeviceId,\n\t\tevidence: \"local_creation\",\n\t});\n}\n\n/**\n * Internal auth boundary: verifiedPeerDeviceId MUST come from successful transport\n * authentication, never op.device_id, payload origin, a form field, or a signature claim.\n * The namespace authenticates NEW identities, including absent rows. It cannot prove\n * ownership of a historical unqualified UUID. Forwarded claims are not accepted.\n */\nexport function verifyAuthenticatedMemorySource(\n\tdb: Database,\n\tinput: { entityId: string; verifiedPeerDeviceId: string },\n): VerifiedMemorySource {\n\tconst namespace = memorySourceNamespace(input.entityId);\n\tif (!namespace) throw new Error(\"memory_source_verification_required\");\n\tif (namespace !== input.verifiedPeerDeviceId) throw new Error(\"memory_source_sender_mismatch\");\n\treturn persistBinding(db, {\n\t\tentityId: input.entityId,\n\t\tsourceDeviceId: namespace,\n\t\tevidence: \"authenticated_namespace\",\n\t});\n}\n\n/** Retirement consumers consult immutable proof, never mutable memory origin metadata. */\nexport function assertVerifiedMemorySource(\n\tdb: Database,\n\tentityId: string,\n\tsourceDeviceId: string,\n): void {\n\tconst binding = getVerifiedMemorySource(db, entityId);\n\tif (!binding) throw new Error(\"memory_source_verification_required\");\n\tif (binding.sourceDeviceId !== sourceDeviceId) throw new Error(\"memory_source_sender_mismatch\");\n}\n","import type { Database } from \"./db.js\";\nimport { getVerifiedMemorySource } from \"./memory-source-identity.js\";\n\n// Actor/workspace aliases and replication clocks may change during local adoption.\n// Scope and user-facing content must still match the immutable creation snapshot.\nconst CREATION_CONTENT_SQL = `json_array(memory_items.kind, memory_items.title,\n\tmemory_items.subtitle, memory_items.body_text, memory_items.confidence,\n\tmemory_items.tags_text, memory_items.visibility, memory_items.workspace_kind,\n\tmemory_items.origin_source, memory_items.trust_state, memory_items.narrative,\n\tmemory_items.facts, memory_items.concepts, memory_items.files_read,\n\tmemory_items.files_modified, memory_items.user_prompt_id, memory_items.prompt_number,\n\tmemory_items.project, memory_items.active, memory_items.deleted_at,\n\tjson_remove(CASE WHEN json_valid(memory_items.metadata_json)\n\t\tTHEN memory_items.metadata_json ELSE '{}' END, '$.clock_device_id', '$.import_key'))`;\n\nfunction hasTable(db: Database, name: string): boolean {\n\treturn (\n\t\tdb.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\").get(name) !==\n\t\tundefined\n\t);\n}\n\nfunction ensureCreationProvenanceSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_local_creation_snapshots (\n\t\tentity_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_source_bindings(entity_id),\n\t\tscope_id TEXT,\n\t\tcontent_json TEXT NOT NULL,\n\t\tsource_public_key TEXT,\n\t\tsource_fingerprint TEXT,\n\t\tcreated_at TEXT NOT NULL\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_foreign_revisions (\n\t\tentity_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_source_bindings(entity_id),\n\t\twrite_path TEXT NOT NULL CHECK(write_path IN ('replication', 'bootstrap', 'import')),\n\t\tcreated_at TEXT NOT NULL\n\t);`);\n\tfor (const table of [\"memory_local_creation_snapshots\", \"memory_foreign_revisions\"]) {\n\t\tdb.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_no_update BEFORE UPDATE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_creation_provenance_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_delete BEFORE DELETE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_creation_provenance_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_replace BEFORE INSERT ON ${table}\n\t\t\tWHEN EXISTS (SELECT 1 FROM ${table} WHERE entity_id = NEW.entity_id)\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_creation_provenance_immutable'); END;`);\n\t}\n}\n\n/** Only a genuine creation/copy transaction can record the original row. No backfill. */\nexport function recordLocalCreationSnapshot(db: Database, memoryId: number): void {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst row = db.prepare(\"SELECT import_key FROM memory_items WHERE id = ?\").get(memoryId) as\n\t\t| { import_key: string | null }\n\t\t| undefined;\n\tif (\n\t\t!row?.import_key ||\n\t\tgetVerifiedMemorySource(db, row.import_key)?.evidence !== \"local_creation\"\n\t)\n\t\treturn;\n\tensureCreationProvenanceSchema(db);\n\tlet publicKeySql = \"NULL\";\n\tlet fingerprintSql = \"NULL\";\n\tif (hasTable(db, \"sync_device\")) {\n\t\tpublicKeySql =\n\t\t\t\"(SELECT public_key FROM sync_device WHERE device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = memory_items.import_key))\";\n\t\tfingerprintSql =\n\t\t\t\"(SELECT fingerprint FROM sync_device WHERE device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = memory_items.import_key))\";\n\t}\n\tdb.prepare(`INSERT INTO memory_local_creation_snapshots(entity_id, scope_id, content_json, source_public_key, source_fingerprint, created_at)\n\t\tSELECT import_key, scope_id, ${CREATION_CONTENT_SQL},\n\t\t${publicKeySql}, ${fingerprintSql},\n\t\t? FROM memory_items WHERE id = ?`).run(new Date().toISOString(), memoryId);\n}\n\n/** The inbound write path, not peer-supplied clocks/origins, records permanent negative proof. */\nexport function recordForeignMemoryRevision(\n\tdb: Database,\n\tentityId: string,\n\twritePath: \"replication\" | \"bootstrap\" | \"import\",\n): void {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tif (!hasRecordedLocalCreation(db, entityId)) return;\n\tensureCreationProvenanceSchema(db);\n\tif (db.prepare(\"SELECT 1 FROM memory_foreign_revisions WHERE entity_id = ?\").get(entityId))\n\t\treturn;\n\tdb.prepare(\n\t\t\"INSERT INTO memory_foreign_revisions(entity_id, write_path, created_at) VALUES (?, ?, ?)\",\n\t).run(entityId, writePath, new Date().toISOString());\n}\n\n/** Preservation evidence only: this must not authorize a read or mutation. */\nexport function hasRecordedLocalCreation(db: Database, entityId: string): boolean {\n\treturn (\n\t\thasTable(db, \"memory_source_bindings\") &&\n\t\tgetVerifiedMemorySource(db, entityId)?.evidence === \"local_creation\"\n\t);\n}\n\n/** Read-only SQL, using primary-key lookups for both creation and negative facts. */\nexport function matchingLocalCreationClause(db: Database): string | null {\n\tif (!hasTable(db, \"memory_local_creation_snapshots\") || !hasTable(db, \"memory_foreign_revisions\"))\n\t\treturn null;\n\tlet keyMatchSql = \"creation.source_public_key IS NULL\";\n\tif (hasTable(db, \"sync_device\"))\n\t\tkeyMatchSql = `(creation.source_public_key IS NULL OR EXISTS (SELECT 1 FROM sync_device creation_device\n\t\t\tWHERE creation_device.device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = creation.entity_id)\n\t\t\tAND creation_device.public_key = creation.source_public_key\n\t\t\tAND creation_device.fingerprint = creation.source_fingerprint))`;\n\treturn `EXISTS (SELECT 1 FROM memory_local_creation_snapshots creation\n\t\tWHERE creation.entity_id = memory_items.import_key\n\t\tAND creation.scope_id IS memory_items.scope_id\n\t\tAND creation.content_json = ${CREATION_CONTENT_SQL}\n\t\tAND ${keyMatchSql}\n\t\tAND NOT EXISTS (SELECT 1 FROM memory_foreign_revisions foreign_revision\n\t\t\tWHERE foreign_revision.entity_id = creation.entity_id))`;\n}\n\nexport function hasMatchingLocalCreation(\n\tdb: Database,\n\tentityId: string,\n\tsourceIds: readonly string[],\n\toptions: { memoryId?: number } = {},\n): boolean {\n\tif (!sourceIds.length) return false;\n\tif (options.memoryId !== undefined && !Number.isSafeInteger(options.memoryId)) return false;\n\tconst clause = matchingLocalCreationClause(db);\n\tif (!clause) return false;\n\tconst binding = getVerifiedMemorySource(db, entityId);\n\tif (binding?.evidence !== \"local_creation\" || !sourceIds.includes(binding.sourceDeviceId))\n\t\treturn false;\n\tif (options.memoryId !== undefined)\n\t\treturn (\n\t\t\tdb\n\t\t\t\t.prepare(`SELECT 1 FROM memory_items WHERE id = ? AND import_key = ? AND ${clause}`)\n\t\t\t\t.get(options.memoryId, entityId) !== undefined\n\t\t);\n\treturn (\n\t\tdb.prepare(`SELECT 1 FROM memory_items WHERE import_key = ? AND ${clause}`).get(entityId) !==\n\t\tundefined\n\t);\n}\n","import { homedir } from \"node:os\";\n\nexport function codememHomeDir(): string {\n\treturn process.env.HOME?.trim() || homedir();\n}\n","/**\n * OpenCode provider configuration loading and resolution.\n *\n * Mirrors codemem/observer_config.py — reads ~/.config/opencode/opencode.json{c},\n * resolves custom provider settings (base URL, headers, API keys), and expands\n * environment variable / file placeholders in config values.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tcloseSync,\n\texistsSync,\n\tfchmodSync,\n\tfchownSync,\n\tfsyncSync,\n\tftruncateSync,\n\tlstatSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\treadlinkSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { codememHomeDir } from \"./home.js\";\n\n// ---------------------------------------------------------------------------\n// JSONC helpers\n// ---------------------------------------------------------------------------\n\n/** Strip JavaScript-style `//` line comments and `/* ... */` block comments from JSONC text. */\nexport function stripJsonComments(text: string): string {\n\tconst result: string[] = [];\n\tlet inString = false;\n\tlet escapeNext = false;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst char = text.charAt(i);\n\t\tif (escapeNext) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && inString) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = !inString;\n\t\t\tresult.push(char);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!inString && char === \"/\" && i + 1 < text.length) {\n\t\t\tconst next = text.charAt(i + 1);\n\t\t\tif (next === \"/\") {\n\t\t\t\t// Line comment — skip until newline\n\t\t\t\tlet j = i + 2;\n\t\t\t\twhile (j < text.length && text.charAt(j) !== \"\\n\") j++;\n\t\t\t\ti = j - 1; // outer loop will increment\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (next === \"*\") {\n\t\t\t\t// Block comment — skip until */\n\t\t\t\tlet j = i + 2;\n\t\t\t\twhile (j < text.length - 1) {\n\t\t\t\t\tif (text.charAt(j) === \"*\" && text.charAt(j + 1) === \"/\") {\n\t\t\t\t\t\tj += 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\ti = j - 1; // outer loop will increment\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tresult.push(char);\n\t}\n\treturn result.join(\"\");\n}\n\n/** Remove trailing commas before `]` or `}` (outside strings). */\nexport function stripTrailingCommas(text: string): string {\n\tconst result: string[] = [];\n\tlet inString = false;\n\tlet escapeNext = false;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst char = text.charAt(i);\n\t\tif (escapeNext) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && inString) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = !inString;\n\t\t\tresult.push(char);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!inString && char === \",\") {\n\t\t\t// Look ahead past whitespace for a closing bracket/brace\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < text.length && /\\s/.test(text.charAt(j))) j++;\n\t\t\tif (j < text.length && (text.charAt(j) === \"]\" || text.charAt(j) === \"}\")) {\n\t\t\t\tcontinue; // skip the trailing comma\n\t\t\t}\n\t\t}\n\t\tresult.push(char);\n\t}\n\treturn result.join(\"\");\n}\n\n// ---------------------------------------------------------------------------\n// Config loading\n// ---------------------------------------------------------------------------\n\n/** Load OpenCode config from `~/.config/opencode/opencode.json{c}`. */\nexport function loadOpenCodeConfig(): Record<string, unknown> {\n\tconst configDir = join(codememHomeDir(), \".config\", \"opencode\");\n\tconst candidates = [join(configDir, \"opencode.json\"), join(configDir, \"opencode.jsonc\")];\n\n\tconst configPath = candidates.find((p) => existsSync(p));\n\tif (!configPath) return {};\n\n\tlet text: string;\n\ttry {\n\t\ttext = readFileSync(configPath, \"utf-8\");\n\t} catch {\n\t\treturn {};\n\t}\n\n\t// Try plain JSON first\n\ttry {\n\t\treturn JSON.parse(text) as Record<string, unknown>;\n\t} catch {\n\t\t// fall through to JSONC\n\t}\n\n\ttry {\n\t\tconst cleaned = stripTrailingCommas(stripJsonComments(text));\n\t\treturn JSON.parse(cleaned) as Record<string, unknown>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n/** Expand `~/...` paths like Python's `Path(...).expanduser()`. */\nexport function expandUserPath(value: string): string {\n\treturn value.startsWith(\"~/\") ? join(codememHomeDir(), value.slice(2)) : value;\n}\n\nfunction isSafeWorkspaceId(value: string): boolean {\n\treturn /^[A-Za-z0-9._:-]+$/.test(value) && !/^\\.+$/.test(value);\n}\n\nexport function getWorkspaceCodememConfigPath(workspaceId: string): string {\n\tconst trimmed = workspaceId.trim();\n\tif (!trimmed || !isSafeWorkspaceId(trimmed)) {\n\t\tthrow new Error(`Invalid workspace id for config path: ${workspaceId}`);\n\t}\n\treturn join(codememHomeDir(), \".codemem\", \"workspaces\", trimmed, \"config\", \"codemem.json\");\n}\n\nexport function getWorkspaceScopedCodememConfigPath(): string | null {\n\tconst runtimeRoot = process.env.CODEMEM_RUNTIME_ROOT?.trim();\n\tif (runtimeRoot) {\n\t\tconst expandedRoot = expandUserPath(runtimeRoot);\n\t\tif (isAbsolute(expandedRoot)) {\n\t\t\treturn join(expandedRoot, \"config\", \"codemem.json\");\n\t\t}\n\t\t// Invalid/relative runtime root — fall through to workspace-id lookup\n\t}\n\n\tconst workspaceId = process.env.CODEMEM_WORKSPACE_ID?.trim();\n\tif (!workspaceId) return null;\n\tif (!isSafeWorkspaceId(workspaceId)) return null;\n\treturn getWorkspaceCodememConfigPath(workspaceId);\n}\n\nfunction getLegacyCodememConfigPath(): string {\n\tconst configDir = join(codememHomeDir(), \".config\", \"codemem\");\n\tconst candidates = [join(configDir, \"config.json\"), join(configDir, \"config.jsonc\")];\n\treturn candidates.find((p) => existsSync(p)) ?? join(configDir, \"config.json\");\n}\n\nfunction getCodememConfigWritePath(): string {\n\treturn resolveCodememConfigPath(undefined, \"write\").resolved.path;\n}\n\nexport function readWorkspaceCodememConfigFile(workspaceId: string): Record<string, unknown> {\n\treturn readCodememConfigFileAtPath(getWorkspaceCodememConfigPath(workspaceId));\n}\n\n/** Env var overrides matching Python's CONFIG_ENV_OVERRIDES. */\nexport const CODEMEM_CONFIG_ENV_OVERRIDES: Record<string, string> = {\n\tactor_id: \"CODEMEM_ACTOR_ID\",\n\tactor_display_name: \"CODEMEM_ACTOR_DISPLAY_NAME\",\n\tclaude_command: \"CODEMEM_CLAUDE_COMMAND\",\n\tcodex_command: \"CODEMEM_CODEX_COMMAND\",\n\tobserver_provider: \"CODEMEM_OBSERVER_PROVIDER\",\n\tobserver_model: \"CODEMEM_OBSERVER_MODEL\",\n\tobserver_temperature: \"CODEMEM_OBSERVER_TEMPERATURE\",\n\tobserver_openai_use_responses: \"CODEMEM_OBSERVER_OPENAI_USE_RESPONSES\",\n\tobserver_max_output_tokens: \"CODEMEM_OBSERVER_MAX_OUTPUT_TOKENS\",\n\tobserver_reasoning_effort: \"CODEMEM_OBSERVER_REASONING_EFFORT\",\n\tobserver_reasoning_summary: \"CODEMEM_OBSERVER_REASONING_SUMMARY\",\n\tobserver_tier_routing_enabled: \"CODEMEM_OBSERVER_TIER_ROUTING_ENABLED\",\n\tobserver_simple_provider: \"CODEMEM_OBSERVER_SIMPLE_PROVIDER\",\n\tobserver_simple_model: \"CODEMEM_OBSERVER_SIMPLE_MODEL\",\n\tobserver_simple_temperature: \"CODEMEM_OBSERVER_SIMPLE_TEMPERATURE\",\n\tobserver_rich_provider: \"CODEMEM_OBSERVER_RICH_PROVIDER\",\n\tobserver_rich_model: \"CODEMEM_OBSERVER_RICH_MODEL\",\n\tobserver_rich_temperature: \"CODEMEM_OBSERVER_RICH_TEMPERATURE\",\n\tobserver_rich_reasoning_effort: \"CODEMEM_OBSERVER_RICH_REASONING_EFFORT\",\n\tobserver_rich_reasoning_summary: \"CODEMEM_OBSERVER_RICH_REASONING_SUMMARY\",\n\tobserver_rich_max_output_tokens: \"CODEMEM_OBSERVER_RICH_MAX_OUTPUT_TOKENS\",\n\tobserver_output_mode: \"CODEMEM_OBSERVER_OUTPUT_MODE\",\n\tobserver_base_url: \"CODEMEM_OBSERVER_BASE_URL\",\n\tobserver_runtime: \"CODEMEM_OBSERVER_RUNTIME\",\n\tobserver_auth_source: \"CODEMEM_OBSERVER_AUTH_SOURCE\",\n\tobserver_auth_file: \"CODEMEM_OBSERVER_AUTH_FILE\",\n\tobserver_auth_command: \"CODEMEM_OBSERVER_AUTH_COMMAND\",\n\tobserver_auth_timeout_ms: \"CODEMEM_OBSERVER_AUTH_TIMEOUT_MS\",\n\tobserver_auth_cache_ttl_s: \"CODEMEM_OBSERVER_AUTH_CACHE_TTL_S\",\n\tobserver_headers: \"CODEMEM_OBSERVER_HEADERS\",\n\tobserver_max_chars: \"CODEMEM_OBSERVER_MAX_CHARS\",\n\tobserver_max_tokens: \"CODEMEM_OBSERVER_MAX_TOKENS\",\n\tpack_observation_limit: \"CODEMEM_PACK_OBSERVATION_LIMIT\",\n\tpack_session_limit: \"CODEMEM_PACK_SESSION_LIMIT\",\n\tsync_enabled: \"CODEMEM_SYNC_ENABLED\",\n\tsync_device_name: \"CODEMEM_SYNC_DEVICE_NAME\",\n\tsync_host: \"CODEMEM_SYNC_HOST\",\n\tsync_port: \"CODEMEM_SYNC_PORT\",\n\tsync_interval_s: \"CODEMEM_SYNC_INTERVAL_S\",\n\tsync_mdns: \"CODEMEM_SYNC_MDNS\",\n\tsync_advertise: \"CODEMEM_SYNC_ADVERTISE\",\n\tsync_coordinator_url: \"CODEMEM_SYNC_COORDINATOR_URL\",\n\tsync_coordinator_group: \"CODEMEM_SYNC_COORDINATOR_GROUP\",\n\tsync_coordinator_groups: \"CODEMEM_SYNC_COORDINATOR_GROUPS\",\n\tsync_coordinator_timeout_s: \"CODEMEM_SYNC_COORDINATOR_TIMEOUT_S\",\n\tsync_coordinator_presence_ttl_s: \"CODEMEM_SYNC_COORDINATOR_PRESENCE_TTL_S\",\n\tsync_coordinator_admin_secret: \"CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET\",\n\tsync_retention_enabled: \"CODEMEM_SYNC_RETENTION_ENABLED\",\n\tsync_retention_max_age_days: \"CODEMEM_SYNC_RETENTION_MAX_AGE_DAYS\",\n\tsync_retention_max_size_mb: \"CODEMEM_SYNC_RETENTION_MAX_SIZE_MB\",\n\tsync_retention_interval_s: \"CODEMEM_SYNC_RETENTION_INTERVAL_S\",\n\tsync_retention_max_runtime_ms: \"CODEMEM_SYNC_RETENTION_MAX_RUNTIME_MS\",\n\tsync_retention_max_ops_per_pass: \"CODEMEM_SYNC_RETENTION_MAX_OPS_PER_PASS\",\n\tsync_projects_include: \"CODEMEM_SYNC_PROJECTS_INCLUDE\",\n\tsync_projects_exclude: \"CODEMEM_SYNC_PROJECTS_EXCLUDE\",\n\tsync_ops_limit: \"CODEMEM_SYNC_OPS_LIMIT\",\n\traw_events_sweeper_interval_s: \"CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_S\",\n\traw_events_retention_enabled: \"CODEMEM_RAW_EVENTS_RETENTION_ENABLED\",\n\traw_events_retention_max_age_days: \"CODEMEM_RAW_EVENTS_RETENTION_MAX_AGE_DAYS\",\n};\n\n/** Normalize a configured sidecar command from argv or a shell-style string. */\nexport function coerceObserverCommand(value: unknown): string[] | null {\n\tif (value == null) return null;\n\tif (Array.isArray(value)) {\n\t\tconst parts = value.filter((item): item is string => {\n\t\t\treturn typeof item === \"string\" && item.trim() !== \"\";\n\t\t});\n\t\treturn parts.length > 0 ? parts : null;\n\t}\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(trimmed) as unknown;\n\t\tif (Array.isArray(parsed) && parsed.every((item) => typeof item === \"string\")) {\n\t\t\tconst parts = parsed.filter((item) => item.trim() !== \"\");\n\t\t\treturn parts.length > 0 ? parts : null;\n\t\t}\n\t} catch {\n\t\t// Non-JSON command strings use the same whitespace splitting as existing config.\n\t}\n\tconst parts = trimmed.split(/\\s+/).filter((item) => item !== \"\");\n\treturn parts.length > 0 ? parts : null;\n}\n\n// ---------------------------------------------------------------------------\n// Unified config path resolver with full traceability\n// ---------------------------------------------------------------------------\n\nexport type ConfigPathSource =\n\t| \"cli-flag\"\n\t| \"env-codemem-config\"\n\t| \"env-runtime-root\"\n\t| \"env-workspace-id\"\n\t| \"legacy-global\";\n\nexport interface ConfigPathResolution {\n\tpath: string;\n\tsource: ConfigPathSource;\n\treason: string;\n\texists: boolean;\n\t/** Whether this candidate is structurally valid (absolute path, safe workspace id, etc.). */\n\tvalid: boolean;\n}\n\nexport interface ConfigResolutionResult {\n\tresolved: ConfigPathResolution;\n\tfallbackChain: ConfigPathResolution[];\n}\n\n/**\n * Resolve the codemem config path with full traceability.\n *\n * Every candidate in the precedence chain is evaluated and recorded.\n * The `resolved` field is the winner; `fallbackChain` holds all rejected candidates\n * with a reason string explaining why each was skipped.\n *\n * @param cliConfigPath - explicit --config flag value (highest precedence)\n * @param mode - 'read' checks existence and falls back; 'write' takes first match\n */\nexport function resolveCodememConfigPath(\n\tcliConfigPath?: string,\n\tmode: \"read\" | \"write\" = \"read\",\n): ConfigResolutionResult {\n\tconst candidates: ConfigPathResolution[] = [];\n\n\t// 1. CLI flag (highest precedence)\n\tif (cliConfigPath?.trim()) {\n\t\tconst path = expandUserPath(cliConfigPath.trim());\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"cli-flag\",\n\t\t\treason: `--config ${cliConfigPath}`,\n\t\t\texists: existsSync(path),\n\t\t\tvalid: true,\n\t\t});\n\t}\n\n\t// 2. CODEMEM_CONFIG env\n\tconst envConfig = process.env.CODEMEM_CONFIG?.trim();\n\tif (envConfig) {\n\t\tconst path = expandUserPath(envConfig);\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"env-codemem-config\",\n\t\t\treason: `CODEMEM_CONFIG='${envConfig}'`,\n\t\t\texists: existsSync(path),\n\t\t\tvalid: true,\n\t\t});\n\t}\n\n\t// 3. CODEMEM_RUNTIME_ROOT env (must be absolute after expandUser)\n\tconst runtimeRoot = process.env.CODEMEM_RUNTIME_ROOT?.trim();\n\tif (runtimeRoot) {\n\t\tconst expandedRoot = expandUserPath(runtimeRoot);\n\t\tconst absolute = isAbsolute(expandedRoot);\n\t\tconst path = join(expandedRoot, \"config\", \"codemem.json\");\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"env-runtime-root\",\n\t\t\treason: absolute\n\t\t\t\t? `CODEMEM_RUNTIME_ROOT='${runtimeRoot}'`\n\t\t\t\t: `CODEMEM_RUNTIME_ROOT='${runtimeRoot}' is relative, not absolute`,\n\t\t\texists: absolute ? existsSync(path) : false,\n\t\t\tvalid: absolute,\n\t\t});\n\t}\n\n\t// 4. CODEMEM_WORKSPACE_ID env (must pass isSafeWorkspaceId)\n\tconst workspaceId = process.env.CODEMEM_WORKSPACE_ID?.trim();\n\tif (workspaceId) {\n\t\tconst safe = isSafeWorkspaceId(workspaceId);\n\t\tconst path = safe\n\t\t\t? getWorkspaceCodememConfigPath(workspaceId)\n\t\t\t: join(codememHomeDir(), \".codemem\", \"workspaces\", workspaceId, \"config\", \"codemem.json\");\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"env-workspace-id\",\n\t\t\treason: safe\n\t\t\t\t? `CODEMEM_WORKSPACE_ID='${workspaceId}'`\n\t\t\t\t: `CODEMEM_WORKSPACE_ID='${workspaceId}' failed safety check`,\n\t\t\texists: safe ? existsSync(path) : false,\n\t\t\tvalid: safe,\n\t\t});\n\t}\n\n\t// 5. Legacy global config (~/.config/codemem/config.json{c})\n\tconst legacyPath = getLegacyCodememConfigPath();\n\tcandidates.push({\n\t\tpath: legacyPath,\n\t\tsource: \"legacy-global\",\n\t\treason: \"legacy global config\",\n\t\texists: existsSync(legacyPath),\n\t\tvalid: true,\n\t});\n\n\t// Explicit overrides (cli-flag, env-codemem-config) are authoritative:\n\t// they win in both read and write mode regardless of file existence.\n\t// This matches the original getCodememConfigPath behavior where\n\t// CODEMEM_CONFIG is returned immediately without an existence check.\n\tconst isAuthoritative = (c: ConfigPathResolution): boolean =>\n\t\tc.source === \"cli-flag\" || c.source === \"env-codemem-config\";\n\n\t// Select the winner based on mode.\n\t// Validity is determined structurally via the `valid` flag on each candidate,\n\t// not by inspecting the `reason` string.\n\tlet resolvedIndex: number;\n\tif (mode === \"write\") {\n\t\t// Write mode: first valid candidate regardless of existence\n\t\tresolvedIndex = candidates.findIndex((c) => c.valid);\n\t} else {\n\t\t// Read mode: authoritative sources win immediately; otherwise first existing candidate\n\t\tconst authoritativeIndex = candidates.findIndex((c) => isAuthoritative(c) && c.valid);\n\t\tif (authoritativeIndex >= 0) {\n\t\t\tresolvedIndex = authoritativeIndex;\n\t\t} else {\n\t\t\tconst existingIndex = candidates.findIndex((c) => c.valid && c.exists);\n\t\t\t// If none exist, fall back to first valid candidate (matches getCodememConfigPath behavior)\n\t\t\tresolvedIndex = existingIndex >= 0 ? existingIndex : candidates.findIndex((c) => c.valid);\n\t\t}\n\t}\n\n\t// Should always find at least the legacy candidate, but guard anyway\n\tif (resolvedIndex < 0) resolvedIndex = candidates.length - 1;\n\n\tconst resolved = candidates[resolvedIndex] ?? candidates[candidates.length - 1];\n\tif (!resolved) {\n\t\tthrow new Error(\"No config path candidates were generated\");\n\t}\n\tconst fallbackChain = candidates.filter((_, i) => i !== resolvedIndex);\n\n\t// Annotate skipped candidates with why they were not selected\n\tfor (const entry of fallbackChain) {\n\t\tif (entry.source === \"env-runtime-root\" && entry.reason.includes(\"is relative\")) {\n\t\t\t// Already has a descriptive reason\n\t\t} else if (\n\t\t\tentry.source === \"env-workspace-id\" &&\n\t\t\tentry.reason.includes(\"failed safety check\")\n\t\t) {\n\t\t\t// Already has a descriptive reason\n\t\t} else if (mode === \"read\" && !entry.exists) {\n\t\t\tentry.reason += \" (does not exist)\";\n\t\t}\n\t}\n\n\treturn { resolved, fallbackChain };\n}\n\n/**\n * Resolve codemem config path with precedence:\n * 1. explicit CODEMEM_CONFIG override\n * 2. workspace-scoped config via CODEMEM_RUNTIME_ROOT or CODEMEM_WORKSPACE_ID\n * 3. legacy global config under ~/.config/codemem/\n */\nexport function getCodememConfigPath(): string {\n\treturn resolveCodememConfigPath(undefined, \"read\").resolved.path;\n}\n\n/** Read codemem config file with the same JSON/JSONC behavior as Python. */\nexport function readCodememConfigFile(): Record<string, unknown> {\n\tconst configPath = getCodememConfigPath();\n\treturn readCodememConfigFileAtPath(configPath);\n}\n\nexport function readCodememConfigFileAtPath(configPath: string): Record<string, unknown> {\n\tconst resolvedPath = expandUserPath(configPath);\n\tif (!existsSync(resolvedPath)) return {};\n\n\tlet text: string;\n\ttry {\n\t\ttext = readFileSync(resolvedPath, \"utf-8\");\n\t} catch {\n\t\treturn {};\n\t}\n\n\tif (!text.trim()) return {};\n\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\treturn parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t: {};\n\t} catch {\n\t\t// fall through to JSONC\n\t}\n\n\ttry {\n\t\tconst cleaned = stripTrailingCommas(stripJsonComments(text));\n\t\tconst parsed = JSON.parse(cleaned) as unknown;\n\t\treturn parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t: {};\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nexport type CodememConfigReadOutcome =\n\t| { status: \"missing\"; path: string; revision: \"missing\" }\n\t| {\n\t\t\tstatus: \"valid\";\n\t\t\tpath: string;\n\t\t\tdata: Record<string, unknown>;\n\t\t\trevision: string;\n\t\t\tmode: number;\n\t\t\tuid: number;\n\t\t\tgid: number;\n\t\t\tctimeNs: bigint;\n\t\t\tdev: bigint;\n\t\t\tino: bigint;\n\t }\n\t| { status: \"invalid\"; path: string; reason: \"empty\" | \"non_object\" | \"parse_error\" }\n\t| { status: \"unreadable\"; path: string };\n\nexport type CodememConfigMutationResult = {\n\tpath: string;\n\tmutationPath: string;\n\tdata: Record<string, unknown>;\n\trevision: string;\n};\n\nexport type ConfigFileMetadata = { mode: number; uid: number; gid: number };\ntype ConfigFileIdentity = ConfigFileMetadata & {\n\tctimeNs: bigint;\n\tdev: bigint;\n\tino: bigint;\n};\n\nexport class CodememConfigMutationError extends Error {\n\treadonly code: \"busy\" | \"changed\" | \"invalid\" | \"unreadable\";\n\n\tconstructor(code: CodememConfigMutationError[\"code\"], message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CodememConfigMutationError\";\n\t\tthis.code = code;\n\t}\n}\n\ntype AtomicConfigFileOperations = {\n\topen: typeof openSync;\n\tclose: typeof closeSync;\n\tchown?: typeof fchownSync;\n\tchmod: typeof fchmodSync;\n\ttruncate?: typeof ftruncateSync;\n\tsync: typeof fsyncSync;\n\twrite: typeof writeSync;\n\trename: typeof renameSync;\n\tunlink: typeof unlinkSync;\n\tseedMetadata?: (sourcePath: string, destinationFd: number) => boolean;\n};\n\ntype ConfigLockCleanupOperations = Pick<AtomicConfigFileOperations, \"close\" | \"unlink\">;\n\nlet gnuCopyAvailable: boolean | undefined;\n\nfunction hasGnuCopy(): boolean {\n\tif (gnuCopyAvailable !== undefined) return gnuCopyAvailable;\n\ttry {\n\t\texecFileSync(\"/bin/cp\", [\"--version\"], { stdio: \"ignore\" });\n\t\tgnuCopyAvailable = true;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\tgnuCopyAvailable = false;\n\t\t\treturn gnuCopyAvailable;\n\t\t}\n\t\tif (error instanceof Error && \"status\" in error && typeof error.status === \"number\") {\n\t\t\tgnuCopyAvailable = false;\n\t\t\treturn gnuCopyAvailable;\n\t\t}\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t\"Cannot update config because extended access metadata support could not be checked.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\treturn gnuCopyAvailable;\n}\n\nfunction clearMacOsReplacementFlags(destinationFd: number): void {\n\texecFileSync(\"/usr/bin/chflags\", [\"0\", \"/dev/fd/3\"], {\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\", destinationFd],\n\t});\n}\n\nfunction seedConfigReplacementMetadata(sourcePath: string, destinationFd: number): boolean {\n\tlet args: string[] | undefined;\n\tlet env: NodeJS.ProcessEnv | undefined;\n\tif (process.platform === \"darwin\") {\n\t\targs = [\"-p\", sourcePath, \"/dev/fd/3\"];\n\t\tenv = { ...process.env };\n\t\tdelete env.COPYFILE_DISABLE;\n\t} else if (process.platform === \"linux\" && hasGnuCopy()) {\n\t\targs = [\"--preserve=mode,ownership,xattr\", \"--\", sourcePath, \"/proc/self/fd/3\"];\n\t}\n\tif (!args) return false;\n\n\ttry {\n\t\texecFileSync(\"/bin/cp\", args, {\n\t\t\tenv,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\", destinationFd],\n\t\t});\n\t\tif (process.platform === \"darwin\") clearMacOsReplacementFlags(destinationFd);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\ttry {\n\t\t\t\tclearMacOsReplacementFlags(destinationFd);\n\t\t\t} catch {\n\t\t\t\t// Preserve the metadata-copy failure; cleanup will retry unlinking the temp file.\n\t\t\t}\n\t\t}\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t`Cannot update config because extended access metadata from ${sourcePath} could not be preserved.`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nconst atomicConfigFileOperations: AtomicConfigFileOperations = {\n\topen: openSync,\n\tclose: closeSync,\n\tchown: fchownSync,\n\tchmod: fchmodSync,\n\ttruncate: ftruncateSync,\n\tsync: fsyncSync,\n\twrite: writeSync,\n\trename: renameSync,\n\tunlink: unlinkSync,\n\tseedMetadata: seedConfigReplacementMetadata,\n};\n\nconst configLockCleanupOperations: ConfigLockCleanupOperations = {\n\tclose: closeSync,\n\tunlink: unlinkSync,\n};\n\nfunction configRevision(text: string): string {\n\treturn createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\nfunction parseConfigText(\n\ttext: string,\n):\n\t| { status: \"valid\"; data: Record<string, unknown> }\n\t| { status: \"invalid\"; reason: \"empty\" | \"non_object\" | \"parse_error\" } {\n\tif (!text.trim()) return { status: \"invalid\", reason: \"empty\" };\n\tfor (const candidate of [text, stripTrailingCommas(stripJsonComments(text))]) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(candidate) as unknown;\n\t\t\tif (parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\t\treturn { status: \"valid\", data: parsed as Record<string, unknown> };\n\t\t\t}\n\t\t\treturn { status: \"invalid\", reason: \"non_object\" };\n\t\t} catch {\n\t\t\t// Try JSONC before reporting invalid syntax.\n\t\t}\n\t}\n\treturn { status: \"invalid\", reason: \"parse_error\" };\n}\n\n/** Read a config for mutation without treating damaged input as an empty object. */\nexport function readCodememConfigFileForMutation(configPath?: string): CodememConfigReadOutcome {\n\tconst path = configPath ? expandUserPath(configPath) : getCodememConfigWritePath();\n\tif (!existsSync(path)) return { status: \"missing\", path, revision: \"missing\" };\n\tlet text: string;\n\tlet metadata: ConfigFileIdentity;\n\ttry {\n\t\ttext = readFileSync(path, \"utf8\");\n\t\tconst stats = statSync(path, { bigint: true });\n\t\tmetadata = {\n\t\t\tmode: Number(stats.mode & 0o777n),\n\t\t\tuid: Number(stats.uid),\n\t\t\tgid: Number(stats.gid),\n\t\t\tctimeNs: stats.ctimeNs,\n\t\t\tdev: stats.dev,\n\t\t\tino: stats.ino,\n\t\t};\n\t} catch {\n\t\treturn { status: \"unreadable\", path };\n\t}\n\tconst parsed = parseConfigText(text);\n\tif (parsed.status === \"invalid\") return { ...parsed, path };\n\treturn { ...parsed, path, revision: configRevision(text), ...metadata };\n}\n\nfunction unlinkIfPresent(path: string, unlink: typeof unlinkSync): void {\n\ttry {\n\t\tunlink(path);\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? String(error.code) : \"\";\n\t\tif (code !== \"ENOENT\") throw error;\n\t}\n}\n\nfunction cleanupReplacementTempFile(\n\ttempPath: string,\n\tunlink: typeof unlinkSync,\n\trenameCommitted: boolean,\n): void {\n\ttry {\n\t\tunlinkIfPresent(tempPath, unlink);\n\t} catch (error) {\n\t\tif (!renameCommitted) throw error;\n\t}\n}\n\nfunction resolveConfigMutationTarget(path: string): string {\n\tconst seen = new Set<string>();\n\tlet current = path;\n\twhile (true) {\n\t\tif (seen.has(current)) {\n\t\t\tthrow new CodememConfigMutationError(\n\t\t\t\t\"unreadable\",\n\t\t\t\t`Cannot update config because ${path} contains a symbolic-link cycle.`,\n\t\t\t);\n\t\t}\n\t\tseen.add(current);\n\t\ttry {\n\t\t\treturn realpathSync(current);\n\t\t} catch {\n\t\t\t// Follow broken link chains until reaching the intended missing target.\n\t\t}\n\t\ttry {\n\t\t\tif (lstatSync(current).isSymbolicLink()) {\n\t\t\t\tconst target = readlinkSync(current);\n\t\t\t\tcurrent = isAbsolute(target) ? target : resolve(dirname(current), target);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn current;\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\treturn join(realpathSync(dirname(current)), basename(current));\n\t\t\t} catch {\n\t\t\t\treturn current;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction syncConfigDirectory(targetPath: string, operations: AtomicConfigFileOperations): void {\n\tlet directoryFd: number | null = null;\n\ttry {\n\t\tdirectoryFd = operations.open(dirname(targetPath), \"r\");\n\t\toperations.sync(directoryFd);\n\t} catch {\n\t\t// The rename already committed. Directory sync is best-effort on filesystems\n\t\t// that reject or fail it, so callers must not mistake this for an uncommitted save.\n\t} finally {\n\t\tif (directoryFd != null) {\n\t\t\ttry {\n\t\t\t\toperations.close(directoryFd);\n\t\t\t} catch {\n\t\t\t\t// Closing after a committed rename cannot safely turn success into failure.\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction writeCompleteConfig(\n\tfd: number,\n\ttext: string,\n\twrite: AtomicConfigFileOperations[\"write\"],\n): void {\n\tconst bytes = Buffer.from(text, \"utf8\");\n\tlet offset = 0;\n\twhile (offset < bytes.length) {\n\t\tconst written = write(fd, bytes, offset, bytes.length - offset, offset);\n\t\tif (written === 0) throw new Error(\"Config replacement write made no progress\");\n\t\toffset += written;\n\t}\n}\n\n/** Internal fault-injection seam used by config persistence tests. */\nexport function atomicReplaceConfigFile(\n\ttargetPath: string,\n\ttext: string,\n\tmetadata: ConfigFileMetadata | number | undefined,\n\toperations: AtomicConfigFileOperations = atomicConfigFileOperations,\n\tverifyBeforeRename?: () => void,\n\t{ followSymlink = true }: { followSymlink?: boolean } = {},\n): void {\n\tconst replacementPath = followSymlink ? resolveConfigMutationTarget(targetPath) : targetPath;\n\tconst tempPath = `${replacementPath}.tmp-${process.pid}-${randomUUID()}`;\n\tlet tempFd: number | null = null;\n\tlet renameCommitted = false;\n\ttry {\n\t\tconst mode = typeof metadata === \"number\" ? metadata : metadata?.mode;\n\t\ttempFd = operations.open(tempPath, \"wx\", mode ?? 0o600);\n\t\tconst seededMetadata =\n\t\t\ttypeof metadata === \"object\" && operations.seedMetadata?.(replacementPath, tempFd) === true;\n\t\tif (seededMetadata) {\n\t\t\tif (!operations.truncate) throw new Error(\"Seeded config replacement requires truncate\");\n\t\t\toperations.truncate(tempFd, 0);\n\t\t}\n\t\tif (typeof metadata === \"object\" && process.platform !== \"win32\") {\n\t\t\toperations.chown?.(tempFd, metadata.uid, metadata.gid);\n\t\t}\n\t\tif (mode != null) operations.chmod(tempFd, mode);\n\t\twriteCompleteConfig(tempFd, text, operations.write);\n\t\toperations.sync(tempFd);\n\t\tconst completedFd = tempFd;\n\t\ttempFd = null;\n\t\toperations.close(completedFd);\n\t\tverifyBeforeRename?.();\n\t\toperations.rename(tempPath, replacementPath);\n\t\trenameCommitted = true;\n\t\tsyncConfigDirectory(replacementPath, operations);\n\t} finally {\n\t\ttry {\n\t\t\tif (tempFd != null) operations.close(tempFd);\n\t\t} finally {\n\t\t\tcleanupReplacementTempFile(tempPath, operations.unlink, renameCommitted);\n\t\t}\n\t}\n}\n\nfunction assertMutationInput(outcome: CodememConfigReadOutcome): Record<string, unknown> {\n\tif (outcome.status === \"missing\") return {};\n\tif (outcome.status === \"valid\") return outcome.data;\n\tif (outcome.status === \"unreadable\") {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t`Cannot update config because ${outcome.path} could not be read.`,\n\t\t);\n\t}\n\tthrow new CodememConfigMutationError(\n\t\t\"invalid\",\n\t\t`Cannot update config because ${outcome.path} is not a valid JSON object.`,\n\t);\n}\n\nfunction currentRevision(path: string): string | \"missing\" | \"unreadable\" {\n\tif (!existsSync(path)) return \"missing\";\n\ttry {\n\t\treturn configRevision(readFileSync(path, \"utf8\"));\n\t} catch {\n\t\treturn \"unreadable\";\n\t}\n}\n\nfunction currentMetadata(path: string): ConfigFileIdentity | \"missing\" | \"unreadable\" {\n\tif (!existsSync(path)) return \"missing\";\n\ttry {\n\t\tconst stats = statSync(path, { bigint: true });\n\t\treturn {\n\t\t\tmode: Number(stats.mode & 0o777n),\n\t\t\tuid: Number(stats.uid),\n\t\t\tgid: Number(stats.gid),\n\t\t\tctimeNs: stats.ctimeNs,\n\t\t\tdev: stats.dev,\n\t\t\tino: stats.ino,\n\t\t};\n\t} catch {\n\t\treturn \"unreadable\";\n\t}\n}\n\nfunction configIdentityMatches(\n\tcurrent: ReturnType<typeof currentMetadata>,\n\texpected: ConfigFileIdentity,\n): boolean {\n\treturn (\n\t\ttypeof current !== \"string\" &&\n\t\tconfigMetadataMatches(current, expected) &&\n\t\tcurrent.ctimeNs === expected.ctimeNs &&\n\t\tcurrent.dev === expected.dev &&\n\t\tcurrent.ino === expected.ino\n\t);\n}\n\nfunction configMetadataMatches(\n\tcurrent: ReturnType<typeof currentMetadata>,\n\texpected: ConfigFileMetadata,\n): boolean {\n\treturn (\n\t\ttypeof current !== \"string\" &&\n\t\tcurrent.mode === expected.mode &&\n\t\tcurrent.uid === expected.uid &&\n\t\tcurrent.gid === expected.gid\n\t);\n}\n\nfunction configMetadata(outcome: CodememConfigReadOutcome): ConfigFileMetadata | undefined {\n\tif (outcome.status !== \"valid\") return undefined;\n\treturn { mode: outcome.mode, uid: outcome.uid, gid: outcome.gid };\n}\n\nfunction acquireConfigLock(targetPath: string): { fd: number; path: string } {\n\tconst path = `${targetPath}.lock`;\n\ttry {\n\t\treturn { fd: openSync(path, \"wx\", 0o600), path };\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? String(error.code) : \"\";\n\t\tif (code === \"EEXIST\") {\n\t\t\tthrow new CodememConfigMutationError(\n\t\t\t\t\"busy\",\n\t\t\t\t`Cannot update config because another writer is updating ${targetPath}. Retry the save; if no save is active, remove the stale lock at ${path}.`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t`Cannot update config because its writer lock could not be created at ${path}.`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nfunction releaseConfigLock(\n\tlock: { fd: number; path: string },\n\toperations: ConfigLockCleanupOperations,\n): void {\n\tlet firstError: unknown;\n\ttry {\n\t\toperations.close(lock.fd);\n\t} catch (error) {\n\t\tfirstError = error;\n\t}\n\ttry {\n\t\tunlinkIfPresent(lock.path, operations.unlink);\n\t} catch (error) {\n\t\tfirstError ??= error;\n\t}\n\tif (firstError !== undefined) throw firstError;\n}\n\nfunction releaseConfigLocks(\n\tlocks: Array<{ fd: number; path: string }>,\n\toperations: ConfigLockCleanupOperations = configLockCleanupOperations,\n): void {\n\tlet firstError: unknown;\n\tfor (const lock of locks.reverse()) {\n\t\ttry {\n\t\t\treleaseConfigLock(lock, operations);\n\t\t} catch (error) {\n\t\t\tfirstError ??= error;\n\t\t}\n\t}\n\tif (firstError !== undefined) throw firstError;\n}\n\nfunction releaseConfigLocksAfterMutation(\n\tlocks: Array<{ fd: number; path: string }>,\n\tcommitted: boolean,\n\toperations: ConfigLockCleanupOperations,\n): void {\n\ttry {\n\t\treleaseConfigLocks(locks, operations);\n\t} catch (error) {\n\t\tif (!committed) throw error;\n\t}\n}\n\nfunction acquireConfigLocks(targetPaths: string[]): Array<{ fd: number; path: string }> {\n\tconst orderedPaths = [...new Set(targetPaths)].sort((left, right) => {\n\t\tif (left < right) return -1;\n\t\tif (left > right) return 1;\n\t\treturn 0;\n\t});\n\tconst locks: Array<{ fd: number; path: string }> = [];\n\ttry {\n\t\tfor (const path of orderedPaths) {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\tlocks.push(acquireConfigLock(path));\n\t\t}\n\t\treturn locks;\n\t} catch (error) {\n\t\ttry {\n\t\t\treleaseConfigLocks(locks);\n\t\t} catch {\n\t\t\t// Preserve the acquisition failure after attempting every cleanup.\n\t\t}\n\t\tthrow error;\n\t}\n}\n\ntype ConfigMutationOptions = {\n\texpectedMutationPath?: string;\n\texpectedRevision?: string;\n\tfallbackReadPath?: string;\n\tlockCleanupOperations?: ConfigLockCleanupOperations;\n};\n\nfunction acquireConfigMutationLocks(\n\ttargetPath: string,\n\tusesImplicitPath: boolean,\n\toptions: ConfigMutationOptions,\n): {\n\tpreliminaryTarget: CodememConfigReadOutcome;\n\tfallbackReadPath: string | undefined;\n\ttargetMutationPath: string;\n\tfallbackMutationPath: string | undefined;\n\tlocks: Array<{ fd: number; path: string }>;\n} {\n\tfor (let attempt = 0; attempt < 3; attempt += 1) {\n\t\tconst preliminaryTarget = readCodememConfigFileForMutation(targetPath);\n\t\tconst fallbackReadPath =\n\t\t\toptions.fallbackReadPath ?? (usesImplicitPath ? getCodememConfigPath() : undefined);\n\t\tconst targetMutationPath = options.expectedMutationPath\n\t\t\t? expandUserPath(options.expectedMutationPath)\n\t\t\t: resolveConfigMutationTarget(targetPath);\n\t\tconst fallbackMutationPath =\n\t\t\tpreliminaryTarget.status === \"missing\" && fallbackReadPath != null\n\t\t\t\t? resolveConfigMutationTarget(expandUserPath(fallbackReadPath))\n\t\t\t\t: undefined;\n\t\tconst locks = acquireConfigLocks([targetMutationPath]);\n\t\tconst targetIdentityStable = resolveConfigMutationTarget(targetPath) === targetMutationPath;\n\t\tconst fallbackIdentityStable =\n\t\t\tfallbackMutationPath === undefined ||\n\t\t\tresolveConfigMutationTarget(expandUserPath(fallbackReadPath ?? targetPath)) ===\n\t\t\t\tfallbackMutationPath;\n\t\tif (targetIdentityStable && fallbackIdentityStable) {\n\t\t\treturn {\n\t\t\t\tpreliminaryTarget,\n\t\t\t\tfallbackReadPath,\n\t\t\t\ttargetMutationPath,\n\t\t\t\tfallbackMutationPath,\n\t\t\t\tlocks,\n\t\t\t};\n\t\t}\n\t\treleaseConfigLocks(locks);\n\t}\n\tthrow new CodememConfigMutationError(\n\t\t\"changed\",\n\t\t`Cannot update config because ${targetPath} changed before the save. Retry the save.`,\n\t);\n}\n\nfunction assertTargetDidNotDisappear(\n\tpreliminaryTarget: CodememConfigReadOutcome,\n\toutcome: CodememConfigReadOutcome,\n\ttargetPath: string,\n): void {\n\tif (preliminaryTarget.status === \"missing\" || outcome.status !== \"missing\") return;\n\tthrow new CodememConfigMutationError(\n\t\t\"changed\",\n\t\t`Cannot update config because ${targetPath} changed before the save. Retry the save.`,\n\t);\n}\n\nfunction mutationInputOutcome(\n\ttarget: CodememConfigReadOutcome,\n\ttargetPath: string,\n\tfallbackReadPath: string | undefined,\n): CodememConfigReadOutcome {\n\tif (target.status !== \"missing\") return target;\n\tconst readPath = fallbackReadPath ?? targetPath;\n\treturn readPath === targetPath ? target : readCodememConfigFileForMutation(readPath);\n}\n\nfunction verifyConfigMutation(input: {\n\ttargetPath: string;\n\ttargetMutationPath: string;\n\texpectedRevision: string;\n\texpectedMetadata: ConfigFileMetadata | undefined;\n\texpectedIdentity: ConfigFileIdentity | undefined;\n\tfallbackReadPath: string | undefined;\n\tfallbackMutationPath: string | undefined;\n\tinputOutcome: CodememConfigReadOutcome;\n\tinputRevision: string;\n}): void {\n\tconst observedMetadata = currentMetadata(input.targetMutationPath);\n\tif (\n\t\tresolveConfigMutationTarget(input.targetPath) !== input.targetMutationPath ||\n\t\tcurrentRevision(input.targetMutationPath) !== input.expectedRevision ||\n\t\t(input.expectedMetadata !== undefined &&\n\t\t\t!configMetadataMatches(observedMetadata, input.expectedMetadata)) ||\n\t\t(input.expectedIdentity !== undefined &&\n\t\t\t!configIdentityMatches(observedMetadata, input.expectedIdentity))\n\t) {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"changed\",\n\t\t\t`Cannot update config because ${input.targetPath} changed during the save. Retry the save.`,\n\t\t);\n\t}\n\tif (\n\t\tinput.fallbackMutationPath !== undefined &&\n\t\tresolveConfigMutationTarget(expandUserPath(input.fallbackReadPath ?? input.targetPath)) !==\n\t\t\tinput.fallbackMutationPath\n\t) {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"changed\",\n\t\t\t`Cannot update config because ${input.fallbackReadPath} changed during the save. Retry the save.`,\n\t\t);\n\t}\n\tif (\n\t\tinput.inputOutcome.path !== input.targetMutationPath &&\n\t\tcurrentRevision(input.inputOutcome.path) !== input.inputRevision\n\t) {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"changed\",\n\t\t\t`Cannot update config because ${input.inputOutcome.path} changed during the save. Retry the save.`,\n\t\t);\n\t}\n}\n\nfunction assertExpectedRevision(targetPath: string, actual: string, expected?: string): void {\n\tif (expected == null || actual === expected) return;\n\tthrow new CodememConfigMutationError(\n\t\t\"changed\",\n\t\t`Cannot update config because ${targetPath} changed before the save. Retry the save.`,\n\t);\n}\n\nfunction expectedConfigState(\n\toutcome: CodememConfigReadOutcome,\n\ttargetPath: string,\n\texpectedRevisionOption?: string,\n): { expectedRevision: string; expectedIdentity: ConfigFileIdentity | undefined } {\n\tconst expectedRevision = outcome.status === \"valid\" ? outcome.revision : \"missing\";\n\tassertExpectedRevision(targetPath, expectedRevision, expectedRevisionOption);\n\treturn {\n\t\texpectedRevision,\n\t\texpectedIdentity:\n\t\t\toutcome.status === \"valid\"\n\t\t\t\t? {\n\t\t\t\t\t\tmode: outcome.mode,\n\t\t\t\t\t\tuid: outcome.uid,\n\t\t\t\t\t\tgid: outcome.gid,\n\t\t\t\t\t\tctimeNs: outcome.ctimeNs,\n\t\t\t\t\t\tdev: outcome.dev,\n\t\t\t\t\t\tino: outcome.ino,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t};\n}\n\nfunction commitConfigMutation(\n\tinput: Parameters<typeof verifyConfigMutation>[0] & {\n\t\tmetadata: ConfigFileMetadata | undefined;\n\t\ttext: string;\n\t},\n): void {\n\tatomicReplaceConfigFile(\n\t\tinput.targetMutationPath,\n\t\tinput.text,\n\t\tinput.metadata,\n\t\tatomicConfigFileOperations,\n\t\t() => verifyConfigMutation(input),\n\t);\n}\n\n/** Serialize a read-modify-write config update across cooperating processes. */\nexport function mutateCodememConfigFile(\n\tmutator: (\n\t\tdata: Record<string, unknown>,\n\t\toutcome: CodememConfigReadOutcome,\n\t) => Record<string, unknown> | undefined,\n\tconfigPath?: string,\n\toptions: ConfigMutationOptions = {},\n): CodememConfigMutationResult {\n\tconst targetPath = configPath ? expandUserPath(configPath) : getCodememConfigWritePath();\n\tconst { preliminaryTarget, fallbackReadPath, targetMutationPath, fallbackMutationPath, locks } =\n\t\tacquireConfigMutationLocks(targetPath, configPath == null, options);\n\tlet committed = false;\n\ttry {\n\t\tconst outcome = readCodememConfigFileForMutation(targetMutationPath);\n\t\tassertTargetDidNotDisappear(preliminaryTarget, outcome, targetPath);\n\t\tconst readPath = fallbackMutationPath ?? fallbackReadPath;\n\t\tconst inputOutcome = mutationInputOutcome(outcome, targetMutationPath, readPath);\n\t\tconst { expectedRevision, expectedIdentity } = expectedConfigState(\n\t\t\toutcome,\n\t\t\ttargetPath,\n\t\t\toptions.expectedRevision,\n\t\t);\n\t\tconst current = { ...assertMutationInput(inputOutcome) };\n\t\tconst data = mutator(current, outcome);\n\t\tif (data === undefined) {\n\t\t\treturn {\n\t\t\t\tpath: targetPath,\n\t\t\t\tmutationPath: targetMutationPath,\n\t\t\t\tdata: current,\n\t\t\t\trevision: expectedRevision,\n\t\t\t};\n\t\t}\n\t\tconst inputRevision =\n\t\t\tinputOutcome.status === \"valid\" ? inputOutcome.revision : inputOutcome.status;\n\t\tconst text = `${JSON.stringify(data, null, 2)}\\n`;\n\t\tcommitConfigMutation({\n\t\t\ttargetPath,\n\t\t\ttargetMutationPath,\n\t\t\ttext,\n\t\t\tmetadata: configMetadata(outcome),\n\t\t\texpectedRevision,\n\t\t\texpectedMetadata: configMetadata(outcome),\n\t\t\texpectedIdentity,\n\t\t\tfallbackReadPath,\n\t\t\tfallbackMutationPath,\n\t\t\tinputOutcome,\n\t\t\tinputRevision,\n\t\t});\n\t\tcommitted = true;\n\t\treturn {\n\t\t\tpath: targetPath,\n\t\t\tmutationPath: targetMutationPath,\n\t\t\tdata,\n\t\t\trevision: configRevision(text),\n\t\t};\n\t} finally {\n\t\treleaseConfigLocksAfterMutation(\n\t\t\tlocks,\n\t\t\tcommitted,\n\t\t\toptions.lockCleanupOperations ?? configLockCleanupOperations,\n\t\t);\n\t}\n}\n\n/** Delete a config only when it still has the expected revision. */\nexport function deleteCodememConfigFile(\n\tconfigPath: string,\n\texpectedRevision: string,\n\texpectedMutationPath?: string,\n\tlockCleanupOperations: ConfigLockCleanupOperations = configLockCleanupOperations,\n): void {\n\tconst targetPath = expandUserPath(configPath);\n\tconst replacementPath = expectedMutationPath ?? resolveConfigMutationTarget(targetPath);\n\tconst lock = acquireConfigLock(replacementPath);\n\tlet committed = false;\n\ttry {\n\t\tif (\n\t\t\tresolveConfigMutationTarget(targetPath) !== replacementPath ||\n\t\t\tcurrentRevision(replacementPath) !== expectedRevision\n\t\t) {\n\t\t\tthrow new CodememConfigMutationError(\n\t\t\t\t\"changed\",\n\t\t\t\t`Cannot restore config because ${targetPath} changed after the save.`,\n\t\t\t);\n\t\t}\n\t\tunlinkSync(replacementPath);\n\t\tcommitted = true;\n\t\tsyncConfigDirectory(replacementPath, atomicConfigFileOperations);\n\t} finally {\n\t\treleaseConfigLocksAfterMutation([lock], committed, lockCleanupOperations);\n\t}\n}\n\n/** Persist the codemem config file as normalized JSON using atomic replacement. */\nexport function writeCodememConfigFile(data: Record<string, unknown>, configPath?: string): string {\n\treturn mutateCodememConfigFile(() => data, configPath).path;\n}\n\nexport function writeWorkspaceCodememConfigFile(\n\tworkspaceId: string,\n\tdata: Record<string, unknown>,\n): string {\n\treturn writeCodememConfigFile(data, getWorkspaceCodememConfigPath(workspaceId));\n}\n\n// Match loadObserverConfig's nullish string precedence, including empty strings.\nconst OBSERVER_STRING_ENV_KEYS = new Set([\n\t\"observer_provider\",\n\t\"observer_model\",\n\t\"observer_runtime\",\n\t\"observer_base_url\",\n\t\"observer_simple_provider\",\n\t\"observer_simple_model\",\n\t\"observer_rich_provider\",\n\t\"observer_rich_model\",\n\t\"observer_reasoning_effort\",\n\t\"observer_reasoning_summary\",\n\t\"observer_rich_reasoning_effort\",\n\t\"observer_rich_reasoning_summary\",\n\t\"observer_auth_source\",\n\t\"observer_auth_file\",\n]);\n\nfunction parseObserverJsonEnv(key: string, value: string): unknown {\n\tconst isCommand = key === \"observer_auth_command\";\n\tif (!value.trim()) return isCommand ? [] : {};\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (isCommand) {\n\t\t\tif (Array.isArray(parsed) && parsed.every((item) => typeof item === \"string\")) return parsed;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed;\n\t} catch {\n\t\t// Invalid values retain the saved configuration, so do not claim env control.\n\t}\n\treturn undefined;\n}\n\nfunction parseConfigEnvOverride(key: string, value: string): unknown {\n\tif (OBSERVER_STRING_ENV_KEYS.has(key)) return value;\n\tswitch (key) {\n\t\tcase \"observer_temperature\":\n\t\tcase \"observer_simple_temperature\":\n\t\tcase \"observer_rich_temperature\":\n\t\tcase \"observer_rich_max_output_tokens\":\n\t\tcase \"observer_max_output_tokens\": {\n\t\t\tconst number = Number(value);\n\t\t\treturn Number.isFinite(number) ? number : undefined;\n\t\t}\n\t\tcase \"observer_max_chars\":\n\t\tcase \"observer_max_tokens\":\n\t\tcase \"observer_auth_timeout_ms\":\n\t\tcase \"observer_auth_cache_ttl_s\": {\n\t\t\tconst number = Number.parseInt(value, 10);\n\t\t\treturn Number.isFinite(number) ? number : undefined;\n\t\t}\n\t\tcase \"observer_tier_routing_enabled\":\n\t\tcase \"observer_openai_use_responses\":\n\t\t\treturn value === \"1\" || value === \"true\";\n\t\tcase \"observer_output_mode\":\n\t\t\treturn [\"auto\", \"json_schema\", \"legacy_xml\"].includes(value) ? value : undefined;\n\t\tcase \"claude_command\":\n\t\tcase \"codex_command\":\n\t\t\treturn coerceObserverCommand(value) ?? undefined;\n\t\tcase \"observer_headers\":\n\t\tcase \"observer_auth_command\":\n\t\t\treturn parseObserverJsonEnv(key, value);\n\t\tdefault:\n\t\t\treturn value === \"\" ? undefined : value;\n\t}\n}\n\n/** Parsed active overrides; omitted entries fall back to saved configuration. */\nexport function getCodememEnvOverrideValues(): Record<string, unknown> {\n\tconst values: Record<string, unknown> = {};\n\tfor (const [key, envVar] of Object.entries(CODEMEM_CONFIG_ENV_OVERRIDES)) {\n\t\tconst raw = process.env[envVar];\n\t\tif (raw === undefined) continue;\n\t\tconst value = parseConfigEnvOverride(key, raw);\n\t\tif (value !== undefined) values[key] = value;\n\t}\n\treturn values;\n}\n\n/** Return env vars that actually override saved codemem config values. */\nexport function getCodememEnvOverrides(): Record<string, string> {\n\tconst overrides: Record<string, string> = {};\n\tfor (const key of Object.keys(getCodememEnvOverrideValues())) {\n\t\tconst envVar = CODEMEM_CONFIG_ENV_OVERRIDES[key];\n\t\tif (envVar) overrides[key] = envVar;\n\t}\n\treturn overrides;\n}\n\n// ---------------------------------------------------------------------------\n// Provider helpers\n// ---------------------------------------------------------------------------\n\ntype AnyRecord = Record<string, unknown>;\n\nfunction asRecord(value: unknown): AnyRecord | null {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as AnyRecord)\n\t\t: null;\n}\n\n/** Get provider-specific config block from the opencode config. */\nexport function getOpenCodeProviderConfig(provider: string): AnyRecord {\n\tconst config = loadOpenCodeConfig();\n\tconst providerConfig = asRecord(config.provider);\n\tif (!providerConfig) return {};\n\tconst data = asRecord(providerConfig[provider]);\n\treturn data ?? {};\n}\n\n/** True when the opencode config has a provider block for this provider name. */\nexport function hasOpenCodeProviderConfig(provider: string): boolean {\n\treturn Object.keys(getOpenCodeProviderConfig(provider)).length > 0;\n}\n\n/** List all custom provider keys from the opencode config. */\nexport function listCustomProviders(): Set<string> {\n\tconst config = loadOpenCodeConfig();\n\tconst providerConfig = asRecord(config.provider);\n\tif (!providerConfig) return new Set();\n\treturn new Set(Object.keys(providerConfig));\n}\n\nconst BUILTIN_MODEL_PREFIX_PROVIDERS = new Set([\"openai\", \"anthropic\", \"opencode\"]);\n\nfunction extractProviderPrefix(value: unknown): string | null {\n\tif (typeof value !== \"string\" || !value.includes(\"/\")) return null;\n\tconst prefix = value.split(\"/\")[0]?.trim().toLowerCase();\n\treturn prefix ? prefix : null;\n}\n\nexport function listConfiguredOpenCodeProviders(): Set<string> {\n\tconst providers = listCustomProviders();\n\tconst config = loadOpenCodeConfig();\n\tfor (const key of [\"model\", \"small_model\"]) {\n\t\tconst prefix = extractProviderPrefix(config[key]);\n\t\tif (prefix) providers.add(prefix);\n\t}\n\treturn providers;\n}\n\nexport function listObserverProviderOptions(): string[] {\n\tconst providers = listConfiguredOpenCodeProviders();\n\tfor (const provider of BUILTIN_MODEL_PREFIX_PROVIDERS) providers.add(provider);\n\treturn Array.from(providers).sort((a, b) => a.localeCompare(b));\n}\n\nexport function resolveBuiltInProviderFromModel(model: string): string | null {\n\tconst prefix = extractProviderPrefix(model);\n\treturn prefix && BUILTIN_MODEL_PREFIX_PROVIDERS.has(prefix) ? prefix : null;\n}\n\nexport function resolveBuiltInProviderDefaultModel(provider: string): string | null {\n\tif (provider === \"openai\") return \"gpt-6-luna\";\n\tif (provider === \"anthropic\") return \"claude-haiku-4-5\";\n\tif (provider === \"opencode\") return \"opencode/gpt-6-luna\";\n\treturn null;\n}\n\nexport function resolveBuiltInProviderModel(\n\tprovider: string,\n\tmodelName: string,\n): [baseUrl: string | null, modelId: string | null, headers: Record<string, string>] {\n\tif (provider !== \"opencode\") {\n\t\treturn [null, modelName || resolveBuiltInProviderDefaultModel(provider), {}];\n\t}\n\tconst name = modelName || resolveBuiltInProviderDefaultModel(provider) || \"\";\n\tconst prefix = `${provider}/`;\n\tconst shortName = name.toLowerCase().startsWith(prefix) ? name.slice(prefix.length) : name;\n\treturn [\"https://opencode.ai/zen/v1\", shortName || null, {}];\n}\n\n/** Extract provider prefix from a model string like `\"myprovider/model-name\"`. */\nexport function resolveCustomProviderFromModel(\n\tmodel: string,\n\tproviders: Set<string>,\n): string | null {\n\tif (!model?.includes(\"/\")) return null;\n\tconst prefix = model.split(\"/\")[0] ?? \"\";\n\tif (!prefix) return null;\n\tif (providers.has(prefix)) return prefix;\n\tconst normalizedPrefix = prefix.toLowerCase();\n\treturn [...providers].find((provider) => provider.toLowerCase() === normalizedPrefix) ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Placeholder resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Expand `$ENV_VAR` / `${ENV_VAR}` references and `{file:/path}` placeholders.\n *\n * Environment variable expansion mirrors Python's `os.path.expandvars`.\n * File placeholders read the file content and substitute it inline.\n */\nexport function resolvePlaceholder(value: string): string {\n\tconst expanded = expandEnvVars(value);\n\treturn resolveFilePlaceholder(expanded);\n}\n\n/** Expand `$VAR` and `${VAR}` environment variable references. */\nfunction expandEnvVars(value: string): string {\n\tlet result = \"\";\n\tfor (let i = 0; i < value.length; i++) {\n\t\tif (value[i] !== \"$\" || i === value.length - 1) {\n\t\t\tresult += value[i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (value[i + 1] === \"{\") {\n\t\t\tconst end = value.indexOf(\"}\", i + 2);\n\t\t\tif (end > i + 2) {\n\t\t\t\tconst name = value.slice(i + 2, end);\n\t\t\t\tresult += process.env[name] ?? value.slice(i, end + 1);\n\t\t\t\ti = end;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tconst start = i + 1;\n\t\tlet end = start;\n\t\twhile (end < value.length) {\n\t\t\tconst code = value.charCodeAt(end);\n\t\t\tconst isLetter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\t\t\tconst isDigit = code >= 48 && code <= 57;\n\t\t\tif (!isLetter && !isDigit && code !== 95) break;\n\t\t\tend++;\n\t\t}\n\t\tconst name = value.slice(start, end);\n\t\tif (!name || !Number.isNaN(Number(name[0]))) {\n\t\t\tresult += \"$\";\n\t\t\tcontinue;\n\t\t}\n\t\tresult += process.env[name] ?? value.slice(i, end);\n\t\ti = end - 1;\n\t}\n\treturn result;\n}\n\n/** Expand `{file:path}` placeholders by reading the referenced file. */\nfunction resolveFilePlaceholder(value: string): string {\n\tif (!value.includes(\"{file:\")) return value;\n\tlet result = \"\";\n\tlet index = 0;\n\twhile (index < value.length) {\n\t\tconst start = value.indexOf(\"{file:\", index);\n\t\tif (start < 0) {\n\t\t\tresult += value.slice(index);\n\t\t\tbreak;\n\t\t}\n\t\tconst end = value.indexOf(\"}\", start + 6);\n\t\tif (end < 0) {\n\t\t\tresult += value.slice(index);\n\t\t\tbreak;\n\t\t}\n\t\tresult += value.slice(index, start);\n\t\tconst match = value.slice(start, end + 1);\n\t\tconst rawPath = value.slice(start + 6, end);\n\t\tconst trimmed = rawPath.trim();\n\t\tif (!trimmed) {\n\t\t\tresult += match;\n\t\t\tindex = end + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst expanded = expandEnvVars(trimmed);\n\t\tconst resolved = expanded.startsWith(\"~\")\n\t\t\t? `${codememHomeDir()}${expanded.slice(1)}`\n\t\t\t: expanded;\n\t\ttry {\n\t\t\tresult += readFileSync(resolved, \"utf-8\").trim();\n\t\t} catch {\n\t\t\tresult += match;\n\t\t}\n\t\tindex = end + 1;\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// Provider option extraction\n// ---------------------------------------------------------------------------\n\n/** Extract the `options` sub-object from a provider config block. */\nexport function getProviderOptions(providerConfig: AnyRecord): AnyRecord {\n\tconst options = asRecord(providerConfig.options);\n\treturn options ?? {};\n}\n\n/** Extract `baseURL` / `baseUrl` / `base_url` from provider config. */\nexport function getProviderBaseUrl(providerConfig: AnyRecord): string | null {\n\tconst options = getProviderOptions(providerConfig);\n\t// Use || (not ??) so empty strings fall through to the next candidate (matches Python's `or`)\n\tconst baseUrl = options.baseURL || options.baseUrl || options.base_url || providerConfig.base_url;\n\treturn typeof baseUrl === \"string\" && baseUrl ? baseUrl : null;\n}\n\n/** Extract and resolve headers (with placeholder expansion) from provider config. */\nexport function getProviderHeaders(providerConfig: AnyRecord): Record<string, string> {\n\tconst options = getProviderOptions(providerConfig);\n\tconst headers = asRecord(options.headers);\n\tif (!headers) return {};\n\tconst parsed: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (typeof key !== \"string\" || typeof value !== \"string\") continue;\n\t\tparsed[key] = resolvePlaceholder(value);\n\t}\n\treturn parsed;\n}\n\n/** Extract API key from provider config (direct value or env-var reference). */\nexport function getProviderApiKey(providerConfig: AnyRecord): string | null {\n\tconst options = getProviderOptions(providerConfig);\n\t// Use || (not ??) so empty strings fall through (matches Python's `or`)\n\tconst apiKey = options.apiKey || providerConfig.apiKey;\n\tif (typeof apiKey === \"string\" && apiKey) {\n\t\treturn resolvePlaceholder(apiKey);\n\t}\n\tconst apiKeyEnv = (options.apiKeyEnv ?? options.api_key_env) as string | undefined;\n\tif (typeof apiKeyEnv === \"string\" && apiKeyEnv) {\n\t\tconst value = process.env[apiKeyEnv];\n\t\tif (value) return value;\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Custom provider model resolution\n// ---------------------------------------------------------------------------\n\n/** Find the default model for a custom provider. */\nexport function resolveCustomProviderDefaultModel(provider: string): string | null {\n\tconst providerConfig = getOpenCodeProviderConfig(provider);\n\tconst options = getProviderOptions(providerConfig);\n\tconst defaultModel =\n\t\toptions.defaultModel ??\n\t\toptions.default_model ??\n\t\tproviderConfig.defaultModel ??\n\t\tproviderConfig.default_model;\n\tif (typeof defaultModel === \"string\" && defaultModel) {\n\t\treturn defaultModel.startsWith(`${provider}/`) ? defaultModel : `${provider}/${defaultModel}`;\n\t}\n\tconst models = asRecord(providerConfig.models);\n\tif (models) {\n\t\tconst firstKey = Object.keys(models)[0];\n\t\tif (typeof firstKey === \"string\" && firstKey) {\n\t\t\treturn `${provider}/${firstKey}`;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Resolve base_url, model_id, and headers for a custom provider model.\n *\n * Returns `[baseUrl, modelId, headers]`.\n */\nexport function resolveCustomProviderModel(\n\tprovider: string,\n\tmodelName: string,\n): [baseUrl: string | null, modelId: string | null, headers: Record<string, string>] {\n\tconst providerConfig = getOpenCodeProviderConfig(provider);\n\tconst baseUrl = getProviderBaseUrl(providerConfig);\n\tconst headers = getProviderHeaders(providerConfig);\n\n\tlet name = modelName;\n\tif (!name) {\n\t\tname = resolveCustomProviderDefaultModel(provider) ?? \"\";\n\t}\n\n\tconst prefix = `${provider}/`;\n\tconst shortName = name.toLowerCase().startsWith(prefix.toLowerCase())\n\t\t? name.slice(prefix.length)\n\t\t: name;\n\n\tconst models = asRecord(providerConfig.models);\n\tlet modelId: string | null = shortName;\n\tif (models) {\n\t\tconst modelConfig = asRecord(models[shortName]);\n\t\tif (modelConfig && typeof modelConfig.id === \"string\") {\n\t\t\tmodelId = modelConfig.id;\n\t\t}\n\t}\n\n\tif (typeof modelId !== \"string\" || !modelId) {\n\t\tmodelId = null;\n\t}\n\n\treturn [baseUrl, modelId, headers];\n}\n","import type { Database } from \"better-sqlite3\";\nimport * as sqliteVec from \"sqlite-vec\";\n\n/** Current schema version this TS runtime was built against. */\nexport const SCHEMA_VERSION = 21;\n\nexport const REQUIRED_TABLES = [\n\t\"memory_items\",\n\t\"sessions\",\n\t\"artifacts\",\n\t\"raw_events\",\n\t\"raw_event_sessions\",\n\t\"usage_events\",\n] as const;\n\nexport const REQUIRED_BOOTSTRAPPED_TABLES = [\n\t...REQUIRED_TABLES,\n\t\"memory_fts\",\n\t\"coordinator_enrollment_reconciliation_issues\",\n\t// The legacy_team_setup_* tables are deliberately NOT listed: they are\n\t// created additively by `ensureLegacyTeamSetupDraftSchema` on every\n\t// connection path. Listing them would make a valid older bootstrapped\n\t// schema look partial and skip WAL/pragma connection setup for the first\n\t// post-upgrade connection.\n] as const;\n\n/** Check if embeddings are disabled via environment variable. */\nexport function isEmbeddingDisabled(): boolean {\n\tconst val = process.env.CODEMEM_EMBEDDING_DISABLED?.toLowerCase();\n\treturn val === \"1\" || val === \"true\" || val === \"yes\";\n}\n\n/** Load sqlite-vec and verify that the extension is callable. */\nexport function loadSqliteVec(db: Database): void {\n\tif (isEmbeddingDisabled()) return;\n\tsqliteVec.load(db);\n\tconst row = db.prepare(\"SELECT vec_version() AS v\").get() as { v: string } | undefined;\n\tif (!row?.v) throw new Error(\"sqlite-vec loaded but version check failed\");\n}\n\n/** Read the schema `user_version` pragma, returning zero for an empty database. */\nexport function getSchemaVersion(db: Database): number {\n\tconst row = db.pragma(\"user_version\", { simple: true });\n\treturn typeof row === \"number\" ? row : 0;\n}\n\nconst IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS: ReadonlyArray<{ name: string; create: string }> = [\n\t{\n\t\tname: \"trg_identity_devices_assignment_version\",\n\t\tcreate: `CREATE TRIGGER trg_identity_devices_assignment_version\n\tAFTER UPDATE OF identity_id ON identity_devices\n\tWHEN NEW.identity_id <> OLD.identity_id\n\tBEGIN\n\t\tUPDATE identity_devices\n\t\tSET assignment_version = OLD.assignment_version + 1\n\t\tWHERE device_id = NEW.device_id;\n\tEND`,\n\t},\n\t{\n\t\tname: \"trg_identity_devices_purge_decisions\",\n\t\tcreate: `CREATE TRIGGER trg_identity_devices_purge_decisions\n\tAFTER DELETE ON identity_devices\n\tBEGIN\n\t\tDELETE FROM policy_team_device_decisions WHERE device_id = OLD.device_id;\n\tEND`,\n\t},\n];\n\nexport const IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL = IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS.map(\n\t({ name, create }) => `DROP TRIGGER IF EXISTS ${name};\\n${create};`,\n).join(\"\\n\");\n\nfunction normalizedSql(sql: string): string {\n\treturn sql.replace(/\\s+/g, \" \").trim();\n}\n\n/** True when both security triggers exist with exactly the expected definitions. */\nexport function identityDeviceAssignmentTriggersCurrent(db: Database): boolean {\n\tconst lookup = db.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?\");\n\treturn IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS.every(({ name, create }) => {\n\t\tconst row = lookup.get(name) as { sql?: string | null } | undefined;\n\t\treturn typeof row?.sql === \"string\" && normalizedSql(row.sql) === normalizedSql(create);\n\t});\n}\n","import type { Database } from \"./db.js\";\n\nexport function ensureMemoryRetirementDeliverySchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_retirement_deliveries (\n\t\tcontrol_id TEXT NOT NULL,\n\t\tpeer_device_id TEXT NOT NULL,\n\t\tentity_id TEXT NOT NULL,\n\t\tsource_device_id TEXT NOT NULL,\n\t\tretired_scope_id TEXT NOT NULL,\n\t\tacknowledged_at TEXT,\n\t\tPRIMARY KEY (control_id, peer_device_id)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_memory_retirement_deliveries_pending\n\t\tON memory_retirement_deliveries(peer_device_id, source_device_id, acknowledged_at, control_id);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_peer_trust (\n\t\tlocal_device_id TEXT NOT NULL,\n\t\tpeer_device_id TEXT NOT NULL,\n\t\tpublic_key TEXT NOT NULL,\n\t\tpinned_fingerprint TEXT NOT NULL,\n\t\tPRIMARY KEY (local_device_id, peer_device_id)\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_receipts (\n\t\tcontrol_id TEXT PRIMARY KEY,\n\t\tsource_device_id TEXT NOT NULL,\n\t\treceived_at TEXT NOT NULL\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_reset_receivers (\n\t\treset_id TEXT PRIMARY KEY, source_device_id TEXT NOT NULL, source_public_key TEXT NOT NULL,\n\t\tlocal_device_id TEXT NOT NULL, boundary TEXT NOT NULL, next_offset INTEGER NOT NULL DEFAULT 0,\n\t\tcomplete INTEGER NOT NULL DEFAULT 0, last_page_digest TEXT\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_reset_manifests (\n\t\treset_id TEXT NOT NULL, peer_device_id TEXT NOT NULL, source_device_id TEXT NOT NULL,\n\t\tboundary TEXT NOT NULL, controls_json TEXT NOT NULL,\n\t\tPRIMARY KEY(reset_id, peer_device_id, source_device_id)\n\t);`);\n}\n","import type { Database } from \"./db.js\";\nimport {\n\tassertVerifiedMemorySource,\n\tverifyAuthenticatedMemorySource,\n} from \"./memory-source-identity.js\";\n\n/** Internal prerequisite; no wire capability or production retirement caller is enabled. */\nexport function ensureMemoryScopeRetirementSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_scope_retirements (\n\t\tentity_id TEXT NOT NULL,\n\t\tsource_device_id TEXT NOT NULL,\n\t\tretired_scope_id TEXT NOT NULL,\n\t\tretired_at TEXT NOT NULL,\n\t\tPRIMARY KEY (entity_id, retired_scope_id)\n\t);\n\tCREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_update\n\tBEFORE UPDATE ON memory_scope_retirements\n\tBEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_delete\n\tBEFORE DELETE ON memory_scope_retirements\n\tBEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_replace\n\tBEFORE INSERT ON memory_scope_retirements\n\tWHEN EXISTS (SELECT 1 FROM memory_scope_retirements WHERE entity_id = NEW.entity_id AND retired_scope_id = NEW.retired_scope_id)\n\tBEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;`);\n}\n\n/** Payload-free control: no destination, recipients, memory content, or clock. */\nexport interface MemoryScopeRetirement {\n\tentityId: string;\n\tsourceDeviceId: string;\n\tretiredScopeId: string;\n}\n\nfunction validateRetirement(input: MemoryScopeRetirement): void {\n\tfor (const value of [input.entityId, input.sourceDeviceId, input.retiredScopeId]) {\n\t\tif (\n\t\t\ttypeof value !== \"string\" ||\n\t\t\t!value ||\n\t\t\tvalue.length > 1500 ||\n\t\t\tvalue !== value.trim() ||\n\t\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t\t)\n\t\t\tthrow new Error(\"memory_retirement_invalid\");\n\t}\n}\n\n/** No foreign keys: row erasure, scope cleanup and log compaction must retain this fence. */\nexport function isMemoryScopeRetired(\n\tdb: Database,\n\tentityId: string,\n\tscopeId: string | null,\n): boolean {\n\tif (!scopeId) return false;\n\treturn Boolean(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM memory_scope_retirements WHERE entity_id = ? AND retired_scope_id = ?\",\n\t\t\t)\n\t\t\t.get(entityId, scopeId),\n\t);\n}\n\nexport function assertMemoryScopeNotRetired(db: Database, entityId: string, scopeId: string): void {\n\tif (isMemoryScopeRetired(db, entityId, scopeId)) throw new Error(\"memory_scope_retired\");\n}\n\nexport function hasMemoryScopeRetirement(db: Database, entityId: string): boolean {\n\treturn Boolean(\n\t\tdb.prepare(\"SELECT 1 FROM memory_scope_retirements WHERE entity_id = ? LIMIT 1\").get(entityId),\n\t);\n}\n\n/**\n * Caller MUST supply a successfully authenticated transport device identity (or the\n * actual local device for a local move), never an op sender, payload origin or form field.\n * The caller transaction must also perform the move/cleanup; this primitive only fences.\n * An absent qualified identity is verifiable by its namespace owner. A legacy UUID is not.\n */\nexport function recordMemoryScopeRetirement(\n\tdb: Database,\n\tinput: MemoryScopeRetirement,\n\toptions: { authenticatedSourceDeviceId: string; now: string },\n): void {\n\tvalidateRetirement(input);\n\tif (options.authenticatedSourceDeviceId !== input.sourceDeviceId)\n\t\tthrow new Error(\"memory_retirement_sender_mismatch\");\n\tif (!db.inTransaction) throw new Error(\"memory_retirement_transaction_required\");\n\tverifyAuthenticatedMemorySource(db, {\n\t\tentityId: input.entityId,\n\t\tverifiedPeerDeviceId: options.authenticatedSourceDeviceId,\n\t});\n\tassertVerifiedMemorySource(db, input.entityId, input.sourceDeviceId);\n\tif (isMemoryScopeRetired(db, input.entityId, input.retiredScopeId)) return;\n\tdb.prepare(`INSERT INTO memory_scope_retirements(entity_id, source_device_id, retired_scope_id, retired_at)\n\t\tVALUES (?, ?, ?, ?)`).run(\n\t\tinput.entityId,\n\t\tinput.sourceDeviceId,\n\t\tinput.retiredScopeId,\n\t\toptions.now,\n\t);\n}\n","import type { Database } from \"./db.js\";\nimport { ensureMemoryRetirementDeliverySchema } from \"./memory-retirement-delivery-schema.js\";\nimport { ensureMemoryScopeRetirementSchema } from \"./memory-scope-retirement.js\";\nimport { ensureMemorySourceIdentitySchema } from \"./memory-source-identity.js\";\n\nexport function ensureMemoryOwnershipSchemas(db: Database): void {\n\tensureMemorySourceIdentitySchema(db);\n\tensureMemoryScopeRetirementSchema(db);\n\tensureMemoryRetirementDeliverySchema(db);\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_ownership_recoveries (\n\t\toperation_id TEXT PRIMARY KEY,\n\t\tactor_id TEXT NOT NULL,\n\t\tdevice_id TEXT NOT NULL,\n\t\trequest_json TEXT NOT NULL,\n\t\treviewed_digest TEXT NOT NULL,\n\t\tresult_json TEXT NOT NULL,\n\t\tcreated_at TEXT NOT NULL\n\t);`);\n}\n","import type { Database } from \"./db.js\";\n\nexport interface RepositoryWorkspaceEvidence {\n\tcwd: string;\n\trecordedIdentitiesJson: string;\n\tfilesystemIdentity: string | null;\n\tfilesystemAnchor: string | null;\n\tanchorMtimeNs: string | null;\n\tcheckedAtMs: number;\n}\n\ninterface RepositoryDiscoveryState {\n\tsource_revision: number;\n\tindexed_revision: number;\n}\n\nfunction discoveryTriggerCount(db: Database): number {\n\treturn db\n\t\t.prepare(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND name IN (\n\t\t\t'trg_repository_discovery_session_insert',\n\t\t\t'trg_repository_discovery_session_update',\n\t\t\t'trg_repository_discovery_session_delete'\n\t\t)`)\n\t\t.pluck()\n\t\t.get() as number;\n}\n\nexport function ensureRepositoryDiscoveryIndex(db: Database): void {\n\tdb.exec(\"SAVEPOINT repository_discovery_repair\");\n\ttry {\n\t\trepairRepositoryDiscoveryIndex(db);\n\t\tdb.exec(\"RELEASE repository_discovery_repair\");\n\t} catch (error) {\n\t\tdb.exec(\"ROLLBACK TO repository_discovery_repair; RELEASE repository_discovery_repair\");\n\t\tthrow error;\n\t}\n}\n\nfunction repairRepositoryDiscoveryIndex(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS repository_discovery_state (\n\t\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\t\tsource_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\tindexed_revision INTEGER NOT NULL DEFAULT -1\n\t\t);\n\t\tINSERT OR IGNORE INTO repository_discovery_state(id) VALUES (1);\n\t`);\n\t// Acquire the write lock before checking for missing schema, so no session\n\t// mutation can slip between invalidation and trigger recreation.\n\tdb.prepare(\n\t\t\"UPDATE repository_discovery_state SET indexed_revision = indexed_revision WHERE id = 1\",\n\t).run();\n\tconst evidenceTableExists = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'repository_workspace_evidence'\",\n\t\t)\n\t\t.get();\n\tif (discoveryTriggerCount(db) !== 3 || !evidenceTableExists) {\n\t\t// Missing triggers may have missed writes, and a missing evidence table has\n\t\t// lost its rows. Invalidate in-memory and on-disk snapshots before repair.\n\t\tdb.prepare(`UPDATE repository_discovery_state\n\t\t\t\tSET source_revision = source_revision + 1, indexed_revision = -1 WHERE id = 1`).run();\n\t}\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS repository_workspace_evidence (\n\t\t\tcwd TEXT PRIMARY KEY,\n\t\t\trecorded_identities_json TEXT NOT NULL,\n\t\t\tfilesystem_identity TEXT,\n\t\t\tfilesystem_anchor TEXT,\n\t\t\tanchor_mtime_ns TEXT,\n\t\t\tchecked_at_ms INTEGER NOT NULL\n\t\t);\n\t\tCREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_insert\n\t\tAFTER INSERT ON sessions BEGIN\n\t\t\tUPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n\t\tEND;\n\t\tCREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_update\n\t\tAFTER UPDATE OF cwd, git_remote, metadata_json ON sessions BEGIN\n\t\t\tUPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n\t\tEND;\n\t\tCREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_delete\n\t\tAFTER DELETE ON sessions BEGIN\n\t\t\tUPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n\t\tEND;\n\t`);\n}\n\nexport function repositoryDiscoveryRevision(db: Database): number | null {\n\ttry {\n\t\tif (discoveryTriggerCount(db) !== 3) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT source_revision FROM repository_discovery_state WHERE id = 1\")\n\t\t\t.get() as { source_revision: number } | undefined;\n\t\treturn row?.source_revision ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function loadRepositoryDiscoveryEvidence(\n\tdb: Database,\n): RepositoryWorkspaceEvidence[] | null {\n\ttry {\n\t\treturn db.transaction(() => {\n\t\t\tconst state = db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT source_revision, indexed_revision FROM repository_discovery_state WHERE id = 1\",\n\t\t\t\t)\n\t\t\t\t.get() as RepositoryDiscoveryState | undefined;\n\t\t\tif (!state || state.source_revision !== state.indexed_revision) return null;\n\t\t\treturn db\n\t\t\t\t.prepare(`SELECT cwd, recorded_identities_json AS recordedIdentitiesJson,\n\t\t\t\tfilesystem_identity AS filesystemIdentity, filesystem_anchor AS filesystemAnchor,\n\t\t\t\tanchor_mtime_ns AS anchorMtimeNs, checked_at_ms AS checkedAtMs\n\t\t\t\tFROM repository_workspace_evidence ORDER BY cwd`)\n\t\t\t\t.all() as RepositoryWorkspaceEvidence[];\n\t\t})();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function replaceRepositoryDiscoveryEvidence(\n\tdb: Database,\n\texpectedRevision: number,\n\trows: RepositoryWorkspaceEvidence[],\n): boolean {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (repositoryDiscoveryRevision(db) !== expectedRevision) return false;\n\t\t\tdb.prepare(\"DELETE FROM repository_workspace_evidence\").run();\n\t\t\tconst insert = db.prepare(`INSERT INTO repository_workspace_evidence(\n\t\t\tcwd, recorded_identities_json, filesystem_identity, filesystem_anchor,\n\t\t\tanchor_mtime_ns, checked_at_ms\n\t\t) VALUES (?, ?, ?, ?, ?, ?)`);\n\t\t\tfor (const row of rows) {\n\t\t\t\tinsert.run(\n\t\t\t\t\trow.cwd,\n\t\t\t\t\trow.recordedIdentitiesJson,\n\t\t\t\t\trow.filesystemIdentity,\n\t\t\t\t\trow.filesystemAnchor,\n\t\t\t\t\trow.anchorMtimeNs,\n\t\t\t\t\trow.checkedAtMs,\n\t\t\t\t);\n\t\t\t}\n\t\t\tdb.prepare(\"UPDATE repository_discovery_state SET indexed_revision = ? WHERE id = 1\").run(\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\treturn true;\n\t\t})\n\t\t.immediate();\n}\n","import type { MemoryResult } from \"./types.js\";\n\ntype SummaryLikeInput = {\n\tkind?: string | null;\n\tmetadata?: unknown;\n};\n\nfunction parseMetadataObject(value: unknown): Record<string, unknown> {\n\tif (!value) return {};\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(value) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\t\treturn parsed as Record<string, unknown>;\n\t\t\t}\n\t\t\treturn {};\n\t\t} catch {\n\t\t\treturn {};\n\t\t}\n\t}\n\tif (typeof value === \"object\" && !Array.isArray(value)) {\n\t\treturn value as Record<string, unknown>;\n\t}\n\treturn {};\n}\n\nexport function getSummaryMetadata(metadata: unknown): Record<string, unknown> {\n\treturn parseMetadataObject(metadata);\n}\n\n/** SQL equivalent of isSummaryLikeMemory for a trusted memory-items table alias. */\nexport function summaryLikeSqlPredicate(\n\talias: \"memory_items\" | \"mi\" | \"\" = \"memory_items\",\n): string {\n\tconst prefix = alias ? `${alias}.` : \"\";\n\tconst kind = `${prefix}kind`;\n\tconst metadata = `${prefix}metadata_json`;\n\treturn `(\n\t\tLOWER(TRIM(COALESCE(${kind}, ''))) = 'session_summary'\n\t\tOR CASE WHEN json_valid(COALESCE(${metadata}, '')) = 1 THEN (\n\t\t\tCOALESCE(json_type(${metadata}, '$.is_summary') = 'true', 0)\n\t\t\tOR LOWER(TRIM(COALESCE(json_extract(${metadata}, '$.source'), ''))) = 'observer_summary'\n\t\t) ELSE 0 END\n\t)`;\n}\n\nexport function isSummaryLikeMemory(input: SummaryLikeInput): boolean {\n\tconst kindValue = String(input.kind ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (kindValue === \"session_summary\") return true;\n\tconst metadata = getSummaryMetadata(input.metadata);\n\tif (metadata.is_summary === true) return true;\n\treturn (\n\t\tString(metadata.source ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase() === \"observer_summary\"\n\t);\n}\n\nexport function summaryContinuityFilter(summarySessionId?: number | null): {\n\tclauses: string[];\n\tparams: number[];\n} {\n\tif (summarySessionId === undefined) return { clauses: [], params: [] };\n\tconst predicate = summaryLikeSqlPredicate();\n\tif (summarySessionId === null) return { clauses: [`NOT ${predicate}`], params: [] };\n\treturn {\n\t\tclauses: [`(NOT ${predicate} OR memory_items.session_id = ?)`],\n\t\tparams: [summarySessionId],\n\t};\n}\n\nexport function isNativeSessionSummaryMemory(input: SummaryLikeInput): boolean {\n\tconst kindValue = String(input.kind ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (kindValue !== \"session_summary\") return false;\n\tconst metadata = getSummaryMetadata(input.metadata);\n\tif (metadata.is_summary === true) return false;\n\treturn (\n\t\tString(metadata.source ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase() !== \"observer_summary\"\n\t);\n}\n\nexport function canonicalMemoryKind(kind: string | null | undefined, metadata?: unknown): string {\n\tconst normalized = String(kind ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (isSummaryLikeMemory({ kind: normalized, metadata })) return \"session_summary\";\n\treturn normalized || \"change\";\n}\n\nexport function canonicalizeMemoryResultKind<T extends Pick<MemoryResult, \"kind\" | \"metadata\">>(\n\titem: T,\n): T {\n\treturn {\n\t\t...item,\n\t\tkind: canonicalMemoryKind(item.kind, item.metadata),\n\t};\n}\n","/**\n * AUTO-GENERATED by scripts/generate-test-schema.ts\n *\n * Do not edit manually. Regenerate with:\n * pnpm --filter @codemem/core run generate:test-schema\n */\n\nexport const TEST_SCHEMA_BASE_DDL =\n\t\"CREATE TABLE IF NOT EXISTS `device_identity_binding_commits` (\\n\\t`commit_digest` text PRIMARY KEY NOT NULL,\\n\\t`reviewed_inventory_digest` text NOT NULL,\\n\\t`request_json` text NOT NULL,\\n\\t`outcomes_json` text NOT NULL,\\n\\t`write_count` integer NOT NULL,\\n\\t`decided_by_identity_id` text NOT NULL,\\n\\t`decided_by_device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `device_identity_binding_audit` (\\n\\t`event_id` text PRIMARY KEY NOT NULL,\\n\\t`commit_digest` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`previous_identity_id` text,\\n\\t`target_identity_id` text NOT NULL,\\n\\t`action` text NOT NULL,\\n\\t`previous_assignment_version` integer,\\n\\t`resulting_assignment_version` integer NOT NULL,\\n\\t`decided_by_identity_id` text NOT NULL,\\n\\t`decided_by_device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\tFOREIGN KEY (`commit_digest`) REFERENCES `device_identity_binding_commits`(`commit_digest`) ON UPDATE no action ON DELETE no action\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_device_identity_binding_audit_commit_device` ON `device_identity_binding_audit` (`commit_digest`,`device_id`);\\nCREATE INDEX IF NOT EXISTS `idx_device_identity_binding_audit_device_created` ON `device_identity_binding_audit` (`device_id`,`created_at`,`event_id`);\\nCREATE TABLE IF NOT EXISTS `sessions` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`started_at` text NOT NULL,\\n\\t`ended_at` text,\\n\\t`cwd` text,\\n\\t`project` text,\\n\\t`git_remote` text,\\n\\t`git_branch` text,\\n\\t`user` text,\\n\\t`tool_version` text,\\n\\t`metadata_json` text,\\n\\t`import_key` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_sessions_started_id` ON `sessions` (`started_at`,`id`);\\nCREATE TABLE IF NOT EXISTS `replication_scopes` (\\n\\t`scope_id` text PRIMARY KEY NOT NULL,\\n\\t`label` text NOT NULL,\\n\\t`kind` text DEFAULT 'user' NOT NULL,\\n\\t`authority_type` text DEFAULT 'local' NOT NULL,\\n\\t`coordinator_id` text,\\n\\t`group_id` text,\\n\\t`manifest_issuer_device_id` text,\\n\\t`membership_epoch` integer DEFAULT 0 NOT NULL,\\n\\t`manifest_hash` text,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_status` ON `replication_scopes` (`status`);\\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_authority_group` ON `replication_scopes` (`coordinator_id`,`group_id`);\\nCREATE TABLE IF NOT EXISTS `project_scope_mappings` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`workspace_identity` text,\\n\\t`project_pattern` text NOT NULL,\\n\\t`scope_id` text NOT NULL,\\n\\t`priority` integer DEFAULT 0 NOT NULL,\\n\\t`source` text DEFAULT 'user' NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_workspace_priority` ON `project_scope_mappings` (`workspace_identity`,`priority`);\\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_pattern_priority` ON `project_scope_mappings` (`project_pattern`,`priority`);\\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_scope` ON `project_scope_mappings` (`scope_id`);\\nCREATE TABLE IF NOT EXISTS `scope_memberships` (\\n\\t`scope_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`role` text DEFAULT 'member' NOT NULL,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`membership_epoch` integer DEFAULT 0 NOT NULL,\\n\\t`coordinator_id` text,\\n\\t`group_id` text,\\n\\t`manifest_issuer_device_id` text,\\n\\t`manifest_hash` text,\\n\\t`signed_manifest_json` text,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`scope_id`, `device_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_device_status` ON `scope_memberships` (`device_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_scope_status` ON `scope_memberships` (`scope_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_authority_group` ON `scope_memberships` (`coordinator_id`,`group_id`);\\nCREATE TABLE IF NOT EXISTS `artifacts` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer NOT NULL,\\n\\t`kind` text NOT NULL,\\n\\t`path` text,\\n\\t`content_text` text,\\n\\t`content_hash` text,\\n\\t`created_at` text NOT NULL,\\n\\t`metadata_json` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_artifacts_session_kind` ON `artifacts` (`session_id`,`kind`);\\nCREATE TABLE IF NOT EXISTS `memory_items` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer NOT NULL,\\n\\t`kind` text NOT NULL,\\n\\t`title` text NOT NULL,\\n\\t`subtitle` text,\\n\\t`body_text` text NOT NULL,\\n\\t`confidence` real DEFAULT 0.5,\\n\\t`tags_text` text DEFAULT '',\\n\\t`active` integer DEFAULT 1,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\t`metadata_json` text,\\n\\t`actor_id` text,\\n\\t`actor_display_name` text,\\n\\t`visibility` text,\\n\\t`workspace_id` text,\\n\\t`workspace_kind` text,\\n\\t`origin_device_id` text,\\n\\t`origin_source` text,\\n\\t`trust_state` text,\\n\\t`facts` text,\\n\\t`narrative` text,\\n\\t`concepts` text,\\n\\t`files_read` text,\\n\\t`files_modified` text,\\n\\t`user_prompt_id` integer,\\n\\t`prompt_number` integer,\\n\\t`deleted_at` text,\\n\\t`rev` integer DEFAULT 0,\\n\\t`dedup_key` text,\\n\\t`import_key` text,\\n\\t`scope_id` text,\\n\\t`project` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_active_created` ON `memory_items` (`active`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_created_id` ON `memory_items` (`created_at`,`id`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_origin_device_active` ON `memory_items` (`origin_device_id`,`active`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_session` ON `memory_items` (`session_id`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_project` ON `memory_items` (`project`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_visibility_created` ON `memory_items` (`scope_id`,`visibility`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_backfill_pending` ON `memory_items` (`id`) WHERE scope_id IS NULL OR scope_id = '';\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_dedup_key_active_created` ON `memory_items` (`dedup_key`,`active`,`created_at`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_memory_items_same_session_dedup_unique` ON `memory_items` (`session_id`,`kind`,`visibility`,`workspace_id`,`dedup_key`) WHERE active = 1 AND dedup_key IS NOT NULL;\\nCREATE TABLE IF NOT EXISTS `memory_file_refs` (\\n\\t`memory_id` integer NOT NULL,\\n\\t`file_path` text NOT NULL,\\n\\t`relation` text NOT NULL,\\n\\tPRIMARY KEY(`memory_id`, `file_path`, `relation`),\\n\\tFOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_memory_file_refs_path` ON `memory_file_refs` (`file_path`);\\nCREATE TABLE IF NOT EXISTS `memory_concept_refs` (\\n\\t`memory_id` integer NOT NULL,\\n\\t`concept` text NOT NULL,\\n\\tPRIMARY KEY(`memory_id`, `concept`),\\n\\tFOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_memory_concept_refs_concept` ON `memory_concept_refs` (`concept`);\\nCREATE TABLE IF NOT EXISTS `usage_events` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer,\\n\\t`event` text NOT NULL,\\n\\t`tokens_read` integer DEFAULT 0,\\n\\t`tokens_written` integer DEFAULT 0,\\n\\t`tokens_saved` integer DEFAULT 0,\\n\\t`created_at` text NOT NULL,\\n\\t`metadata_json` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_usage_events_event_created` ON `usage_events` (`event`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_usage_events_session` ON `usage_events` (`session_id`);\\nCREATE TABLE IF NOT EXISTS `retrieval_attempts` (\\n\\t`attempt_id` text PRIMARY KEY NOT NULL,\\n\\t`contract_version` integer NOT NULL,\\n\\t`surface` text NOT NULL,\\n\\t`trigger` text NOT NULL,\\n\\t`started_at` text NOT NULL,\\n\\t`completed_at` text,\\n\\t`retrieval_status` text NOT NULL,\\n\\t`delivery_status` text NOT NULL,\\n\\t`candidate_count` integer NOT NULL,\\n\\t`selected_count` integer NOT NULL,\\n\\t`persisted_candidate_count` integer NOT NULL,\\n\\t`recorder_version` text NOT NULL,\\n\\t`session_id` integer,\\n\\t`source` text,\\n\\t`stream_id` text,\\n\\t`source_session_id` text,\\n\\t`prompt_number` integer,\\n\\t`request_id` text,\\n\\t`raw_event_start_seq` integer,\\n\\t`raw_event_end_seq` integer,\\n\\t`experiment_id` text,\\n\\t`experiment_cell_id` text,\\n\\t`evaluation_checkout_id` text,\\n\\t`evaluation_fixture_id` text,\\n\\t`evaluation_seed` integer,\\n\\t`latency_ms` integer,\\n\\t`project` text,\\n\\t`scope_id` text,\\n\\t`mode` text,\\n\\t`limit_requested` integer,\\n\\t`token_budget` integer,\\n\\t`output_tokens` integer,\\n\\t`working_set_file_count` integer,\\n\\t`working_set_files_json` text,\\n\\t`query_hash_sha256` text,\\n\\t`query_char_count` integer,\\n\\t`query_token_estimate` integer,\\n\\t`filter_summary_json` text,\\n\\t`failure_code` text,\\n\\t`failure_stage` text,\\n\\t`trace_version` integer,\\n\\t`automatic_recall_json` text,\\n\\t`automatic_recall_key` text,\\n\\t`retention_until` text,\\n\\t`retention_pinned` integer DEFAULT 0 NOT NULL,\\n\\t`retention_finalized_at` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_session_started` ON `retrieval_attempts` (`session_id`,`started_at`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_attempts_automatic_recall_key` ON `retrieval_attempts` (`automatic_recall_key`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_source_stream_started` ON `retrieval_attempts` (`source`,`stream_id`,`started_at`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_retention` ON `retrieval_attempts` (`retention_pinned`,`retention_until`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_started` ON `retrieval_attempts` (`started_at`,`attempt_id`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_surface_started` ON `retrieval_attempts` (`surface`,`started_at`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_attempts_request_identity` ON `retrieval_attempts` (`source`,`surface`,`request_id`) WHERE request_id IS NOT NULL;\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_experiment_cell` ON `retrieval_attempts` (`experiment_id`,`experiment_cell_id`);\\nCREATE TABLE IF NOT EXISTS `retrieval_exposures` (\\n\\t`exposure_id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`attempt_id` text NOT NULL,\\n\\t`memory_id` integer,\\n\\t`memory_import_key` text,\\n\\t`origin_device_id` text,\\n\\t`rank` integer NOT NULL,\\n\\t`disposition` text NOT NULL,\\n\\t`section` text,\\n\\t`handoff_status` text NOT NULL,\\n\\t`memory_rev` integer,\\n\\t`memory_updated_at` text,\\n\\t`memory_scope_id` text,\\n\\t`memory_kind` text,\\n\\t`memory_active` integer,\\n\\t`memory_deleted_at` text,\\n\\t`score_summary_json` text,\\n\\t`reason_codes_json` text,\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `retrieval_attempts`(`attempt_id`) ON UPDATE no action ON DELETE cascade,\\n\\tFOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE set null\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_exposures_attempt_rank` ON `retrieval_exposures` (`attempt_id`,`rank`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_exposures_memory` ON `retrieval_exposures` (`memory_id`);\\nCREATE TABLE IF NOT EXISTS `outcome_evidence` (\\n\\t`evidence_id` text PRIMARY KEY NOT NULL,\\n\\t`contract_version` integer NOT NULL,\\n\\t`dimension` text NOT NULL,\\n\\t`evidence_type` text NOT NULL,\\n\\t`source_class` text NOT NULL,\\n\\t`observed_at` text NOT NULL,\\n\\t`producer` text NOT NULL,\\n\\t`producer_version` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`value_type` text,\\n\\t`value_integer` integer,\\n\\t`value_real` real,\\n\\t`value_unit` text,\\n\\t`session_id` integer,\\n\\t`source` text,\\n\\t`stream_id` text,\\n\\t`source_session_id` text,\\n\\t`prompt_number` integer,\\n\\t`raw_event_start_seq` integer,\\n\\t`raw_event_end_seq` integer,\\n\\t`experiment_id` text,\\n\\t`experiment_cell_id` text,\\n\\t`window_start_at` text,\\n\\t`window_end_at` text,\\n\\t`references_json` text,\\n\\t`retention_until` text,\\n\\t`retention_pinned` integer DEFAULT 0 NOT NULL,\\n\\t`retention_finalized_at` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_observed_id` ON `outcome_evidence` (`observed_at`,`evidence_id`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_session_observed` ON `outcome_evidence` (`session_id`,`observed_at`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_source_stream_observed` ON `outcome_evidence` (`source`,`stream_id`,`observed_at`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_type_observed` ON `outcome_evidence` (`evidence_type`,`observed_at`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_retention` ON `outcome_evidence` (`retention_pinned`,`retention_until`);\\nCREATE TABLE IF NOT EXISTS `attribution_assessments` (\\n\\t`assessment_id` text PRIMARY KEY NOT NULL,\\n\\t`contract_version` integer NOT NULL,\\n\\t`subject_type` text NOT NULL,\\n\\t`attempt_id` text NOT NULL,\\n\\t`exposure_id` integer,\\n\\t`dimension` text NOT NULL,\\n\\t`impact_label` text NOT NULL,\\n\\t`basis` text NOT NULL,\\n\\t`confidence_level` text NOT NULL,\\n\\t`method` text NOT NULL,\\n\\t`method_version` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`claim_type` text DEFAULT 'observational' NOT NULL,\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `retrieval_attempts`(`attempt_id`) ON UPDATE no action ON DELETE cascade,\\n\\tFOREIGN KEY (`exposure_id`) REFERENCES `retrieval_exposures`(`exposure_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_attempt_created` ON `attribution_assessments` (`attempt_id`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_label_created` ON `attribution_assessments` (`impact_label`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_exposure` ON `attribution_assessments` (`exposure_id`);\\nCREATE TABLE IF NOT EXISTS `attribution_assessment_evidence` (\\n\\t`assessment_id` text NOT NULL,\\n\\t`evidence_id` text NOT NULL,\\n\\tPRIMARY KEY(`assessment_id`, `evidence_id`),\\n\\tFOREIGN KEY (`assessment_id`) REFERENCES `attribution_assessments`(`assessment_id`) ON UPDATE no action ON DELETE cascade,\\n\\tFOREIGN KEY (`evidence_id`) REFERENCES `outcome_evidence`(`evidence_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessment_evidence_evidence` ON `attribution_assessment_evidence` (`evidence_id`,`assessment_id`);\\nCREATE TABLE IF NOT EXISTS `raw_events` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`event_id` text,\\n\\t`event_seq` integer NOT NULL,\\n\\t`event_type` text NOT NULL,\\n\\t`ts_wall_ms` integer,\\n\\t`ts_mono_ms` real,\\n\\t`payload_json` text NOT NULL,\\n\\t`capture_context_json` text,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_seq` ON `raw_events` (`source`,`stream_id`,`event_seq`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_event_id` ON `raw_events` (`source`,`stream_id`,`event_id`);\\nCREATE INDEX IF NOT EXISTS `idx_raw_events_session_seq` ON `raw_events` (`opencode_session_id`,`event_seq`);\\nCREATE INDEX IF NOT EXISTS `idx_raw_events_created` ON `raw_events` (`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_raw_events_capture_context` ON `raw_events` (`source`,`stream_id`,`event_seq`) WHERE \\\"raw_events\\\".\\\"capture_context_json\\\" IS NOT NULL;\\nCREATE TABLE IF NOT EXISTS `raw_event_sessions` (\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`cwd` text,\\n\\t`project` text,\\n\\t`started_at` text,\\n\\t`last_seen_ts_wall_ms` integer,\\n\\t`last_received_event_seq` integer DEFAULT -1 NOT NULL,\\n\\t`last_flushed_event_seq` integer DEFAULT -1 NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`source`, `stream_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_raw_event_sessions_pending_updated` ON `raw_event_sessions` (`updated_at`) WHERE \\\"raw_event_sessions\\\".\\\"last_received_event_seq\\\" > \\\"raw_event_sessions\\\".\\\"last_flushed_event_seq\\\";\\nCREATE TABLE IF NOT EXISTS `opencode_sessions` (\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`session_id` integer,\\n\\t`created_at` text NOT NULL,\\n\\tPRIMARY KEY(`source`, `stream_id`),\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_opencode_sessions_session` ON `opencode_sessions` (`session_id`);\\nCREATE TABLE IF NOT EXISTS `pi_import_state` (\\n\\t`file_path` text PRIMARY KEY NOT NULL,\\n\\t`size_bytes` integer NOT NULL,\\n\\t`mtime_ms` real NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `raw_event_flush_batches` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`start_event_seq` integer NOT NULL,\\n\\t`end_event_seq` integer NOT NULL,\\n\\t`extractor_version` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`error_message` text,\\n\\t`error_type` text,\\n\\t`observer_provider` text,\\n\\t`observer_model` text,\\n\\t`observer_runtime` text,\\n\\t`observer_auth_source` text,\\n\\t`observer_auth_type` text,\\n\\t`observer_error_code` text,\\n\\t`observer_error_message` text,\\n\\t`attempt_count` integer DEFAULT 0 NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_flush_batches_source_stream_seq_ver` ON `raw_event_flush_batches` (`source`,`stream_id`,`start_event_seq`,`end_event_seq`,`extractor_version`);\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_session_created` ON `raw_event_flush_batches` (`opencode_session_id`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`);\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_observer_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`) WHERE \\\"raw_event_flush_batches\\\".\\\"observer_provider\\\" IS NOT NULL;\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_capture_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`) WHERE \\\"raw_event_flush_batches\\\".\\\"observer_provider\\\" IS NULL;\\nCREATE TABLE IF NOT EXISTS `user_prompts` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer,\\n\\t`project` text,\\n\\t`prompt_text` text NOT NULL,\\n\\t`prompt_number` integer,\\n\\t`created_at` text NOT NULL,\\n\\t`created_at_epoch` integer NOT NULL,\\n\\t`metadata_json` text,\\n\\t`import_key` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_session` ON `user_prompts` (`session_id`);\\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_project` ON `user_prompts` (`project`);\\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_epoch` ON `user_prompts` (`created_at_epoch`);\\nCREATE TABLE IF NOT EXISTS `session_summaries` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer,\\n\\t`project` text,\\n\\t`request` text,\\n\\t`investigated` text,\\n\\t`learned` text,\\n\\t`completed` text,\\n\\t`next_steps` text,\\n\\t`notes` text,\\n\\t`files_read` text,\\n\\t`files_edited` text,\\n\\t`prompt_number` integer,\\n\\t`created_at` text NOT NULL,\\n\\t`created_at_epoch` integer NOT NULL,\\n\\t`metadata_json` text,\\n\\t`import_key` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_session` ON `session_summaries` (`session_id`);\\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_project` ON `session_summaries` (`project`);\\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_epoch` ON `session_summaries` (`created_at_epoch`);\\nCREATE TABLE IF NOT EXISTS `replication_ops` (\\n\\t`op_id` text PRIMARY KEY NOT NULL,\\n\\t`entity_type` text NOT NULL,\\n\\t`entity_id` text NOT NULL,\\n\\t`op_type` text NOT NULL,\\n\\t`payload_json` text,\\n\\t`clock_rev` integer NOT NULL,\\n\\t`clock_updated_at` text NOT NULL,\\n\\t`clock_device_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`scope_id` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_created` ON `replication_ops` (`created_at`,`op_id`);\\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_entity` ON `replication_ops` (`entity_type`,`entity_id`);\\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_scope_created` ON `replication_ops` (`scope_id`,`created_at`,`op_id`);\\nCREATE TABLE IF NOT EXISTS `replication_cursors` (\\n\\t`peer_device_id` text PRIMARY KEY NOT NULL,\\n\\t`last_applied_cursor` text,\\n\\t`last_acked_cursor` text,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `replication_cursors_v2` (\\n\\t`peer_device_id` text NOT NULL,\\n\\t`scope_id` text NOT NULL,\\n\\t`last_applied_cursor` text,\\n\\t`last_acked_cursor` text,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`peer_device_id`, `scope_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_replication_cursors_v2_scope` ON `replication_cursors_v2` (`scope_id`);\\nCREATE TABLE IF NOT EXISTS `sync_peers` (\\n\\t`peer_device_id` text PRIMARY KEY NOT NULL,\\n\\t`name` text,\\n\\t`pinned_fingerprint` text,\\n\\t`public_key` text,\\n\\t`addresses_json` text,\\n\\t`manual_addresses_json` text,\\n\\t`last_success_address` text,\\n\\t`claimed_local_actor` integer DEFAULT 0 NOT NULL,\\n\\t`actor_id` text,\\n\\t`projects_include_json` text,\\n\\t`projects_exclude_json` text,\\n\\t`created_at` text NOT NULL,\\n\\t`last_seen_at` text,\\n\\t`last_sync_at` text,\\n\\t`last_error` text,\\n\\t`runtime_version` text,\\n\\t`runtime_version_observed_at` text,\\n\\t`highest_observed_direct_signature_version` integer,\\n\\t`discovered_via_coordinator_id` text,\\n\\t`discovered_via_group_id` text,\\n\\t`trust_provenance` text,\\n\\t`pending_bootstrap_grant_id` text\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_nonces` (\\n\\t`nonce` text PRIMARY KEY NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_device` (\\n\\t`device_id` text PRIMARY KEY NOT NULL,\\n\\t`public_key` text NOT NULL,\\n\\t`fingerprint` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_attempts` (\\n\\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`peer_device_id` text NOT NULL,\\n\\t`started_at` text NOT NULL,\\n\\t`finished_at` text,\\n\\t`ok` integer NOT NULL,\\n\\t`ops_in` integer NOT NULL,\\n\\t`ops_out` integer NOT NULL,\\n\\t`error` text,\\n\\t`local_sync_capability` text,\\n\\t`peer_sync_capability` text,\\n\\t`negotiated_sync_capability` text,\\n\\t`failure_category` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_peer_started` ON `sync_attempts` (`peer_device_id`,`started_at`);\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_occurred` ON `sync_attempts` (CASE WHEN \\\"finished_at\\\" IS NULL THEN \\\"started_at\\\" ELSE \\\"finished_at\\\" END,`id`);\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_error_occurred` ON `sync_attempts` (CASE WHEN \\\"finished_at\\\" IS NULL THEN \\\"started_at\\\" ELSE \\\"finished_at\\\" END,`id`) WHERE \\\"sync_attempts\\\".\\\"ok\\\" = 0;\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_success_occurred` ON `sync_attempts` (CASE WHEN \\\"finished_at\\\" IS NULL THEN \\\"started_at\\\" ELSE \\\"finished_at\\\" END,`id`) WHERE \\\"sync_attempts\\\".\\\"ok\\\" <> 0;\\nCREATE TABLE IF NOT EXISTS `sync_scope_rejections` (\\n\\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`peer_device_id` text,\\n\\t`op_id` text NOT NULL,\\n\\t`entity_type` text NOT NULL,\\n\\t`entity_id` text NOT NULL,\\n\\t`scope_id` text,\\n\\t`reason` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_peer_created` ON `sync_scope_rejections` (`peer_device_id`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_scope_created` ON `sync_scope_rejections` (`scope_id`,`created_at`);\\nCREATE TABLE IF NOT EXISTS `sync_daemon_state` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`last_error` text,\\n\\t`last_traceback` text,\\n\\t`last_error_at` text,\\n\\t`last_ok_at` text,\\n\\t`phase` text\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_reset_state` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`snapshot_id` text NOT NULL,\\n\\t`baseline_cursor` text,\\n\\t`retained_floor_cursor` text,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_reset_state_v2` (\\n\\t`scope_id` text PRIMARY KEY NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`snapshot_id` text NOT NULL,\\n\\t`baseline_cursor` text,\\n\\t`retained_floor_cursor` text,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_retention_state_v2` (\\n\\t`scope_id` text PRIMARY KEY NOT NULL,\\n\\t`last_run_at` text,\\n\\t`last_duration_ms` integer,\\n\\t`last_deleted_ops` integer DEFAULT 0 NOT NULL,\\n\\t`last_estimated_bytes_before` integer,\\n\\t`last_estimated_bytes_after` integer,\\n\\t`retained_floor_cursor` text,\\n\\t`last_error` text,\\n\\t`last_error_at` text\\n);\\n\\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_samples` (\\n\\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`inserted_events` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_invalid` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_duplicate` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_conflict` integer DEFAULT 0 NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_stats` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`inserted_events` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_events` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_invalid` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_duplicate` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_conflict` integer DEFAULT 0 NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `coordinator_group_preferences` (\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`projects_include_json` text,\\n\\t`projects_exclude_json` text,\\n\\t`auto_seed_scope` integer DEFAULT 1 NOT NULL,\\n\\t`default_space_scope_id` text,\\n\\t`auto_grant_default_space_on_join` integer DEFAULT 0 NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`coordinator_id`, `group_id`)\\n);\\n\\nCREATE TABLE IF NOT EXISTS `actors` (\\n\\t`actor_id` text PRIMARY KEY NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`is_local` integer DEFAULT 0 NOT NULL,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`merged_into_actor_id` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_actors_is_local` ON `actors` (`is_local`);\\nCREATE INDEX IF NOT EXISTS `idx_actors_status` ON `actors` (`status`);\\nCREATE TABLE IF NOT EXISTS `recipient_policy_review_resolutions` (\\n\\t`review_item_id` text NOT NULL,\\n\\t`source_fingerprint` text NOT NULL,\\n\\t`decision` text NOT NULL,\\n\\t`decision_input_json` text NOT NULL,\\n\\t`preview_json` text NOT NULL,\\n\\t`decided_by_identity_id` text NOT NULL,\\n\\t`decided_by_device_id` text NOT NULL,\\n\\t`resolved_at` text NOT NULL,\\n\\tPRIMARY KEY(`review_item_id`, `source_fingerprint`)\\n);\\n\\nCREATE TABLE IF NOT EXISTS `coordinator_enrollment_reconciliation_issues` (\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`kind` text NOT NULL,\\n\\t`reference_id` text NOT NULL,\\n\\t`code` text NOT NULL,\\n\\t`status` text DEFAULT 'open' NOT NULL,\\n\\t`first_seen_at` text NOT NULL,\\n\\t`last_seen_at` text NOT NULL,\\n\\t`resolved_at` text,\\n\\t`occurrence_count` integer DEFAULT 1 NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`coordinator_id`, `group_id`, `kind`, `reference_id`, `code`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_coordinator_enrollment_issues_boundary_status` ON `coordinator_enrollment_reconciliation_issues` (`coordinator_id`,`group_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_coordinator_enrollment_issues_status_recent` ON `coordinator_enrollment_reconciliation_issues` (`status`,`last_seen_at`,`resolved_at`);\\nCREATE TABLE IF NOT EXISTS `policy_teams` (\\n\\t`team_id` text PRIMARY KEY NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`device_eligibility_mode` text DEFAULT 'person_all_devices' NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `policy_teams_idempotency_key_unique` ON `policy_teams` (`idempotency_key`);\\nCREATE TABLE IF NOT EXISTS `policy_team_memberships` (\\n\\t`team_id` text NOT NULL,\\n\\t`identity_id` text NOT NULL,\\n\\t`role` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`team_id`, `identity_id`)\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `policy_team_memberships_idempotency_key_unique` ON `policy_team_memberships` (`idempotency_key`);\\nCREATE INDEX IF NOT EXISTS `idx_policy_team_memberships_identity_status` ON `policy_team_memberships` (`identity_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `policy_team_device_decisions` (\\n\\t`team_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`decision` text NOT NULL,\\n\\t`assignment_version` integer DEFAULT 0 NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`team_id`, `device_id`),\\n\\tFOREIGN KEY (`team_id`) REFERENCES `policy_teams`(`team_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_policy_team_device_decisions_device` ON `policy_team_device_decisions` (`device_id`);\\nCREATE TABLE IF NOT EXISTS `identity_devices` (\\n\\t`device_id` text PRIMARY KEY NOT NULL,\\n\\t`identity_id` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`assignment_version` integer DEFAULT 0 NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `identity_devices_idempotency_key_unique` ON `identity_devices` (`idempotency_key`);\\nCREATE INDEX IF NOT EXISTS `idx_identity_devices_identity_status` ON `identity_devices` (`identity_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `project_recipients` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`recipient_kind` text NOT NULL,\\n\\t`recipient_id` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`policy_revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`canonical_project_identity`, `recipient_kind`, `recipient_id`)\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `project_recipients_idempotency_key_unique` ON `project_recipients` (`idempotency_key`);\\nCREATE INDEX IF NOT EXISTS `idx_project_recipients_project_status` ON `project_recipients` (`canonical_project_identity`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_project_recipients_recipient_status` ON `project_recipients` (`recipient_kind`,`recipient_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_drafts` (\\n\\t`attempt_id` text PRIMARY KEY NOT NULL,\\n\\t`candidate_id` text NOT NULL,\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`state` text DEFAULT 'needs_setup' NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`roster_fingerprint` text NOT NULL,\\n\\t`projection_fingerprint` text NOT NULL,\\n\\t`finish_digest` text,\\n\\t`safe_error_code` text,\\n\\t`completed_team_id` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\t`completed_at` text,\\n\\t`superseded_at` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_candidate_state` ON `legacy_team_setup_drafts` (`candidate_id`,`state`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_state_updated` ON `legacy_team_setup_drafts` (`state`,`updated_at`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_finish_digest` ON `legacy_team_setup_drafts` (`finish_digest`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_completions` (\\n\\t`attempt_id` text NOT NULL,\\n\\t`finish_digest` text NOT NULL,\\n\\t`candidate_ref` text NOT NULL,\\n\\t`confirmed_access_delta_digest` text NOT NULL,\\n\\t`completed_team_id` text NOT NULL,\\n\\t`response_json` text NOT NULL,\\n\\t`completed_at` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_legacy_team_setup_completions_attempt_finish` ON `legacy_team_setup_completions` (`attempt_id`,`finish_digest`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_completions_exact_replay` ON `legacy_team_setup_completions` (`candidate_ref`,`attempt_id`,`finish_digest`,`confirmed_access_delta_digest`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_draft_devices` (\\n\\t`attempt_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`device_ref` text NOT NULL,\\n\\t`key_fingerprint` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`enabled` integer NOT NULL,\\n\\t`existing_identity_id` text,\\n\\t`existing_assignment_version` integer,\\n\\t`verified_evidence_kind` text,\\n\\t`identity_evidence` text,\\n\\t`decision` text DEFAULT 'unresolved' NOT NULL,\\n\\t`target_identity_id` text,\\n\\t`expected_assignment_kind` text,\\n\\t`expected_assignment_version` integer,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`attempt_id`, `device_id`),\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `legacy_team_setup_drafts`(`attempt_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_legacy_team_setup_devices_attempt_ref` ON `legacy_team_setup_draft_devices` (`attempt_id`,`device_ref`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_devices_attempt_decision` ON `legacy_team_setup_draft_devices` (`attempt_id`,`decision`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_draft_projects` (\\n\\t`attempt_id` text NOT NULL,\\n\\t`project_ref` text NOT NULL,\\n\\t`source_project_identity` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`source_fingerprint` text NOT NULL,\\n\\t`resolution_kind` text DEFAULT 'unresolved' NOT NULL,\\n\\t`resolved_project_identity` text,\\n\\t`target_scope_id` text,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`attempt_id`, `project_ref`),\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `legacy_team_setup_drafts`(`attempt_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_projects_attempt_resolution` ON `legacy_team_setup_draft_projects` (`attempt_id`,`resolution_kind`);\\nCREATE TABLE IF NOT EXISTS `recipient_managed_project_projections` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`managed_scope_id` text NOT NULL,\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`recipient_identity_id` text NOT NULL,\\n\\t`accepting_device_id` text NOT NULL,\\n\\t`source_operation_id` text NOT NULL,\\n\\t`reviewed_project_set_digest` text NOT NULL,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`accepted_at` text NOT NULL,\\n\\t`revoked_at` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`source_operation_id`, `canonical_project_identity`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_recipient_managed_projects_identity_status` ON `recipient_managed_project_projections` (`recipient_identity_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_recipient_managed_projects_scope_authority` ON `recipient_managed_project_projections` (`managed_scope_id`,`coordinator_id`,`group_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `recipient_policy_authority_states` (\\n\\t`canonical_project_identity` text PRIMARY KEY NOT NULL,\\n\\t`authority_state` text DEFAULT 'legacy' NOT NULL,\\n\\t`generation` integer DEFAULT 0 NOT NULL,\\n\\t`desired_devices_digest` text,\\n\\t`current_devices_digest` text,\\n\\t`stable_parity_evidence_digest` text,\\n\\t`stable_parity_passed_at` text,\\n\\t`fresh_snapshot_fingerprint` text,\\n\\t`fresh_snapshot_observed_at` text,\\n\\t`safe_error_code` text,\\n\\t`state_changed_at` text NOT NULL,\\n\\t`last_error_at` text,\\n\\t`attempt_count` integer DEFAULT 0 NOT NULL,\\n\\t`last_attempt_at` text,\\n\\t`wake_epoch` integer DEFAULT 0 NOT NULL,\\n\\t`last_completed_at` text,\\n\\t`lease_owner` text,\\n\\t`lease_acquired_at` text,\\n\\t`lease_expires_at` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `recipient_policy_reconciliation_steps` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`step_key` text NOT NULL,\\n\\t`effect_id` text NOT NULL,\\n\\t`payload_digest` text NOT NULL,\\n\\t`status` text DEFAULT 'pending' NOT NULL,\\n\\t`attempt_count` integer DEFAULT 0 NOT NULL,\\n\\t`started_at` text,\\n\\t`completed_at` text,\\n\\t`last_attempt_at` text,\\n\\t`safe_error_code` text,\\n\\t`error_at` text,\\n\\t`lease_owner` text,\\n\\t`lease_acquired_at` text,\\n\\t`lease_expires_at` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`canonical_project_identity`, `generation`, `step_key`)\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_effect` ON `recipient_policy_reconciliation_steps` (`effect_id`);\\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_status` ON `recipient_policy_reconciliation_steps` (`canonical_project_identity`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_pending_refresh` ON `recipient_policy_reconciliation_steps` (`canonical_project_identity`,`generation`,`step_key`) WHERE \\\"recipient_policy_reconciliation_steps\\\".\\\"status\\\" IN ('pending', 'running', 'failed') AND \\\"recipient_policy_reconciliation_steps\\\".\\\"step_key\\\" GLOB 'refresh-after-revocations-v2:*';\\nCREATE TABLE IF NOT EXISTS `recipient_policy_deny_overlays` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`scope_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`reason_code` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`canonical_project_identity`, `scope_id`, `device_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_deny_overlays_scope_device` ON `recipient_policy_deny_overlays` (`scope_id`,`device_id`);\";\n","import type { Database } from \"better-sqlite3\";\n\nconst INDEX_NAME = \"idx_usage_events_public_aggregate_cover\";\n\n/** Keep dashboard aggregates on the small index instead of decoding metadata on every read. */\nexport function ensureUsageEventsAggregateIndex(db: Database): void {\n\tif (db.readonly) return;\n\ttry {\n\t\tif (db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?\").get(INDEX_NAME))\n\t\t\treturn;\n\t\t// Match classifiedUsageSql's JSON expression and public-row predicate exactly.\n\t\t// Built-in JSON functions keep the derived index writable by older clients.\n\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_usage_events_public_aggregate_cover\n\t\t\tON usage_events (\n\t\t\t\tevent,\n\t\t\t\tCASE WHEN json_valid(metadata_json)\n\t\t\t\t\tTHEN json_extract(metadata_json, '$.token_usage.source') ELSE NULL END,\n\t\t\t\ttokens_read, tokens_written, tokens_saved, session_id\n\t\t\t)\n\t\t\tWHERE event != 'observer_recovery_scope_denial'\n\t\t\t\tAND event NOT GLOB 'observer_recovery_call_clock:*'`);\n\t} catch {\n\t\t// Optional access path: locked, query-only and partial legacy schemas keep\n\t\t// their existing aggregate queries and retry on the next writable open.\n\t}\n}\n","import type { Database } from \"better-sqlite3\";\n\nconst TRIGGERS = [\n\t[\"insert\", \"AFTER INSERT\", \"\"],\n\t[\"delete\", \"AFTER DELETE\", \"\"],\n\t[\n\t\t\"update\",\n\t\t// UPDATE OF id misses writes through rowid/_rowid_/oid aliases.\n\t\t\"AFTER UPDATE\",\n\t\t\"WHEN OLD.id IS NOT NEW.id OR OLD.title IS NOT NEW.title OR OLD.body_text IS NOT NEW.body_text OR OLD.active IS NOT NEW.active\",\n\t],\n].map(([suffix, event, condition]) => ({\n\tname: `vector_corpus_epoch_${suffix}`,\n\tsql: `CREATE TRIGGER vector_corpus_epoch_${suffix} ${event} ON memory_items ${condition}\n\tBEGIN UPDATE vector_corpus_epoch SET epoch = epoch + 1 WHERE id = 1; END`,\n}));\n\nfunction hasCurrentTriggers(db: Database): boolean {\n\tconst select = db.prepare(\"SELECT sql FROM sqlite_schema WHERE type = 'trigger' AND name = ?\");\n\treturn TRIGGERS.every(\n\t\t({ name, sql }) => (select.get(name) as { sql: string } | undefined)?.sql === sql,\n\t);\n}\n\n/** Ordinary-table triggers also observe writes from older application versions. */\nexport function ensureVectorCorpusEpoch(db: Database): void {\n\tif (db.readonly) return;\n\ttry {\n\t\tinstallVectorCorpusEpoch(db);\n\t} catch {\n\t\t// Optional derived state: minimal/query-only/locked handles retain the\n\t\t// conservative mutation fence. The installation transaction rolls back.\n\t}\n}\n\nfunction installVectorCorpusEpoch(db: Database): void {\n\tconst columns = db.prepare(\"PRAGMA table_info(memory_items)\").all() as { name: string }[];\n\tif (![\"id\", \"title\", \"body_text\", \"active\"].every((name) => columns.some((c) => c.name === name)))\n\t\treturn;\n\tif (readVectorCorpusFence(db).epoch !== null) return;\n\tdb.transaction(() => {\n\t\tdb.exec(\n\t\t\t\"CREATE TABLE IF NOT EXISTS vector_corpus_epoch (id INTEGER PRIMARY KEY CHECK (id = 1), epoch INTEGER NOT NULL CHECK (typeof(epoch) = 'integer' AND epoch >= 0))\",\n\t\t);\n\t\tconst initialized = db\n\t\t\t.prepare(\"INSERT OR IGNORE INTO vector_corpus_epoch VALUES (1, 0)\")\n\t\t\t.run().changes;\n\t\tif (!initialized && hasCurrentTriggers(db)) return;\n\t\tfor (const { name, sql } of TRIGGERS) {\n\t\t\tdb.exec(`DROP TRIGGER IF EXISTS ${name}`);\n\t\t\tdb.exec(sql);\n\t\t}\n\t\tdb.exec(\"UPDATE vector_corpus_epoch SET epoch = epoch + 1 WHERE id = 1\");\n\t}).immediate();\n}\n\n/** Compare both fields: repairing a deleted counter row can repeat an epoch. */\nexport type VectorCorpusFence = { schemaVersion: number; epoch: string | null };\n\nexport function readVectorCorpusFence(db: Database): VectorCorpusFence {\n\tconst schemaVersion = Number(db.pragma(\"schema_version\", { simple: true }));\n\ttry {\n\t\tif (!hasCurrentTriggers(db)) return { schemaVersion, epoch: null };\n\t\tconst row = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT CAST(epoch AS TEXT) AS epoch FROM vector_corpus_epoch WHERE id = 1 AND typeof(epoch) = 'integer' AND epoch >= 0\",\n\t\t\t)\n\t\t\t.get() as { epoch: string } | undefined;\n\t\treturn { schemaVersion, epoch: row?.epoch ?? null };\n\t} catch {\n\t\t// Minimal/legacy schemas retain the conservative global mutation fence.\n\t\treturn { schemaVersion, epoch: null };\n\t}\n}\n","import type { Database } from \"better-sqlite3\";\nimport {\n\tgetSchemaVersion,\n\tIDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL,\n\tisEmbeddingDisabled,\n\tloadSqliteVec,\n\tREQUIRED_BOOTSTRAPPED_TABLES,\n\tSCHEMA_VERSION,\n} from \"./database-runtime-primitives.js\";\nimport { ensureMemoryOwnershipSchemas } from \"./memory-ownership-recovery-schema.js\";\nimport { summaryLikeSqlPredicate } from \"./summary-memory.js\";\nimport { TEST_SCHEMA_BASE_DDL } from \"./test-schema.generated.js\";\nimport { ensureUsageEventsAggregateIndex } from \"./usage-aggregate-index.js\";\nimport { ensureVectorCorpusEpoch } from \"./vector-corpus-epoch.js\";\n\n/** Additive derived index; the existence check keeps later opens read-only here. */\nexport function ensureMemoryAggregateIndex(db: Database): void {\n\tif (db.readonly || !tableExists(db, \"memory_items\")) return;\n\tif (\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_memory_items_scope_aggregates'\",\n\t\t\t)\n\t\t\t.get()\n\t)\n\t\treturn;\n\t// Partial legacy schemas may not have gained these additive columns yet.\n\tif (!columnExists(db, \"memory_items\", \"scope_id\") || !columnExists(db, \"memory_items\", \"project\"))\n\t\treturn;\n\t// SQLite matches expression indexes syntactically. Use the same safe JSON\n\t// classifier as reads, without table qualifiers (not allowed in index DDL).\n\ttry {\n\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_memory_items_scope_aggregates\n\t\t\tON memory_items(scope_id, active, session_id, TRIM(tags_text) != '',\n\t\t\t\t${summaryLikeSqlPredicate(\"\")}, project)`);\n\t} catch {\n\t\t// Optional derived index: a locked/partial legacy DB retains ordinary reads\n\t\t// and retries on its next writable open, like the other paging indexes.\n\t}\n}\n\nconst RETRIEVAL_EXPOSURE_DETACH_UNAVAILABLE_MEMORY_DDL = `\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_unavailable_memory\nAFTER INSERT ON retrieval_exposures\nWHEN NEW.memory_id IS NOT NULL AND NOT EXISTS (\n\tSELECT 1 FROM memory_items\n\tWHERE memory_items.id = NEW.memory_id\n\t AND memory_items.active != 0\n\t AND memory_items.deleted_at IS NULL\n\t AND (\n\t\t(\n\t\t\tNEW.memory_import_key IS NOT NULL\n\t\t\tAND TRIM(NEW.memory_import_key) != ''\n\t\t\tAND import_key IS NOT NULL\n\t\t\tAND TRIM(import_key) != ''\n\t\t\tAND NEW.memory_import_key = import_key\n\t\t\tAND (\n\t\t\t\tNEW.origin_device_id IS NULL\n\t\t\t\tOR TRIM(NEW.origin_device_id) = ''\n\t\t\t\tOR (\n\t\t\t\t\torigin_device_id IS NOT NULL\n\t\t\t\t\tAND TRIM(origin_device_id) != ''\n\t\t\t\t\tAND NEW.origin_device_id = origin_device_id\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\tOR (\n\t\t\t(NEW.memory_import_key IS NULL OR TRIM(NEW.memory_import_key) = '')\n\t\t\tAND NEW.memory_rev = rev\n\t\t\tAND julianday(NEW.memory_updated_at) IS NOT NULL\n\t\t\tAND julianday(updated_at) IS NOT NULL\n\t\t\tAND julianday(NEW.memory_updated_at) = julianday(updated_at)\n\t\t\tAND NEW.memory_scope_id IS scope_id\n\t\t\tAND NEW.memory_kind = kind\n\t\t\tAND NEW.memory_active = active\n\t\t\tAND NEW.memory_deleted_at IS deleted_at\n\t\t)\n\t )\n)\nBEGIN\n\tUPDATE retrieval_exposures SET memory_id = NULL WHERE exposure_id = NEW.exposure_id;\nEND;\n`;\n\nconst RETRIEVAL_LEDGER_DDL = `\nCREATE TABLE IF NOT EXISTS retrieval_attempts (\n\tattempt_id TEXT PRIMARY KEY NOT NULL,\n\tcontract_version INTEGER NOT NULL,\n\tsurface TEXT NOT NULL,\n\ttrigger TEXT NOT NULL,\n\tstarted_at TEXT NOT NULL,\n\tcompleted_at TEXT,\n\tretrieval_status TEXT NOT NULL,\n\tdelivery_status TEXT NOT NULL,\n\tcandidate_count INTEGER NOT NULL,\n\tselected_count INTEGER NOT NULL,\n\tpersisted_candidate_count INTEGER NOT NULL,\n\trecorder_version TEXT NOT NULL,\n\tsession_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n\tsource TEXT,\n\tstream_id TEXT,\n\tsource_session_id TEXT,\n\tprompt_number INTEGER,\n\trequest_id TEXT,\n\traw_event_start_seq INTEGER,\n\traw_event_end_seq INTEGER,\n\texperiment_id TEXT,\n\texperiment_cell_id TEXT,\n\tevaluation_checkout_id TEXT,\n\tevaluation_fixture_id TEXT,\n\tevaluation_seed INTEGER,\n\tlatency_ms INTEGER,\n\tproject TEXT,\n\tscope_id TEXT,\n\tmode TEXT,\n\tlimit_requested INTEGER,\n\ttoken_budget INTEGER,\n\toutput_tokens INTEGER,\n\tworking_set_file_count INTEGER,\n\tworking_set_files_json TEXT,\n\tquery_hash_sha256 TEXT,\n\tquery_char_count INTEGER,\n\tquery_token_estimate INTEGER,\n\tfilter_summary_json TEXT,\n\tfailure_code TEXT,\n\tfailure_stage TEXT,\n\ttrace_version INTEGER,\n\tautomatic_recall_json TEXT,\n\tautomatic_recall_key TEXT,\n\tretention_until TEXT,\n\tretention_pinned INTEGER NOT NULL DEFAULT 0,\n\tretention_finalized_at TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_session_started\n\tON retrieval_attempts(session_id, started_at);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_source_stream_started\n\tON retrieval_attempts(source, stream_id, started_at);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_retention\n\tON retrieval_attempts(retention_pinned, retention_until);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_started\n\tON retrieval_attempts(started_at, attempt_id);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_surface_started\n\tON retrieval_attempts(surface, started_at);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_attempts_request_identity\n\tON retrieval_attempts(source, surface, request_id) WHERE request_id IS NOT NULL;\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_experiment_cell\n\tON retrieval_attempts(experiment_id, experiment_cell_id);\n\nCREATE TABLE IF NOT EXISTS retrieval_exposures (\n\texposure_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n\tattempt_id TEXT NOT NULL REFERENCES retrieval_attempts(attempt_id) ON DELETE CASCADE,\n\tmemory_id INTEGER REFERENCES memory_items(id) ON DELETE SET NULL,\n\tmemory_import_key TEXT,\n\torigin_device_id TEXT,\n\trank INTEGER NOT NULL,\n\tdisposition TEXT NOT NULL,\n\tsection TEXT,\n\thandoff_status TEXT NOT NULL,\n\tmemory_rev INTEGER,\n\tmemory_updated_at TEXT,\n\tmemory_scope_id TEXT,\n\tmemory_kind TEXT,\n\tmemory_active INTEGER,\n\tmemory_deleted_at TEXT,\n\tscore_summary_json TEXT,\n\treason_codes_json TEXT\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_exposures_attempt_rank\n\tON retrieval_exposures(attempt_id, rank);\nCREATE INDEX IF NOT EXISTS idx_retrieval_exposures_memory\n\tON retrieval_exposures(memory_id);\n\nCREATE TABLE IF NOT EXISTS outcome_evidence (\n\tevidence_id TEXT PRIMARY KEY NOT NULL,\n\tcontract_version INTEGER NOT NULL,\n\tdimension TEXT NOT NULL,\n\tevidence_type TEXT NOT NULL,\n\tsource_class TEXT NOT NULL,\n\tobserved_at TEXT NOT NULL,\n\tproducer TEXT NOT NULL,\n\tproducer_version TEXT NOT NULL,\n\tstatus TEXT NOT NULL,\n\tvalue_type TEXT,\n\tvalue_integer INTEGER,\n\tvalue_real REAL,\n\tvalue_unit TEXT,\n\tsession_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n\tsource TEXT,\n\tstream_id TEXT,\n\tsource_session_id TEXT,\n\tprompt_number INTEGER,\n\traw_event_start_seq INTEGER,\n\traw_event_end_seq INTEGER,\n\texperiment_id TEXT,\n\texperiment_cell_id TEXT,\n\twindow_start_at TEXT,\n\twindow_end_at TEXT,\n\treferences_json TEXT,\n\tretention_until TEXT,\n\tretention_pinned INTEGER NOT NULL DEFAULT 0,\n\tretention_finalized_at TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_observed_id\n\tON outcome_evidence(observed_at, evidence_id);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_session_observed\n\tON outcome_evidence(session_id, observed_at);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_source_stream_observed\n\tON outcome_evidence(source, stream_id, observed_at);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_type_observed\n\tON outcome_evidence(evidence_type, observed_at);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_retention\n\tON outcome_evidence(retention_pinned, retention_until);\n\nCREATE TABLE IF NOT EXISTS attribution_assessments (\n\tassessment_id TEXT PRIMARY KEY NOT NULL,\n\tcontract_version INTEGER NOT NULL,\n\tsubject_type TEXT NOT NULL,\n\tattempt_id TEXT NOT NULL REFERENCES retrieval_attempts(attempt_id) ON DELETE CASCADE,\n\texposure_id INTEGER REFERENCES retrieval_exposures(exposure_id) ON DELETE CASCADE,\n\tdimension TEXT NOT NULL,\n\timpact_label TEXT NOT NULL,\n\tbasis TEXT NOT NULL,\n\tconfidence_level TEXT NOT NULL,\n\tmethod TEXT NOT NULL,\n\tmethod_version TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL,\n\tclaim_type TEXT NOT NULL DEFAULT 'observational'\n);\n\nCREATE INDEX IF NOT EXISTS idx_attribution_assessments_attempt_created\n\tON attribution_assessments(attempt_id, created_at);\nCREATE INDEX IF NOT EXISTS idx_attribution_assessments_label_created\n\tON attribution_assessments(impact_label, created_at);\nCREATE INDEX IF NOT EXISTS idx_attribution_assessments_exposure\n\tON attribution_assessments(exposure_id);\n\nCREATE TABLE IF NOT EXISTS attribution_assessment_evidence (\n\tassessment_id TEXT NOT NULL REFERENCES attribution_assessments(assessment_id) ON DELETE CASCADE,\n\tevidence_id TEXT NOT NULL REFERENCES outcome_evidence(evidence_id) ON DELETE CASCADE,\n\tPRIMARY KEY (assessment_id, evidence_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_attribution_assessment_evidence_evidence\n\tON attribution_assessment_evidence(evidence_id, assessment_id);\n\n-- Intentionally handwritten: Drizzle models tables/indexes but not SQLite triggers.\n-- This keeps soft deletion aligned with the FK's physical-delete SET NULL behavior.\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_deleted_memory\nAFTER UPDATE OF active, deleted_at ON memory_items\nWHEN NEW.active = 0 OR NEW.deleted_at IS NOT NULL\nBEGIN\n\tUPDATE retrieval_exposures SET memory_id = NULL WHERE memory_id = NEW.id;\nEND;\n\n-- Foreign keys are checked when the INSERT statement finishes, after AFTER\n-- triggers run, so unavailable or identity-mismatched references can be detached\n-- without losing the immutable exposure snapshot.\n-- Keyless/privacy-redacted linkage requires every memory snapshot field to match.\n-- This narrows, but cannot eliminate, the risk of linking a reused numeric ID.\n${RETRIEVAL_EXPOSURE_DETACH_UNAVAILABLE_MEMORY_DDL}\n\n-- Defensive identity check for callers that disable foreign-key enforcement\n-- while replacing memory rows. Normal writable connections keep foreign keys on,\n-- so ON DELETE SET NULL detaches the link before an ID can be reused.\n-- There is intentionally no keyless fallback here: replacement cannot prove\n-- continuity with a previously linked memory.\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_reused_memory_id\nAFTER INSERT ON memory_items\nWHEN EXISTS (SELECT 1 FROM retrieval_exposures WHERE memory_id = NEW.id)\nBEGIN\n\tUPDATE retrieval_exposures\n\tSET memory_id = NULL\n\tWHERE memory_id = NEW.id\n\t AND (\n\t\tCOALESCE(NEW.active, 0) = 0\n\t\tOR NEW.deleted_at IS NOT NULL\n\t\tOR memory_import_key IS NULL\n\t\tOR TRIM(memory_import_key) = ''\n\t\tOR NEW.import_key IS NULL\n\t\tOR TRIM(NEW.import_key) = ''\n\t\tOR memory_import_key != NEW.import_key\n\t\tOR (\n\t\t\torigin_device_id IS NOT NULL\n\t\t\tAND TRIM(origin_device_id) != ''\n\t\t\tAND (\n\t\t\t\tNEW.origin_device_id IS NULL\n\t\t\t\tOR TRIM(NEW.origin_device_id) = ''\n\t\t\t\tOR origin_device_id != NEW.origin_device_id\n\t\t\t)\n\t\t)\n\t );\nEND;\n`;\n\nconst RETRIEVAL_LEDGER_SCHEMA_OBJECTS = [\n\t\"retrieval_attempts\",\n\t\"retrieval_exposures\",\n\t\"outcome_evidence\",\n\t\"attribution_assessments\",\n\t\"attribution_assessment_evidence\",\n\t\"idx_retrieval_attempts_session_started\",\n\t\"idx_retrieval_attempts_source_stream_started\",\n\t\"idx_retrieval_attempts_retention\",\n\t\"idx_retrieval_attempts_started\",\n\t\"idx_retrieval_attempts_surface_started\",\n\t\"idx_retrieval_attempts_request_identity\",\n\t\"idx_retrieval_attempts_experiment_cell\",\n\t\"idx_retrieval_exposures_attempt_rank\",\n\t\"idx_retrieval_exposures_memory\",\n\t\"idx_outcome_evidence_observed_id\",\n\t\"idx_outcome_evidence_session_observed\",\n\t\"idx_outcome_evidence_source_stream_observed\",\n\t\"idx_outcome_evidence_type_observed\",\n\t\"idx_outcome_evidence_retention\",\n\t\"idx_attribution_assessments_attempt_created\",\n\t\"idx_attribution_assessments_label_created\",\n\t\"idx_attribution_assessments_exposure\",\n\t\"idx_attribution_assessment_evidence_evidence\",\n\t\"trg_retrieval_exposures_detach_deleted_memory\",\n\t\"trg_retrieval_exposures_detach_unavailable_memory\",\n\t\"trg_retrieval_exposures_detach_reused_memory_id\",\n] as const;\n\nconst LEGACY_TEAM_SETUP_DRAFT_DDL = `\nCREATE TABLE IF NOT EXISTS legacy_team_setup_drafts (\n\tattempt_id TEXT PRIMARY KEY NOT NULL,\n\tcandidate_id TEXT NOT NULL,\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tstate TEXT NOT NULL DEFAULT 'needs_setup',\n\tdisplay_name TEXT NOT NULL,\n\troster_fingerprint TEXT NOT NULL,\n\tprojection_fingerprint TEXT NOT NULL,\n\tfinish_digest TEXT,\n\tsafe_error_code TEXT,\n\tcompleted_team_id TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tcompleted_at TEXT,\n\tsuperseded_at TEXT\n);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_candidate_state\n\tON legacy_team_setup_drafts(candidate_id, state, created_at);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_state_updated\n\tON legacy_team_setup_drafts(state, updated_at);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_finish_digest\n\tON legacy_team_setup_drafts(finish_digest);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_completions (\n\tattempt_id TEXT NOT NULL,\n\tfinish_digest TEXT NOT NULL,\n\tcandidate_ref TEXT NOT NULL,\n\tconfirmed_access_delta_digest TEXT NOT NULL,\n\tcompleted_team_id TEXT NOT NULL,\n\tresponse_json TEXT NOT NULL,\n\tcompleted_at TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_legacy_team_setup_completions_attempt_finish\n\tON legacy_team_setup_completions(attempt_id, finish_digest);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_completions_exact_replay\n\tON legacy_team_setup_completions(\n\t\tcandidate_ref,\n\t\tattempt_id,\n\t\tfinish_digest,\n\t\tconfirmed_access_delta_digest\n\t);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_draft_devices (\n\tattempt_id TEXT NOT NULL REFERENCES legacy_team_setup_drafts(attempt_id) ON DELETE CASCADE,\n\tdevice_id TEXT NOT NULL,\n\tdevice_ref TEXT NOT NULL,\n\tkey_fingerprint TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tenabled INTEGER NOT NULL,\n\texisting_identity_id TEXT,\n\texisting_assignment_version INTEGER,\n\tverified_evidence_kind TEXT,\n\tidentity_evidence TEXT,\n\tdecision TEXT NOT NULL DEFAULT 'unresolved',\n\ttarget_identity_id TEXT,\n\texpected_assignment_kind TEXT,\n\texpected_assignment_version INTEGER,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (attempt_id, device_id)\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_legacy_team_setup_devices_attempt_ref\n\tON legacy_team_setup_draft_devices(attempt_id, device_ref);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_devices_attempt_decision\n\tON legacy_team_setup_draft_devices(attempt_id, decision);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_draft_projects (\n\tattempt_id TEXT NOT NULL REFERENCES legacy_team_setup_drafts(attempt_id) ON DELETE CASCADE,\n\tproject_ref TEXT NOT NULL,\n\tsource_project_identity TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tsource_fingerprint TEXT NOT NULL,\n\tresolution_kind TEXT NOT NULL DEFAULT 'unresolved',\n\tresolved_project_identity TEXT,\n\ttarget_scope_id TEXT,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (attempt_id, project_ref)\n);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_projects_attempt_resolution\n\tON legacy_team_setup_draft_projects(attempt_id, resolution_kind);\n`;\n\nexport function ensureLegacyTeamSetupDraftSchema(db: Database): void {\n\tdb.exec(LEGACY_TEAM_SETUP_DRAFT_DDL);\n\tconst finishDigestIndex = db\n\t\t.prepare(\n\t\t\t`SELECT \"unique\" AS is_unique\n\t\t\t FROM pragma_index_list('legacy_team_setup_drafts')\n\t\t\t WHERE name = 'idx_legacy_team_setup_drafts_finish_digest'\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get() as { is_unique?: number } | undefined;\n\tif (finishDigestIndex?.is_unique === 1) {\n\t\tdb.exec(`\n\t\t\tDROP INDEX idx_legacy_team_setup_drafts_finish_digest;\n\t\t\tCREATE INDEX idx_legacy_team_setup_drafts_finish_digest\n\t\t\t\tON legacy_team_setup_drafts(finish_digest);\n\t\t`);\n\t}\n\tfor (const [table, column, definition] of [\n\t\t[\"legacy_team_setup_drafts\", \"safe_error_code\", \"TEXT\"],\n\t\t[\"legacy_team_setup_drafts\", \"completed_team_id\", \"TEXT\"],\n\t\t[\"legacy_team_setup_draft_devices\", \"verified_evidence_kind\", \"TEXT\"],\n\t\t[\"legacy_team_setup_draft_devices\", \"identity_evidence\", \"TEXT\"],\n\t\t[\"legacy_team_setup_draft_projects\", \"target_scope_id\", \"TEXT\"],\n\t] as const) {\n\t\tif (!columnExists(db, table, column)) {\n\t\t\tdb.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);\n\t\t}\n\t}\n\t// Every open, not just when the column is added: an older process may still\n\t// write unmarked drafts, and a crash could split the ALTER from the backfill.\n\tbackfillOpenDraftIdentityEvidence(db);\n}\n\nconst OPEN_DRAFT_DEVICES = `identity_evidence IS NULL AND attempt_id IN (\n\tSELECT attempt_id FROM legacy_team_setup_drafts WHERE state IN ('needs_setup', 'in_progress'))`;\n\n/**\n * Drafts still open at upgrade would otherwise upload other devices' local\n * records as ownership. Mark them now. Completed drafts stay unmarked so\n * republishing reproduces the bytes the coordinator already stored. Without\n * exactly one known running device, every row is a label (fail closed).\n */\nfunction backfillOpenDraftIdentityEvidence(db: Database): void {\n\t// Read first: opening an up-to-date database must not need the write lock.\n\tconst pending = db\n\t\t.prepare(`SELECT 1 FROM legacy_team_setup_draft_devices WHERE ${OPEN_DRAFT_DEVICES} LIMIT 1`)\n\t\t.get();\n\tif (!pending) return;\n\ttry {\n\t\tdb.exec(`UPDATE legacy_team_setup_draft_devices\n\t\t\tSET identity_evidence = CASE WHEN device_id IS (\n\t\t\t\tSELECT CASE WHEN COUNT(*) = 1 THEN MAX(device_id) END FROM sync_device\n\t\t\t) THEN 'self' ELSE 'label' END\n\t\t\tWHERE ${OPEN_DRAFT_DEVICES}`);\n\t} catch {\n\t\tdb.exec(`UPDATE legacy_team_setup_draft_devices SET identity_evidence = 'label'\n\t\t\tWHERE ${OPEN_DRAFT_DEVICES}`);\n\t}\n}\n\nconst SCHEMA_AUX_DDL = `\n${RETRIEVAL_LEDGER_DDL}\n\n${LEGACY_TEAM_SETUP_DRAFT_DDL}\n\nCREATE TABLE IF NOT EXISTS policy_team_device_decisions (\n\tteam_id TEXT NOT NULL REFERENCES policy_teams(team_id) ON DELETE CASCADE,\n\tdevice_id TEXT NOT NULL,\n\tdecision TEXT NOT NULL,\n\tassignment_version INTEGER NOT NULL DEFAULT 0,\n\tprovenance TEXT NOT NULL,\n\trevision TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (team_id, device_id)\n);\nCREATE INDEX IF NOT EXISTS idx_policy_team_device_decisions_device\n\tON policy_team_device_decisions(device_id);\n\nCREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);\n\nCREATE TABLE IF NOT EXISTS sync_peer_signature_state (\n\tpeer_device_id TEXT PRIMARY KEY NOT NULL,\n\thighest_observed_direct_signature_version INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS coordinator_enrollment_reconciliation_issues (\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tkind TEXT NOT NULL,\n\treference_id TEXT NOT NULL,\n\tcode TEXT NOT NULL,\n\tstatus TEXT NOT NULL DEFAULT 'open',\n\tfirst_seen_at TEXT NOT NULL,\n\tlast_seen_at TEXT NOT NULL,\n\tresolved_at TEXT,\n\toccurrence_count INTEGER NOT NULL DEFAULT 1,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (coordinator_id, group_id, kind, reference_id, code)\n);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_boundary_status\n\tON coordinator_enrollment_reconciliation_issues(coordinator_id, group_id, status);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_status_recent\n\tON coordinator_enrollment_reconciliation_issues(status, last_seen_at, resolved_at);\n\nCREATE TABLE IF NOT EXISTS recipient_policy_review_resolutions (\n\treview_item_id TEXT NOT NULL,\n\tsource_fingerprint TEXT NOT NULL,\n\tdecision TEXT NOT NULL,\n\tdecision_input_json TEXT NOT NULL,\n\tpreview_json TEXT NOT NULL,\n\tdecided_by_identity_id TEXT NOT NULL,\n\tdecided_by_device_id TEXT NOT NULL,\n\tresolved_at TEXT NOT NULL,\n\tPRIMARY KEY (review_item_id, source_fingerprint)\n);\n\nCREATE TABLE IF NOT EXISTS device_identity_binding_commits (\n\tcommit_digest TEXT PRIMARY KEY NOT NULL,\n\treviewed_inventory_digest TEXT NOT NULL,\n\trequest_json TEXT NOT NULL,\n\toutcomes_json TEXT NOT NULL,\n\twrite_count INTEGER NOT NULL,\n\tdecided_by_identity_id TEXT NOT NULL,\n\tdecided_by_device_id TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS device_identity_binding_audit (\n\tevent_id TEXT PRIMARY KEY NOT NULL,\n\tcommit_digest TEXT NOT NULL REFERENCES device_identity_binding_commits(commit_digest),\n\tdevice_id TEXT NOT NULL,\n\tprevious_identity_id TEXT,\n\ttarget_identity_id TEXT NOT NULL,\n\taction TEXT NOT NULL,\n\tprevious_assignment_version INTEGER,\n\tresulting_assignment_version INTEGER NOT NULL,\n\tdecided_by_identity_id TEXT NOT NULL,\n\tdecided_by_device_id TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_device_identity_binding_audit_commit_device\n\tON device_identity_binding_audit(commit_digest, device_id);\nCREATE INDEX IF NOT EXISTS idx_device_identity_binding_audit_device_created\n\tON device_identity_binding_audit(device_id, created_at, event_id);\n\nCREATE TABLE IF NOT EXISTS recipient_policy_authority_states (\n\tcanonical_project_identity TEXT PRIMARY KEY NOT NULL,\n\tauthority_state TEXT NOT NULL DEFAULT 'legacy',\n\tgeneration INTEGER NOT NULL DEFAULT 0,\n\tdesired_devices_digest TEXT,\n\tcurrent_devices_digest TEXT,\n\tstable_parity_evidence_digest TEXT,\n\tstable_parity_passed_at TEXT,\n\tfresh_snapshot_fingerprint TEXT,\n\tfresh_snapshot_observed_at TEXT,\n\tsafe_error_code TEXT,\n\tstate_changed_at TEXT NOT NULL,\n\tlast_error_at TEXT,\n\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\tlast_attempt_at TEXT,\n\twake_epoch INTEGER NOT NULL DEFAULT 0,\n\tlast_completed_at TEXT,\n\tlease_owner TEXT,\n\tlease_acquired_at TEXT,\n\tlease_expires_at TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS recipient_policy_reconciliation_steps (\n\tcanonical_project_identity TEXT NOT NULL,\n\tgeneration INTEGER NOT NULL,\n\tstep_key TEXT NOT NULL,\n\teffect_id TEXT NOT NULL,\n\tpayload_digest TEXT NOT NULL,\n\tstatus TEXT NOT NULL DEFAULT 'pending',\n\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\tstarted_at TEXT,\n\tcompleted_at TEXT,\n\tlast_attempt_at TEXT,\n\tsafe_error_code TEXT,\n\terror_at TEXT,\n\tlease_owner TEXT,\n\tlease_acquired_at TEXT,\n\tlease_expires_at TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (canonical_project_identity, generation, step_key)\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_effect\n\tON recipient_policy_reconciliation_steps(effect_id);\nCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_status\n\tON recipient_policy_reconciliation_steps(canonical_project_identity, status);\nCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_pending_refresh\n\tON recipient_policy_reconciliation_steps(canonical_project_identity, generation, step_key)\n\tWHERE status IN ('pending', 'running', 'failed')\n\tAND step_key GLOB 'refresh-after-revocations-v2:*';\nCREATE TABLE IF NOT EXISTS recipient_policy_deny_overlays (\n\tcanonical_project_identity TEXT NOT NULL,\n\tscope_id TEXT NOT NULL,\n\tdevice_id TEXT NOT NULL,\n\tgeneration INTEGER NOT NULL,\n\treason_code TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (canonical_project_identity, scope_id, device_id)\n);\nCREATE INDEX IF NOT EXISTS idx_recipient_policy_deny_overlays_scope_device\n\tON recipient_policy_deny_overlays(scope_id, device_id);\n\nCREATE TABLE IF NOT EXISTS recipient_managed_project_projections (\n\tcanonical_project_identity TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tmanaged_scope_id TEXT NOT NULL,\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\trecipient_identity_id TEXT NOT NULL,\n\taccepting_device_id TEXT NOT NULL,\n\tsource_operation_id TEXT NOT NULL,\n\treviewed_project_set_digest TEXT NOT NULL,\n\tstatus TEXT NOT NULL DEFAULT 'active',\n\taccepted_at TEXT NOT NULL,\n\trevoked_at TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (source_operation_id, canonical_project_identity)\n);\nCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_identity_status\n\tON recipient_managed_project_projections(recipient_identity_id, status);\nCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_scope_authority\n\tON recipient_managed_project_projections(managed_scope_id, coordinator_id, group_id, status);\n\nCREATE TABLE IF NOT EXISTS share_operations (\n\toperation_id TEXT PRIMARY KEY NOT NULL,\n\tstate TEXT NOT NULL,\n\tinviter_actor_id TEXT NOT NULL,\n\tinviter_device_ids_json TEXT NOT NULL,\n\tperson_id TEXT NOT NULL,\n\tperson_kind TEXT NOT NULL,\n\tpending_person_operation_id TEXT,\n\tteammate_name TEXT NOT NULL,\n\thistory_policy TEXT NOT NULL,\n\treviewed_project_set_digest TEXT NOT NULL,\n\tcoordinator_group_id TEXT NOT NULL,\n\tcoordinator_invite_id TEXT,\n\tinvite_token_digest TEXT NOT NULL,\n\tinvite_expires_at TEXT NOT NULL,\n\trecipient_actor_id TEXT,\n\trecipient_display_name TEXT,\n\trecipient_device_id TEXT,\n\trecipient_device_display_name TEXT,\n\trecipient_public_key TEXT,\n\trecipient_fingerprint TEXT,\n\tacceptance_consumed_at TEXT,\n\ttrust_state TEXT,\n\tbootstrap_grant_id TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_share_operations_state_updated\n\tON share_operations(state, updated_at);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_invite_digest\n\tON share_operations(invite_token_digest);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_pending_person_operation\n\tON share_operations(pending_person_operation_id)\n\tWHERE pending_person_operation_id IS NOT NULL;\nCREATE TABLE IF NOT EXISTS share_operation_projects (\n\toperation_id TEXT NOT NULL,\n\tcanonical_project_identity TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tidentity_source TEXT NOT NULL,\n\texisting_memory_count INTEGER NOT NULL,\n\tordinal INTEGER NOT NULL,\n\tPRIMARY KEY (operation_id, canonical_project_identity)\n);\nCREATE TABLE IF NOT EXISTS share_operation_steps (\n\toperation_id TEXT NOT NULL,\n\tstep_key TEXT NOT NULL,\n\teffect_id TEXT NOT NULL,\n\tstatus TEXT NOT NULL,\n\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\tstarted_at TEXT,\n\tcompleted_at TEXT,\n\tlast_attempt_at TEXT,\n\tsafe_error_code TEXT,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (operation_id, step_key)\n);\n\nCREATE TABLE IF NOT EXISTS sync_retention_state (\n\tid INTEGER PRIMARY KEY,\n\tlast_run_at TEXT,\n\tlast_duration_ms INTEGER,\n\tlast_deleted_ops INTEGER NOT NULL DEFAULT 0,\n\tlast_estimated_bytes_before INTEGER,\n\tlast_estimated_bytes_after INTEGER,\n\tretained_floor_cursor TEXT,\n\tlast_error TEXT,\n\tlast_error_at TEXT\n);\n\nCREATE TABLE IF NOT EXISTS maintenance_jobs (\n\tkind TEXT PRIMARY KEY,\n\ttitle TEXT NOT NULL,\n\tstatus TEXT NOT NULL,\n\tmessage TEXT,\n\tprogress_current INTEGER NOT NULL DEFAULT 0,\n\tprogress_total INTEGER,\n\tprogress_unit TEXT NOT NULL DEFAULT 'items',\n\tmetadata_json TEXT,\n\tstarted_at TEXT,\n\tupdated_at TEXT NOT NULL,\n\tfinished_at TEXT,\n\terror TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated\n\tON maintenance_jobs(status, updated_at);\n\nCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\tpeer_device_id TEXT,\n\top_id TEXT NOT NULL,\n\tentity_type TEXT NOT NULL,\n\tentity_id TEXT NOT NULL,\n\tscope_id TEXT,\n\treason TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n\tON sync_scope_rejections(peer_device_id, created_at);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n\tON sync_scope_rejections(scope_id, created_at);\n\n-- import_key is the primary lookup key from replication_ops.entity_id back to\n-- the source memory. The scope-backfill runner's selectReplicationOpScopeCandidates\n-- query joins on it for every unstamped op; without this index a Pi 4 with\n-- ~17k memories and ~35k ops scans the full memory_items table on every batch\n-- tick. The partial WHERE clause keeps the index small (most rows have\n-- import_key set; the few that don't aren't searchable anyway).\nCREATE INDEX IF NOT EXISTS idx_memory_items_import_key\n\tON memory_items(import_key)\n\tWHERE import_key IS NOT NULL;\n\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n\ttitle, body_text, tags_text,\n\tcontent='memory_items',\n\tcontent_rowid='id'\n);\n\nCREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN\n\tINSERT INTO memory_fts(rowid, title, body_text, tags_text)\n\tVALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_au;\nCREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN\n\tINSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n\tVALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n\tINSERT INTO memory_fts(rowid, title, body_text, tags_text)\n\tVALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_ad;\nCREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN\n\tINSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n\tVALUES('delete', old.id, old.title, old.body_text, old.tags_text);\nEND;\n\nCREATE TABLE IF NOT EXISTS memory_file_refs (\n\tmemory_id INTEGER NOT NULL,\n\tfile_path TEXT NOT NULL,\n\trelation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n\tPRIMARY KEY (memory_id, file_path, relation),\n\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_file_refs_path\n\tON memory_file_refs(file_path);\n\nCREATE TABLE IF NOT EXISTS memory_concept_refs (\n\tmemory_id INTEGER NOT NULL,\n\tconcept TEXT NOT NULL,\n\tPRIMARY KEY (memory_id, concept),\n\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept\n\tON memory_concept_refs(concept);\n\nCREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tprojects_include_json TEXT,\n\tprojects_exclude_json TEXT,\n\tauto_seed_scope INTEGER NOT NULL DEFAULT 1,\n\tdefault_space_scope_id TEXT,\n\tauto_grant_default_space_on_join INTEGER NOT NULL DEFAULT 0,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (coordinator_id, group_id)\n);\n\nCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tlast_refresh_at TEXT NOT NULL,\n\tlast_success_at TEXT,\n\tlast_error TEXT,\n\tupdated_at TEXT NOT NULL,\n\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\tPRIMARY KEY (coordinator_id, group_id)\n);\n`;\n\n/**\n * DDL for the sqlite-vec `memory_vectors` virtual table. Drizzle cannot model\n * virtual tables driven by a loadable extension, so this lives alongside the\n * other aux DDL and is executed through `ensureVectorSchema` (which first\n * makes sure the `vec0` module is actually loaded on the connection).\n *\n * Columns mirror the Python `_ensure_vector_schema` helper in `codemem/db.py`.\n * The embedding width (384) matches the default BAAI/bge-small-en-v1.5 model\n * and the existing vectors tests; changing it requires rebuilding existing\n * vector rows via the migration helper.\n */\nconst MEMORY_VECTORS_DDL = `\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_vectors USING vec0(\n\tembedding float[384],\n\tmemory_id INTEGER,\n\tchunk_index INTEGER,\n\tcontent_hash TEXT,\n\tmodel TEXT\n);\n`;\n\n/**\n * Create the `memory_vectors` sqlite-vec virtual table on `db` if it does not\n * already exist. No-op when embeddings are disabled via\n * `CODEMEM_EMBEDDING_DISABLED`, matching the Python backend's behavior.\n *\n * This function is safe to call from any bootstrap path — it probes for\n * `vec_version()` first and only attempts to load the sqlite-vec extension if\n * it is not already present on the connection. That avoids double-loading when\n * callers (like `MemoryStore`) have already called `loadSqliteVec` directly.\n */\nexport function ensureVectorSchema(db: Database): void {\n\tif (isEmbeddingDisabled()) return;\n\ttry {\n\t\tif (!isSqliteVecLoaded(db)) {\n\t\t\tloadSqliteVec(db);\n\t\t}\n\t\tdb.exec(MEMORY_VECTORS_DDL);\n\t} catch {\n\t\treturn;\n\t}\n}\n\nfunction isSqliteVecLoaded(db: Database): boolean {\n\ttry {\n\t\tconst row = db.prepare(\"SELECT vec_version() AS v\").get() as { v?: string } | undefined;\n\t\treturn typeof row?.v === \"string\" && row.v.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function bootstrapSchema(db: Database): void {\n\tdb.transaction(() => {\n\t\tdb.exec(TEST_SCHEMA_BASE_DDL);\n\t\tdb.exec(SCHEMA_AUX_DDL);\n\t\tensureLegacyTeamSetupDraftSchema(db);\n\t\tensureRawEventCaptureContextSchema(db);\n\t\tensurePolicyTeamDeviceEligibilityColumns(db);\n\t\tensureSyncPeerSignatureStateSchema(db);\n\t\tensureSyncPeerManualAddressesColumn(db);\n\t\tensureSyncPeerLastSuccessAddressColumn(db);\n\t\tensureRetrievalAttemptColumns(db);\n\t\tensureOutcomeEvidenceColumns(db);\n\t\tensureMemoryOwnershipSchemas(db);\n\t\tensureMemoryAggregateIndex(db);\n\t\tensureUsageEventsAggregateIndex(db);\n\t\tensureVectorCorpusEpoch(db);\n\t\tassertBootstrapTablesCreated(db);\n\t\tdb.pragma(`user_version = ${SCHEMA_VERSION}`);\n\t}).immediate();\n\n\t// sqlite-vec support is optional/best-effort. Keep it outside the core\n\t// bootstrap transaction so an unavailable extension cannot produce a\n\t// half-successful core schema, and cannot prevent first-run stats/setup.\n\tensureVectorSchema(db);\n}\n\nfunction ensureSyncPeerManualAddressesColumn(db: Database): void {\n\tif (!columnExists(db, \"sync_peers\", \"manual_addresses_json\")) {\n\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN manual_addresses_json TEXT\");\n\t}\n}\n\nfunction ensureSyncPeerLastSuccessAddressColumn(db: Database): void {\n\tif (!columnExists(db, \"sync_peers\", \"last_success_address\")) {\n\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN last_success_address TEXT\");\n\t}\n}\n\nfunction ensurePolicyTeamDeviceEligibilityColumns(db: Database): void {\n\tif (!columnExists(db, \"policy_teams\", \"device_eligibility_mode\")) {\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE policy_teams ADD COLUMN device_eligibility_mode TEXT NOT NULL DEFAULT 'person_all_devices'\",\n\t\t);\n\t}\n\tif (!columnExists(db, \"identity_devices\", \"assignment_version\")) {\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE identity_devices ADD COLUMN assignment_version INTEGER NOT NULL DEFAULT 0\",\n\t\t);\n\t}\n\tif (!columnExists(db, \"policy_team_device_decisions\", \"assignment_version\")) {\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE policy_team_device_decisions ADD COLUMN assignment_version INTEGER NOT NULL DEFAULT 0\",\n\t\t);\n\t}\n\tensureIdentityDeviceAssignmentVersionTriggers(db);\n}\n\n/** Add sticky direct-peer signature state without requiring a schema-version bump. */\nexport function ensureSyncPeerDirectSignatureVersionColumn(db: Database): void {\n\tif (!tableExists(db, \"sync_peers\")) return;\n\tif (columnExists(db, \"sync_peers\", \"highest_observed_direct_signature_version\")) return;\n\ttry {\n\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN highest_observed_direct_signature_version INTEGER\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\tif (\n\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\tcolumnExists(db, \"sync_peers\", \"highest_observed_direct_signature_version\")\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Keep signature downgrade protection outside deletable peer trust rows.\n *\n * The copy is advancing-only so this repair can run on every open, including\n * databases whose compatibility marker was written before this table existed.\n */\nexport function ensureSyncPeerSignatureStateSchema(db: Database): void {\n\tif (!tableExists(db, \"sync_peers\")) return;\n\tensureSyncPeerDirectSignatureVersionColumn(db);\n\tif (!tableExists(db, \"sync_peer_signature_state\")) {\n\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_peer_signature_state (\n\t\t\t\tpeer_device_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\thighest_observed_direct_signature_version INTEGER NOT NULL\n\t\t\t);\n\t\t`);\n\t}\n\t// Every CLI command opens the store, so only take the write lock when a\n\t// peer's recorded version is actually ahead of the preserved state.\n\tconst pending = db\n\t\t.prepare(\n\t\t\t`SELECT 1 FROM sync_peers AS peer\n\t\t\t LEFT JOIN sync_peer_signature_state AS state USING (peer_device_id)\n\t\t\t WHERE peer.highest_observed_direct_signature_version IS NOT NULL\n\t\t\t AND (state.peer_device_id IS NULL\n\t\t\t OR state.highest_observed_direct_signature_version\n\t\t\t < peer.highest_observed_direct_signature_version)\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get();\n\tif (!pending) return;\n\tdb.exec(`\n\t\tINSERT INTO sync_peer_signature_state(\n\t\t\tpeer_device_id, highest_observed_direct_signature_version\n\t\t)\n\t\tSELECT peer_device_id, highest_observed_direct_signature_version\n\t\tFROM sync_peers\n\t\tWHERE highest_observed_direct_signature_version IS NOT NULL\n\t\tON CONFLICT(peer_device_id) DO UPDATE SET\n\t\t\thighest_observed_direct_signature_version = excluded.highest_observed_direct_signature_version\n\t\tWHERE sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t< excluded.highest_observed_direct_signature_version;\n\t`);\n}\n\nfunction ensureIdentityDeviceAssignmentVersionTriggers(db: Database): void {\n\tdb.exec(IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL);\n}\n\n/** Add the local-only retrieval ledger to an already initialized database. */\nexport function ensureRetrievalLedgerSchema(db: Database): void {\n\tif (!tableExists(db, \"sessions\") || !tableExists(db, \"memory_items\")) return;\n\tensureMemoryItemsDeletedAtColumn(db);\n\t// Contract-v1 cleanup is explicit and bounded by retention/privacy selectors.\n\t// Remove the earlier global orphan trigger even when every table/index already exists.\n\tdb.exec(\"DROP TRIGGER IF EXISTS trg_attribution_evidence_delete_orphan\");\n\tif (\n\t\t!columnExists(db, \"memory_items\", \"import_key\") ||\n\t\t!columnExists(db, \"memory_items\", \"origin_device_id\")\n\t) {\n\t\treturn;\n\t}\n\tconst placeholders = RETRIEVAL_LEDGER_SCHEMA_OBJECTS.map(() => \"?\").join(\", \");\n\tconst row = db\n\t\t.prepare(`SELECT COUNT(*) AS count FROM sqlite_master WHERE name IN (${placeholders})`)\n\t\t.get(...RETRIEVAL_LEDGER_SCHEMA_OBJECTS) as { count?: number } | undefined;\n\tif (row?.count !== RETRIEVAL_LEDGER_SCHEMA_OBJECTS.length) {\n\t\t// Replay the idempotent DDL only after detecting an interrupted migration.\n\t\tdb.exec(RETRIEVAL_LEDGER_DDL);\n\t}\n\tensureRetrievalExposureDetachUnavailableMemoryTrigger(db);\n\tensureRetrievalAttemptColumns(db);\n\tensureOutcomeEvidenceColumns(db);\n}\n\nfunction ensureRetrievalExposureDetachUnavailableMemoryTrigger(db: Database): void {\n\tconst sql = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'trg_retrieval_exposures_detach_unavailable_memory'\",\n\t\t)\n\t\t.pluck()\n\t\t.get() as string | undefined;\n\tif (\n\t\tsql?.includes(\"NEW.memory_import_key IS NOT NULL\") &&\n\t\tsql.includes(\"NEW.memory_import_key = import_key\") &&\n\t\tsql.includes(\"NEW.origin_device_id = origin_device_id\") &&\n\t\tsql.includes(\"NEW.memory_rev = rev\") &&\n\t\tsql.includes(\"julianday(NEW.memory_updated_at) = julianday(updated_at)\")\n\t) {\n\t\treturn;\n\t}\n\tdb.transaction(() => {\n\t\tdb.exec(`\n\t\t\tDROP TRIGGER IF EXISTS trg_retrieval_exposures_detach_unavailable_memory;\n\t\t\t${RETRIEVAL_EXPOSURE_DETACH_UNAVAILABLE_MEMORY_DDL}\n\t\t`);\n\t}).immediate();\n}\n\nfunction ensureMemoryItemsDeletedAtColumn(db: Database): void {\n\tif (columnExists(db, \"memory_items\", \"deleted_at\")) return;\n\ttry {\n\t\t// Existing rows become NULL, preserving active rows while leaving legacy\n\t\t// active=0 rows unavailable without inventing a deletion timestamp.\n\t\tdb.exec(\"ALTER TABLE memory_items ADD COLUMN deleted_at TEXT\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\tif (\n\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\tcolumnExists(db, \"memory_items\", \"deleted_at\")\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction ensureRetrievalAttemptColumns(db: Database): void {\n\tfor (const [name, definition] of [\n\t\t[\"evaluation_checkout_id\", \"TEXT\"],\n\t\t[\"evaluation_fixture_id\", \"TEXT\"],\n\t\t[\"evaluation_seed\", \"INTEGER\"],\n\t\t[\"retention_finalized_at\", \"TEXT\"],\n\t\t[\"automatic_recall_json\", \"TEXT\"],\n\t\t[\"automatic_recall_key\", \"TEXT\"],\n\t] as const) {\n\t\tconst exists = db\n\t\t\t.prepare(\"SELECT 1 FROM pragma_table_info('retrieval_attempts') WHERE name = ? LIMIT 1\")\n\t\t\t.get(name);\n\t\tif (exists === undefined) {\n\t\t\tdb.exec(`ALTER TABLE retrieval_attempts ADD COLUMN ${name} ${definition}`);\n\t\t}\n\t}\n\tdb.exec(\n\t\t\"CREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_attempts_automatic_recall_key ON retrieval_attempts(automatic_recall_key)\",\n\t);\n}\n\nfunction ensureOutcomeEvidenceColumns(db: Database): void {\n\tif (columnExists(db, \"outcome_evidence\", \"retention_finalized_at\")) return;\n\ttry {\n\t\tdb.exec(\"ALTER TABLE outcome_evidence ADD COLUMN retention_finalized_at TEXT\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\tif (\n\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\tcolumnExists(db, \"outcome_evidence\", \"retention_finalized_at\")\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction assertBootstrapTablesCreated(db: Database): void {\n\tconst missing = REQUIRED_BOOTSTRAPPED_TABLES.filter((table) => !tableExists(db, table));\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Schema bootstrap failed; missing required tables: ${missing.join(\", \")}`);\n\t}\n}\n\nfunction isSafeEmptyDatabase(db: Database): boolean {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS count\n\t\t\t FROM sqlite_master\n\t\t\t WHERE name NOT LIKE 'sqlite\\\\_%' ESCAPE '\\\\'`,\n\t\t)\n\t\t.get() as { count?: number } | undefined;\n\treturn (row?.count ?? 0) === 0;\n}\n\nfunction tableExists(db: Database, table: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1\")\n\t\t.get(table);\n\treturn row !== undefined;\n}\n\nfunction columnExists(db: Database, table: string, column: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1\")\n\t\t.get(table, column);\n\treturn row !== undefined;\n}\n\n/** Additive only: old event IDs, payloads and provenance remain untouched. */\nexport function ensureRawEventCaptureContextSchema(db: Database): void {\n\tif (isReadonlyDatabase(db) || !tableExists(db, \"raw_events\")) return;\n\tconst indexExists = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_raw_events_capture_context'\",\n\t\t)\n\t\t.get();\n\tif (columnExists(db, \"raw_events\", \"capture_context_json\") && indexExists) return;\n\tdb.transaction(() => {\n\t\tif (!columnExists(db, \"raw_events\", \"capture_context_json\")) {\n\t\t\tdb.exec(\"ALTER TABLE raw_events ADD COLUMN capture_context_json TEXT\");\n\t\t}\n\t\tif (\n\t\t\t[\"source\", \"stream_id\", \"event_seq\"].every((column) => columnExists(db, \"raw_events\", column))\n\t\t) {\n\t\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_raw_events_capture_context\n\t\t\t\tON raw_events(source, stream_id, event_seq) WHERE capture_context_json IS NOT NULL`);\n\t\t}\n\t}).immediate();\n}\n\n/**\n * Run `bootstrapSchema` on a database only if it's still at the unbootstrapped\n * state (`user_version === 0`). `connect()` now calls this by default for\n * writable handles, but explicit callers may still use it directly. Idempotent:\n * already-initialized databases are left untouched.\n */\nexport function ensureSchemaBootstrapped(db: Database): void {\n\tif (!isReadonlyDatabase(db) && canAutoBootstrapSchema(db)) {\n\t\tbootstrapSchema(db);\n\t}\n}\n\nexport function canAutoBootstrapSchema(db: Database): boolean {\n\treturn getSchemaVersion(db) === 0 && isSafeEmptyDatabase(db);\n}\n\nfunction isReadonlyDatabase(db: Database): boolean {\n\treturn (db as { readonly?: boolean }).readonly === true;\n}\n","/**\n * Database connection and schema primitives for the codemem store.\n *\n * Owns the `connect()` helper (pragmas, WAL mode, sqlite-vec loading, legacy\n * path migration) and the schema-version introspection helpers\n * (`getSchemaVersion`, `assertSchemaReady`, `ensureAdditiveSchemaCompatibility`,\n * `ensurePlannerStats`). Schema bootstrap DDL lives in `schema-bootstrap.ts`;\n * `connect()` now enforces the fresh-database bootstrap invariant.\n */\n\nimport {\n\tcloseSync,\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport type { Database as DatabaseType } from \"better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport {\n\tgetSchemaVersion,\n\tIDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL,\n\tidentityDeviceAssignmentTriggersCurrent,\n\tREQUIRED_BOOTSTRAPPED_TABLES,\n\tREQUIRED_TABLES,\n\tSCHEMA_VERSION,\n} from \"./database-runtime-primitives.js\";\nimport { ensureMemoryOwnershipSchemas } from \"./memory-ownership-recovery-schema.js\";\nimport { expandUserPath } from \"./observer-config.js\";\nimport { ensureRepositoryDiscoveryIndex } from \"./repository-discovery-index.js\";\nimport {\n\tcanAutoBootstrapSchema,\n\tensureLegacyTeamSetupDraftSchema,\n\tensureMemoryAggregateIndex,\n\tensureRawEventCaptureContextSchema,\n\tensureRetrievalLedgerSchema,\n\tensureSchemaBootstrapped,\n\tensureSyncPeerSignatureStateSchema,\n} from \"./schema-bootstrap.js\";\nimport { ensureUsageEventsAggregateIndex } from \"./usage-aggregate-index.js\";\nimport { ensureVectorCorpusEpoch } from \"./vector-corpus-epoch.js\";\n\nexport {\n\tgetSchemaVersion,\n\tIDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL,\n\tisEmbeddingDisabled,\n\tloadSqliteVec,\n\tREQUIRED_BOOTSTRAPPED_TABLES,\n\tSCHEMA_VERSION,\n} from \"./database-runtime-primitives.js\";\n// Re-export the Database type for consumers\nexport type { DatabaseType as Database };\n\n/**\n * Minimum schema version the TS runtime can operate with.\n * Per the coexistence contract (docs/plans/2026-03-15-db-coexistence-contract.md),\n * TS must tolerate additive newer schemas. It only hard-fails if the schema is\n * too old to have the tables/columns it needs.\n */\nexport const MIN_COMPATIBLE_SCHEMA = 6;\n\n/** Marker file written after the first successful TS access to a DB. */\nconst TS_MARKER = \".codemem-ts-accessed\";\n\n/** Lock file to avoid concurrent first-access backups. */\nconst TS_BACKUP_LOCK = \".codemem-ts-backup.lock\";\n\n/** Consider a backup lock stale after 15 minutes. */\nconst TS_BACKUP_LOCK_STALE_MS = 15 * 60 * 1000;\n\ninterface BackupLockAcquireResult {\n\tfd: number | null;\n\tcontention: boolean;\n}\n\nfunction acquireBackupLock(lockPath: string): BackupLockAcquireResult {\n\tmkdirSync(dirname(lockPath), { recursive: true });\n\ttry {\n\t\treturn { fd: openSync(lockPath, \"wx\"), contention: false };\n\t} catch (err) {\n\t\tconst code = err && typeof err === \"object\" ? (err as NodeJS.ErrnoException).code : undefined;\n\t\tif (code === \"EEXIST\") {\n\t\t\tlet stale = false;\n\t\t\ttry {\n\t\t\t\tconst ageMs = Date.now() - statSync(lockPath).mtimeMs;\n\t\t\t\tstale = Number.isFinite(ageMs) && ageMs > TS_BACKUP_LOCK_STALE_MS;\n\t\t\t} catch {\n\t\t\t\t// If we can't read lock metadata, treat as live contention.\n\t\t\t}\n\n\t\t\tif (!stale) {\n\t\t\t\treturn { fd: null, contention: true };\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tunlinkSync(lockPath);\n\t\t\t} catch (unlinkErr) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[codemem] Warning: failed to clear stale backup lock at ${lockPath}:`,\n\t\t\t\t\tunlinkErr,\n\t\t\t\t);\n\t\t\t\treturn { fd: null, contention: false };\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn { fd: openSync(lockPath, \"wx\"), contention: false };\n\t\t\t} catch (retryErr) {\n\t\t\t\tconst retryCode =\n\t\t\t\t\tretryErr && typeof retryErr === \"object\"\n\t\t\t\t\t\t? (retryErr as NodeJS.ErrnoException).code\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (retryCode === \"EEXIST\") {\n\t\t\t\t\treturn { fd: null, contention: true };\n\t\t\t\t}\n\t\t\t\tconsole.error(`[codemem] Warning: failed to acquire backup lock at ${lockPath}:`, retryErr);\n\t\t\t\treturn { fd: null, contention: false };\n\t\t\t}\n\t\t}\n\n\t\tconsole.error(`[codemem] Warning: failed to acquire backup lock at ${lockPath}:`, err);\n\t\treturn { fd: null, contention: false };\n\t}\n}\n\n/** Default database path — matches Python's DEFAULT_DB_PATH. */\nexport const DEFAULT_DB_PATH = join(homedir(), \".codemem\", \"mem.sqlite\");\n\n/**\n * Resolve the database path from explicit arg → CODEMEM_DB env → default.\n * All TS entry points should use this instead of hardcoding fallback logic.\n */\nexport function resolveDbPath(explicit?: string): string {\n\tif (explicit) return expandUserPath(explicit);\n\tconst envPath = process.env.CODEMEM_DB;\n\tif (envPath) return expandUserPath(envPath);\n\treturn DEFAULT_DB_PATH;\n}\n\n/** Legacy database paths that may exist from older installs. */\nconst LEGACY_DB_PATHS = [\n\tjoin(homedir(), \".codemem.sqlite\"),\n\tjoin(homedir(), \".opencode-mem.sqlite\"),\n];\n\n/** WAL sidecar extensions for a SQLite database file. */\nconst SIDECAR_EXTENSIONS = [\"-wal\", \"-shm\"];\n\n/**\n * Move a file and its WAL sidecars to a new location.\n * Falls back to copy+delete if rename fails (cross-device).\n */\nfunction moveWithSidecars(src: string, dst: string): void {\n\tmkdirSync(dirname(dst), { recursive: true });\n\tconst pairs: [string, string][] = [\n\t\t[src, dst],\n\t\t...SIDECAR_EXTENSIONS.map((ext): [string, string] => [src + ext, dst + ext]),\n\t];\n\tfor (const [srcPath, dstPath] of pairs) {\n\t\tif (!existsSync(srcPath)) continue;\n\t\ttry {\n\t\t\trenameSync(srcPath, dstPath);\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tcopyFileSync(srcPath, dstPath);\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(srcPath);\n\t\t\t\t} catch {\n\t\t\t\t\t// Best effort — original left in place\n\t\t\t\t}\n\t\t\t} catch (copyErr) {\n\t\t\t\t// TOCTOU: source vanished between existsSync and copy (concurrent migration).\n\t\t\t\t// If target now exists, another process already migrated — that's fine.\n\t\t\t\tif (existsSync(dstPath)) continue;\n\t\t\t\tthrow copyErr;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Migrate legacy database paths to the current default location.\n *\n * Only runs when dbPath is the DEFAULT_DB_PATH and doesn't already exist.\n * Matches Python's migrate_legacy_default_db in db.py.\n */\nexport function migrateLegacyDbPath(dbPath: string): void {\n\tif (dbPath !== DEFAULT_DB_PATH) return;\n\tif (existsSync(dbPath)) return;\n\n\tfor (const legacyPath of LEGACY_DB_PATHS) {\n\t\tif (!existsSync(legacyPath)) continue;\n\t\tmoveWithSidecars(legacyPath, dbPath);\n\t\treturn;\n\t}\n}\n\n/**\n * Open a better-sqlite3 connection with the standard codemem pragmas.\n *\n * Migrates legacy DB paths if needed, creates parent directories,\n * sets WAL mode, busy timeout, foreign keys, and bootstraps the schema when\n * opening a brand-new or otherwise uninitialized writable database.\n */\nexport function connect(dbPath: string = DEFAULT_DB_PATH): DatabaseType {\n\tmigrateLegacyDbPath(dbPath);\n\tmkdirSync(dirname(dbPath), { recursive: true });\n\tconst db = new Database(dbPath);\n\ttry {\n\t\t// Match Python's connect() pragmas exactly\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\tconst configureWal = canAutoBootstrapSchema(db) || hasBootstrappedCodememSchema(db);\n\n\t\tensureSchemaBootstrapped(db);\n\t\tif (!configureWal) return db;\n\n\t\t// In-memory databases cannot use WAL (SQLite reports \"memory\") and have\n\t\t// no cross-process readers, so skip the pragma and its warning.\n\t\tif (!db.memory) {\n\t\t\tconst journalMode = db.pragma(\"journal_mode = WAL\", { simple: true }) as string;\n\t\t\tif (journalMode.toLowerCase() !== \"wal\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`Failed to enable WAL mode (got ${journalMode}). Concurrent access may not work correctly.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tdb.pragma(\"synchronous = NORMAL\");\n\n\t\t// Read tuning for large (multi-GB) databases. The SQLite defaults — a\n\t\t// ~2 MiB page cache and no mmap — force repeated disk/page-cache reads of\n\t\t// B-tree interior pages on every non-trivial query. A 64 MiB cache, 1 GiB\n\t\t// memory-mapped I/O, and in-memory temp B-trees cut that cost. These are\n\t\t// per-connection and must be set here (they do not persist in the file).\n\t\tdb.pragma(\"cache_size = -65536\");\n\t\tdb.pragma(\"mmap_size = 1073741824\");\n\t\tdb.pragma(\"temp_store = MEMORY\");\n\n\t\treturn db;\n\t} catch (error) {\n\t\tdb.close();\n\t\tthrow error;\n\t}\n}\n\n/**\n * Open an EXISTING database read-only.\n *\n * Unlike {@link connect}, this never creates the parent directory, never opens\n * for writing, and never enables WAL or runs schema bootstrap — so it works on\n * read-only snapshots and read-only directories (e.g. a copied audit snapshot).\n * Read-tuning pragmas are still applied because they are per-connection and do\n * not write to the file. Schema readiness is validated read-only.\n */\nexport interface ReadOnlyConnectionOptions {\n\twarn?: (message: string) => void;\n}\n\nexport function connectReadOnly(\n\tdbPath: string = DEFAULT_DB_PATH,\n\toptions: ReadOnlyConnectionOptions = {},\n): DatabaseType {\n\tconst db = new Database(dbPath, { readonly: true, fileMustExist: true });\n\ttry {\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\t// Read tuning only — safe on a read-only connection (per-connection state).\n\t\tdb.pragma(\"cache_size = -65536\");\n\t\tdb.pragma(\"mmap_size = 1073741824\");\n\t\tdb.pragma(\"temp_store = MEMORY\");\n\t\tassertSchemaReadyReadOnly(db, options.warn);\n\t\treturn db;\n\t} catch (error) {\n\t\tdb.close();\n\t\tthrow error;\n\t}\n}\n\n/**\n * Validate schema readiness without any writes (no bootstrap, no migration).\n * Mirrors {@link assertSchemaReady} but is safe on read-only connections.\n */\nexport function assertSchemaReadyReadOnly(\n\tdb: DatabaseType,\n\twarn: (message: string) => void = console.warn,\n): void {\n\tconst version = getSchemaVersion(db);\n\tif (version === 0) {\n\t\tthrow new Error(\n\t\t\t\"Database schema is not initialized (read-only open). \" +\n\t\t\t\t\"Point at an initialized codemem database.\",\n\t\t);\n\t}\n\tif (version < MIN_COMPATIBLE_SCHEMA) {\n\t\tthrow new Error(\n\t\t\t`Database schema version ${version} is older than minimum compatible (${MIN_COMPATIBLE_SCHEMA}).`,\n\t\t);\n\t}\n\tif (version > SCHEMA_VERSION) {\n\t\twarn(\n\t\t\t`Database schema version ${version} is newer than this TS runtime (${SCHEMA_VERSION}). ` +\n\t\t\t\t\"Running in read-only compatibility mode.\",\n\t\t);\n\t}\n\tconst missing = REQUIRED_TABLES.filter((t) => !tableExists(db, t));\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Required tables missing: ${missing.join(\", \")}. ` +\n\t\t\t\t\"The database may be corrupt or from an incompatible version.\",\n\t\t);\n\t}\n}\n\nfunction hasBootstrappedCodememSchema(db: DatabaseType): boolean {\n\treturn REQUIRED_BOOTSTRAPPED_TABLES.every((table) => tableExists(db, table));\n}\n\nfunction hasPlannerStats(db: DatabaseType): boolean {\n\ttry {\n\t\treturn !!db.prepare(\"SELECT 1 FROM sqlite_stat1 LIMIT 1\").pluck().get();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Keep SQLite planner statistics healthy for FTS-heavy queries.\n *\n * We always run PRAGMA optimize as a cheap maintenance hint. If planner\n * statistics have never been collected and the core search tables exist,\n * bootstrap them with ANALYZE so Node SQLite picks stable FTS query plans.\n */\nexport function ensurePlannerStats(db: DatabaseType): void {\n\t// Statistics are only a planner hint. Never wait on another writer for\n\t// them: skip this open and let a later open refresh them.\n\twithoutBusyWait(db, () => {\n\t\tdb.pragma(\"optimize\");\n\n\t\tif (hasPlannerStats(db)) return;\n\t\tif (!tableExists(db, \"memory_items\") || !tableExists(db, \"memory_fts\")) return;\n\n\t\tdb.exec(\"ANALYZE\");\n\t\tdb.pragma(\"optimize\");\n\t});\n}\n\nfunction isSqliteBusy(error: unknown): boolean {\n\tconst code = (error as { code?: unknown } | null)?.code;\n\treturn code === \"SQLITE_BUSY\" || code === \"SQLITE_LOCKED\";\n}\n\n/** Refresh planner hints if the database is free; never waits on another writer. */\nexport function optimizeWithoutWaiting(db: DatabaseType): void {\n\twithoutBusyWait(db, () => db.pragma(\"optimize\"));\n}\n\n/** Run optional write work without waiting on locks; skip it if the database is busy. */\nfunction withoutBusyWait(db: DatabaseType, work: () => void): void {\n\tconst previous = db.pragma(\"busy_timeout\", { simple: true }) as number;\n\tdb.pragma(\"busy_timeout = 0\");\n\ttry {\n\t\twork();\n\t} catch (error) {\n\t\tif (!isSqliteBusy(error)) throw error;\n\t} finally {\n\t\tdb.pragma(`busy_timeout = ${Number(previous) || 0}`);\n\t}\n}\n\n/**\n * Create a timestamped backup of the database on first TS access.\n *\n * The backup file is named `mem.sqlite.pre-ts-YYYYMMDDTHHMMSS.bak` and placed\n * next to the original. A marker file prevents repeated backups. This ensures\n * users can recover if the TS runtime introduces bugs that corrupt the DB\n * during the migration period.\n */\nexport function backupOnFirstAccess(dbPath: string): void {\n\tconst markerPath = join(dirname(dbPath), TS_MARKER);\n\tif (existsSync(markerPath)) return;\n\n\t// Find the actual DB file to back up. It may be at the target path already,\n\t// or at a legacy location that migrateLegacyDbPath() will move later.\n\t// Back up whichever exists BEFORE migration runs.\n\tlet sourceDbPath = dbPath;\n\tif (!existsSync(dbPath)) {\n\t\t// Check legacy locations — same order as migrateLegacyDbPath()\n\t\tconst legacyPaths = [\n\t\t\tjoin(dirname(dbPath), \"..\", \".codemem.sqlite\"),\n\t\t\tjoin(dirname(dbPath), \"..\", \".opencode-mem.sqlite\"),\n\t\t];\n\t\tconst legacyPath = legacyPaths.find((p) => existsSync(p));\n\t\tif (legacyPath) {\n\t\t\tsourceDbPath = legacyPath;\n\t\t} else {\n\t\t\treturn; // Fresh DB, nothing to back up\n\t\t}\n\t}\n\n\tconst lockPath = join(dirname(dbPath), TS_BACKUP_LOCK);\n\tconst { fd: lockFd, contention } = acquireBackupLock(lockPath);\n\tif (contention) {\n\t\t// Another process is handling first-access backup.\n\t\treturn;\n\t}\n\n\tconst writeMarker = (): void => {\n\t\ttry {\n\t\t\tmkdirSync(dirname(markerPath), { recursive: true });\n\t\t\twriteFileSync(markerPath, new Date().toISOString(), \"utf-8\");\n\t\t} catch {\n\t\t\t// Non-fatal — worst case we attempt backup again later.\n\t\t}\n\t};\n\n\tconst hasViableExistingBackup = (): boolean => {\n\t\tlet sourceSize = 0;\n\t\ttry {\n\t\t\tsourceSize = statSync(sourceDbPath).size;\n\t\t} catch {\n\t\t\tsourceSize = 0;\n\t\t}\n\t\tconst minViableSize = sourceSize > 0 ? Math.floor(sourceSize * 0.9) : 1;\n\t\tconst prefix = `${basename(sourceDbPath)}.pre-ts-`;\n\t\ttry {\n\t\t\tconst entries = readdirSync(dirname(sourceDbPath));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (!entry.startsWith(prefix) || !entry.endsWith(\".bak\")) continue;\n\t\t\t\tconst fullPath = join(dirname(sourceDbPath), entry);\n\t\t\t\ttry {\n\t\t\t\t\tif (statSync(fullPath).size >= minViableSize) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore races while inspecting backup candidates.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore directory read errors — proceed with normal backup path.\n\t\t}\n\t\treturn false;\n\t};\n\n\tconst ts = new Date().toISOString().replace(/[:.]/g, \"\").slice(0, 15);\n\tconst backupPath = `${sourceDbPath}.pre-ts-${ts}.bak`;\n\tlet backupSucceeded = false;\n\ttry {\n\t\tif (existsSync(markerPath)) return;\n\t\tif (hasViableExistingBackup()) {\n\t\t\twriteMarker();\n\t\t\treturn;\n\t\t}\n\n\t\tcopyFileSync(sourceDbPath, backupPath);\n\t\t// Also back up WAL/SHM if present (they contain uncommitted data)\n\t\tconst walPath = `${sourceDbPath}-wal`;\n\t\tconst shmPath = `${sourceDbPath}-shm`;\n\t\tif (existsSync(walPath)) copyFileSync(walPath, `${backupPath}-wal`);\n\t\tif (existsSync(shmPath)) copyFileSync(shmPath, `${backupPath}-shm`);\n\t\tconsole.error(`[codemem] First TS access — backed up database to ${backupPath}`);\n\t\tbackupSucceeded = true;\n\t} catch (err) {\n\t\tconsole.error(`[codemem] Warning: failed to create backup at ${backupPath}:`, err);\n\t\t// Continue — backup failure shouldn't prevent operation, but don't write marker\n\t} finally {\n\t\tif (lockFd != null) {\n\t\t\ttry {\n\t\t\t\tcloseSync(lockFd);\n\t\t\t} catch {\n\t\t\t\t// Ignore close errors.\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tunlinkSync(lockPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore lock cleanup errors.\n\t\t\t}\n\t\t}\n\t}\n\n\t// Only write marker after backup succeeds — a transient failure should\n\t// retry on next access, not permanently suppress the safety net.\n\tif (backupSucceeded) {\n\t\twriteMarker();\n\t}\n}\n\n/**\n * Verify the database schema is initialized and compatible.\n *\n * Empty writable first-run handles are bootstrapped here as a final safety net,\n * even though `connect()` already does the same. A few lower-level maintenance\n * and integration paths call this assertion after receiving an existing database\n * handle, so keeping the bootstrap invariant here prevents one entry point from\n * requiring a manual `codemem db init` while another works automatically.\n *\n * Per the coexistence contract: TS tolerates additive newer schemas (Python may\n * have run migrations that add tables/columns the TS runtime doesn't know about).\n * TS only hard-fails if:\n * - Schema is still uninitialized after a bootstrap attempt (version 0)\n * - Schema is too old (below MIN_COMPATIBLE_SCHEMA)\n * - Required tables are missing\n * - FTS5 index is missing (needed for search)\n *\n * Warns (but continues) if schema is newer than SCHEMA_VERSION — the additive\n * changes are assumed safe per the coexistence contract.\n */\nexport function assertSchemaReady(db: DatabaseType): void {\n\tensureSchemaBootstrapped(db);\n\tconst version = getSchemaVersion(db);\n\tif (version === 0) {\n\t\tthrow new Error(\n\t\t\t\"Database schema is not initialized. \" +\n\t\t\t\t\"Initialize the SQLite database with the current TypeScript runtime before retrying.\",\n\t\t);\n\t}\n\tif (version < MIN_COMPATIBLE_SCHEMA) {\n\t\tthrow new Error(\n\t\t\t`Database schema version ${version} is older than minimum compatible (${MIN_COMPATIBLE_SCHEMA}). ` +\n\t\t\t\t\"Upgrade the database schema with the current TypeScript runtime before retrying.\",\n\t\t);\n\t}\n\tif (version > SCHEMA_VERSION) {\n\t\tconsole.warn(\n\t\t\t`Database schema version ${version} is newer than this TS runtime (${SCHEMA_VERSION}). ` +\n\t\t\t\t\"Running in compatibility mode — additive schema changes are tolerated.\",\n\t\t);\n\t}\n\n\t// Validate required tables exist (catches corrupt or partially migrated DBs)\n\tconst missing = REQUIRED_TABLES.filter((t) => !tableExists(db, t));\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Required tables missing: ${missing.join(\", \")}. ` +\n\t\t\t\t\"The database may be corrupt or from an incompatible version.\",\n\t\t);\n\t}\n\n\t// FTS5 index is required for search\n\tif (!tableExists(db, \"memory_fts\")) {\n\t\tthrow new Error(\n\t\t\t\"FTS5 index (memory_fts) is missing. \" +\n\t\t\t\t\"Rebuild the database schema with the current TypeScript runtime before retrying.\",\n\t\t);\n\t}\n}\n\n/** Check if a table exists in the database. */\nexport function tableExists(db: DatabaseType, table: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(table);\n\treturn row !== undefined;\n}\n\n/** Check if a column exists in a table. */\nexport function columnExists(db: DatabaseType, table: string, column: string): boolean {\n\tif (!tableExists(db, table)) return false;\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1\")\n\t\t.get(table, column);\n\treturn row !== undefined;\n}\n\nfunction addColumnIfMissing(\n\tdb: DatabaseType,\n\ttable: string,\n\tname: string,\n\tdefinition: string,\n): void {\n\tif (columnExists(db, table, name)) return;\n\ttry {\n\t\tdb.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${definition}`);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\tif (message.includes(\"duplicate column name\") && columnExists(db, table, name)) {\n\t\t\treturn;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nconst RECIPIENT_POLICY_DEVICE_ELIGIBILITY_COMPATIBILITY_ERROR =\n\t\"recipient_policy_device_eligibility_schema_incompatible\";\n\nfunction ensureIdentityDeviceAssignmentVersionTriggers(db: DatabaseType): void {\n\tif (\n\t\t!tableExists(db, \"identity_devices\") ||\n\t\t!columnExists(db, \"identity_devices\", \"identity_id\") ||\n\t\t!columnExists(db, \"identity_devices\", \"assignment_version\") ||\n\t\t!tableExists(db, \"policy_team_device_decisions\") ||\n\t\t!columnExists(db, \"policy_team_device_decisions\", \"device_id\")\n\t) {\n\t\treturn;\n\t}\n\t// Rewriting needs the write lock; skip it when both triggers are already\n\t// current so read-only opens do not block behind long write transactions.\n\tif (identityDeviceAssignmentTriggersCurrent(db)) return;\n\tdb.transaction(() => db.exec(IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL)).immediate();\n}\n\nfunction ensureDeviceIdentityBindingAuditSchema(db: DatabaseType): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS device_identity_binding_commits (\n\t\t\tcommit_digest TEXT PRIMARY KEY NOT NULL,\n\t\t\treviewed_inventory_digest TEXT NOT NULL,\n\t\t\trequest_json TEXT NOT NULL,\n\t\t\toutcomes_json TEXT NOT NULL,\n\t\t\twrite_count INTEGER NOT NULL,\n\t\t\tdecided_by_identity_id TEXT NOT NULL,\n\t\t\tdecided_by_device_id TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS device_identity_binding_audit (\n\t\t\tevent_id TEXT PRIMARY KEY NOT NULL,\n\t\t\tcommit_digest TEXT NOT NULL REFERENCES device_identity_binding_commits(commit_digest),\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tprevious_identity_id TEXT,\n\t\t\ttarget_identity_id TEXT NOT NULL,\n\t\t\taction TEXT NOT NULL,\n\t\t\tprevious_assignment_version INTEGER,\n\t\t\tresulting_assignment_version INTEGER NOT NULL,\n\t\t\tdecided_by_identity_id TEXT NOT NULL,\n\t\t\tdecided_by_device_id TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_device_identity_binding_audit_commit_device\n\t\t\tON device_identity_binding_audit(commit_digest, device_id);\n\t\tCREATE INDEX IF NOT EXISTS idx_device_identity_binding_audit_device_created\n\t\t\tON device_identity_binding_audit(device_id, created_at, event_id);\n\t`);\n}\n\n/**\n * Create the (created_at, id) keyset index that vector backfill paging relies on.\n * Runs unconditionally rather than inside the SCHEMA_VERSION-gated compat block:\n * databases already marked at the current SCHEMA_VERSION would otherwise skip it\n * forever and keep paying the temporary-sort cost during inactive backfills.\n */\nfunction ensureMemoryItemsPagingIndex(db: DatabaseType): void {\n\tif (!tableExists(db, \"memory_items\")) return;\n\ttry {\n\t\tdb.exec(\n\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_created_id ON memory_items(created_at, id)\",\n\t\t);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\n/**\n * Create the (started_at, id) keyset index that newest-first candidate scans\n * rely on (listProjectScopeCandidates). Same rationale as the memory_items\n * paging index: run unconditionally so databases already at the current\n * SCHEMA_VERSION pick it up instead of re-sorting sessions on every page.\n */\nfunction ensureSessionsPagingIndex(db: DatabaseType): void {\n\tif (!tableExists(db, \"sessions\")) return;\n\ttry {\n\t\tdb.exec(\"CREATE INDEX IF NOT EXISTS idx_sessions_started_id ON sessions(started_at, id)\");\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction ensureSyncAttemptsDiagnosticIndexes(db: DatabaseType): void {\n\tif (!tableExists(db, \"sync_attempts\")) return;\n\ttry {\n\t\tdb.exec(`\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_attempts_occurred\n\t\t\t\tON sync_attempts(\n\t\t\t\t\tCASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n\t\t\t\t\tid\n\t\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_attempts_error_occurred\n\t\t\t\tON sync_attempts(\n\t\t\t\t\tCASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n\t\t\t\t\tid\n\t\t\t\t)\n\t\t\t\tWHERE ok = 0;\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_attempts_success_occurred\n\t\t\t\tON sync_attempts(\n\t\t\t\t\tCASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n\t\t\t\t\tid\n\t\t\t\t)\n\t\t\t\tWHERE ok <> 0;\n\t\t`);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction ensureRawEventSessionsPendingIndex(db: DatabaseType): void {\n\tif (!tableExists(db, \"raw_event_sessions\")) return;\n\ttry {\n\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_raw_event_sessions_pending_updated\n\t\t\tON raw_event_sessions(updated_at)\n\t\t\tWHERE last_received_event_seq > last_flushed_event_seq`);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction ensureFlushBatchDiagnosticIndexes(db: DatabaseType): void {\n\tif (!tableExists(db, \"raw_event_flush_batches\")) return;\n\ttry {\n\t\tdb.exec(`\n\t\t\tCREATE INDEX IF NOT EXISTS idx_flush_batches_observer_status_updated\n\t\t\t\tON raw_event_flush_batches(status, updated_at)\n\t\t\t\tWHERE observer_provider IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS idx_flush_batches_capture_status_updated\n\t\t\t\tON raw_event_flush_batches(status, updated_at)\n\t\t\t\tWHERE observer_provider IS NULL;\n\t\t`);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction assertRecipientPolicyDeviceEligibilityCompatibility(db: DatabaseType): void {\n\tconst recipientPolicySchemaPresent = [\n\t\t\"policy_teams\",\n\t\t\"policy_team_memberships\",\n\t\t\"identity_devices\",\n\t\t\"project_recipients\",\n\t\t\"policy_team_device_decisions\",\n\t].some((table) => tableExists(db, table));\n\tif (!recipientPolicySchemaPresent) return;\n\n\tconst missing: string[] = [];\n\tfor (const [table, column] of [\n\t\t[\"policy_teams\", \"device_eligibility_mode\"],\n\t\t[\"identity_devices\", \"assignment_version\"],\n\t] as const) {\n\t\ttry {\n\t\t\tif (!columnExists(db, table, column)) missing.push(`${table}.${column}`);\n\t\t} catch {\n\t\t\tmissing.push(`${table}.${column}`);\n\t\t}\n\t}\n\tfor (const column of [\"team_id\", \"device_id\", \"decision\", \"assignment_version\"]) {\n\t\ttry {\n\t\t\tif (!columnExists(db, \"policy_team_device_decisions\", column)) {\n\t\t\t\tmissing.push(`policy_team_device_decisions.${column}`);\n\t\t\t}\n\t\t} catch {\n\t\t\tmissing.push(`policy_team_device_decisions.${column}`);\n\t\t}\n\t}\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`${RECIPIENT_POLICY_DEVICE_ELIGIBILITY_COMPATIBILITY_ERROR}:${missing.join(\",\")}`,\n\t\t);\n\t}\n}\n\n/**\n * Repair display-only peer version metadata independently of the compatibility\n * marker because these additive columns intentionally do not bump the schema.\n */\nfunction ensureSyncPeerRuntimeVersionColumns(db: DatabaseType): void {\n\tif (!tableExists(db, \"sync_peers\")) return;\n\taddColumnIfMissing(db, \"sync_peers\", \"runtime_version\", \"TEXT\");\n\taddColumnIfMissing(db, \"sync_peers\", \"runtime_version_observed_at\", \"TEXT\");\n}\n\n/** Add the structured sync-attempt failure category without a schema-version bump. */\nexport function ensureSyncAttemptFailureCategoryColumn(db: DatabaseType): void {\n\tif (!tableExists(db, \"sync_attempts\")) return;\n\taddColumnIfMissing(db, \"sync_attempts\", \"failure_category\", \"TEXT\");\n}\n\n/** Persist a direct-peer signature version only when it advances the peer's observed maximum. */\nexport function recordHighestObservedDirectSignatureVersion(\n\tdb: DatabaseType,\n\tpeerDeviceId: string,\n\tversion: number,\n): boolean {\n\tif (!Number.isSafeInteger(version) || version < 1) {\n\t\tthrow new RangeError(\"Direct signature version must be a positive safe integer\");\n\t}\n\treturn db.transaction(() => {\n\t\tconst result = db\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO sync_peer_signature_state(\n\t\t\t\t\tpeer_device_id, highest_observed_direct_signature_version\n\t\t\t\t )\n\t\t\t\t SELECT ?, ?\n\t\t\t\t WHERE EXISTS (\n\t\t\t\t\tSELECT 1 FROM sync_peers WHERE peer_device_id = ?\n\t\t\t\t )\n\t\t\t\t ON CONFLICT(peer_device_id) DO UPDATE SET\n\t\t\t\t\thighest_observed_direct_signature_version = excluded.highest_observed_direct_signature_version\n\t\t\t\t WHERE sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t\t\t< excluded.highest_observed_direct_signature_version`,\n\t\t\t)\n\t\t\t.run(peerDeviceId, version, peerDeviceId);\n\t\t// Retain the additive column as a compatibility mirror for older runtimes.\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers\n\t\t\t SET highest_observed_direct_signature_version = ?\n\t\t\t WHERE peer_device_id = ?\n\t\t\t AND (\n\t\t\t\t highest_observed_direct_signature_version IS NULL\n\t\t\t\t OR highest_observed_direct_signature_version < ?\n\t\t\t )`,\n\t\t).run(version, peerDeviceId, version);\n\t\treturn result.changes > 0;\n\t})();\n}\n\n/**\n * Has the additive compatibility shim already run for the current SCHEMA_VERSION?\n *\n * Fail-safe: returns false on any error (including a missing\n * `schema_compat_state` table) so the shim re-runs rather than skipping needed\n * additive DDL on uncertainty. Keyed on SCHEMA_VERSION so a future runtime with\n * a higher SCHEMA_VERSION (and new additive DDL) sees the older marker and\n * re-applies.\n */\nfunction schemaCompatAlreadyApplied(db: DatabaseType): boolean {\n\ttry {\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT applied_schema_version AS v FROM schema_compat_state WHERE id = 1 LIMIT 1\")\n\t\t\t.get() as { v: number } | undefined;\n\t\treturn typeof row?.v === \"number\" && row.v >= SCHEMA_VERSION;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Record that the additive compatibility shim has been applied for the current\n * SCHEMA_VERSION. Fail-open: a failed mark just means the shim re-runs on the\n * next open, which is harmless because the DDL is idempotent.\n */\nfunction markSchemaCompatApplied(db: DatabaseType): void {\n\ttry {\n\t\tdb.prepare(\n\t\t\t`INSERT INTO schema_compat_state(id, applied_schema_version, applied_at)\n\t\t\t VALUES (1, ?, ?)\n\t\t\t ON CONFLICT(id) DO UPDATE SET\n\t\t\t\t applied_schema_version = excluded.applied_schema_version,\n\t\t\t\t applied_at = excluded.applied_at`,\n\t\t).run(SCHEMA_VERSION, new Date().toISOString());\n\t} catch {\n\t\t// Fail-open: a missed mark only costs one extra idempotent re-run.\n\t}\n}\n\n/**\n * Backfill the denormalized memory_items.project column from sessions.project.\n *\n * Runs on EVERY store open (not gated behind the schema-compat marker) because\n * moveMemoryProject edits sessions.project and relies on this backfill plus a\n * reader-fallback to propagate the new project to legacy rows whose project is\n * still NULL. Idempotent — only touches rows where project IS NULL.\n */\nfunction backfillMemoryItemProject(db: DatabaseType): void {\n\ttry {\n\t\t// Only take the write lock when some row can actually gain a project.\n\t\tconst pending = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT 1 FROM memory_items AS m\n\t\t\t\t JOIN sessions AS s ON s.id = m.session_id\n\t\t\t\t WHERE m.project IS NULL AND s.project IS NOT NULL\n\t\t\t\t LIMIT 1`,\n\t\t\t)\n\t\t\t.get();\n\t\tif (!pending) return;\n\t\tdb.exec(`UPDATE memory_items\n\t\t\t SET project = (\n\t\t\t\t SELECT s.project FROM sessions s\n\t\t\t\t WHERE s.id = memory_items.session_id\n\t\t\t )\n\t\t\t WHERE project IS NULL`);\n\t} catch {\n\t\t// Best-effort backfill — readers fall back to sessions.project\n\t\t// when memory_items.project is null.\n\t}\n}\n\n/**\n * Apply additive compatibility fixes for legacy TS-era schemas.\n *\n * These are safe, one-way `ALTER TABLE ... ADD COLUMN` updates used to\n * prevent runtime failures when older local databases are missing columns\n * introduced in later releases.\n *\n * The ~39 idempotent DDL statements are gated behind a `schema_compat_state`\n * marker so steady-state opens skip them: each database runs the shim once\n * (idempotent — a fresh DB's statements are all no-ops), records the marker,\n * and skips thereafter. We deliberately do NOT short-circuit on\n * `user_version >= SCHEMA_VERSION`: additive columns (e.g. memory_items.project)\n * have been added over time WITHOUT bumping SCHEMA_VERSION, so a database can\n * report user_version=SCHEMA_VERSION yet still lack a column the shim adds —\n * the version is not proof the shim ran. Only the marker is. The project\n * backfill still runs on every open regardless of the gate.\n */\nfunction indexColumns(db: DatabaseType, indexName: string): string[] {\n\tconst quoted = indexName.replaceAll('\"', '\"\"');\n\treturn (db.prepare(`PRAGMA index_info(\"${quoted}\")`).all() as Array<{ name?: string }>)\n\t\t.map((row) => String(row.name ?? \"\"))\n\t\t.filter(Boolean);\n}\n\nconst SHARE_OPERATION_EFFECT_ID_INDEX_SQL =\n\t\"CREATE INDEX idx_share_operation_steps_effect_id_nonempty ON share_operation_steps(effect_id) WHERE effect_id <> ''\";\n\nfunction normalizedIndexSql(sql: string): string {\n\treturn sql\n\t\t.replace(/\\s+/g, \" \")\n\t\t.replace(/\\s*\\(\\s*/g, \"(\")\n\t\t.replace(/\\s*\\)\\s*/g, \") \")\n\t\t.trim();\n}\n\n/** True when the partial index exists with exactly the expected definition. */\nfunction shareOperationEffectIdIndexCurrent(db: DatabaseType): boolean {\n\tconst row = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type = 'index' AND name = 'idx_share_operation_steps_effect_id_nonempty'\",\n\t\t)\n\t\t.get() as { sql?: string | null } | undefined;\n\treturn (\n\t\ttypeof row?.sql === \"string\" &&\n\t\tnormalizedIndexSql(row.sql) === normalizedIndexSql(SHARE_OPERATION_EFFECT_ID_INDEX_SQL)\n\t);\n}\n\nfunction repairShareOperationEffectIdIndex(db: DatabaseType): void {\n\tif (\n\t\t!tableExists(db, \"share_operation_steps\") ||\n\t\t!columnExists(db, \"share_operation_steps\", \"effect_id\")\n\t) {\n\t\treturn;\n\t}\n\tconst indexes = db.prepare(\"PRAGMA index_list('share_operation_steps')\").all() as Array<{\n\t\tname: string;\n\t\tunique: number;\n\t}>;\n\tconst hasInlineUniqueEffectId = indexes.some(\n\t\t(index) =>\n\t\t\tindex.unique === 1 &&\n\t\t\tindex.name !== \"idx_share_operation_steps_effect_id_nonempty\" &&\n\t\t\tindexColumns(db, index.name).join(\",\") === \"effect_id\",\n\t);\n\tif (hasInlineUniqueEffectId) {\n\t\tdb.transaction(() => {\n\t\t\tdb.exec(`\n\t\t\t\tDROP INDEX IF EXISTS idx_share_operation_steps_effect_id_nonempty;\n\t\t\t\tALTER TABLE share_operation_steps RENAME TO share_operation_steps_unique_legacy;\n\t\t\t\tCREATE TABLE share_operation_steps (\n\t\t\t\t\toperation_id TEXT NOT NULL,\n\t\t\t\t\tstep_key TEXT NOT NULL,\n\t\t\t\t\teffect_id TEXT NOT NULL,\n\t\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\t\tstarted_at TEXT,\n\t\t\t\t\tcompleted_at TEXT,\n\t\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\t\tsafe_error_code TEXT,\n\t\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (operation_id, step_key)\n\t\t\t\t);\n\t\t\t\tINSERT INTO share_operation_steps(\n\t\t\t\t\toperation_id, step_key, effect_id, status, attempt_count, started_at,\n\t\t\t\t\tcompleted_at, last_attempt_at, safe_error_code, updated_at\n\t\t\t\t) SELECT operation_id, step_key, effect_id, status, attempt_count, started_at,\n\t\t\t\t\tcompleted_at, last_attempt_at, safe_error_code, updated_at\n\t\t\t\tFROM share_operation_steps_unique_legacy;\n\t\t\t\tDROP TABLE share_operation_steps_unique_legacy;\n\t\t\t`);\n\t\t})();\n\t}\n\t// Rebuilding the index takes the write lock; skip it only when the stored\n\t// definition, including its WHERE clause, matches exactly.\n\tif (!hasInlineUniqueEffectId && shareOperationEffectIdIndexCurrent(db)) return;\n\tdb.exec(`\n\t\tDROP INDEX IF EXISTS idx_share_operation_steps_effect_id_nonempty;\n\t\tCREATE INDEX IF NOT EXISTS idx_share_operation_steps_effect_id_nonempty\n\t\t\tON share_operation_steps(effect_id)\n\t\t\tWHERE effect_id <> '';\n\t`);\n}\n\nlet retrievalLedgerSchemaWarningEmitted = false;\n\nfunction ensureOptionalRetrievalLedgerSchema(db: DatabaseType): void {\n\t// This remains outside the compatibility marker gate so a partial legacy\n\t// database can gain its base tables before a later open creates the ledger.\n\ttry {\n\t\tensureRetrievalLedgerSchema(db);\n\t} catch {\n\t\t// The ledger is optional local derived state. A malformed/locked optional\n\t\t// ledger must not prevent the existing store from opening.\n\t\tif (!retrievalLedgerSchemaWarningEmitted) {\n\t\t\tretrievalLedgerSchemaWarningEmitted = true;\n\t\t\tconsole.warn(\n\t\t\t\t\"[codemem] Retrieval evidence storage is unavailable; continuing without attribution data.\",\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction ensureRecipientPolicyAdditiveColumns(db: DatabaseType): void {\n\tfor (const [table, name, definition] of [\n\t\t[\"policy_teams\", \"device_eligibility_mode\", \"TEXT NOT NULL DEFAULT 'person_all_devices'\"],\n\t\t[\"identity_devices\", \"assignment_version\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t[\"policy_team_device_decisions\", \"assignment_version\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t] as const) {\n\t\ttry {\n\t\t\taddColumnIfMissing(db, table, name, definition);\n\t\t} catch {\n\t\t\t// Continue repairing independent recipient-policy columns.\n\t\t}\n\t}\n}\n\nfunction ensureRecipientPolicyWakeColumn(db: DatabaseType): void {\n\t// Earlier compatibility markers could be written after this column failed to\n\t// upgrade. Repair on every open and fail before advancing schema markers.\n\tif (!tableExists(db, \"recipient_policy_authority_states\")) return;\n\taddColumnIfMissing(\n\t\tdb,\n\t\t\"recipient_policy_authority_states\",\n\t\t\"wake_epoch\",\n\t\t\"INTEGER NOT NULL DEFAULT 0\",\n\t);\n}\n\nfunction ensureAlwaysOnSchemaCompatibility(db: DatabaseType): void {\n\tensureVectorCorpusEpoch(db);\n\tif (tableExists(db, \"sync_peers\") && !columnExists(db, \"sync_peers\", \"manual_addresses_json\")) {\n\t\ttry {\n\t\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN manual_addresses_json TEXT\");\n\t\t} catch (error) {\n\t\t\tif (!columnExists(db, \"sync_peers\", \"manual_addresses_json\")) throw error;\n\t\t}\n\t}\n\tif (tableExists(db, \"sync_peers\") && !columnExists(db, \"sync_peers\", \"last_success_address\")) {\n\t\ttry {\n\t\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN last_success_address TEXT\");\n\t\t} catch (error) {\n\t\t\tif (!columnExists(db, \"sync_peers\", \"last_success_address\")) throw error;\n\t\t}\n\t}\n\tensureMemoryOwnershipSchemas(db);\n\tensureOptionalRetrievalLedgerSchema(db);\n\ttry {\n\t\tensureRepositoryDiscoveryIndex(db);\n\t} catch {\n\t\t// Derived discovery evidence is optional; stamping retains its full-scan path.\n\t}\n\tensureRecipientPolicyWakeColumn(db);\n\t// Always run: current-marker databases may predate these no-version-bump\n\t// columns, so the schema_compat_state gate cannot prove they exist.\n\tensureSyncPeerRuntimeVersionColumns(db);\n\tensureSyncAttemptFailureCategoryColumn(db);\n\tensureRawEventCaptureContextSchema(db);\n\tensureSyncPeerSignatureStateSchema(db);\n\tensureDeviceIdentityBindingAuditSchema(db);\n\tensureLegacyTeamSetupDraftSchema(db);\n\tensureMemoryItemsPagingIndex(db);\n\tensureSessionsPagingIndex(db);\n\tensureSyncAttemptsDiagnosticIndexes(db);\n\tensureRawEventSessionsPendingIndex(db);\n}\n\nexport function ensureAdditiveSchemaCompatibility(db: DatabaseType): void {\n\tensureAlwaysOnSchemaCompatibility(db);\n\tapplyAdditiveSchemaCompatibility(db);\n\t// Current-marker databases also need this index, but legacy columns must\n\t// exist before its first creation. Later opens only check sqlite_master.\n\tensureMemoryAggregateIndex(db);\n\tensureUsageEventsAggregateIndex(db);\n}\n\nfunction applyAdditiveSchemaCompatibility(db: DatabaseType): void {\n\tconst compatAlreadyApplied = schemaCompatAlreadyApplied(db);\n\tif (!compatAlreadyApplied) {\n\t\t// IMPORTANT: any NEW DDL added to this gated block REQUIRES bumping\n\t\t// SCHEMA_VERSION. The \"already applied\" marker keys on SCHEMA_VERSION, so\n\t\t// without a bump, legacy DBs already marked at the current version would\n\t\t// skip the new DDL forever.\n\t\t// Marker table must exist before we can mark; create it first.\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\t\tCREATE TABLE IF NOT EXISTS schema_compat_state (\n\t\t\t\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\t\t\t\tapplied_schema_version INTEGER NOT NULL,\n\t\t\t\t\tapplied_at TEXT NOT NULL\n\t\t\t\t)\n\t\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for the marker table.\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS coordinator_enrollment_reconciliation_issues (\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\treference_id TEXT NOT NULL,\n\t\t\t\tcode TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'open',\n\t\t\t\tfirst_seen_at TEXT NOT NULL,\n\t\t\t\tlast_seen_at TEXT NOT NULL,\n\t\t\t\tresolved_at TEXT,\n\t\t\t\toccurrence_count INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (coordinator_id, group_id, kind, reference_id, code)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_boundary_status\n\t\t\t\tON coordinator_enrollment_reconciliation_issues(coordinator_id, group_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_status_recent\n\t\t\t\tON coordinator_enrollment_reconciliation_issues(status, last_seen_at, resolved_at);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_review_resolutions (\n\t\t\t\treview_item_id TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT NOT NULL,\n\t\t\t\tdecision TEXT NOT NULL,\n\t\t\t\tdecision_input_json TEXT NOT NULL,\n\t\t\t\tpreview_json TEXT NOT NULL,\n\t\t\t\tdecided_by_identity_id TEXT NOT NULL,\n\t\t\t\tdecided_by_device_id TEXT NOT NULL,\n\t\t\t\tresolved_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (review_item_id, source_fingerprint)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS policy_teams (\n\t\t\t\tteam_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tdevice_eligibility_mode TEXT NOT NULL DEFAULT 'person_all_devices',\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS policy_team_memberships (\n\t\t\t\tteam_id TEXT NOT NULL,\n\t\t\t\tidentity_id TEXT NOT NULL,\n\t\t\t\trole TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (team_id, identity_id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS identity_devices (\n\t\t\t\tdevice_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tidentity_id TEXT NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tassignment_version INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS policy_team_device_decisions (\n\t\t\t\tteam_id TEXT NOT NULL REFERENCES policy_teams(team_id) ON DELETE CASCADE,\n\t\t\t\tdevice_id TEXT NOT NULL,\n\t\t\t\tdecision TEXT NOT NULL,\n\t\t\t\tassignment_version INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (team_id, device_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_policy_team_device_decisions_device\n\t\t\t\tON policy_team_device_decisions(device_id);\n\t\t\tCREATE TABLE IF NOT EXISTS project_recipients (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\trecipient_kind TEXT NOT NULL,\n\t\t\t\trecipient_id TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\tpolicy_revision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (canonical_project_identity, recipient_kind, recipient_id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_authority_states (\n\t\t\t\tcanonical_project_identity TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tauthority_state TEXT NOT NULL DEFAULT 'legacy',\n\t\t\t\tgeneration INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tdesired_devices_digest TEXT,\n\t\t\t\tcurrent_devices_digest TEXT,\n\t\t\t\tstable_parity_evidence_digest TEXT,\n\t\t\t\tstable_parity_passed_at TEXT,\n\t\t\t\tfresh_snapshot_fingerprint TEXT,\n\t\t\t\tfresh_snapshot_observed_at TEXT,\n\t\t\t\tsafe_error_code TEXT,\n\t\t\t\tstate_changed_at TEXT NOT NULL,\n\t\t\t\tlast_error_at TEXT,\n\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\twake_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_completed_at TEXT,\n\t\t\t\tlease_owner TEXT,\n\t\t\t\tlease_acquired_at TEXT,\n\t\t\t\tlease_expires_at TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_reconciliation_steps (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\tstep_key TEXT NOT NULL,\n\t\t\t\teffect_id TEXT NOT NULL,\n\t\t\t\tpayload_digest TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'pending',\n\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tstarted_at TEXT,\n\t\t\t\tcompleted_at TEXT,\n\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\tsafe_error_code TEXT,\n\t\t\t\terror_at TEXT,\n\t\t\t\tlease_owner TEXT,\n\t\t\t\tlease_acquired_at TEXT,\n\t\t\t\tlease_expires_at TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (canonical_project_identity, generation, step_key)\n\t\t\t);\n\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_effect\n\t\t\t\tON recipient_policy_reconciliation_steps(effect_id);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_status\n\t\t\t\tON recipient_policy_reconciliation_steps(canonical_project_identity, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_pending_refresh\n\t\t\t\tON recipient_policy_reconciliation_steps(canonical_project_identity, generation, step_key)\n\t\t\t\tWHERE status IN ('pending', 'running', 'failed')\n\t\t\t\tAND step_key GLOB 'refresh-after-revocations-v2:*';\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_deny_overlays (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tdevice_id TEXT NOT NULL,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\treason_code TEXT NOT NULL,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (canonical_project_identity, scope_id, device_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_policy_deny_overlays_scope_device\n\t\t\t\tON recipient_policy_deny_overlays(scope_id, device_id);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_policy_team_memberships_identity_status\n\t\t\t\tON policy_team_memberships(identity_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_identity_devices_identity_status\n\t\t\t\tON identity_devices(identity_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_recipients_project_status\n\t\t\t\tON project_recipients(canonical_project_identity, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_recipients_recipient_status\n\t\t\t\tON project_recipients(recipient_kind, recipient_id, status);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_managed_project_projections (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tmanaged_scope_id TEXT NOT NULL,\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\trecipient_identity_id TEXT NOT NULL,\n\t\t\t\taccepting_device_id TEXT NOT NULL,\n\t\t\t\tsource_operation_id TEXT NOT NULL,\n\t\t\t\treviewed_project_set_digest TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\t\taccepted_at TEXT NOT NULL,\n\t\t\t\trevoked_at TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (source_operation_id, canonical_project_identity)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_identity_status\n\t\t\t\tON recipient_managed_project_projections(recipient_identity_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_scope_authority\n\t\t\t\tON recipient_managed_project_projections(\n\t\t\t\t\tmanaged_scope_id, coordinator_id, group_id, status\n\t\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS share_operations (\n\t\t\t\toperation_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tstate TEXT NOT NULL,\n\t\t\t\tinviter_actor_id TEXT NOT NULL,\n\t\t\t\tinviter_device_ids_json TEXT NOT NULL,\n\t\t\t\tperson_id TEXT NOT NULL,\n\t\t\t\tperson_kind TEXT NOT NULL,\n\t\t\t\tpending_person_operation_id TEXT,\n\t\t\t\tteammate_name TEXT NOT NULL,\n\t\t\t\thistory_policy TEXT NOT NULL,\n\t\t\t\treviewed_project_set_digest TEXT NOT NULL,\n\t\t\t\tcoordinator_group_id TEXT NOT NULL,\n\t\t\t\tcoordinator_invite_id TEXT,\n\t\t\t\tinvite_token_digest TEXT NOT NULL,\n\t\t\t\tinvite_expires_at TEXT NOT NULL,\n\t\t\t\trecipient_actor_id TEXT,\n\t\t\t\trecipient_display_name TEXT,\n\t\t\t\trecipient_device_id TEXT,\n\t\t\t\trecipient_device_display_name TEXT,\n\t\t\t\trecipient_public_key TEXT,\n\t\t\t\trecipient_fingerprint TEXT,\n\t\t\t\tacceptance_consumed_at TEXT,\n\t\t\t\ttrust_state TEXT,\n\t\t\t\tbootstrap_grant_id TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS share_operation_projects (\n\t\t\t\toperation_id TEXT NOT NULL,\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tidentity_source TEXT NOT NULL,\n\t\t\t\texisting_memory_count INTEGER NOT NULL,\n\t\t\t\tordinal INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (operation_id, canonical_project_identity)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS share_operation_steps (\n\t\t\t\toperation_id TEXT NOT NULL,\n\t\t\t\tstep_key TEXT NOT NULL,\n\t\t\t\teffect_id TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tstarted_at TEXT,\n\t\t\t\tcompleted_at TEXT,\n\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\tsafe_error_code TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (operation_id, step_key)\n\t\t\t);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for additive share-operation state.\n\t\t}\n\t\tensureRecipientPolicyAdditiveColumns(db);\n\t\tconst shareOperationColumns = [\n\t\t\t[\"state\", \"TEXT NOT NULL DEFAULT 'waiting_for_acceptance'\"],\n\t\t\t[\"inviter_actor_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"inviter_device_ids_json\", \"TEXT NOT NULL DEFAULT '[]'\"],\n\t\t\t[\"person_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"person_kind\", \"TEXT NOT NULL DEFAULT 'pending'\"],\n\t\t\t[\"pending_person_operation_id\", \"TEXT\"],\n\t\t\t[\"teammate_name\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"history_policy\", \"TEXT NOT NULL DEFAULT 'existing_and_future'\"],\n\t\t\t[\"reviewed_project_set_digest\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"coordinator_group_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"coordinator_invite_id\", \"TEXT\"],\n\t\t\t[\"invite_token_digest\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"invite_expires_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"recipient_actor_id\", \"TEXT\"],\n\t\t\t[\"recipient_display_name\", \"TEXT\"],\n\t\t\t[\"recipient_device_id\", \"TEXT\"],\n\t\t\t[\"recipient_device_display_name\", \"TEXT\"],\n\t\t\t[\"recipient_public_key\", \"TEXT\"],\n\t\t\t[\"recipient_fingerprint\", \"TEXT\"],\n\t\t\t[\"acceptance_consumed_at\", \"TEXT\"],\n\t\t\t[\"trust_state\", \"TEXT\"],\n\t\t\t[\"bootstrap_grant_id\", \"TEXT\"],\n\t\t\t[\"created_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"updated_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t] as const;\n\t\tfor (const [name, definition] of shareOperationColumns) {\n\t\t\ttry {\n\t\t\t\taddColumnIfMissing(db, \"share_operations\", name, definition);\n\t\t\t} catch {\n\t\t\t\t// Continue repairing independent additive columns.\n\t\t\t}\n\t\t}\n\t\tfor (const [table, columns] of [\n\t\t\t[\n\t\t\t\t\"share_operation_projects\",\n\t\t\t\t[\n\t\t\t\t\t[\"display_name\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t\t[\"identity_source\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t\t[\"existing_memory_count\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t\t\t\t[\"ordinal\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t\t\t],\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"share_operation_steps\",\n\t\t\t\t[\n\t\t\t\t\t[\"effect_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t\t[\"status\", \"TEXT NOT NULL DEFAULT 'pending'\"],\n\t\t\t\t\t[\"attempt_count\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t\t\t\t[\"started_at\", \"TEXT\"],\n\t\t\t\t\t[\"completed_at\", \"TEXT\"],\n\t\t\t\t\t[\"last_attempt_at\", \"TEXT\"],\n\t\t\t\t\t[\"safe_error_code\", \"TEXT\"],\n\t\t\t\t\t[\"updated_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t],\n\t\t\t],\n\t\t] as const) {\n\t\t\tfor (const [name, definition] of columns) {\n\t\t\t\ttry {\n\t\t\t\t\taddColumnIfMissing(db, table, name, definition);\n\t\t\t\t} catch {\n\t\t\t\t\t// Continue repairing independent additive columns.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\t\tCREATE INDEX IF NOT EXISTS idx_share_operations_state_updated\n\t\t\t\t\tON share_operations(state, updated_at);\n\t\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_invite_digest\n\t\t\t\t\tON share_operations(invite_token_digest);\n\t\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_pending_person_operation\n\t\t\t\t\tON share_operations(pending_person_operation_id)\n\t\t\t\t\tWHERE pending_person_operation_id IS NOT NULL;\n\t\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for additive share-operation indexes.\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_reset_state (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\t\tbaseline_cursor TEXT,\n\t\t\t\tretained_floor_cursor TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t)\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tpeer_device_id TEXT,\n\t\t\t\top_id TEXT NOT NULL,\n\t\t\t\tentity_type TEXT NOT NULL,\n\t\t\t\tentity_id TEXT NOT NULL,\n\t\t\t\tscope_id TEXT,\n\t\t\t\treason TEXT NOT NULL,\n\t\t\t\tcreated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n\t\t\t\tON sync_scope_rejections(peer_device_id, created_at);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n\t\t\t\tON sync_scope_rejections(scope_id, created_at);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive diagnostics.\n\t\t}\n\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_reset_state_v2 (\n\t\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\t\tbaseline_cursor TEXT,\n\t\t\t\tretained_floor_cursor TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\n\t\t\tCREATE TABLE IF NOT EXISTS sync_retention_state_v2 (\n\t\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tlast_run_at TEXT,\n\t\t\t\tlast_duration_ms INTEGER,\n\t\t\t\tlast_deleted_ops INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_estimated_bytes_before INTEGER,\n\t\t\t\tlast_estimated_bytes_after INTEGER,\n\t\t\t\tretained_floor_cursor TEXT,\n\t\t\t\tlast_error TEXT,\n\t\t\t\tlast_error_at TEXT\n\t\t\t);\n\n\t\t\tCREATE TABLE IF NOT EXISTS replication_cursors_v2 (\n\t\t\t\tpeer_device_id TEXT NOT NULL,\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tlast_applied_cursor TEXT,\n\t\t\t\tlast_acked_cursor TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (peer_device_id, scope_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_replication_cursors_v2_scope\n\t\t\t\tON replication_cursors_v2(scope_id);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\n\t\tif (tableExists(db, \"sync_reset_state\") && tableExists(db, \"sync_reset_state_v2\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(`\n\t\t\t\tINSERT OR IGNORE INTO sync_reset_state_v2\n\t\t\t\t\t(scope_id, generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at)\n\t\t\t\tSELECT 'local-default', generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at\n\t\t\t\tFROM sync_reset_state\n\t\t\t\tWHERE id = 1\n\t\t\t`);\n\t\t\t} catch {\n\t\t\t\t// Best-effort bridge from legacy singleton state.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"sync_retention_state\") && tableExists(db, \"sync_retention_state_v2\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(`\n\t\t\t\tINSERT OR IGNORE INTO sync_retention_state_v2\n\t\t\t\t\t(\n\t\t\t\t\t\tscope_id,\n\t\t\t\t\t\tlast_run_at,\n\t\t\t\t\t\tlast_duration_ms,\n\t\t\t\t\t\tlast_deleted_ops,\n\t\t\t\t\t\tlast_estimated_bytes_before,\n\t\t\t\t\t\tlast_estimated_bytes_after,\n\t\t\t\t\t\tretained_floor_cursor,\n\t\t\t\t\t\tlast_error,\n\t\t\t\t\t\tlast_error_at\n\t\t\t\t\t)\n\t\t\t\tSELECT\n\t\t\t\t\t'local-default',\n\t\t\t\t\tlast_run_at,\n\t\t\t\t\tlast_duration_ms,\n\t\t\t\t\tlast_deleted_ops,\n\t\t\t\t\tlast_estimated_bytes_before,\n\t\t\t\t\tlast_estimated_bytes_after,\n\t\t\t\t\tretained_floor_cursor,\n\t\t\t\t\tlast_error,\n\t\t\t\t\tlast_error_at\n\t\t\t\tFROM sync_retention_state\n\t\t\t\tWHERE id = 1\n\t\t\t`);\n\t\t\t} catch {\n\t\t\t\t// Best-effort bridge from legacy singleton state.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"replication_cursors\") && tableExists(db, \"replication_cursors_v2\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(`\n\t\t\t\tINSERT OR IGNORE INTO replication_cursors_v2\n\t\t\t\t\t(peer_device_id, scope_id, last_applied_cursor, last_acked_cursor, updated_at)\n\t\t\t\tSELECT peer_device_id, 'local-default', last_applied_cursor, last_acked_cursor, updated_at\n\t\t\t\tFROM replication_cursors\n\t\t\t`);\n\t\t\t} catch {\n\t\t\t\t// Best-effort bridge from legacy peer-level cursors.\n\t\t\t}\n\t\t}\n\n\t\t// Add phase column to sync_daemon_state for rebootstrap safety gate.\n\t\tif (tableExists(db, \"sync_daemon_state\") && !columnExists(db, \"sync_daemon_state\", \"phase\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(\"ALTER TABLE sync_daemon_state ADD COLUMN phase TEXT\");\n\t\t\t} catch {\n\t\t\t\t// Race-safe: another process may have added it first.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"memory_items\")) {\n\t\t\t// idx_memory_items_created_id is created unconditionally by\n\t\t\t// ensureMemoryItemsPagingIndex so already-current databases also get it.\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_origin_device_active ON memory_items(origin_device_id, active)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\tif (!columnExists(db, \"memory_items\", \"dedup_key\")) {\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(\"ALTER TABLE memory_items ADD COLUMN dedup_key TEXT\");\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tconst duplicateColumn = message.includes(\"duplicate column name\");\n\t\t\t\t\tif (!(duplicateColumn && columnExists(db, \"memory_items\", \"dedup_key\"))) {\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_dedup_key_active_created ON memory_items(dedup_key, active, created_at)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_items_same_session_dedup_unique ON memory_items(session_id, kind, visibility, workspace_id, dedup_key) WHERE active = 1 AND dedup_key IS NOT NULL\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\taddColumnIfMissing(db, \"memory_items\", \"scope_id\", \"TEXT\");\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_scope_visibility_created ON memory_items(scope_id, visibility, created_at)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_scope_backfill_pending ON memory_items(id) WHERE scope_id IS NULL OR scope_id = ''\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\t// Denormalized project column: created here so the Projects read model can\n\t\t\t// read directly from memory_items without joining through sessions (which\n\t\t\t// carry device-local cwd and don't replicate). The actual NULL backfill\n\t\t\t// runs unconditionally via backfillMemoryItemProject() on every open below.\n\t\t\taddColumnIfMissing(db, \"memory_items\", \"project\", \"TEXT\");\n\t\t\ttry {\n\t\t\t\tdb.exec(\"CREATE INDEX IF NOT EXISTS idx_memory_items_project ON memory_items(project)\");\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\t// Drop legacy memory_items indexes that no longer back any query, only\n\t\t\t// adding write amplification on databases created by older schemas. The\n\t\t\t// current schema never creates these. `visibility`/`workspace_kind` are\n\t\t\t// low-cardinality and only ever appear as secondary predicates already\n\t\t\t// covered by composite indexes (e.g. idx_memory_items_scope_visibility_created,\n\t\t\t// idx_memory_items_same_session_dedup_unique); `user_prompt_id` is unused\n\t\t\t// as a filter (and is all-NULL in practice).\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t`DROP INDEX IF EXISTS idx_memory_items_visibility;\n\t\t\t\t DROP INDEX IF EXISTS idx_memory_items_workspace_kind;\n\t\t\t\t DROP INDEX IF EXISTS idx_memory_items_user_prompt_id;`,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Best-effort cleanup of legacy indexes.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"replication_ops\")) {\n\t\t\taddColumnIfMissing(db, \"replication_ops\", \"scope_id\", \"TEXT\");\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_replication_ops_scope_created ON replication_ops(scope_id, created_at, op_id)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS replication_scopes (\n\t\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tlabel TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL DEFAULT 'user',\n\t\t\t\tauthority_type TEXT NOT NULL DEFAULT 'local',\n\t\t\t\tcoordinator_id TEXT,\n\t\t\t\tgroup_id TEXT,\n\t\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tmanifest_hash TEXT,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_replication_scopes_status\n\t\t\t\tON replication_scopes(status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_replication_scopes_authority_group\n\t\t\t\tON replication_scopes(coordinator_id, group_id);\n\n\t\t\tCREATE TABLE IF NOT EXISTS project_scope_mappings (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tworkspace_identity TEXT,\n\t\t\t\tproject_pattern TEXT NOT NULL,\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tpriority INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tsource TEXT NOT NULL DEFAULT 'user',\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_scope_mappings_workspace_priority\n\t\t\t\tON project_scope_mappings(workspace_identity, priority);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_scope_mappings_pattern_priority\n\t\t\t\tON project_scope_mappings(project_pattern, priority);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_scope_mappings_scope\n\t\t\t\tON project_scope_mappings(scope_id);\n\n\t\t\tCREATE TABLE IF NOT EXISTS scope_memberships (\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tdevice_id TEXT NOT NULL,\n\t\t\t\trole TEXT NOT NULL DEFAULT 'member',\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tcoordinator_id TEXT,\n\t\t\t\tgroup_id TEXT,\n\t\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\t\tmanifest_hash TEXT,\n\t\t\t\tsigned_manifest_json TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (scope_id, device_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_scope_memberships_device_status\n\t\t\t\tON scope_memberships(device_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_scope_memberships_scope_status\n\t\t\t\tON scope_memberships(scope_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_scope_memberships_authority_group\n\t\t\t\tON scope_memberships(coordinator_id, group_id);\n\n\t\t\tCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\tlast_refresh_at TEXT NOT NULL,\n\t\t\t\tlast_success_at TEXT,\n\t\t\t\tlast_error TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t\t);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive scope metadata.\n\t\t}\n\n\t\t// Junction tables for structured file/concept references on memories.\n\t\t// Added in schema v7; existing v6 databases need these created additively.\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS memory_file_refs (\n\t\t\t\tmemory_id INTEGER NOT NULL,\n\t\t\t\tfile_path TEXT NOT NULL,\n\t\t\t\trelation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n\t\t\t\tPRIMARY KEY (memory_id, file_path, relation),\n\t\t\t\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_memory_file_refs_path ON memory_file_refs(file_path);\n\n\t\t\tCREATE TABLE IF NOT EXISTS memory_concept_refs (\n\t\t\t\tmemory_id INTEGER NOT NULL,\n\t\t\t\tconcept TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (memory_id, concept),\n\t\t\t\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept ON memory_concept_refs(concept);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\n\t\t// Multi-team coordinator groups (v1) — additive columns + preferences table.\n\t\t// Existing databases acquire these so peer enrollment can record the group\n\t\t// it came from, and so per-group scope templates can be stored locally.\n\t\tif (tableExists(db, \"sync_peers\")) {\n\t\t\tfor (const name of [\n\t\t\t\t\"discovered_via_coordinator_id\",\n\t\t\t\t\"discovered_via_group_id\",\n\t\t\t\t\"trust_provenance\",\n\t\t\t\t\"pending_bootstrap_grant_id\",\n\t\t\t]) {\n\t\t\t\tif (columnExists(db, \"sync_peers\", name)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(`ALTER TABLE sync_peers ADD COLUMN ${name} TEXT`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tif (message.includes(\"duplicate column name\") && columnExists(db, \"sync_peers\", name)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (tableExists(db, \"sync_attempts\")) {\n\t\t\tfor (const name of [\n\t\t\t\t\"local_sync_capability\",\n\t\t\t\t\"peer_sync_capability\",\n\t\t\t\t\"negotiated_sync_capability\",\n\t\t\t]) {\n\t\t\t\tif (columnExists(db, \"sync_attempts\", name)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(`ALTER TABLE sync_attempts ADD COLUMN ${name} TEXT`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tif (\n\t\t\t\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\t\t\t\tcolumnExists(db, \"sync_attempts\", name)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\tprojects_include_json TEXT,\n\t\t\t\tprojects_exclude_json TEXT,\n\t\t\t\tauto_seed_scope INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tdefault_space_scope_id TEXT,\n\t\t\t\tauto_grant_default_space_on_join INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t\t)\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\t\tfor (const { name, ddl } of [\n\t\t\t{ name: \"default_space_scope_id\", ddl: \"TEXT\" },\n\t\t\t{ name: \"auto_grant_default_space_on_join\", ddl: \"INTEGER NOT NULL DEFAULT 0\" },\n\t\t]) {\n\t\t\tif (columnExists(db, \"coordinator_group_preferences\", name)) continue;\n\t\t\ttry {\n\t\t\t\tdb.exec(`ALTER TABLE coordinator_group_preferences ADD COLUMN ${name} ${ddl}`);\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\tif (message.includes(\"duplicate column name\")) continue;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"raw_event_flush_batches\")) {\n\t\t\tconst additiveColumns: Array<{ name: string; ddl: string }> = [\n\t\t\t\t{ name: \"error_message\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"error_type\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_provider\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_model\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_runtime\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_auth_source\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_auth_type\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_error_code\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_error_message\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"attempt_count\", ddl: \"INTEGER NOT NULL DEFAULT 0\" },\n\t\t\t];\n\n\t\t\tfor (const { name, ddl } of additiveColumns) {\n\t\t\t\tif (columnExists(db, \"raw_event_flush_batches\", name)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(`ALTER TABLE raw_event_flush_batches ADD COLUMN ${name} ${ddl}`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tconst duplicateColumn = message.includes(\"duplicate column name\");\n\t\t\t\t\tif (duplicateColumn && columnExists(db, \"raw_event_flush_batches\", name)) {\n\t\t\t\t\t\t// Another process may have raced and added the column first.\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst recipientPolicyTablesReady = [\n\t\t\t\"coordinator_enrollment_reconciliation_issues\",\n\t\t\t\"policy_teams\",\n\t\t\t\"policy_team_memberships\",\n\t\t\t\"policy_team_device_decisions\",\n\t\t\t\"identity_devices\",\n\t\t\t\"project_recipients\",\n\t\t\t\"recipient_managed_project_projections\",\n\t\t\t\"recipient_policy_authority_states\",\n\t\t\t\"recipient_policy_reconciliation_steps\",\n\t\t\t\"recipient_policy_deny_overlays\",\n\t\t].every((table) => tableExists(db, table));\n\t\tconst currentVersion = getSchemaVersion(db);\n\t\tif (recipientPolicyTablesReady && currentVersion > 0 && currentVersion < SCHEMA_VERSION) {\n\t\t\tdb.pragma(`user_version = ${SCHEMA_VERSION}`);\n\t\t}\n\t}\n\t// Run after the gated legacy-column repair so one open can both add\n\t// observer_provider and install its partial diagnostic indexes. This remains\n\t// outside the marker gate for current-marker databases missing only indexes.\n\tensureFlushBatchDiagnosticIndexes(db);\n\t// Intentionally fail the whole connect path: no runtime surface may open a\n\t// partially upgraded authorization schema and discover the drift via raw SELECTs.\n\tassertRecipientPolicyDeviceEligibilityCompatibility(db);\n\t// Reinstall outside the compatibility marker so a missing or stale security\n\t// trigger self-heals before any authorization reader can use the connection.\n\tensureIdentityDeviceAssignmentVersionTriggers(db);\n\tif (!compatAlreadyApplied) markSchemaCompatApplied(db);\n\ttry {\n\t\trepairShareOperationEffectIdIndex(db);\n\t} catch {\n\t\t// Keep compatibility shim fail-open for interrupted or partial legacy schemas.\n\t}\n\n\t// Always runs (not gated): moveMemoryProject relies on this backfill +\n\t// reader-fallback to propagate sessions.project edits to legacy NULL rows.\n\tbackfillMemoryItemProject(db);\n}\n\n/** Safely parse a JSON string, returning {} on failure. */\nexport function fromJson(text: string | null | undefined): Record<string, unknown> {\n\tif (!text) return {};\n\ttry {\n\t\tconst parsed = JSON.parse(text);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\treturn {};\n\t\t}\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\tconsole.warn(`[codemem] fromJson: invalid JSON (${text.slice(0, 80)}...)`);\n\t\treturn {};\n\t}\n}\n\n/**\n * Parse a JSON string strictly — throws on invalid input.\n *\n * Use in mutation paths (replication apply, import) where silently\n * returning {} would mask data corruption. Read paths should use\n * fromJson() which is forgiving.\n */\nexport function fromJsonStrict(text: string | null | undefined): Record<string, unknown> {\n\tif (!text) return {};\n\tconst parsed = JSON.parse(text);\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(\n\t\t\t`fromJsonStrict: expected object, got ${Array.isArray(parsed) ? \"array\" : typeof parsed}`,\n\t\t);\n\t}\n\treturn parsed as Record<string, unknown>;\n}\n\n/** Serialize a value to JSON, defaulting null/undefined to \"{}\". */\nexport function toJson(data: unknown): string {\n\tif (data == null) return \"{}\";\n\treturn JSON.stringify(data);\n}\n\n/**\n * Serialize a value to JSON, preserving null as SQL NULL.\n *\n * Use this for columns that store JSON arrays (facts, concepts, files_read,\n * files_modified) where NULL means \"no data\" and \"{}\" would be corruption.\n * Also normalizes empty objects ({}) to null — Python's from_json returns {}\n * for empty DB values, so imported exports carry {} instead of null.\n * Use `toJson` for metadata_json where \"{}\" is the correct empty default.\n */\nexport function toJsonNullable(data: unknown): string | null {\n\tif (data == null) return null;\n\t// Normalize empty objects to null — these are never valid array column values\n\tif (\n\t\ttypeof data === \"object\" &&\n\t\t!Array.isArray(data) &&\n\t\tObject.keys(data as object).length === 0\n\t) {\n\t\treturn null;\n\t}\n\treturn JSON.stringify(data);\n}\n","/**\n * Drizzle ORM schema for the codemem SQLite database.\n */\n\nimport { sql } from \"drizzle-orm\";\nimport {\n\tindex,\n\tinteger,\n\tprimaryKey,\n\treal,\n\tsqliteTable,\n\ttext,\n\tuniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\n\nexport const sessions = sqliteTable(\n\t\"sessions\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tstarted_at: text(\"started_at\").notNull(),\n\t\tended_at: text(\"ended_at\"),\n\t\tcwd: text(\"cwd\"),\n\t\tproject: text(\"project\"),\n\t\tgit_remote: text(\"git_remote\"),\n\t\tgit_branch: text(\"git_branch\"),\n\t\tuser: text(\"user\"),\n\t\ttool_version: text(\"tool_version\"),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\timport_key: text(\"import_key\"),\n\t},\n\t(table) => [\n\t\t// Keyset paging for newest-first candidate scans (listProjectScopeCandidates).\n\t\tindex(\"idx_sessions_started_id\").on(table.started_at, table.id),\n\t],\n);\n\nexport type Session = typeof sessions.$inferSelect;\nexport type NewSession = typeof sessions.$inferInsert;\n\nexport const replicationScopes = sqliteTable(\n\t\"replication_scopes\",\n\t{\n\t\tscope_id: text(\"scope_id\").primaryKey(),\n\t\tlabel: text(\"label\").notNull(),\n\t\tkind: text(\"kind\").notNull().default(\"user\"),\n\t\tauthority_type: text(\"authority_type\").notNull().default(\"local\"),\n\t\tcoordinator_id: text(\"coordinator_id\"),\n\t\tgroup_id: text(\"group_id\"),\n\t\tmanifest_issuer_device_id: text(\"manifest_issuer_device_id\"),\n\t\tmembership_epoch: integer(\"membership_epoch\").notNull().default(0),\n\t\tmanifest_hash: text(\"manifest_hash\"),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tindex(\"idx_replication_scopes_status\").on(table.status),\n\t\tindex(\"idx_replication_scopes_authority_group\").on(table.coordinator_id, table.group_id),\n\t],\n);\n\nexport type ReplicationScope = typeof replicationScopes.$inferSelect;\nexport type NewReplicationScope = typeof replicationScopes.$inferInsert;\n\nexport const projectScopeMappings = sqliteTable(\n\t\"project_scope_mappings\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tworkspace_identity: text(\"workspace_identity\"),\n\t\tproject_pattern: text(\"project_pattern\").notNull(),\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tpriority: integer(\"priority\").notNull().default(0),\n\t\tsource: text(\"source\").notNull().default(\"user\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tindex(\"idx_project_scope_mappings_workspace_priority\").on(\n\t\t\ttable.workspace_identity,\n\t\t\ttable.priority,\n\t\t),\n\t\tindex(\"idx_project_scope_mappings_pattern_priority\").on(table.project_pattern, table.priority),\n\t\tindex(\"idx_project_scope_mappings_scope\").on(table.scope_id),\n\t],\n);\n\nexport type ProjectScopeMapping = typeof projectScopeMappings.$inferSelect;\nexport type NewProjectScopeMapping = typeof projectScopeMappings.$inferInsert;\n\nexport const scopeMemberships = sqliteTable(\n\t\"scope_memberships\",\n\t{\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\trole: text(\"role\").notNull().default(\"member\"),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\tmembership_epoch: integer(\"membership_epoch\").notNull().default(0),\n\t\tcoordinator_id: text(\"coordinator_id\"),\n\t\tgroup_id: text(\"group_id\"),\n\t\tmanifest_issuer_device_id: text(\"manifest_issuer_device_id\"),\n\t\tmanifest_hash: text(\"manifest_hash\"),\n\t\tsigned_manifest_json: text(\"signed_manifest_json\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.scope_id, table.device_id] }),\n\t\tindex(\"idx_scope_memberships_device_status\").on(table.device_id, table.status),\n\t\tindex(\"idx_scope_memberships_scope_status\").on(table.scope_id, table.status),\n\t\tindex(\"idx_scope_memberships_authority_group\").on(table.coordinator_id, table.group_id),\n\t],\n);\n\nexport type ScopeMembership = typeof scopeMemberships.$inferSelect;\nexport type NewScopeMembership = typeof scopeMemberships.$inferInsert;\n\nexport const artifacts = sqliteTable(\n\t\"artifacts\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tkind: text(\"kind\").notNull(),\n\t\tpath: text(\"path\"),\n\t\tcontent_text: text(\"content_text\"),\n\t\tcontent_hash: text(\"content_hash\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t},\n\t(table) => [index(\"idx_artifacts_session_kind\").on(table.session_id, table.kind)],\n);\n\nexport type Artifact = typeof artifacts.$inferSelect;\nexport type NewArtifact = typeof artifacts.$inferInsert;\n\nexport const memoryItems = sqliteTable(\n\t\"memory_items\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tkind: text(\"kind\").notNull(),\n\t\ttitle: text(\"title\").notNull(),\n\t\tsubtitle: text(\"subtitle\"),\n\t\tbody_text: text(\"body_text\").notNull(),\n\t\tconfidence: real(\"confidence\").default(0.5),\n\t\ttags_text: text(\"tags_text\").default(\"\"),\n\t\tactive: integer(\"active\").default(1),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\tactor_id: text(\"actor_id\"),\n\t\tactor_display_name: text(\"actor_display_name\"),\n\t\tvisibility: text(\"visibility\"),\n\t\tworkspace_id: text(\"workspace_id\"),\n\t\tworkspace_kind: text(\"workspace_kind\"),\n\t\torigin_device_id: text(\"origin_device_id\"),\n\t\torigin_source: text(\"origin_source\"),\n\t\ttrust_state: text(\"trust_state\"),\n\t\tfacts: text(\"facts\"),\n\t\tnarrative: text(\"narrative\"),\n\t\tconcepts: text(\"concepts\"),\n\t\tfiles_read: text(\"files_read\"),\n\t\tfiles_modified: text(\"files_modified\"),\n\t\tuser_prompt_id: integer(\"user_prompt_id\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\tdeleted_at: text(\"deleted_at\"),\n\t\trev: integer(\"rev\").default(0),\n\t\tdedup_key: text(\"dedup_key\"),\n\t\timport_key: text(\"import_key\"),\n\t\tscope_id: text(\"scope_id\"),\n\t\t// Denormalized project name. Carries the originating session's project\n\t\t// across sync boundaries so cross-device memories surface under their\n\t\t// real project identity instead of an inferred placeholder. Backfilled\n\t\t// from sessions.project for legacy rows during migration. May be null\n\t\t// when the originating session had no project.\n\t\tproject: text(\"project\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_memory_items_active_created\").on(table.active, table.created_at),\n\t\tindex(\"idx_memory_items_created_id\").on(table.created_at, table.id),\n\t\tindex(\"idx_memory_items_origin_device_active\").on(table.origin_device_id, table.active),\n\t\tindex(\"idx_memory_items_session\").on(table.session_id),\n\t\tindex(\"idx_memory_items_project\").on(table.project),\n\t\tindex(\"idx_memory_items_scope_visibility_created\").on(\n\t\t\ttable.scope_id,\n\t\t\ttable.visibility,\n\t\t\ttable.created_at,\n\t\t),\n\t\tindex(\"idx_memory_items_scope_backfill_pending\")\n\t\t\t.on(table.id)\n\t\t\t.where(sql`scope_id IS NULL OR scope_id = ''`),\n\t\tindex(\"idx_memory_items_dedup_key_active_created\").on(\n\t\t\ttable.dedup_key,\n\t\t\ttable.active,\n\t\t\ttable.created_at,\n\t\t),\n\t\tuniqueIndex(\"idx_memory_items_same_session_dedup_unique\")\n\t\t\t.on(table.session_id, table.kind, table.visibility, table.workspace_id, table.dedup_key)\n\t\t\t.where(sql`active = 1 AND dedup_key IS NOT NULL`),\n\t],\n);\n\nexport type MemoryItem = typeof memoryItems.$inferSelect;\nexport type NewMemoryItem = typeof memoryItems.$inferInsert;\n\nexport const memoryFileRefs = sqliteTable(\n\t\"memory_file_refs\",\n\t{\n\t\tmemory_id: integer(\"memory_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => memoryItems.id, { onDelete: \"cascade\" }),\n\t\tfile_path: text(\"file_path\").notNull(),\n\t\trelation: text(\"relation\").notNull(), // 'read' | 'modified'\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.memory_id, table.file_path, table.relation] }),\n\t\tindex(\"idx_memory_file_refs_path\").on(table.file_path),\n\t],\n);\n\nexport type MemoryFileRef = typeof memoryFileRefs.$inferSelect;\nexport type NewMemoryFileRef = typeof memoryFileRefs.$inferInsert;\n\nexport const memoryConceptRefs = sqliteTable(\n\t\"memory_concept_refs\",\n\t{\n\t\tmemory_id: integer(\"memory_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => memoryItems.id, { onDelete: \"cascade\" }),\n\t\tconcept: text(\"concept\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.memory_id, table.concept] }),\n\t\tindex(\"idx_memory_concept_refs_concept\").on(table.concept),\n\t],\n);\n\nexport type MemoryConceptRef = typeof memoryConceptRefs.$inferSelect;\nexport type NewMemoryConceptRef = typeof memoryConceptRefs.$inferInsert;\n\nexport const usageEvents = sqliteTable(\n\t\"usage_events\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"set null\",\n\t\t}),\n\t\tevent: text(\"event\").notNull(),\n\t\ttokens_read: integer(\"tokens_read\").default(0),\n\t\ttokens_written: integer(\"tokens_written\").default(0),\n\t\ttokens_saved: integer(\"tokens_saved\").default(0),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_usage_events_event_created\").on(table.event, table.created_at),\n\t\tindex(\"idx_usage_events_session\").on(table.session_id),\n\t],\n);\n\nexport type UsageEvent = typeof usageEvents.$inferSelect;\nexport type NewUsageEvent = typeof usageEvents.$inferInsert;\n\nexport const retrievalAttempts = sqliteTable(\n\t\"retrieval_attempts\",\n\t{\n\t\tattempt_id: text(\"attempt_id\").primaryKey(),\n\t\tcontract_version: integer(\"contract_version\").notNull(),\n\t\tsurface: text(\"surface\").notNull(),\n\t\ttrigger: text(\"trigger\").notNull(),\n\t\tstarted_at: text(\"started_at\").notNull(),\n\t\tcompleted_at: text(\"completed_at\"),\n\t\tretrieval_status: text(\"retrieval_status\").notNull(),\n\t\tdelivery_status: text(\"delivery_status\").notNull(),\n\t\tcandidate_count: integer(\"candidate_count\").notNull(),\n\t\tselected_count: integer(\"selected_count\").notNull(),\n\t\tpersisted_candidate_count: integer(\"persisted_candidate_count\").notNull(),\n\t\trecorder_version: text(\"recorder_version\").notNull(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tsource: text(\"source\"),\n\t\tstream_id: text(\"stream_id\"),\n\t\tsource_session_id: text(\"source_session_id\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\trequest_id: text(\"request_id\"),\n\t\traw_event_start_seq: integer(\"raw_event_start_seq\"),\n\t\traw_event_end_seq: integer(\"raw_event_end_seq\"),\n\t\texperiment_id: text(\"experiment_id\"),\n\t\texperiment_cell_id: text(\"experiment_cell_id\"),\n\t\tevaluation_checkout_id: text(\"evaluation_checkout_id\"),\n\t\tevaluation_fixture_id: text(\"evaluation_fixture_id\"),\n\t\tevaluation_seed: integer(\"evaluation_seed\"),\n\t\tlatency_ms: integer(\"latency_ms\"),\n\t\tproject: text(\"project\"),\n\t\tscope_id: text(\"scope_id\"),\n\t\tmode: text(\"mode\"),\n\t\tlimit_requested: integer(\"limit_requested\"),\n\t\ttoken_budget: integer(\"token_budget\"),\n\t\toutput_tokens: integer(\"output_tokens\"),\n\t\tworking_set_file_count: integer(\"working_set_file_count\"),\n\t\tworking_set_files_json: text(\"working_set_files_json\"),\n\t\tquery_hash_sha256: text(\"query_hash_sha256\"),\n\t\tquery_char_count: integer(\"query_char_count\"),\n\t\tquery_token_estimate: integer(\"query_token_estimate\"),\n\t\tfilter_summary_json: text(\"filter_summary_json\"),\n\t\tfailure_code: text(\"failure_code\"),\n\t\tfailure_stage: text(\"failure_stage\"),\n\t\ttrace_version: integer(\"trace_version\"),\n\t\tautomatic_recall_json: text(\"automatic_recall_json\"),\n\t\tautomatic_recall_key: text(\"automatic_recall_key\"),\n\t\tretention_until: text(\"retention_until\"),\n\t\tretention_pinned: integer(\"retention_pinned\").notNull().default(0),\n\t\tretention_finalized_at: text(\"retention_finalized_at\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_retrieval_attempts_session_started\").on(table.session_id, table.started_at),\n\t\tuniqueIndex(\"idx_retrieval_attempts_automatic_recall_key\").on(table.automatic_recall_key),\n\t\tindex(\"idx_retrieval_attempts_source_stream_started\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.started_at,\n\t\t),\n\t\tindex(\"idx_retrieval_attempts_retention\").on(table.retention_pinned, table.retention_until),\n\t\tindex(\"idx_retrieval_attempts_started\").on(table.started_at, table.attempt_id),\n\t\tindex(\"idx_retrieval_attempts_surface_started\").on(table.surface, table.started_at),\n\t\tuniqueIndex(\"idx_retrieval_attempts_request_identity\")\n\t\t\t.on(table.source, table.surface, table.request_id)\n\t\t\t.where(sql`request_id IS NOT NULL`),\n\t\tindex(\"idx_retrieval_attempts_experiment_cell\").on(\n\t\t\ttable.experiment_id,\n\t\t\ttable.experiment_cell_id,\n\t\t),\n\t],\n);\n\nexport type RetrievalAttempt = typeof retrievalAttempts.$inferSelect;\nexport type NewRetrievalAttempt = typeof retrievalAttempts.$inferInsert;\n\nexport const retrievalExposures = sqliteTable(\n\t\"retrieval_exposures\",\n\t{\n\t\texposure_id: integer(\"exposure_id\").primaryKey({ autoIncrement: true }),\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => retrievalAttempts.attempt_id, { onDelete: \"cascade\" }),\n\t\tmemory_id: integer(\"memory_id\").references(() => memoryItems.id, { onDelete: \"set null\" }),\n\t\tmemory_import_key: text(\"memory_import_key\"),\n\t\torigin_device_id: text(\"origin_device_id\"),\n\t\trank: integer(\"rank\").notNull(),\n\t\tdisposition: text(\"disposition\").notNull(),\n\t\tsection: text(\"section\"),\n\t\thandoff_status: text(\"handoff_status\").notNull(),\n\t\tmemory_rev: integer(\"memory_rev\"),\n\t\tmemory_updated_at: text(\"memory_updated_at\"),\n\t\tmemory_scope_id: text(\"memory_scope_id\"),\n\t\tmemory_kind: text(\"memory_kind\"),\n\t\tmemory_active: integer(\"memory_active\"),\n\t\tmemory_deleted_at: text(\"memory_deleted_at\"),\n\t\tscore_summary_json: text(\"score_summary_json\"),\n\t\treason_codes_json: text(\"reason_codes_json\"),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_retrieval_exposures_attempt_rank\").on(table.attempt_id, table.rank),\n\t\tindex(\"idx_retrieval_exposures_memory\").on(table.memory_id),\n\t],\n);\n\nexport type RetrievalExposure = typeof retrievalExposures.$inferSelect;\nexport type NewRetrievalExposure = typeof retrievalExposures.$inferInsert;\n\nexport const outcomeEvidence = sqliteTable(\n\t\"outcome_evidence\",\n\t{\n\t\tevidence_id: text(\"evidence_id\").primaryKey(),\n\t\tcontract_version: integer(\"contract_version\").notNull(),\n\t\tdimension: text(\"dimension\").notNull(),\n\t\tevidence_type: text(\"evidence_type\").notNull(),\n\t\tsource_class: text(\"source_class\").notNull(),\n\t\tobserved_at: text(\"observed_at\").notNull(),\n\t\tproducer: text(\"producer\").notNull(),\n\t\tproducer_version: text(\"producer_version\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tvalue_type: text(\"value_type\"),\n\t\tvalue_integer: integer(\"value_integer\"),\n\t\tvalue_real: real(\"value_real\"),\n\t\tvalue_unit: text(\"value_unit\"),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tsource: text(\"source\"),\n\t\tstream_id: text(\"stream_id\"),\n\t\tsource_session_id: text(\"source_session_id\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\traw_event_start_seq: integer(\"raw_event_start_seq\"),\n\t\traw_event_end_seq: integer(\"raw_event_end_seq\"),\n\t\texperiment_id: text(\"experiment_id\"),\n\t\texperiment_cell_id: text(\"experiment_cell_id\"),\n\t\twindow_start_at: text(\"window_start_at\"),\n\t\twindow_end_at: text(\"window_end_at\"),\n\t\treferences_json: text(\"references_json\"),\n\t\tretention_until: text(\"retention_until\"),\n\t\tretention_pinned: integer(\"retention_pinned\").notNull().default(0),\n\t\tretention_finalized_at: text(\"retention_finalized_at\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_outcome_evidence_observed_id\").on(table.observed_at, table.evidence_id),\n\t\tindex(\"idx_outcome_evidence_session_observed\").on(table.session_id, table.observed_at),\n\t\tindex(\"idx_outcome_evidence_source_stream_observed\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.observed_at,\n\t\t),\n\t\tindex(\"idx_outcome_evidence_type_observed\").on(table.evidence_type, table.observed_at),\n\t\tindex(\"idx_outcome_evidence_retention\").on(table.retention_pinned, table.retention_until),\n\t],\n);\n\nexport type OutcomeEvidence = typeof outcomeEvidence.$inferSelect;\nexport type NewOutcomeEvidence = typeof outcomeEvidence.$inferInsert;\n\nexport const attributionAssessments = sqliteTable(\n\t\"attribution_assessments\",\n\t{\n\t\tassessment_id: text(\"assessment_id\").primaryKey(),\n\t\tcontract_version: integer(\"contract_version\").notNull(),\n\t\tsubject_type: text(\"subject_type\").notNull(),\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => retrievalAttempts.attempt_id, { onDelete: \"cascade\" }),\n\t\texposure_id: integer(\"exposure_id\").references(() => retrievalExposures.exposure_id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tdimension: text(\"dimension\").notNull(),\n\t\timpact_label: text(\"impact_label\").notNull(),\n\t\tbasis: text(\"basis\").notNull(),\n\t\tconfidence_level: text(\"confidence_level\").notNull(),\n\t\tmethod: text(\"method\").notNull(),\n\t\tmethod_version: text(\"method_version\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tclaim_type: text(\"claim_type\").notNull().default(\"observational\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_attribution_assessments_attempt_created\").on(table.attempt_id, table.created_at),\n\t\tindex(\"idx_attribution_assessments_label_created\").on(table.impact_label, table.created_at),\n\t\tindex(\"idx_attribution_assessments_exposure\").on(table.exposure_id),\n\t],\n);\n\nexport type AttributionAssessment = typeof attributionAssessments.$inferSelect;\nexport type NewAttributionAssessment = typeof attributionAssessments.$inferInsert;\n\nexport const attributionAssessmentEvidence = sqliteTable(\n\t\"attribution_assessment_evidence\",\n\t{\n\t\tassessment_id: text(\"assessment_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => attributionAssessments.assessment_id, { onDelete: \"cascade\" }),\n\t\tevidence_id: text(\"evidence_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => outcomeEvidence.evidence_id, { onDelete: \"cascade\" }),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.assessment_id, table.evidence_id] }),\n\t\tindex(\"idx_attribution_assessment_evidence_evidence\").on(\n\t\t\ttable.evidence_id,\n\t\t\ttable.assessment_id,\n\t\t),\n\t],\n);\n\nexport type AttributionAssessmentEvidence = typeof attributionAssessmentEvidence.$inferSelect;\nexport type NewAttributionAssessmentEvidence = typeof attributionAssessmentEvidence.$inferInsert;\n\nexport const maintenanceJobs = sqliteTable(\n\t\"maintenance_jobs\",\n\t{\n\t\tkind: text(\"kind\").primaryKey(),\n\t\ttitle: text(\"title\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tmessage: text(\"message\"),\n\t\tprogress_current: integer(\"progress_current\").notNull().default(0),\n\t\tprogress_total: integer(\"progress_total\"),\n\t\tprogress_unit: text(\"progress_unit\").notNull().default(\"items\"),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\tstarted_at: text(\"started_at\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t\tfinished_at: text(\"finished_at\"),\n\t\terror: text(\"error\"),\n\t},\n\t(table) => [index(\"idx_maintenance_jobs_status_updated\").on(table.status, table.updated_at)],\n);\n\nexport type MaintenanceJob = typeof maintenanceJobs.$inferSelect;\nexport type NewMaintenanceJob = typeof maintenanceJobs.$inferInsert;\n\nexport const rawEvents = sqliteTable(\n\t\"raw_events\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tevent_id: text(\"event_id\"),\n\t\tevent_seq: integer(\"event_seq\").notNull(),\n\t\tevent_type: text(\"event_type\").notNull(),\n\t\tts_wall_ms: integer(\"ts_wall_ms\"),\n\t\tts_mono_ms: real(\"ts_mono_ms\"),\n\t\tpayload_json: text(\"payload_json\").notNull(),\n\t\tcapture_context_json: text(\"capture_context_json\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_raw_events_source_stream_seq\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.event_seq,\n\t\t),\n\t\tuniqueIndex(\"idx_raw_events_source_stream_event_id\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.event_id,\n\t\t),\n\t\tindex(\"idx_raw_events_session_seq\").on(table.opencode_session_id, table.event_seq),\n\t\tindex(\"idx_raw_events_created\").on(table.created_at),\n\t\tindex(\"idx_raw_events_capture_context\")\n\t\t\t.on(table.source, table.stream_id, table.event_seq)\n\t\t\t.where(sql`${table.capture_context_json} IS NOT NULL`),\n\t],\n);\n\nexport type RawEvent = typeof rawEvents.$inferSelect;\nexport type NewRawEvent = typeof rawEvents.$inferInsert;\n\nexport const rawEventSessions = sqliteTable(\n\t\"raw_event_sessions\",\n\t{\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tcwd: text(\"cwd\"),\n\t\tproject: text(\"project\"),\n\t\tstarted_at: text(\"started_at\"),\n\t\tlast_seen_ts_wall_ms: integer(\"last_seen_ts_wall_ms\"),\n\t\tlast_received_event_seq: integer(\"last_received_event_seq\").notNull().default(-1),\n\t\tlast_flushed_event_seq: integer(\"last_flushed_event_seq\").notNull().default(-1),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.source, table.stream_id] }),\n\t\tindex(\"idx_raw_event_sessions_pending_updated\")\n\t\t\t.on(table.updated_at)\n\t\t\t.where(sql`${table.last_received_event_seq} > ${table.last_flushed_event_seq}`),\n\t],\n);\n\nexport type RawEventSession = typeof rawEventSessions.$inferSelect;\nexport type NewRawEventSession = typeof rawEventSessions.$inferInsert;\n\nexport const piImportState = sqliteTable(\"pi_import_state\", {\n\tfile_path: text(\"file_path\").primaryKey(),\n\tsize_bytes: integer(\"size_bytes\").notNull(),\n\tmtime_ms: real(\"mtime_ms\").notNull(),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type PiImportStateRow = typeof piImportState.$inferSelect;\nexport type NewPiImportStateRow = typeof piImportState.$inferInsert;\n\nexport const opencodeSessions = sqliteTable(\n\t\"opencode_sessions\",\n\t{\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.source, table.stream_id] }),\n\t\tindex(\"idx_opencode_sessions_session\").on(table.session_id),\n\t],\n);\n\nexport type OpencodeSession = typeof opencodeSessions.$inferSelect;\nexport type NewOpencodeSession = typeof opencodeSessions.$inferInsert;\n\nexport const rawEventFlushBatches = sqliteTable(\n\t\"raw_event_flush_batches\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tstart_event_seq: integer(\"start_event_seq\").notNull(),\n\t\tend_event_seq: integer(\"end_event_seq\").notNull(),\n\t\textractor_version: text(\"extractor_version\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\terror_message: text(\"error_message\"),\n\t\terror_type: text(\"error_type\"),\n\t\tobserver_provider: text(\"observer_provider\"),\n\t\tobserver_model: text(\"observer_model\"),\n\t\tobserver_runtime: text(\"observer_runtime\"),\n\t\tobserver_auth_source: text(\"observer_auth_source\"),\n\t\tobserver_auth_type: text(\"observer_auth_type\"),\n\t\tobserver_error_code: text(\"observer_error_code\"),\n\t\tobserver_error_message: text(\"observer_error_message\"),\n\t\tattempt_count: integer(\"attempt_count\").notNull().default(0),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_flush_batches_source_stream_seq_ver\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.start_event_seq,\n\t\t\ttable.end_event_seq,\n\t\t\ttable.extractor_version,\n\t\t),\n\t\tindex(\"idx_flush_batches_session_created\").on(table.opencode_session_id, table.created_at),\n\t\tindex(\"idx_flush_batches_status_updated\").on(table.status, table.updated_at),\n\t\tindex(\"idx_flush_batches_observer_status_updated\")\n\t\t\t.on(table.status, table.updated_at)\n\t\t\t.where(sql`${table.observer_provider} IS NOT NULL`),\n\t\tindex(\"idx_flush_batches_capture_status_updated\")\n\t\t\t.on(table.status, table.updated_at)\n\t\t\t.where(sql`${table.observer_provider} IS NULL`),\n\t],\n);\n\nexport type RawEventFlushBatch = typeof rawEventFlushBatches.$inferSelect;\nexport type NewRawEventFlushBatch = typeof rawEventFlushBatches.$inferInsert;\n\nexport const userPrompts = sqliteTable(\n\t\"user_prompts\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tproject: text(\"project\"),\n\t\tprompt_text: text(\"prompt_text\").notNull(),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tcreated_at_epoch: integer(\"created_at_epoch\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\timport_key: text(\"import_key\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_user_prompts_session\").on(table.session_id),\n\t\tindex(\"idx_user_prompts_project\").on(table.project),\n\t\tindex(\"idx_user_prompts_epoch\").on(table.created_at_epoch),\n\t],\n);\n\nexport type UserPrompt = typeof userPrompts.$inferSelect;\nexport type NewUserPrompt = typeof userPrompts.$inferInsert;\n\nexport const sessionSummaries = sqliteTable(\n\t\"session_summaries\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tproject: text(\"project\"),\n\t\trequest: text(\"request\"),\n\t\tinvestigated: text(\"investigated\"),\n\t\tlearned: text(\"learned\"),\n\t\tcompleted: text(\"completed\"),\n\t\tnext_steps: text(\"next_steps\"),\n\t\tnotes: text(\"notes\"),\n\t\tfiles_read: text(\"files_read\"),\n\t\tfiles_edited: text(\"files_edited\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tcreated_at_epoch: integer(\"created_at_epoch\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\timport_key: text(\"import_key\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_session_summaries_session\").on(table.session_id),\n\t\tindex(\"idx_session_summaries_project\").on(table.project),\n\t\tindex(\"idx_session_summaries_epoch\").on(table.created_at_epoch),\n\t],\n);\n\nexport type SessionSummary = typeof sessionSummaries.$inferSelect;\nexport type NewSessionSummary = typeof sessionSummaries.$inferInsert;\n\nexport const replicationOps = sqliteTable(\n\t\"replication_ops\",\n\t{\n\t\top_id: text(\"op_id\").primaryKey(),\n\t\tentity_type: text(\"entity_type\").notNull(),\n\t\tentity_id: text(\"entity_id\").notNull(),\n\t\top_type: text(\"op_type\").notNull(),\n\t\tpayload_json: text(\"payload_json\"),\n\t\tclock_rev: integer(\"clock_rev\").notNull(),\n\t\tclock_updated_at: text(\"clock_updated_at\").notNull(),\n\t\tclock_device_id: text(\"clock_device_id\").notNull(),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tscope_id: text(\"scope_id\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_replication_ops_created\").on(table.created_at, table.op_id),\n\t\tindex(\"idx_replication_ops_entity\").on(table.entity_type, table.entity_id),\n\t\tindex(\"idx_replication_ops_scope_created\").on(table.scope_id, table.created_at, table.op_id),\n\t],\n);\n\nexport type ReplicationOp = typeof replicationOps.$inferSelect;\nexport type NewReplicationOp = typeof replicationOps.$inferInsert;\n\nexport const replicationCursors = sqliteTable(\"replication_cursors\", {\n\tpeer_device_id: text(\"peer_device_id\").primaryKey(),\n\tlast_applied_cursor: text(\"last_applied_cursor\"),\n\tlast_acked_cursor: text(\"last_acked_cursor\"),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type ReplicationCursor = typeof replicationCursors.$inferSelect;\nexport type NewReplicationCursor = typeof replicationCursors.$inferInsert;\n\nexport const replicationCursorsV2 = sqliteTable(\n\t\"replication_cursors_v2\",\n\t{\n\t\tpeer_device_id: text(\"peer_device_id\").notNull(),\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tlast_applied_cursor: text(\"last_applied_cursor\"),\n\t\tlast_acked_cursor: text(\"last_acked_cursor\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.peer_device_id, table.scope_id] }),\n\t\tindex(\"idx_replication_cursors_v2_scope\").on(table.scope_id),\n\t],\n);\n\nexport type ReplicationCursorV2 = typeof replicationCursorsV2.$inferSelect;\nexport type NewReplicationCursorV2 = typeof replicationCursorsV2.$inferInsert;\n\nexport const syncPeers = sqliteTable(\"sync_peers\", {\n\tpeer_device_id: text(\"peer_device_id\").primaryKey(),\n\tname: text(\"name\"),\n\tpinned_fingerprint: text(\"pinned_fingerprint\"),\n\tpublic_key: text(\"public_key\"),\n\taddresses_json: text(\"addresses_json\"),\n\tmanual_addresses_json: text(\"manual_addresses_json\"),\n\tlast_success_address: text(\"last_success_address\"),\n\tclaimed_local_actor: integer(\"claimed_local_actor\").notNull().default(0),\n\tactor_id: text(\"actor_id\"),\n\tprojects_include_json: text(\"projects_include_json\"),\n\tprojects_exclude_json: text(\"projects_exclude_json\"),\n\tcreated_at: text(\"created_at\").notNull(),\n\tlast_seen_at: text(\"last_seen_at\"),\n\tlast_sync_at: text(\"last_sync_at\"),\n\tlast_error: text(\"last_error\"),\n\truntime_version: text(\"runtime_version\"),\n\truntime_version_observed_at: text(\"runtime_version_observed_at\"),\n\thighest_observed_direct_signature_version: integer(\"highest_observed_direct_signature_version\"),\n\tdiscovered_via_coordinator_id: text(\"discovered_via_coordinator_id\"),\n\tdiscovered_via_group_id: text(\"discovered_via_group_id\"),\n\ttrust_provenance: text(\"trust_provenance\"),\n\tpending_bootstrap_grant_id: text(\"pending_bootstrap_grant_id\"),\n});\n\nexport type SyncPeer = typeof syncPeers.$inferSelect;\nexport type NewSyncPeer = typeof syncPeers.$inferInsert;\n\nexport const syncPeerSignatureState = sqliteTable(\"sync_peer_signature_state\", {\n\tpeer_device_id: text(\"peer_device_id\").primaryKey(),\n\thighest_observed_direct_signature_version: integer(\n\t\t\"highest_observed_direct_signature_version\",\n\t).notNull(),\n});\n\nexport type SyncPeerSignatureState = typeof syncPeerSignatureState.$inferSelect;\nexport type NewSyncPeerSignatureState = typeof syncPeerSignatureState.$inferInsert;\n\nexport const syncNonces = sqliteTable(\"sync_nonces\", {\n\tnonce: text(\"nonce\").primaryKey(),\n\tdevice_id: text(\"device_id\").notNull(),\n\tcreated_at: text(\"created_at\").notNull(),\n});\n\nexport type SyncNonce = typeof syncNonces.$inferSelect;\nexport type NewSyncNonce = typeof syncNonces.$inferInsert;\n\nexport const syncDevice = sqliteTable(\"sync_device\", {\n\tdevice_id: text(\"device_id\").primaryKey(),\n\tpublic_key: text(\"public_key\").notNull(),\n\tfingerprint: text(\"fingerprint\").notNull(),\n\tcreated_at: text(\"created_at\").notNull(),\n});\n\nexport type SyncDevice = typeof syncDevice.$inferSelect;\nexport type NewSyncDevice = typeof syncDevice.$inferInsert;\n\nexport const syncAttempts = sqliteTable(\n\t\"sync_attempts\",\n\t{\n\t\tid: integer(\"id\").primaryKey({ autoIncrement: true }),\n\t\tpeer_device_id: text(\"peer_device_id\").notNull(),\n\t\tstarted_at: text(\"started_at\").notNull(),\n\t\tfinished_at: text(\"finished_at\"),\n\t\tok: integer(\"ok\").notNull(),\n\t\tops_in: integer(\"ops_in\").notNull(),\n\t\tops_out: integer(\"ops_out\").notNull(),\n\t\terror: text(\"error\"),\n\t\tlocal_sync_capability: text(\"local_sync_capability\"),\n\t\tpeer_sync_capability: text(\"peer_sync_capability\"),\n\t\tnegotiated_sync_capability: text(\"negotiated_sync_capability\"),\n\t\tfailure_category: text(\"failure_category\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_sync_attempts_peer_started\").on(table.peer_device_id, table.started_at),\n\t\tindex(\"idx_sync_attempts_occurred\").on(\n\t\t\tsql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`,\n\t\t\ttable.id,\n\t\t),\n\t\tindex(\"idx_sync_attempts_error_occurred\")\n\t\t\t.on(\n\t\t\t\tsql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`,\n\t\t\t\ttable.id,\n\t\t\t)\n\t\t\t.where(sql`${table.ok} = 0`),\n\t\tindex(\"idx_sync_attempts_success_occurred\")\n\t\t\t.on(\n\t\t\t\tsql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`,\n\t\t\t\ttable.id,\n\t\t\t)\n\t\t\t.where(sql`${table.ok} <> 0`),\n\t],\n);\n\nexport type SyncAttempt = typeof syncAttempts.$inferSelect;\nexport type NewSyncAttempt = typeof syncAttempts.$inferInsert;\n\nexport const syncScopeRejections = sqliteTable(\n\t\"sync_scope_rejections\",\n\t{\n\t\tid: integer(\"id\").primaryKey({ autoIncrement: true }),\n\t\tpeer_device_id: text(\"peer_device_id\"),\n\t\top_id: text(\"op_id\").notNull(),\n\t\tentity_type: text(\"entity_type\").notNull(),\n\t\tentity_id: text(\"entity_id\").notNull(),\n\t\tscope_id: text(\"scope_id\"),\n\t\treason: text(\"reason\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tindex(\"idx_sync_scope_rejections_peer_created\").on(table.peer_device_id, table.created_at),\n\t\tindex(\"idx_sync_scope_rejections_scope_created\").on(table.scope_id, table.created_at),\n\t],\n);\n\nexport type SyncScopeRejection = typeof syncScopeRejections.$inferSelect;\nexport type NewSyncScopeRejection = typeof syncScopeRejections.$inferInsert;\n\nexport const syncDaemonState = sqliteTable(\"sync_daemon_state\", {\n\tid: integer(\"id\").primaryKey(),\n\tlast_error: text(\"last_error\"),\n\tlast_traceback: text(\"last_traceback\"),\n\tlast_error_at: text(\"last_error_at\"),\n\tlast_ok_at: text(\"last_ok_at\"),\n\tphase: text(\"phase\"),\n});\n\nexport type SyncDaemonState = typeof syncDaemonState.$inferSelect;\nexport type NewSyncDaemonState = typeof syncDaemonState.$inferInsert;\n\nexport const syncResetState = sqliteTable(\"sync_reset_state\", {\n\tid: integer(\"id\").primaryKey(),\n\tgeneration: integer(\"generation\").notNull(),\n\tsnapshot_id: text(\"snapshot_id\").notNull(),\n\tbaseline_cursor: text(\"baseline_cursor\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type SyncResetState = typeof syncResetState.$inferSelect;\nexport type NewSyncResetState = typeof syncResetState.$inferInsert;\n\nexport const syncResetStateV2 = sqliteTable(\"sync_reset_state_v2\", {\n\tscope_id: text(\"scope_id\").primaryKey(),\n\tgeneration: integer(\"generation\").notNull(),\n\tsnapshot_id: text(\"snapshot_id\").notNull(),\n\tbaseline_cursor: text(\"baseline_cursor\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type SyncResetStateV2 = typeof syncResetStateV2.$inferSelect;\nexport type NewSyncResetStateV2 = typeof syncResetStateV2.$inferInsert;\n\nexport const syncRetentionState = sqliteTable(\"sync_retention_state\", {\n\tid: integer(\"id\").primaryKey(),\n\tlast_run_at: text(\"last_run_at\"),\n\tlast_duration_ms: integer(\"last_duration_ms\"),\n\tlast_deleted_ops: integer(\"last_deleted_ops\").notNull().default(0),\n\tlast_estimated_bytes_before: integer(\"last_estimated_bytes_before\"),\n\tlast_estimated_bytes_after: integer(\"last_estimated_bytes_after\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tlast_error: text(\"last_error\"),\n\tlast_error_at: text(\"last_error_at\"),\n});\n\nexport type SyncRetentionState = typeof syncRetentionState.$inferSelect;\nexport type NewSyncRetentionState = typeof syncRetentionState.$inferInsert;\n\nexport const syncRetentionStateV2 = sqliteTable(\"sync_retention_state_v2\", {\n\tscope_id: text(\"scope_id\").primaryKey(),\n\tlast_run_at: text(\"last_run_at\"),\n\tlast_duration_ms: integer(\"last_duration_ms\"),\n\tlast_deleted_ops: integer(\"last_deleted_ops\").notNull().default(0),\n\tlast_estimated_bytes_before: integer(\"last_estimated_bytes_before\"),\n\tlast_estimated_bytes_after: integer(\"last_estimated_bytes_after\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tlast_error: text(\"last_error\"),\n\tlast_error_at: text(\"last_error_at\"),\n});\n\nexport type SyncRetentionStateV2 = typeof syncRetentionStateV2.$inferSelect;\nexport type NewSyncRetentionStateV2 = typeof syncRetentionStateV2.$inferInsert;\n\nexport const rawEventIngestSamples = sqliteTable(\"raw_event_ingest_samples\", {\n\tid: integer(\"id\").primaryKey({ autoIncrement: true }),\n\tcreated_at: text(\"created_at\").notNull(),\n\tinserted_events: integer(\"inserted_events\").notNull().default(0),\n\tskipped_invalid: integer(\"skipped_invalid\").notNull().default(0),\n\tskipped_duplicate: integer(\"skipped_duplicate\").notNull().default(0),\n\tskipped_conflict: integer(\"skipped_conflict\").notNull().default(0),\n});\n\nexport type RawEventIngestSample = typeof rawEventIngestSamples.$inferSelect;\nexport type NewRawEventIngestSample = typeof rawEventIngestSamples.$inferInsert;\n\nexport const rawEventIngestStats = sqliteTable(\"raw_event_ingest_stats\", {\n\tid: integer(\"id\").primaryKey(),\n\tinserted_events: integer(\"inserted_events\").notNull().default(0),\n\tskipped_events: integer(\"skipped_events\").notNull().default(0),\n\tskipped_invalid: integer(\"skipped_invalid\").notNull().default(0),\n\tskipped_duplicate: integer(\"skipped_duplicate\").notNull().default(0),\n\tskipped_conflict: integer(\"skipped_conflict\").notNull().default(0),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type RawEventIngestStat = typeof rawEventIngestStats.$inferSelect;\nexport type NewRawEventIngestStat = typeof rawEventIngestStats.$inferInsert;\n\nexport const coordinatorGroupPreferences = sqliteTable(\n\t\"coordinator_group_preferences\",\n\t{\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\tprojects_include_json: text(\"projects_include_json\"),\n\t\tprojects_exclude_json: text(\"projects_exclude_json\"),\n\t\tauto_seed_scope: integer(\"auto_seed_scope\").notNull().default(1),\n\t\tdefault_space_scope_id: text(\"default_space_scope_id\"),\n\t\tauto_grant_default_space_on_join: integer(\"auto_grant_default_space_on_join\")\n\t\t\t.notNull()\n\t\t\t.default(0),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tpk: primaryKey({ columns: [table.coordinator_id, table.group_id] }),\n\t}),\n);\n\nexport type CoordinatorGroupPreferences = typeof coordinatorGroupPreferences.$inferSelect;\nexport type NewCoordinatorGroupPreferences = typeof coordinatorGroupPreferences.$inferInsert;\n\nexport const actors = sqliteTable(\n\t\"actors\",\n\t{\n\t\tactor_id: text(\"actor_id\").primaryKey(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tis_local: integer(\"is_local\").notNull().default(0),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\tmerged_into_actor_id: text(\"merged_into_actor_id\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tisLocalIdx: index(\"idx_actors_is_local\").on(table.is_local),\n\t\tstatusIdx: index(\"idx_actors_status\").on(table.status),\n\t}),\n);\n\nexport type Actor = typeof actors.$inferSelect;\nexport type NewActor = typeof actors.$inferInsert;\n\nexport const recipientPolicyReviewResolutions = sqliteTable(\n\t\"recipient_policy_review_resolutions\",\n\t{\n\t\treview_item_id: text(\"review_item_id\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\").notNull(),\n\t\tdecision: text(\"decision\").notNull(),\n\t\tdecision_input_json: text(\"decision_input_json\").notNull(),\n\t\tpreview_json: text(\"preview_json\").notNull(),\n\t\tdecided_by_identity_id: text(\"decided_by_identity_id\").notNull(),\n\t\tdecided_by_device_id: text(\"decided_by_device_id\").notNull(),\n\t\tresolved_at: text(\"resolved_at\").notNull(),\n\t},\n\t(table) => [primaryKey({ columns: [table.review_item_id, table.source_fingerprint] })],\n);\n\nexport type RecipientPolicyReviewResolution = typeof recipientPolicyReviewResolutions.$inferSelect;\nexport type NewRecipientPolicyReviewResolution =\n\ttypeof recipientPolicyReviewResolutions.$inferInsert;\n\nexport const coordinatorEnrollmentReconciliationIssues = sqliteTable(\n\t\"coordinator_enrollment_reconciliation_issues\",\n\t{\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\tkind: text(\"kind\").notNull(),\n\t\treference_id: text(\"reference_id\").notNull(),\n\t\tcode: text(\"code\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"open\"),\n\t\tfirst_seen_at: text(\"first_seen_at\").notNull(),\n\t\tlast_seen_at: text(\"last_seen_at\").notNull(),\n\t\tresolved_at: text(\"resolved_at\"),\n\t\toccurrence_count: integer(\"occurrence_count\").notNull().default(1),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.coordinator_id, table.group_id, table.kind, table.reference_id, table.code],\n\t\t}),\n\t\tindex(\"idx_coordinator_enrollment_issues_boundary_status\").on(\n\t\t\ttable.coordinator_id,\n\t\t\ttable.group_id,\n\t\t\ttable.status,\n\t\t),\n\t\tindex(\"idx_coordinator_enrollment_issues_status_recent\").on(\n\t\t\ttable.status,\n\t\t\ttable.last_seen_at,\n\t\t\ttable.resolved_at,\n\t\t),\n\t],\n);\n\nexport type CoordinatorEnrollmentReconciliationIssue =\n\ttypeof coordinatorEnrollmentReconciliationIssues.$inferSelect;\nexport type NewCoordinatorEnrollmentReconciliationIssue =\n\ttypeof coordinatorEnrollmentReconciliationIssues.$inferInsert;\n\nexport const policyTeams = sqliteTable(\"policy_teams\", {\n\tteam_id: text(\"team_id\").primaryKey(),\n\tdisplay_name: text(\"display_name\").notNull(),\n\tstatus: text(\"status\").notNull(),\n\tdevice_eligibility_mode: text(\"device_eligibility_mode\").notNull().default(\"person_all_devices\"),\n\tprovenance: text(\"provenance\").notNull(),\n\trevision: text(\"revision\").notNull(),\n\tmigration_state: text(\"migration_state\").notNull(),\n\tsource_fingerprint: text(\"source_fingerprint\"),\n\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\tcreated_at: text(\"created_at\").notNull(),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type PolicyTeam = typeof policyTeams.$inferSelect;\nexport type NewPolicyTeam = typeof policyTeams.$inferInsert;\n\nexport const policyTeamMemberships = sqliteTable(\n\t\"policy_team_memberships\",\n\t{\n\t\tteam_id: text(\"team_id\").notNull(),\n\t\tidentity_id: text(\"identity_id\").notNull(),\n\t\trole: text(\"role\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\trevision: text(\"revision\").notNull(),\n\t\tmigration_state: text(\"migration_state\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\"),\n\t\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tpk: primaryKey({ columns: [table.team_id, table.identity_id] }),\n\t\tidentityStatusIdx: index(\"idx_policy_team_memberships_identity_status\").on(\n\t\t\ttable.identity_id,\n\t\t\ttable.status,\n\t\t),\n\t}),\n);\n\nexport type PolicyTeamMembership = typeof policyTeamMemberships.$inferSelect;\nexport type NewPolicyTeamMembership = typeof policyTeamMemberships.$inferInsert;\n\nexport const policyTeamDeviceDecisions = sqliteTable(\n\t\"policy_team_device_decisions\",\n\t{\n\t\tteam_id: text(\"team_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => policyTeams.team_id, { onDelete: \"cascade\" }),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tdecision: text(\"decision\").notNull(),\n\t\tassignment_version: integer(\"assignment_version\").notNull().default(0),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\trevision: text(\"revision\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.team_id, table.device_id] }),\n\t\tindex(\"idx_policy_team_device_decisions_device\").on(table.device_id),\n\t],\n);\n\nexport type PolicyTeamDeviceDecisionRow = typeof policyTeamDeviceDecisions.$inferSelect;\nexport type NewPolicyTeamDeviceDecisionRow = typeof policyTeamDeviceDecisions.$inferInsert;\n\nexport const identityDevices = sqliteTable(\n\t\"identity_devices\",\n\t{\n\t\tdevice_id: text(\"device_id\").primaryKey(),\n\t\tidentity_id: text(\"identity_id\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\trevision: text(\"revision\").notNull(),\n\t\tmigration_state: text(\"migration_state\").notNull(),\n\t\tassignment_version: integer(\"assignment_version\").notNull().default(0),\n\t\tsource_fingerprint: text(\"source_fingerprint\"),\n\t\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tidentityStatusIdx: index(\"idx_identity_devices_identity_status\").on(\n\t\t\ttable.identity_id,\n\t\t\ttable.status,\n\t\t),\n\t}),\n);\n\nexport type IdentityDevice = typeof identityDevices.$inferSelect;\nexport type NewIdentityDevice = typeof identityDevices.$inferInsert;\n\nexport const deviceIdentityBindingCommits = sqliteTable(\"device_identity_binding_commits\", {\n\tcommit_digest: text(\"commit_digest\").primaryKey(),\n\treviewed_inventory_digest: text(\"reviewed_inventory_digest\").notNull(),\n\trequest_json: text(\"request_json\").notNull(),\n\toutcomes_json: text(\"outcomes_json\").notNull(),\n\twrite_count: integer(\"write_count\").notNull(),\n\tdecided_by_identity_id: text(\"decided_by_identity_id\").notNull(),\n\tdecided_by_device_id: text(\"decided_by_device_id\").notNull(),\n\tcreated_at: text(\"created_at\").notNull(),\n});\n\nexport const deviceIdentityBindingAudit = sqliteTable(\n\t\"device_identity_binding_audit\",\n\t{\n\t\tevent_id: text(\"event_id\").primaryKey(),\n\t\tcommit_digest: text(\"commit_digest\")\n\t\t\t.notNull()\n\t\t\t.references(() => deviceIdentityBindingCommits.commit_digest),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tprevious_identity_id: text(\"previous_identity_id\"),\n\t\ttarget_identity_id: text(\"target_identity_id\").notNull(),\n\t\taction: text(\"action\").notNull(),\n\t\tprevious_assignment_version: integer(\"previous_assignment_version\"),\n\t\tresulting_assignment_version: integer(\"resulting_assignment_version\").notNull(),\n\t\tdecided_by_identity_id: text(\"decided_by_identity_id\").notNull(),\n\t\tdecided_by_device_id: text(\"decided_by_device_id\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_device_identity_binding_audit_commit_device\").on(\n\t\t\ttable.commit_digest,\n\t\t\ttable.device_id,\n\t\t),\n\t\tindex(\"idx_device_identity_binding_audit_device_created\").on(\n\t\t\ttable.device_id,\n\t\t\ttable.created_at,\n\t\t\ttable.event_id,\n\t\t),\n\t],\n);\n\nexport const projectRecipients = sqliteTable(\n\t\"project_recipients\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\trecipient_kind: text(\"recipient_kind\").notNull(),\n\t\trecipient_id: text(\"recipient_id\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\tpolicy_revision: text(\"policy_revision\").notNull(),\n\t\tmigration_state: text(\"migration_state\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\"),\n\t\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tpk: primaryKey({\n\t\t\tcolumns: [table.canonical_project_identity, table.recipient_kind, table.recipient_id],\n\t\t}),\n\t\tprojectStatusIdx: index(\"idx_project_recipients_project_status\").on(\n\t\t\ttable.canonical_project_identity,\n\t\t\ttable.status,\n\t\t),\n\t\trecipientStatusIdx: index(\"idx_project_recipients_recipient_status\").on(\n\t\t\ttable.recipient_kind,\n\t\t\ttable.recipient_id,\n\t\t\ttable.status,\n\t\t),\n\t}),\n);\n\nexport type ProjectRecipient = typeof projectRecipients.$inferSelect;\nexport type NewProjectRecipient = typeof projectRecipients.$inferInsert;\n\nexport const legacyTeamSetupDrafts = sqliteTable(\n\t\"legacy_team_setup_drafts\",\n\t{\n\t\tattempt_id: text(\"attempt_id\").primaryKey(),\n\t\tcandidate_id: text(\"candidate_id\").notNull(),\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\tstate: text(\"state\").notNull().default(\"needs_setup\"),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\troster_fingerprint: text(\"roster_fingerprint\").notNull(),\n\t\tprojection_fingerprint: text(\"projection_fingerprint\").notNull(),\n\t\tfinish_digest: text(\"finish_digest\"),\n\t\tsafe_error_code: text(\"safe_error_code\"),\n\t\tcompleted_team_id: text(\"completed_team_id\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t\tcompleted_at: text(\"completed_at\"),\n\t\tsuperseded_at: text(\"superseded_at\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_legacy_team_setup_drafts_candidate_state\").on(\n\t\t\ttable.candidate_id,\n\t\t\ttable.state,\n\t\t\ttable.created_at,\n\t\t),\n\t\tindex(\"idx_legacy_team_setup_drafts_state_updated\").on(table.state, table.updated_at),\n\t\tindex(\"idx_legacy_team_setup_drafts_finish_digest\").on(table.finish_digest),\n\t],\n);\n\nexport type LegacyTeamSetupDraft = typeof legacyTeamSetupDrafts.$inferSelect;\nexport type NewLegacyTeamSetupDraft = typeof legacyTeamSetupDrafts.$inferInsert;\n\nexport const legacyTeamSetupCompletions = sqliteTable(\n\t\"legacy_team_setup_completions\",\n\t{\n\t\tattempt_id: text(\"attempt_id\").notNull(),\n\t\tfinish_digest: text(\"finish_digest\").notNull(),\n\t\tcandidate_ref: text(\"candidate_ref\").notNull(),\n\t\tconfirmed_access_delta_digest: text(\"confirmed_access_delta_digest\").notNull(),\n\t\tcompleted_team_id: text(\"completed_team_id\").notNull(),\n\t\tresponse_json: text(\"response_json\").notNull(),\n\t\tcompleted_at: text(\"completed_at\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_legacy_team_setup_completions_attempt_finish\").on(\n\t\t\ttable.attempt_id,\n\t\t\ttable.finish_digest,\n\t\t),\n\t\tindex(\"idx_legacy_team_setup_completions_exact_replay\").on(\n\t\t\ttable.candidate_ref,\n\t\t\ttable.attempt_id,\n\t\t\ttable.finish_digest,\n\t\t\ttable.confirmed_access_delta_digest,\n\t\t),\n\t],\n);\n\nexport type LegacyTeamSetupCompletion = typeof legacyTeamSetupCompletions.$inferSelect;\nexport type NewLegacyTeamSetupCompletion = typeof legacyTeamSetupCompletions.$inferInsert;\n\nexport const legacyTeamSetupDraftDevices = sqliteTable(\n\t\"legacy_team_setup_draft_devices\",\n\t{\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => legacyTeamSetupDrafts.attempt_id, { onDelete: \"cascade\" }),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tdevice_ref: text(\"device_ref\").notNull(),\n\t\tkey_fingerprint: text(\"key_fingerprint\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tenabled: integer(\"enabled\", { mode: \"boolean\" }).notNull(),\n\t\texisting_identity_id: text(\"existing_identity_id\"),\n\t\texisting_assignment_version: integer(\"existing_assignment_version\"),\n\t\tverified_evidence_kind: text(\"verified_evidence_kind\"),\n\t\tidentity_evidence: text(\"identity_evidence\"),\n\t\tdecision: text(\"decision\").notNull().default(\"unresolved\"),\n\t\ttarget_identity_id: text(\"target_identity_id\"),\n\t\texpected_assignment_kind: text(\"expected_assignment_kind\"),\n\t\texpected_assignment_version: integer(\"expected_assignment_version\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.attempt_id, table.device_id] }),\n\t\tuniqueIndex(\"idx_legacy_team_setup_devices_attempt_ref\").on(table.attempt_id, table.device_ref),\n\t\tindex(\"idx_legacy_team_setup_devices_attempt_decision\").on(table.attempt_id, table.decision),\n\t],\n);\n\nexport type LegacyTeamSetupDraftDevice = typeof legacyTeamSetupDraftDevices.$inferSelect;\nexport type NewLegacyTeamSetupDraftDevice = typeof legacyTeamSetupDraftDevices.$inferInsert;\n\nexport const legacyTeamSetupDraftProjects = sqliteTable(\n\t\"legacy_team_setup_draft_projects\",\n\t{\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => legacyTeamSetupDrafts.attempt_id, { onDelete: \"cascade\" }),\n\t\tproject_ref: text(\"project_ref\").notNull(),\n\t\tsource_project_identity: text(\"source_project_identity\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\").notNull(),\n\t\tresolution_kind: text(\"resolution_kind\").notNull().default(\"unresolved\"),\n\t\tresolved_project_identity: text(\"resolved_project_identity\"),\n\t\ttarget_scope_id: text(\"target_scope_id\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.attempt_id, table.project_ref] }),\n\t\tindex(\"idx_legacy_team_setup_projects_attempt_resolution\").on(\n\t\t\ttable.attempt_id,\n\t\t\ttable.resolution_kind,\n\t\t),\n\t],\n);\n\nexport type LegacyTeamSetupDraftProject = typeof legacyTeamSetupDraftProjects.$inferSelect;\nexport type NewLegacyTeamSetupDraftProject = typeof legacyTeamSetupDraftProjects.$inferInsert;\n\nexport const recipientManagedProjectProjections = sqliteTable(\n\t\"recipient_managed_project_projections\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tmanaged_scope_id: text(\"managed_scope_id\").notNull(),\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\trecipient_identity_id: text(\"recipient_identity_id\").notNull(),\n\t\taccepting_device_id: text(\"accepting_device_id\").notNull(),\n\t\tsource_operation_id: text(\"source_operation_id\").notNull(),\n\t\treviewed_project_set_digest: text(\"reviewed_project_set_digest\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\taccepted_at: text(\"accepted_at\").notNull(),\n\t\trevoked_at: text(\"revoked_at\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.source_operation_id, table.canonical_project_identity],\n\t\t}),\n\t\tindex(\"idx_recipient_managed_projects_identity_status\").on(\n\t\t\ttable.recipient_identity_id,\n\t\t\ttable.status,\n\t\t),\n\t\tindex(\"idx_recipient_managed_projects_scope_authority\").on(\n\t\t\ttable.managed_scope_id,\n\t\t\ttable.coordinator_id,\n\t\t\ttable.group_id,\n\t\t\ttable.status,\n\t\t),\n\t],\n);\n\nexport type RecipientManagedProjectProjection =\n\ttypeof recipientManagedProjectProjections.$inferSelect;\nexport type NewRecipientManagedProjectProjection =\n\ttypeof recipientManagedProjectProjections.$inferInsert;\n\nexport const recipientPolicyAuthorityStates = sqliteTable(\"recipient_policy_authority_states\", {\n\tcanonical_project_identity: text(\"canonical_project_identity\").primaryKey(),\n\tauthority_state: text(\"authority_state\").notNull().default(\"legacy\"),\n\tgeneration: integer(\"generation\").notNull().default(0),\n\tdesired_devices_digest: text(\"desired_devices_digest\"),\n\tcurrent_devices_digest: text(\"current_devices_digest\"),\n\tstable_parity_evidence_digest: text(\"stable_parity_evidence_digest\"),\n\tstable_parity_passed_at: text(\"stable_parity_passed_at\"),\n\tfresh_snapshot_fingerprint: text(\"fresh_snapshot_fingerprint\"),\n\tfresh_snapshot_observed_at: text(\"fresh_snapshot_observed_at\"),\n\tsafe_error_code: text(\"safe_error_code\"),\n\tstate_changed_at: text(\"state_changed_at\").notNull(),\n\tlast_error_at: text(\"last_error_at\"),\n\tattempt_count: integer(\"attempt_count\").notNull().default(0),\n\tlast_attempt_at: text(\"last_attempt_at\"),\n\twake_epoch: integer(\"wake_epoch\").notNull().default(0),\n\tlast_completed_at: text(\"last_completed_at\"),\n\tlease_owner: text(\"lease_owner\"),\n\tlease_acquired_at: text(\"lease_acquired_at\"),\n\tlease_expires_at: text(\"lease_expires_at\"),\n\tcreated_at: text(\"created_at\").notNull(),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type RecipientPolicyAuthorityStateRow = typeof recipientPolicyAuthorityStates.$inferSelect;\nexport type NewRecipientPolicyAuthorityStateRow =\n\ttypeof recipientPolicyAuthorityStates.$inferInsert;\n\nexport const recipientPolicyReconciliationSteps = sqliteTable(\n\t\"recipient_policy_reconciliation_steps\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\tgeneration: integer(\"generation\").notNull(),\n\t\tstep_key: text(\"step_key\").notNull(),\n\t\teffect_id: text(\"effect_id\").notNull(),\n\t\tpayload_digest: text(\"payload_digest\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"pending\"),\n\t\tattempt_count: integer(\"attempt_count\").notNull().default(0),\n\t\tstarted_at: text(\"started_at\"),\n\t\tcompleted_at: text(\"completed_at\"),\n\t\tlast_attempt_at: text(\"last_attempt_at\"),\n\t\tsafe_error_code: text(\"safe_error_code\"),\n\t\terror_at: text(\"error_at\"),\n\t\tlease_owner: text(\"lease_owner\"),\n\t\tlease_acquired_at: text(\"lease_acquired_at\"),\n\t\tlease_expires_at: text(\"lease_expires_at\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.canonical_project_identity, table.generation, table.step_key],\n\t\t}),\n\t\tuniqueIndex(\"idx_recipient_policy_reconciliation_steps_effect\").on(table.effect_id),\n\t\tindex(\"idx_recipient_policy_reconciliation_steps_status\").on(\n\t\t\ttable.canonical_project_identity,\n\t\t\ttable.status,\n\t\t),\n\t\tindex(\"idx_recipient_policy_reconciliation_steps_pending_refresh\")\n\t\t\t.on(table.canonical_project_identity, table.generation, table.step_key)\n\t\t\t.where(\n\t\t\t\tsql`${table.status} IN ('pending', 'running', 'failed') AND ${table.step_key} GLOB 'refresh-after-revocations-v2:*'`,\n\t\t\t),\n\t],\n);\n\nexport type RecipientPolicyReconciliationStep =\n\ttypeof recipientPolicyReconciliationSteps.$inferSelect;\nexport type NewRecipientPolicyReconciliationStep =\n\ttypeof recipientPolicyReconciliationSteps.$inferInsert;\n\nexport const recipientPolicyDenyOverlays = sqliteTable(\n\t\"recipient_policy_deny_overlays\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tgeneration: integer(\"generation\").notNull(),\n\t\treason_code: text(\"reason_code\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.canonical_project_identity, table.scope_id, table.device_id],\n\t\t}),\n\t\tindex(\"idx_recipient_policy_deny_overlays_scope_device\").on(table.scope_id, table.device_id),\n\t],\n);\n\nexport type RecipientPolicyDenyOverlay = typeof recipientPolicyDenyOverlays.$inferSelect;\nexport type NewRecipientPolicyDenyOverlay = typeof recipientPolicyDenyOverlays.$inferInsert;\n\nexport const schema = {\n\tdeviceIdentityBindingCommits,\n\tdeviceIdentityBindingAudit,\n\tsessions,\n\treplicationScopes,\n\tprojectScopeMappings,\n\tscopeMemberships,\n\tartifacts,\n\tmemoryItems,\n\tmemoryFileRefs,\n\tmemoryConceptRefs,\n\tusageEvents,\n\tretrievalAttempts,\n\tretrievalExposures,\n\toutcomeEvidence,\n\tattributionAssessments,\n\tattributionAssessmentEvidence,\n\trawEvents,\n\trawEventSessions,\n\topencodeSessions,\n\tpiImportState,\n\trawEventFlushBatches,\n\tuserPrompts,\n\tsessionSummaries,\n\treplicationOps,\n\treplicationCursors,\n\treplicationCursorsV2,\n\tsyncPeers,\n\tsyncNonces,\n\tsyncDevice,\n\tsyncAttempts,\n\tsyncScopeRejections,\n\tsyncDaemonState,\n\tsyncResetState,\n\tsyncResetStateV2,\n\tsyncRetentionStateV2,\n\trawEventIngestSamples,\n\trawEventIngestStats,\n\tcoordinatorGroupPreferences,\n\tactors,\n\trecipientPolicyReviewResolutions,\n\tcoordinatorEnrollmentReconciliationIssues,\n\tpolicyTeams,\n\tpolicyTeamMemberships,\n\tpolicyTeamDeviceDecisions,\n\tidentityDevices,\n\tprojectRecipients,\n\tlegacyTeamSetupDrafts,\n\tlegacyTeamSetupCompletions,\n\tlegacyTeamSetupDraftDevices,\n\tlegacyTeamSetupDraftProjects,\n\trecipientManagedProjectProjections,\n\trecipientPolicyAuthorityStates,\n\trecipientPolicyReconciliationSteps,\n\trecipientPolicyDenyOverlays,\n};\n","/**\n * Device identity management for the codemem sync system.\n *\n * Handles Ed25519 keypair generation, fingerprinting, and optional\n * keychain storage. Ported from codemem/sync_identity.py.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { connect as connectDb, resolveDbPath } from \"./db.js\";\nimport { codememHomeDir } from \"./home.js\";\nimport { adoptLocalCapture, hasPendingLocalCapture } from \"./memory-local-capture.js\";\nimport { readCodememConfigFile } from \"./observer-config.js\";\nimport * as schema from \"./schema.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst PRIVATE_KEY_NAME = \"device.key\";\nconst PUBLIC_KEY_NAME = \"device.key.pub\";\nconst KEYCHAIN_SERVICE = \"codemem-sync\";\n\nfunction defaultKeysDir(): string {\n\treturn join(codememHomeDir(), \".config\", \"codemem\", \"keys\");\n}\n\n// ---------------------------------------------------------------------------\n// Fingerprint\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Key store mode\n// ---------------------------------------------------------------------------\n\nfunction keyStoreMode(): \"file\" | \"keychain\" {\n\tconst env = process.env.CODEMEM_SYNC_KEY_STORE?.toLowerCase();\n\tif (env === \"keychain\") return \"keychain\";\n\treturn \"file\";\n}\n\n// ---------------------------------------------------------------------------\n// CLI availability helpers\n// ---------------------------------------------------------------------------\n\nfunction cliAvailable(cmd: string): boolean {\n\ttry {\n\t\texecFileSync(\"which\", [cmd], { stdio: \"pipe\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Keychain storage (platform-specific)\n// ---------------------------------------------------------------------------\n\nfunction warnKeychainLimitations(): void {\n\tif (process.platform !== \"darwin\") return;\n\tif (keyStoreMode() !== \"keychain\") return;\n\tif (process.env.CODEMEM_SYNC_KEYCHAIN_WARN === \"0\") return;\n\tconsole.warn(\n\t\t\"[codemem] keychain storage on macOS uses the `security` CLI and may expose the key in process arguments.\",\n\t);\n}\n\n/** Store a private key in the OS keychain. Returns true on success. */\nexport function storePrivateKeyKeychain(privateKey: Buffer, deviceId: string): boolean {\n\tif (process.platform === \"linux\") {\n\t\tif (!cliAvailable(\"secret-tool\")) return false;\n\t\ttry {\n\t\t\texecFileSync(\n\t\t\t\t\"secret-tool\",\n\t\t\t\t[\"store\", \"--label\", \"codemem sync key\", \"service\", KEYCHAIN_SERVICE, \"account\", deviceId],\n\t\t\t\t{ input: privateKey, stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (process.platform === \"darwin\") {\n\t\tif (!cliAvailable(\"security\")) return false;\n\t\ttry {\n\t\t\texecFileSync(\n\t\t\t\t\"security\",\n\t\t\t\t[\n\t\t\t\t\t\"add-generic-password\",\n\t\t\t\t\t\"-a\",\n\t\t\t\t\tdeviceId,\n\t\t\t\t\t\"-s\",\n\t\t\t\t\tKEYCHAIN_SERVICE,\n\t\t\t\t\t\"-w\",\n\t\t\t\t\tprivateKey.toString(\"utf-8\"),\n\t\t\t\t\t\"-U\",\n\t\t\t\t],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Load a private key from the OS keychain. Returns null if unavailable. */\nexport function loadPrivateKeyKeychain(deviceId: string): Buffer | null {\n\tif (process.platform === \"linux\") {\n\t\tif (!cliAvailable(\"secret-tool\")) return null;\n\t\ttry {\n\t\t\tconst out = execFileSync(\n\t\t\t\t\"secret-tool\",\n\t\t\t\t[\"lookup\", \"service\", KEYCHAIN_SERVICE, \"account\", deviceId],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn Buffer.from(out);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (process.platform === \"darwin\") {\n\t\tif (!cliAvailable(\"security\")) return null;\n\t\ttry {\n\t\t\tconst out = execFileSync(\n\t\t\t\t\"security\",\n\t\t\t\t[\"find-generic-password\", \"-a\", deviceId, \"-s\", KEYCHAIN_SERVICE, \"-w\"],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn Buffer.from(out);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Key path resolution\n// ---------------------------------------------------------------------------\n\n/** Resolve private and public key file paths. */\nexport function resolveKeyPaths(keysDir?: string): [string, string] {\n\tconst dir = keysDir ?? defaultKeysDir();\n\treturn [join(dir, PRIVATE_KEY_NAME), join(dir, PUBLIC_KEY_NAME)];\n}\n\n// ---------------------------------------------------------------------------\n// Key file I/O\n// ---------------------------------------------------------------------------\n\n/** Read the public key from disk. Returns null if missing or empty. */\nexport function loadPublicKey(keysDir?: string): string | null {\n\tconst [, publicPath] = resolveKeyPaths(keysDir);\n\tif (!existsSync(publicPath)) return null;\n\tconst content = readFileSync(publicPath, \"utf-8\").trim();\n\treturn content || null;\n}\n\n/**\n * Read the private key from disk with keychain fallback. When dbPath identifies an\n * enrolled device, only a key matching that stored identity is returned.\n */\nexport function loadPrivateKey(\n\tkeysDir?: string,\n\tdbPath?: string,\n\tdeviceId?: string,\n): Buffer | null {\n\tconst storedIdentity = dbPath === undefined ? null : loadStoredDeviceIdentity(dbPath);\n\treturn loadPrivateKeyForIdentity(keysDir, deviceId, storedIdentity, () =>\n\t\tdbPath === undefined && !deviceId ? loadStoredDeviceIdentity() : storedIdentity,\n\t);\n}\n\nfunction loadPrivateKeyForIdentity(\n\tkeysDir: string | undefined,\n\tdeviceId: string | undefined,\n\tstoredIdentity: StoredDeviceIdentity | null,\n\tkeychainIdentity: () => StoredDeviceIdentity | null,\n): Buffer | null {\n\tconst [privatePath] = resolveKeyPaths(keysDir);\n\tconst privateKeyFile = readPrivateKeyFile(privatePath);\n\tconst privateKeyFromFile = isUsableEd25519PrivateKey(privateKeyFile.value)\n\t\t? privateKeyFile.value\n\t\t: null;\n\tif (storedIdentity && deviceId && storedIdentity.deviceId !== deviceId) return null;\n\tif (\n\t\tprivateKeyFromFile &&\n\t\t(!storedIdentity || privateKeyMatchesStoredIdentity(privateKeyFromFile, storedIdentity))\n\t) {\n\t\treturn privateKeyFromFile;\n\t}\n\tif (keyStoreMode() === \"keychain\") {\n\t\tconst identity = keychainIdentity();\n\t\tconst resolvedDeviceId = deviceId ?? identity?.deviceId;\n\t\tif (resolvedDeviceId) {\n\t\t\tconst keychainValue = loadPrivateKeyKeychain(resolvedDeviceId);\n\t\t\tif (\n\t\t\t\tisUsableEd25519PrivateKey(keychainValue) &&\n\t\t\t\t(!identity || privateKeyMatchesStoredIdentity(keychainValue, identity))\n\t\t\t) {\n\t\t\t\treturn keychainValue;\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\ninterface StoredDeviceIdentity {\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\n/** Read-only counterpart of signing-key selection, using the caller's connection.\n * Derives public bytes from the actual private key; never generates or repairs keys. */\nexport function loadRuntimeSigningPublicKey(\n\tdb: Database,\n\toptions: { deviceId: string; keysDir?: string },\n): string | null {\n\ttry {\n\t\tconst rows = db\n\t\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t\t.all() as Array<{ device_id: string; public_key: string; fingerprint: string }>;\n\t\tconst row = rows[0];\n\t\tif (rows.length !== 1 || !row || row.device_id !== options.deviceId) return null;\n\t\tconst identity = {\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t};\n\t\tconst privateKey = loadPrivateKeyForIdentity(\n\t\t\toptions.keysDir,\n\t\t\toptions.deviceId,\n\t\t\tidentity,\n\t\t\t() => identity,\n\t\t);\n\t\treturn privateKey ? derivePublicKey(privateKey) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Load the enrolled identity from the database for identity-aware key selection. */\nfunction loadStoredDeviceIdentity(dbPath?: string): StoredDeviceIdentity | null {\n\tconst path = resolveDbPath(dbPath);\n\tif (!existsSync(path)) return null;\n\tconst conn = connectDb(path);\n\ttry {\n\t\tconst d = drizzle(conn, { schema });\n\t\tconst row = d\n\t\t\t.select({\n\t\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\t\tpublic_key: schema.syncDevice.public_key,\n\t\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t\t})\n\t\t\t.from(schema.syncDevice)\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t};\n\t} finally {\n\t\tconn.close();\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Key generation & validation\n// ---------------------------------------------------------------------------\n\nfunction canonicalEd25519PublicKey(publicKey: string): string | null {\n\tconst [keyType, keyData] = publicKey.trim().split(/\\s+/);\n\tif (keyType !== \"ssh-ed25519\" || !keyData) return null;\n\treturn `${keyType} ${keyData}`;\n}\n\nfunction publicKeyLooksValid(publicKey: string): boolean {\n\treturn canonicalEd25519PublicKey(publicKey) !== null;\n}\n\nfunction backupInvalidKeyFile(path: string, stamp: string): void {\n\tif (!existsSync(path)) return;\n\tconst backupPath = join(dirname(path), `${basename(path)}.invalid-${stamp}`);\n\trenameSync(path, backupPath);\n}\n\n/**\n * Generate an Ed25519 keypair using Node's native crypto.\n * Stores private key as PEM (PKCS8), public key as SSH format for compatibility.\n */\nexport function generateKeypair(privatePath: string, publicPath: string): void {\n\tmkdirSync(dirname(privatePath), { recursive: true });\n\tif (existsSync(privatePath) && existsSync(publicPath)) return;\n\n\tif (existsSync(privatePath) && !existsSync(publicPath)) {\n\t\t// Private key exists but public is missing — derive public from private\n\t\ttry {\n\t\t\tconst privKeyObj = loadPrivateKeyObject(privatePath);\n\t\t\tconst pubKeyObj = createPublicKey(privKeyObj);\n\t\t\tconst sshPub = pubKeyObj.export({ type: \"spki\", format: \"der\" });\n\t\t\tconst sshPubStr = derToSshEd25519(sshPub);\n\t\t\tif (sshPubStr && publicKeyLooksValid(sshPubStr)) {\n\t\t\t\twriteFileSync(publicPath, `${sshPubStr}\\n`, { mode: 0o644 });\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Derivation failed — fall through to full regeneration with backup\n\t\t}\n\t\t// Back up the orphaned private key before regenerating\n\t\tconst stamp = new Date().toISOString().replace(/[:.]/g, \"\");\n\t\trenameSync(privatePath, `${privatePath}.orphan-${stamp}`);\n\t}\n\n\tconst { publicKey, privateKey } = generateKeyPairSync(\"ed25519\");\n\n\t// Export private key as PEM (PKCS8)\n\tconst privatePem = privateKey.export({ type: \"pkcs8\", format: \"pem\" }) as string;\n\twriteFileSync(privatePath, privatePem, { mode: 0o600 });\n\n\t// Export public key as SSH wire format: \"ssh-ed25519 <base64>\"\n\tconst pubDer = publicKey.export({ type: \"spki\", format: \"der\" });\n\tconst sshPub = derToSshEd25519(pubDer);\n\tif (!sshPub) {\n\t\tthrow new Error(\"failed to convert public key to SSH format\");\n\t}\n\twriteFileSync(publicPath, `${sshPub}\\n`, { mode: 0o644 });\n}\n\n/**\n * Convert a DER-encoded SPKI Ed25519 public key to SSH wire format.\n * The last 32 bytes of the DER are the raw Ed25519 public key.\n */\nfunction derToSshEd25519(spkiDer: Buffer): string | null {\n\t// Ed25519 SPKI DER is 44 bytes: 12-byte header + 32-byte key\n\tif (spkiDer.length !== 44) return null;\n\tconst rawKey = spkiDer.subarray(spkiDer.length - 32);\n\n\t// SSH wire format: string \"ssh-ed25519\" + string <32-byte key>\n\tconst keyType = Buffer.from(\"ssh-ed25519\");\n\tconst buf = Buffer.alloc(4 + keyType.length + 4 + rawKey.length);\n\tlet offset = 0;\n\tbuf.writeUInt32BE(keyType.length, offset);\n\toffset += 4;\n\tkeyType.copy(buf, offset);\n\toffset += keyType.length;\n\tbuf.writeUInt32BE(rawKey.length, offset);\n\toffset += 4;\n\trawKey.copy(buf, offset);\n\n\treturn `ssh-ed25519 ${buf.toString(\"base64\")}`;\n}\n\n/**\n * Load a private key that may be in OpenSSH format (existing keys) or\n * PKCS8 PEM format (newly generated keys). Node's createPrivateKey\n * handles both transparently.\n */\nfunction loadPrivateKeyObject(privatePath: string): ReturnType<typeof createPrivateKey> {\n\treturn loadPrivateKeyObjectFromBytes(readFileSync(privatePath));\n}\n\nfunction loadPrivateKeyObjectFromBytes(raw: Buffer): ReturnType<typeof createPrivateKey> {\n\t// Try PKCS8 PEM first (our generated format), then OpenSSH\n\ttry {\n\t\treturn createPrivateKey(raw);\n\t} catch {\n\t\treturn createPrivateKey({ key: raw, format: \"pem\", type: \"pkcs8\" });\n\t}\n}\n\nfunction derivePublicKey(privateKey: Buffer): string {\n\tconst privateKeyObject = loadPrivateKeyObjectFromBytes(privateKey);\n\tif (privateKeyObject.asymmetricKeyType !== \"ed25519\") {\n\t\tthrow new Error(\"private key is not Ed25519\");\n\t}\n\tconst publicKeyObject = createPublicKey(privateKeyObject);\n\tconst publicKeyDer = publicKeyObject.export({ type: \"spki\", format: \"der\" });\n\tconst publicKey = derToSshEd25519(publicKeyDer);\n\tif (!publicKey || !publicKeyLooksValid(publicKey)) {\n\t\tthrow new Error(\"failed to derive public key\");\n\t}\n\treturn publicKey;\n}\n\nfunction isUsableEd25519PrivateKey(privateKey: Buffer | null): privateKey is Buffer {\n\tif (!privateKey) return false;\n\ttry {\n\t\tderivePublicKey(privateKey);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ntype PrivateKeyFileRead =\n\t| { status: \"available\"; value: Buffer }\n\t| { status: \"missing\" | \"unreadable\"; value: null };\n\nfunction readPrivateKeyFile(privatePath: string): PrivateKeyFileRead {\n\ttry {\n\t\tif (!existsSync(privatePath)) return { status: \"missing\", value: null };\n\t\treturn { status: \"available\", value: readFileSync(privatePath) };\n\t} catch {\n\t\treturn { status: \"unreadable\", value: null };\n\t}\n}\n\nfunction privateKeyMatchesStoredIdentity(\n\tprivateKey: Buffer,\n\tidentity: StoredDeviceIdentity,\n): boolean {\n\tconst storedPublicKey = canonicalEd25519PublicKey(identity.publicKey);\n\tif (!storedPublicKey || fingerprintPublicKey(identity.publicKey) !== identity.fingerprint) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn canonicalEd25519PublicKey(derivePublicKey(privateKey)) === storedPublicKey;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport type DeviceIdentityErrorCode =\n\t| \"device_identity_private_key_missing\"\n\t| \"device_identity_private_key_invalid\"\n\t| \"device_identity_key_mismatch\";\n\nexport class DeviceIdentityError extends Error {\n\treadonly code: DeviceIdentityErrorCode;\n\n\tconstructor(code: DeviceIdentityErrorCode, detail: string) {\n\t\tsuper(`${code}: ${detail}`);\n\t\tthis.name = \"DeviceIdentityError\";\n\t\tthis.code = code;\n\t}\n}\n\nfunction existingIdentityError(code: DeviceIdentityErrorCode, detail: string): DeviceIdentityError {\n\treturn new DeviceIdentityError(code, detail);\n}\n\n/** Validate that an existing keypair is consistent. */\nexport function validateExistingKeypair(privatePath: string, publicPath: string): boolean {\n\tif (!existsSync(privatePath) || !existsSync(publicPath)) return false;\n\tconst publicKey = readFileSync(publicPath, \"utf-8\").trim();\n\tif (!publicKey || !publicKeyLooksValid(publicKey)) return false;\n\ttry {\n\t\tconst privKeyObj = loadPrivateKeyObject(privatePath);\n\t\tconst pubKeyObj = createPublicKey(privKeyObj);\n\t\tconst pubDer = pubKeyObj.export({ type: \"spki\", format: \"der\" });\n\t\tconst derived = derToSshEd25519(pubDer);\n\t\tif (!derived || !publicKeyLooksValid(derived)) return false;\n\t\t// Auto-fix mismatched public key file\n\t\tif (canonicalEd25519PublicKey(derived) !== canonicalEd25519PublicKey(publicKey)) {\n\t\t\twriteFileSync(publicPath, `${derived}\\n`, \"utf-8\");\n\t\t}\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Main entry: ensure device identity\n// ---------------------------------------------------------------------------\n\nexport interface EnsureDeviceIdentityOptions {\n\tkeysDir?: string;\n\tdeviceId?: string;\n}\n\n/** Device identity ensure boundary; constructors and ordinary memory reads do not associate. */\nfunction adoptPendingCaptureForEnsuredIdentity(\n\tdb: Database,\n\tdeviceId: string,\n\tpublicKey: string,\n): void {\n\tif (!hasPendingLocalCapture(db)) return;\n\tconst configuredDevice = process.env.CODEMEM_DEVICE_ID?.trim();\n\tif (configuredDevice && configuredDevice !== deviceId) return;\n\tconst config = readCodememConfigFile();\n\tlet configuredActor = typeof config.actor_id === \"string\" ? config.actor_id.trim() : undefined;\n\tif (Object.hasOwn(process.env, \"CODEMEM_ACTOR_ID\"))\n\t\tconfiguredActor = process.env.CODEMEM_ACTOR_ID?.trim();\n\ttry {\n\t\tdb.transaction(() =>\n\t\t\tadoptLocalCapture(db, deviceId, {\n\t\t\t\texpectedPublicKey: publicKey,\n\t\t\t\tactorId: configuredActor || `local:${deviceId}`,\n\t\t\t\truntimeDeviceId: deviceId,\n\t\t\t}),\n\t\t).immediate();\n\t} catch (error) {\n\t\t// Only the plain actor conflict is nonfatal; SQLite/key failures propagate.\n\t\tif (\n\t\t\t!(error instanceof Error) ||\n\t\t\terror.constructor !== Error ||\n\t\t\terror.message !== \"device_adoption_actor_conflict\"\n\t\t)\n\t\t\tthrow error;\n\t}\n}\n\n/**\n * Ensure this device has a keypair and a row in the sync_device table.\n *\n * Returns [deviceId, fingerprint]. Creates keys and DB row if missing,\n * validates and repairs if existing.\n */\nexport function ensureDeviceIdentity(\n\tdb: Database,\n\toptions?: EnsureDeviceIdentityOptions,\n): [string, string] {\n\tconst keysDir = options?.keysDir ?? defaultKeysDir();\n\tconst [privatePath, publicPath] = resolveKeyPaths(keysDir);\n\twarnKeychainLimitations();\n\n\t// Check for existing device row\n\tconst d = drizzle(db, { schema });\n\tconst row = deviceRowForEnsure(db);\n\tconst existingDeviceId = row?.device_id ?? \"\";\n\tconst existingPublicKey = row?.public_key ?? \"\";\n\tconst existingFingerprint = row?.fingerprint ?? \"\";\n\n\tif (existingDeviceId) {\n\t\tconst privateKeyFile = readPrivateKeyFile(privatePath);\n\t\tconst validPrivateKeyFromFile = isUsableEd25519PrivateKey(privateKeyFile.value)\n\t\t\t? privateKeyFile.value\n\t\t\t: null;\n\t\tconst storedIdentity: StoredDeviceIdentity = {\n\t\t\tdeviceId: existingDeviceId,\n\t\t\tpublicKey: existingPublicKey,\n\t\t\tfingerprint: existingFingerprint,\n\t\t};\n\n\t\tconst fileMatchesStoredIdentity =\n\t\t\tvalidPrivateKeyFromFile !== null &&\n\t\t\tprivateKeyMatchesStoredIdentity(validPrivateKeyFromFile, storedIdentity);\n\t\tconst privateKeyFromKeychain =\n\t\t\t!fileMatchesStoredIdentity && keyStoreMode() === \"keychain\"\n\t\t\t\t? loadPrivateKeyKeychain(existingDeviceId)\n\t\t\t\t: null;\n\t\tconst validPrivateKeyFromKeychain = isUsableEd25519PrivateKey(privateKeyFromKeychain)\n\t\t\t? privateKeyFromKeychain\n\t\t\t: null;\n\t\tconst keychainMatchesStoredIdentity =\n\t\t\tvalidPrivateKeyFromKeychain !== null &&\n\t\t\tprivateKeyMatchesStoredIdentity(validPrivateKeyFromKeychain, storedIdentity);\n\t\tconst privateKey = fileMatchesStoredIdentity\n\t\t\t? validPrivateKeyFromFile\n\t\t\t: keychainMatchesStoredIdentity\n\t\t\t\t? validPrivateKeyFromKeychain\n\t\t\t\t: null;\n\t\tif (!privateKey) {\n\t\t\tif (validPrivateKeyFromFile || validPrivateKeyFromKeychain) {\n\t\t\t\tthrow existingIdentityError(\n\t\t\t\t\t\"device_identity_key_mismatch\",\n\t\t\t\t\t\"the restored private key does not match the peer identity stored in the database\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow existingIdentityError(\n\t\t\t\tprivateKeyFile.status !== \"missing\" || privateKeyFromKeychain\n\t\t\t\t\t? \"device_identity_private_key_invalid\"\n\t\t\t\t\t: \"device_identity_private_key_missing\",\n\t\t\t\tprivateKeyFile.status !== \"missing\" || privateKeyFromKeychain\n\t\t\t\t\t? \"the restored private key is unreadable or unsupported; restore the original Ed25519 key material\"\n\t\t\t\t\t: \"the database contains an existing peer identity but its private key is unavailable; restore the original key material with the database\",\n\t\t\t);\n\t\t}\n\n\t\tlet derivedPublicKey: string;\n\t\ttry {\n\t\t\tderivedPublicKey = derivePublicKey(privateKey);\n\t\t} catch {\n\t\t\tthrow existingIdentityError(\n\t\t\t\t\"device_identity_private_key_invalid\",\n\t\t\t\t\"the restored private key is unreadable or unsupported; restore the original Ed25519 key material\",\n\t\t\t);\n\t\t}\n\t\tconst storedPublicKey = canonicalEd25519PublicKey(existingPublicKey);\n\t\tif (\n\t\t\t!storedPublicKey ||\n\t\t\tcanonicalEd25519PublicKey(derivedPublicKey) !== storedPublicKey ||\n\t\t\tfingerprintPublicKey(existingPublicKey) !== existingFingerprint\n\t\t) {\n\t\t\tthrow existingIdentityError(\n\t\t\t\t\"device_identity_key_mismatch\",\n\t\t\t\t\"the restored private key does not match the peer identity stored in the database\",\n\t\t\t);\n\t\t}\n\n\t\tconst publicKeyOnDisk = loadPublicKey(keysDir);\n\t\tif (publicKeyOnDisk !== existingPublicKey) {\n\t\t\tmkdirSync(dirname(publicPath), { recursive: true });\n\t\t\twriteFileSync(publicPath, `${existingPublicKey}\\n`, { mode: 0o644 });\n\t\t}\n\t\tif (keyStoreMode() === \"keychain\" && fileMatchesStoredIdentity) {\n\t\t\tstorePrivateKeyKeychain(privateKey, existingDeviceId);\n\t\t}\n\t\tadoptPendingCaptureForEnsuredIdentity(db, existingDeviceId, derivedPublicKey);\n\t\treturn [existingDeviceId, existingFingerprint];\n\t}\n\n\t// Validate or regenerate keys\n\tlet keysReady = existsSync(privatePath) && existsSync(publicPath);\n\tif (keysReady && !validateExistingKeypair(privatePath, publicPath)) {\n\t\tconst stamp = new Date()\n\t\t\t.toISOString()\n\t\t\t.replace(/[-:T.Z]/g, \"\")\n\t\t\t.slice(0, 20);\n\t\tbackupInvalidKeyFile(privatePath, stamp);\n\t\tbackupInvalidKeyFile(publicPath, stamp);\n\t\tkeysReady = false;\n\t}\n\tif (!keysReady) {\n\t\tgenerateKeypair(privatePath, publicPath);\n\t}\n\n\tconst publicKey = readFileSync(publicPath, \"utf-8\").trim();\n\tif (!publicKey) {\n\t\tthrow new Error(\"public key missing\");\n\t}\n\tconst fingerprint = fingerprintPublicKey(publicKey);\n\tconst now = new Date().toISOString();\n\n\t// Insert new device row\n\tconst resolvedDeviceId = options?.deviceId ?? randomUUID();\n\tdb.transaction(() => {\n\t\td.insert(schema.syncDevice)\n\t\t\t.values({ device_id: resolvedDeviceId, public_key: publicKey, fingerprint, created_at: now })\n\t\t\t.run();\n\t\tadoptPendingCaptureForEnsuredIdentity(db, resolvedDeviceId, publicKey);\n\t})();\n\tif (keyStoreMode() === \"keychain\") {\n\t\tconst privateKey = existsSync(privatePath) ? readFileSync(privatePath) : null;\n\t\tif (privateKey) {\n\t\t\tstorePrivateKeyKeychain(privateKey, resolvedDeviceId);\n\t\t}\n\t}\n\treturn [resolvedDeviceId, fingerprint];\n}\n\nfunction deviceRowForEnsure(db: Database) {\n\treturn drizzle(db, { schema })\n\t\t.select({\n\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\tpublic_key: schema.syncDevice.public_key,\n\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t})\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, lstatSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport type { Database } from \"./db.js\";\n\nexport interface GitRepositoryIdentity {\n\tidentity: string;\n\troot: string | null;\n\tsource: \"git_remote\" | \"git_common_dir\";\n}\n\nexport const REPOSITORY_IDENTITY_METADATA_KEY = \"codemem_repository_identity\";\n\n/**\n * SQL expression for the recorded repository identity in a metadata JSON\n * column, or NULL. Read queries select this instead of the whole column: few\n * sessions record the key, and the substring check skips JSON parsing for the\n * rest.\n */\nexport function repositoryIdentitySql(column: string): string {\n\tconst path = `'$.${REPOSITORY_IDENTITY_METADATA_KEY}'`;\n\treturn `CASE\n\t\tWHEN instr(${column}, '${REPOSITORY_IDENTITY_METADATA_KEY}') = 0 THEN NULL\n\t\tWHEN json_valid(${column}) THEN\n\t\t\tCASE WHEN json_type(${column}, ${path}) = 'text' THEN json_extract(${column}, ${path}) END\n\tEND`;\n}\n\n/**\n * Recorded repository identities keyed by session id, for the few sessions\n * that recorded one. Lets per-memory queries join by session id instead of\n * evaluating session metadata once per memory row.\n */\nexport function recordedRepositoryIdentitiesBySession(db: Database): Map<number, string> {\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT id, ${repositoryIdentitySql(\"metadata_json\")} AS repository_identity\n\t\t\t FROM sessions\n\t\t\t WHERE instr(metadata_json, '${REPOSITORY_IDENTITY_METADATA_KEY}') > 0`,\n\t\t)\n\t\t.all() as Array<{ id: number; repository_identity: string | null }>;\n\tconst identities = new Map<number, string>();\n\tfor (const row of rows) {\n\t\tconst identity = row.repository_identity?.trim();\n\t\tif (identity) identities.set(row.id, identity);\n\t}\n\treturn identities;\n}\n\nexport function repositoryIdentityFromMetadata(\n\tmetadataJson: string | null | undefined,\n): string | null {\n\tif (!metadataJson) return null;\n\ttry {\n\t\tconst metadata = JSON.parse(metadataJson) as Record<string, unknown>;\n\t\tconst value = metadata[REPOSITORY_IDENTITY_METADATA_KEY];\n\t\treturn typeof value === \"string\" && value.trim() ? value.trim() : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction normalizePathLike(value: string): string {\n\treturn value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\") || value.trim();\n}\n\nfunction normalizeRemoteIdentity(value: string, repositoryRoot: string): string | null {\n\tconst remote = value.trim();\n\tif (!remote) return null;\n\tif (/^[a-z][a-z0-9+.-]*:\\/\\//iu.test(remote)) {\n\t\ttry {\n\t\t\tconst url = new URL(remote);\n\t\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") url.username = \"\";\n\t\t\turl.password = \"\";\n\t\t\turl.search = \"\";\n\t\t\turl.hash = \"\";\n\t\t\treturn normalizePathLike(url.toString());\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (/^[A-Za-z]:[\\\\/]/u.test(remote) || !remote.includes(\":\")) {\n\t\treturn normalizePathLike(resolve(repositoryRoot, remote));\n\t}\n\tconst scpRemote = remote.match(/^((?:[^/@:]+@)?[^/:]+):(.+)$/u);\n\tif (!scpRemote?.[1] || !scpRemote[2]) return null;\n\treturn `${scpRemote[1]}:${normalizePathLike(scpRemote[2])}`;\n}\n\nexport function projectBasename(value: string): string {\n\tlet normalized = value.replaceAll(\"\\\\\", \"/\");\n\twhile (normalized.endsWith(\"/\")) normalized = normalized.slice(0, -1);\n\tif (!normalized) return \"\";\n\tconst parts = normalized.split(\"/\");\n\treturn parts[parts.length - 1] ?? \"\";\n}\n\nfunction escapeSqlLikePattern(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n\nexport function projectColumnClause(\n\tcolumnExpr: string,\n\tproject: string,\n): { clause: string; params: string[] } {\n\tconst trimmed = project.trim();\n\tif (!trimmed) return { clause: \"\", params: [] };\n\tconst value = /[\\\\/]/.test(trimmed) ? projectBasename(trimmed) : trimmed;\n\tif (!value) return { clause: \"\", params: [] };\n\tconst escaped = escapeSqlLikePattern(value);\n\treturn {\n\t\tclause: `(${columnExpr} = ? OR ${columnExpr} LIKE ? ESCAPE '\\\\' OR ${columnExpr} LIKE ? ESCAPE '\\\\')`,\n\t\tparams: [value, `%/${escaped}`, `%\\\\${escaped}`],\n\t};\n}\n\nexport function projectClause(project: string): { clause: string; params: string[] } {\n\treturn projectColumnClause(\"sessions.project\", project);\n}\n\nexport function projectMatchesFilter(\n\tprojectFilter: string | null | undefined,\n\titemProject: string | null | undefined,\n): boolean {\n\tif (!projectFilter) return true;\n\tif (!itemProject) return false;\n\tconst normalizedFilter = projectFilter.trim().replaceAll(\"\\\\\", \"/\");\n\tif (!normalizedFilter) return true;\n\tconst filterValue = normalizedFilter.includes(\"/\")\n\t\t? projectBasename(normalizedFilter)\n\t\t: normalizedFilter;\n\tconst normalizedProject = itemProject.replaceAll(\"\\\\\", \"/\");\n\treturn normalizedProject === filterValue || normalizedProject.endsWith(`/${filterValue}`);\n}\n\nfunction findGitAnchor(startCwd: string): string | null {\n\tlet current = resolve(startCwd);\n\twhile (true) {\n\t\tconst gitPath = resolve(current, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\tconst gitDirectory = gitDirectoryFromMarker(current, gitPath);\n\t\t\tif (!gitDirectory) return current;\n\t\t\tconst layout = gitDirectoryLayout(gitDirectory);\n\t\t\treturn layout.isLinkedWorktree && basename(layout.commonDirectory) === \".git\"\n\t\t\t\t? dirname(layout.commonDirectory)\n\t\t\t\t: current;\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return null;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction gitDirectoryFromMarker(repositoryRoot: string, gitPath: string): string | null {\n\ttry {\n\t\tconst pathInfo = lstatSync(gitPath);\n\t\tif (pathInfo.isDirectory()) return gitPath;\n\t\tif (pathInfo.isSymbolicLink() && statSync(gitPath).isDirectory()) return realpathSync(gitPath);\n\t\tconst text = readFileSync(gitPath, \"utf8\").trim();\n\t\tif (!text.startsWith(\"gitdir:\")) return null;\n\t\treturn resolve(repositoryRoot, text.slice(\"gitdir:\".length).trim());\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction gitDirectoryLayout(gitDirectory: string): {\n\tcommonDirectory: string;\n\tisLinkedWorktree: boolean;\n} {\n\ttry {\n\t\tconst marker = readFileSync(resolve(gitDirectory, \"commondir\"), \"utf8\").trim();\n\t\tif (marker) return { commonDirectory: resolve(gitDirectory, marker), isLinkedWorktree: true };\n\t} catch {\n\t\t// Normal repositories use their own .git directory as the common directory.\n\t}\n\treturn { commonDirectory: gitDirectory, isLinkedWorktree: false };\n}\n\nfunction originRemote(commonDirectory: string, repositoryRoot: string): string | null {\n\ttry {\n\t\tconst value = execFileSync(\n\t\t\t\"git\",\n\t\t\t[\n\t\t\t\t\"config\",\n\t\t\t\t\"--file\",\n\t\t\t\tresolve(commonDirectory, \"config\"),\n\t\t\t\t\"--includes\",\n\t\t\t\t\"--get\",\n\t\t\t\t\"remote.origin.url\",\n\t\t\t],\n\t\t\t{ encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"], timeout: 2_000 },\n\t\t).trim();\n\t\treturn normalizeRemoteIdentity(value, repositoryRoot);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Resolve a location-independent identity for a live Git repository or linked worktree. */\nexport function resolveGitRepositoryIdentity(cwd: string): GitRepositoryIdentity | null {\n\tlet current = resolve(cwd);\n\twhile (true) {\n\t\tconst gitPath = resolve(current, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\tconst gitDirectory = gitDirectoryFromMarker(current, gitPath);\n\t\t\tif (!gitDirectory) return null;\n\t\t\tconst layout = gitDirectoryLayout(gitDirectory);\n\t\t\tconst { commonDirectory } = layout;\n\t\t\tconst normalizedCommonDirectory = normalizePathLike(commonDirectory);\n\t\t\tconst root =\n\t\t\t\tlayout.isLinkedWorktree && basename(normalizedCommonDirectory) === \".git\"\n\t\t\t\t\t? dirname(commonDirectory)\n\t\t\t\t\t: current;\n\t\t\tconst remote = originRemote(commonDirectory, root);\n\t\t\tif (remote) return { identity: remote, root, source: \"git_remote\" };\n\t\t\treturn {\n\t\t\t\tidentity: normalizedCommonDirectory,\n\t\t\t\troot,\n\t\t\t\tsource: \"git_common_dir\",\n\t\t\t};\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return null;\n\t\tcurrent = parent;\n\t}\n}\n\nexport function resolveProject(cwd: string, override?: string | null): string | null {\n\tif (override != null) {\n\t\tconst trimmed = override.trim();\n\t\treturn trimmed || null;\n\t}\n\tconst gitAnchor = findGitAnchor(cwd);\n\tif (gitAnchor) {\n\t\treturn basename(gitAnchor);\n\t}\n\treturn basename(resolve(cwd));\n}\n\n/**\n * Resolve the working-tree root for a directory by walking up to the nearest\n * `.git` marker and returning the directory that contains it. Returns null when\n * no repository is found.\n *\n * Unlike `resolveProject` (which follows a linked worktree's gitdir back to the\n * primary checkout for a stable project name), this returns the *current*\n * worktree root so repo-root files like AGENTS.md are read from the worktree\n * actually being used, not another checkout.\n */\nexport function resolveProjectRoot(cwd: string): string | null {\n\tlet current = resolve(cwd);\n\twhile (true) {\n\t\tif (existsSync(resolve(current, \".git\"))) return current;\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return null;\n\t\tcurrent = parent;\n\t}\n}\n","import type { Database } from \"better-sqlite3\";\nimport { AUTH_BROWSER_TXN_SCHEMA_SQL } from \"./coordinator-auth-browser-transaction-contract.js\";\n\nconst TABLE = \"coordinator_auth_browser_transactions\";\nconst REBUILT_TABLE = \"coordinator_auth_browser_transactions_owner_upgrade\";\nconst [tableSql, remainder = \"\"] = AUTH_BROWSER_TXN_SCHEMA_SQL.split(\n\t\"CREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created\",\n);\nconst indexSql =\n\t`CREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created${remainder}`.split(\n\t\t\"CREATE TABLE IF NOT EXISTS coordinator_auth_signin_purge_floors\",\n\t)[0];\n\n/** Run only in a transaction: preserves every old column and all uniqueness constraints. */\nexport const AUTH_BROWSER_OWNER_PURPOSE_UPGRADE_SQL = `\n${tableSql?.replace(TABLE, REBUILT_TABLE)}\nINSERT INTO ${REBUILT_TABLE} SELECT * FROM ${TABLE};\nDROP TABLE ${TABLE};\nALTER TABLE ${REBUILT_TABLE} RENAME TO ${TABLE};\n${indexSql}\n`;\n\n/** Atomic upgrade preserves same-table indexes/triggers; foreign dependents can abort it. */\nexport function upgradeAuthBrowserOwnerPurposeSchema(db: Database): void {\n\tconst present = db\n\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(TABLE) as { sql: string } | undefined;\n\tif (!present || present.sql.includes(\"'owner_enroll'\")) return;\n\t// Recheck after reserving the write lock in case another connection upgraded first.\n\tdb.transaction(() => {\n\t\tconst table = db\n\t\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t\t.get(TABLE) as { sql: string } | undefined;\n\t\tif (!table || table.sql.includes(\"'owner_enroll'\")) return;\n\t\tconst objects = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT name, sql FROM sqlite_master WHERE tbl_name = ? AND type IN ('index','trigger') AND sql IS NOT NULL\",\n\t\t\t)\n\t\t\t.all(TABLE) as { name: string; sql: string }[];\n\t\tdb.exec(AUTH_BROWSER_OWNER_PURPOSE_UPGRADE_SQL);\n\t\tfor (const object of objects) {\n\t\t\tconst recreated = db.prepare(\"SELECT 1 FROM sqlite_master WHERE name = ?\").get(object.name);\n\t\t\tif (!recreated) db.exec(object.sql);\n\t\t}\n\t}).immediate();\n}\n","/** Inert ledger schema: only future verified, atomic enrollment writes may populate it. */\nexport const COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_ownership_bindings (\n device_id TEXT PRIMARY KEY NOT NULL CHECK(\n typeof(device_id) = 'text' AND length(trim(device_id)) > 0 AND instr(device_id, char(0)) = 0),\n key_id TEXT NOT NULL UNIQUE CHECK(\n typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^a-f0-9]*'\n AND instr(key_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK(\n typeof(identity_id) = 'text' AND length(trim(identity_id)) > 0 AND instr(identity_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK(\n typeof(coordinator_id) = 'text' AND length(trim(coordinator_id)) > 0 AND instr(coordinator_id, char(0)) = 0),\n binding_id TEXT NOT NULL UNIQUE CHECK(\n typeof(binding_id) = 'text' AND length(trim(binding_id)) > 0 AND instr(binding_id, char(0)) = 0),\n provenance TEXT NOT NULL CHECK(\n typeof(provenance) = 'text' AND provenance IN ('owner_enrollment', 'reviewed_legacy_migration')),\n source_ref TEXT NOT NULL CHECK(\n typeof(source_ref) = 'text' AND length(trim(source_ref)) > 0 AND instr(source_ref, char(0)) = 0),\n bound_at TEXT NOT NULL CHECK(\n typeof(bound_at) = 'text' AND length(trim(bound_at)) > 0 AND instr(bound_at, char(0)) = 0)\n);\n\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_insert_collision\nBEFORE INSERT ON coordinator_device_ownership_bindings\nWHEN EXISTS (\n SELECT 1 FROM coordinator_device_ownership_bindings\n WHERE rowid = NEW.rowid OR device_id = NEW.device_id OR key_id = NEW.key_id\n OR binding_id = NEW.binding_id\n)\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_collision');\nEND;\n\n-- An automatic rowid reads as -1 before insert; positive rowids keep that from matching a row.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_rowid\nAFTER INSERT ON coordinator_device_ownership_bindings\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_immutable_update\nBEFORE UPDATE ON coordinator_device_ownership_bindings\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_immutable');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_immutable_delete\nBEFORE DELETE ON coordinator_device_ownership_bindings\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_immutable');\nEND;\n`;\n\n/**\n * Earlier installs have a collision trigger that ignores rowid, so INSERT OR\n * REPLACE with an existing rowid could delete a binding without firing its\n * DELETE trigger. Returns the SQL that replaces it, or null when current.\n */\nexport function upgradeDeviceOwnershipTriggersSql(\n\texistingTriggerSql: string | null,\n): string | null {\n\tif (!existingTriggerSql || existingTriggerSql.includes(\"rowid = NEW.rowid\")) return null;\n\treturn \"DROP TRIGGER IF EXISTS coordinator_device_ownership_insert_collision;\";\n}\n","/**\n * BetterSqliteCoordinatorStore — SQLite-backed state for the coordinator relay server.\n *\n * The coordinator is a cloud relay that manages group membership, device\n * enrollment, presence, invites, and join requests for sync between devices.\n *\n * This store uses its OWN database (separate from the main codemem DB) and\n * owns its own schema — the TS side creates tables directly.\n *\n * Ported from codemem/coordinator_store.py.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Database as DatabaseType } from \"better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\tCONNECTION_SCHEMA_PRESENCE_SQL,\n\ttype ConnectionSchemaState,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { AccountLinkStatusOperations } from \"./coordinator-account-link-status.js\";\nimport { AccountOwnerTargetOperations } from \"./coordinator-account-owner-target.js\";\nimport {\n\tAUTH_ACCOUNT_PROFILE_SCHEMA_SQL,\n\tAuthAccountProfileOperations,\n\ttype CoordinatorAuthAccountProfileInput,\n} from \"./coordinator-auth-account-profile.js\";\nimport { upgradeAuthBrowserOwnerPurposeSchema } from \"./coordinator-auth-browser-schema-upgrade.js\";\nimport {\n\tAUTH_BROWSER_TXN_SCHEMA_SQL,\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\tCoordinatorAuthBrowserTransactions,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n} from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\tAUTH_CONTROLLER_ACTIVE_SQL,\n\tAUTH_CONTROLLER_CONFLICT_SQL,\n\tAUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_INSERT_SQL,\n\tAUTH_CONTROLLER_RETRY_ACTIVE_SQL,\n\tAUTH_CONTROLLER_RETRY_ELIGIBLE_SQL,\n\tAUTH_CONTROLLER_REVOKE_SQL,\n\tAUTH_CONTROLLER_SCHEMA_SQL,\n\tauthControllerAuthorityValues,\n\tauthControllerConflictValues,\n\tauthControllerInsertValues,\n\tauthControllerRetryActiveValues,\n\tauthControllerRetryEligibleValues,\n\tauthControllerRetryResult,\n\tauthControllerReviewSql,\n\tauthControllerSubjectOwnerConflictValues,\n\tauthControllerUnavailableResult,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerCreateResult,\n\ttype CoordinatorAuthControllerReviewInput,\n\ttype CoordinatorAuthControllerSubjectOwnerInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n\tisAuthControllerUniqueError,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistoryInput,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport { AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL } from \"./coordinator-auth-controller-owner.js\";\nimport { COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL } from \"./coordinator-auth-device-claim-schema.js\";\nimport {\n\ttype AuthLinkBackend,\n\tAuthLinkOperations,\n\ttype AuthLinkStatement,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_BROWSER_START_COLUMN_SQL,\n\tAUTH_LINK_SCHEMA_SQL,\n\ttype CoordinatorAuthLinkClaimInput,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkConfirmInput,\n\ttype CoordinatorAuthLinkCreateInput,\n\ttype CoordinatorAuthLinkFailInput,\n\ttype CoordinatorAuthLinkFinalizeInput,\n\ttype CoordinatorAuthLinkMaintenanceOptions,\n\ttype CoordinatorAuthLinkOidcInput,\n\ttype CoordinatorAuthLinkOptions,\n\ttype CoordinatorAuthLinkRequester,\n} from \"./coordinator-auth-link-contract.js\";\nimport { AUTH_LINK_PROFILE_SCHEMA_SQL } from \"./coordinator-auth-link-profile.js\";\nimport {\n\tAUTH_SCHEMA_READINESS_SQL,\n\tAUTH_SCHEMA_READY_COUNT,\n\tassertCoordinatorAuthSchema,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\twithCoordinatorAuthSchema,\n} from \"./coordinator-auth-schema.js\";\nimport { AuthSessionOperations } from \"./coordinator-auth-session.js\";\nimport {\n\tAUTH_SESSION_RETENTION_COLUMN_SQL,\n\tAUTH_SESSION_SCHEMA_SQL,\n\ttype CoordinatorAuthAccountSignInInput,\n\ttype CoordinatorAuthBoundLinkSessionRedeemInput,\n\ttype CoordinatorAuthLinkSessionRedeemInput,\n\ttype CoordinatorAuthSessionPurgeOptions,\n\ttype CoordinatorAuthSessionScope,\n} from \"./coordinator-auth-session-contract.js\";\nimport {\n\tBOOTSTRAP_AUTHORIZATION_SOURCE_SQL,\n\ttype BootstrapAuthorizationRow,\n\tbootstrapAuthorizationDecision,\n\tbootstrapAuthorizationResult,\n\tbootstrapAuthorizationSourceError,\n\tcaptureBootstrapAuthorizationInput,\n\trejectBootstrapAuthorization,\n} from \"./coordinator-bootstrap-grant-authorization.js\";\nimport {\n\tBOOTSTRAP_PARTICIPANT_SOURCE_SQL,\n\tBOOTSTRAP_PARTICIPANTS_REVOKED_SQL,\n\tBOOTSTRAP_RAW_INSERT_SQL,\n\ttype BootstrapParticipantSource,\n\tbootstrapRawInsertValues,\n\tcaptureBootstrapParticipantSource,\n} from \"./coordinator-bootstrap-grant-issuance.js\";\nimport {\n\tCOORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL,\n\tupgradeDeviceOwnershipTriggersSql,\n} from \"./coordinator-device-ownership-schema.js\";\nimport {\n\tCOORDINATOR_DEVICE_REBIND_SCHEMA_SQL,\n\treadDeviceRebindBackend,\n\trebindAttemptsNeedSelfBindRebuild,\n\trebuildRebindAttemptsForSelfBindSql,\n\tupgradePreReleaseRebindAttemptsSql,\n} from \"./coordinator-device-rebind-schema.js\";\nimport {\n\ttype CoordinatorCreateDeviceRevocationInput,\n\ttype CoordinatorListDeviceRevocationsInput,\n\ttype CoordinatorRecordAuthorizedNonceInput,\n\tDEVICE_REVOCATION_SCHEMA_SQL,\n\tDEVICE_REVOCATION_SUBJECT_EXISTS_SQL,\n\tDeviceRevocationOperations,\n} from \"./coordinator-device-revocation.js\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_OWNERSHIP_COLUMNS,\n\twithEnrollmentOwnership,\n} from \"./coordinator-enrollment-ownership.js\";\nimport {\n\ttype CoordinatorIdentityGroupGrant,\n\ttype CoordinatorIdentityGroupGrantIssueInput,\n\ttype CoordinatorIdentityGroupGrantIssueResult,\n\ttype CoordinatorIdentityGroupGrantRevokeInput,\n\ttype CoordinatorIdentityGroupGrantScope,\n\tcaptureIdentityGroupGrantInput,\n\tIDENTITY_GROUP_GRANT_INSERT_SQL,\n\tIDENTITY_GROUP_GRANT_LIST_SQL,\n\tIDENTITY_GROUP_GRANT_RETRY_SQL,\n\tIDENTITY_GROUP_GRANT_REVOKE_SQL,\n\tIDENTITY_GROUP_GRANT_SCHEMA_SQL,\n\tIDENTITY_GROUP_GRANT_SOURCE_SQL,\n} from \"./coordinator-identity-group-grant.js\";\nimport { joinReviewGuardEvidence } from \"./coordinator-join-review-guards.js\";\nimport {\n\tcaptureLegacyCompletionOwnerProof,\n\tlegacyCompletionOwnerProofSql,\n} from \"./coordinator-legacy-completion-owner-proof.js\";\nimport {\n\tassertLegacyDeviceScope,\n\tcaptureLegacyEnrollment,\n\tcaptureLegacyEnrollmentPublicKey,\n\tcaptureLegacyProjectInviteInput,\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_DEVICE_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_WRITE_SQL,\n\tlegacyDeviceAuthorizationFailure,\n\tlegacyDeviceDenial,\n\tlegacyDeviceWriteChanges,\n\tlegacyProjectInviteOwnershipEvidence,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport {\n\tLEGACY_OWNER_INPUT_SQL,\n\tLEGACY_OWNER_KEYS_SQL,\n\tLEGACY_OWNER_SOURCE_CURRENT_SQL,\n\tlegacyCompletionWriteResult,\n\tlegacyOwnerKeyMetadata,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionScopeBinding,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionScopeBindings,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\nimport {\n\ttype NegativeOwnerConsistency,\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerConsistency,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport { OwnerResolutionReviewOperations } from \"./coordinator-owner-resolution-review.js\";\nimport {\n\tCAPTURE_PEER_ENROLLMENTS_SQL,\n\ttype CapturedPeerEnrollment,\n\tcapturePeerEnrollments,\n\tREAD_CURRENT_PEERS_SQL,\n\trequirePeerDiscoveryRows,\n} from \"./coordinator-peer-discovery.js\";\nimport { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport {\n\tprepareRecipientOwnerConsistency,\n\trecipientOwnerWriteSql,\n\tvalidateRecipientOwnerInput,\n} from \"./coordinator-recipient-owner-consistency.js\";\nimport { ResolvedAccountOwnerStatusOperations } from \"./coordinator-resolved-account-owner-status.js\";\nimport {\n\ttype CapturedScopeMember,\n\tcaptureScopeAuthorizationInput,\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\tparseScopeAuthorizationMembers,\n\tREAD_SCOPE_AUTHORIZATION_SQL,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeAuthorizationInput,\n\tCoordinatorScopeAuthorizationResult,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tclean,\n\tinspectCoordinatorRecipientInvite as inspectInvite,\n\tmergeCoordinatorAddresses,\n\tnormalizeCoordinatorAuditLimit,\n\tnormalizeCoordinatorBootstrapGrantInput,\n\tnormalizeCoordinatorBootstrapGrantRequest,\n\tnormalizeCoordinatorCreateScopeInput,\n\tnormalizeCoordinatorGrantScopeMembershipInput,\n\tnormalizeCoordinatorInviteMetadata,\n\tnormalizeCoordinatorUpdateScopeInput,\n\tnormalizeEpoch,\n} from \"./coordinator-store-input-rules.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport const DEFAULT_COORDINATOR_DB_PATH = join(homedir(), \".codemem\", \"coordinator.sqlite\");\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\treturn randomBytes(bytes).toString(\"base64url\").replace(/=+$/, \"\");\n}\n\nfunction tokenDigest(token: string): string {\n\treturn createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction insertMembershipAuditSync(\n\tdb: DatabaseType,\n\tinput: {\n\t\teffectId: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tcurrent: CoordinatorScopeMembership;\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): void {\n\tdb.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n\t\tinput.effectId,\n\t\tinput.action,\n\t\tinput.current.scope_id,\n\t\tinput.current.device_id,\n\t\tinput.current.role,\n\t\tinput.current.status,\n\t\tinput.current.membership_epoch,\n\t\tinput.previous?.role ?? null,\n\t\tinput.previous?.status ?? null,\n\t\tinput.previous?.membership_epoch ?? null,\n\t\tinput.current.coordinator_id,\n\t\tinput.current.group_id,\n\t\tinput.actorType,\n\t\tinput.actorId,\n\t\tinput.current.manifest_hash,\n\t\tinput.createdAt,\n\t);\n}\n\nfunction getMembershipEffectReceiptSync(\n\tdb: DatabaseType,\n\teffectId: string,\n): CoordinatorMembershipEffectReceipt | null {\n\tconst row = db\n\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t.get(effectId);\n\treturn row ? rowToRecord<CoordinatorMembershipEffectReceipt>(row) : null;\n}\n\nfunction insertMembershipEffectReceiptSync(\n\tdb: DatabaseType,\n\tinput: {\n\t\teffectId: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\trequestJson: string;\n\t\tapplied: boolean;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tmembership: CoordinatorScopeMembership | null;\n\t\tcreatedAt: string;\n\t},\n): void {\n\tdb.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n\t\tinput.effectId,\n\t\tinput.action,\n\t\tinput.requestJson,\n\t\tinput.applied ? 1 : 0,\n\t\tinput.scopeId,\n\t\tinput.deviceId,\n\t\tinput.membership?.role ?? null,\n\t\tinput.membership?.status ?? null,\n\t\tinput.membership?.membership_epoch ?? null,\n\t\tinput.membership?.coordinator_id ?? null,\n\t\tinput.membership?.group_id ?? null,\n\t\tinput.membership?.manifest_issuer_device_id ?? null,\n\t\tinput.membership?.manifest_hash ?? null,\n\t\tinput.membership?.signed_manifest_json ?? null,\n\t\tinput.membership?.updated_at ?? null,\n\t\tinput.createdAt,\n\t);\n}\n\nfunction assertScopeMembershipDeviceEnrolled(\n\tdb: DatabaseType,\n\tgroupId: string | null,\n\tdeviceId: string,\n): void {\n\tif (!groupId) return;\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1\")\n\t\t.get(groupId, deviceId);\n\tif (!row) {\n\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t}\n}\n\nfunction insertBootstrapGrantSync(\n\tdb: DatabaseType,\n\topts: CoordinatorCreateBootstrapGrantInput,\n\trequestedGrantId?: string,\n\trequestedCreatedAt?: string,\n\tauthorization?: { sql: string; values: (string | null)[]; assertAuthorized: () => void },\n): CoordinatorBootstrapGrant {\n\tconst normalized = normalizeCoordinatorBootstrapGrantInput(opts);\n\tconst grantId = requestedGrantId ?? tokenUrlSafe(12);\n\tconst createdAt = requestedCreatedAt ?? nowISO();\n\tconst result = db\n\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t) SELECT ?, ?, ?, ?, ?, ?, ?, NULL WHERE ${authorization?.sql ?? \"1\"}`)\n\t\t.run(\n\t\t\tgrantId,\n\t\t\tnormalized.groupId,\n\t\t\tnormalized.seedDeviceId,\n\t\t\tnormalized.workerDeviceId,\n\t\t\tnormalized.expiresAt,\n\t\t\tcreatedAt,\n\t\t\tnormalized.createdBy,\n\t\t\t...(authorization?.values ?? []),\n\t\t);\n\tif (authorization && result.changes === 0) {\n\t\tauthorization.assertAuthorized();\n\t\tthrow new Error(\"invite_acceptance_incomplete\");\n\t}\n\tconst row = db\n\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t.get(grantId);\n\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n}\n\nfunction upgradeAuthSessionRetentionSchema(db: DatabaseType): void {\n\tconst present = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_session_receipts') WHERE name = 'purge_eligible'\",\n\t\t)\n\t\t.get();\n\tif (present) return;\n\tdb.transaction(() => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_auth_session_receipts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\tif (columns.length === 0 || columns.some((column) => column.name === \"purge_eligible\")) return;\n\t\tdb.exec(\n\t\t\t`ALTER TABLE coordinator_auth_session_receipts ADD COLUMN ${AUTH_SESSION_RETENTION_COLUMN_SQL}`,\n\t\t);\n\t}).immediate();\n}\n\nfunction upgradeAuthLinkBrowserStartSchema(db: DatabaseType): void {\n\tconst present = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_link_attempts') WHERE name = 'browser_start_hash'\",\n\t\t)\n\t\t.get();\n\tif (present) return;\n\tdb.transaction(() => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_auth_link_attempts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\tif (columns.length === 0 || columns.some((column) => column.name === \"browser_start_hash\"))\n\t\t\treturn;\n\t\tdb.exec(\n\t\t\t`ALTER TABLE coordinator_auth_link_attempts ADD COLUMN ${AUTH_LINK_BROWSER_START_COLUMN_SQL}`,\n\t\t);\n\t}).immediate();\n}\n\nfunction initializeDeviceLedgerSchemas(db: DatabaseType): void {\n\tupgradeDeviceOwnershipTriggers(db);\n\tdb.exec(COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL);\n\tdb.exec(DEVICE_REVOCATION_SCHEMA_SQL);\n\t// Optional owner storage never forces an upgrade of a legacy/direct coordinator.\n\t// Do not install new-column triggers on an existing pre-0034 table either.\n\tconst ownerTable = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_owner_enrollment_attempts'\",\n\t\t)\n\t\t.get();\n\tif (!ownerTable) db.exec(COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL);\n\t// Additive rebind storage (ADR 0005 Section 8). Only an empty pre-release\n\t// attempts table is recreated; see upgradePreReleaseRebindAttemptsSql.\n\tupgradePreReleaseRebindAttempts(db);\n\tupgradeRebindAttemptsForSelfBind(db);\n\tdb.exec(COORDINATOR_DEVICE_REBIND_SCHEMA_SQL);\n}\n\nconst REBIND_ATTEMPTS_SQL =\n\t\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_device_rebind_attempts'\";\n\nconst OWNERSHIP_COLLISION_TRIGGER_SQL =\n\t\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'coordinator_device_ownership_insert_collision'\";\n\n/** Reads first; replaces an outdated trigger and recreates it in one transaction. */\nfunction upgradeDeviceOwnershipTriggers(db: DatabaseType): void {\n\tconst plan = () =>\n\t\tupgradeDeviceOwnershipTriggersSql(\n\t\t\t(db.prepare(OWNERSHIP_COLLISION_TRIGGER_SQL).pluck().get() as string | undefined) ?? null,\n\t\t);\n\tif (!plan()) return;\n\tdb.transaction(() => {\n\t\tconst upgrade = plan();\n\t\tif (!upgrade) return;\n\t\tdb.exec(upgrade);\n\t\tdb.exec(COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL);\n\t}).immediate();\n}\n\n/** Reads first; rebuilds an attempts table that forbids self-binds, keeping its rows. */\nfunction upgradeRebindAttemptsForSelfBind(db: DatabaseType): void {\n\tconst needed = () =>\n\t\trebindAttemptsNeedSelfBindRebuild(\n\t\t\t(db.prepare(REBIND_ATTEMPTS_SQL).pluck().get() as string | undefined) ?? null,\n\t\t);\n\tif (!needed()) return;\n\tdb.transaction(() => {\n\t\tif (needed()) db.exec(rebuildRebindAttemptsForSelfBindSql());\n\t}).immediate();\n}\n\n/** Reads first, so opening an up-to-date database takes no write lock. */\nfunction upgradePreReleaseRebindAttempts(db: DatabaseType): void {\n\tconst plan = () => {\n\t\tconst existing = db.prepare(REBIND_ATTEMPTS_SQL).pluck().get() as string | undefined;\n\t\tif (!existing) return null;\n\t\tconst rows = db\n\t\t\t.prepare(\"SELECT count(*) FROM coordinator_device_rebind_attempts\")\n\t\t\t.pluck()\n\t\t\t.get() as number;\n\t\treturn upgradePreReleaseRebindAttemptsSql(existing, rows);\n\t};\n\tif (!plan()) return;\n\tdb.transaction(() => {\n\t\tconst upgrade = plan();\n\t\tif (upgrade) db.exec(upgrade);\n\t}).immediate();\n}\n\nfunction initializeAuthBrowserSchema(db: DatabaseType): void {\n\tupgradeAuthBrowserOwnerPurposeSchema(db);\n\tdb.exec(AUTH_BROWSER_TXN_SCHEMA_SQL);\n}\n\nfunction initializeAuthLinkSchema(db: DatabaseType): void {\n\tconst ready = db.prepare(AUTH_SCHEMA_READINESS_SQL).get() as { ready: number };\n\tif (ready.ready === AUTH_SCHEMA_READY_COUNT) return;\n\tconst existing = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type='table' AND name='coordinator_auth_link_attempts'\",\n\t\t)\n\t\t.get() as { sql: string } | undefined;\n\tif (existing && !existing.sql.includes(\"authority_kind\")) {\n\t\tupgradeAuthLinkBrowserStartSchema(db);\n\t\tdb.exec(AUTH_LINK_SCHEMA_SQL);\n\t\treturn;\n\t}\n\tdb.transaction(() => {\n\t\tupgradeAuthLinkBrowserStartSchema(db);\n\t\tdb.exec(AUTH_LINK_SCHEMA_SQL);\n\t\tconst explicit = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_link_attempts') WHERE name = 'authority_kind'\",\n\t\t\t)\n\t\t\t.get();\n\t\tif (explicit) db.exec(COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL);\n\t}).immediate();\n}\n\nfunction initializeOptionalAuthSchema(db: DatabaseType): void {\n\tif ((db.prepare(CONNECTION_SCHEMA_PRESENCE_SQL).get() as { present: number }).present) return;\n\tdb.exec(AUTH_CONTROLLER_SCHEMA_SQL);\n\tinitializeAuthLinkSchema(db);\n\tupgradeAuthSessionRetentionSchema(db);\n\tdb.exec(AUTH_SESSION_SCHEMA_SQL);\n\tdb.exec(AUTH_ACCOUNT_PROFILE_SCHEMA_SQL);\n\tdb.exec(AUTH_LINK_PROFILE_SCHEMA_SQL);\n\tinitializeAuthBrowserSchema(db);\n}\nfunction initializeSchema(db: DatabaseType): void {\n\tdb.exec(IDENTITY_GROUP_GRANT_SCHEMA_SQL);\n\tinitializeDeviceLedgerSchemas(db);\n\tinitializeOptionalAuthSchema(db);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS groups (\n\t\t\tgroup_id TEXT PRIMARY KEY,\n\t\t\tdisplay_name TEXT,\n\t\t\tarchived_at TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS enrolled_devices (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tpublic_key TEXT NOT NULL,\n\t\t\tfingerprint TEXT NOT NULL,\n\t\t\tidentity_id TEXT,\n\t\t\tdisplay_name TEXT,\n\t\t\tenabled INTEGER NOT NULL DEFAULT 1,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (group_id, device_id)\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS presence_records (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\taddresses_json TEXT NOT NULL,\n\t\t\tlast_seen_at TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcapabilities_json TEXT NOT NULL DEFAULT '{}',\n\t\t\tPRIMARY KEY (group_id, device_id)\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS request_nonces (\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tnonce TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (device_id, nonce)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_request_nonces_created_at\n\t\t\tON request_nonces(created_at);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_invites (\n\t\t\tinvite_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\ttoken TEXT NOT NULL UNIQUE,\n\t\t\tpolicy TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tcreated_by TEXT,\n\t\t\tteam_name_snapshot TEXT,\n\t\t\trevoked_at TEXT,\n\t\t\toperation_id TEXT,\n\t\t\treviewed_project_set_digest TEXT,\n\t\t\ttoken_digest TEXT,\n\t\t\tinviter_actor_id TEXT,\n\t\t\tinviter_display_name TEXT,\n\t\t\tinviter_device_id TEXT,\n\t\t\tpending_person_id TEXT,\n\t\t\tproject_summaries_json TEXT,\n\t\t\tproject_intent_json TEXT,\n\t\t\tconsumed_at TEXT,\n\t\t\tbound_device_id TEXT,\n\t\t\tbound_public_key TEXT,\n\t\t\tbound_fingerprint TEXT,\n\t\t\trecipient_actor_id TEXT,\n\t\t\trecipient_display_name TEXT,\n\t\t\trecipient_device_display_name TEXT,\n\t\t\ttrust_state TEXT,\n\t\t\tbootstrap_grant_id TEXT,\n\t\t\tinvite_kind TEXT,\n\t\t\tpolicy_team_id TEXT,\n\t\t\ttarget_identity_id TEXT,\n\t\t\tassigned_identity_id TEXT,\n\t\t\treviewed_preview_digest TEXT,\n\t\t\treviewed_intent_json TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_join_requests (\n\t\t\trequest_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tpublic_key TEXT NOT NULL,\n\t\t\tfingerprint TEXT NOT NULL,\n\t\t\tdisplay_name TEXT,\n\t\t\ttoken TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\treviewed_at TEXT,\n\t\t\treviewed_by TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_reciprocal_approvals (\n\t\t\trequest_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\trequesting_device_id TEXT NOT NULL,\n\t\t\trequested_device_id TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tresolved_at TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_bootstrap_grants (\n\t\t\tgrant_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tseed_device_id TEXT NOT NULL,\n\t\t\tworker_device_id TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tcreated_by TEXT,\n\t\t\trevoked_at TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scopes (\n\t\t\tscope_id TEXT PRIMARY KEY,\n\t\t\tlabel TEXT NOT NULL,\n\t\t\tkind TEXT NOT NULL DEFAULT 'user',\n\t\t\tauthority_type TEXT NOT NULL DEFAULT 'coordinator',\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\tmanifest_hash TEXT,\n\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scopes_status\n\t\t\tON coordinator_scopes(status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scopes_authority_group\n\t\t\tON coordinator_scopes(coordinator_id, group_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_memberships (\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT NOT NULL DEFAULT 'member',\n\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tsigned_manifest_json TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (scope_id, device_id)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_device_status\n\t\t\tON coordinator_scope_memberships(device_id, status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_scope_status\n\t\t\tON coordinator_scope_memberships(scope_id, status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_authority_group\n\t\t\tON coordinator_scope_memberships(coordinator_id, group_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_membership_audit_log (\n\t\t\tevent_id INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\teffect_id TEXT,\n\t\t\taction TEXT NOT NULL,\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tmembership_epoch INTEGER NOT NULL,\n\t\t\tprevious_role TEXT,\n\t\t\tprevious_status TEXT,\n\t\t\tprevious_membership_epoch INTEGER,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tactor_type TEXT,\n\t\t\tactor_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_scope_created\n\t\t\tON coordinator_scope_membership_audit_log(scope_id, created_at, event_id);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_device_created\n\t\t\tON coordinator_scope_membership_audit_log(device_id, created_at, event_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_membership_effect_receipts (\n\t\t\teffect_id TEXT PRIMARY KEY,\n\t\t\taction TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),\n\t\t\trequest_json TEXT NOT NULL,\n\t\t\toutcome_applied INTEGER NOT NULL CHECK (outcome_applied IN (0, 1)),\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT,\n\t\t\tstatus TEXT,\n\t\t\tmembership_epoch INTEGER,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tsigned_manifest_json TEXT,\n\t\t\tupdated_at TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_legacy_team_completions (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tcandidate_ref TEXT NOT NULL,\n\t\t\tmanifest_version INTEGER NOT NULL CHECK (manifest_version = 1),\n\t\t\tmanifest_json TEXT NOT NULL,\n\t\t\tcompleted_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (group_id, candidate_ref)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_legacy_team_completions_group\n\t\t\tON coordinator_legacy_team_completions(group_id, completed_at, candidate_ref);\n\t`);\n\ttry {\n\t\tdb.prepare(\n\t\t\t\"ALTER TABLE coordinator_scope_membership_audit_log ADD COLUMN effect_id TEXT\",\n\t\t).run();\n\t} catch {\n\t\t// already exists\n\t}\n\tdb.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_effect\n\t\tON coordinator_scope_membership_audit_log(effect_id) WHERE effect_id IS NOT NULL`);\n\ttry {\n\t\tdb.prepare(\"ALTER TABLE groups ADD COLUMN archived_at TEXT\").run();\n\t} catch {\n\t\t// already exists\n\t}\n\ttry {\n\t\tdb.prepare(\"ALTER TABLE enrolled_devices ADD COLUMN identity_id TEXT\").run();\n\t} catch {\n\t\t// already exists\n\t}\n\tfor (const column of [\n\t\t\"operation_id\",\n\t\t\"reviewed_project_set_digest\",\n\t\t\"token_digest\",\n\t\t\"inviter_actor_id\",\n\t\t\"inviter_display_name\",\n\t\t\"inviter_device_id\",\n\t\t\"pending_person_id\",\n\t\t\"project_summaries_json\",\n\t\t\"project_intent_json\",\n\t\t\"consumed_at\",\n\t\t\"bound_device_id\",\n\t\t\"bound_public_key\",\n\t\t\"bound_fingerprint\",\n\t\t\"recipient_actor_id\",\n\t\t\"recipient_display_name\",\n\t\t\"recipient_device_display_name\",\n\t\t\"trust_state\",\n\t\t\"bootstrap_grant_id\",\n\t\t\"invite_kind\",\n\t\t\"policy_team_id\",\n\t\t\"target_identity_id\",\n\t\t\"assigned_identity_id\",\n\t\t\"reviewed_preview_digest\",\n\t\t\"reviewed_intent_json\",\n\t]) {\n\t\ttry {\n\t\t\tdb.prepare(`ALTER TABLE coordinator_invites ADD COLUMN ${column} TEXT`).run();\n\t\t} catch {\n\t\t\t// already exists\n\t\t}\n\t}\n\tdb.exec(\n\t\t`CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_invites_operation_id\n\t\t\tON coordinator_invites(operation_id) WHERE operation_id IS NOT NULL;\n\t\t CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_invites_token_digest\n\t\t\tON coordinator_invites(token_digest) WHERE token_digest IS NOT NULL;\n\t\t CREATE INDEX IF NOT EXISTS idx_coordinator_invites_group_created\n\t\t\tON coordinator_invites(group_id, created_at DESC);\n\t\t UPDATE coordinator_invites\n\t\t\tSET invite_kind = CASE WHEN operation_id IS NOT NULL THEN 'project_share' ELSE 'legacy_enrollment' END\n\t\t\tWHERE invite_kind IS NULL;`,\n\t);\n}\n\nexport function connectCoordinator(\n\tpath?: string,\n\toptions: { existingOnly?: boolean } = {},\n): DatabaseType {\n\tconst dbPath = path ?? DEFAULT_COORDINATOR_DB_PATH;\n\tif (options.existingOnly) {\n\t\tconst db = new Database(dbPath, { fileMustExist: true });\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\treturn db;\n\t}\n\tmkdirSync(dirname(dbPath), { recursive: true });\n\tconst db = new Database(dbPath);\n\tdb.pragma(\"foreign_keys = ON\");\n\tdb.pragma(\"busy_timeout = 5000\");\n\tdb.pragma(\"journal_mode = WAL\");\n\tdb.pragma(\"synchronous = NORMAL\");\n\tinitializeSchema(db);\n\treturn db;\n}\n\nfunction enrollmentRevocationKeyId(publicKey: string): string | null {\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(publicKey);\n\tif (parsed.kind !== \"ed25519\") return null;\n\treturn createHash(\"sha256\").update(parsed.blob).digest(\"hex\");\n}\n\nexport class BetterSqliteCoordinatorStore implements CoordinatorStore {\n\t/** The raw backend, without the auth schema wrapper. */\n\tprivate readonly schemaBackend: AuthLinkBackend;\n\tprivate readonly accountChangeBackend: AuthLinkBackend;\n\tprivate readonly accountChangesCapability: AccountChangeOperations;\n\treadonly path: string;\n\treadonly db: DatabaseType;\n\tprivate readonly authLinks: AuthLinkOperations;\n\treadonly assertAuthSchemaReady: () => Promise<void>;\n\tprivate readonly accountLinkStatus: AccountLinkStatusOperations;\n\tprivate readonly accountOwnerTarget: AccountOwnerTargetOperations;\n\tprivate readonly deviceRevocations: DeviceRevocationOperations;\n\tprivate readonly authSessions: AuthSessionOperations;\n\tprivate readonly authAccountProfiles: AuthAccountProfileOperations;\n\tprivate readonly authBrowserTransactions: CoordinatorAuthBrowserTransactions;\n\n\tconstructor(\n\t\tpath?: string,\n\t\toptions: CoordinatorAuthLinkOptions & { existingOnly?: boolean } = {},\n\t) {\n\t\tthis.path = path ?? DEFAULT_COORDINATOR_DB_PATH;\n\t\tthis.db = connectCoordinator(this.path, options);\n\t\tthis.deviceRevocations = new DeviceRevocationOperations(\n\t\t\t{\n\t\t\t\tall: async (statement) => ({\n\t\t\t\t\tresults: this.db.prepare(statement.sql).all(...statement.values),\n\t\t\t\t}),\n\t\t\t\tbatch: async (statements) =>\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\t\tstatements.map((statement) => {\n\t\t\t\t\t\t\t\tconst prepared = this.db.prepare(statement.sql);\n\t\t\t\t\t\t\t\tif (statement.read) return { results: prepared.all(...statement.values) };\n\t\t\t\t\t\t\t\treturn { meta: { changes: prepared.run(...statement.values).changes } };\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.immediate(),\n\t\t\t},\n\t\t\toptions.authClock,\n\t\t);\n\t\tconst rawAuthBackend: AuthLinkBackend = {\n\t\t\tall: async <T>(statement: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(statement.sql).all(...statement.values) as T[],\n\t\t\tfirst: async <T>(statement: AuthLinkStatement) =>\n\t\t\t\t(this.db.prepare(statement.sql).get(...statement.values) as T | undefined) ?? null,\n\t\t\trun: async (statement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.transaction(() => this.db.prepare(statement.sql).run(...statement.values).changes)\n\t\t\t\t\t.immediate(),\n\t\t\tbatch: async (statements) => {\n\t\t\t\treturn this.db\n\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\tstatements.map(\n\t\t\t\t\t\t\t(statement) => this.db.prepare(statement.sql).run(...statement.values).changes,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.immediate();\n\t\t\t},\n\t\t};\n\t\tthis.assertAuthSchemaReady = () => assertCoordinatorAuthSchema(rawAuthBackend);\n\t\tthis.schemaBackend = rawAuthBackend;\n\t\tconst authBackend = withCoordinatorAuthSchema(rawAuthBackend);\n\t\tthis.accountChangeBackend = withCoordinatorAuthSchema(rawAuthBackend, { connections: true });\n\t\tthis.accountChangesCapability = new AccountChangeOperations(\n\t\t\tthis.accountChangeBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t\tthis.authLinks = new AuthLinkOperations(authBackend, options.authClock);\n\t\tthis.accountLinkStatus = new AccountLinkStatusOperations(authBackend, options.authClock);\n\t\tthis.accountOwnerTarget = new AccountOwnerTargetOperations(authBackend, this);\n\t\tthis.authSessions = new AuthSessionOperations(authBackend, options.authClock);\n\t\tthis.authAccountProfiles = new AuthAccountProfileOperations(authBackend, options.authClock);\n\t\tthis.authBrowserTransactions = new CoordinatorAuthBrowserTransactions(\n\t\t\tauthBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t}\n\t/** ADR 0005 Section 8 rebind storage; null before its tables exist. */\n\treadDeviceRebindBackend(): Promise<AuthLinkBackend | null> {\n\t\treturn readDeviceRebindBackend(this.schemaBackend);\n\t}\n\t/** Explicit capability: legacy V2 remains usable without enabling management. */\n\tasync getAccountChanges(): Promise<AccountChangeOperations> {\n\t\tawait this.accountChangeBackend.first({ sql: \"SELECT 1\", values: [] });\n\t\treturn this.accountChangesCapability;\n\t}\n\treadAccountConnectionSchemaState(): Promise<ConnectionSchemaState> {\n\t\treturn readConnectionSchemaState(this.schemaBackend);\n\t}\n\t/** One fresh startup lookup; returned operations still check every SQL entry. */\n\tasync readAccountChangeCapability(): Promise<AccountChangeOperations | null> {\n\t\tconst state = await this.readAccountConnectionSchemaState();\n\t\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\t\treturn state === \"ready\" ? this.accountChangesCapability : null;\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionPurpose(input, config);\n\t}\n\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionActivity(input, config);\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.startAuthBrowserTransaction(input, config);\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.consumeAuthBrowserTransaction(input, config);\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.resolveAuthLinkBrowserTransaction(input, config);\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t) {\n\t\treturn this.authBrowserTransactions.cancelAuthSigninBrowserTransaction(input, scope);\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.retireAuthBrowserTransactions(config, options);\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.purgeAuthSigninBrowserTransactions(scope, options);\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.maintainAuthBrowserTransactions(scope, options);\n\t}\n\n\tasync redeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSession(input, config);\n\t}\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSessionWithBrowserTransaction(input, config);\n\t}\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.preserveAuthLinkSessionCompletion(input, config);\n\t}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninSessions(scope, options);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninReceipts(scope, options);\n\t}\n\tasync signInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.signInWithAuthAccount(input, config);\n\t}\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.signInWithConsumedBrowserTransaction(input, config);\n\t}\n\tasync readAuthSession(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authSessions.readAuthSession(credentialHash, config);\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authAccountProfiles.recordAuthAccountProfile(input, config);\n\t}\n\tasync readAuthSessionAccount(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authAccountProfiles.readAuthSessionAccount(credentialHash, config);\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t) {\n\t\treturn this.authAccountProfiles.clearRevokedAuthAccountProfile(input, scope);\n\t}\n\tasync signOutAuthSession(credentialHash: string, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.signOutAuthSession(credentialHash, scope);\n\t}\n\tasync revokeAuthAccountLink(input: { linkId: string }, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.revokeAuthAccountLink(input, scope);\n\t}\n\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t) {\n\t\treturn this.authLinks.maintainAuthLinkAttempts(config, options);\n\t}\n\treadAccountLinkStatus(...args: Parameters<AccountLinkStatusOperations[\"readAccountLinkStatus\"]>) {\n\t\treturn this.accountLinkStatus.readAccountLinkStatus(...args);\n\t}\n\treadAccountOwnerTarget(\n\t\t...args: Parameters<AccountOwnerTargetOperations[\"readAccountOwnerTarget\"]>\n\t) {\n\t\treturn this.accountOwnerTarget.readAccountOwnerTarget(...args);\n\t}\n\treadResolvedAccountOwnerStatus(\n\t\t...args: Parameters<ResolvedAccountOwnerStatusOperations[\"readResolvedAccountOwnerStatus\"]>\n\t) {\n\t\treturn new ResolvedAccountOwnerStatusOperations({\n\t\t\t...this.accountChangeBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t}).readResolvedAccountOwnerStatus(...args);\n\t}\n\tprivate ownerResolutionReviews(): OwnerResolutionReviewOperations {\n\t\treturn new OwnerResolutionReviewOperations({\n\t\t\t...this.schemaBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\trun: async ({ sql, values }) => this.db.prepare(sql).run(...values).changes,\n\t\t\tbatch: async (statements) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\tstatements.map(({ sql, values }) => {\n\t\t\t\t\t\t\tconst statement = this.db.prepare(sql);\n\t\t\t\t\t\t\tif (statement.reader) {\n\t\t\t\t\t\t\t\tstatement.all(...values);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn statement.run(...values).changes;\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.immediate(),\n\t\t});\n\t}\n\tpreviewOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"previewOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().previewOwnerResolutionReview(...args);\n\t}\n\tconfirmOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"confirmOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().confirmOwnerResolutionReview(...args);\n\t}\n\treadAuthDeviceClaimReadiness(\n\t\t...args: Parameters<AccountLinkStatusOperations[\"readAuthDeviceClaimReadiness\"]>\n\t) {\n\t\treturn this.accountLinkStatus.readAuthDeviceClaimReadiness(...args);\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.createAuthLinkAttempt(input, config);\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.claimAuthLinkAttempt(input, config);\n\t}\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.recordAuthLinkOidcVerified(input, config);\n\t}\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.confirmAuthLinkAttempt(input, config);\n\t}\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readAuthLinkCompletionDestination(input, config);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.finalizeAuthLinkAttempt(input, config);\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.failAuthLinkAttempt(input, config);\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.getAuthLinkAttemptStatus(attemptId, requester, config);\n\t}\n\n\tprivate enrollDeviceSync(groupId: string, opts: CoordinatorEnrollDeviceInput): void {\n\t\tconst { deviceId, publicKey, fingerprint, identityId, displayName } = captureLegacyEnrollment(\n\t\t\tgroupId,\n\t\t\topts,\n\t\t);\n\t\ttry {\n\t\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t.get(groupId, deviceId) ?? null,\n\t\t\t);\n\t\t\tconst keyId = enrollmentRevocationKeyId(publicKey);\n\t\t\tconst currentKeyId =\n\t\t\t\tcurrentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey);\n\t\t\tconst source = [currentPublicKey, groupId, deviceId, groupId, deviceId, currentPublicKey];\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_WRITE_SQL)\n\t\t\t\t.run(\n\t\t\t\t\tgroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tidentityId ?? null,\n\t\t\t\t\tdisplayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\t...source,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\tcurrentPublicKey,\n\t\t\t\t);\n\t\t\tif (legacyDeviceWriteChanges({ meta: result }) === 1) return;\n\t\t\tconst denial = this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_DENIAL_SQL)\n\t\t\t\t.get(deviceId, keyId, deviceId, keyId, deviceId, currentKeyId, ...source);\n\t\t\tthrow new Error(legacyDeviceDenial(denial));\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.db.close();\n\t}\n\n\tasync issueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"attestationId\"]);\n\t\tif (!captured) return { kind: \"rejected\", error: \"invalid_grant_input\" };\n\t\ttry {\n\t\t\treturn this.db\n\t\t\t\t.transaction((): CoordinatorIdentityGroupGrantIssueResult => {\n\t\t\t\t\tconst source = this.db\n\t\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_SOURCE_SQL)\n\t\t\t\t\t\t.get(captured.coordinatorId, captured.attestationId) as\n\t\t\t\t\t\t| CoordinatorEnrollment\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (!source) return { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\t\t\tconst authority = [\n\t\t\t\t\t\tcaptured.coordinatorId,\n\t\t\t\t\t\tcaptured.attestationId,\n\t\t\t\t\t\tsource.group_id,\n\t\t\t\t\t\tsource.device_id,\n\t\t\t\t\t\tsource.public_key,\n\t\t\t\t\t\tsource.fingerprint,\n\t\t\t\t\t\tsource.identity_id,\n\t\t\t\t\t\tsource.device_id,\n\t\t\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t\t\t];\n\t\t\t\t\tconst grant = this.db\n\t\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_INSERT_SQL)\n\t\t\t\t\t\t.get(nowISO(), ...authority) as CoordinatorIdentityGroupGrant | undefined;\n\t\t\t\t\tif (grant) return { kind: \"created\", grant };\n\t\t\t\t\tconst existing = this.db.prepare(IDENTITY_GROUP_GRANT_RETRY_SQL).get(...authority) as\n\t\t\t\t\t\t| CoordinatorIdentityGroupGrant\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (existing) return { kind: \"existing\", grant: existing };\n\t\t\t\t\treturn { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tasync listIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"identityId\"]);\n\t\tif (!captured) throw new Error(\"invalid_grant_input\");\n\t\treturn this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_LIST_SQL)\n\t\t\t.all(captured.coordinatorId, captured.identityId) as CoordinatorIdentityGroupGrant[];\n\t}\n\n\tasync revokeIdentityGroupGrant(\n\t\tinput: CoordinatorIdentityGroupGrantRevokeInput,\n\t): Promise<boolean> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\n\t\t\t\"coordinatorId\",\n\t\t\t\"identityId\",\n\t\t\t\"groupId\",\n\t\t\t\"expectedRevision\",\n\t\t]);\n\t\tif (!captured) return false;\n\t\treturn (\n\t\t\tthis.db\n\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_REVOKE_SQL)\n\t\t\t\t.run(\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tcaptured.coordinatorId,\n\t\t\t\t\tcaptured.identityId,\n\t\t\t\t\tcaptured.groupId,\n\t\t\t\t\tcaptured.expectedRevision,\n\t\t\t\t).changes > 0\n\t\t);\n\t}\n\n\tasync createAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review) return { kind: \"rejected\", error: \"invalid_review_input\" };\n\t\tconst conflict = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_CONFLICT_SQL)\n\t\t\t.get(...authControllerConflictValues(review)) as\n\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t| undefined;\n\t\tconst hasConflict = conflict !== undefined;\n\t\tconst consistency = hasConflict ? null : await this.prepareAuthControllerConsistency(review);\n\t\tif (!hasConflict && !consistency) return authControllerUnavailableResult(review);\n\t\tlet retryAfterPinChange = false;\n\t\tconst result = this.db\n\t\t\t.transaction((): CoordinatorAuthControllerCreateResult => {\n\t\t\t\tconst source = this.db\n\t\t\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\tif (!source) return authControllerUnavailableResult(review);\n\t\t\t\tconst authority = authControllerAuthorityValues(\n\t\t\t\t\tsource,\n\t\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t\t);\n\t\t\t\tif (hasConflict) return this.resolveAuthControllerRetrySync(review, authority);\n\t\t\t\ttry {\n\t\t\t\t\tconst statement = withNegativeOwnerConsistency(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_INSERT_SQL, review),\n\t\t\t\t\t\t\tvalues: authControllerInsertValues(review, nowISO(), authority),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tconsistency ?? { sql: \"SELECT 0 AS matches\", values: [] },\n\t\t\t\t\t);\n\t\t\t\t\tconst inserted = this.db.prepare(statement.sql).run(...statement.values);\n\t\t\t\t\tif (inserted.changes === 0) {\n\t\t\t\t\t\tretryAfterPinChange = true;\n\t\t\t\t\t\treturn authControllerUnavailableResult(review);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!isAuthControllerUniqueError(error)) throw error;\n\t\t\t\t\treturn this.resolveAuthControllerRetrySync(review, authority);\n\t\t\t\t}\n\t\t\t\tconst attestation = this.getActiveAuthControllerAttestationSync(\n\t\t\t\t\treview.coordinatorId,\n\t\t\t\t\treview.attestationId,\n\t\t\t\t\tauthority,\n\t\t\t\t);\n\t\t\t\tif (!attestation) throw new Error(\"auth_controller_persistence_incomplete\");\n\t\t\t\treturn { kind: \"created\", attestation };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (!retryAfterPinChange) return result;\n\t\treturn this.retryAuthControllerAfterPinChange(review);\n\t}\n\n\tprivate async retryAuthControllerAfterPinChange(\n\t\treview: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\t// The winner changes the evidence pin. Recapture without accepting new conflicts.\n\t\tconst retryConsistency = await this.prepareAuthControllerConsistency(review);\n\t\tif (!retryConsistency) return authControllerUnavailableResult(review);\n\t\treturn this.db\n\t\t\t.transaction((): CoordinatorAuthControllerCreateResult => {\n\t\t\t\tconst pin = this.db.prepare(retryConsistency.sql).get(...retryConsistency.values) as\n\t\t\t\t\t| { matches: number }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (pin?.matches !== 1) return authControllerUnavailableResult(review);\n\t\t\t\tconst source = this.db\n\t\t\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\tif (!source) return authControllerUnavailableResult(review);\n\t\t\t\treturn this.resolveAuthControllerRetrySync(\n\t\t\t\t\treview,\n\t\t\t\t\tauthControllerAuthorityValues(source, enrollmentRevocationKeyId(source.public_key)),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate prepareAuthControllerConsistency(review: CoordinatorAuthControllerReviewInput) {\n\t\treturn prepareNegativeOwnerConsistency(\n\t\t\t{\n\t\t\t\tfirst: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t(this.db.prepare(sql).get(...values) as T | undefined) ?? null,\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t},\n\t\t\t{\n\t\t\t\t...review,\n\t\t\t\townerIdentityId: review.identityId,\n\t\t\t\tenrollment: { groupId: review.groupId },\n\t\t\t\tverifiedHistory: review.verifiedSnapshot?.legacyHistory,\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate resolveAuthControllerRetrySync(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t\tauthority: (string | null)[],\n\t): CoordinatorAuthControllerCreateResult {\n\t\tif (\n\t\t\t!this.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL, input))\n\t\t\t\t.get(...authControllerRetryEligibleValues(input, authority))\n\t\t)\n\t\t\treturn {\n\t\t\t\tkind: \"rejected\",\n\t\t\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t\t\t};\n\t\tconst row = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_CONFLICT_SQL)\n\t\t\t.get(...authControllerConflictValues(input)) as\n\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t| undefined;\n\t\tconst result = authControllerRetryResult(input, row ?? null);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tconst active = this.getActiveAuthControllerAttestationSync(\n\t\t\tinput.coordinatorId,\n\t\t\tinput.attestationId,\n\t\t\tauthority,\n\t\t);\n\t\tif (!active) return { kind: \"rejected\", error: \"enrollment_mismatch\" };\n\t\treturn { kind: \"existing\", attestation: active };\n\t}\n\n\tprivate getActiveAuthControllerAttestationSync(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t\tauthority?: (string | null)[],\n\t): CoordinatorAuthControllerAttestation | null {\n\t\tif (!authority) {\n\t\t\tconst source = this.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL)\n\t\t\t\t.get(coordinatorId, attestationId) as CoordinatorEnrollment | undefined;\n\t\t\tif (!source) return null;\n\t\t\tauthority = authControllerAuthorityValues(\n\t\t\t\tsource,\n\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\t(this.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_ACTIVE_SQL)\n\t\t\t\t.get(coordinatorId, attestationId, ...authority) as\n\t\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t\t| undefined) ?? null\n\t\t);\n\t}\n\n\tasync getActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return null;\n\t\treturn this.getActiveAuthControllerAttestationSync(coordinatorId, attestationId);\n\t}\n\n\tasync readAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review?.verifiedSnapshot?.accountOwnerTarget) return null;\n\t\tconst source = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t);\n\t\treturn (\n\t\t\t(this.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, review))\n\t\t\t\t.get(...authControllerRetryActiveValues(review, authority)) as\n\t\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t\t| undefined) ?? null\n\t\t);\n\t}\n\n\tasync hasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean> {\n\t\treturn !!this.db\n\t\t\t.prepare(AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL)\n\t\t\t.get(...authControllerSubjectOwnerConflictValues(input));\n\t}\n\n\tasync revokeAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<boolean> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return false;\n\t\treturn (\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_REVOKE_SQL).run(nowISO(), coordinatorId, attestationId)\n\t\t\t\t.changes > 0\n\t\t);\n\t}\n\n\tasync createGroup(groupId: string, displayName?: string | null): Promise<void> {\n\t\tthis.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.run(groupId, displayName ?? null, nowISO());\n\t}\n\n\tasync getGroup(groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t)\n\t\t\t.get(groupId);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t)\n\t\t\t.all()\n\t\t\t.map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(groupId: string, displayName: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t.run(displayName, groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync archiveGroup(groupId: string, archivedAt = nowISO()): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t.run(archivedAt, groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync unarchiveGroup(groupId: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\n\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t)\n\t\t\t.run(groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync enrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst input = captureLegacyEnrollment(groupId, opts);\n\t\ttry {\n\t\t\tthis.db.transaction(() => this.enrollDeviceSync(groupId, input)).immediate();\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync listEnrolledDevices(\n\t\tgroupId: string,\n\t\tincludeDisabled = false,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\treturn withEnrollmentOwnership(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}, ${ENROLLMENT_OWNERSHIP_COLUMNS}\n\t\t\t\t FROM enrolled_devices\n\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t.all(groupId)\n\t\t\t\t.map(rowToEnrollmentWithPresence),\n\t\t);\n\t}\n\n\tasync getEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t FROM enrolled_devices\n\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t.get(groupId, deviceId);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t.run(displayName, groupId, deviceId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync setDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean> {\n\t\tassertLegacyDeviceScope(groupId, deviceId);\n\t\tif (typeof enabled !== \"boolean\") throw new Error(\"invalid_input\");\n\t\tif (enabled) {\n\t\t\ttry {\n\t\t\t\treturn this.db\n\t\t\t\t\t.transaction(() => {\n\t\t\t\t\t\tconst enrollment = this.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.get(groupId, deviceId) as { public_key: string } | undefined;\n\t\t\t\t\t\tif (!enrollment) return false;\n\t\t\t\t\t\tconst publicKey = enrollment.public_key;\n\t\t\t\t\t\tif (typeof publicKey !== \"string\")\n\t\t\t\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\t\t\tconst keyId = enrollmentRevocationKeyId(publicKey);\n\t\t\t\t\t\tconst result = this.db\n\t\t\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = 1\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ?\n\t\t\t\t\t\tAND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\t\t\tAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`)\n\t\t\t\t\t\t\t.run(groupId, deviceId, publicKey, deviceId, keyId, deviceId, keyId);\n\t\t\t\t\t\tif (legacyDeviceWriteChanges({ meta: result }) === 1) return true;\n\t\t\t\t\t\tconst denial = legacyDeviceDenial(\n\t\t\t\t\t\t\tthis.db.prepare(LEGACY_DEVICE_DENIAL_SQL).get(deviceId, keyId, deviceId, keyId),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (denial === \"device_ownership_requires_verified_identity\") throw new Error(denial);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t})\n\t\t\t\t\t.immediate();\n\t\t\t} catch (error) {\n\t\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t\t}\n\t\t}\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t.run(enabled ? 1 : 0, groupId, deviceId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync removeDevice(groupId: string, deviceId: string): Promise<boolean> {\n\t\t// Atomic: a partial failure must not leave presence/approval rows\n\t\t// orphaned against a still-enrolled device (or vice versa).\n\t\tconst removeAll = this.db.transaction(() => {\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.run(groupId, deviceId);\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.run(groupId, deviceId, deviceId);\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.run(groupId, deviceId);\n\t\t\treturn result.changes > 0;\n\t\t});\n\t\treturn removeAll();\n\t}\n\n\tasync recordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean> {\n\t\ttry {\n\t\t\tthis.db\n\t\t\t\t.prepare(\"INSERT INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\")\n\t\t\t\t.run(deviceId, nonce, createdAt);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync createDeviceRevocation(input: CoordinatorCreateDeviceRevocationInput) {\n\t\treturn this.deviceRevocations.createDeviceRevocation(input);\n\t}\n\n\tasync listDeviceRevocations(input: CoordinatorListDeviceRevocationsInput) {\n\t\treturn this.deviceRevocations.listDeviceRevocations(input);\n\t}\n\n\tasync recordAuthorizedNonce(input: CoordinatorRecordAuthorizedNonceInput) {\n\t\treturn this.deviceRevocations.recordAuthorizedNonce(input);\n\t}\n\n\tasync cleanupNonces(cutoff: string): Promise<void> {\n\t\tthis.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").run(cutoff);\n\t}\n\n\tasync createInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\t// Normalize to canonical UTC ISO so the lexicographic `expires_at > ?`\n\t\t// comparison in getInviteByToken is sound.\n\t\tconst expiresAt = normalizeInviteExpiresAt(opts.expiresAt);\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = tokenDigest(token);\n\t\tconst group = await this.getGroup(opts.groupId);\n\t\tconst operationId = clean(opts.operationId);\n\t\tconst reviewedProjectSetDigest = clean(opts.reviewedProjectSetDigest);\n\t\tconst metadata = await normalizeCoordinatorInviteMetadata(opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = (): CoordinatorInvite | null => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = this.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t.get(operationId) as CoordinatorInvite | undefined;\n\t\t\tif (!existing) return null;\n\t\t\t// Project bearer tokens remain retrievable only until first consume so an\n\t\t\t// interrupted create can return the same invite. Consume replaces the\n\t\t\t// plaintext with a non-secret marker; later create retries must not emit it.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== opts.groupId ||\n\t\t\t\texisting.policy !== opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== clean(opts.inviterActorId) ||\n\t\t\t\texisting.inviter_display_name !== clean(opts.inviterDisplayName) ||\n\t\t\t\texisting.inviter_device_id !== clean(opts.inviterDeviceId) ||\n\t\t\t\texisting.pending_person_id !== clean(opts.pendingPersonId) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(opts.projectSummaries ? JSON.stringify(opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(opts.projectIntent ? JSON.stringify(opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn existing;\n\t\t};\n\t\tconst renewOperationInvite = (existing: CoordinatorInvite): CoordinatorInvite => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t.run(\n\t\t\t\t\ttoken,\n\t\t\t\t\tdigest,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\topts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\texisting.token,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\tconst renewed = readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = readOperationInvite();\n\t\t\tif (existing) return renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.run(\n\t\t\t\t\tinviteId,\n\t\t\t\t\topts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\topts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\topts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tclean(opts.inviterActorId),\n\t\t\t\t\tclean(opts.inviterDisplayName),\n\t\t\t\t\tclean(opts.inviterDeviceId),\n\t\t\t\t\tclean(opts.pendingPersonId),\n\t\t\t\t\topts.projectSummaries ? JSON.stringify(opts.projectSummaries) : null,\n\t\t\t\t\topts.projectIntent ? JSON.stringify(opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = readOperationInvite();\n\t\t\t\tif (existing) return renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t.get(inviteId);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByToken(token: string): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites\n\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t AND expires_at > ?`)\n\t\t\t.get(tokenDigest(token), token, new Date().toISOString());\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t)\n\t\t\t.get(tokenDigest(token), token);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await inspectInvite(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tprivate validateRecipientInviteParticipants(\n\t\tinvite: CoordinatorInvite,\n\t\topts: Pick<\n\t\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t\t>,\n\t): (string | null)[] {\n\t\tconst existingEnrollment = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id !== null &&\n\t\t\t\t\texistingEnrollment.identity_id !== opts.identityId))\n\t\t)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t// The immediate transaction keeps both participants unchanged through grant recovery.\n\t\tconst inviterEnrollment = invite.inviter_device_id\n\t\t\t? (this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t: undefined;\n\t\tconst subjects = [\n\t\t\topts.deviceId,\n\t\t\tenrollmentRevocationKeyId(opts.publicKey),\n\t\t\tinvite.inviter_device_id ?? null,\n\t\t\tinviterEnrollment ? enrollmentRevocationKeyId(inviterEnrollment.public_key) : null,\n\t\t];\n\t\tconst revoked = this.db\n\t\t\t.prepare(`SELECT 1 WHERE ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`)\n\t\t\t.get(...subjects);\n\t\tif (revoked) throw new Error(\"device_revoked\");\n\t\treturn subjects;\n\t}\n\n\tprivate getRecipientInviteById(inviteId: string): CoordinatorInvite {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t.get(inviteId) as CoordinatorInvite;\n\t}\n\n\tprivate getRecipientInviteBootstrapGrant(grantId: string): CoordinatorBootstrapGrant | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id,\n\t\t\texpires_at, created_at, created_by, revoked_at FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t.get(grantId) as CoordinatorBootstrapGrant | undefined;\n\t\treturn row ?? null;\n\t}\n\n\tprivate assertRecipientInviteAuthorized(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tsubjects: (string | null)[],\n\t): void {\n\t\tthis.validateRecipientInviteParticipants(invite, opts);\n\t\ttry {\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}) AS revoked,\n\t\t\t\t(${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}) AS owned`)\n\t\t\t\t.get(...subjects, ...subjects.slice(0, 2)) as\n\t\t\t\t| { revoked: number; owned: number }\n\t\t\t\t| undefined;\n\t\t\tif (\n\t\t\t\t!row ||\n\t\t\t\t(\"success\" in row && row.success === false) ||\n\t\t\t\t[row.revoked, row.owned].some((value) => value !== 0 && value !== 1)\n\t\t\t)\n\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\t\tif (row.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tprivate recipientInviteAuthorization(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tsubjects: (string | null)[],\n\t) {\n\t\treturn {\n\t\t\tsql: `NOT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL})`,\n\t\t\tvalues: [...subjects, ...subjects.slice(0, 2)],\n\t\t\tassertAuthorized: () => this.assertRecipientInviteAuthorized(invite, opts, subjects),\n\t\t};\n\t}\n\n\tasync consumeRecipientInvite(\n\t\tinput: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst opts = { ...input };\n\t\tconst consumedAt = normalizeInviteExpiresAt(opts.now);\n\t\tconst deviceDisplayName = opts.deviceDisplayName ?? null;\n\t\tvalidateRecipientOwnerInput(opts);\n\t\tconst preflightInvite = await this.getInviteByTokenForInspection(opts.token);\n\t\tconst preflightInspection = preflightInvite ? await inspectInvite(preflightInvite) : null;\n\t\tconst consistency = await prepareRecipientOwnerConsistency(\n\t\t\t{\n\t\t\t\t...this.schemaBackend,\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t},\n\t\t\topts,\n\t\t);\n\t\treturn this.db\n\t\t\t.transaction((): CoordinatorRecipientInviteAcceptance => {\n\t\t\t\tconst invite = this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(tokenDigest(opts.token), opts.token) as CoordinatorInvite | undefined;\n\t\t\t\tif (\n\t\t\t\t\t!invite ||\n\t\t\t\t\t!preflightInspection ||\n\t\t\t\t\tinvite.invite_id !== preflightInvite?.invite_id ||\n\t\t\t\t\tinvite.reviewed_intent_json !== preflightInvite.reviewed_intent_json ||\n\t\t\t\t\tinvite.reviewed_preview_digest !== preflightInvite.reviewed_preview_digest ||\n\t\t\t\t\tinvite.policy_team_id !== preflightInvite.policy_team_id ||\n\t\t\t\t\tinvite.target_identity_id !== preflightInvite.target_identity_id ||\n\t\t\t\t\tinvite.assigned_identity_id !== preflightInvite.assigned_identity_id ||\n\t\t\t\t\tpreflightInspection.kind !== opts.inviteKind ||\n\t\t\t\t\tinvite.revoked_at\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_invalid\");\n\t\t\t\t}\n\t\t\t\tconst group = this.db\n\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\tif (!group) throw new Error(\"group_not_found\");\n\t\t\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(consumedAt)) {\n\t\t\t\t\tthrow new Error(\"invite_expired\");\n\t\t\t\t}\n\t\t\t\tif (fingerprintPublicKey(opts.publicKey) !== opts.fingerprint) {\n\t\t\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t\t\t}\n\t\t\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(preflightInspection);\n\t\t\t\tif (authoritativeIdentityId !== opts.identityId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst sameBinding =\n\t\t\t\t\tinvite.bound_device_id === opts.deviceId &&\n\t\t\t\t\tinvite.bound_public_key === opts.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === opts.fingerprint;\n\t\t\t\tif (invite.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\t\t\tif (invite.consumed_at && invite.recipient_actor_id !== authoritativeIdentityId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst participantSubjects = this.validateRecipientInviteParticipants(invite, opts);\n\t\t\t\tconst authorization = this.recipientInviteAuthorization(invite, opts, participantSubjects);\n\t\t\t\tconst { sql: authorizationSql, values: authorizationValues } = authorization;\n\t\t\t\tthis.assertRecipientInviteAuthorized(invite, opts, participantSubjects);\n\t\t\t\tthis.assertRecipientOwnerPin(consistency);\n\t\t\t\tconst retained = consistency.retainedRecheck;\n\t\t\t\tconst changed = this.consumeRecipientOwnerToken(invite, opts, {\n\t\t\t\t\tauthorization,\n\t\t\t\t\tconsistency,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t});\n\t\t\t\tlet pendingPin = retained;\n\t\t\t\tconst saved = this.getRecipientInviteById(invite.invite_id);\n\t\t\t\tif (\n\t\t\t\t\tsaved.bound_device_id !== opts.deviceId ||\n\t\t\t\t\tsaved.bound_public_key !== opts.publicKey ||\n\t\t\t\t\tsaved.bound_fingerprint !== opts.fingerprint\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t\t\t}\n\t\t\t\tif (saved.recipient_actor_id !== authoritativeIdentityId)\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\tif (changed === 1) {\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t\t\t\t`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?, 1, ?\n\t\t\t\t\tWHERE ${authorizationSql}\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`,\n\t\t\t\t\t\t\t\tretained,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t...retained.values,\n\t\t\t\t\t\t\tinvite.group_id,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\t...authorizationValues,\n\t\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tpendingPin = this.repairRecipientOwnerIdentity(invite, opts, {\n\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\tconsistency,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthis.assertRecipientInviteAuthorized(invite, opts, participantSubjects);\n\t\t\t\tthis.validateAcceptedRecipientOwner(invite, opts);\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tif (\n\t\t\t\t\tpreflightInspection.kind === \"add_device\" &&\n\t\t\t\t\tinvite.inviter_device_id &&\n\t\t\t\t\t!invite.bootstrap_grant_id &&\n\t\t\t\t\tnew Date(invite.expires_at) > new Date(consumedAt)\n\t\t\t\t) {\n\t\t\t\t\tconst seed = this.db\n\t\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined;\n\t\t\t\t\tif (seed) {\n\t\t\t\t\t\tconst grantId = tokenUrlSafe(12);\n\t\t\t\t\t\tconst claimed = this.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\t trust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\t\t\t WHERE invite_id = ? AND bootstrap_grant_id IS NULL AND ${authorizationSql}`,\n\t\t\t\t\t\t\t\t\tpendingPin,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(...pendingPin.values, grantId, invite.invite_id, ...authorizationValues);\n\t\t\t\t\t\tif (claimed.changes === 1) {\n\t\t\t\t\t\t\tbootstrapGrant = insertBootstrapGrantSync(\n\t\t\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tgroupId: invite.group_id,\n\t\t\t\t\t\t\t\t\tseedDeviceId: seed.device_id,\n\t\t\t\t\t\t\t\t\tworkerDeviceId: opts.deviceId,\n\t\t\t\t\t\t\t\t\texpiresAt: invite.expires_at,\n\t\t\t\t\t\t\t\t\tcreatedBy: authoritativeIdentityId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst savedWithGrant = this.getRecipientInviteById(invite.invite_id);\n\t\t\t\tif (!bootstrapGrant && savedWithGrant.bootstrap_grant_id) {\n\t\t\t\t\tbootstrapGrant = this.getRecipientInviteBootstrapGrant(savedWithGrant.bootstrap_grant_id);\n\t\t\t\t}\n\t\t\t\t// Trigger effects belong to this transaction too; denial rolls back all acceptance writes.\n\t\t\t\tthis.assertRecipientInviteAuthorized(savedWithGrant, opts, participantSubjects);\n\t\t\t\tthis.assertRecipientOwnerPin(pendingPin);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\t\t\tinvite: savedWithGrant,\n\t\t\t\t\treviewed_intent: preflightInspection.reviewed_intent,\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate repairRecipientOwnerIdentity(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\toptions: { authorization: AuthLinkStatement; consistency: NegativeOwnerConsistency },\n\t): AuthLinkStatement {\n\t\tconst { authorization, consistency } = options;\n\t\tconst repaired = this.db\n\t\t\t.prepare(\n\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t`UPDATE enrolled_devices SET identity_id = ?\n\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\t\tAND public_key = ? AND fingerprint = ? AND ${authorization.sql}`,\n\t\t\t\t\tconsistency,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.run(\n\t\t\t\t...consistency.values,\n\t\t\t\topts.identityId,\n\t\t\t\tinvite.group_id,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\t...authorization.values,\n\t\t\t);\n\t\t// A zero-row repair does not consume the initial owner evidence.\n\t\treturn repaired.changes === 1 ? consistency.retainedRecheck : consistency;\n\t}\n\n\tprivate validateAcceptedRecipientOwner(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t) {\n\t\tconst enrollment = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (\n\t\t\tenrollment.public_key !== opts.publicKey ||\n\t\t\tenrollment.fingerprint !== opts.fingerprint ||\n\t\t\tenrollment.identity_id !== opts.identityId\n\t\t)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t}\n\n\tprivate assertRecipientOwnerPin(\n\t\tpredicate: AuthLinkStatement | null,\n\t): asserts predicate is AuthLinkStatement {\n\t\tif (\n\t\t\t!predicate ||\n\t\t\t(this.db.prepare(predicate.sql).get(...predicate.values) as { matches: number } | undefined)\n\t\t\t\t?.matches !== 1\n\t\t)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\n\tprivate consumeRecipientOwnerToken(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\toptions: {\n\t\t\tauthorization: AuthLinkStatement;\n\t\t\tconsistency: AuthLinkStatement;\n\t\t\tconsumedAt: string;\n\t\t},\n\t) {\n\t\tif (invite.consumed_at) return 0;\n\t\tconst { authorization, consistency, consumedAt } = options;\n\t\treturn this.db\n\t\t\t.prepare(\n\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?, recipient_display_name = ?, recipient_device_display_name = ?\n WHERE invite_id = ? AND consumed_at IS NULL AND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id AND g.archived_at IS NULL)\n AND ${authorization.sql}`,\n\t\t\t\t\tconsistency,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.run(\n\t\t\t\t...consistency.values,\n\t\t\t\t`consumed:${invite.invite_id}`,\n\t\t\t\tconsumedAt,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\topts.identityId,\n\t\t\t\topts.recipientDisplayName ?? null,\n\t\t\t\topts.deviceDisplayName ?? null,\n\t\t\t\tinvite.invite_id,\n\t\t\t\tconsumedAt,\n\t\t\t\topts.inviteKind,\n\t\t\t\t...authorization.values,\n\t\t\t).changes;\n\t}\n\n\tprivate prepareProjectInviteGuards(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t) {\n\t\tconst current = this.db\n\t\t\t.prepare(`SELECT public_key FROM enrolled_devices\n\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t.get(invite.group_id, opts.deviceId);\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(current ?? null);\n\t\tconst inviter = invite.inviter_device_id\n\t\t\t? (this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t: undefined;\n\t\tconst incomingKeyId = enrollmentRevocationKeyId(opts.publicKey);\n\t\tconst evidence = projectInviteGuardEvidence(invite, opts, inviter ?? null, {\n\t\t\trecipient: incomingKeyId,\n\t\t\tinviter: inviter ? enrollmentRevocationKeyId(inviter.public_key) : null,\n\t\t});\n\t\tconst guard = legacyProjectInviteOwnershipEvidence(evidence, opts.deviceId, {\n\t\t\tincoming: incomingKeyId,\n\t\t\tcurrent: currentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey),\n\t\t});\n\t\ttry {\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked,\n\t\t\t(${guard.ownershipSql}) AS owned`)\n\t\t\t\t.get(...guard.revocationValues, ...guard.ownershipValues) as\n\t\t\t\t| { revoked: number; owned: number }\n\t\t\t\t| undefined;\n\t\t\tif (!row || [row.revoked, row.owned].some((value) => value !== 0 && value !== 1))\n\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\t\tif (row.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t\tthis.validateRecipientInviteParticipants(invite, {\n\t\t\t...opts,\n\t\t\tidentityId: opts.recipientActorId,\n\t\t});\n\t\treturn guard;\n\t}\n\n\tprivate assertProjectInviteEligible(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t\tguard: ReturnType<BetterSqliteCoordinatorStore[\"prepareProjectInviteGuards\"]>,\n\t): void {\n\t\tconst state = this.db\n\t\t\t.prepare(`SELECT i.revoked_at, g.group_id, g.archived_at\n\t\t\tFROM coordinator_invites i LEFT JOIN groups g ON g.group_id = i.group_id\n\t\t\tWHERE i.invite_id = ?`)\n\t\t\t.get(invite.invite_id) as\n\t\t\t| {\n\t\t\t\t\trevoked_at: string | null;\n\t\t\t\t\tgroup_id: string | null;\n\t\t\t\t\tarchived_at: string | null;\n\t\t\t }\n\t\t\t| undefined;\n\t\tif (!state || state.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (!state.group_id) throw new Error(\"group_not_found\");\n\t\tif (state.archived_at) throw new Error(\"group_archived\");\n\t\tthis.prepareProjectInviteGuards(invite, opts);\n\t\tconst eligible = this.db\n\t\t\t.prepare(`SELECT 1 WHERE ${guard.boundEligibilitySql}`)\n\t\t\t.get(...guard.boundEligibilityValues);\n\t\tif (!eligible) throw new Error(\"invite_acceptance_incomplete\");\n\t}\n\n\tasync consumeProjectInvite(\n\t\tinput: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tconst opts = captureLegacyProjectInviteInput(input);\n\t\tconst consumedAt = normalizeInviteExpiresAt(opts.now);\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tlet invite = this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(tokenDigest(opts.token), opts.token) as CoordinatorInvite | undefined;\n\t\t\t\tif (!invite?.operation_id || !invite.project_intent_json || invite.revoked_at) {\n\t\t\t\t\tthrow new Error(\"invite_invalid\");\n\t\t\t\t}\n\t\t\t\tconst group = this.db\n\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\tif (!group) throw new Error(\"group_not_found\");\n\t\t\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\t\t\tif (invite.operation_id !== opts.operationId) throw new Error(\"invite_invalid\");\n\t\t\t\tif (fingerprintPublicKey(opts.publicKey) !== opts.fingerprint) {\n\t\t\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t\t\t}\n\t\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(consumedAt)) {\n\t\t\t\t\tthrow new Error(\"invite_expired\");\n\t\t\t\t}\n\t\t\t\tconst sameBinding =\n\t\t\t\t\tinvite.bound_device_id === opts.deviceId &&\n\t\t\t\t\tinvite.bound_public_key === opts.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === opts.fingerprint;\n\t\t\t\tif (invite.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\t\t\tif (\n\t\t\t\t\tinvite.consumed_at &&\n\t\t\t\t\t(invite.recipient_actor_id !== opts.recipientActorId ||\n\t\t\t\t\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\t\t\t\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName)\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst guard = this.prepareProjectInviteGuards(invite, opts);\n\t\t\t\tlet accepted = false;\n\t\t\t\tif (!invite.consumed_at) {\n\t\t\t\t\tconst changed = this.db\n\t\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\t\tWHERE invite_id = ? AND consumed_at IS NULL\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\t\tAND ${guard.eligibilitySql}`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t`consumed:${invite.invite_id}`,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\topts.recipientActorId,\n\t\t\t\t\t\t\topts.recipientDisplayName,\n\t\t\t\t\t\t\topts.deviceDisplayName,\n\t\t\t\t\t\t\tinvite.invite_id,\n\t\t\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t\t);\n\t\t\t\t\taccepted = changed.changes === 1;\n\t\t\t\t\tinvite = this.db\n\t\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t\t\t.get(invite.invite_id) as CoordinatorInvite;\n\t\t\t\t\tif (!accepted) {\n\t\t\t\t\t\tconst currentGroup = this.db\n\t\t\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\t\t\tif (currentGroup?.archived_at) throw new Error(\"group_archived\");\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\t\t\t\t\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\t\t\t\t\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.recipient_actor_id !== opts.recipientActorId ||\n\t\t\t\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\t\t\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\n\t\t\t\tif (accepted) {\n\t\t\t\t\tthis.assertProjectInviteEligible(invite, opts, guard);\n\t\t\t\t\tthis.enrollDeviceSync(invite.group_id, {\n\t\t\t\t\t\tdeviceId: opts.deviceId,\n\t\t\t\t\t\tpublicKey: opts.publicKey,\n\t\t\t\t\t\tfingerprint: opts.fingerprint,\n\t\t\t\t\t\tidentityId: opts.recipientActorId,\n\t\t\t\t\t\tdisplayName: opts.deviceDisplayName,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\t\t\t\t\t\tAND public_key = ? AND fingerprint = ? AND ${guard.boundEligibilitySql}`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\topts.recipientActorId,\n\t\t\t\t\t\t\tinvite.group_id,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst seed = invite.inviter_device_id\n\t\t\t\t\t? (this.db\n\t\t\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t\t\t: undefined;\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tif (\n\t\t\t\t\tseed &&\n\t\t\t\t\t!invite.bootstrap_grant_id &&\n\t\t\t\t\tnew Date(invite.expires_at) > new Date(consumedAt)\n\t\t\t\t) {\n\t\t\t\t\tconst grantId = tokenUrlSafe(12);\n\t\t\t\t\tconst claimed = this.db\n\t\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE invite_id = ? AND bootstrap_grant_id IS NULL AND bound_device_id = ?\n\t\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t\t\t.run(grantId, invite.invite_id, opts.deviceId, ...guard.boundEligibilityValues);\n\t\t\t\t\tif (claimed.changes === 1) {\n\t\t\t\t\t\tbootstrapGrant = insertBootstrapGrantSync(\n\t\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tgroupId: invite.group_id,\n\t\t\t\t\t\t\t\tseedDeviceId: seed.device_id,\n\t\t\t\t\t\t\t\tworkerDeviceId: opts.deviceId,\n\t\t\t\t\t\t\t\texpiresAt: invite.expires_at,\n\t\t\t\t\t\t\t\tcreatedBy: invite.inviter_actor_id,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst saved = this.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t\t.get(invite.invite_id) as CoordinatorInvite;\n\t\t\t\tconst enrollment = this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\t// Trigger effects are inside the immediate transaction; denial rolls back every write.\n\t\t\t\tthis.assertProjectInviteEligible(saved, opts, guard);\n\t\t\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\t\t\tif (enrollment.identity_id !== opts.recipientActorId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tif (!bootstrapGrant && saved.bootstrap_grant_id) {\n\t\t\t\t\tbootstrapGrant =\n\t\t\t\t\t\t(this.db\n\t\t\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\t\tcreated_at, created_by, revoked_at FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t\t\t\t.get(saved.bootstrap_grant_id) as CoordinatorBootstrapGrant | undefined) ?? null;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: accepted ? (\"accepted\" as const) : (\"existing\" as const),\n\t\t\t\t\tinvite: saved,\n\t\t\t\t\tenrollment,\n\t\t\t\t\tseed_enrollment: seed ?? null,\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tasync listInvites(groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t.all(groupId)\n\t\t\t.map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\topts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.run(\n\t\t\t\trequestId,\n\t\t\t\topts.groupId,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\topts.displayName ?? null,\n\t\t\t\topts.token,\n\t\t\t\tnow,\n\t\t\t);\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t.get(requestId);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(groupId: string, status = \"pending\"): Promise<CoordinatorJoinRequest[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t.all(groupId, status)\n\t\t\t.map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\topts = {\n\t\t\t...opts,\n\t\t\tbootstrapGrant: opts.bootstrapGrant ? { ...opts.bootstrapGrant } : opts.bootstrapGrant,\n\t\t};\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst row = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t.get(opts.requestId) as (CoordinatorJoinRequest & { public_key: string }) | undefined;\n\t\t\t\tif (!row) return null;\n\t\t\t\tif (row.status !== \"pending\")\n\t\t\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t\t\tconst bootstrapGrantRequest = normalizeCoordinatorBootstrapGrantRequest(\n\t\t\t\t\topts.bootstrapGrant,\n\t\t\t\t);\n\t\t\t\tconst reviewedAt = nowISO();\n\t\t\t\tconst nextStatus = opts.approved ? \"approved\" : \"denied\";\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tconst guard = opts.approved\n\t\t\t\t\t? this.prepareJoinApprovalSync(row, bootstrapGrantRequest)\n\t\t\t\t\t: null;\n\t\t\t\tconst transition = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\tWHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.run(nextStatus, reviewedAt, opts.reviewedBy ?? null, opts.requestId);\n\t\t\t\tif (transition.changes !== 1) throw new Error(\"join_review_incomplete\");\n\t\t\t\tif (guard) {\n\t\t\t\t\tbootstrapGrant = this.applyJoinApprovalSync(\n\t\t\t\t\t\trow,\n\t\t\t\t\t\tguard,\n\t\t\t\t\t\tbootstrapGrantRequest,\n\t\t\t\t\t\treviewedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst updated = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t.get(opts.requestId);\n\t\t\t\tif (!updated) throw new Error(\"join_review_incomplete\");\n\t\t\t\treturn {\n\t\t\t\t\t...rowToRecord<CoordinatorJoinRequestReviewResult>(updated),\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate prepareJoinApprovalSync(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tbootstrap: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t) {\n\t\tlet seed: CoordinatorEnrollment | null = null;\n\t\tif (bootstrap) {\n\t\t\tseed =\n\t\t\t\t(this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT * FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(row.group_id, bootstrap.seedDeviceId) as CoordinatorEnrollment | undefined) ?? null;\n\t\t\tif (!seed) throw new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\tif (seed.device_id === row.device_id)\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t}\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.get(row.group_id, row.device_id) ?? null,\n\t\t);\n\t\tconst guard = joinReviewGuardEvidence(\n\t\t\trow,\n\t\t\tseed,\n\t\t\t{\n\t\t\t\trecipient: enrollmentRevocationKeyId(row.public_key),\n\t\t\t\tseed: seed ? enrollmentRevocationKeyId(seed.public_key) : null,\n\t\t\t\tcurrent: currentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey),\n\t\t\t},\n\t\t\tcurrentPublicKey,\n\t\t);\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\treturn guard;\n\t}\n\n\tprivate assertJoinApprovalCurrentSync(guard: ReturnType<typeof joinReviewGuardEvidence>) {\n\t\tif (this.db.prepare(`SELECT 1 WHERE ${guard.revocationSql}`).get(...guard.revocationValues))\n\t\t\tthrow new Error(\"device_revoked\");\n\t\tlet owned: unknown;\n\t\ttry {\n\t\t\towned = this.db.prepare(`SELECT 1 WHERE ${guard.ownershipSql}`).get(...guard.ownershipValues);\n\t\t} catch {\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t}\n\t\tif (owned) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\tif (!this.db.prepare(`SELECT 1 WHERE ${guard.eligibilitySql}`).get(...guard.eligibilityValues))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n\n\tprivate applyJoinApprovalSync(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\tbootstrap: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t\treviewedAt: string,\n\t) {\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tif (!this.db.prepare(`SELECT 1 WHERE ${guard.sourceSql}`).get(...guard.sourceValues))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\tthis.enrollDeviceSync(row.group_id, {\n\t\t\tdeviceId: row.device_id,\n\t\t\tfingerprint: row.fingerprint,\n\t\t\tpublicKey: row.public_key,\n\t\t\tdisplayName: (row.display_name ?? \"\").trim() || null,\n\t\t});\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tconst grant = bootstrap\n\t\t\t? insertBootstrapGrantSync(this.db, {\n\t\t\t\t\t...bootstrap,\n\t\t\t\t\tgroupId: row.group_id,\n\t\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t\t})\n\t\t\t: null;\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tconst complete = this.db\n\t\t\t.prepare(`SELECT 1 FROM coordinator_join_requests jr\n\t\t\tJOIN enrolled_devices e ON e.group_id = jr.group_id AND e.device_id = jr.device_id\n\t\t\tWHERE jr.request_id = ? AND jr.status = 'approved' AND jr.reviewed_at = ?\n\t\t\tAND e.public_key = ? AND e.fingerprint = ? AND e.enabled = 1`)\n\t\t\t.get(row.request_id, reviewedAt, row.public_key, row.fingerprint);\n\t\tif (!complete) throw new Error(\"join_review_incomplete\");\n\t\treturn grant;\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = String(opts.groupId ?? \"\").trim();\n\t\tconst requestingDeviceId = String(opts.requestingDeviceId ?? \"\").trim();\n\t\tconst requestedDeviceId = String(opts.requestedDeviceId ?? \"\").trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\treturn this.db.transaction(() => {\n\t\t\tconst now = nowISO();\n\t\t\tif (hasExpectedIncomingRequestId) {\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.run(now, expectedIncomingRequestId, groupId, requestedDeviceId, requestingDeviceId);\n\t\t\t\tif (result.changes !== 1) {\n\t\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t\t}\n\t\t\t\tconst completed = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.get(expectedIncomingRequestId);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tconst existing = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ?\n\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t LIMIT 1`)\n\t\t\t\t.get(groupId, requestingDeviceId, requestedDeviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\t\t}\n\t\t\tconst reverse = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ?\n\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t LIMIT 1`)\n\t\t\t\t.get(groupId, requestedDeviceId, requestingDeviceId);\n\t\t\tif (reverse) {\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?`)\n\t\t\t\t\t.run(now, (reverse as CoordinatorReciprocalApproval).request_id);\n\t\t\t\tconst completed = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.get((reverse as CoordinatorReciprocalApproval).request_id);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tconst requestId = tokenUrlSafe(12);\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.run(requestId, groupId, requestingDeviceId, requestedDeviceId, now);\n\t\t\tconst created = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.get(requestId);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t\t})();\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst input = normalizeCoordinatorBootstrapGrantInput(opts);\n\t\ttry {\n\t\t\treturn this.db\n\t\t\t\t.transaction(() => {\n\t\t\t\t\tconst revoked = this.db.prepare(BOOTSTRAP_PARTICIPANTS_REVOKED_SQL);\n\t\t\t\t\tif (revoked.get(input.seedDeviceId, null, input.workerDeviceId, null)) {\n\t\t\t\t\t\tthrow new Error(\"device_revoked\");\n\t\t\t\t\t}\n\t\t\t\t\tconst source = this.db.prepare(BOOTSTRAP_PARTICIPANT_SOURCE_SQL);\n\t\t\t\t\tconst seed = captureBootstrapParticipantSource(\n\t\t\t\t\t\t(source.get(input.groupId, input.seedDeviceId) as\n\t\t\t\t\t\t\t| BootstrapParticipantSource\n\t\t\t\t\t\t\t| undefined) ?? null,\n\t\t\t\t\t);\n\t\t\t\t\tconst worker = captureBootstrapParticipantSource(\n\t\t\t\t\t\t(source.get(input.groupId, input.workerDeviceId) as\n\t\t\t\t\t\t\t| BootstrapParticipantSource\n\t\t\t\t\t\t\t| undefined) ?? null,\n\t\t\t\t\t);\n\t\t\t\t\tconst subjects = [\n\t\t\t\t\t\tinput.seedDeviceId,\n\t\t\t\t\t\tseed ? enrollmentRevocationKeyId(seed.public_key) : null,\n\t\t\t\t\t\tinput.workerDeviceId,\n\t\t\t\t\t\tworker ? enrollmentRevocationKeyId(worker.public_key) : null,\n\t\t\t\t\t];\n\t\t\t\t\tif (revoked.get(...subjects)) throw new Error(\"device_revoked\");\n\t\t\t\t\tconst values = bootstrapRawInsertValues(\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\t{ grantId: tokenUrlSafe(12), createdAt: nowISO() },\n\t\t\t\t\t\t{ seed, worker },\n\t\t\t\t\t\tsubjects,\n\t\t\t\t\t);\n\t\t\t\t\tconst row = this.db.prepare(BOOTSTRAP_RAW_INSERT_SQL).get(...values);\n\t\t\t\t\t// A trigger may revoke a participant during insertion; abort the entire transaction.\n\t\t\t\t\tif (revoked.get(...subjects)) throw new Error(\"device_revoked\");\n\t\t\t\t\tif (!row) throw new Error(\"bootstrap_grant_write_incomplete\");\n\t\t\t\t\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"device_revoked\") throw error;\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tprivate getScopeSync(scopeId: string): CoordinatorScope | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t.get(scopeId);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate getScopeMembershipSync(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): CoordinatorScopeMembership | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t.get(scopeId, deviceId);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCoordinatorCreateScopeInput(opts);\n\t\tif (this.getScopeSync(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.run(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t);\n\t\tconst scope = this.getScopeSync(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? this.getScopeSync(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeCoordinatorUpdateScopeInput(opts, existing);\n\t\tthis.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.run(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t);\n\t\treturn this.getScopeSync(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`)\n\t\t\t.all(...params)\n\t\t\t.map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync getScopeAuthorization(\n\t\traw: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureScopeAuthorizationInput(raw);\n\t\t\treturn this.db\n\t\t\t\t.transaction((): CoordinatorScopeAuthorizationResult => {\n\t\t\t\t\tconst scope = this.getScopeSync(input.scopeId);\n\t\t\t\t\tif (!scope) return { kind: \"rejected\", error: \"scope_not_found\" };\n\t\t\t\t\trequireScopeAuthorizationRecord(scope, SCOPE_FIELDS);\n\t\t\t\t\tconst error = scopeAuthorizationError(scope, input.groupId);\n\t\t\t\t\tif (error) return { kind: \"rejected\", error };\n\t\t\t\t\tconst group = this.db\n\t\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t\t.get(input.groupId) as { archived_at: string | null } | undefined;\n\t\t\t\t\tif (!group) return { kind: \"rejected\", error: \"scope_source_mismatch\" };\n\t\t\t\t\tif (group.archived_at !== null) return { kind: \"rejected\", error: \"group_archived\" };\n\t\t\t\t\tconst members = this.captureScopeAuthorizationMembers(scope, input.groupId);\n\t\t\t\t\tconst current = this.db\n\t\t\t\t\t\t.prepare(READ_SCOPE_AUTHORIZATION_SQL)\n\t\t\t\t\t\t.get(JSON.stringify([scope]), JSON.stringify(members)) as\n\t\t\t\t\t\t| (CoordinatorScope & { members_json: string })\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (!current) return { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t\t\t\trequireScopeAuthorizationRecord(current, SCOPE_FIELDS);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"authorized\",\n\t\t\t\t\t\tauthorizationVersion: 1,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tmembers: parseScopeAuthorizationMembers(current.members_json, members),\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\treturn { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t}\n\t}\n\n\tprivate captureScopeAuthorizationMembers(\n\t\tscope: CoordinatorScope,\n\t\tgroupId: string,\n\t): CapturedScopeMember[] {\n\t\tconst memberships = this.db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT * FROM coordinator_scope_memberships WHERE scope_id = ? ORDER BY device_id ASC\",\n\t\t\t)\n\t\t\t.all(scope.scope_id) as CoordinatorScopeMembership[];\n\t\tconst captured: Array<Omit<CapturedScopeMember, \"keyId\">> = [];\n\t\tfor (const membership of memberships) {\n\t\t\trequireScopeAuthorizationRecord(membership, [\"status\"]);\n\t\t\tif (membership.status !== \"active\") continue;\n\t\t\trequireScopeAuthorizationRecord(membership, MEMBERSHIP_FIELDS);\n\t\t\tif (!isCurrentScopeMember(scope, membership)) continue;\n\t\t\tconst enrollment = this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${ENROLLMENT_FIELDS.join(\", \")} FROM enrolled_devices WHERE group_id = ? AND device_id = ?`,\n\t\t\t\t)\n\t\t\t\t.get(groupId, membership.device_id) as CoordinatorEnrollment | undefined;\n\t\t\tif (!enrollment) continue;\n\t\t\trequireScopeAuthorizationRecord(enrollment, ENROLLMENT_FIELDS);\n\t\t\tif (enrollment.enabled !== 1) continue;\n\t\t\tcaptured.push({ membership: { ...membership }, enrollment: { ...enrollment } });\n\t\t}\n\t\t// Capture the complete source set before any hash hook can change another tuple.\n\t\treturn captured.flatMap((member) => {\n\t\t\tconst keyId = enrollmentRevocationKeyId(member.enrollment.public_key);\n\t\t\treturn keyId === null ? [] : [{ ...member, keyId }];\n\t\t});\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst grantScopeMembershipTransaction = () => {\n\t\t\tconst receipt = getMembershipEffectReceiptSync(this.db, effectId);\n\t\t\tif (receipt) {\n\t\t\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\t\t\treturn membershipFromEffectReceipt(receipt);\n\t\t\t}\n\t\t\tconst scopeId = clean(opts.scopeId);\n\t\t\tconst deviceId = clean(opts.deviceId);\n\t\t\tconst scope = scopeId ? this.getScopeSync(scopeId) : null;\n\t\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\t\tconst existing = scopeId && deviceId ? this.getScopeMembershipSync(scopeId, deviceId) : null;\n\t\t\tconst normalized = normalizeCoordinatorGrantScopeMembershipInput(opts, scope, existing);\n\t\t\tassertScopeMembershipDeviceEnrolled(this.db, normalized.groupId, normalized.deviceId);\n\t\t\tconst now = nowISO();\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\t\trole = excluded.role,\n\t\t\t\t\t\tstatus = 'active',\n\t\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t\t OR (\n\t\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t\t )`)\n\t\t\t\t.run(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\tif (result.changes <= 0) {\n\t\t\t\tthrow new Error(\"scope membership grant was not applied.\");\n\t\t\t}\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.get(normalized.scopeId, normalized.deviceId);\n\t\t\tconst membership = rowToRecord<CoordinatorScopeMembership>(row);\n\t\t\tinsertMembershipAuditSync(this.db, {\n\t\t\t\teffectId,\n\t\t\t\taction: \"grant\",\n\t\t\t\tcurrent: membership,\n\t\t\t\tprevious: existing,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\teffectId,\n\t\t\t\taction: \"grant\",\n\t\t\t\trequestJson,\n\t\t\t\tapplied: true,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tmembership,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t\treturn membership;\n\t\t};\n\t\treturn this.db.transaction(grantScopeMembershipTransaction).immediate();\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst receipt = getMembershipEffectReceiptSync(this.db, effectId);\n\t\t\t\tif (receipt) {\n\t\t\t\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\t\t\t\treturn receipt.outcome_applied === 1;\n\t\t\t\t}\n\t\t\t\tconst membershipEpoch =\n\t\t\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\t\t\tconst requestedGroupId = clean(opts.groupId);\n\t\t\t\tconst scope = requestedGroupId ? this.getScopeSync(scopeId) : null;\n\t\t\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t\t\t}\n\t\t\t\tconst existing = this.getScopeMembershipSync(scopeId, deviceId);\n\t\t\t\tconst now = nowISO();\n\t\t\t\tif (!existing) {\n\t\t\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\t\t\teffectId,\n\t\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\t\trequestJson,\n\t\t\t\t\t\tapplied: false,\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tmembership: null,\n\t\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\t});\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (membershipEpoch != null && membershipEpoch <= existing.membership_epoch) {\n\t\t\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t\t\t}\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\t\tclean(opts.manifestHash),\n\t\t\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\texisting.membership_epoch,\n\t\t\t\t\t\texisting.status,\n\t\t\t\t\t);\n\t\t\t\tif (result.changes <= 0) return false;\n\t\t\t\tconst membership = this.getScopeMembershipSync(scopeId, deviceId);\n\t\t\t\tif (!membership) throw new Error(\"scope membership revoke was not applied.\");\n\t\t\t\tinsertMembershipAuditSync(this.db, {\n\t\t\t\t\teffectId,\n\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\tcurrent: membership,\n\t\t\t\t\tprevious: existing,\n\t\t\t\t\tactorType: clean(opts.actorType),\n\t\t\t\t\tactorId: clean(opts.actorId),\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t});\n\t\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\t\teffectId,\n\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\trequestJson,\n\t\t\t\t\tapplied: true,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembership,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t.all(normalizedScopeId)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedDeviceId = clean(deviceId);\n\t\tif (!normalizedDeviceId) throw new Error(\"deviceId is required.\");\n\t\t// Served by idx_coordinator_scope_memberships_device_status.\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE device_id = ? ${statusWhere}\n\t\t\t\t ORDER BY scope_id ASC`)\n\t\t\t.all(normalizedDeviceId)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeCoordinatorAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn this.db\n\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t LIMIT ?`)\n\t\t\t.all(...params)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t.get(grantId);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync getBootstrapGrantAuthorization(\n\t\traw: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureBootstrapAuthorizationInput(raw);\n\t\t\treturn this.db\n\t\t\t\t.transaction(() => {\n\t\t\t\t\tconst source = this.db.prepare(BOOTSTRAP_AUTHORIZATION_SOURCE_SQL).get(input.grantId) as\n\t\t\t\t\t\t| BootstrapAuthorizationRow\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tconst sourceError = bootstrapAuthorizationSourceError(input, source ?? null);\n\t\t\t\t\tif (sourceError) return rejectBootstrapAuthorization(sourceError);\n\t\t\t\t\tif (!source) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t\t\t\tconst captured = { ...source };\n\t\t\t\t\tconst decision = bootstrapAuthorizationDecision(input, captured, {\n\t\t\t\t\t\tseed:\n\t\t\t\t\t\t\tcaptured.seed_enrollment_public_key === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: enrollmentRevocationKeyId(captured.seed_enrollment_public_key),\n\t\t\t\t\t\tworker:\n\t\t\t\t\t\t\tcaptured.worker_enrollment_public_key === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: enrollmentRevocationKeyId(captured.worker_enrollment_public_key),\n\t\t\t\t\t});\n\t\t\t\t\tconst current = this.db.prepare(decision.sql).get(...decision.values) as\n\t\t\t\t\t\t| BootstrapAuthorizationRow\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\treturn bootstrapAuthorizationResult(current ?? null);\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t}\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t.all(groupId)\n\t\t\t.map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t WHERE grant_id = ?`)\n\t\t\t.run(revokedAt, grantId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = String(opts.status ?? \"pending\").trim() || \"pending\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t.all(opts.groupId, opts.deviceId, status)\n\t\t\t.map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync createLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst group = await this.getGroup(normalizedGroupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst manifestJson = canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest);\n\t\tconst normalized = JSON.parse(manifestJson) as CoordinatorLegacyTeamCompletionManifestV1;\n\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(normalized);\n\t\tconst existing = this.readStoredLegacyCompletion(normalizedGroupId, normalized.candidate_ref);\n\t\tif (existing)\n\t\t\treturn legacyCompletionWriteResult(existing.manifest_json, manifestJson, \"existing\");\n\t\tconst coordinatorId = await this.requireLegacyTeamCompletionSources(\n\t\t\tnormalizedGroupId,\n\t\t\tnormalized,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst ownerProof = await this.prepareLegacyTeamCompletionOwnerProof(\n\t\t\tnormalizedGroupId,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst { result, stored, denial } = this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`${LEGACY_OWNER_INPUT_SQL}${ownerProof.ctes}\n\t\t\tINSERT OR IGNORE INTO coordinator_legacy_team_completions(\n\t\t\t\tgroup_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n\t\t\t) SELECT ?, ?, ?, ?, ?, ?\n\t\t\t FROM groups\n\t\t\t WHERE group_id = ? AND archived_at IS NULL\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1\n\t\t\t FROM json_each(?, '$.project_mappings') AS requested\n\t\t\t LEFT JOIN coordinator_scopes AS scope\n\t\t\t ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t AND scope.coordinator_id = ?\n\t\t\t AND scope.group_id = ?\n\t\t\t\t AND scope.status = 'active'\n\t\t\t WHERE scope.scope_id IS NULL\n\t\t\t )\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t WHERE enrolled.group_id = ?\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n\t\t\t AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n\t\t\t AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n\t\t\t )\n\t\t\t )\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t WHERE json_extract(requested.value, '$.decision') = 'included'\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t WHERE enrolled.group_id = ?\n\t\t\t AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n\t\t\t AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n\t\t\t AND enrolled.enabled = 1\n\t\t\t )\n\t\t\t ) AND ${LEGACY_OWNER_SOURCE_CURRENT_SQL}\n\t\t\t\t AND (${ownerProof.currentSql}) AND (${ownerProof.compatibleSql})`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\t...ownerProof.values,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tnormalized.candidate_ref,\n\t\t\t\t\t\tnormalized.version,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tnormalized.completed_at,\n\t\t\t\t\t\tnowISO(),\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t);\n\t\t\t\tconst stored = this.readStoredLegacyCompletion(normalizedGroupId, normalized.candidate_ref);\n\t\t\t\tconst denial = stored\n\t\t\t\t\t? null\n\t\t\t\t\t: (this.db.prepare(ownerProof.denialSql).get(...ownerProof.values) as { denial: string });\n\t\t\t\treturn { result, stored, denial };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (!stored) {\n\t\t\tawait this.requireLegacyTeamCompletionSources(normalizedGroupId, normalized, manifestJson);\n\t\t\tif (denial?.denial === \"completion_conflict\") {\n\t\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t\t}\n\t\t\tthrow new Error(\"completion_manifest_unavailable\");\n\t\t}\n\t\treturn legacyCompletionWriteResult(\n\t\t\tstored.manifest_json,\n\t\t\tmanifestJson,\n\t\t\tresult.changes === 1 ? \"created\" : \"existing\",\n\t\t);\n\t}\n\n\tprivate readStoredLegacyCompletion(groupId: string, candidateRef: string) {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t.get(groupId, candidateRef) as { manifest_json: string } | undefined;\n\t}\n\n\tprivate async prepareLegacyTeamCompletionOwnerProof(groupId: string, manifestJson: string) {\n\t\tconst keyMetadata = await legacyOwnerKeyMetadata(\n\t\t\tthis.db.prepare(LEGACY_OWNER_KEYS_SQL).all(manifestJson, groupId) as { public_key: string }[],\n\t\t);\n\t\tconst proof = legacyCompletionOwnerProofSql(\n\t\t\tawait captureLegacyCompletionOwnerProof({\n\t\t\t\tbackend: {\n\t\t\t\t\t...this.schemaBackend,\n\t\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t\t},\n\t\t\t\tgroupId,\n\t\t\t\tmanifestJson,\n\t\t\t\tkeyMetadata,\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\t...proof,\n\t\t\tvalues: [manifestJson, groupId, keyMetadata, ...proof.values],\n\t\t\tdenialSql: `${LEGACY_OWNER_INPUT_SQL}${proof.ctes}\n\t\t SELECT CASE WHEN NOT (${LEGACY_OWNER_SOURCE_CURRENT_SQL}) OR NOT (${proof.currentSql})\n\t\t THEN 'completion_manifest_unavailable'\n\t\t WHEN NOT (${proof.compatibleSql}) THEN 'completion_conflict'\n\t\t ELSE 'completion_manifest_unavailable' END AS denial`,\n\t\t};\n\t}\n\n\tprivate async requireLegacyTeamCompletionSources(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tmanifestJson: string,\n\t): Promise<string | null> {\n\t\tconst group = await this.getGroup(groupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst bindings = this.db\n\t\t\t.prepare(`SELECT DISTINCT requested.scope_id, scope.authority_type,\n\t\t\t\tscope.coordinator_id, scope.group_id, scope.status\n\t\t\t FROM (SELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\tFROM json_each(?, '$.project_mappings')) AS requested\n\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t.all(manifestJson) as CoordinatorLegacyTeamCompletionScopeBinding[];\n\t\treturn requireCoordinatorLegacyTeamCompletionScopeBindings(manifest, groupId, bindings);\n\t}\n\n\tasync getLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tconst normalizedCandidateRef =\n\t\t\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef(candidateRef);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t.get(normalizedGroupId, normalizedCandidateRef) as { manifest_json: string } | undefined;\n\t\treturn row\n\t\t\t? normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json))\n\t\t\t: null;\n\t}\n\n\tasync listLegacyTeamCompletions(\n\t\tgroupIds: string[],\n\t): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t\tconst normalizedGroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(groupIds);\n\t\tif (normalizedGroupIds.length === 0) return [];\n\t\tconst placeholders = normalizedGroupIds.map(() => \"?\").join(\", \");\n\t\tconst stats = this.db\n\t\t\t.prepare(`SELECT\n\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\tFROM coordinator_legacy_team_completions\n\t\t\tWHERE group_id IN (${placeholders})`)\n\t\t\t.get(...normalizedGroupIds) as {\n\t\t\trecord_count: number;\n\t\t\tbatch_bytes: number;\n\t\t\tmax_manifest_bytes: number;\n\t\t};\n\t\tif (\n\t\t\tstats.record_count > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS ||\n\t\t\tstats.batch_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES ||\n\t\t\tstats.max_manifest_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t\t) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst rows = this.db\n\t\t\t.prepare(`WITH completion_stats AS (\n\t\t\t\tSELECT\n\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id IN (${placeholders})\n\t\t\t)\n\t\t\tSELECT completions.group_id, completions.manifest_json\n\t\t\tFROM coordinator_legacy_team_completions AS completions\n\t\t\tCROSS JOIN completion_stats\n\t\t\tWHERE completions.group_id IN (${placeholders})\n\t\t\t\t AND completion_stats.record_count <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS}\n\t\t\t\t AND completion_stats.batch_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES}\n\t\t\t\t AND completion_stats.max_manifest_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t AND LENGTH(completions.manifest_json) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\tORDER BY completions.group_id, completions.completed_at, completions.candidate_ref\n\t\t\t\tLIMIT ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1}`)\n\t\t\t.all(...normalizedGroupIds, ...normalizedGroupIds) as Array<{\n\t\t\tgroup_id: string;\n\t\t\tmanifest_json: string;\n\t\t}>;\n\t\tif (rows.length === 0 && stats.record_count > 0) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst batchBytes = rows.reduce(\n\t\t\t(total, row) =>\n\t\t\t\ttotal + Buffer.byteLength(row.group_id) + Buffer.byteLength(row.manifest_json),\n\t\t\t0,\n\t\t);\n\t\tif (batchBytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\treturn rows.map((row) => ({\n\t\t\tgroup_id: row.group_id,\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json)),\n\t\t}));\n\t}\n\n\tasync captureAuthControllerLegacyHistory(input: ControllerHistoryInput) {\n\t\treturn captureControllerHistory(\n\t\t\tinput,\n\t\t\tasync <T>(sql: string, values: string[]) => this.db.prepare(sql).all(...values) as T[],\n\t\t);\n\t}\n\n\tasync upsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeCoordinatorAddresses([], opts.addresses);\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.run(\n\t\t\t\topts.groupId,\n\t\t\t\topts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(opts.capabilities ?? {}),\n\t\t\t);\n\t\treturn {\n\t\t\tgroup_id: opts.groupId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\tgroupId: string,\n\t\trequestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\ttry {\n\t\t\treturn this.readGroupPeers(groupId, requestingDeviceId);\n\t\t} catch {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n\n\tprivate readGroupPeers(groupId: string, requestingDeviceId: string): CoordinatorPeerRecord[] {\n\t\tconst now = new Date();\n\t\tconst rows = this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst captured = capturePeerEnrollments(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(CAPTURE_PEER_ENROLLMENTS_SQL)\n\t\t\t\t\t\t.all(groupId, requestingDeviceId) as CapturedPeerEnrollment[],\n\t\t\t\t);\n\t\t\t\tconst candidates = captured.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tkeyId: enrollmentRevocationKeyId(row.public_key),\n\t\t\t\t}));\n\t\t\t\treturn requirePeerDiscoveryRows(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(READ_CURRENT_PEERS_SQL)\n\t\t\t\t\t\t.all(JSON.stringify(candidates), groupId, requestingDeviceId),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.immediate();\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeCoordinatorAddresses(\n\t\t\t\t\t\t[],\n\t\t\t\t\t\tJSON.parse((row.addresses_json as string) || \"[]\") as string[],\n\t\t\t\t\t);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse((row.capabilities_json as string) || \"{}\") as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\tunknown\n\t\t\t\t>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","import { getCodememEnvOverrides, readCodememConfigFile } from \"./observer-config.js\";\n\ntype ConfigRecord = Record<string, unknown>;\n\nfunction clean(value: unknown): string {\n\treturn typeof value === \"string\" ? value.trim() : \"\";\n}\n\nfunction parseIntOr(value: unknown, fallback: number): number {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return Math.trunc(value);\n\tif (typeof value === \"string\" && /^-?\\d+$/.test(value.trim()))\n\t\treturn Number.parseInt(value.trim(), 10);\n\treturn fallback;\n}\n\nfunction parseBoolOr(value: unknown, fallback: boolean): boolean {\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\tif ([\"1\", \"true\", \"yes\", \"on\"].includes(normalized)) return true;\n\t\tif ([\"0\", \"false\", \"no\", \"off\"].includes(normalized)) return false;\n\t}\n\treturn fallback;\n}\n\nfunction parseStringList(value: unknown): string[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.filter((item): item is string => typeof item === \"string\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t}\n\tif (typeof value === \"string\") {\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t}\n\treturn [];\n}\n\nexport interface CoordinatorSyncConfig {\n\tsyncEnabled: boolean;\n\tsyncHost: string;\n\tsyncPort: number;\n\tsyncIntervalS: number;\n\tsyncAdvertise: string;\n\tsyncMdns: boolean;\n\tsyncRetentionEnabled: boolean;\n\tsyncRetentionMaxAgeDays: number;\n\tsyncRetentionMaxSizeMb: number;\n\tsyncRetentionIntervalS: number;\n\tsyncRetentionMaxRuntimeMs: number;\n\tsyncRetentionMaxOpsPerPass: number;\n\trawEventsRetentionEnabled: boolean;\n\t/** Whether raw_events_retention_enabled was explicitly set (file or env), so\n\t * callers can treat an explicit `false` as authoritative over legacy knobs. */\n\trawEventsRetentionConfigured: boolean;\n\trawEventsRetentionMaxAgeDays: number;\n\tsyncProjectsInclude: string[];\n\tsyncProjectsExclude: string[];\n\tsyncOpsLimit: number;\n\tsyncCoordinatorUrl: string;\n\tsyncCoordinatorGroup: string;\n\tsyncCoordinatorGroups: string[];\n\tsyncCoordinatorTimeoutS: number;\n\tsyncCoordinatorPresenceTtlS: number;\n\tsyncCoordinatorAdminSecret: string;\n}\n\nexport function readCoordinatorSyncConfig(config?: ConfigRecord): CoordinatorSyncConfig {\n\tconst raw = { ...(config ?? readCodememConfigFile()) } as ConfigRecord;\n\tconst envOverrides = getCodememEnvOverrides();\n\tfor (const key of Object.keys(envOverrides)) {\n\t\tconst value = process.env[envOverrides[key] as string];\n\t\tif (value != null) raw[key] = value;\n\t}\n\tconst syncCoordinatorGroup = clean(raw.sync_coordinator_group);\n\tconst syncCoordinatorGroups = parseStringList(raw.sync_coordinator_groups);\n\tif (syncCoordinatorGroups.length === 0 && syncCoordinatorGroup) {\n\t\tsyncCoordinatorGroups.push(syncCoordinatorGroup);\n\t}\n\treturn {\n\t\tsyncEnabled: parseBoolOr(raw.sync_enabled, false),\n\t\tsyncHost: clean(raw.sync_host) || \"0.0.0.0\",\n\t\tsyncPort: parseIntOr(raw.sync_port, 7337),\n\t\tsyncIntervalS: parseIntOr(raw.sync_interval_s, 120),\n\t\tsyncAdvertise: clean(raw.sync_advertise) || \"auto\",\n\t\tsyncMdns: parseBoolOr(raw.sync_mdns, false),\n\t\tsyncRetentionEnabled: parseBoolOr(raw.sync_retention_enabled, false),\n\t\tsyncRetentionMaxAgeDays: Math.max(1, parseIntOr(raw.sync_retention_max_age_days, 30)),\n\t\tsyncRetentionMaxSizeMb: Math.max(1, parseIntOr(raw.sync_retention_max_size_mb, 512)),\n\t\tsyncRetentionIntervalS: Math.max(5, parseIntOr(raw.sync_retention_interval_s, 300)),\n\t\tsyncRetentionMaxRuntimeMs: Math.max(100, parseIntOr(raw.sync_retention_max_runtime_ms, 2000)),\n\t\tsyncRetentionMaxOpsPerPass: Math.max(1, parseIntOr(raw.sync_retention_max_ops_per_pass, 5000)),\n\t\trawEventsRetentionEnabled: parseBoolOr(raw.raw_events_retention_enabled, false),\n\t\trawEventsRetentionConfigured: raw.raw_events_retention_enabled !== undefined,\n\t\trawEventsRetentionMaxAgeDays: Math.max(\n\t\t\t1,\n\t\t\tparseIntOr(raw.raw_events_retention_max_age_days, 90),\n\t\t),\n\t\tsyncProjectsInclude: parseStringList(raw.sync_projects_include),\n\t\tsyncProjectsExclude: parseStringList(raw.sync_projects_exclude),\n\t\tsyncOpsLimit: Math.max(1, Math.min(1000, parseIntOr(raw.sync_ops_limit, 500))),\n\t\tsyncCoordinatorUrl: clean(raw.sync_coordinator_url),\n\t\tsyncCoordinatorGroup,\n\t\tsyncCoordinatorGroups,\n\t\tsyncCoordinatorTimeoutS: parseIntOr(raw.sync_coordinator_timeout_s, 3),\n\t\tsyncCoordinatorPresenceTtlS: parseIntOr(raw.sync_coordinator_presence_ttl_s, 180),\n\t\tsyncCoordinatorAdminSecret: clean(raw.sync_coordinator_admin_secret),\n\t};\n}\n\nexport function coordinatorEnabled(config: CoordinatorSyncConfig): boolean {\n\treturn Boolean(config.syncCoordinatorUrl && config.syncCoordinatorGroups.length > 0);\n}\n","import type { Database } from \"./db.js\";\nimport type { RecipientPolicyDenyOverlayRecord } from \"./recipient-policy-reconciliation.js\";\n\nexport function denyOverlayRow(row: Record<string, unknown>): RecipientPolicyDenyOverlayRecord {\n\treturn {\n\t\tcanonicalProjectIdentity: String(row.canonical_project_identity),\n\t\tscopeId: String(row.scope_id),\n\t\tdeviceId: String(row.device_id),\n\t\tgeneration: Number(row.generation),\n\t\treasonCode: String(row.reason_code),\n\t\tcreatedAt: String(row.created_at),\n\t\tupdatedAt: String(row.updated_at),\n\t};\n}\n\n/** Any deny for the pair applies, including ambiguous legacy project overlays. */\nexport function getAnyRecipientPolicyDenyOverlayForScopeDevice(\n\tdb: Database,\n\tinput: { scopeId: string; deviceId: string },\n): RecipientPolicyDenyOverlayRecord | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t WHERE scope_id = ? AND device_id = ?\n\t\t\t ORDER BY canonical_project_identity\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(input.scopeId, input.deviceId) as Record<string, unknown> | undefined;\n\treturn row ? denyOverlayRow(row) : null;\n}\n","import { createHash } from \"node:crypto\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport interface ScopeMembershipCatalog {\n\tversion: 1;\n\titems: CoordinatorScope[];\n}\n\nexport interface ScopeMembershipSnapshot {\n\tauthorization_version: 1;\n\tscope: CoordinatorScope;\n\titems: Array<{\n\t\tmembership: CoordinatorScopeMembership;\n\t\tenrollment: CoordinatorEnrollment;\n\t\tkey_id: string;\n\t}>;\n}\n\nfunction requireEnvelope(raw: unknown, versionField: string): Record<string, unknown> {\n\tif (!raw || typeof raw !== \"object\" || Array.isArray(raw))\n\t\tthrow new Error(\"Invalid current scope snapshot.\");\n\tconst envelope = raw as Record<string, unknown>;\n\tif (envelope[versionField] !== 1 || !Array.isArray(envelope.items))\n\t\tthrow new Error(\"Current scope snapshot version 1 and items required.\");\n\treturn envelope;\n}\n\nfunction requireScope(raw: unknown, groupId: string): CoordinatorScope {\n\trequireScopeAuthorizationRecord(raw, SCOPE_FIELDS);\n\tconst scope = raw as CoordinatorScope;\n\tif (scopeAuthorizationError(scope, groupId)) throw new Error(\"Invalid scope source or status.\");\n\treturn scope;\n}\n\nexport function normalizeScopeCatalog(raw: unknown, groupId: string): CoordinatorScope[] {\n\tconst envelope = requireEnvelope(raw, \"version\");\n\tconst scopes = (envelope.items as unknown[]).map((item) => requireScope(item, groupId));\n\tif (new Set(scopes.map((scope) => scope.scope_id)).size !== scopes.length)\n\t\tthrow new Error(\"Duplicate scope in catalog.\");\n\treturn scopes;\n}\n\nfunction copyFields<T extends object>(value: T, fields: readonly (keyof T)[]): T {\n\treturn Object.fromEntries(fields.map((field) => [field, value[field]])) as T;\n}\n\nfunction requireMember(\n\traw: unknown,\n\tscope: CoordinatorScope,\n): ScopeMembershipSnapshot[\"items\"][number] {\n\tif (!raw || typeof raw !== \"object\" || Array.isArray(raw))\n\t\tthrow new Error(\"Invalid current scope member.\");\n\tconst member = raw as ScopeMembershipSnapshot[\"items\"][number];\n\trequireScopeAuthorizationRecord(member.membership, MEMBERSHIP_FIELDS);\n\trequireScopeAuthorizationRecord(member.enrollment, ENROLLMENT_FIELDS);\n\tconst { membership, enrollment } = member;\n\t// Legacy fingerprints are stored tuple evidence; canonical identity comes from the key blob.\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(enrollment.public_key);\n\tif (\n\t\t!isCurrentScopeMember(scope, membership) ||\n\t\tenrollment.enabled !== 1 ||\n\t\tenrollment.group_id !== scope.group_id ||\n\t\tenrollment.device_id !== membership.device_id ||\n\t\tparsed.kind !== \"ed25519\" ||\n\t\tcreateHash(\"sha256\").update(parsed.blob).digest(\"hex\") !== member.key_id\n\t)\n\t\tthrow new Error(\"Current scope member evidence mismatch.\");\n\treturn {\n\t\tmembership: copyFields(membership, MEMBERSHIP_FIELDS),\n\t\tenrollment: copyFields(enrollment, ENROLLMENT_FIELDS),\n\t\tkey_id: member.key_id,\n\t};\n}\n\nexport function normalizeScopeSnapshot(\n\traw: unknown,\n\tcatalogScope: CoordinatorScope,\n\tgroupId: string,\n\tcoordinatorId: string,\n): {\n\tscope: CoordinatorScope;\n\tmemberships: CoordinatorScopeMembership[];\n\tsourceCoordinatorId: string | null;\n\tevidence: ScopeMembershipSnapshot;\n} {\n\tconst envelope = requireEnvelope(raw, \"authorization_version\");\n\tconst source = requireScope(envelope.scope, groupId);\n\tif (\n\t\tsource.scope_id !== catalogScope.scope_id ||\n\t\tsource.membership_epoch < catalogScope.membership_epoch ||\n\t\tsource.coordinator_id !== catalogScope.coordinator_id\n\t)\n\t\tthrow new Error(\"Current scope snapshot source mismatch.\");\n\tconst members = (envelope.items as unknown[]).map((item) => requireMember(item, source));\n\tif (new Set(members.map((member) => member.membership.device_id)).size !== members.length)\n\t\tthrow new Error(\"Duplicate device in current scope snapshot.\");\n\t// The configured cache authority can be a URL, not the server's coordinator ID.\n\tconst capturedScope = copyFields(source, SCOPE_FIELDS);\n\tconst scope = { ...capturedScope, coordinator_id: coordinatorId };\n\tconst memberships = members.map((member) => ({\n\t\t...member.membership,\n\t\tcoordinator_id: coordinatorId,\n\t\tgroup_id: groupId,\n\t}));\n\treturn {\n\t\tscope,\n\t\tmemberships,\n\t\tsourceCoordinatorId: source.coordinator_id,\n\t\tevidence: { authorization_version: 1, scope: capturedScope, items: members },\n\t};\n}\n","import { createHash } from \"node:crypto\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport type { CoordinatorScope, CoordinatorScopeMembership } from \"./coordinator-store-contract.js\";\nimport type { Database } from \"./db.js\";\nimport {\n\tnormalizeScopeSnapshot,\n\ttype ScopeMembershipSnapshot,\n} from \"./scope-membership-snapshot.js\";\n\ntype Batch = ReturnType<typeof normalizeScopeSnapshot>;\ntype Authority = { coordinatorId: string; groupId: string };\ntype EvidenceRow = { scope_id: string; device_id: string; evidence_json: string };\n\n// Deliberately excludes presentation labels and timestamps, not authority facts.\nconst SCOPE_AUTHORITY_FIELDS = [\n\t\"scope_id\",\n\t\"kind\",\n\t\"authority_type\",\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"membership_epoch\",\n\t\"manifest_hash\",\n\t\"status\",\n] as const;\nconst MEMBER_AUTHORITY_FIELDS = [\n\t\"scope_id\",\n\t\"device_id\",\n\t\"role\",\n\t\"status\",\n\t\"membership_epoch\",\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"manifest_hash\",\n\t\"signed_manifest_json\",\n] as const;\n\nexport function scopeEvidenceTableExists(db: Database): boolean {\n\treturn !!db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(\"scope_membership_authorization_evidence\");\n}\n\nfunction ensureEvidenceTable(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS scope_membership_authorization_evidence (\n\t\tcoordinator_id TEXT NOT NULL, group_id TEXT NOT NULL,\n\t\tscope_id TEXT NOT NULL, device_id TEXT NOT NULL, evidence_json TEXT NOT NULL,\n\t\tPRIMARY KEY (coordinator_id, group_id, scope_id, device_id)\n\t)`);\n}\n\nfunction sameFields<T>(left: T, right: T, fields: readonly (keyof T)[]): boolean {\n\treturn fields.every((field) => left[field] === right[field]);\n}\n\nfunction matchesRows(\n\tbatch: Batch,\n\tscope: CoordinatorScope,\n\tmember: CoordinatorScopeMembership,\n): boolean {\n\tconst captured = batch.memberships[0];\n\tif (!captured) return false;\n\treturn (\n\t\tsameFields(batch.scope, scope, SCOPE_AUTHORITY_FIELDS) &&\n\t\tbatch.memberships.length === 1 &&\n\t\tsameFields(captured, member, MEMBER_AUTHORITY_FIELDS)\n\t);\n}\n\nfunction parseEvidence(raw: string, authority: Authority): Batch | null {\n\ttry {\n\t\tconst snapshot = JSON.parse(raw) as ScopeMembershipSnapshot;\n\t\tconst batch = normalizeScopeSnapshot(\n\t\t\tsnapshot,\n\t\t\tsnapshot.scope,\n\t\t\tauthority.groupId,\n\t\t\tauthority.coordinatorId,\n\t\t);\n\t\treturn batch.evidence.items.length === 1 ? batch : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction singleMemberEvidence(batch: Batch, index: number): ScopeMembershipSnapshot {\n\tconst item = batch.evidence.items[index];\n\tif (!item) throw new Error(\"Scope authorization evidence unavailable.\");\n\treturn { ...batch.evidence, items: [item] };\n}\n\n/** Called only inside the whole-group cache transaction; never backfills historical rows. */\nexport function reconcileScopeAuthorizationEvidence(\n\tdb: Database,\n\tbatches: Batch[],\n\tauthority: Authority,\n\toptions: { removalOnly: boolean },\n): void {\n\tif (options.removalOnly) {\n\t\tpruneEvidence(db, batches, authority);\n\t\treturn;\n\t}\n\tensureEvidenceTable(db);\n\tdb.prepare(\n\t\t\"DELETE FROM scope_membership_authorization_evidence WHERE coordinator_id = ? AND group_id = ?\",\n\t).run(authority.coordinatorId, authority.groupId);\n\tconst insert = db.prepare(`INSERT INTO scope_membership_authorization_evidence\n\t\t(coordinator_id, group_id, scope_id, device_id, evidence_json) VALUES (?, ?, ?, ?, ?)`);\n\tfor (const batch of batches) {\n\t\tfor (const [index, member] of batch.memberships.entries()) {\n\t\t\tinsert.run(\n\t\t\t\tauthority.coordinatorId,\n\t\t\t\tauthority.groupId,\n\t\t\t\tbatch.scope.scope_id,\n\t\t\t\tmember.device_id,\n\t\t\t\tJSON.stringify(singleMemberEvidence(batch, index)),\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction sameProof(previous: Batch, current: Batch): boolean {\n\tconst oldItem = previous.evidence.items[0];\n\tconst item = current.evidence.items[0];\n\tconst member = current.memberships[0];\n\tif (!oldItem || !item || !member) return false;\n\treturn (\n\t\tmatchesRows(previous, current.scope, member) &&\n\t\tprevious.sourceCoordinatorId === current.sourceCoordinatorId &&\n\t\toldItem.key_id === item.key_id &&\n\t\tsameFields(oldItem.membership, item.membership, MEMBER_AUTHORITY_FIELDS) &&\n\t\tsameFields(oldItem.enrollment, item.enrollment, [\n\t\t\t\"group_id\",\n\t\t\t\"device_id\",\n\t\t\t\"fingerprint\",\n\t\t\t\"enabled\",\n\t\t])\n\t);\n}\n\nfunction pruneEvidence(db: Database, batches: Batch[], authority: Authority): void {\n\tif (!scopeEvidenceTableExists(db)) return;\n\tconst rows = db\n\t\t.prepare(`SELECT scope_id, device_id, evidence_json\n\t\tFROM scope_membership_authorization_evidence WHERE coordinator_id = ? AND group_id = ?`)\n\t\t.all(authority.coordinatorId, authority.groupId) as EvidenceRow[];\n\tconst remove = db.prepare(`DELETE FROM scope_membership_authorization_evidence\n\t\tWHERE coordinator_id = ? AND group_id = ? AND scope_id = ? AND device_id = ?`);\n\tfor (const row of rows) {\n\t\tconst batch = batches.find((item) => item.scope.scope_id === row.scope_id);\n\t\tconst index =\n\t\t\tbatch?.memberships.findIndex((member) => member.device_id === row.device_id) ?? -1;\n\t\tconst old = parseEvidence(row.evidence_json, authority);\n\t\tconst current =\n\t\t\tbatch && index >= 0\n\t\t\t\t? normalizeScopeSnapshot(\n\t\t\t\t\t\tsingleMemberEvidence(batch, index),\n\t\t\t\t\t\tbatch.evidence.scope,\n\t\t\t\t\t\tauthority.groupId,\n\t\t\t\t\t\tauthority.coordinatorId,\n\t\t\t\t\t)\n\t\t\t\t: null;\n\t\tif (!old || !current || !sameProof(old, current))\n\t\t\tremove.run(authority.coordinatorId, authority.groupId, row.scope_id, row.device_id);\n\t}\n}\n\n/** Evidence is not a lease: freshness policy remains with the caller. Malformed storage denies. */\nexport function getRetainedScopeAuthorizationKey(\n\tdb: Database,\n\tscope: CoordinatorScope,\n\tmember: CoordinatorScopeMembership,\n\texpectedPublicKey?: string,\n): string | null {\n\ttry {\n\t\tif (!scope.coordinator_id || !scope.group_id || !scopeEvidenceTableExists(db)) return null;\n\t\tconst authority = { coordinatorId: scope.coordinator_id, groupId: scope.group_id };\n\t\tconst row = db\n\t\t\t.prepare(`SELECT evidence_json FROM scope_membership_authorization_evidence\n\t\t\tWHERE coordinator_id = ? AND group_id = ? AND scope_id = ? AND device_id = ?`)\n\t\t\t.get(authority.coordinatorId, authority.groupId, scope.scope_id, member.device_id) as\n\t\t\t| EvidenceRow\n\t\t\t| undefined;\n\t\tconst proof = row && parseEvidence(row.evidence_json, authority);\n\t\tif (!proof || !matchesRows(proof, scope, member)) return null;\n\t\tconst keyId = proof.evidence.items[0]?.key_id;\n\t\tif (!keyId) return null;\n\t\tif (expectedPublicKey !== undefined) {\n\t\t\tconst parsed = parseSshEd25519PublicKeyForRevocation(expectedPublicKey);\n\t\t\tif (\n\t\t\t\tparsed.kind !== \"ed25519\" ||\n\t\t\t\tcreateHash(\"sha256\").update(parsed.blob).digest(\"hex\") !== keyId\n\t\t\t)\n\t\t\t\treturn null;\n\t\t}\n\t\treturn keyId;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","/**\n * Sync authentication: request signing, verification, and nonce management.\n *\n * Uses Node's native Ed25519 crypto for sign/verify and SHA-256 canonical\n * request hashing. No ssh-keygen shelling.\n */\n\nimport {\n\tcreateHash,\n\tcreatePrivateKey,\n\tcreatePublicKey,\n\trandomBytes,\n\tsign,\n\tverify,\n} from \"node:crypto\";\nimport { lt } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { loadPrivateKey } from \"./sync-identity.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Signature version. v1 = SSHSIG format (ssh-keygen era), v2 = raw Ed25519.\n *\n * v2 is a breaking change: Python peers using `ssh-keygen -Y verify` cannot\n * verify v2 signatures. Once all peers run the TS runtime, v1 support can\n * be removed. During migration, the verifier accepts both versions.\n */\nexport const SIGNATURE_VERSION = \"v2\";\n\n/** Direct-peer-only recipient-bound signature version. */\nexport const DIRECT_PEER_SIGNATURE_VERSION = \"v3\";\n\nfunction isValidRecipientId(recipientId: string): boolean {\n\treturn (\n\t\tBoolean(recipientId.trim()) && recipientId === recipientId.trim() && !/[\\r\\n]/.test(recipientId)\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Canonical request\n// ---------------------------------------------------------------------------\n\n/**\n * Build a canonical request buffer for signing/verification.\n *\n * SHA-256 hashes the body, then joins method/path/timestamp/nonce/bodyHash\n * with newlines and returns the UTF-8 encoded result.\n */\nexport function buildCanonicalRequest(\n\tmethod: string,\n\tpathWithQuery: string,\n\ttimestamp: string,\n\tnonce: string,\n\tbodyBytes: Buffer,\n): Buffer {\n\tconst bodyHash = createHash(\"sha256\").update(bodyBytes).digest(\"hex\");\n\tconst canonical = [method.toUpperCase(), pathWithQuery, timestamp, nonce, bodyHash].join(\"\\n\");\n\treturn Buffer.from(canonical, \"utf-8\");\n}\n\n/**\n * Build the direct-peer v3 canonical request without changing the v2 bytes.\n * The recipient is the sixth field so the signature cannot be replayed to a\n * different peer.\n */\nexport function buildDirectPeerCanonicalRequest(\n\tmethod: string,\n\tpathWithQuery: string,\n\ttimestamp: string,\n\tnonce: string,\n\tbodyBytes: Buffer,\n\trecipientId: string,\n): Buffer {\n\tif (!isValidRecipientId(recipientId)) {\n\t\tthrow new Error(\"recipientId must be a non-empty single-line value\");\n\t}\n\treturn Buffer.concat([\n\t\tbuildCanonicalRequest(method, pathWithQuery, timestamp, nonce, bodyBytes),\n\t\tBuffer.from(`\\n${recipientId}`, \"utf-8\"),\n\t]);\n}\n\n// ---------------------------------------------------------------------------\n// Sign\n// ---------------------------------------------------------------------------\n\nexport interface SignRequestOptions {\n\tmethod: string;\n\turl: string;\n\tbodyBytes: Buffer;\n\tkeysDir?: string;\n\tdeviceId?: string;\n\tdbPath?: string;\n\ttimestamp?: string;\n\tnonce?: string;\n}\n\nexport interface SignedRequestHeaders {\n\t\"X-Opencode-Timestamp\": string;\n\t\"X-Opencode-Nonce\": string;\n\t\"X-Opencode-Signature\": string;\n}\n\ninterface SigningKeyOptions {\n\tkeysDir?: string;\n\tdeviceId?: string;\n\tdbPath?: string;\n}\n\nfunction requestPath(url: string): string {\n\tconst parsed = new URL(url);\n\treturn `${parsed.pathname || \"/\"}${parsed.search}`;\n}\n\nfunction signCanonicalRequest(canonical: Buffer, options: SigningKeyOptions): string {\n\tconst keyData = loadPrivateKey(options.keysDir, options.dbPath, options.deviceId);\n\tif (!keyData) throw new Error(\"private key missing\");\n\n\tlet privateKeyObj: ReturnType<typeof createPrivateKey>;\n\ttry {\n\t\tprivateKeyObj = createPrivateKey(keyData);\n\t} catch {\n\t\tprivateKeyObj = createPrivateKey({ key: keyData, format: \"pem\", type: \"pkcs8\" });\n\t}\n\treturn sign(null, canonical, privateKeyObj).toString(\"base64\");\n}\n\n/**\n * Sign an HTTP request and return the auth headers.\n *\n * Uses Node's native Ed25519 crypto.sign() — no ssh-keygen shelling.\n * Returns X-Opencode-Timestamp, X-Opencode-Nonce, X-Opencode-Signature headers.\n */\nexport function signRequest(options: SignRequestOptions): SignedRequestHeaders {\n\tconst ts = options.timestamp ?? String(Math.floor(Date.now() / 1000));\n\tconst nonceValue = options.nonce ?? randomBytes(16).toString(\"hex\");\n\n\tconst path = requestPath(options.url);\n\tconst canonical = buildCanonicalRequest(options.method, path, ts, nonceValue, options.bodyBytes);\n\tconst signature = signCanonicalRequest(canonical, options);\n\n\treturn {\n\t\t\"X-Opencode-Timestamp\": ts,\n\t\t\"X-Opencode-Nonce\": nonceValue,\n\t\t\"X-Opencode-Signature\": `${SIGNATURE_VERSION}:${signature}`,\n\t};\n}\n\nexport interface SignDirectPeerRequestOptions\n\textends Omit<SignRequestOptions, \"timestamp\" | \"nonce\"> {\n\trecipientId: string;\n\ttimestamp: string;\n\tnonce: string;\n}\n\nexport interface DirectPeerSignatureHeaders {\n\t\"X-Codemem-Recipient\": string;\n\t\"X-Codemem-Signature\": string;\n}\n\n/** Sign the isolated recipient-bound v3 material for a direct-peer request. */\nexport function signDirectPeerRequest(\n\toptions: SignDirectPeerRequestOptions,\n): DirectPeerSignatureHeaders {\n\tconst path = requestPath(options.url);\n\tconst canonical = buildDirectPeerCanonicalRequest(\n\t\toptions.method,\n\t\tpath,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t\toptions.recipientId,\n\t);\n\tconst signature = signCanonicalRequest(canonical, options);\n\n\treturn {\n\t\t\"X-Codemem-Recipient\": options.recipientId,\n\t\t\"X-Codemem-Signature\": `${DIRECT_PEER_SIGNATURE_VERSION}:${signature}`,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Verify\n// ---------------------------------------------------------------------------\n\nexport interface VerifySignatureOptions {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Buffer;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n\ttimeWindowS?: number;\n}\n\nfunction isFreshTimestamp(timestamp: string, timeWindowS: number): boolean {\n\tif (!/^\\d+$/.test(timestamp)) return false;\n\tconst seconds = Number.parseInt(timestamp, 10);\n\treturn Math.abs(Math.floor(Date.now() / 1000) - seconds) <= timeWindowS;\n}\n\nfunction decodeStrictBase64(encoded: string): Buffer | undefined {\n\tif (!encoded) return undefined;\n\tconst decoded = Buffer.from(encoded, \"base64\");\n\treturn decoded.toString(\"base64\") === encoded ? decoded : undefined;\n}\n\n/**\n * Verify a signed request.\n *\n * Checks timestamp freshness, signature version prefix, then uses\n * Node's native crypto.verify() with the sender's Ed25519 public key.\n */\nexport function verifySignature(options: VerifySignatureOptions): boolean {\n\tconst timeWindow = options.timeWindowS ?? DEFAULT_TIME_WINDOW_S;\n\n\tif (!isFreshTimestamp(options.timestamp, timeWindow)) return false;\n\n\t// Validate signature version prefix — accept both v1 and v2 during migration\n\tconst ACCEPTED_VERSIONS = [\"v1\", \"v2\"];\n\tconst colonIdx = options.signature.indexOf(\":\");\n\tif (colonIdx < 1) return false;\n\tconst sigVersion = options.signature.slice(0, colonIdx);\n\tif (!ACCEPTED_VERSIONS.includes(sigVersion)) return false;\n\n\tconst signatureBytes = decodeStrictBase64(options.signature.slice(colonIdx + 1));\n\tif (!signatureBytes) return false;\n\n\tconst canonical = buildCanonicalRequest(\n\t\toptions.method,\n\t\toptions.pathWithQuery,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t);\n\n\ttry {\n\t\tconst publicKeyObj = sshEd25519ToPublicKey(options.publicKey);\n\t\treturn verify(null, canonical, publicKeyObj, signatureBytes);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport interface VerifyDirectPeerSignatureOptions {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Buffer;\n\ttimestamp: string;\n\tnonce: string;\n\trecipientId?: string;\n\texpectedRecipientId: string;\n\tsignature?: string;\n\tpublicKey: string;\n\ttimeWindowS?: number;\n}\n\nexport type DirectPeerSignatureVerification =\n\t| { status: \"absent\" }\n\t| {\n\t\t\tstatus: \"invalid\";\n\t\t\treason:\n\t\t\t\t| \"incomplete_material\"\n\t\t\t\t| \"malformed_recipient\"\n\t\t\t\t| \"invalid_timestamp\"\n\t\t\t\t| \"unsupported_version\"\n\t\t\t\t| \"invalid_signature\"\n\t\t\t\t| \"recipient_mismatch\";\n\t }\n\t| { status: \"valid\"; version: \"v3\" };\n\n/**\n * Verify direct-peer v3 material with an explicit absent/invalid distinction.\n * Callers may permit legacy v2 only for `absent`; any `invalid` result must fail\n * closed rather than falling back to the accompanying v2 signature.\n */\nexport function verifyDirectPeerSignature(\n\toptions: VerifyDirectPeerSignatureOptions,\n): DirectPeerSignatureVerification {\n\tconst recipientId = options.recipientId === \"\" ? undefined : options.recipientId;\n\tconst signature = options.signature === \"\" ? undefined : options.signature;\n\tif (recipientId === undefined && signature === undefined) {\n\t\treturn { status: \"absent\" };\n\t}\n\tif (!recipientId || !signature) {\n\t\treturn { status: \"invalid\", reason: \"incomplete_material\" };\n\t}\n\tif (!isValidRecipientId(recipientId)) {\n\t\treturn { status: \"invalid\", reason: \"malformed_recipient\" };\n\t}\n\tconst timeWindow = options.timeWindowS ?? DEFAULT_TIME_WINDOW_S;\n\tif (!isFreshTimestamp(options.timestamp, timeWindow)) {\n\t\treturn { status: \"invalid\", reason: \"invalid_timestamp\" };\n\t}\n\n\tconst prefix = `${DIRECT_PEER_SIGNATURE_VERSION}:`;\n\tif (!signature.startsWith(prefix)) {\n\t\treturn { status: \"invalid\", reason: \"unsupported_version\" };\n\t}\n\tconst signatureBytes = decodeStrictBase64(signature.slice(prefix.length));\n\tif (!signatureBytes) {\n\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t}\n\n\tconst canonical = buildDirectPeerCanonicalRequest(\n\t\toptions.method,\n\t\toptions.pathWithQuery,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t\trecipientId,\n\t);\n\ttry {\n\t\tconst publicKeyObj = sshEd25519ToPublicKey(options.publicKey);\n\t\tif (!verify(null, canonical, publicKeyObj, signatureBytes)) {\n\t\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t\t}\n\t} catch {\n\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t}\n\tif (recipientId !== options.expectedRecipientId) {\n\t\treturn { status: \"invalid\", reason: \"recipient_mismatch\" };\n\t}\n\treturn {\n\t\tstatus: \"valid\",\n\t\tversion: DIRECT_PEER_SIGNATURE_VERSION,\n\t};\n}\n\n/**\n * Parse an SSH ed25519 public key string into a Node crypto KeyObject.\n *\n * SSH format: \"ssh-ed25519 <base64-wire-format>\"\n * Wire format: uint32 key-type-len + key-type + uint32 key-data-len + key-data\n */\nfunction sshEd25519ToPublicKey(sshPub: string): ReturnType<typeof createPublicKey> {\n\tconst parts = sshPub.trim().split(/\\s+/);\n\tconst [keyType, keyData] = parts;\n\tif (keyType !== \"ssh-ed25519\" || !keyData) {\n\t\tthrow new Error(\"not an ssh-ed25519 key\");\n\t}\n\tconst wireFormat = Buffer.from(keyData, \"base64\");\n\n\t// Read key type length\n\tif (wireFormat.length < 4) throw new Error(\"truncated wire format\");\n\tconst typeLen = wireFormat.readUInt32BE(0);\n\tconst typeEnd = 4 + typeLen;\n\tif (wireFormat.length < typeEnd + 4) throw new Error(\"truncated wire format\");\n\n\t// Read key data length\n\tconst keyLen = wireFormat.readUInt32BE(typeEnd);\n\tconst keyStart = typeEnd + 4;\n\tif (wireFormat.length < keyStart + keyLen) throw new Error(\"truncated wire format\");\n\tconst rawKey = wireFormat.subarray(keyStart, keyStart + keyLen);\n\n\tif (rawKey.length !== 32) throw new Error(`unexpected Ed25519 key length: ${rawKey.length}`);\n\n\t// Wrap raw 32-byte key in SPKI DER: 12-byte Ed25519 header + 32-byte key\n\tconst ed25519SpkiPrefix = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n\tconst spkiDer = Buffer.concat([ed25519SpkiPrefix, rawKey]);\n\n\treturn createPublicKey({ key: spkiDer, format: \"der\", type: \"spki\" });\n}\n\n// ---------------------------------------------------------------------------\n// Auth headers (convenience)\n// ---------------------------------------------------------------------------\n\nexport interface BuildAuthHeadersOptions {\n\tdeviceId: string;\n\tmethod: string;\n\turl: string;\n\tbodyBytes: Buffer;\n\tbootstrapGrantId?: string;\n\tkeysDir?: string;\n\tdbPath?: string;\n\ttimestamp?: string;\n\tnonce?: string;\n}\n\nexport type AuthHeaders = Record<string, string> &\n\tSignedRequestHeaders & {\n\t\t\"X-Opencode-Device\": string;\n\t};\n\n/**\n * Build full auth headers including device ID and request signature.\n */\nexport function buildAuthHeaders(options: BuildAuthHeadersOptions): AuthHeaders {\n\treturn {\n\t\t\"X-Opencode-Device\": options.deviceId,\n\t\t...(options.bootstrapGrantId ? { \"X-Codemem-Bootstrap-Grant\": options.bootstrapGrantId } : {}),\n\t\t...signRequest({\n\t\t\tmethod: options.method,\n\t\t\turl: options.url,\n\t\t\tbodyBytes: options.bodyBytes,\n\t\t\tkeysDir: options.keysDir,\n\t\t\tdeviceId: options.deviceId,\n\t\t\tdbPath: options.dbPath,\n\t\t\ttimestamp: options.timestamp,\n\t\t\tnonce: options.nonce,\n\t\t}),\n\t};\n}\n\nexport interface BuildDirectPeerAuthHeadersOptions extends BuildAuthHeadersOptions {\n\trecipientId: string;\n}\n\nexport type DirectPeerAuthHeaders = AuthHeaders & DirectPeerSignatureHeaders;\n\n/** Build dual v2 + recipient-bound v3 headers for direct-peer requests only. */\nexport function buildDirectPeerAuthHeaders(\n\toptions: BuildDirectPeerAuthHeadersOptions,\n): DirectPeerAuthHeaders {\n\tconst legacyHeaders = buildAuthHeaders(options);\n\tconst directHeaders = signDirectPeerRequest({\n\t\tmethod: options.method,\n\t\turl: options.url,\n\t\tbodyBytes: options.bodyBytes,\n\t\trecipientId: options.recipientId,\n\t\tkeysDir: options.keysDir,\n\t\tdeviceId: options.deviceId,\n\t\tdbPath: options.dbPath,\n\t\ttimestamp: legacyHeaders[\"X-Opencode-Timestamp\"],\n\t\tnonce: legacyHeaders[\"X-Opencode-Nonce\"],\n\t});\n\n\treturn {\n\t\t...legacyHeaders,\n\t\t...directHeaders,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Nonce management\n// ---------------------------------------------------------------------------\n\n/**\n * Record a nonce to prevent replay attacks.\n *\n * Returns true on success, false if the nonce was already recorded\n * (duplicate = potential replay).\n */\nexport function recordNonce(\n\tdb: Database,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): boolean {\n\tconst d = drizzle(db, { schema });\n\ttry {\n\t\td.insert(schema.syncNonces).values({ nonce, device_id: deviceId, created_at: createdAt }).run();\n\t\treturn true;\n\t} catch (err: unknown) {\n\t\tif (err instanceof Error && err.message.includes(\"UNIQUE constraint failed\")) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n/**\n * Remove nonces older than the given cutoff timestamp.\n */\nexport function cleanupNonces(db: Database, cutoff: string): void {\n\tconst d = drizzle(db, { schema });\n\td.delete(schema.syncNonces).where(lt(schema.syncNonces.created_at, cutoff)).run();\n}\n","/**\n * Sync HTTP client: JSON request helper using Node.js built-in fetch.\n *\n * Async counterpart to the synchronous Python http.client implementation.\n * Ported from codemem/sync/http_client.py.\n */\n\n// ---------------------------------------------------------------------------\n// URL helpers\n// ---------------------------------------------------------------------------\n\nfunction stripTrailingSlashes(value: string): string {\n\tlet end = value.length;\n\twhile (end > 0 && value.charCodeAt(end - 1) === 47) end--;\n\treturn end === value.length ? value : value.slice(0, end);\n}\n\nfunction hasUrlScheme(value: string): boolean {\n\tconst separator = value.indexOf(\"://\");\n\tif (separator <= 0) return false;\n\tconst first = value.charCodeAt(0);\n\tif (!((first >= 65 && first <= 90) || (first >= 97 && first <= 122))) return false;\n\tfor (let i = 1; i < separator; i++) {\n\t\tconst code = value.charCodeAt(i);\n\t\tconst isLetter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\t\tconst isDigit = code >= 48 && code <= 57;\n\t\tif (!isLetter && !isDigit && code !== 43 && code !== 45 && code !== 46) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Normalize a peer address into a base URL.\n *\n * Adds `http://` when no scheme is present, trims whitespace and trailing slashes.\n */\nexport function buildBaseUrl(address: string): string {\n\tconst trimmed = stripTrailingSlashes(address.trim());\n\tif (!trimmed) return \"\";\n\t// Check for an existing scheme (e.g. http://, https://)\n\tif (hasUrlScheme(trimmed)) return trimmed;\n\treturn `http://${trimmed}`;\n}\n\n// ---------------------------------------------------------------------------\n// JSON request\n// ---------------------------------------------------------------------------\n\nexport interface RequestJsonOptions {\n\theaders?: Record<string, string>;\n\tbody?: Record<string, unknown>;\n\tbodyBytes?: Uint8Array;\n\ttimeoutS?: number;\n\tmaxResponseBytes?: number;\n\tredirect?: \"error\";\n}\n\nfunction isolateDirectPeerConnection(headers: Record<string, string>): Record<string, string> {\n\tconst isDirectPeer = Object.keys(headers).some(\n\t\t(name) => name.toLowerCase() === \"x-codemem-recipient\",\n\t);\n\tif (!isDirectPeer) return headers;\n\n\t// Sync preparation can block expiry callbacks past a peer's idle deadline.\n\t// Close reads too, so a later write cannot reuse their expired connection.\n\treturn {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(headers).filter(([name]) => name.toLowerCase() !== \"connection\"),\n\t\t),\n\t\tConnection: \"close\",\n\t};\n}\n\nfunction requestRedirectPolicy(\n\theaders: Record<string, string>,\n\tredirect?: \"error\",\n): \"error\" | \"follow\" {\n\tconst carriesAdminCredential = Object.keys(headers).some(\n\t\t(name) => name.toLowerCase() === \"x-codemem-coordinator-admin\",\n\t);\n\tif (carriesAdminCredential) return \"error\";\n\treturn redirect ?? \"follow\";\n}\n\nfunction buildRequestHeaders(options: {\n\theaders?: Record<string, string>;\n\tbodyBytes?: Uint8Array;\n}): Record<string, string> {\n\tconst headers: Record<string, string> = { Accept: \"application/json\" };\n\tif (options.bodyBytes != null) {\n\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\theaders[\"Content-Length\"] = String(options.bodyBytes.byteLength);\n\t}\n\tif (options.headers) Object.assign(headers, options.headers);\n\treturn headers;\n}\n\n/**\n * Send an HTTP request and parse the JSON response.\n *\n * Returns `[statusCode, parsedBody]`. The body is null when the response\n * has no content. Non-JSON responses are returned as `{ error: \"non_json_response: ...\" }`.\n */\nexport async function requestJson(\n\tmethod: string,\n\turl: string,\n\toptions: RequestJsonOptions = {},\n): Promise<[status: number, body: Record<string, unknown> | null]> {\n\tconst { headers, body, timeoutS = 3 } = options;\n\tlet { bodyBytes } = options;\n\n\tif (bodyBytes == null && body != null) {\n\t\tbodyBytes = new TextEncoder().encode(JSON.stringify(body));\n\t}\n\n\tconst requestHeaders = buildRequestHeaders({ headers, bodyBytes });\n\tconst requestBody = (bodyBytes ?? null) as RequestInit[\"body\"] | null;\n\n\tconst response = await fetch(url, {\n\t\tmethod,\n\t\theaders: isolateDirectPeerConnection(requestHeaders),\n\t\tbody: requestBody,\n\t\tredirect: requestRedirectPolicy(requestHeaders, options.redirect),\n\t\tsignal: AbortSignal.timeout(Math.round(timeoutS * 1_000)),\n\t});\n\n\tlet raw: string;\n\tif (options.maxResponseBytes != null && response.body) {\n\t\tconst declaredLength = Number(response.headers.get(\"content-length\"));\n\t\tif (Number.isFinite(declaredLength) && declaredLength > options.maxResponseBytes) {\n\t\t\tawait response.body.cancel();\n\t\t\treturn [response.status, { error: \"response_too_large\" }];\n\t\t}\n\t\tconst reader = response.body.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\tlet totalBytes = 0;\n\t\traw = \"\";\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\ttotalBytes += value.byteLength;\n\t\t\t\tif (totalBytes > options.maxResponseBytes) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn [response.status, { error: \"response_too_large\" }];\n\t\t\t\t}\n\t\t\t\traw += decoder.decode(value, { stream: true });\n\t\t\t}\n\t\t\traw += decoder.decode();\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t} else {\n\t\traw = await response.text();\n\t}\n\tif (!raw) return [response.status, null];\n\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(raw);\n\t} catch {\n\t\tconst snippet = raw.slice(0, 240).trim();\n\t\treturn [\n\t\t\tresponse.status,\n\t\t\t{ error: snippet ? `non_json_response: ${snippet}` : \"non_json_response\" },\n\t\t];\n\t}\n\n\tif (typeof payload === \"object\" && payload !== null && !Array.isArray(payload)) {\n\t\treturn [response.status, payload as Record<string, unknown>];\n\t}\n\treturn [\n\t\tresponse.status,\n\t\t{ error: `unexpected_json_type: ${Array.isArray(payload) ? \"array\" : typeof payload}` },\n\t];\n}\n","import { BetterSqliteCoordinatorStore, DEFAULT_COORDINATOR_DB_PATH } from \"./coordinator-store.js\";\nimport type { CoordinatorScope, CoordinatorScopeMembership } from \"./coordinator-store-contract.js\";\nimport {\n\ttype CoordinatorSyncConfig,\n\tcoordinatorEnabled,\n\treadCoordinatorSyncConfig,\n} from \"./coordinator-sync-config.js\";\nimport type { Database } from \"./db.js\";\nimport { getAnyRecipientPolicyDenyOverlayForScopeDevice } from \"./recipient-policy-deny-overlay.js\";\nimport {\n\tgetRetainedScopeAuthorizationKey,\n\treconcileScopeAuthorizationEvidence,\n} from \"./scope-membership-evidence.js\";\nimport {\n\texplainScopeMembershipRevocation,\n\ttype ScopeMembershipEpochStatus,\n\ttype ScopeMembershipRevocationNotice,\n\tscopeMembershipEpochStatus,\n} from \"./scope-membership-semantics.js\";\nimport {\n\tnormalizeScopeCatalog,\n\tnormalizeScopeSnapshot,\n\ttype ScopeMembershipCatalog,\n\ttype ScopeMembershipSnapshot,\n} from \"./scope-membership-snapshot.js\";\nimport { buildAuthHeaders } from \"./sync-auth.js\";\nimport { buildBaseUrl, requestJson } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity } from \"./sync-identity.js\";\n\nexport const DEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS = 60_000;\n\nexport type ScopeMembershipCacheFreshness = \"fresh\" | \"stale\" | \"unknown\";\n\nexport type ScopeMembershipAuthorizationState =\n\t| \"authorized\"\n\t| \"not_authorized\"\n\t| \"revoked\"\n\t| \"stale_epoch\"\n\t| \"policy_denied\"\n\t| \"scope_unknown\"\n\t| \"scope_inactive\";\n\nexport interface ScopeMembershipCacheAuthority {\n\tcoordinatorId: string;\n\tgroupId: string;\n}\n\nexport interface ScopeMembershipCacheState extends ScopeMembershipCacheAuthority {\n\tlast_refresh_at: string;\n\tlast_success_at: string | null;\n\tlast_error: string | null;\n\tupdated_at: string;\n}\n\nexport interface CachedScopeMembership extends CoordinatorScopeMembership {\n\tscope: CoordinatorScope | null;\n}\n\nexport interface CachedDeviceScopeMemberships {\n\tdeviceId: string;\n\tfreshness: ScopeMembershipCacheFreshness;\n\tmemberships: CachedScopeMembership[];\n\tcacheStates: ScopeMembershipCacheState[];\n}\n\nexport interface CachedScopeAuthorization {\n\tdeviceId: string;\n\tscopeId: string;\n\tauthorized: boolean;\n\tstate: ScopeMembershipAuthorizationState;\n\tfreshness: ScopeMembershipCacheFreshness;\n\tepoch: ScopeMembershipEpochStatus;\n\trevocation: ScopeMembershipRevocationNotice | null;\n\tmembership: CoordinatorScopeMembership | null;\n\tscope: CoordinatorScope | null;\n\tcacheStates: ScopeMembershipCacheState[];\n}\n\nexport interface EffectiveCachedScopeAuthorization extends CachedScopeAuthorization {\n\tkeyId: string | null;\n}\n\nexport interface ScopeMembershipCacheFetchers {\n\tlistScopes(groupId: string): Promise<ScopeMembershipCatalog>;\n\tgetScopeSnapshot(groupId: string, scopeId: string): Promise<ScopeMembershipSnapshot>;\n}\n\nexport interface RefreshScopeMembershipCacheOptions {\n\tgroupIds: string[];\n\tcoordinatorId?: string | null;\n\tremoteUrl?: string | null;\n\tadminSecret?: string | null;\n\t/** @deprecated The refresh database is taken from refreshScopeMembershipCache(db, opts). */\n\tdb?: Database;\n\tkeysDir?: string | null;\n\tdbPath?: string;\n\t/** Separate local coordinator storage; dbPath remains the memory/signing database. */\n\tcoordinatorDbPath?: string;\n\tnow?: Date;\n\tfetchers?: ScopeMembershipCacheFetchers;\n}\n\nexport interface RefreshScopeMembershipCacheGroupResult {\n\tgroupId: string;\n\tstatus: \"refreshed\" | \"stale\";\n\tscopeCount: number;\n\tmembershipCount: number;\n\terror: string | null;\n}\n\nexport interface RefreshScopeMembershipCacheResult {\n\tstatus: \"refreshed\" | \"partial\" | \"stale\" | \"skipped\";\n\tcoordinatorId: string | null;\n\tgroups: RefreshScopeMembershipCacheGroupResult[];\n}\n\ninterface ScopeMembershipCacheLookupOptions {\n\tnow?: Date;\n\tmaxAgeMs?: number;\n\tauthority?: ScopeMembershipCacheAuthority | null;\n}\n\ninterface JoinedMembershipRow extends CoordinatorScopeMembership {\n\tscope_label: string | null;\n\tscope_kind: string | null;\n\tscope_authority_type: string | null;\n\tscope_coordinator_id: string | null;\n\tscope_group_id: string | null;\n\tscope_manifest_issuer_device_id: string | null;\n\tscope_membership_epoch: number | null;\n\tscope_manifest_hash: string | null;\n\tscope_status: string | null;\n\tscope_created_at: string | null;\n\tscope_updated_at: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction nowIso(now?: Date): string {\n\treturn (now ?? new Date()).toISOString();\n}\n\nfunction groupIds(input: string[]): string[] {\n\treturn [...new Set(input.map((item) => item.trim()).filter(Boolean))].toSorted();\n}\n\nfunction authorityId(remoteUrl: string | null | undefined): string {\n\tconst remote = clean(remoteUrl);\n\tif (!remote) return \"local\";\n\ttry {\n\t\treturn buildBaseUrl(remote);\n\t} catch {\n\t\treturn remote;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\tif (error instanceof Error) return error.message;\n\treturn String(error ?? \"unknown\");\n}\n\nexport function ensureScopeMembershipCacheStateTable(db: Database): void {\n\tif (hasRefreshRevision(db)) return;\n\t// Recheck under the write lock: another process may have upgraded the cache.\n\tdb.transaction(() => {\n\t\tif (hasRefreshRevision(db)) return;\n\t\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tlast_refresh_at TEXT NOT NULL,\n\t\t\tlast_success_at TEXT,\n\t\t\tlast_error TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t)\n\t`);\n\t\tif (!hasRefreshRevision(db))\n\t\t\tdb.exec(\n\t\t\t\t\"ALTER TABLE scope_membership_cache_state ADD COLUMN refresh_revision INTEGER NOT NULL DEFAULT 0\",\n\t\t\t);\n\t}).immediate();\n}\n\nfunction hasRefreshRevision(db: Database): boolean {\n\treturn !!db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info('scope_membership_cache_state') WHERE name = ?\")\n\t\t.get(\"refresh_revision\");\n}\n\n/** Local write ordering only; neither a membership epoch nor a permission lease. */\nfunction readRefreshRevision(db: Database, authority: ScopeMembershipCacheAuthority): number {\n\tconst row = db\n\t\t.prepare(`SELECT refresh_revision FROM scope_membership_cache_state\n\t\tWHERE coordinator_id = ? AND group_id = ?`)\n\t\t.get(authority.coordinatorId, authority.groupId) as { refresh_revision: number } | undefined;\n\tconst revision = row ? row.refresh_revision : 0;\n\tif (!Number.isSafeInteger(revision) || revision < 0 || revision >= Number.MAX_SAFE_INTEGER)\n\t\tthrow new Error(\"Scope membership cache revision unavailable.\");\n\treturn revision;\n}\n\nfunction coordinatorUrl(opts: RefreshScopeMembershipCacheOptions): string {\n\tconst remote = clean(opts.remoteUrl);\n\tif (!remote) throw new Error(\"Coordinator URL required.\");\n\treturn buildBaseUrl(remote);\n}\n\nfunction signedCoordinatorGet(\n\tdb: Database,\n\turl: string,\n\tkeysDir?: string | null,\n\tdbPath?: string,\n): Promise<Record<string, unknown> | null> {\n\tconst [deviceId] = ensureDeviceIdentity(db, { keysDir: keysDir ?? undefined });\n\tconst bodyBytes = Buffer.alloc(0);\n\tconst headers = buildAuthHeaders({\n\t\tdeviceId,\n\t\tmethod: \"GET\",\n\t\turl,\n\t\tbodyBytes,\n\t\tkeysDir: keysDir ?? undefined,\n\t\tdbPath,\n\t});\n\treturn requestJson(\"GET\", url, {\n\t\theaders,\n\t}).then(([status, payload]) => {\n\t\tif (status < 200 || status >= 300) {\n\t\t\tthrow new Error(`Coordinator membership snapshot failed (${status})`);\n\t\t}\n\t\treturn payload;\n\t});\n}\n\nfunction authenticatedFetchers(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): ScopeMembershipCacheFetchers {\n\tconst baseUrl = coordinatorUrl(opts);\n\treturn {\n\t\tlistScopes: async (groupId) => {\n\t\t\tconst url = `${baseUrl}/v1/scopes?group_id=${encodeURIComponent(groupId)}`;\n\t\t\treturn (await signedCoordinatorGet(\n\t\t\t\tdb,\n\t\t\t\turl,\n\t\t\t\topts.keysDir,\n\t\t\t\topts.dbPath,\n\t\t\t)) as unknown as ScopeMembershipCatalog;\n\t\t},\n\t\tgetScopeSnapshot: async (groupId, scopeId) => {\n\t\t\tconst url = `${baseUrl}/v1/scopes/${encodeURIComponent(scopeId)}/members?group_id=${encodeURIComponent(groupId)}`;\n\t\t\treturn (await signedCoordinatorGet(\n\t\t\t\tdb,\n\t\t\t\turl,\n\t\t\t\topts.keysDir,\n\t\t\t\topts.dbPath,\n\t\t\t)) as unknown as ScopeMembershipSnapshot;\n\t\t},\n\t};\n}\n\nfunction defaultFetchers(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): ScopeMembershipCacheFetchers {\n\tif (clean(opts.remoteUrl)) return authenticatedFetchers(db, opts);\n\treturn {\n\t\tlistScopes: (groupId) =>\n\t\t\twithLocalCoordinator(opts, async (store) => ({\n\t\t\t\tversion: 1,\n\t\t\t\titems: await store.listScopes({ groupId }),\n\t\t\t})),\n\t\tgetScopeSnapshot: (groupId, scopeId) =>\n\t\t\twithLocalCoordinator(opts, async (store) => {\n\t\t\t\tconst decision = await store.getScopeAuthorization({ groupId, scopeId });\n\t\t\t\tif (decision.kind !== \"authorized\") throw new Error(decision.error);\n\t\t\t\treturn {\n\t\t\t\t\tauthorization_version: decision.authorizationVersion,\n\t\t\t\t\tscope: decision.scope,\n\t\t\t\t\titems: decision.members.map(({ membership, enrollment, keyId }) => ({\n\t\t\t\t\t\tmembership,\n\t\t\t\t\t\tenrollment,\n\t\t\t\t\t\tkey_id: keyId,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}),\n\t};\n}\n\nasync function withLocalCoordinator<T>(\n\topts: RefreshScopeMembershipCacheOptions,\n\tread: (store: BetterSqliteCoordinatorStore) => Promise<T>,\n): Promise<T> {\n\tconst store = new BetterSqliteCoordinatorStore(\n\t\topts.coordinatorDbPath ?? DEFAULT_COORDINATOR_DB_PATH,\n\t);\n\ttry {\n\t\treturn await read(store);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nfunction upsertScope(db: Database, scope: CoordinatorScope): void {\n\tdb.prepare(\n\t\t`INSERT INTO replication_scopes(\n\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(scope_id) DO UPDATE SET\n\t\t\tlabel = excluded.label,\n\t\t\tkind = excluded.kind,\n\t\t\tauthority_type = excluded.authority_type,\n\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\tgroup_id = excluded.group_id,\n\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\tstatus = excluded.status,\n\t\t\tupdated_at = excluded.updated_at\n\t\tWHERE excluded.membership_epoch >= replication_scopes.membership_epoch`,\n\t).run(\n\t\tscope.scope_id,\n\t\tscope.label,\n\t\tscope.kind,\n\t\tscope.authority_type,\n\t\tscope.coordinator_id,\n\t\tscope.group_id,\n\t\tscope.manifest_issuer_device_id,\n\t\tscope.membership_epoch,\n\t\tscope.manifest_hash,\n\t\tscope.status,\n\t\tscope.created_at,\n\t\tscope.updated_at,\n\t);\n}\n\nfunction placeholders(count: number): string {\n\treturn Array.from({ length: count }, () => \"?\").join(\", \");\n}\n\nfunction reconcileScopeMembershipSnapshot(\n\tdb: Database,\n\tbatch: CurrentScopeBatch,\n\tauthority: ScopeMembershipCacheAuthority,\n\ttimestamp: string,\n): void {\n\tconst { scope, memberships, sourceCoordinatorId } = batch;\n\t// The authorized scope-members endpoint returns the complete membership list\n\t// that is active at the current epoch, so absence is fail-closed here.\n\tconst deviceIds = memberships.map((membership) => membership.device_id);\n\tconst deviceFilter =\n\t\tdeviceIds.length > 0 ? `AND device_id NOT IN (${placeholders(deviceIds.length)})` : \"\";\n\tdb.prepare(\n\t\t`UPDATE scope_memberships\n\t\t SET status = 'revoked',\n\t\t\t membership_epoch = CASE WHEN membership_epoch > ? THEN membership_epoch ELSE ? END,\n\t\t\t coordinator_id = ?,\n\t\t\t group_id = ?,\n\t\t\t updated_at = ?\n\t\t WHERE scope_id = ?\n\t\t\t AND COALESCE(coordinator_id, ?) IN (?, ?)\n\t\t\t AND COALESCE(group_id, ?) = ?\n\t\t\t AND status != 'revoked'\n\t\t\t ${deviceFilter}`,\n\t).run(\n\t\tscope.membership_epoch,\n\t\tscope.membership_epoch,\n\t\tauthority.coordinatorId,\n\t\tauthority.groupId,\n\t\ttimestamp,\n\t\tscope.scope_id,\n\t\tauthority.coordinatorId,\n\t\tauthority.coordinatorId,\n\t\tsourceCoordinatorId,\n\t\tauthority.groupId,\n\t\tauthority.groupId,\n\t\t...deviceIds,\n\t);\n}\n\nfunction reconcileGroupScopeSnapshot(\n\tdb: Database,\n\tauthority: ScopeMembershipCacheAuthority,\n\tscopes: CoordinatorScope[],\n\ttimestamp: string,\n): void {\n\tconst scopeIds = scopes.map((scope) => scope.scope_id);\n\tconst scopeFilter =\n\t\tscopeIds.length > 0 ? `AND scope_id NOT IN (${placeholders(scopeIds.length)})` : \"\";\n\tconst missing = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE coordinator_id = ?\n\t\t\t\t AND group_id = ?\n\t\t\t\t ${scopeFilter}`,\n\t\t)\n\t\t.all(authority.coordinatorId, authority.groupId, ...scopeIds) as Array<{ scope_id: string }>;\n\tif (missing.length === 0) return;\n\tconst missingScopeIds = missing.map((row) => row.scope_id);\n\tdb.prepare(\n\t\t`UPDATE replication_scopes\n\t\t SET status = 'archived', updated_at = ?\n\t\t WHERE coordinator_id = ?\n\t\t\t AND group_id = ?\n\t\t\t AND scope_id IN (${placeholders(missingScopeIds.length)})`,\n\t).run(timestamp, authority.coordinatorId, authority.groupId, ...missingScopeIds);\n\t// Enrolled-device scope listings are filtered by the requester's current access.\n\t// Archiving the omitted scope fails closed without poisoning unchanged peer rows\n\t// as revoked; a later visible snapshot can reconcile its full membership list.\n}\n\nexport function upsertCachedScopeMemberships(\n\tdb: Database,\n\tmemberships: CoordinatorScopeMembership[],\n): number {\n\tconst insert = db.prepare(\n\t\t`INSERT INTO scope_memberships(\n\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\trole = excluded.role,\n\t\t\tstatus = excluded.status,\n\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\tgroup_id = excluded.group_id,\n\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\tupdated_at = excluded.updated_at\n\t\tWHERE excluded.membership_epoch > scope_memberships.membership_epoch\n\t\t\tOR (\n\t\t\t\texcluded.membership_epoch = scope_memberships.membership_epoch\n\t\t\t\tAND scope_memberships.status != 'revoked'\n\t\t\t)`,\n\t);\n\tlet count = 0;\n\tdb.transaction(() => {\n\t\tfor (const membership of memberships) {\n\t\t\tinsert.run(\n\t\t\t\tmembership.scope_id,\n\t\t\t\tmembership.device_id,\n\t\t\t\tmembership.role,\n\t\t\t\tmembership.status,\n\t\t\t\tmembership.membership_epoch,\n\t\t\t\tmembership.coordinator_id,\n\t\t\t\tmembership.group_id,\n\t\t\t\tmembership.manifest_issuer_device_id,\n\t\t\t\tmembership.manifest_hash,\n\t\t\t\tmembership.signed_manifest_json,\n\t\t\t\tmembership.updated_at,\n\t\t\t);\n\t\t\tcount += 1;\n\t\t}\n\t})();\n\treturn count;\n}\n\nfunction recordRefreshState(\n\tdb: Database,\n\tinput: ScopeMembershipCacheAuthority & { ok: boolean; error?: string | null; now: string },\n): void {\n\tensureScopeMembershipCacheStateTable(db);\n\treadRefreshRevision(db, input);\n\tconst result = db\n\t\t.prepare(\n\t\t\t`INSERT INTO scope_membership_cache_state(\n\t\t\tcoordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at, refresh_revision\n\t\t) VALUES (?, ?, ?, ?, ?, ?, 1)\n\t\tON CONFLICT(coordinator_id, group_id) DO UPDATE SET\n\t\t\tlast_refresh_at = excluded.last_refresh_at,\n\t\t\tlast_success_at = COALESCE(excluded.last_success_at, scope_membership_cache_state.last_success_at),\n\t\t\tlast_error = excluded.last_error,\n\t\t\tupdated_at = excluded.updated_at,\n\t\t\trefresh_revision = scope_membership_cache_state.refresh_revision + 1\n\t\tWHERE scope_membership_cache_state.refresh_revision < 9007199254740991`,\n\t\t)\n\t\t.run(\n\t\t\tinput.coordinatorId,\n\t\t\tinput.groupId,\n\t\t\tinput.now,\n\t\t\tinput.ok ? input.now : null,\n\t\t\tinput.ok ? null : (input.error ?? \"unknown\"),\n\t\t\tinput.now,\n\t\t);\n\tif (result.changes !== 1) throw new Error(\"Scope membership cache revision unavailable.\");\n}\n\nfunction loadCacheStates(\n\tdb: Database,\n\tauthority?: ScopeMembershipCacheAuthority | null,\n): ScopeMembershipCacheState[] {\n\tif (\n\t\t!db\n\t\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t\t.get(\"scope_membership_cache_state\")\n\t)\n\t\treturn [];\n\tif (authority) {\n\t\treturn db\n\t\t\t.prepare(\n\t\t\t\t`SELECT coordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at\n\t\t\t\t FROM scope_membership_cache_state\n\t\t\t\t WHERE coordinator_id = ? AND group_id = ?`,\n\t\t\t)\n\t\t\t.all(authority.coordinatorId, authority.groupId) as ScopeMembershipCacheState[];\n\t}\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT coordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at\n\t\t\t FROM scope_membership_cache_state\n\t\t\t ORDER BY coordinator_id ASC, group_id ASC`,\n\t\t)\n\t\t.all() as ScopeMembershipCacheState[];\n}\n\nfunction recordRefreshFailure(\n\tdb: Database,\n\tinput: ScopeMembershipCacheAuthority & { error: string; now: string },\n\texpectedRevision: number | undefined,\n): string {\n\tif (expectedRevision === undefined) return \"Scope membership cache revision unavailable.\";\n\ttry {\n\t\tdb.transaction(() => {\n\t\t\t// A delayed failure must not overwrite a newer refresh or advance its revision.\n\t\t\tif (readRefreshRevision(db, input) !== expectedRevision) return;\n\t\t\trecordRefreshState(db, { ...input, ok: false });\n\t\t}).immediate();\n\t\treturn input.error;\n\t} catch {\n\t\treturn \"Scope membership cache refresh state unavailable.\";\n\t}\n}\n\nfunction freshness(\n\tstates: ScopeMembershipCacheState[],\n\toptions: { now?: Date; maxAgeMs?: number },\n): ScopeMembershipCacheFreshness {\n\tif (states.length === 0) return \"unknown\";\n\tif (states.some((state) => clean(state.last_error) != null)) return \"stale\";\n\tconst maxAgeMs = options.maxAgeMs ?? DEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS;\n\tconst nowMs = (options.now ?? new Date()).getTime();\n\treturn states.some((state) => {\n\t\tconst refreshedAt = Date.parse(state.last_success_at ?? \"\");\n\t\treturn !Number.isFinite(refreshedAt) || nowMs - refreshedAt > maxAgeMs;\n\t})\n\t\t? \"stale\"\n\t\t: \"fresh\";\n}\n\nfunction scopeFromJoinedRow(row: JoinedMembershipRow): CoordinatorScope | null {\n\tif (!row.scope_label || !row.scope_kind || !row.scope_authority_type) return null;\n\treturn {\n\t\tscope_id: row.scope_id,\n\t\tlabel: row.scope_label,\n\t\tkind: row.scope_kind,\n\t\tauthority_type: row.scope_authority_type,\n\t\tcoordinator_id: row.scope_coordinator_id,\n\t\tgroup_id: row.scope_group_id,\n\t\tmanifest_issuer_device_id: row.scope_manifest_issuer_device_id,\n\t\tmembership_epoch: row.scope_membership_epoch ?? row.membership_epoch,\n\t\tmanifest_hash: row.scope_manifest_hash,\n\t\tstatus: row.scope_status ?? \"active\",\n\t\tcreated_at: row.scope_created_at ?? row.updated_at,\n\t\tupdated_at: row.scope_updated_at ?? row.updated_at,\n\t};\n}\n\nfunction loadScope(\n\tdb: Database,\n\tscopeId: string,\n\tauthority?: ScopeMembershipCacheAuthority | null,\n): CoordinatorScope | null {\n\tconst authorityFilter = authority ? \" AND coordinator_id = ? AND group_id = ?\" : \"\";\n\tconst params = authority ? [scopeId, authority.coordinatorId, authority.groupId] : [scopeId];\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t FROM replication_scopes\n\t\t\t WHERE scope_id = ?${authorityFilter}\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(...params) as CoordinatorScope | undefined;\n\treturn row ?? null;\n}\n\nfunction membershipFromJoinedRow(row: JoinedMembershipRow): CoordinatorScopeMembership {\n\treturn {\n\t\tscope_id: row.scope_id,\n\t\tdevice_id: row.device_id,\n\t\trole: row.role,\n\t\tstatus: row.status,\n\t\tmembership_epoch: row.membership_epoch,\n\t\tcoordinator_id: row.coordinator_id,\n\t\tgroup_id: row.group_id,\n\t\tmanifest_issuer_device_id: row.manifest_issuer_device_id,\n\t\tmanifest_hash: row.manifest_hash,\n\t\tsigned_manifest_json: row.signed_manifest_json,\n\t\tupdated_at: row.updated_at,\n\t};\n}\n\nfunction joinedMembershipSelect(whereSql: string): string {\n\treturn `SELECT\n\t\tsm.scope_id,\n\t\tsm.device_id,\n\t\tsm.role,\n\t\tsm.status,\n\t\tsm.membership_epoch,\n\t\tsm.coordinator_id,\n\t\tsm.group_id,\n\t\tsm.manifest_issuer_device_id,\n\t\tsm.manifest_hash,\n\t\tsm.signed_manifest_json,\n\t\tsm.updated_at,\n\t\trs.label AS scope_label,\n\t\trs.kind AS scope_kind,\n\t\trs.authority_type AS scope_authority_type,\n\t\trs.coordinator_id AS scope_coordinator_id,\n\t\trs.group_id AS scope_group_id,\n\t\trs.manifest_issuer_device_id AS scope_manifest_issuer_device_id,\n\t\trs.membership_epoch AS scope_membership_epoch,\n\t\trs.manifest_hash AS scope_manifest_hash,\n\t\trs.status AS scope_status,\n\t\trs.created_at AS scope_created_at,\n\t\trs.updated_at AS scope_updated_at\n\tFROM scope_memberships sm\n\tLEFT JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t${whereSql}`;\n}\n\nfunction authorityFromMembership(\n\tmembership: CoordinatorScopeMembership | null,\n\tfallback?: ScopeMembershipCacheAuthority | null,\n): ScopeMembershipCacheAuthority | null {\n\tconst coordinatorId = clean(membership?.coordinator_id) ?? fallback?.coordinatorId;\n\tconst groupId = clean(membership?.group_id) ?? fallback?.groupId;\n\treturn coordinatorId && groupId ? { coordinatorId, groupId } : null;\n}\n\nfunction authorityFromScope(scope: CoordinatorScope | null): ScopeMembershipCacheAuthority | null {\n\tconst coordinatorId = clean(scope?.coordinator_id);\n\tconst groupId = clean(scope?.group_id);\n\treturn coordinatorId && groupId ? { coordinatorId, groupId } : null;\n}\n\nexport async function refreshScopeMembershipCache(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): Promise<RefreshScopeMembershipCacheResult> {\n\tconst groups = groupIds(opts.groupIds);\n\tif (groups.length === 0) return { status: \"skipped\", coordinatorId: null, groups: [] };\n\tconst coordinatorId = clean(opts.coordinatorId) ?? authorityId(opts.remoteUrl);\n\tconst authorityForGroup = (groupId: string): ScopeMembershipCacheAuthority => ({\n\t\tcoordinatorId,\n\t\tgroupId,\n\t});\n\tconst fetchers = opts.fetchers ?? defaultFetchers(db, opts);\n\tconst timestamp = nowIso(opts.now);\n\tconst results: RefreshScopeMembershipCacheGroupResult[] = [];\n\n\tfor (const groupId of groups) {\n\t\tlet expectedRevision: number | undefined;\n\t\ttry {\n\t\t\tconst authority = authorityForGroup(groupId);\n\t\t\tensureScopeMembershipCacheStateTable(db);\n\t\t\texpectedRevision = readRefreshRevision(db, authority);\n\t\t\tconst membershipBatches = await gatherCurrentSnapshots(fetchers, authority);\n\t\t\tconst scopes = membershipBatches.map((batch) => batch.scope);\n\t\t\tconst error = persistCurrentSnapshots(\n\t\t\t\tdb,\n\t\t\t\tmembershipBatches,\n\t\t\t\tauthority,\n\t\t\t\ttimestamp,\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\tconst membershipCount = membershipBatches.reduce(\n\t\t\t\t(count, batch) => count + batch.memberships.length,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\tgroupId,\n\t\t\t\tstatus: error ? \"stale\" : \"refreshed\",\n\t\t\t\tscopeCount: error ? 0 : scopes.length,\n\t\t\t\tmembershipCount: error ? 0 : membershipCount,\n\t\t\t\terror,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = recordRefreshFailure(\n\t\t\t\tdb,\n\t\t\t\t{ coordinatorId, groupId, error: errorMessage(error), now: timestamp },\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\tresults.push({ groupId, status: \"stale\", scopeCount: 0, membershipCount: 0, error: message });\n\t\t}\n\t}\n\n\tconst refreshed = results.filter((result) => result.status === \"refreshed\").length;\n\tlet status: RefreshScopeMembershipCacheResult[\"status\"] = \"partial\";\n\tif (refreshed === results.length) status = \"refreshed\";\n\telse if (refreshed === 0) status = \"stale\";\n\treturn { status, coordinatorId, groups: results };\n}\n\ntype CurrentScopeBatch = ReturnType<typeof normalizeScopeSnapshot>;\n\nasync function gatherCurrentSnapshots(\n\tfetchers: ScopeMembershipCacheFetchers,\n\tauthority: ScopeMembershipCacheAuthority,\n): Promise<CurrentScopeBatch[]> {\n\tconst catalog = normalizeScopeCatalog(\n\t\tawait fetchers.listScopes(authority.groupId),\n\t\tauthority.groupId,\n\t);\n\tconst batches: CurrentScopeBatch[] = [];\n\tfor (const scope of catalog) {\n\t\tconst snapshot = await fetchers.getScopeSnapshot(authority.groupId, scope.scope_id);\n\t\tbatches.push(\n\t\t\tnormalizeScopeSnapshot(snapshot, scope, authority.groupId, authority.coordinatorId),\n\t\t);\n\t}\n\treturn batches;\n}\n\nfunction matchesSnapshotSource(\n\trow: { coordinator_id: string | null; group_id: string | null },\n\tbatch: CurrentScopeBatch,\n): boolean {\n\treturn (\n\t\t(row.group_id === null || row.group_id === batch.scope.group_id) &&\n\t\t(row.coordinator_id === null ||\n\t\t\trow.coordinator_id === batch.scope.coordinator_id ||\n\t\t\trow.coordinator_id === batch.sourceCoordinatorId)\n\t);\n}\n\nfunction requireUnsupersededSnapshot(db: Database, batch: CurrentScopeBatch): boolean {\n\tconst { scope, memberships } = batch;\n\tconst stored = loadScope(db, scope.scope_id);\n\tif (\n\t\tstored &&\n\t\t(stored.membership_epoch > scope.membership_epoch || !matchesSnapshotSource(stored, batch))\n\t)\n\t\tthrow new Error(\"Current scope snapshot conflicts with cached authority or epoch.\");\n\tconst rows = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, status, membership_epoch, coordinator_id, group_id FROM scope_memberships WHERE scope_id = ?\",\n\t\t)\n\t\t.all(scope.scope_id) as CoordinatorScopeMembership[];\n\tconst incoming = new Map(memberships.map((member) => [member.device_id, member]));\n\tlet revivalConflict = false;\n\tfor (const row of rows) {\n\t\tconst member = incoming.get(row.device_id);\n\t\t// Current omissions remove access even when the member advanced beyond the scope epoch.\n\t\tif (\n\t\t\t(member && row.membership_epoch > member.membership_epoch) ||\n\t\t\t!matchesSnapshotSource(row, batch)\n\t\t)\n\t\t\tthrow new Error(\"Current scope snapshot superseded by cached membership.\");\n\t\tif (member && row.status === \"revoked\" && row.membership_epoch === member.membership_epoch)\n\t\t\trevivalConflict = true;\n\t}\n\treturn revivalConflict;\n}\n\nfunction migrateSnapshotMembershipAuthority(db: Database, batch: CurrentScopeBatch): void {\n\tdb.prepare(\n\t\t`UPDATE scope_memberships SET coordinator_id = ?, group_id = ?\n\t\t WHERE scope_id = ? AND COALESCE(group_id, ?) = ?\n\t\t AND COALESCE(coordinator_id, ?) IN (?, ?)`,\n\t).run(\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.scope_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.sourceCoordinatorId,\n\t);\n}\n\nfunction persistCurrentSnapshots(\n\tdb: Database,\n\tbatches: CurrentScopeBatch[],\n\tauthority: ScopeMembershipCacheAuthority,\n\ttimestamp: string,\n\texpectedRevision: number,\n): string | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (readRefreshRevision(db, authority) !== expectedRevision)\n\t\t\t\treturn \"Current scope snapshot superseded by a newer cache refresh.\";\n\t\t\t// Validate every batch before writes, even when an earlier batch cannot revive a row.\n\t\t\tconst conflicts = batches.map((batch) => requireUnsupersededSnapshot(db, batch));\n\t\t\tconst error = conflicts.some(Boolean)\n\t\t\t\t? \"Current scope snapshot cannot revive cached revoked membership at the same epoch.\"\n\t\t\t\t: null;\n\t\t\tfor (const batch of batches) {\n\t\t\t\tif (!error) {\n\t\t\t\t\tupsertScope(db, batch.scope);\n\t\t\t\t\tmigrateSnapshotMembershipAuthority(db, batch);\n\t\t\t\t\tupsertCachedScopeMemberships(db, batch.memberships);\n\t\t\t\t}\n\t\t\t\treconcileScopeMembershipSnapshot(db, batch, authority, timestamp);\n\t\t\t}\n\t\t\treconcileGroupScopeSnapshot(\n\t\t\t\tdb,\n\t\t\t\tauthority,\n\t\t\t\tbatches.map((batch) => batch.scope),\n\t\t\t\ttimestamp,\n\t\t\t);\n\t\t\ttry {\n\t\t\t\treconcileScopeAuthorizationEvidence(db, batches, authority, {\n\t\t\t\t\tremovalOnly: error !== null,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"Scope authorization evidence unavailable.\");\n\t\t\t}\n\t\t\trecordRefreshState(db, { ...authority, ok: error === null, error, now: timestamp });\n\t\t\treturn error;\n\t\t})\n\t\t.immediate();\n}\n\nexport async function refreshConfiguredScopeMembershipCache(\n\tdb: Database,\n\tconfig?: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string | null; dbPath?: string },\n): Promise<RefreshScopeMembershipCacheResult> {\n\tconst syncConfig = config ?? readCoordinatorSyncConfig();\n\tif (!coordinatorEnabled(syncConfig)) {\n\t\treturn { status: \"skipped\", coordinatorId: null, groups: [] };\n\t}\n\treturn refreshScopeMembershipCache(db, {\n\t\tgroupIds: syncConfig.syncCoordinatorGroups,\n\t\tcoordinatorId: authorityId(syncConfig.syncCoordinatorUrl),\n\t\tremoteUrl: syncConfig.syncCoordinatorUrl,\n\t\tadminSecret: syncConfig.syncCoordinatorAdminSecret,\n\t\tkeysDir: options?.keysDir ?? null,\n\t\tdbPath: options?.dbPath,\n\t});\n}\n\nexport function listCachedScopesForDevice(\n\tdb: Database,\n\tdeviceId: string,\n\topts: ScopeMembershipCacheLookupOptions = {},\n): CachedDeviceScopeMemberships {\n\tconst cleanDeviceId = clean(deviceId);\n\tif (!cleanDeviceId) throw new Error(\"device_id is required.\");\n\tconst params: string[] = [cleanDeviceId];\n\tconst authorityFilter = opts.authority\n\t\t? \" AND COALESCE(sm.coordinator_id, rs.coordinator_id) = ? AND COALESCE(sm.group_id, rs.group_id) = ?\"\n\t\t: \"\";\n\tif (opts.authority) params.push(opts.authority.coordinatorId, opts.authority.groupId);\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`${joinedMembershipSelect(\n\t\t\t\t`WHERE sm.device_id = ? AND sm.status = 'active' AND rs.scope_id IS NOT NULL AND rs.status = 'active' AND sm.membership_epoch >= rs.membership_epoch${authorityFilter}`,\n\t\t\t)} ORDER BY sm.scope_id ASC`,\n\t\t)\n\t\t.all(...params) as JoinedMembershipRow[];\n\tconst cacheStates = loadCacheStates(db, opts.authority ?? null);\n\tconst memberships = rows.filter(\n\t\t(row) =>\n\t\t\tgetAnyRecipientPolicyDenyOverlayForScopeDevice(db, {\n\t\t\t\tscopeId: row.scope_id,\n\t\t\t\tdeviceId: cleanDeviceId,\n\t\t\t}) == null,\n\t);\n\treturn {\n\t\tdeviceId: cleanDeviceId,\n\t\tfreshness: freshness(cacheStates, opts),\n\t\tmemberships: memberships.map((row) => ({\n\t\t\t...membershipFromJoinedRow(row),\n\t\t\tscope: scopeFromJoinedRow(row),\n\t\t})),\n\t\tcacheStates,\n\t};\n}\n\nexport function getCachedScopeAuthorization(\n\tdb: Database,\n\tinput: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions,\n): CachedScopeAuthorization {\n\tif (!clean(input.deviceId) || !clean(input.scopeId))\n\t\tthrow new Error(\"device_id and scope_id are required.\");\n\treturn readCachedScopeAuthorization(db, input);\n}\n\n/** Managed access needs a current-refresh proof, not merely historical cache rows.\n * This read neither creates evidence nor refreshes permissions or adds an expiry. */\nexport function getEffectiveCachedScopeAuthorization(\n\tdb: Database,\n\tinput: {\n\t\tdeviceId: string;\n\t\tscopeId: string;\n\t\texpectedPublicKey?: string;\n\t} & ScopeMembershipCacheLookupOptions,\n): EffectiveCachedScopeAuthorization {\n\tconst cached = readCachedScopeAuthorization(db, input);\n\tif (!cached.authorized || cached.scope?.authority_type !== \"coordinator\")\n\t\treturn { ...cached, keyId: null };\n\tconst keyId =\n\t\tcached.membership &&\n\t\tgetRetainedScopeAuthorizationKey(db, cached.scope, cached.membership, input.expectedPublicKey);\n\tif (!keyId) return { ...cached, authorized: false, state: \"not_authorized\", keyId: null };\n\treturn { ...cached, keyId };\n}\n\nfunction readCachedScopeAuthorization(\n\tdb: Database,\n\tinput: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions,\n): CachedScopeAuthorization {\n\tconst deviceId = clean(input.deviceId);\n\tconst scopeId = clean(input.scopeId);\n\tif (!deviceId || !scopeId) throw new Error(\"device_id and scope_id are required.\");\n\tconst { membership, scope } = readCachedScopeRows(db, { ...input, deviceId, scopeId });\n\tconst authority = authorityFromMembership(\n\t\tmembership,\n\t\tinput.authority ?? authorityFromScope(scope),\n\t);\n\tconst cacheStates = loadCacheStates(db, authority);\n\tconst epoch = scopeMembershipEpochStatus({\n\t\tmembershipEpoch: membership?.membership_epoch ?? null,\n\t\trequiredEpoch: scope?.membership_epoch ?? null,\n\t});\n\tconst state = cachedScopeDecisionState({\n\t\tmembership,\n\t\tscope,\n\t\tepoch,\n\t\tpolicyDenied: !!getAnyRecipientPolicyDenyOverlayForScopeDevice(db, { deviceId, scopeId }),\n\t});\n\tlet revocation: ScopeMembershipRevocationNotice | null = null;\n\tif (state === \"revoked\" && membership)\n\t\trevocation = explainScopeMembershipRevocation({\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tmembershipEpoch: membership.membership_epoch,\n\t\t});\n\treturn {\n\t\tdeviceId,\n\t\tscopeId,\n\t\tauthorized: state === \"authorized\",\n\t\tstate,\n\t\tfreshness: freshness(cacheStates, input),\n\t\tepoch,\n\t\trevocation,\n\t\tmembership,\n\t\tscope,\n\t\tcacheStates,\n\t};\n}\n\nfunction readCachedScopeRows(\n\tdb: Database,\n\tinput: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions,\n): { membership: CoordinatorScopeMembership | null; scope: CoordinatorScope | null } {\n\tconst authorityFilter = input.authority\n\t\t? \" AND COALESCE(sm.coordinator_id, rs.coordinator_id) = ? AND COALESCE(sm.group_id, rs.group_id) = ?\"\n\t\t: \"\";\n\tconst params = input.authority\n\t\t? [input.deviceId, input.scopeId, input.authority.coordinatorId, input.authority.groupId]\n\t\t: [input.deviceId, input.scopeId];\n\tconst row = db\n\t\t.prepare(\n\t\t\t`${joinedMembershipSelect(`WHERE sm.device_id = ? AND sm.scope_id = ?${authorityFilter} LIMIT 1`)}`,\n\t\t)\n\t\t.get(...params) as JoinedMembershipRow | undefined;\n\tconst membership = row ? membershipFromJoinedRow(row) : null;\n\tconst scope = row\n\t\t? scopeFromJoinedRow(row)\n\t\t: loadScope(db, input.scopeId, input.authority ?? null);\n\treturn { membership, scope };\n}\n\nfunction cachedScopeDecisionState(input: {\n\tmembership: CoordinatorScopeMembership | null;\n\tscope: CoordinatorScope | null;\n\tepoch: ScopeMembershipEpochStatus;\n\tpolicyDenied: boolean;\n}): ScopeMembershipAuthorizationState {\n\tconst { membership, scope, epoch, policyDenied } = input;\n\tif (policyDenied) return \"policy_denied\";\n\tif (!membership) return \"not_authorized\";\n\tif (membership.status === \"revoked\") return \"revoked\";\n\tif (scope?.status && scope.status !== \"active\") return \"scope_inactive\";\n\tif (!scope) return \"scope_unknown\";\n\tif (epoch.stale) return \"stale_epoch\";\n\treturn membership.status === \"active\" ? \"authorized\" : \"not_authorized\";\n}\n","const matchesDot = (character: string): boolean =>\n\t![\"\\n\", \"\\r\", \"\\u2028\", \"\\u2029\"].includes(character);\n\nfunction matchesSingle(token: string, character: string): boolean {\n\treturn token === \"?\" ? matchesDot(character) : token === character;\n}\n\nfunction advanceWildcardRow(previous: Uint8Array, token: string, characters: string[]): Uint8Array {\n\tconst next = new Uint8Array(characters.length + 1);\n\tif (token === \"*\") next[0] = previous[0] ?? 0;\n\tfor (let index = 1; index <= characters.length; index += 1) {\n\t\tconst character = characters[index - 1] ?? \"\";\n\t\tif (token === \"*\") {\n\t\t\tnext[index] = previous[index] || (next[index - 1] && matchesDot(character)) ? 1 : 0;\n\t\t} else if (matchesSingle(token, character)) {\n\t\t\tnext[index] = previous[index - 1] ?? 0;\n\t\t}\n\t}\n\treturn next;\n}\n\n/** Match the legacy wildcard language without exploring wildcard partitions.\n * Each pattern/input pair is visited once: O(pattern × input) time,\n * O(pattern + input) space for tokens and the current/previous rows.\n * Scope resolution historically used UTF-16 units; recipient projection used /u.\n */\nexport function matchesWildcard(\n\tidentity: string,\n\tpattern: string,\n\toptions: { unicode: boolean },\n): boolean {\n\tconst characters = options.unicode ? Array.from(identity) : identity.split(\"\");\n\tconst tokens = options.unicode ? Array.from(pattern) : pattern.split(\"\");\n\tlet previous: Uint8Array = new Uint8Array(characters.length + 1);\n\tprevious[0] = 1;\n\tfor (const token of tokens) {\n\t\tprevious = advanceWildcardRow(previous, token, characters);\n\t}\n\treturn previous[characters.length] === 1;\n}\n","import { resolve } from \"node:path\";\nimport type { Database } from \"better-sqlite3\";\nimport { cleanProjectIdentity } from \"./project-identity.js\";\nimport { getEffectiveCachedScopeAuthorization } from \"./scope-membership-cache.js\";\nimport { matchesWildcard } from \"./wildcard-match.js\";\nimport {\n\ttype CanonicalWorkspaceIdentity,\n\tcanonicalWorkspaceIdentity,\n\ttype WorkspaceIdentityInput,\n} from \"./workspace-identity.js\";\n\nexport {\n\ttype CanonicalWorkspaceIdentity,\n\tcanonicalWorkspaceIdentity,\n\ttype WorkspaceIdentityInput,\n\ttype WorkspaceIdentitySource,\n} from \"./workspace-identity.js\";\n\nexport const LOCAL_DEFAULT_SCOPE_ID = \"local-default\";\n\n/**\n * Scope id used by the conservative migration backfill for legacy shared\n * memories that cannot yet be assigned to a concrete team/org scope. Single\n * source of truth: filters.ts and scope-backfill.ts re-import this so the\n * read-visibility predicate and the backfill agree on one literal.\n */\nexport const LEGACY_SHARED_REVIEW_SCOPE_ID = \"legacy-shared-review\";\n\n/**\n * Upper bound on how many scope ids we will inline into the index-eligible\n * `scope_id IN (...)` fast path (one bound parameter each). Larger sets use\n * a single JSON array parameter instead of exceeding SQLite's variable limit.\n */\nexport const MAX_SCOPE_IN_PARAMS = 500;\n\nexport interface ScopeMapping {\n\tid?: number | null;\n\tworkspace_identity?: string | null;\n\tproject_pattern: string;\n\tscope_id: string;\n\tpriority?: number | null;\n\tupdated_at?: string | null;\n\tsource?: string | null;\n}\n\nexport type ScopeResolutionReason =\n\t| \"explicit_override\"\n\t| \"exact_mapping\"\n\t| \"pattern_mapping\"\n\t| \"local_default\";\n\nexport interface ScopeResolution {\n\tscopeId: string;\n\treason: ScopeResolutionReason;\n\tworkspaceIdentity: CanonicalWorkspaceIdentity;\n\tmapping: ScopeMapping | null;\n\tmatchedPattern: string | null;\n}\n\nexport interface ResolveProjectScopeInput extends WorkspaceIdentityInput {\n\tallowRepositoryCwdFallback?: boolean;\n\texplicitScopeId?: string | null;\n\tmappings?: ScopeMapping[];\n\tlocalDefaultScopeId?: string;\n}\n\ninterface MappingCandidate {\n\tmapping: ScopeMapping;\n\tspecificity: number;\n\tmatchedPattern: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction normalizeSlash(value: string): string {\n\tconst normalized = value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\");\n\treturn normalized || value.trim();\n}\n\nfunction normalizeCwd(cwd: string): string {\n\t// Callers should pass an already-realpathed session cwd when symlink\n\t// resolution matters; this pure helper only normalizes path syntax.\n\treturn normalizeSlash(resolve(cwd));\n}\n\nfunction normalizeMappingIdentity(value: string | null | undefined): string | null {\n\tconst cleaned = clean(value);\n\treturn cleaned ? normalizeSlash(cleaned) : null;\n}\n\nfunction isBasenameOnlyPattern(pattern: string): boolean {\n\treturn !/[\\\\/:]/.test(pattern);\n}\n\nfunction patternSpecificity(pattern: string): number {\n\treturn pattern.replace(/[*?]/g, \"\").length;\n}\n\nfunction matchesPattern(identity: string, pattern: string): boolean {\n\tconst normalizedPattern = normalizeSlash(pattern);\n\tif (!normalizedPattern || isBasenameOnlyPattern(normalizedPattern)) return false;\n\tif (!/[*?]/.test(normalizedPattern)) return identity === normalizedPattern;\n\treturn matchesWildcard(identity, normalizedPattern, { unicode: false });\n}\n\nfunction candidatePriority(candidate: MappingCandidate): number {\n\treturn candidate.mapping.priority ?? 0;\n}\n\nfunction candidateUpdatedAt(candidate: MappingCandidate): number {\n\tconst updatedAt = clean(candidate.mapping.updated_at);\n\tif (!updatedAt) return 0;\n\tconst time = Date.parse(updatedAt);\n\treturn Number.isFinite(time) ? time : 0;\n}\n\nfunction compareCandidates(a: MappingCandidate, b: MappingCandidate): number {\n\treturn (\n\t\tcandidatePriority(b) - candidatePriority(a) ||\n\t\tb.specificity - a.specificity ||\n\t\tcandidateUpdatedAt(b) - candidateUpdatedAt(a) ||\n\t\t(b.mapping.id ?? 0) - (a.mapping.id ?? 0) ||\n\t\ta.mapping.scope_id.localeCompare(b.mapping.scope_id)\n\t);\n}\n\nfunction bestCandidate(candidates: MappingCandidate[]): MappingCandidate | null {\n\treturn candidates.toSorted(compareCandidates)[0] ?? null;\n}\n\nfunction exactMappingIdentities(\n\tinput: ResolveProjectScopeInput,\n\tworkspaceIdentity: CanonicalWorkspaceIdentity,\n): string[] {\n\tconst identities = [workspaceIdentity.value];\n\tif (input.allowRepositoryCwdFallback === false) return identities;\n\tif (\n\t\tworkspaceIdentity.source !== \"git_repository\" &&\n\t\tworkspaceIdentity.source !== \"git_remote\" &&\n\t\tworkspaceIdentity.source !== \"git_remote_branch\"\n\t) {\n\t\treturn identities;\n\t}\n\tconst cwd = cleanProjectIdentity(input.cwd);\n\tif (cwd) identities.push(normalizeCwd(cwd));\n\treturn identities;\n}\n\nfunction patternMappingIdentities(\n\tinput: ResolveProjectScopeInput,\n\tworkspaceIdentity: CanonicalWorkspaceIdentity,\n): string[] {\n\tconst identities = [workspaceIdentity.value];\n\tif (input.allowRepositoryCwdFallback === false) return identities;\n\tif (\n\t\tworkspaceIdentity.source !== \"git_repository\" &&\n\t\tworkspaceIdentity.source !== \"git_remote\" &&\n\t\tworkspaceIdentity.source !== \"git_remote_branch\"\n\t) {\n\t\treturn identities;\n\t}\n\tconst cwd = cleanProjectIdentity(input.cwd);\n\tif (cwd) identities.push(normalizeCwd(cwd));\n\treturn identities;\n}\n\nfunction bestExactMapping(mappings: ScopeMapping[], identities: string[]): MappingCandidate | null {\n\tfor (const identity of identities) {\n\t\tconst candidate = bestCandidate(\n\t\t\tmappings\n\t\t\t\t.filter((mapping) => normalizeMappingIdentity(mapping.workspace_identity) === identity)\n\t\t\t\t.map((mapping) => ({ mapping, matchedPattern: null, specificity: identity.length })),\n\t\t);\n\t\tif (candidate) return candidate;\n\t}\n\treturn null;\n}\n\nfunction bestPatternMapping(\n\tmappings: ScopeMapping[],\n\tidentities: string[],\n): MappingCandidate | null {\n\treturn bestCandidate(\n\t\tidentities.flatMap((identity) =>\n\t\t\tmappings.flatMap((mapping): MappingCandidate[] => {\n\t\t\t\tif (clean(mapping.workspace_identity)) return [];\n\t\t\t\tconst projectPattern = clean(mapping.project_pattern);\n\t\t\t\tif (!projectPattern || !matchesPattern(identity, projectPattern)) return [];\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tmapping,\n\t\t\t\t\t\tmatchedPattern: normalizeSlash(projectPattern),\n\t\t\t\t\t\tspecificity: patternSpecificity(projectPattern),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}),\n\t\t),\n\t);\n}\n\nexport function scopeIdsMatchingProjectPatterns(\n\tmappings: ScopeMapping[],\n\tworkspaceIdentities: Iterable<string>,\n): Set<string> {\n\tconst identities = [...workspaceIdentities].map(normalizeSlash);\n\tconst scopeIds = new Set<string>();\n\tfor (const mapping of mappings) {\n\t\tif (clean(mapping.workspace_identity)) continue;\n\t\tconst projectPattern = clean(mapping.project_pattern);\n\t\tif (\n\t\t\t!projectPattern ||\n\t\t\t!identities.some((identity) => matchesPattern(identity, projectPattern))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tscopeIds.add(mapping.scope_id);\n\t}\n\treturn scopeIds;\n}\n\nexport function resolveProjectScope(input: ResolveProjectScopeInput): ScopeResolution {\n\tconst workspaceIdentity = canonicalWorkspaceIdentity(input);\n\tconst explicitScopeId = clean(input.explicitScopeId);\n\tif (explicitScopeId) {\n\t\treturn {\n\t\t\tscopeId: explicitScopeId,\n\t\t\treason: \"explicit_override\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\tif (workspaceIdentity.source === \"unmapped\") {\n\t\treturn {\n\t\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\t\treason: \"local_default\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst mappings = input.mappings ?? [];\n\tconst exactIdentities = exactMappingIdentities(input, workspaceIdentity);\n\tconst exact = bestExactMapping(mappings, exactIdentities);\n\tif (exact) {\n\t\treturn {\n\t\t\tscopeId: exact.mapping.scope_id,\n\t\t\treason: \"exact_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: exact.mapping,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst pattern = bestPatternMapping(mappings, patternMappingIdentities(input, workspaceIdentity));\n\tif (pattern) {\n\t\treturn {\n\t\t\tscopeId: pattern.mapping.scope_id,\n\t\t\treason: \"pattern_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: pattern.mapping,\n\t\t\tmatchedPattern: pattern.matchedPattern,\n\t\t};\n\t}\n\n\treturn {\n\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\treason: \"local_default\",\n\t\tworkspaceIdentity,\n\t\tmapping: null,\n\t\tmatchedPattern: null,\n\t};\n}\n\nexport interface ScopeVisibilityOptions {\n\t/** Public key of the runtime's actual signing key, not an enrolled DB row. */\n\texpectedPublicKey?: string;\n\t/** Read-only key loader, called once only when coordinator candidates exist. */\n\tloadExpectedPublicKey?: () => string | undefined;\n}\n\nfunction resolveVisibilityPublicKey(\n\tmemberScopes: Array<{ scope_id: string | null; authority_type: string }>,\n\toptions: ScopeVisibilityOptions,\n): string | undefined {\n\tif (options.expectedPublicKey != null) return options.expectedPublicKey;\n\tif (!memberScopes.some((row) => row.scope_id != null && row.authority_type === \"coordinator\"))\n\t\treturn undefined;\n\treturn options.loadExpectedPublicKey?.();\n}\n\n/**\n * Resolve readable scopes once per request. Coordinator membership SQL lists\n * candidates only; retained proof must match the supplied actual signing key.\n * Unknown scopes deny, while local/manual/invite scopes retain existing rules.\n * NULL scopes remain the filter's dedicated local-default branch.\n */\nexport function resolveVisibleScopeIds(\n\tdb: Database,\n\tdeviceId: string,\n\toptions: ScopeVisibilityOptions = {},\n): string[] {\n\tconst visible = new Set<string>([\"\", LOCAL_DEFAULT_SCOPE_ID, LEGACY_SHARED_REVIEW_SCOPE_ID]);\n\tconst localScopes = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'local'`,\n\t\t)\n\t\t.all() as Array<{ scope_id: string | null }>;\n\tfor (const row of localScopes) {\n\t\tif (row.scope_id != null) visible.add(row.scope_id);\n\t}\n\tconst memberScopes = db\n\t\t.prepare(\n\t\t\t`SELECT sm.scope_id AS scope_id, rs.authority_type\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch`,\n\t\t)\n\t\t.all(deviceId) as Array<{ scope_id: string | null; authority_type: string }>;\n\tconst expectedPublicKey = resolveVisibilityPublicKey(memberScopes, options);\n\tfor (const row of memberScopes) {\n\t\tif (row.scope_id == null) continue;\n\t\tif ([\"local\", \"manual\", \"invite\"].includes(row.authority_type)) {\n\t\t\tvisible.add(row.scope_id);\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.authority_type !== \"coordinator\") continue;\n\t\tif (!expectedPublicKey?.trim()) continue;\n\t\tconst authorization = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId,\n\t\t\tscopeId: row.scope_id,\n\t\t\texpectedPublicKey,\n\t\t});\n\t\tif (!authorization.authorized) continue;\n\t\tvisible.add(row.scope_id);\n\t}\n\treturn [...visible];\n}\n","/**\n * Filter builder for memory_items queries.\n *\n * Mirrors Python's _extend_memory_filter_clauses in codemem/store/search.py.\n * Builds WHERE clause fragments and parameter arrays from a MemoryFilters object.\n */\n\nimport type { Database } from \"./db.js\";\nimport { matchingLocalCreationClause } from \"./memory-creation-provenance.js\";\nimport { localCreationSourceIds } from \"./memory-local-capture.js\";\nimport { projectColumnClause } from \"./project.js\";\nimport {\n\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tMAX_SCOPE_IN_PARAMS,\n\tresolveVisibleScopeIds,\n} from \"./scope-resolution.js\";\nimport type { MemoryFilters } from \"./types.js\";\n\nexport interface OwnershipFilterContext {\n\tactorId: string;\n\tdeviceId: string;\n\tclaimedDeviceIds?: string[];\n\tlegacyActorIds?: string[];\n\t/**\n\t * Apply the local read boundary for replication scopes. This is opt-in so\n\t * low-level filter unit tests and non-memory callers can keep using the pure\n\t * filter builder, while store/search paths can make scope visibility a hard\n\t * invariant.\n\t */\n\tenforceScopeVisibility?: boolean;\n\t/**\n\t * Pre-resolved set of scope_ids this device may read (see\n\t * `resolveVisibleScopeIds` in scope-resolution.ts). When present, scope visibility is\n\t * enforced with an index-eligible `scope_id IN (...)` predicate instead of\n\t * the per-row EXISTS subqueries. Without this set, scopeVisibilityDb resolves\n\t * the same decisions. Without either, SQL can grant only unmanaged access.\n\t */\n\tvisibleScopeIds?: readonly string[];\n\tscopeVisibilityDb?: Database;\n\t/** Public key of the actual runtime signing key; managed reads deny without it. */\n\texpectedPublicKey?: string;\n\t/** Lazy read-only actual-key loader; used only for managed scope candidates. */\n\tloadExpectedPublicKey?: () => string | undefined;\n}\n\nexport interface FilterResult {\n\tclauses: string[];\n\tparams: unknown[];\n\tjoinSessions: boolean;\n}\n\n/**\n * Normalize a filter value that may be a single string or an array of strings\n * into a clean, non-empty array of trimmed strings.\n */\nexport function normalizeFilterStrings(value: string | string[] | undefined | null): string[] {\n\tif (value == null) return [];\n\tconst items = Array.isArray(value) ? value : [value];\n\tconst seen = new Set<string>();\n\tconst normalized: string[] = [];\n\tfor (const item of items) {\n\t\tconst candidate = String(item).trim();\n\t\tif (!candidate || seen.has(candidate)) continue;\n\t\tseen.add(candidate);\n\t\tnormalized.push(candidate);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeWorkspaceKinds(value: string | string[] | undefined | null): string[] {\n\treturn normalizeFilterStrings(value)\n\t\t.map((raw) => raw.toLowerCase())\n\t\t.filter(\n\t\t\t(raw, idx, arr) => (raw === \"personal\" || raw === \"shared\") && arr.indexOf(raw) === idx,\n\t\t);\n}\n\nexport function normalizeVisibilityValues(value: string | string[] | undefined | null): string[] {\n\treturn normalizeFilterStrings(value)\n\t\t.map((raw) => raw.toLowerCase())\n\t\t.filter((raw, idx, arr) => (raw === \"private\" || raw === \"shared\") && arr.indexOf(raw) === idx);\n}\n\nexport function normalizeTrustStates(value: string | string[] | undefined | null): string[] {\n\treturn normalizeFilterStrings(value)\n\t\t.map((raw) => raw.toLowerCase())\n\t\t.filter(\n\t\t\t(raw, idx, arr) =>\n\t\t\t\t(raw === \"trusted\" || raw === \"legacy_unknown\" || raw === \"unreviewed\") &&\n\t\t\t\tarr.indexOf(raw) === idx,\n\t\t);\n}\n\n/**\n * Add IN / NOT IN clauses for a multi-value filter column.\n * Mirrors Python's _add_multi_value_filter.\n */\nfunction addMultiValueFilter(\n\tclauses: string[],\n\tparams: unknown[],\n\tcolumn: string,\n\tincludeValues: string[],\n\texcludeValues: string[],\n): void {\n\tif (includeValues.length > 0) {\n\t\tconst placeholders = includeValues.map(() => \"?\").join(\", \");\n\t\tclauses.push(`${column} IN (${placeholders})`);\n\t\tparams.push(...includeValues);\n\t}\n\tif (excludeValues.length > 0) {\n\t\tconst placeholders = excludeValues.map(() => \"?\").join(\", \");\n\t\tclauses.push(`(${column} IS NULL OR ${column} NOT IN (${placeholders}))`);\n\t\tparams.push(...excludeValues);\n\t}\n}\n\nfunction cleanUniqueStrings(value: string[] | undefined): string[] {\n\treturn [...new Set((value ?? []).map((item) => item.trim()).filter(Boolean))];\n}\n\n// Mirror MemoryStore.buildOwnershipPredicate(): prefer the top-level column,\n// then fall back to the metadata_json copy, and finally normalize a missing\n// owner to '' (never NULL) so the `theirs` (NOT ...) comparison stays null-safe.\nfunction ownershipColumnSql(column: string, jsonPath: string): string {\n\treturn `COALESCE(\n\tNULLIF(TRIM(memory_items.${column}), ''),\n\tNULLIF(TRIM(CASE\n\t\tWHEN json_valid(COALESCE(memory_items.metadata_json, ''))\n\t\tTHEN COALESCE(json_extract(memory_items.metadata_json, '${jsonPath}'), '')\n\t\tELSE ''\n\tEND), ''),\n\t''\n)`;\n}\n\nconst OWNERSHIP_ACTOR_SQL = ownershipColumnSql(\"actor_id\", \"$.actor_id\");\nconst OWNERSHIP_ORIGIN_DEVICE_SQL = ownershipColumnSql(\"origin_device_id\", \"$.origin_device_id\");\n\nfunction ownershipPredicateSql(context: OwnershipFilterContext): {\n\tclause: string;\n\tparams: string[];\n} {\n\tconst alternatives: string[] = [];\n\tconst params: string[] = [];\n\t// Guard blank identity: an empty actorId/deviceId must NOT match every\n\t// ownerless row (mirrors the falsy checks in\n\t// MemoryStore.buildOwnershipPredicate()). Skip the equality alternative\n\t// when the value is empty rather than emitting `<expr> = ''`.\n\tconst actorId = context.actorId.trim();\n\tif (actorId) {\n\t\talternatives.push(`${OWNERSHIP_ACTOR_SQL} = ?`);\n\t\tparams.push(actorId);\n\t}\n\tconst deviceId = context.deviceId.trim();\n\tif (deviceId) {\n\t\talternatives.push(`${OWNERSHIP_ORIGIN_DEVICE_SQL} = ?`);\n\t\tparams.push(deviceId);\n\t}\n\tconst claimedDeviceIds = cleanUniqueStrings(context.claimedDeviceIds);\n\tif (claimedDeviceIds.length > 0) {\n\t\talternatives.push(\n\t\t\t`${OWNERSHIP_ORIGIN_DEVICE_SQL} IN (${claimedDeviceIds.map(() => \"?\").join(\", \")})`,\n\t\t);\n\t\tparams.push(...claimedDeviceIds);\n\t}\n\tconst legacyActorIds = cleanUniqueStrings(context.legacyActorIds);\n\tif (legacyActorIds.length > 0) {\n\t\talternatives.push(`${OWNERSHIP_ACTOR_SQL} IN (${legacyActorIds.map(() => \"?\").join(\", \")})`);\n\t\tparams.push(...legacyActorIds);\n\t}\n\t// No usable owner identity → nothing is \"mine\" (and `theirs` = everything).\n\tif (alternatives.length === 0) return { clause: \"(0 = 1)\", params };\n\treturn { clause: `(${alternatives.join(\" OR \")})`, params };\n}\n\nfunction localCreationSourcesForFilter(\n\tcontext: OwnershipFilterContext,\n\tvisibleScopeIds: readonly string[] | undefined,\n): string[] {\n\tconst db = context.scopeVisibilityDb;\n\tif (!db || !visibleScopeIds) return [];\n\tconst creationClause = matchingLocalCreationClause(db);\n\tif (!creationClause) return [];\n\tif (\n\t\t!db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_source_bindings'\",\n\t\t\t)\n\t\t\t.get()\n\t)\n\t\treturn [];\n\t// Open the signing key only when matching creation evidence needs history access.\n\tconst candidate = db\n\t\t.prepare(`SELECT 1 FROM memory_source_bindings msb\n\t\tJOIN memory_items ON memory_items.import_key = msb.entity_id\n\t\tWHERE msb.evidence = 'local_creation' AND ${creationClause}\n\t\tAND NOT EXISTS (SELECT 1 FROM json_each(?) visible WHERE visible.value = COALESCE(memory_items.scope_id, '')) LIMIT 1`)\n\t\t.get(JSON.stringify(visibleScopeIds));\n\treturn candidate ? localCreationSourceIds(db, context.deviceId.trim(), context) : [];\n}\n\nfunction addScopeVisibilityFilter(\n\tclauses: string[],\n\tparams: unknown[],\n\tcontext: OwnershipFilterContext | undefined,\n\tresolvedBranches?: FilterResult[],\n): void {\n\tif (!context?.enforceScopeVisibility) return;\n\tconst deviceId = context.deviceId.trim();\n\tif (!deviceId) {\n\t\tclauses.push(\"0 = 1\");\n\t\treturn;\n\t}\n\t// Blank/NULL scope_id is treated as local-default for read visibility.\n\t// Migration backfill promotes legacy rows to explicit scopes asynchronously,\n\t// but until that completes those rows must remain visible to their owning\n\t// device exactly the way local-default rows are.\n\tconst visibleScopeIds =\n\t\tcontext.visibleScopeIds ??\n\t\t(context.scopeVisibilityDb\n\t\t\t? resolveVisibleScopeIds(context.scopeVisibilityDb, deviceId, context)\n\t\t\t: undefined);\n\t// Mutable origin fields cannot prove managed authorship. Retain this legacy\n\t// exception only for explicitly unmanaged scopes, even after membership loss.\n\t// A legacy 'local' origin with an import key may be a foreign replica.\n\tconst unmanagedAuthored = `(memory_items.scope_id IN (\n\t\tSELECT scope_id FROM replication_scopes\n\t\tWHERE authority_type IN ('local', 'manual', 'invite')\n\t) AND ((${OWNERSHIP_ORIGIN_DEVICE_SQL} = ? AND ? <> 'local')\n\t\tOR (${OWNERSHIP_ORIGIN_DEVICE_SQL} = 'local'\n\t\t\tAND COALESCE(TRIM(memory_items.import_key), '') = '')))`;\n\tlet authored = unmanagedAuthored;\n\tconst authoredBranches: FilterResult[] = [\n\t\t{ clauses: [unmanagedAuthored], params: [deviceId, deviceId], joinSessions: false },\n\t];\n\tconst sourceIds = localCreationSourcesForFilter(context, visibleScopeIds);\n\tif (sourceIds.length && context.scopeVisibilityDb) {\n\t\t// Immutable creation history can also remain readable in managed scopes.\n\t\tconst bindingFilter = `msb.evidence = 'local_creation'\n\t\t\tAND msb.source_device_id IN (${sourceIds.map(() => \"?\").join(\", \")})`;\n\t\tconst creationClause = matchingLocalCreationClause(context.scopeVisibilityDb);\n\t\tauthored = `(${authored} OR EXISTS (SELECT 1 FROM memory_source_bindings msb\n\t\t\tWHERE msb.entity_id = memory_items.import_key AND ${bindingFilter}\n\t\t\tAND ${creationClause}))`;\n\t\t// Drive this exceptional branch from creation bindings/import keys rather\n\t\t// than inspecting provenance JSON for every row in every unreadable scope.\n\t\tauthoredBranches.push({\n\t\t\tclauses: [\n\t\t\t\t`memory_items.id IN (SELECT id FROM memory_items\n\t\t\t\t\tWHERE import_key IN (SELECT msb.entity_id FROM memory_source_bindings msb WHERE ${bindingFilter}))`,\n\t\t\t\t`${creationClause}`,\n\t\t\t\t`NOT COALESCE(${unmanagedAuthored}, 0)`,\n\t\t\t],\n\t\t\tparams: [...sourceIds, deviceId, deviceId],\n\t\t\tjoinSessions: false,\n\t\t});\n\t}\n\tif (visibleScopeIds !== undefined) {\n\t\taddResolvedScopeVisibilityFilter(\n\t\t\tclauses,\n\t\t\tparams,\n\t\t\tvisibleScopeIds,\n\t\t\tauthored,\n\t\t\tdeviceId,\n\t\t\tauthoredBranches,\n\t\t\tresolvedBranches,\n\t\t);\n\t\tparams.push(...sourceIds);\n\t\treturn;\n\t}\n\t// DB-less callers cannot validate managed proof. Preserve local/manual/invite\n\t// membership behavior, but never let raw coordinator rows grant permission.\n\tclauses.push(`(\n\t\tCOALESCE(TRIM(memory_items.scope_id), '') IN (?, ?, ?)\n\t\tOR EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM replication_scopes rs\n\t\t\tWHERE rs.scope_id = memory_items.scope_id\n\t\t\t AND rs.status = 'active'\n\t\t\t AND rs.authority_type = 'local'\n\t\t)\n\t\tOR EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM scope_memberships sm\n\t\t\tJOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\tWHERE sm.scope_id = memory_items.scope_id\n\t\t\t AND sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND rs.authority_type IN ('local', 'manual', 'invite')\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch\n\t\t)\n\t\tOR ${authored}\n\t)`);\n\tparams.push(\n\t\t\"\",\n\t\tLOCAL_DEFAULT_SCOPE_ID,\n\t\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\tdeviceId,\n\t\tdeviceId,\n\t\tdeviceId,\n\t);\n}\n\nfunction addResolvedScopeVisibilityFilter(\n\tclauses: string[],\n\tparams: unknown[],\n\tvisibleScopeIds: readonly string[],\n\tauthored: string,\n\tdeviceId: string,\n\tauthoredBranches: FilterResult[],\n\tresolvedBranches?: FilterResult[],\n): void {\n\tlet scopeClause = \"0 = 1\";\n\tconst scopeParams: unknown[] = [];\n\tif (visibleScopeIds.length > MAX_SCOPE_IN_PARAMS) {\n\t\tscopeClause = \"memory_items.scope_id IN (SELECT value FROM json_each(?))\";\n\t\tscopeParams.push(JSON.stringify(visibleScopeIds));\n\t} else if (visibleScopeIds.length > 0) {\n\t\tscopeClause = `memory_items.scope_id IN (${visibleScopeIds.map(() => \"?\").join(\", \")})`;\n\t\tscopeParams.push(...visibleScopeIds);\n\t}\n\tif (resolvedBranches) {\n\t\t// UNION ALL consumers must not count NULL, visible and authored rows twice.\n\t\t// Keep the full authored predicate, including immutable managed creation proof.\n\t\tresolvedBranches.push(\n\t\t\t{ clauses: [\"memory_items.scope_id IS NULL\"], params: [], joinSessions: false },\n\t\t\t{ clauses: [scopeClause], params: scopeParams, joinSessions: false },\n\t\t\t...authoredBranches.map((branch) => ({\n\t\t\t\tclauses: [\"memory_items.scope_id IS NOT NULL\", `NOT (${scopeClause})`, ...branch.clauses],\n\t\t\t\tparams: [...scopeParams, ...branch.params],\n\t\t\t\tjoinSessions: false,\n\t\t\t})),\n\t\t);\n\t\treturn;\n\t}\n\tparams.push(...scopeParams);\n\tclauses.push(`(memory_items.scope_id IS NULL OR ${scopeClause} OR ${authored})`);\n\tparams.push(deviceId, deviceId);\n}\n\n/**\n * Disjoint equivalents of the central read filter for UNION ALL aggregates.\n * Unresolved/DB-less contexts retain the exact ordinary filter as one branch.\n * Resolve on every call: these branches are not an authorization cache.\n */\nexport function buildFilterBranchesWithContext(\n\tfilters: MemoryFilters | undefined | null,\n\townership?: OwnershipFilterContext,\n): FilterResult[] {\n\tif (ownership?.visibleScopeIds === undefined) {\n\t\treturn [buildFilterClausesWithContext(filters, ownership)];\n\t}\n\tconst branches: FilterResult[] = [];\n\tconst clauses: string[] = [];\n\tconst params: unknown[] = [];\n\taddScopeVisibilityFilter(clauses, params, ownership, branches);\n\tconst common = buildFilterClausesWithContext(\n\t\tfilters,\n\t\townership ? { ...ownership, enforceScopeVisibility: false } : undefined,\n\t);\n\tif (!branches.length) branches.push({ clauses, params, joinSessions: false });\n\treturn branches.map((branch) => ({\n\t\tclauses: [...branch.clauses, ...common.clauses],\n\t\tparams: [...branch.params, ...common.params],\n\t\tjoinSessions: common.joinSessions,\n\t}));\n}\n\n/**\n * Build WHERE clause fragments from a MemoryFilters object.\n *\n * Returns clauses, params, and whether the sessions table must be joined.\n * The caller is responsible for prepending `memory_items.active = 1` or\n * similar base conditions — this function only appends filter-specific clauses.\n */\nexport function buildFilterClauses(filters: MemoryFilters | undefined | null): FilterResult {\n\treturn buildFilterClausesWithContext(filters);\n}\n\nfunction addProjectFilter(project: string | null | undefined, result: FilterResult): void {\n\tif (!project) return;\n\t// Session moves take precedence; redacted sessions fall back to readable memory attribution.\n\tconst filter = projectColumnClause(\"COALESCE(sessions.project, memory_items.project)\", project);\n\tif (!filter.clause) return;\n\tresult.clauses.push(filter.clause);\n\tresult.params.push(...filter.params);\n\tresult.joinSessions = true;\n}\n\nexport function buildFilterClausesWithContext(\n\tfilters: MemoryFilters | undefined | null,\n\townership?: OwnershipFilterContext,\n): FilterResult {\n\tconst result: FilterResult = { clauses: [], params: [], joinSessions: false };\n\tconst { clauses, params } = result;\n\taddScopeVisibilityFilter(clauses, params, ownership);\n\tif (!filters) return result;\n\n\t// Single kind filter — guard against non-string kinds from untyped\n\t// JSON request bodies (a number/bool would otherwise become a broken\n\t// bound parameter).\n\tif (typeof filters.kind === \"string\" && filters.kind) {\n\t\tclauses.push(\"memory_items.kind = ?\");\n\t\tparams.push(filters.kind);\n\t}\n\tif (filters.session_id) {\n\t\tclauses.push(\"memory_items.session_id = ?\");\n\t\tparams.push(filters.session_id);\n\t}\n\tif (filters.since) {\n\t\tclauses.push(\"memory_items.created_at >= ?\");\n\t\tparams.push(filters.since);\n\t}\n\n\tconst ownershipScope = String(filters.ownership_scope ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (ownership && (ownershipScope === \"mine\" || ownershipScope === \"theirs\")) {\n\t\tconst ownedPredicate = ownershipPredicateSql(ownership);\n\t\tif (ownershipScope === \"mine\") {\n\t\t\tclauses.push(ownedPredicate.clause);\n\t\t} else {\n\t\t\tclauses.push(`NOT ${ownedPredicate.clause}`);\n\t\t}\n\t\tparams.push(...ownedPredicate.params);\n\t}\n\n\taddProjectFilter(filters.project, result);\n\n\t// Visibility\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.visibility\",\n\t\tnormalizeVisibilityValues(filters.include_visibility ?? filters.visibility),\n\t\tnormalizeVisibilityValues(filters.exclude_visibility),\n\t);\n\n\t// Replication scope filters. These are an explicit narrowing layer and are\n\t// always intersected with the central scope-visibility gate above when the\n\t// caller enables it.\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.scope_id\",\n\t\tnormalizeFilterStrings(filters.include_scope_ids ?? filters.scope_id),\n\t\tnormalizeFilterStrings(filters.exclude_scope_ids),\n\t);\n\n\t// Workspace IDs\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.workspace_id\",\n\t\tnormalizeFilterStrings(filters.include_workspace_ids),\n\t\tnormalizeFilterStrings(filters.exclude_workspace_ids),\n\t);\n\n\t// Workspace kinds\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.workspace_kind\",\n\t\tnormalizeWorkspaceKinds(filters.include_workspace_kinds),\n\t\tnormalizeWorkspaceKinds(filters.exclude_workspace_kinds),\n\t);\n\n\t// Actor IDs\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.actor_id\",\n\t\tnormalizeFilterStrings(filters.include_actor_ids),\n\t\tnormalizeFilterStrings(filters.exclude_actor_ids),\n\t);\n\n\t// Trust states\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.trust_state\",\n\t\tnormalizeTrustStates(filters.include_trust_states),\n\t\tnormalizeTrustStates(filters.exclude_trust_states),\n\t);\n\n\treturn result;\n}\n","/**\n * Embedding primitives for semantic search.\n *\n * Ports codemem/semantic.py — text chunking, hashing, and embedding via a\n * pluggable client interface. The default factory lazily loads the optional\n * `@codemem/embeddings` runtime. When it is unavailable the helpers return\n * empty arrays and callers fall back to FTS-only retrieval.\n *\n * Embeddings are always disabled when CODEMEM_EMBEDDING_DISABLED=1.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { isEmbeddingDisabled } from \"./db.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal interface a concrete embedding backend must satisfy. */\nexport interface EmbeddingRuntimeIdentity {\n\treadonly package: \"@huggingface/transformers\";\n\treadonly version: string;\n\treadonly model: string;\n\treadonly revision: string;\n\treadonly requestedRevision?: string;\n\treadonly dtype: \"fp32\";\n\treadonly device: \"cpu\";\n\treadonly pooling: \"mean\";\n\treadonly normalization: \"l2\";\n\treadonly dimensions: number;\n}\n\nexport interface EmbeddingClient {\n\treadonly model: string;\n\treadonly dimensions: number;\n\treadonly identity?: EmbeddingRuntimeIdentity;\n\tembed(texts: string[]): Promise<Float32Array[]>;\n}\n\nexport interface EmbeddingRuntimeRequest {\n\tmodel: string;\n\trevision?: string;\n}\n\nexport type EmbeddingRuntimeFactory = (\n\trequest: EmbeddingRuntimeRequest,\n) => Promise<EmbeddingClient | null>;\n\nexport type EmbeddingRuntimeStatus =\n\t| { state: \"uninitialized\" | \"ready\" | \"disabled\" }\n\t| { state: \"unavailable\"; reason: \"missing_package\" | \"initialization_failed\" | \"no_client\" };\n\ninterface EmbeddingTensor {\n\tdata: ArrayLike<number | bigint>;\n\tdims?: number[];\n}\n\ntype FeatureExtractor = (\n\ttexts: string[],\n\toptions: { pooling: \"mean\"; normalize: true },\n) => Promise<EmbeddingTensor>;\n\nconst EMBEDDING_BATCH_SIZE = 32;\nconst DEFAULT_EMBEDDING_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst EMBEDDING_DIMENSIONS = 384;\nexport const DEFAULT_EMBEDDING_REVISION = \"ea104dacec62c0de699686887e3f920caeb4f3e3\";\n\n/** Copy validated embedding model data into owned Float32 storage. */\nexport function embeddingDataToFloat32(data: ArrayLike<number | bigint>): Float32Array {\n\tconst vector = new Float32Array(data.length);\n\tfor (let index = 0; index < data.length; index++) {\n\t\tconst value = data[index];\n\t\tconst float32Value = typeof value === \"number\" ? Math.fround(value) : Number.NaN;\n\t\tif (!Number.isFinite(float32Value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding model returned non-finite, non-numeric, or unrepresentable tensor data at index ${index}`,\n\t\t\t);\n\t\t}\n\t\tvector[index] = float32Value;\n\t}\n\treturn vector;\n}\n\n/** Split one validated row-major tensor into independently owned vectors. */\nexport function embeddingTensorToFloat32Rows(\n\toutput: EmbeddingTensor,\n\texpectedRows: number,\n\tdimensions: number,\n): Float32Array[] {\n\tif (\n\t\t!Number.isInteger(expectedRows) ||\n\t\texpectedRows <= 0 ||\n\t\t!Number.isInteger(dimensions) ||\n\t\tdimensions <= 0\n\t) {\n\t\tthrow new TypeError(\"Embedding tensor shape expectations must be positive integers\");\n\t}\n\tif (\n\t\toutput.dims?.length !== 2 ||\n\t\toutput.dims[0] !== expectedRows ||\n\t\toutput.dims[1] !== dimensions\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding model returned shape [${output.dims?.join(\", \") ?? \"unknown\"}], expected [${expectedRows}, ${dimensions}]`,\n\t\t);\n\t}\n\tif (output.data.length !== expectedRows * dimensions) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding model returned ${output.data.length} values, expected ${expectedRows * dimensions}`,\n\t\t);\n\t}\n\n\tconst rows = Array.from({ length: expectedRows }, () => new Float32Array(dimensions));\n\tfor (let flatIndex = 0; flatIndex < output.data.length; flatIndex++) {\n\t\tconst value = output.data[flatIndex];\n\t\tconst float32Value = typeof value === \"number\" ? Math.fround(value) : Number.NaN;\n\t\tif (!Number.isFinite(float32Value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding model returned non-finite, non-numeric, or unrepresentable tensor data at index ${flatIndex}`,\n\t\t\t);\n\t\t}\n\t\tconst row = rows[Math.floor(flatIndex / dimensions)];\n\t\tif (!row) throw new TypeError(\"Embedding tensor row calculation failed\");\n\t\trow[flatIndex % dimensions] = float32Value;\n\t}\n\treturn rows;\n}\n\n/** Run array inference in bounded batches while preserving input order. */\nexport async function embedTextBatches(\n\textractor: FeatureExtractor,\n\ttexts: string[],\n\tdimensions: number,\n\tbatchSize = EMBEDDING_BATCH_SIZE,\n): Promise<Float32Array[]> {\n\tif (texts.length === 0) return [];\n\tif (!Number.isInteger(batchSize) || batchSize <= 0) {\n\t\tthrow new TypeError(\"Embedding batch size must be a positive integer\");\n\t}\n\n\tconst vectors: Float32Array[] = [];\n\tfor (let offset = 0; offset < texts.length; offset += batchSize) {\n\t\tconst batch = texts.slice(offset, offset + batchSize);\n\t\tconst output = await extractor(batch, { pooling: \"mean\", normalize: true });\n\t\tvectors.push(...embeddingTensorToFloat32Rows(output, batch.length, dimensions));\n\t}\n\treturn vectors;\n}\n\n// ---------------------------------------------------------------------------\n// Text helpers (ports of semantic.py)\n// ---------------------------------------------------------------------------\n\n/** SHA-256 hex digest of UTF-8 encoded text. */\nexport function hashText(text: string): string {\n\treturn createHash(\"sha256\").update(text, \"utf-8\").digest(\"hex\");\n}\n\n/**\n * Split long text into ≤ `maxChars` chunks, preferring paragraph then\n * sentence boundaries. Matches Python's `chunk_text()`.\n */\nexport function chunkText(text: string, maxChars = 1200): string[] {\n\tconst cleaned = text.trim();\n\tif (!cleaned) return [];\n\tif (cleaned.length <= maxChars) return [cleaned];\n\n\tconst paragraphs = cleaned\n\t\t.split(/\\n{2,}/)\n\t\t.map((p) => p.trim())\n\t\t.filter(Boolean);\n\tconst chunks: string[] = [];\n\tlet buffer: string[] = [];\n\tlet bufferLen = 0;\n\n\tfor (const paragraph of paragraphs) {\n\t\tif (bufferLen + paragraph.length + 2 <= maxChars) {\n\t\t\tbuffer.push(paragraph);\n\t\t\tbufferLen += paragraph.length + 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (buffer.length > 0) {\n\t\t\tchunks.push(buffer.join(\"\\n\\n\"));\n\t\t\tbuffer = [];\n\t\t\tbufferLen = 0;\n\t\t}\n\t\tif (paragraph.length <= maxChars) {\n\t\t\tchunks.push(paragraph);\n\t\t\tcontinue;\n\t\t}\n\t\t// Split long paragraph by sentence\n\t\tconst sentences = paragraph\n\t\t\t.split(/(?<=[.!?])\\s+/)\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter(Boolean);\n\t\tconst sentBuf: string[] = [];\n\t\tlet sentLen = 0;\n\t\tfor (const sentence of sentences) {\n\t\t\t// Hard-split sentences that exceed maxChars on their own\n\t\t\tif (sentence.length > maxChars) {\n\t\t\t\tif (sentBuf.length > 0) {\n\t\t\t\t\tchunks.push(sentBuf.join(\" \"));\n\t\t\t\t\tsentBuf.length = 0;\n\t\t\t\t\tsentLen = 0;\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < sentence.length; i += maxChars) {\n\t\t\t\t\tchunks.push(sentence.slice(i, i + maxChars));\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sentLen + sentence.length + 1 <= maxChars) {\n\t\t\t\tsentBuf.push(sentence);\n\t\t\t\tsentLen += sentence.length + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sentBuf.length > 0) chunks.push(sentBuf.join(\" \"));\n\t\t\tsentBuf.length = 0;\n\t\t\tsentBuf.push(sentence);\n\t\t\tsentLen = sentence.length;\n\t\t}\n\t\tif (sentBuf.length > 0) chunks.push(sentBuf.join(\" \"));\n\t}\n\tif (buffer.length > 0) chunks.push(buffer.join(\"\\n\\n\"));\n\treturn chunks;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy singleton client\n// ---------------------------------------------------------------------------\n\nlet _client: EmbeddingClient | null | undefined;\nlet _clientPromise: Promise<EmbeddingClient | null> | undefined;\nlet _clientRequest: Required<EmbeddingRuntimeRequest> | undefined;\nlet _clientGeneration = 0;\nlet _runtimeWarningEmitted = false;\nlet _runtimeStatus: EmbeddingRuntimeStatus = { state: \"uninitialized\" };\n\nconst defaultEmbeddingRuntimeFactory: EmbeddingRuntimeFactory = async (request) => {\n\tconst { createEmbeddingRuntime } = await import(\"@codemem/embeddings\");\n\tconst client = await createEmbeddingRuntime(request);\n\tif (client && !client.identity) {\n\t\tthrow new TypeError(\n\t\t\t\"Installed @codemem/embeddings is outdated and does not expose runtime identity. Upgrade codemem and @codemem/embeddings together, then restart Codemem.\",\n\t\t);\n\t}\n\treturn client;\n};\nlet embeddingRuntimeFactory = defaultEmbeddingRuntimeFactory;\n\n/** Reset the singleton (for tests). */\nexport function _resetEmbeddingClient(): void {\n\t_client = undefined;\n\t_clientPromise = undefined;\n\t_clientRequest = undefined;\n\t_clientGeneration++;\n\t_runtimeStatus = { state: \"uninitialized\" };\n}\n\n/** Override the embedding runtime factory (for tests). */\nexport function _setEmbeddingRuntimeFactory(factory: EmbeddingRuntimeFactory): void {\n\tembeddingRuntimeFactory = factory;\n\t_resetEmbeddingClient();\n}\n\n/** Restore the default embedding runtime factory (for tests). */\nexport function _resetEmbeddingRuntimeFactory(): void {\n\tembeddingRuntimeFactory = defaultEmbeddingRuntimeFactory;\n\t_runtimeWarningEmitted = false;\n\t_resetEmbeddingClient();\n}\n\nfunction warnEmbeddingRuntimeUnavailable(error: unknown): void {\n\tif (_runtimeWarningEmitted) return;\n\t_runtimeWarningEmitted = true;\n\tif (isMissingEmbeddingRuntimePackage(error)) {\n\t\tconsole.warn(\n\t\t\t\"Semantic search is unavailable. Install @codemem/embeddings and restart Codemem to enable it.\",\n\t\t);\n\t\treturn;\n\t}\n\tconst cause = error instanceof Error ? error.message : String(error);\n\tconsole.warn(`Semantic search is unavailable because the embedding runtime failed: ${cause}`);\n}\n\nfunction isMissingEmbeddingRuntimePackage(error: unknown): boolean {\n\tlet current: unknown = error;\n\tconst seen = new Set<unknown>();\n\twhile (typeof current === \"object\" && current !== null && !seen.has(current)) {\n\t\tseen.add(current);\n\t\tif (\n\t\t\t\"code\" in current &&\n\t\t\tcurrent.code === \"ERR_MODULE_NOT_FOUND\" &&\n\t\t\tcurrent instanceof Error &&\n\t\t\tcurrent.message.includes(\"@codemem/embeddings\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = \"cause\" in current ? current.cause : undefined;\n\t}\n\treturn false;\n}\n\n/** Return process-local runtime state without loading the embedding model. */\nexport function getEmbeddingRuntimeStatus(): EmbeddingRuntimeStatus {\n\treturn _runtimeStatus;\n}\n\nfunction recordEmbeddingRuntimeClient(client: EmbeddingClient | null): void {\n\t_client = client;\n\tif (client) {\n\t\t_runtimeStatus = { state: \"ready\" };\n\t\treturn;\n\t}\n\t_runtimeStatus = { state: \"unavailable\", reason: \"no_client\" };\n\twarnEmbeddingRuntimeUnavailable(\"embedding runtime returned no client\");\n}\n\nasync function createEmbeddingClient(\n\tmodel: string,\n\trevision: string,\n\tgeneration: number,\n): Promise<EmbeddingClient | null> {\n\ttry {\n\t\tconst client = await embeddingRuntimeFactory({ model, revision });\n\t\tif (client) assertEmbeddingRuntimeIdentity(client, model, revision);\n\t\t// A reset while creation was in flight makes this client stale. Resolve\n\t\t// waiters through the live generation so model labels and dimensions agree.\n\t\tif (generation !== _clientGeneration) return getEmbeddingClient();\n\t\trecordEmbeddingRuntimeClient(client);\n\t\treturn client;\n\t} catch (error) {\n\t\t// A stale creation failure must not force current-generation waiters to null.\n\t\tif (generation !== _clientGeneration) return getEmbeddingClient();\n\t\t_client = null;\n\t\t_runtimeStatus = {\n\t\t\tstate: \"unavailable\",\n\t\t\treason: isMissingEmbeddingRuntimePackage(error) ? \"missing_package\" : \"initialization_failed\",\n\t\t};\n\t\twarnEmbeddingRuntimeUnavailable(error);\n\t\treturn null;\n\t} finally {\n\t\tif (generation === _clientGeneration) _clientPromise = undefined;\n\t}\n}\n\n/** Return the configured bare embedding model repository without loading the client. */\nexport function resolveEmbeddingModel(): string {\n\treturn process.env.CODEMEM_EMBEDDING_MODEL || DEFAULT_EMBEDDING_MODEL;\n}\n\n/** Resolve a configured revision without making non-semantic callers throw. */\nexport function tryResolveEmbeddingRevision(\n\tmodel = resolveEmbeddingModel(),\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | null {\n\tconst configuredRevision = env.CODEMEM_EMBEDDING_REVISION?.trim();\n\tif (configuredRevision) return configuredRevision;\n\tif (model === DEFAULT_EMBEDDING_MODEL) return DEFAULT_EMBEDDING_REVISION;\n\treturn null;\n}\n\n/** Resolve the concrete model revision required by vector-producing callers. */\nexport function resolveEmbeddingRevision(\n\tmodel = resolveEmbeddingModel(),\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst revision = tryResolveEmbeddingRevision(model, env);\n\tif (revision) return revision;\n\tthrow new TypeError(\n\t\t\"CODEMEM_EMBEDDING_REVISION is required when CODEMEM_EMBEDDING_MODEL selects a custom model\",\n\t);\n}\n\n/** Return the canonical persisted identity for the v4 embedding contract. */\nexport function resolveEmbeddingVectorIdentityLabel(\n\tmodel = resolveEmbeddingModel(),\n\trevision?: string,\n): string {\n\tif (revision === undefined) {\n\t\tconst configuredRevision = process.env.CODEMEM_EMBEDDING_REVISION?.trim();\n\t\tif (model !== DEFAULT_EMBEDDING_MODEL && !configuredRevision) {\n\t\t\tresolveEmbeddingRevision(model);\n\t\t}\n\t\tif (model !== DEFAULT_EMBEDDING_MODEL || configuredRevision) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Embedding vector identity requires a canonical commit SHA returned by the runtime\",\n\t\t\t);\n\t\t}\n\t\trevision = DEFAULT_EMBEDDING_REVISION;\n\t}\n\tif (!/^[0-9a-f]{40}$/.test(revision)) {\n\t\tthrow new TypeError(\n\t\t\t\"Embedding vector identity requires a canonical commit SHA returned by the runtime\",\n\t\t);\n\t}\n\treturn [\n\t\t\"transformers-v4\",\n\t\t`model=${encodeURIComponent(model)}`,\n\t\t`revision=${encodeURIComponent(revision)}`,\n\t\t\"dtype=fp32\",\n\t\t\"pooling=mean\",\n\t\t\"normalization=l2\",\n\t\t`dimensions=${EMBEDDING_DIMENSIONS}`,\n\t].join(\":\");\n}\n\n/** Construct a persisted vector identity only from runtime-resolved metadata. */\nexport function resolveEmbeddingClientVectorIdentityLabel(client: EmbeddingClient): string {\n\tif (!client.identity) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required to label persisted vectors\");\n\t}\n\treturn resolveEmbeddingVectorIdentityLabel(client.identity.model, client.identity.revision);\n}\n\nexport interface PersistedEmbeddingTarget {\n\ttargetModel?: unknown;\n\trequestedModel?: unknown;\n\trequestedRevision?: unknown;\n}\n\n/** Match a persisted canonical target to the active request, or use the built-in pin. */\nexport function tryResolveEmbeddingVectorIdentityLabel(\n\tpersisted: PersistedEmbeddingTarget = {},\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | null {\n\tconst model = env.CODEMEM_EMBEDDING_MODEL || DEFAULT_EMBEDDING_MODEL;\n\tconst requestedRevision = tryResolveEmbeddingRevision(model, env);\n\tif (\n\t\ttypeof persisted.targetModel === \"string\" &&\n\t\tpersisted.requestedModel === model &&\n\t\tpersisted.requestedRevision === requestedRevision\n\t) {\n\t\treturn persisted.targetModel;\n\t}\n\tif (\n\t\t_client?.identity?.model === model &&\n\t\t_client.identity.requestedRevision === requestedRevision\n\t) {\n\t\treturn resolveEmbeddingClientVectorIdentityLabel(_client);\n\t}\n\tif (\n\t\tmodel === DEFAULT_EMBEDDING_MODEL &&\n\t\trequestedRevision === DEFAULT_EMBEDDING_REVISION &&\n\t\t!env.CODEMEM_EMBEDDING_REVISION?.trim()\n\t) {\n\t\treturn DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL;\n\t}\n\treturn null;\n}\n\nexport const DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL = resolveEmbeddingVectorIdentityLabel(\n\tDEFAULT_EMBEDDING_MODEL,\n\tDEFAULT_EMBEDDING_REVISION,\n);\n\n/** Validate the runtime contract and agreement between a client and its identity. */\nexport function assertEmbeddingClientIdentity(\n\tclient: EmbeddingClient,\n): asserts client is EmbeddingClient & { readonly identity: EmbeddingRuntimeIdentity } {\n\tif (!client.identity) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required\");\n\t}\n\tif (\n\t\ttypeof client.model !== \"string\" ||\n\t\t!client.model.trim() ||\n\t\ttypeof client.identity.model !== \"string\" ||\n\t\t!client.identity.model.trim()\n\t) {\n\t\tthrow new TypeError(\"Embedding client model must be a non-empty string\");\n\t}\n\tconst runtimeMajorVersion = /^(\\d+)\\./.exec(client.identity.version)?.[1];\n\tif (runtimeMajorVersion !== \"4\") {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity mismatch for version: expected major 4, received ${String(client.identity.version)}`,\n\t\t);\n\t}\n\tconst expected = {\n\t\tpackage: \"@huggingface/transformers\",\n\t\tdtype: \"fp32\",\n\t\tdevice: \"cpu\",\n\t\tpooling: \"mean\",\n\t\tnormalization: \"l2\",\n\t\tdimensions: EMBEDDING_DIMENSIONS,\n\t} as const;\n\tfor (const key of Object.keys(expected) as Array<keyof typeof expected>) {\n\t\tif (client.identity[key] !== expected[key]) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding runtime identity mismatch for ${key}: expected ${String(expected[key])}, received ${String(client.identity[key])}`,\n\t\t\t);\n\t\t}\n\t}\n\tif (!/^[0-9a-f]{40}$/.test(client.identity.revision)) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity revision is not a canonical commit SHA: ${client.identity.revision}`,\n\t\t);\n\t}\n\tif (client.model !== client.identity.model) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding client model mismatch: expected ${client.identity.model}, received ${client.model}`,\n\t\t);\n\t}\n\tif (client.dimensions !== client.identity.dimensions) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding client dimensions mismatch: expected ${client.identity.dimensions}, received ${client.dimensions}`,\n\t\t);\n\t}\n}\n\nfunction assertEmbeddingRuntimeIdentity(\n\tclient: EmbeddingClient,\n\tmodel: string,\n\trequestedRevision: string,\n): void {\n\tassertEmbeddingClientIdentity(client);\n\tif (client.identity.model !== model) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity mismatch for model: expected ${model}, received ${client.identity.model}`,\n\t\t);\n\t}\n\tif (client.identity.requestedRevision !== requestedRevision) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity requestedRevision mismatch: expected ${requestedRevision}, got ${client.identity.requestedRevision ?? \"missing\"}`,\n\t\t);\n\t}\n}\n\n/**\n * Get the shared embedding client, creating it lazily on first call.\n * Returns null when embeddings are disabled or the runtime is unavailable.\n */\nexport async function getEmbeddingClient(): Promise<EmbeddingClient | null> {\n\tif (isEmbeddingDisabled()) {\n\t\t_client = null;\n\t\t_runtimeStatus = { state: \"disabled\" };\n\t\treturn null;\n\t}\n\tlet model: string;\n\tlet revision: string;\n\ttry {\n\t\tmodel = resolveEmbeddingModel();\n\t\trevision = resolveEmbeddingRevision(model);\n\t} catch (error) {\n\t\twarnEmbeddingRuntimeUnavailable(error);\n\t\treturn null;\n\t}\n\tconst request = { model, revision };\n\tconst requestMatches =\n\t\t_clientRequest?.model === request.model && _clientRequest.revision === request.revision;\n\tif (_client !== undefined && requestMatches) return _client;\n\tif (_clientPromise && requestMatches) return _clientPromise;\n\tif (_client !== undefined || _clientPromise) {\n\t\t_clientGeneration += 1;\n\t\t_client = undefined;\n\t\t_clientPromise = undefined;\n\t}\n\t_clientRequest = request;\n\tconst generation = _clientGeneration;\n\t_clientPromise = createEmbeddingClient(model, revision, generation);\n\treturn _clientPromise;\n}\n\n/**\n * Embed texts using the shared client.\n * Returns an empty array when embeddings are unavailable.\n */\nexport async function embedTexts(\n\ttexts: string[],\n\tresolvedClient?: EmbeddingClient,\n): Promise<Float32Array[]> {\n\tconst client = resolvedClient ?? (await getEmbeddingClient());\n\tif (!client) return [];\n\treturn client.embed(texts);\n}\n\n// ---------------------------------------------------------------------------\n// Serialization helpers (sqlite-vec wire format)\n// ---------------------------------------------------------------------------\n\n/** Serialize a Float32Array to a little-endian Buffer for sqlite-vec. */\nexport function serializeFloat32(vector: Float32Array): Buffer {\n\tconst buf = Buffer.alloc(vector.length * 4);\n\tfor (let i = 0; i < vector.length; i++) {\n\t\tbuf.writeFloatLE(vector[i] ?? 0, i * 4);\n\t}\n\treturn buf;\n}\n","/** Internal query stages shared by inline and worker semantic ranking, not a package API. */\nimport { DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL } from \"./embeddings.js\";\nimport { buildFilterBranchesWithContext, type OwnershipFilterContext } from \"./filters.js\";\nimport type { MaintenanceJobSnapshot } from \"./maintenance-jobs.js\";\nimport { summaryContinuityFilter } from \"./summary-memory.js\";\nimport type { MemoryFilters } from \"./types.js\";\nimport type { SemanticSearchResult, SemanticSearchScopeContext } from \"./vectors.js\";\n\nfunction scopeVisibleFilterContext(context: SemanticSearchScopeContext): OwnershipFilterContext {\n\treturn {\n\t\tactorId: context?.actorId ?? \"\",\n\t\tdeviceId: context?.deviceId ?? \"\",\n\t\tclaimedDeviceIds: context?.claimedDeviceIds ?? [],\n\t\tlegacyActorIds: context?.legacyActorIds ?? [],\n\t\tenforceScopeVisibility: true,\n\t\tvisibleScopeIds: context?.visibleScopeIds,\n\t\tscopeVisibilityDb: context?.scopeVisibilityDb,\n\t\texpectedPublicKey: context?.expectedPublicKey,\n\t\tloadExpectedPublicKey: context?.loadExpectedPublicKey,\n\t};\n}\n\nexport function buildAuthorizedSemanticMemoryIdsQuery(\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId: number | null | undefined,\n): { sql: string; params: unknown[] } {\n\tconst branches = buildFilterBranchesWithContext(filters, scopeVisibleFilterContext(context));\n\tconst continuity = summaryContinuityFilter(summarySessionId);\n\tconst queries = branches.map((branch) => {\n\t\tconst join = branch.joinSessions\n\t\t\t? \"JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t\t: \"\";\n\t\tconst clauses = [\"memory_items.active = 1\", ...branch.clauses, ...continuity.clauses];\n\t\treturn `SELECT memory_items.id FROM memory_items ${join}\n\t\t\tWHERE ${clauses.join(\" AND \")}`;\n\t});\n\treturn {\n\t\tsql: queries.join(\" UNION ALL \"),\n\t\tparams: branches.flatMap((branch) => [...branch.params, ...continuity.params]),\n\t};\n}\n\nexport function semanticResult(row: Record<string, unknown>): SemanticSearchResult {\n\treturn {\n\t\tid: Number(row.id),\n\t\tkind: String(row.kind ?? \"observation\"),\n\t\ttitle: String(row.title ?? \"\"),\n\t\tbody_text: String(row.body_text ?? \"\"),\n\t\tconfidence: Number(row.confidence ?? 0),\n\t\ttags_text: String(row.tags_text ?? \"\"),\n\t\tmetadata_json: row.metadata_json == null ? null : String(row.metadata_json),\n\t\tcreated_at: String(row.created_at ?? \"\"),\n\t\tupdated_at: String(row.updated_at ?? \"\"),\n\t\tsession_id: Number(row.session_id),\n\t\tscore: 1.0 / (1.0 + Number(row.distance ?? 0)),\n\t\tdistance: Number(row.distance ?? 0),\n\t\tnarrative: row.narrative == null ? null : String(row.narrative),\n\t\tfacts: row.facts == null ? null : String(row.facts),\n\t};\n}\n\nconst LEGACY_MODEL = \"Xenova/bge-small-en-v1.5\";\n\nfunction resolveLegacyRebuild(options: {\n\tcurrentModel: string;\n\tsourceModel: string;\n\ttargetModel: string | null;\n\tmodels: readonly (string | null)[];\n}): string | null {\n\tif (\n\t\toptions.sourceModel !== LEGACY_MODEL ||\n\t\toptions.targetModel !== DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL ||\n\t\toptions.currentModel !== DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL\n\t)\n\t\treturn null;\n\tif (options.models.includes(options.sourceModel)) return options.sourceModel;\n\tif (options.models.includes(options.currentModel)) return options.currentModel;\n\treturn null;\n}\n\nfunction catalogDefault(currentModel: string, models: readonly (string | null)[]): string | null {\n\tif (currentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL && models.includes(LEGACY_MODEL)) {\n\t\treturn LEGACY_MODEL;\n\t}\n\tif (models.includes(currentModel) && models.every((model) => model === currentModel)) {\n\t\treturn currentModel;\n\t}\n\treturn null;\n}\n\nfunction metadataModel(value: unknown): string | null {\n\treturn typeof value === \"string\" ? value : null;\n}\n\nexport function resolveSemanticSearchModelFromCatalog(\n\tcurrentModel: string,\n\tjob: Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null,\n\tmodels: readonly (string | null)[],\n): string | null {\n\tconst metadata = job?.metadata ?? {};\n\tconst sourceModel = metadataModel(metadata.source_model);\n\tconst targetModel = metadataModel(metadata.target_model);\n\tconst reconciliationTargetCoverageComplete =\n\t\tmetadata.reconciliation_target_coverage_complete === true;\n\tif (models.length === 0) return null;\n\tconst hasCurrentModel = models.includes(currentModel);\n\tif (\n\t\t[\"running\", \"pending\"].includes(job?.status ?? \"\") &&\n\t\treconciliationTargetCoverageComplete &&\n\t\ttargetModel === currentModel\n\t) {\n\t\treturn hasCurrentModel ? currentModel : null;\n\t}\n\tif (\n\t\t[\"running\", \"pending\", \"failed\"].includes(job?.status ?? \"\") &&\n\t\tsourceModel &&\n\t\tsourceModel !== currentModel\n\t) {\n\t\treturn resolveLegacyRebuild({ currentModel, sourceModel, targetModel, models });\n\t}\n\tif (job?.status === \"completed\" && targetModel === currentModel) {\n\t\treturn hasCurrentModel ? currentModel : null;\n\t}\n\treturn catalogDefault(currentModel, models);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"better-sqlite3\";\n\nexport type VectorLayout =\n\t| { kind: \"absent\" }\n\t| { kind: \"legacy\"; physicalName: \"memory_vectors\"; rowidsName: \"memory_vectors_rowids\" }\n\t| { kind: \"v1\"; physicalName: \"memory_vectors_v1\"; rowidsName: \"memory_vectors_v1_rowids\" };\n\nexport const VECTOR_V1_DDL = `CREATE VIRTUAL TABLE memory_vectors_v1 USING vec0(\n\tembedding float[384], memory_id INTEGER, chunk_index INTEGER, content_hash TEXT, model TEXT\n);`;\n\n// Keep the format-v1 catalog/version contract shared with the validated index.\nexport const VALIDATED_VECTOR_SCHEMA_DDL = `\nCREATE TABLE IF NOT EXISTS validated_vector_state (\n id INTEGER PRIMARY KEY CHECK(id=1), generation_id TEXT NOT NULL,\n revision INTEGER NOT NULL, writer_version INTEGER NOT NULL,\n status TEXT NOT NULL, audit_started INTEGER NOT NULL DEFAULT 0,\n known_models TEXT NOT NULL DEFAULT '[]', pending_count INTEGER NOT NULL DEFAULT 0,\n invalid_count INTEGER NOT NULL DEFAULT 0);\nCREATE TABLE IF NOT EXISTS validated_vector_models (\n model_null INTEGER NOT NULL, model_key TEXT NOT NULL, model TEXT,\n count INTEGER NOT NULL CHECK(count>=0), PRIMARY KEY(model_null,model_key));\nCREATE TABLE IF NOT EXISTS validated_vector_versions (\n memory_id INTEGER NOT NULL, model_null INTEGER NOT NULL, model_key TEXT NOT NULL,\n model TEXT, version INTEGER NOT NULL, count INTEGER NOT NULL CHECK(count>=0),\n PRIMARY KEY(memory_id,model_null,model_key));\nCREATE TABLE IF NOT EXISTS validated_vector_rows (\n rowid INTEGER PRIMARY KEY, memory_id INTEGER NOT NULL, model TEXT,\n chunk_index INTEGER NOT NULL, content_hash TEXT, audit_state TEXT NOT NULL, reason TEXT);\nCREATE INDEX IF NOT EXISTS validated_vector_rows_model_memory\n ON validated_vector_rows(model,memory_id);\nCREATE INDEX IF NOT EXISTS validated_vector_rows_state\n ON validated_vector_rows(audit_state,rowid);\nCREATE INDEX IF NOT EXISTS validated_vector_rows_model_state_memory\n ON validated_vector_rows(model,audit_state,memory_id);`;\n\nexport const VECTOR_COMPATIBILITY_DDL = `\nCREATE VIEW memory_vectors AS\n SELECT rowid AS rowid,embedding,memory_id,chunk_index,content_hash,model FROM memory_vectors_v1;\nCREATE TRIGGER memory_vectors_reject_insert INSTEAD OF INSERT ON memory_vectors\n BEGIN SELECT RAISE(ABORT,'vector_writer_upgrade_required'); END;\nCREATE TRIGGER memory_vectors_reject_update INSTEAD OF UPDATE ON memory_vectors\n BEGIN SELECT RAISE(ABORT,'vector_writer_upgrade_required'); END;\nCREATE TRIGGER memory_vectors_compat_delete INSTEAD OF DELETE ON memory_vectors\nBEGIN\n SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM validated_vector_rows WHERE rowid=OLD.rowid\n AND memory_id IS OLD.memory_id AND model IS OLD.model\n AND chunk_index IS OLD.chunk_index AND content_hash IS OLD.content_hash)\n THEN RAISE(ABORT,'vector_index_metadata_missing') END;\n SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM validated_vector_models\n WHERE model_null=(OLD.model IS NULL) AND model_key=COALESCE(OLD.model,'') AND count>0)\n OR NOT EXISTS (SELECT 1 FROM validated_vector_versions WHERE memory_id=OLD.memory_id\n AND model_null=(OLD.model IS NULL) AND model_key=COALESCE(OLD.model,'') AND count>0)\n OR NOT EXISTS (SELECT 1 FROM validated_vector_state WHERE id=1 AND writer_version=1)\n THEN RAISE(ABORT,'vector_index_metadata_missing') END;\n UPDATE validated_vector_models SET count=count-1\n WHERE model_null=(OLD.model IS NULL) AND model_key=COALESCE(OLD.model,'');\n UPDATE validated_vector_versions SET count=count-1,version=version+1\n WHERE memory_id=OLD.memory_id AND model_null=(OLD.model IS NULL)\n AND model_key=COALESCE(OLD.model,'');\n UPDATE validated_vector_state SET revision=revision+1,\n pending_count=pending_count-(SELECT audit_state='pending' FROM validated_vector_rows WHERE rowid=OLD.rowid),\n invalid_count=invalid_count-(SELECT audit_state='invalid' FROM validated_vector_rows WHERE rowid=OLD.rowid)\n WHERE id=1;\n DELETE FROM validated_vector_rows WHERE rowid=OLD.rowid;\n DELETE FROM memory_vectors_v1 WHERE rowid=OLD.rowid;\n UPDATE validated_vector_state SET status=CASE\n WHEN audit_started=0 OR pending_count>0 THEN 'building'\n WHEN invalid_count>0 THEN 'needsrepair' ELSE 'ready' END WHERE id=1;\nEND;`;\n\nconst METADATA_TABLES = [\n\t\"validated_vector_state\",\n\t\"validated_vector_rows\",\n\t\"validated_vector_models\",\n\t\"validated_vector_versions\",\n] as const;\n\nfunction normalizedDdl(sql: string): string {\n\treturn sql.trim().replace(/;$/, \"\").replace(/\\s+/g, \" \");\n}\n\nfunction compatibilityFenceExists(db: Database): boolean {\n\tconst read = db.prepare(\"SELECT sql FROM sqlite_schema WHERE name=?\");\n\tconst names = [\n\t\t\"memory_vectors\",\n\t\t\"memory_vectors_reject_insert\",\n\t\t\"memory_vectors_reject_update\",\n\t\t\"memory_vectors_compat_delete\",\n\t];\n\tconst definitions = VECTOR_COMPATIBILITY_DDL.trim().split(/(?=CREATE (?:VIEW|TRIGGER) )/);\n\treturn names.every((name, index) => {\n\t\tconst row = read.get(name) as { sql: string } | undefined;\n\t\treturn row !== undefined && normalizedDdl(row.sql) === normalizedDdl(definitions[index] ?? \"\");\n\t});\n}\n\n/** Only return identifiers selected from this fixed set, never caller SQL. */\nexport function resolveVectorLayout(db: Database): VectorLayout {\n\tconst objects = db\n\t\t.prepare(\n\t\t\t\"SELECT name,type FROM sqlite_schema WHERE name IN ('memory_vectors','memory_vectors_v1','memory_vectors_v1_rowids')\",\n\t\t)\n\t\t.all() as { name: string; type: string }[];\n\tconst legacy = objects.find((object) => object.name === \"memory_vectors\");\n\tif (legacy?.type === \"table\") {\n\t\tif (objects.some((object) => object.name === \"memory_vectors_v1\"))\n\t\t\tthrow new Error(\"vector_layout_inconsistent\");\n\t\treturn { kind: \"legacy\", physicalName: \"memory_vectors\", rowidsName: \"memory_vectors_rowids\" };\n\t}\n\tif (!objects.length) return { kind: \"absent\" };\n\tconst exists = db.prepare(\"SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?\");\n\tif (\n\t\tlegacy?.type !== \"view\" ||\n\t\t!objects.some((object) => object.name === \"memory_vectors_v1\" && object.type === \"table\") ||\n\t\t!objects.some((object) => object.name === \"memory_vectors_v1_rowids\") ||\n\t\t!METADATA_TABLES.every((name) => exists.get(name))\n\t) {\n\t\tthrow new Error(\"vector_layout_inconsistent\");\n\t}\n\tconst state = db.prepare(\"SELECT writer_version FROM validated_vector_state WHERE id=1\").get() as\n\t\t| { writer_version: number }\n\t\t| undefined;\n\tif (state?.writer_version !== 1) throw new Error(\"validated_index_format_required\");\n\tif (!compatibilityFenceExists(db)) throw new Error(\"vector_layout_writer_fence_missing\");\n\treturn { kind: \"v1\", physicalName: \"memory_vectors_v1\", rowidsName: \"memory_vectors_v1_rowids\" };\n}\n\nexport function vectorStoreExists(db: Database): boolean {\n\ttry {\n\t\treturn resolveVectorLayout(db).kind !== \"absent\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Fresh stores never create the legacy writable name. No imports from db/bootstrap. */\nexport function createEmptyVectorLayout(db: Database): void {\n\tdb.transaction(() => {\n\t\tdb.exec(VECTOR_V1_DDL);\n\t\tdb.exec(VALIDATED_VECTOR_SCHEMA_DDL);\n\t\tdb.prepare(`INSERT INTO validated_vector_state\n\t\t (id,generation_id,revision,writer_version,status,audit_started) VALUES(1,?,0,1,'ready',1)`).run(\n\t\t\trandomUUID(),\n\t\t);\n\t\tdb.exec(VECTOR_COMPATIBILITY_DDL);\n\t}).immediate();\n}\n","/** Exact semantic ranking inside a caller-owned, validated read snapshot. */\nimport { type Database, tableExists } from \"../db.js\";\nimport { DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL } from \"../embeddings.js\";\nimport type { MaintenanceJobSnapshot, MaintenanceJobStatus } from \"../maintenance-jobs.js\";\nimport {\n\tbuildAuthorizedSemanticMemoryIdsQuery,\n\tresolveSemanticSearchModelFromCatalog,\n\tsemanticResult,\n} from \"../semantic-query.js\";\nimport type { MemoryFilters } from \"../types.js\";\nimport { resolveVectorLayout } from \"../vector-layout.js\";\nimport type { SemanticSearchResult, SemanticSearchScopeContext } from \"../vectors.js\";\n\nexport interface PreparedQuery {\n\tmodel: string;\n\tvectors: readonly Float32Array[];\n}\nexport interface VectorRowInput {\n\tmemoryId: number;\n\tchunkIndex: number;\n\tcontentHash: string;\n\tvector: Float32Array;\n}\ntype Rejection = \"shape\" | \"nonfinite\" | \"norm\" | \"model\";\nexport interface RankingRequest {\n\tquery: PreparedQuery;\n\tlimit: number;\n\tfilters: MemoryFilters | null;\n\tcontext: SemanticSearchScopeContext;\n\tsummarySessionId?: number | null;\n}\ninterface Probe {\n\tmodel: string;\n\tk: number;\n\treturned: number;\n\texhausted: boolean;\n\ttailDistance: number | null;\n}\nexport interface RankingResult {\n\tresults: SemanticSearchResult[];\n\tstrategy: \"native\" | \"scalar\";\n\tprobes: readonly Probe[];\n\tfallbackCount: number;\n}\ninterface CandidateScope {\n\tsql: string;\n\tparams: unknown[];\n\tacceptedSql: string;\n\tacceptedParams: string[];\n\trowidSource: \"memory_vectors\" | \"validated_vector_rows\";\n\tvectorTable: \"memory_vectors\" | \"memory_vectors_v1\";\n}\ninterface Neighbor {\n\tid: number;\n\tdistance: number;\n}\n\nexport function requireModel(model: string): void {\n\tif (typeof model !== \"string\" || !model.trim()) throw new TypeError(\"vector_model_required\");\n}\n\nfunction vectorRejection(vector: Float32Array): Rejection | null {\n\tif (!(vector instanceof Float32Array) || vector.length !== 384) return \"shape\";\n\tlet normSquared = 0;\n\tfor (const component of vector) {\n\t\tif (!Number.isFinite(component)) return \"nonfinite\";\n\t\tnormSquared += component * component;\n\t}\n\t// Normalized embeddings have norm ~1. Norm <=2 allows rounding headroom without\n\t// renormalization. For two accepted vectors L2 <=4, squared L2 <=16: float32-safe.\n\tif (normSquared > 4) return \"norm\";\n\treturn null;\n}\n\nexport function vectorBytes(vector: Float32Array): Buffer {\n\tconst rejection = vectorRejection(vector);\n\tif (rejection) throw new TypeError(`invalid_vector_${rejection}`);\n\tconst bytes = Buffer.alloc(384 * 4);\n\tvector.forEach((component, index) => {\n\t\tbytes.writeFloatLE(component, index * 4);\n\t});\n\treturn bytes;\n}\n\nexport function inspectBytes(bytes: Buffer): Rejection | null {\n\tif (!Buffer.isBuffer(bytes) || bytes.length !== 384 * 4) return \"shape\";\n\tconst vector = new Float32Array(384);\n\tfor (let index = 0; index < vector.length; index++) vector[index] = bytes.readFloatLE(index * 4);\n\treturn vectorRejection(vector);\n}\n\nfunction readModelMetadata(json: string | null): Record<string, unknown> | null {\n\ttry {\n\t\tconst value: unknown = JSON.parse(json ?? \"null\");\n\t\tif (value && typeof value === \"object\" && !Array.isArray(value)) {\n\t\t\treturn value as Record<string, unknown>;\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n\nexport function readModelJob(\n\tdb: Database,\n): Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null {\n\tif (!tableExists(db, \"maintenance_jobs\")) return null;\n\tconst row = db\n\t\t.prepare(\"SELECT status, metadata_json FROM maintenance_jobs WHERE kind = ?\")\n\t\t.get(\"vector_model_migration\") as\n\t\t| { status: MaintenanceJobStatus; metadata_json: string | null }\n\t\t| undefined;\n\tif (!row) return null;\n\treturn { status: row.status, metadata: readModelMetadata(row.metadata_json) };\n}\n\nexport function resolveCatalogModels(\n\tcurrentModel: string,\n\tcatalog: Array<string | null>,\n\tjob: Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null,\n): string[] {\n\tconst primary = resolveSemanticSearchModelFromCatalog(currentModel, job, catalog);\n\tif (!primary) return [];\n\tif (\n\t\tprimary === \"Xenova/bge-small-en-v1.5\" &&\n\t\tcurrentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL &&\n\t\tcatalog.includes(currentModel)\n\t) {\n\t\treturn [primary, currentModel];\n\t}\n\treturn [primary];\n}\n\nfunction candidateScope(\n\tdb: Database,\n\trequest: RankingRequest,\n\toptions: { acceptedIds: string | null; indexedRows?: boolean },\n): CandidateScope {\n\tconst authorized = buildAuthorizedSemanticMemoryIdsQuery(\n\t\trequest.filters,\n\t\t{ ...request.context, visibleScopeIds: undefined, scopeVisibilityDb: db },\n\t\trequest.summarySessionId,\n\t);\n\tconst rowidSource = options.indexedRows ? \"validated_vector_rows\" : \"memory_vectors\";\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\tconst vectorTable = layout.physicalName;\n\tconst validitySql = options.indexedRows ? \"AND audit_state='valid'\" : \"\";\n\tif (options.acceptedIds === null) {\n\t\treturn {\n\t\t\t...authorized,\n\t\t\tacceptedSql: validitySql,\n\t\t\tacceptedParams: [],\n\t\t\trowidSource,\n\t\t\tvectorTable,\n\t\t};\n\t}\n\treturn {\n\t\t...authorized,\n\t\tacceptedSql: `${validitySql} AND rowid IN (SELECT value FROM json_each(?))`,\n\t\tacceptedParams: [options.acceptedIds],\n\t\trowidSource,\n\t\tvectorTable,\n\t};\n}\n\nfunction nativeProbe(\n\tdb: Database,\n\toptions: { model: string; scope: CandidateScope; query: Buffer; k: number },\n) {\n\tconst { scope } = options;\n\t// Both constraints belong to vec0's MATCH query, not a joined postfilter.\n\tconst rows = db\n\t\t.prepare(`WITH authorized_ids AS MATERIALIZED (${scope.sql})\n\t\tSELECT memory_id AS id, distance FROM ${scope.vectorTable}\n\t\tWHERE embedding MATCH ? AND k = ? AND model = ?\n\t\tAND rowid IN (\n\t\t\tSELECT rowid FROM ${scope.rowidSource}\n\t\t\tWHERE model = ? AND memory_id IN (SELECT id FROM authorized_ids)\n\t\t\t${scope.acceptedSql}\n\t\t) ORDER BY distance`)\n\t\t.all(\n\t\t\t...scope.params,\n\t\t\toptions.query,\n\t\t\toptions.k,\n\t\t\toptions.model,\n\t\t\toptions.model,\n\t\t\t...scope.acceptedParams,\n\t\t) as Neighbor[];\n\tfor (const row of rows) {\n\t\tif (!Number.isSafeInteger(row.id) || !Number.isFinite(row.distance)) {\n\t\t\tthrow new Error(\"invalid_native_neighbor\");\n\t\t}\n\t}\n\tconst probe: Probe = {\n\t\tmodel: options.model,\n\t\tk: options.k,\n\t\treturned: rows.length,\n\t\t// Exactly k returned may also exhaust a model, but proving that would\n\t\t// require counting every eligible row. Treat it as unknown instead.\n\t\texhausted: rows.length < options.k,\n\t\ttailDistance: rows.at(-1)?.distance ?? null,\n\t};\n\treturn { neighbors: rows, probe };\n}\n\nfunction mergeNeighbors(neighbors: Neighbor[]): Neighbor[] {\n\tconst best = new Map<number, number>();\n\tfor (const { id, distance } of neighbors) {\n\t\tbest.set(id, Math.min(best.get(id) ?? Number.POSITIVE_INFINITY, distance));\n\t}\n\treturn [...best]\n\t\t.map(([id, distance]) => ({ id, distance }))\n\t\t.sort((a, b) => a.distance - b.distance || a.id - b.id);\n}\n\nfunction scalarRank(\n\tdb: Database,\n\toptions: { scope: CandidateScope; models: string[]; query: Buffer; limit: number },\n): Neighbor[] {\n\tconst { scope } = options;\n\treturn db\n\t\t.prepare(`WITH authorized_ids AS MATERIALIZED (${scope.sql})\n\t\tSELECT memory_id AS id, MIN(vec_distance_l2(embedding, ?)) AS distance\n\t\tFROM ${scope.vectorTable} WHERE rowid IN (\n\t\t\tSELECT rowid FROM ${scope.rowidSource}\n\t\t\tWHERE memory_id IN (SELECT id FROM authorized_ids)\n\t\t\tAND model IN (SELECT value FROM json_each(?)) ${scope.acceptedSql}\n\t\t)\n\t\tGROUP BY memory_id ORDER BY distance, memory_id LIMIT ?`)\n\t\t.all(\n\t\t\t...scope.params,\n\t\t\toptions.query,\n\t\t\tJSON.stringify(options.models),\n\t\t\t...scope.acceptedParams,\n\t\t\toptions.limit,\n\t\t) as Neighbor[];\n}\n\nfunction loadPayloads(db: Database, ranked: Neighbor[]): SemanticSearchResult[] {\n\tconst rows = db\n\t\t.prepare(\"SELECT * FROM memory_items WHERE id IN (SELECT value FROM json_each(?))\")\n\t\t.all(JSON.stringify(ranked.map(({ id }) => id))) as Record<string, unknown>[];\n\tconst byId = new Map(rows.map((row) => [Number(row.id), row]));\n\tconst results: SemanticSearchResult[] = [];\n\tfor (const { id, distance } of ranked) {\n\t\tconst row = byId.get(id);\n\t\tif (!row) continue;\n\t\tresults.push(semanticResult({ ...row, distance }));\n\t}\n\treturn results;\n}\n\n/** Internal engine; caller supplies validation evidence and owns the read snapshot. */\nexport function rankPrevalidatedSnapshot(\n\tdb: Database,\n\trequest: RankingRequest,\n\toptions: { models: string[]; acceptedIds: string | null; indexedRows?: boolean },\n): RankingResult {\n\tif (!db.inTransaction) throw new Error(\"ranking_snapshot_required\");\n\tvalidateRankingRequest(request);\n\tconst query = vectorBytes(request.query.vectors[0] as Float32Array);\n\tconst scope = candidateScope(db, request, options);\n\tconst { models } = options;\n\tconst k = Math.min(4096, Math.max(request.limit + 1, 4 * request.limit));\n\tconst outputs = models.map((model) =>\n\t\tnativeProbe(db, {\n\t\t\tmodel,\n\t\t\tscope,\n\t\t\tquery,\n\t\t\tk,\n\t\t}),\n\t);\n\tconst probes = outputs.map((output) => output.probe);\n\tconst merged = mergeNeighbors(outputs.flatMap((output) => output.neighbors));\n\tconst nth = merged[request.limit - 1]?.distance;\n\tconst certified =\n\t\tnth !== undefined &&\n\t\tprobes.every(\n\t\t\t(probe) => probe.exhausted || (probe.tailDistance !== null && probe.tailDistance > nth),\n\t\t);\n\tconst ranked = certified\n\t\t? merged.slice(0, request.limit)\n\t\t: scalarRank(db, { scope, models, query, limit: request.limit });\n\tconst results = loadPayloads(db, ranked);\n\treturn {\n\t\tresults,\n\t\tstrategy: certified ? \"native\" : \"scalar\",\n\t\tprobes,\n\t\tfallbackCount: certified ? 0 : 1,\n\t};\n}\n\nexport function validateRankingRequest(request: RankingRequest): void {\n\tif (!Number.isInteger(request.limit) || request.limit < 1 || request.limit > 200) {\n\t\tthrow new RangeError(\"semantic_limit_must_be_1_to_200\");\n\t}\n\trequireModel(request.query.model);\n\tif (request.query.vectors.length !== 1) throw new TypeError(\"query_vector_count_mismatch\");\n\tif (!request.context?.deviceId?.trim()) throw new Error(\"semantic_search_scope_context_required\");\n}\n","/** Persisted format-v1 metadata. Raw/older writers require invalidation and rebuild. */\nimport { randomUUID } from \"node:crypto\";\nimport { type Database, tableExists } from \"../db.js\";\nimport type { MaintenanceJobSnapshot } from \"../maintenance-jobs.js\";\nimport { readModelJob } from \"./semantic-ranking.js\";\nimport type { AuditStateStatements, CountStatements } from \"./validated-vector-index-statements.js\";\n\nexport interface VectorCatalog {\n\tgenerationId: string;\n\trevision: number;\n\tstatus: \"building\" | \"needsrepair\" | \"ready\";\n\twriterVersion: 1;\n\tmodels: { model: string | null; count: number }[];\n\tmigration: Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null;\n}\nexport interface CandidateVersion {\n\tmemoryId: number;\n\tmodel: string;\n\tversion: number;\n\tcount: number;\n}\nexport interface State {\n\tgeneration_id: string;\n\trevision: number;\n\tstatus: VectorCatalog[\"status\"];\n\twriter_version: number;\n\taudit_started: number;\n\tknown_models: string;\n\tpending_count: number;\n\tinvalid_count: number;\n}\nexport interface IndexedRow {\n\trowid: number;\n\tmemory_id: number;\n\tmodel: string | null;\n\tchunk_index: number;\n\tcontent_hash: string;\n\taudit_state: \"pending\" | \"valid\" | \"invalid\";\n\treason: string | null;\n}\nexport interface AuditProgress {\n\tcatalog: VectorCatalog;\n\tchecked: number;\n\tremaining: number;\n\tinvalid: number;\n\tdiagnostics: {\n\t\trowid: number;\n\t\treason: string;\n\t\tmemoryId?: number;\n\t\tmodel?: string | null;\n\t\taction?: \"pruned\";\n\t}[];\n}\n\nexport function snapshot<T>(db: Database, read: () => T): T {\n\tif (db.inTransaction) return read();\n\treturn db.transaction(read)();\n}\n\nexport function readState(db: Database): State {\n\tconst state = db.prepare(\"SELECT * FROM validated_vector_state WHERE id = 1\").get() as State;\n\tif (state?.writer_version !== 1) throw new Error(\"validated_index_format_required\");\n\treturn state;\n}\n\nexport function readCatalog(db: Database): VectorCatalog | null {\n\treturn snapshot(db, () => {\n\t\tif (!tableExists(db, \"validated_vector_state\")) return null;\n\t\tconst state = readState(db);\n\t\tconst models = db\n\t\t\t.prepare(`SELECT model, count FROM validated_vector_models\n\t\t\tWHERE count > 0 ORDER BY model_null, model_key`)\n\t\t\t.all() as VectorCatalog[\"models\"];\n\t\treturn {\n\t\t\tgenerationId: state.generation_id,\n\t\t\trevision: state.revision,\n\t\t\tstatus: state.status,\n\t\t\twriterVersion: 1,\n\t\t\tmodels,\n\t\t\tmigration: readModelJob(db),\n\t\t};\n\t});\n}\n\nexport function requireCatalog(db: Database): VectorCatalog {\n\tconst catalog = readCatalog(db);\n\tif (!catalog) throw new Error(\"validated_index_not_initialized\");\n\treturn catalog;\n}\n\n/** Completed audits can supply valid evidence while other derived rows await repair. */\nexport function isSearchableVectorCatalog(\n\tdb: Database,\n\tcatalog: VectorCatalog | null,\n): catalog is VectorCatalog {\n\tif (catalog?.writerVersion !== 1) return false;\n\tif (catalog.status === \"ready\") return catalog.models.some(({ count }) => count > 0);\n\tif (catalog.status !== \"needsrepair\") return false;\n\treturn Boolean(\n\t\tdb.prepare(\"SELECT 1 FROM validated_vector_rows WHERE audit_state='valid' LIMIT 1\").get(),\n\t);\n}\n\nexport function readSearchableModelLabels(\n\tdb: Database,\n\tcatalog: VectorCatalog,\n): Array<string | null> {\n\tconst labels = catalog.models.map(({ model }) => model);\n\tif (catalog.status !== \"needsrepair\") return labels;\n\tconst valid = db.prepare(\n\t\t\"SELECT 1 FROM validated_vector_rows WHERE model IS ? AND audit_state='valid' LIMIT 1\",\n\t);\n\treturn labels.filter((model) => Boolean(valid.get(model)));\n}\n\nexport function requireWriter(version: number): void {\n\tif (version !== 1) throw new TypeError(\"validated_writer_version_required\");\n}\n\nexport function requireGenerationModel(state: State, model: string): void {\n\tif (!state.audit_started) return;\n\tconst knownModels: unknown = JSON.parse(state.known_models);\n\tif (!Array.isArray(knownModels) || !knownModels.includes(model)) {\n\t\tthrow new TypeError(\"vector_model_not_declared_in_generation\");\n\t}\n}\n\nexport function initializeValidatedIndex(\n\tdb: Database,\n\toptions: { allWritersUpgraded: true; writerVersion: 1 },\n): VectorCatalog {\n\tif (options.allWritersUpgraded !== true) throw new TypeError(\"all_writers_must_be_upgraded\");\n\trequireWriter(options.writerVersion);\n\treturn db.transaction(() => {\n\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_state (\n\t\t\t id INTEGER PRIMARY KEY CHECK(id=1), generation_id TEXT NOT NULL,\n\t\t\t revision INTEGER NOT NULL, writer_version INTEGER NOT NULL,\n\t\t\t status TEXT NOT NULL, audit_started INTEGER NOT NULL DEFAULT 0,\n\t\t\t known_models TEXT NOT NULL DEFAULT '[]', pending_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t invalid_count INTEGER NOT NULL DEFAULT 0);\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_models (\n\t\t\t model_null INTEGER NOT NULL, model_key TEXT NOT NULL, model TEXT,\n\t\t\t count INTEGER NOT NULL CHECK(count>=0), PRIMARY KEY(model_null,model_key));\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_versions (\n\t\t\t memory_id INTEGER NOT NULL, model_null INTEGER NOT NULL, model_key TEXT NOT NULL,\n\t\t\t model TEXT, version INTEGER NOT NULL, count INTEGER NOT NULL CHECK(count>=0),\n\t\t\t PRIMARY KEY(memory_id,model_null,model_key));\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_rows (\n\t\t\t rowid INTEGER PRIMARY KEY, memory_id INTEGER NOT NULL, model TEXT,\n\t\t\t chunk_index INTEGER NOT NULL, content_hash TEXT, audit_state TEXT NOT NULL,\n\t\t\t reason TEXT);\n\t\t\tCREATE INDEX IF NOT EXISTS validated_vector_rows_model_memory\n\t\t\t ON validated_vector_rows(model,memory_id);\n\t\t\tCREATE INDEX IF NOT EXISTS validated_vector_rows_state\n\t\t\t ON validated_vector_rows(audit_state,rowid);\n\t\t\tCREATE INDEX IF NOT EXISTS validated_vector_rows_model_state_memory\n\t\t\t ON validated_vector_rows(model,audit_state,memory_id);\n\t\t`);\n\t\tdb.prepare(`INSERT OR IGNORE INTO validated_vector_state\n\t\t\t(id,generation_id,revision,writer_version,status) VALUES(1,?,0,1,'building')`).run(\n\t\t\trandomUUID(),\n\t\t);\n\t\treturn requireCatalog(db);\n\t})();\n}\n\nexport function invalidateValidatedIndex(db: Database): VectorCatalog {\n\treturn db.transaction(() => {\n\t\treadState(db);\n\t\tdb.prepare(`UPDATE validated_vector_state SET generation_id=?, revision=revision+1,\n\t\t\tstatus='building',audit_started=0 WHERE id=1`).run(randomUUID());\n\t\treturn requireCatalog(db);\n\t})();\n}\n\nexport function refreshStatus(db: Database): void {\n\tdb.exec(`UPDATE validated_vector_state SET status=CASE\n\t\tWHEN audit_started=0 OR pending_count>0 THEN 'building'\n\t\tWHEN invalid_count>0 THEN 'needsrepair' ELSE 'ready' END WHERE id=1`);\n}\n\nexport function finishMutation(db: Database): VectorCatalog {\n\tdb.exec(\"UPDATE validated_vector_state SET revision=revision+1 WHERE id=1\");\n\trefreshStatus(db);\n\treturn requireCatalog(db);\n}\n\nexport function changeCounts(\n\tstatements: CountStatements,\n\tmemoryId: number,\n\tmodel: string | null,\n\tdelta: number,\n): void {\n\tconst nullKey = Number(model === null);\n\tconst key = model ?? \"\";\n\tstatements.insertModel.run(nullKey, key, model);\n\tstatements.updateModelCount.run(delta, nullKey, key);\n\tstatements.insertVersion.run(memoryId, nullKey, key, model);\n\tstatements.updateVersionCount.run(delta, memoryId, nullKey, key);\n}\n\nexport function updateAuditState(\n\tstatements: AuditStateStatements,\n\trow: IndexedRow,\n\tstate: IndexedRow[\"audit_state\"],\n\treason: string | null = null,\n): void {\n\tstatements.updateRowState.run(state, reason, row.rowid);\n\tconst pending = Number(state === \"pending\") - Number(row.audit_state === \"pending\");\n\tconst invalid = Number(state === \"invalid\") - Number(row.audit_state === \"invalid\");\n\tstatements.updateAuditCounts.run(pending, invalid);\n}\n\nexport function progress(\n\tdb: Database,\n\tchecked = 0,\n\tdiagnostics: AuditProgress[\"diagnostics\"] = [],\n): AuditProgress {\n\tconst state = readState(db);\n\treturn {\n\t\tcatalog: requireCatalog(db),\n\t\tchecked,\n\t\tremaining: state.pending_count,\n\t\tinvalid: state.invalid_count,\n\t\tdiagnostics,\n\t};\n}\n\nexport function requireLimit(limit: number): void {\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {\n\t\tthrow new RangeError(\"audit_limit_must_be_1_to_1000\");\n\t}\n}\n\nexport function readCandidateVersions(\n\tdb: Database,\n\toptions: { memoryIds: readonly number[]; models: readonly string[] },\n): CandidateVersion[] {\n\treturn snapshot(db, () => {\n\t\tif (!tableExists(db, \"validated_vector_state\")) return [];\n\t\treadState(db);\n\t\treturn db\n\t\t\t.prepare(`SELECT memory_id AS memoryId,model,version,count FROM validated_vector_versions\n\t\t\tWHERE memory_id IN (SELECT value FROM json_each(?)) AND model_null=0\n\t\t\tAND model_key IN (SELECT value FROM json_each(?)) ORDER BY memory_id,model_key`)\n\t\t\t.all(JSON.stringify(options.memoryIds), JSON.stringify(options.models)) as CandidateVersion[];\n\t});\n}\n","import type { Statement } from \"better-sqlite3\";\nimport type { Database } from \"../db.js\";\nimport { resolveVectorLayout } from \"../vector-layout.js\";\n\nexport type IndexStatement = Statement<unknown[]>;\n\nexport interface CountStatements {\n\tinsertModel: IndexStatement;\n\tupdateModelCount: IndexStatement;\n\tinsertVersion: IndexStatement;\n\tupdateVersionCount: IndexStatement;\n}\n\nexport interface InsertStatements {\n\tcounts: CountStatements;\n\tinsertVector: IndexStatement;\n\tinsertIndexedRow: IndexStatement;\n}\n\nexport interface RemoveStatements {\n\tcounts: CountStatements;\n\tdeleteVector: IndexStatement;\n\tdeleteIndexedRow: IndexStatement;\n\tdecrementAuditCounts: IndexStatement;\n}\n\nexport interface AuditStateStatements {\n\tupdateRowState: IndexStatement;\n\tupdateAuditCounts: IndexStatement;\n}\n\n/** These sets belong to one synchronous operation, never a connection-wide cache. */\nexport function prepareCountStatements(db: Database): CountStatements {\n\treturn {\n\t\tinsertModel:\n\t\t\tdb.prepare(`INSERT OR IGNORE INTO validated_vector_models(model_null,model_key,model,count)\n\t\tVALUES(?,?,?,0)`),\n\t\tupdateModelCount: db.prepare(\n\t\t\t`UPDATE validated_vector_models SET count=count+? WHERE model_null=? AND model_key=?`,\n\t\t),\n\t\tinsertVersion:\n\t\t\tdb.prepare(`INSERT OR IGNORE INTO validated_vector_versions(memory_id,model_null,model_key,model,version,count)\n\t\tVALUES(?,?,?,?,0,0)`),\n\t\tupdateVersionCount:\n\t\t\tdb.prepare(`UPDATE validated_vector_versions SET version=version+1,count=count+?\n\t\tWHERE memory_id=? AND model_null=? AND model_key=?`),\n\t};\n}\n\nexport function prepareInsertStatements(db: Database, counts: CountStatements): InsertStatements {\n\tconst table = physicalVectorTable(db);\n\treturn {\n\t\tcounts,\n\t\tinsertVector: db.prepare(`INSERT INTO ${table}\n\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`),\n\t\tinsertIndexedRow: db.prepare(`INSERT INTO validated_vector_rows\n\t\t(rowid,memory_id,model,chunk_index,content_hash,audit_state) VALUES(?,?,?,?,?,'valid')`),\n\t};\n}\n\nexport function prepareRemoveStatements(db: Database, counts: CountStatements): RemoveStatements {\n\tconst table = physicalVectorTable(db);\n\treturn {\n\t\tcounts,\n\t\tdeleteVector: db.prepare(`DELETE FROM ${table} WHERE rowid=?`),\n\t\tdeleteIndexedRow: db.prepare(\"DELETE FROM validated_vector_rows WHERE rowid=?\"),\n\t\tdecrementAuditCounts:\n\t\t\tdb.prepare(`UPDATE validated_vector_state SET pending_count=pending_count-?,\n\t\tinvalid_count=invalid_count-? WHERE id=1`),\n\t};\n}\n\nfunction physicalVectorTable(db: Database): \"memory_vectors\" | \"memory_vectors_v1\" {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\t// The v1 compatibility view owns legacy-delete bookkeeping and rejects inserts.\n\treturn layout.physicalName;\n}\n\nexport function prepareAuditStateStatements(db: Database): AuditStateStatements {\n\treturn {\n\t\tupdateRowState: db.prepare(\n\t\t\t\"UPDATE validated_vector_rows SET audit_state=?,reason=? WHERE rowid=?\",\n\t\t),\n\t\tupdateAuditCounts: db.prepare(`UPDATE validated_vector_state SET pending_count=pending_count+?,\n\t\tinvalid_count=invalid_count+? WHERE id=1`),\n\t};\n}\n","import type { Database } from \"../db.js\";\nimport { type VectorRowInput, vectorBytes } from \"./semantic-ranking.js\";\nimport {\n\tchangeCounts,\n\tfinishMutation,\n\ttype IndexedRow,\n\treadState,\n\trequireGenerationModel,\n\trequireWriter,\n\ttype VectorCatalog,\n} from \"./validated-vector-index-state.js\";\nimport {\n\ttype IndexStatement,\n\ttype InsertStatements,\n\tprepareCountStatements,\n\tprepareInsertStatements,\n\tprepareRemoveStatements,\n\ttype RemoveStatements,\n} from \"./validated-vector-index-statements.js\";\n\ninterface MemoryModelStatements {\n\trows: IndexStatement;\n\tremove: RemoveStatements;\n}\n\nexport interface ValidatedBatch {\n\twriterVersion: 1;\n\texpectedModel: string;\n\tmodel: string;\n\texpectedCount: number;\n\tmode: \"append\" | \"replace-memory-model\";\n\trows: readonly VectorRowInput[];\n}\n\nexport function requireModel(model: string): void {\n\tif (typeof model !== \"string\" || !model.trim()) throw new TypeError(\"vector_model_required\");\n}\n\nexport function requireVectorMetadata(row: Omit<VectorRowInput, \"vector\">): void {\n\tif (\n\t\t!Number.isSafeInteger(row.memoryId) ||\n\t\trow.memoryId <= 0 ||\n\t\t!Number.isSafeInteger(row.chunkIndex) ||\n\t\trow.chunkIndex < 0 ||\n\t\ttypeof row.contentHash !== \"string\" ||\n\t\t!row.contentHash.trim()\n\t) {\n\t\tthrow new TypeError(\"invalid_vector_metadata\");\n\t}\n}\n\nexport function removeRow(statements: RemoveStatements, row: IndexedRow): void {\n\tstatements.deleteVector.run(BigInt(row.rowid));\n\tstatements.deleteIndexedRow.run(row.rowid);\n\tchangeCounts(statements.counts, row.memory_id, row.model, -1);\n\tstatements.decrementAuditCounts.run(\n\t\tNumber(row.audit_state === \"pending\"),\n\t\tNumber(row.audit_state === \"invalid\"),\n\t);\n}\n\nexport function insertRow(\n\tstatements: InsertStatements,\n\trow: Omit<VectorRowInput, \"vector\">,\n\tmodel: string,\n\tbytes: Buffer,\n): void {\n\tconst result = statements.insertVector.run(\n\t\tbytes,\n\t\tBigInt(row.memoryId),\n\t\tBigInt(row.chunkIndex),\n\t\trow.contentHash,\n\t\tmodel,\n\t);\n\tconst rowid = Number(result.lastInsertRowid);\n\tif (!Number.isSafeInteger(rowid)) throw new RangeError(\"unsafe_vector_rowid\");\n\tstatements.insertIndexedRow.run(rowid, row.memoryId, model, row.chunkIndex, row.contentHash);\n\tchangeCounts(statements.counts, row.memoryId, model, 1);\n}\n\nfunction removeMemoryModel(\n\tstatements: MemoryModelStatements,\n\tmemoryId: number,\n\tmodel: string | null,\n): void {\n\tconst rows = statements.rows.all(model, memoryId) as IndexedRow[];\n\tfor (const row of rows) removeRow(statements.remove, row);\n}\n\nexport function writeValidatedBatch(db: Database, batch: ValidatedBatch): VectorCatalog {\n\trequireWriter(batch.writerVersion);\n\trequireModel(batch.model);\n\tif (batch.expectedModel !== batch.model) throw new TypeError(\"vector_model_mismatch\");\n\tif (!Number.isSafeInteger(batch.expectedCount) || batch.expectedCount !== batch.rows.length) {\n\t\tthrow new TypeError(\"vector_count_mismatch\");\n\t}\n\tif (batch.mode !== \"append\" && batch.mode !== \"replace-memory-model\") {\n\t\tthrow new TypeError(\"invalid_vector_write_mode\");\n\t}\n\tconst prepared = batch.rows.map((row) => {\n\t\trequireVectorMetadata(row);\n\t\treturn { ...row, bytes: vectorBytes(row.vector) };\n\t});\n\treturn db.transaction(() => {\n\t\tconst state = readState(db);\n\t\trequireGenerationModel(state, batch.model);\n\t\tif (batch.mode === \"replace-memory-model\" && !state.audit_started) {\n\t\t\tthrow new Error(\"start_audit_census_required\");\n\t\t}\n\t\tconst counts = prepareCountStatements(db);\n\t\tconst insert = prepareInsertStatements(db, counts);\n\t\tconst sourceExists = db.prepare(\"SELECT 1 FROM memory_items WHERE id=?\");\n\t\tlet removal: MemoryModelStatements | undefined;\n\t\tif (batch.mode === \"replace-memory-model\") {\n\t\t\tremoval = {\n\t\t\t\trows: db.prepare(\"SELECT * FROM validated_vector_rows WHERE model IS ? AND memory_id=?\"),\n\t\t\t\tremove: prepareRemoveStatements(db, counts),\n\t\t\t};\n\t\t}\n\t\tconst ids = new Set(prepared.map((row) => row.memoryId));\n\t\tfor (const id of ids) {\n\t\t\tif (!sourceExists.get(id)) {\n\t\t\t\tthrow new Error(\"vector_source_memory_missing\");\n\t\t\t}\n\t\t\tif (removal) removeMemoryModel(removal, id, batch.model);\n\t\t}\n\t\tfor (const row of prepared) insertRow(insert, row, batch.model, row.bytes);\n\t\treturn finishMutation(db);\n\t})();\n}\n\nexport function deleteValidatedVectors(\n\tdb: Database,\n\toptions: { writerVersion: 1; memoryId: number; model: string | null },\n): VectorCatalog {\n\trequireWriter(options.writerVersion);\n\tif (!Number.isSafeInteger(options.memoryId) || options.memoryId < 1)\n\t\tthrow new TypeError(\"invalid_memory_id\");\n\tif (options.model !== null) requireModel(options.model);\n\treturn db.transaction(() => {\n\t\tif (!readState(db).audit_started) throw new Error(\"start_audit_census_required\");\n\t\tremoveMemoryModel(\n\t\t\t{\n\t\t\t\trows: db.prepare(\"SELECT * FROM validated_vector_rows WHERE model IS ? AND memory_id=?\"),\n\t\t\t\tremove: prepareRemoveStatements(db, prepareCountStatements(db)),\n\t\t\t},\n\t\t\toptions.memoryId,\n\t\t\toptions.model,\n\t\t);\n\t\treturn finishMutation(db);\n\t})();\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"../db.js\";\nimport { inspectBytes } from \"./semantic-ranking.js\";\nimport { requireModel, requireVectorMetadata } from \"./validated-vector-index-mutations.js\";\nimport {\n\ttype AuditProgress,\n\tfinishMutation,\n\ttype IndexedRow,\n\tprogress,\n\treadState,\n\trefreshStatus,\n\trequireCatalog,\n\trequireLimit,\n\tupdateAuditState,\n\ttype VectorCatalog,\n} from \"./validated-vector-index-state.js\";\nimport {\n\ttype IndexStatement,\n\tprepareAuditStateStatements,\n} from \"./validated-vector-index-statements.js\";\n\n/** One metadata census per generation; vector blobs are read only by bounded audit batches. */\nexport function startAudit(\n\tdb: Database,\n\toptions: { knownModels: readonly string[] },\n): VectorCatalog {\n\tfor (const model of options.knownModels) requireModel(model);\n\treturn db.transaction(() => {\n\t\treadState(db);\n\t\tdb.exec(`DELETE FROM validated_vector_rows;\n\t\t\tINSERT INTO validated_vector_rows(rowid,memory_id,model,chunk_index,content_hash,audit_state)\n\t\t\t SELECT rowid,memory_id,model,chunk_index,content_hash,'pending' FROM memory_vectors;\n\t\t\tDELETE FROM validated_vector_models;\n\t\t\tINSERT INTO validated_vector_models(model_null,model_key,model,count)\n\t\t\t SELECT model IS NULL,COALESCE(model,''),model,COUNT(*) FROM validated_vector_rows GROUP BY model;\n\t\t\tUPDATE validated_vector_versions SET count=0,version=version+1;\n\t\t\tINSERT INTO validated_vector_versions(memory_id,model_null,model_key,model,version,count)\n\t\t\t SELECT memory_id,model IS NULL,COALESCE(model,''),model,1,COUNT(*)\n\t\t\t FROM validated_vector_rows GROUP BY memory_id,model\n\t\t\t ON CONFLICT(memory_id,model_null,model_key) DO UPDATE SET count=excluded.count;`);\n\t\tdb.prepare(`UPDATE validated_vector_state SET generation_id=?,revision=revision+1,\n\t\t\taudit_started=1,known_models=?,pending_count=(SELECT COUNT(*) FROM validated_vector_rows),\n\t\t\tinvalid_count=0 WHERE id=1`).run(\n\t\t\trandomUUID(),\n\t\t\tJSON.stringify([...new Set(options.knownModels)]),\n\t\t);\n\t\trefreshStatus(db);\n\t\treturn requireCatalog(db);\n\t})();\n}\n\nfunction rowRejection(\n\tstatements: { sourceExists: IndexStatement; vector: IndexStatement },\n\trow: IndexedRow,\n\tknownModels: Set<string>,\n): string | null {\n\tif (row.model === null || !knownModels.has(row.model)) return \"model\";\n\ttry {\n\t\trequireVectorMetadata({\n\t\t\tmemoryId: row.memory_id,\n\t\t\tchunkIndex: row.chunk_index,\n\t\t\tcontentHash: row.content_hash,\n\t\t});\n\t} catch {\n\t\treturn \"metadata\";\n\t}\n\tif (!statements.sourceExists.get(row.memory_id)) return \"metadata\";\n\tconst vector = statements.vector.get(BigInt(row.rowid)) as { embedding: Buffer } | undefined;\n\tif (!vector) throw new Error(\"audit_vector_row_missing_restart_required\");\n\treturn inspectBytes(vector.embedding);\n}\n\nexport function auditBatch(db: Database, options: { limit: number }): AuditProgress {\n\trequireLimit(options.limit);\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst state = readState(db);\n\t\t\tif (!state.audit_started) throw new Error(\"start_audit_required\");\n\t\t\tconst knownModels = new Set<string>(JSON.parse(state.known_models));\n\t\t\tconst rows = db\n\t\t\t\t.prepare(`SELECT * FROM validated_vector_rows\n\t\t\tWHERE audit_state='pending' ORDER BY rowid LIMIT ?`)\n\t\t\t\t.all(options.limit) as IndexedRow[];\n\t\t\tconst reads = {\n\t\t\t\tsourceExists: db.prepare(\"SELECT 1 FROM memory_items WHERE id=?\"),\n\t\t\t\tvector: db.prepare(\"SELECT embedding FROM memory_vectors WHERE rowid=?\"),\n\t\t\t};\n\t\t\tconst auditState = prepareAuditStateStatements(db);\n\t\t\tconst diagnostics: AuditProgress[\"diagnostics\"] = [];\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst reason = rowRejection(reads, row, knownModels);\n\t\t\t\tupdateAuditState(auditState, row, reason ? \"invalid\" : \"valid\", reason);\n\t\t\t\tif (reason) diagnostics.push({ rowid: row.rowid, reason });\n\t\t\t}\n\t\t\tfinishMutation(db);\n\t\t\treturn progress(db, rows.length, diagnostics);\n\t\t})\n\t\t.immediate();\n}\n","import { eq, or } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { columnExists, type Database, tableExists } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nconst SAME_PERSON_BINDING_PROVENANCE = new Set([\n\t\"user_confirmed_identity_setup\",\n\t\"recipient_invite\",\n\t\"exact_project_invite\",\n\t\"review_resolution\",\n]);\n\n/** Shared read-only resolver; authoritative bindings take precedence over legacy claims. */\nexport function resolveSameActorPeerIds(db: Database, actorId: string): string[] {\n\tconst sets = resolveBindings(db, actorId);\n\tif (!sets) return [];\n\tif (!tableExists(db, \"sync_peers\")) return [...sets.deviceIds].sort();\n\tconst hasAliasEvidence = [\"peer_device_id\", \"public_key\", \"pinned_fingerprint\"].every((column) =>\n\t\tcolumnExists(db, \"sync_peers\", column),\n\t);\n\tif (sets.boundDeviceIds.size > 0 && !hasAliasEvidence) return [...sets.deviceIds].sort();\n\tif (sets.boundDeviceIds.size > 0) resolveAliases(db, sets);\n\tconst legacyRows = drizzle(db, { schema })\n\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t.from(schema.syncPeers)\n\t\t.where(or(eq(schema.syncPeers.claimed_local_actor, 1), eq(schema.syncPeers.actor_id, actorId)))\n\t\t.all();\n\tfor (const row of legacyRows) {\n\t\tconst deviceId = String(row.peer_device_id ?? \"\").trim();\n\t\tif (deviceId && !sets.boundDeviceIds.has(deviceId)) sets.deviceIds.add(deviceId);\n\t}\n\treturn [...sets.deviceIds].sort();\n}\n\ntype BindingSets = {\n\tdeviceIds: Set<string>;\n\tboundDeviceIds: Set<string>;\n\tlocallyBoundDeviceIds: Set<string>;\n};\n\nfunction activeActor(db: Database, actorId: string, bindingCount: number): boolean {\n\tif (bindingCount === 0 || !tableExists(db, \"actors\")) return false;\n\tif (\n\t\t![\"actor_id\", \"status\", \"merged_into_actor_id\"].every((column) =>\n\t\t\tcolumnExists(db, \"actors\", column),\n\t\t)\n\t)\n\t\treturn false;\n\tconst actor = db\n\t\t.prepare(\"SELECT status, merged_into_actor_id FROM actors WHERE actor_id = ?\")\n\t\t.get(actorId) as { status: string; merged_into_actor_id: string | null } | undefined;\n\treturn actor?.status === \"active\" && !actor.merged_into_actor_id;\n}\n\nfunction resolveBindings(db: Database, actorId: string): BindingSets | null {\n\tconst sets: BindingSets = {\n\t\tdeviceIds: new Set(),\n\t\tboundDeviceIds: new Set(),\n\t\tlocallyBoundDeviceIds: new Set(),\n\t};\n\tconst hasIdentityBindings =\n\t\ttableExists(db, \"identity_devices\") &&\n\t\t[\"device_id\", \"identity_id\", \"status\", \"provenance\"].every((column) =>\n\t\t\tcolumnExists(db, \"identity_devices\", column),\n\t\t);\n\tif (tableExists(db, \"identity_devices\") && !hasIdentityBindings) return null;\n\tif (!hasIdentityBindings) return sets;\n\tconst bindings = db\n\t\t.prepare(\"SELECT device_id, identity_id, status, provenance FROM identity_devices\")\n\t\t.all() as Array<{\n\t\tdevice_id: string;\n\t\tidentity_id: string;\n\t\tstatus: string;\n\t\tprovenance: string;\n\t}>;\n\tconst localActorIsActive = activeActor(db, actorId, bindings.length);\n\tfor (const binding of bindings) {\n\t\tconst deviceId = String(binding.device_id ?? \"\").trim();\n\t\tif (!deviceId) continue;\n\t\tsets.boundDeviceIds.add(deviceId);\n\t\tif (\n\t\t\tlocalActorIsActive &&\n\t\t\tString(binding.identity_id ?? \"\").trim() === actorId &&\n\t\t\tbinding.status === \"active\" &&\n\t\t\tSAME_PERSON_BINDING_PROVENANCE.has(binding.provenance)\n\t\t) {\n\t\t\tsets.deviceIds.add(deviceId);\n\t\t\tsets.locallyBoundDeviceIds.add(deviceId);\n\t\t}\n\t}\n\treturn sets;\n}\n\ntype PeerEvidence = {\n\tpeer_device_id: string;\n\tpublic_key: string | null;\n\tpinned_fingerprint: string | null;\n};\n\nfunction validatedFingerprint(row: PeerEvidence): string | null {\n\tconst publicKey = String(row.public_key ?? \"\").trim();\n\tconst pinned = String(row.pinned_fingerprint ?? \"\").trim();\n\tif (!publicKey) return pinned || null;\n\tconst derived = fingerprintPublicKey(publicKey);\n\treturn pinned && pinned !== derived ? null : pinned || derived;\n}\n\nfunction provenFingerprint(row: PeerEvidence): string | null {\n\treturn String(row.public_key ?? \"\").trim() ? validatedFingerprint(row) : null;\n}\n\nfunction resolveAliases(db: Database, sets: BindingSets): void {\n\tconst { deviceIds, boundDeviceIds } = sets;\n\tconst peerEvidence = db\n\t\t.prepare(\"SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers\")\n\t\t.all() as PeerEvidence[];\n\tconst { boundFingerprints, locallyBoundFingerprints } = resolveBoundFingerprints(\n\t\tpeerEvidence,\n\t\tsets,\n\t);\n\tfor (const row of peerEvidence) {\n\t\tconst deviceId = String(row.peer_device_id ?? \"\").trim();\n\t\tconst fingerprint = validatedFingerprint(row);\n\t\tif (!deviceId || !fingerprint || !boundFingerprints.has(fingerprint)) continue;\n\t\tconst hasAuthoritativeBinding = boundDeviceIds.has(deviceId);\n\t\tboundDeviceIds.add(deviceId);\n\t\tif (\n\t\t\t!hasAuthoritativeBinding &&\n\t\t\tlocallyBoundFingerprints.has(fingerprint) &&\n\t\t\tprovenFingerprint(row)\n\t\t) {\n\t\t\tdeviceIds.add(deviceId);\n\t\t}\n\t}\n}\n\nfunction resolveBoundFingerprints(peerEvidence: PeerEvidence[], sets: BindingSets) {\n\tconst { boundDeviceIds, locallyBoundDeviceIds } = sets;\n\tconst boundFingerprints = new Set<string>();\n\tconst locallyBoundFingerprints = new Set<string>();\n\tconst conflictingBoundFingerprints = new Set<string>();\n\tfor (const row of peerEvidence) {\n\t\tconst deviceId = String(row.peer_device_id ?? \"\").trim();\n\t\tconst fingerprint = validatedFingerprint(row);\n\t\tif (!deviceId || !fingerprint || !boundDeviceIds.has(deviceId)) continue;\n\t\tboundFingerprints.add(fingerprint);\n\t\tif (locallyBoundDeviceIds.has(deviceId)) {\n\t\t\tif (provenFingerprint(row)) locallyBoundFingerprints.add(fingerprint);\n\t\t} else {\n\t\t\tconflictingBoundFingerprints.add(fingerprint);\n\t\t}\n\t}\n\tfor (const fingerprint of conflictingBoundFingerprints)\n\t\tlocallyBoundFingerprints.delete(fingerprint);\n\treturn { boundFingerprints, locallyBoundFingerprints };\n}\n","/** Persisted vector writer contract and readiness-gated semantic ranking. */\nimport type { Database } from \"../db.js\";\nimport {\n\ttype RankingRequest,\n\ttype RankingResult,\n\trankPrevalidatedSnapshot,\n\tresolveCatalogModels,\n} from \"./semantic-ranking.js\";\nimport {\n\ttype CandidateVersion,\n\tisSearchableVectorCatalog,\n\treadCandidateVersions,\n\treadCatalog,\n\treadSearchableModelLabels,\n\tsnapshot,\n} from \"./validated-vector-index-state.js\";\n\nexport { auditBatch, startAudit } from \"./validated-vector-index-audit.js\";\nexport {\n\tdeleteValidatedVectors,\n\ttype ValidatedBatch,\n\twriteValidatedBatch,\n} from \"./validated-vector-index-mutations.js\";\nexport {\n\ttype AuditProgress,\n\ttype CandidateVersion,\n\tinitializeValidatedIndex,\n\tinvalidateValidatedIndex,\n\tisSearchableVectorCatalog,\n\treadCandidateVersions,\n\treadCatalog,\n\treadSearchableModelLabels,\n\ttype VectorCatalog,\n} from \"./validated-vector-index-state.js\";\n\nexport interface IndexedRanking extends RankingResult {\n\tgenerationId: string;\n\trevision: number;\n\tmodels: string[];\n\tcandidateVersions: CandidateVersion[];\n}\n\n/** Reuses a caller-owned read transaction; no DDL, audit, BLOB hashes or model-catalog vec0 scan. */\nexport function rankValidatedIndex(db: Database, request: RankingRequest): IndexedRanking | null {\n\treturn snapshot(db, () => {\n\t\tconst catalog = readCatalog(db);\n\t\tif (!isSearchableVectorCatalog(db, catalog)) return null;\n\t\tconst models = resolveCatalogModels(\n\t\t\trequest.query.model,\n\t\t\treadSearchableModelLabels(db, catalog),\n\t\t\tcatalog.migration,\n\t\t);\n\t\tif (!models.length) return null;\n\t\tconst ranked = rankPrevalidatedSnapshot(db, request, {\n\t\t\tmodels,\n\t\t\tacceptedIds: null,\n\t\t\tindexedRows: true,\n\t\t});\n\t\tconst candidateVersions = readCandidateVersions(db, {\n\t\t\tmemoryIds: ranked.results.map((row) => row.id),\n\t\t\tmodels,\n\t\t});\n\t\treturn {\n\t\t\t...ranked,\n\t\t\tgenerationId: catalog.generationId,\n\t\t\trevision: catalog.revision,\n\t\t\tmodels,\n\t\t\tcandidateVersions,\n\t\t};\n\t});\n}\n","import { createHash } from \"node:crypto\";\nimport type { Database } from \"../db.js\";\nimport { resolveSameActorPeerIds } from \"../same-actor-peers.js\";\nimport type { AutomaticContext } from \"../types.js\";\nimport type { RankInput, RankOutput } from \"./semantic-worker-protocol.js\";\nimport {\n\tisSearchableVectorCatalog,\n\trankValidatedIndex,\n\treadCatalog,\n} from \"./validated-vector-index.js\";\n\nexport function contentIdentity(row: Record<string, unknown>): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(row)).digest(\"hex\");\n}\n\nexport function summarySessionId(\n\tdb: Database,\n\tcontext: AutomaticContext | null | undefined,\n): number | null | undefined {\n\tif (context === undefined) return undefined;\n\tif (context === null) return null;\n\tconst source = context.source.trim().toLowerCase();\n\tconst streamId = context.hostSessionId.trim();\n\tif (!source || !streamId || streamId.toLowerCase() === \"unknown\") return null;\n\tconst row = db\n\t\t.prepare(\"SELECT session_id FROM opencode_sessions WHERE source = ? AND stream_id = ? LIMIT 1\")\n\t\t.get(source, streamId) as { session_id: number | null } | undefined;\n\treturn row?.session_id ?? null;\n}\n\n/** Authorization, continuity, model selection, ranking and identities share one short read snapshot. */\nexport function rankWorkerInput(db: Database, input: RankInput): RankOutput | null {\n\treturn db.transaction(() => {\n\t\tconst catalog = readCatalog(db);\n\t\tif (!isSearchableVectorCatalog(db, catalog) || catalog.generationId !== input.generationId)\n\t\t\treturn null;\n\t\tconst claimedDeviceIds = resolveSameActorPeerIds(db, input.proof.actorId);\n\t\tconst ranked = rankValidatedIndex(db, {\n\t\t\tquery: { model: input.embeddingIdentity, vectors: [input.embedding] },\n\t\t\tlimit: input.limit,\n\t\t\tfilters: input.filters,\n\t\t\tcontext: {\n\t\t\t\t...input.proof,\n\t\t\t\tclaimedDeviceIds,\n\t\t\t\tlegacyActorIds: claimedDeviceIds.map((id) => `legacy-sync:${id}`),\n\t\t\t\tscopeVisibilityDb: db,\n\t\t\t},\n\t\t\tsummarySessionId: summarySessionId(db, input.automaticContext),\n\t\t});\n\t\tif (!ranked || ranked.generationId !== input.generationId) return null;\n\t\treturn {\n\t\t\tgenerationId: ranked.generationId,\n\t\t\trevision: ranked.revision,\n\t\t\tmodels: ranked.models,\n\t\t\tcandidateVersions: ranked.candidateVersions,\n\t\t\tcandidates: ranked.results.map((row) => {\n\t\t\t\tconst raw = db.prepare(\"SELECT * FROM memory_items WHERE id = ?\").get(row.id) as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\tunknown\n\t\t\t\t>;\n\t\t\t\treturn {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tdistance: row.distance,\n\t\t\t\t\tcontentIdentity: contentIdentity(raw),\n\t\t\t\t};\n\t\t\t}),\n\t\t};\n\t})();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,GACf,GACA,GACA,GACO;CACF,MAAS,GAAI,QAAQ,KACT,EACf,QAAQ,2IAC6E,CAAC,CACtF,IAAI,eAAe,SAAS,KAAY,KAAW,SAAS,GAC1D,GAAU,MAAU,MAAM,gCAAgC;AAC/D;AAEA,SAAS,EAAS,GAAc,GAAuB;CACtD,OACC,EAAG,QAAQ,+DAA+D,CAAC,CAAC,IAAI,CAAI,MACpF,KAAA;AAEF;AAGA,SAAgB,GAA+B,GAAoB;CAClE,EAAG,KAAK,4aAWL;CACH,KAAK,IAAM,KAAS,CAAC,wBAAwB,+BAA+B,GAC3E,EAAG,KAAK,gCAAgC,EAAM;sBAC1B,EAAM;;kCAEM,EAAM;sBAClB,EAAM;;kCAEM,EAAM;sBAClB,EAAM;gCACI,EAAM;qEAC+B;AAErE;AAEA,SAAS,GAAa,GAAmC;CAExD,OADK,EA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AAc;AAC3B;AAGA,SAAgB,GAAgB,GAAc,GAAqC;CAClF,OAAO,EAAG,kBAAkB;EAC3B,IAAM,IAAU,GAAY,CAAE;EAC9B,IAAI,CAAC,GAA0B,GAAI,CAAO,KAAK,EAAQ,iBAAiB,EAAM,cAC7E,OAAO;EACR,IAAM,IAAmB,GAAwB,GAAI,EAAM,MAAM,OAAO,GAClE,IAAS,GAAmB,GAAI;GACrC,OAAO;IAAE,OAAO,EAAM;IAAmB,SAAS,CAAC,EAAM,SAAS;GAAE;GACpE,OAAO,EAAM;GACb,SAAS,EAAM;GACf,SAAS;IACR,GAAG,EAAM;IACT;IACA,gBAAgB,EAAiB,KAAK,MAAO,eAAe,GAAI;IAChE,mBAAmB;GACpB;GACA,kBAAkB,GAAiB,GAAI,EAAM,gBAAgB;EAC9D,CAAC;EAED,OADI,CAAC,KAAU,EAAO,iBAAiB,EAAM,eAAqB,OAC3D;GACN,cAAc,EAAO;GACrB,UAAU,EAAO;GACjB,QAAQ,EAAO;GACf,mBAAmB,EAAO;GAC1B,YAAY,EAAO,QAAQ,KAAK,MAAQ;IACvC,IAAM,IAAM,EAAG,QAAQ,yCAAyC,CAAC,CAAC,IAAI,EAAI,EAAE;IAI5E,OAAO;KACN,IAAI,EAAI;KACR,UAAU,EAAI;KACd,iBAAiB,GAAgB,CAAG;IACrC;GACD,CAAC;EACF;CACD,CAAC,CAAC,CAAC;AACJ"}
|
|
1
|
+
{"version":3,"file":"semantic-worker-ranking-D9bhmrS_.js","names":[],"sources":["../src/memory-local-capture.ts","../src/memory-source-identity.ts","../src/memory-creation-provenance.ts","../src/home.ts","../src/observer-config.ts","../src/database-runtime-primitives.ts","../src/memory-retirement-delivery-schema.ts","../src/memory-scope-retirement.ts","../src/memory-ownership-recovery-schema.ts","../src/repository-discovery-index.ts","../src/summary-memory.ts","../src/test-schema.generated.ts","../src/usage-aggregate-index.ts","../src/vector-corpus-epoch.ts","../src/schema-bootstrap.ts","../src/db.ts","../src/schema.ts","../src/sync-identity.ts","../src/project.ts","../src/coordinator-auth-browser-schema-upgrade.ts","../src/coordinator-device-ownership-schema.ts","../src/better-sqlite-coordinator-store.ts","../src/coordinator-sync-config.ts","../src/recipient-policy-deny-overlay.ts","../src/scope-membership-snapshot.ts","../src/scope-membership-evidence.ts","../src/sync-auth.ts","../src/sync-http-client.ts","../src/scope-membership-cache.ts","../src/wildcard-match.ts","../src/scope-resolution.ts","../src/filters.ts","../src/embeddings.ts","../src/semantic-query.ts","../src/vector-layout.ts","../src/semantic/semantic-ranking.ts","../src/semantic/validated-vector-index-state.ts","../src/semantic/validated-vector-index-statements.ts","../src/semantic/validated-vector-index-mutations.ts","../src/semantic/validated-vector-index-audit.ts","../src/same-actor-peers.ts","../src/semantic/validated-vector-index.ts","../src/semantic/semantic-worker-ranking.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"./db.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface CaptureBirth {\n\tcapture_id: string;\n}\n\ninterface DeviceTuple {\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n}\n\nexport interface LocalCreationContext {\n\texpectedPublicKey?: string;\n\tloadExpectedPublicKey?: () => string | undefined;\n}\n\nexport interface LocalCaptureAdoptionContext extends LocalCreationContext {\n\tactorId?: string;\n\truntimeDeviceId?: string;\n}\n\nexport function assertLocalCaptureAdoptionActors(\n\tdb: Database,\n\tdeviceId: string,\n\tactorId?: string,\n): void {\n\tif (!hasTable(db, \"actors\")) return;\n\tconst conflict = db\n\t\t.prepare(`SELECT 1 FROM actors WHERE actor_id IN (?, ?, ?)\n\t\tAND (is_local <> 1 OR status <> 'active' OR merged_into_actor_id IS NOT NULL) LIMIT 1`)\n\t\t.get(\"local:local\", `local:${deviceId}`, actorId ?? `local:${deviceId}`);\n\tif (conflict) throw new Error(\"device_adoption_actor_conflict\");\n}\n\nfunction hasTable(db: Database, name: string): boolean {\n\treturn (\n\t\tdb.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\").get(name) !==\n\t\tundefined\n\t);\n}\n\n/** Schema only: the unsigned identity is born in the first genuine creation transaction. */\nexport function ensureMemoryLocalCaptureSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_local_capture (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tcapture_id TEXT NOT NULL UNIQUE,\n\t\tcreated_at TEXT NOT NULL\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_local_capture_adoption (\n\t\tcapture_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_local_capture(capture_id),\n\t\tdevice_id TEXT NOT NULL,\n\t\tpublic_key TEXT NOT NULL,\n\t\tfingerprint TEXT NOT NULL,\n\t\tcreated_at TEXT NOT NULL\n\t);`);\n\tfor (const table of [\"memory_local_capture\", \"memory_local_capture_adoption\"]) {\n\t\tdb.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_no_update\n\t\t\tBEFORE UPDATE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_delete\n\t\t\tBEFORE DELETE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_replace\n\t\t\tBEFORE INSERT ON ${table}\n\t\t\tWHEN EXISTS (SELECT 1 FROM ${table})\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;`);\n\t}\n}\n\nfunction captureBirth(db: Database): CaptureBirth | null {\n\tif (!hasTable(db, \"memory_local_capture\")) return null;\n\treturn (\n\t\t(db.prepare(\"SELECT capture_id FROM memory_local_capture WHERE id = 1\").get() as\n\t\t\t| CaptureBirth\n\t\t\t| undefined) ?? null\n\t);\n}\n\n/** An explicit ensure may finish a pending birth, but never reassociate an adopted one. */\nexport function hasPendingLocalCapture(db: Database): boolean {\n\tconst birth = captureBirth(db);\n\tif (!birth || !hasTable(db, \"memory_local_capture_adoption\")) return false;\n\treturn !db\n\t\t.prepare(\"SELECT 1 FROM memory_local_capture_adoption WHERE capture_id = ?\")\n\t\t.get(birth.capture_id);\n}\n\nfunction deviceTuple(db: Database): DeviceTuple | null {\n\tif (!hasTable(db, \"sync_device\")) return null;\n\tconst rows = db\n\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t.all() as DeviceTuple[];\n\treturn rows.length === 1 ? (rows[0] ?? null) : null;\n}\n\nfunction publicKeyBytes(value: string): string | null {\n\tconst [type, bytes] = value.trim().split(/\\s+/u);\n\treturn type === \"ssh-ed25519\" && bytes ? `${type} ${bytes}` : null;\n}\n\nexport function matchesLocalCaptureRuntime(\n\ttuple: DeviceTuple,\n\tdeviceId: string,\n\tpublicKey: string | undefined,\n): boolean {\n\tconst stored = publicKeyBytes(tuple.public_key);\n\treturn (\n\t\ttuple.device_id === deviceId &&\n\t\tstored !== null &&\n\t\tpublicKey !== undefined &&\n\t\tpublicKeyBytes(publicKey) === stored &&\n\t\tfingerprintPublicKey(tuple.public_key) === tuple.fingerprint\n\t);\n}\n\n/** Never called by reads, imports, bootstrap, or replication. */\nexport function getOrCreateLocalCaptureId(db: Database): string {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst birth = captureBirth(db);\n\tif (birth) return birth.capture_id;\n\tensureMemoryLocalCaptureSchema(db);\n\tconst captureId = `local-capture-v1:${randomUUID()}`;\n\tdb.prepare(\"INSERT INTO memory_local_capture(id, capture_id, created_at) VALUES (1, ?, ?)\").run(\n\t\tcaptureId,\n\t\tnew Date().toISOString(),\n\t);\n\treturn captureId;\n}\n\n/** Retain a one-time association, without renaming any immutable source binding. */\nexport function adoptLocalCapture(\n\tdb: Database,\n\tdeviceId: string,\n\tcontext: LocalCaptureAdoptionContext,\n): void {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst birth = captureBirth(db);\n\tif (!birth) return;\n\tif (\n\t\tcontext.runtimeDeviceId &&\n\t\tcontext.runtimeDeviceId !== \"local\" &&\n\t\tcontext.runtimeDeviceId !== deviceId\n\t)\n\t\treturn;\n\tconst tuple = deviceTuple(db);\n\tconst publicKey = context.expectedPublicKey ?? context.loadExpectedPublicKey?.();\n\tif (!tuple || !matchesLocalCaptureRuntime(tuple, deviceId, publicKey)) return;\n\tconst existing = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, public_key, fingerprint FROM memory_local_capture_adoption WHERE capture_id = ?\",\n\t\t)\n\t\t.get(birth.capture_id) as DeviceTuple | undefined;\n\tif (existing) {\n\t\tif (\n\t\t\texisting.device_id !== tuple.device_id ||\n\t\t\texisting.public_key !== tuple.public_key ||\n\t\t\texisting.fingerprint !== tuple.fingerprint\n\t\t)\n\t\t\tthrow new Error(\"memory_local_capture_adoption_conflict\");\n\t\treturn;\n\t}\n\tassertLocalCaptureAdoptionActors(db, deviceId, context.actorId);\n\tdb.prepare(`INSERT INTO memory_local_capture_adoption(capture_id, device_id, public_key, fingerprint, created_at)\n\t\tVALUES (?, ?, ?, ?, ?)`).run(\n\t\tbirth.capture_id,\n\t\ttuple.device_id,\n\t\ttuple.public_key,\n\t\ttuple.fingerprint,\n\t\tnew Date().toISOString(),\n\t);\n}\n\n/** Read-only: no DDL, key generation, identity repair, actor union, or origin inference. */\nexport function localCreationSourceIds(\n\tdb: Database,\n\tdeviceId: string,\n\tcontext: LocalCreationContext = {},\n): string[] {\n\tif (\n\t\t!hasTable(db, \"memory_source_bindings\") ||\n\t\t!db\n\t\t\t.prepare(\"SELECT 1 FROM memory_source_bindings WHERE evidence = 'local_creation' LIMIT 1\")\n\t\t\t.get()\n\t)\n\t\treturn [];\n\tconst birth = captureBirth(db);\n\tconst tuple = deviceTuple(db);\n\tif (!tuple) {\n\t\tconst noDevice =\n\t\t\t!hasTable(db, \"sync_device\") || !db.prepare(\"SELECT 1 FROM sync_device LIMIT 1\").get();\n\t\tconst adopted =\n\t\t\thasTable(db, \"memory_local_capture_adoption\") &&\n\t\t\tdb.prepare(\"SELECT 1 FROM memory_local_capture_adoption LIMIT 1\").get();\n\t\treturn noDevice && !adopted && deviceId === \"local\" && birth ? [birth.capture_id] : [];\n\t}\n\tif (tuple.device_id !== deviceId) return [];\n\tconst publicKey = context.expectedPublicKey ?? context.loadExpectedPublicKey?.();\n\tif (!matchesLocalCaptureRuntime(tuple, deviceId, publicKey)) return [];\n\tconst sources = [deviceId];\n\tif (!birth || !hasTable(db, \"memory_local_capture_adoption\")) return sources;\n\tconst adoption = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, public_key, fingerprint FROM memory_local_capture_adoption WHERE capture_id = ?\",\n\t\t)\n\t\t.get(birth.capture_id) as DeviceTuple | undefined;\n\tif (\n\t\tadoption &&\n\t\tadoption.device_id === tuple.device_id &&\n\t\tadoption.public_key === tuple.public_key &&\n\t\tadoption.fingerprint === tuple.fingerprint\n\t)\n\t\tsources.push(birth.capture_id);\n\treturn sources;\n}\n\nexport function hasLocalCreationBinding(\n\tdb: Database,\n\tentityId: string,\n\tsourceIds: readonly string[],\n): boolean {\n\tif (!sourceIds.length || !hasTable(db, \"memory_source_bindings\")) return false;\n\tconst binding = db\n\t\t.prepare(\"SELECT source_device_id, evidence FROM memory_source_bindings WHERE entity_id = ?\")\n\t\t.get(entityId) as { source_device_id: string; evidence: string } | undefined;\n\treturn binding?.evidence === \"local_creation\" && sourceIds.includes(binding.source_device_id);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"./db.js\";\nimport {\n\tgetOrCreateLocalCaptureId,\n\ttype LocalCreationContext,\n\tmatchesLocalCaptureRuntime,\n} from \"./memory-local-capture.js\";\n\nconst PREFIX = \"memory-source-v1:\";\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;\n\nexport interface VerifiedMemorySource {\n\tentityId: string;\n\tsourceDeviceId: string;\n\tevidence: \"local_creation\" | \"authenticated_namespace\";\n}\n\n/** Additive prerequisite only; no existing capture or wire protocol is switched on here. */\nexport function ensureMemorySourceIdentitySchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_source_bindings (\n\t\tentity_id TEXT PRIMARY KEY,\n\t\tsource_device_id TEXT NOT NULL,\n\t\tevidence TEXT NOT NULL CHECK(evidence IN ('local_creation', 'authenticated_namespace')),\n\t\tcreated_at TEXT NOT NULL\n\t);\n\tCREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_update\n\tBEFORE UPDATE ON memory_source_bindings\n\tBEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_delete\n\tBEFORE DELETE ON memory_source_bindings\n\tBEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_replace\n\tBEFORE INSERT ON memory_source_bindings\n\tWHEN EXISTS (SELECT 1 FROM memory_source_bindings WHERE entity_id = NEW.entity_id)\n\tBEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;`);\n}\n\nfunction validDeviceId(value: string): boolean {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\n/** Parsing is not authentication. It identifies the namespace a verified sender must own. */\nexport function memorySourceNamespace(entityId: string): string | null {\n\tif (typeof entityId !== \"string\" || entityId.length > 1500 || !entityId.startsWith(PREFIX))\n\t\treturn null;\n\tconst [encoded, nonce, extra] = entityId.slice(PREFIX.length).split(\":\");\n\tif (!encoded || !nonce || extra !== undefined || !UUID.test(nonce)) return null;\n\tconst source = Buffer.from(encoded, \"base64url\").toString(\"utf8\");\n\tif (!validDeviceId(source) || Buffer.from(source).toString(\"base64url\") !== encoded) return null;\n\treturn source;\n}\n\nexport function getVerifiedMemorySource(\n\tdb: Database,\n\tentityId: string,\n): VerifiedMemorySource | null {\n\tconst row = db\n\t\t.prepare(\"SELECT source_device_id, evidence FROM memory_source_bindings WHERE entity_id = ?\")\n\t\t.get(entityId) as\n\t\t| { source_device_id: string; evidence: VerifiedMemorySource[\"evidence\"] }\n\t\t| undefined;\n\tif (!row) return null;\n\treturn { entityId, sourceDeviceId: row.source_device_id, evidence: row.evidence };\n}\n\nfunction persistBinding(db: Database, binding: VerifiedMemorySource): VerifiedMemorySource {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst existing = getVerifiedMemorySource(db, binding.entityId);\n\tif (existing) {\n\t\tif (existing.sourceDeviceId !== binding.sourceDeviceId)\n\t\t\tthrow new Error(\"memory_source_binding_conflict\");\n\t\treturn existing;\n\t}\n\tdb.prepare(`INSERT INTO memory_source_bindings(entity_id, source_device_id, evidence, created_at)\n\t\tVALUES (?, ?, ?, ?)`).run(\n\t\tbinding.entityId,\n\t\tbinding.sourceDeviceId,\n\t\tbinding.evidence,\n\t\tnew Date().toISOString(),\n\t);\n\treturn binding;\n}\n\n/** Allocate inside the transaction creating a new memory/copy; never rename a historical UUID. */\nexport function allocateLocalMemorySource(db: Database): VerifiedMemorySource {\n\tconst rows = db.prepare(\"SELECT device_id FROM sync_device\").all() as Array<{\n\t\tdevice_id: string;\n\t}>;\n\tconst source = rows[0]?.device_id;\n\tif (rows.length !== 1 || !source || !validDeviceId(source))\n\t\tthrow new Error(\"memory_source_local_device_required\");\n\tconst entityId = `${PREFIX}${Buffer.from(source).toString(\"base64url\")}:${randomUUID()}`;\n\treturn persistBinding(db, { entityId, sourceDeviceId: source, evidence: \"local_creation\" });\n}\n\n/** Genuine new captures only. Unsigned capture namespaces are never network-authenticated. */\nexport function allocateLocalCaptureMemorySource(\n\tdb: Database,\n\truntimeDeviceId: string,\n\tcontext: LocalCreationContext = {},\n): VerifiedMemorySource | null {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tlet rows: Array<{\n\t\tdevice_id: string;\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t}> = [];\n\tif (db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sync_device'\").get())\n\t\trows = db\n\t\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t\t.all() as typeof rows;\n\tif (rows.length > 0) {\n\t\tconst tuple = rows[0];\n\t\tif (\n\t\t\trows.length !== 1 ||\n\t\t\t!tuple ||\n\t\t\ttuple.device_id !== runtimeDeviceId ||\n\t\t\t!validDeviceId(runtimeDeviceId)\n\t\t)\n\t\t\treturn null;\n\t\tconst publicKey = context.expectedPublicKey ?? context.loadExpectedPublicKey?.();\n\t\tif (!matchesLocalCaptureRuntime(tuple, runtimeDeviceId, publicKey)) return null;\n\t\treturn allocateLocalMemorySource(db);\n\t}\n\tif (runtimeDeviceId !== \"local\") return null;\n\tconst sourceDeviceId = getOrCreateLocalCaptureId(db);\n\treturn persistBinding(db, {\n\t\tentityId: `memory-local-capture-v1:${Buffer.from(sourceDeviceId).toString(\"base64url\")}:${randomUUID()}`,\n\t\tsourceDeviceId,\n\t\tevidence: \"local_creation\",\n\t});\n}\n\n/**\n * Internal auth boundary: verifiedPeerDeviceId MUST come from successful transport\n * authentication, never op.device_id, payload origin, a form field, or a signature claim.\n * The namespace authenticates NEW identities, including absent rows. It cannot prove\n * ownership of a historical unqualified UUID. Forwarded claims are not accepted.\n */\nexport function verifyAuthenticatedMemorySource(\n\tdb: Database,\n\tinput: { entityId: string; verifiedPeerDeviceId: string },\n): VerifiedMemorySource {\n\tconst namespace = memorySourceNamespace(input.entityId);\n\tif (!namespace) throw new Error(\"memory_source_verification_required\");\n\tif (namespace !== input.verifiedPeerDeviceId) throw new Error(\"memory_source_sender_mismatch\");\n\treturn persistBinding(db, {\n\t\tentityId: input.entityId,\n\t\tsourceDeviceId: namespace,\n\t\tevidence: \"authenticated_namespace\",\n\t});\n}\n\n/** Retirement consumers consult immutable proof, never mutable memory origin metadata. */\nexport function assertVerifiedMemorySource(\n\tdb: Database,\n\tentityId: string,\n\tsourceDeviceId: string,\n): void {\n\tconst binding = getVerifiedMemorySource(db, entityId);\n\tif (!binding) throw new Error(\"memory_source_verification_required\");\n\tif (binding.sourceDeviceId !== sourceDeviceId) throw new Error(\"memory_source_sender_mismatch\");\n}\n","import type { Database } from \"./db.js\";\nimport { getVerifiedMemorySource } from \"./memory-source-identity.js\";\n\n// Actor/workspace aliases and replication clocks may change during local adoption.\n// Scope and user-facing content must still match the immutable creation snapshot.\nconst CREATION_CONTENT_SQL = `json_array(memory_items.kind, memory_items.title,\n\tmemory_items.subtitle, memory_items.body_text, memory_items.confidence,\n\tmemory_items.tags_text, memory_items.visibility, memory_items.workspace_kind,\n\tmemory_items.origin_source, memory_items.trust_state, memory_items.narrative,\n\tmemory_items.facts, memory_items.concepts, memory_items.files_read,\n\tmemory_items.files_modified, memory_items.user_prompt_id, memory_items.prompt_number,\n\tmemory_items.project, memory_items.active, memory_items.deleted_at,\n\tjson_remove(CASE WHEN json_valid(memory_items.metadata_json)\n\t\tTHEN memory_items.metadata_json ELSE '{}' END, '$.clock_device_id', '$.import_key'))`;\n\nfunction hasTable(db: Database, name: string): boolean {\n\treturn (\n\t\tdb.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\").get(name) !==\n\t\tundefined\n\t);\n}\n\nfunction ensureCreationProvenanceSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_local_creation_snapshots (\n\t\tentity_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_source_bindings(entity_id),\n\t\tscope_id TEXT,\n\t\tcontent_json TEXT NOT NULL,\n\t\tsource_public_key TEXT,\n\t\tsource_fingerprint TEXT,\n\t\tcreated_at TEXT NOT NULL\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_foreign_revisions (\n\t\tentity_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_source_bindings(entity_id),\n\t\twrite_path TEXT NOT NULL CHECK(write_path IN ('replication', 'bootstrap', 'import')),\n\t\tcreated_at TEXT NOT NULL\n\t);`);\n\tfor (const table of [\"memory_local_creation_snapshots\", \"memory_foreign_revisions\"]) {\n\t\tdb.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_no_update BEFORE UPDATE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_creation_provenance_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_delete BEFORE DELETE ON ${table}\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_creation_provenance_immutable'); END;\n\t\t\tCREATE TRIGGER IF NOT EXISTS ${table}_no_replace BEFORE INSERT ON ${table}\n\t\t\tWHEN EXISTS (SELECT 1 FROM ${table} WHERE entity_id = NEW.entity_id)\n\t\t\tBEGIN SELECT RAISE(ABORT, 'memory_creation_provenance_immutable'); END;`);\n\t}\n}\n\n/** Only a genuine creation/copy transaction can record the original row. No backfill. */\nexport function recordLocalCreationSnapshot(db: Database, memoryId: number): void {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tconst row = db.prepare(\"SELECT import_key FROM memory_items WHERE id = ?\").get(memoryId) as\n\t\t| { import_key: string | null }\n\t\t| undefined;\n\tif (\n\t\t!row?.import_key ||\n\t\tgetVerifiedMemorySource(db, row.import_key)?.evidence !== \"local_creation\"\n\t)\n\t\treturn;\n\tensureCreationProvenanceSchema(db);\n\tlet publicKeySql = \"NULL\";\n\tlet fingerprintSql = \"NULL\";\n\tif (hasTable(db, \"sync_device\")) {\n\t\tpublicKeySql =\n\t\t\t\"(SELECT public_key FROM sync_device WHERE device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = memory_items.import_key))\";\n\t\tfingerprintSql =\n\t\t\t\"(SELECT fingerprint FROM sync_device WHERE device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = memory_items.import_key))\";\n\t}\n\tdb.prepare(`INSERT INTO memory_local_creation_snapshots(entity_id, scope_id, content_json, source_public_key, source_fingerprint, created_at)\n\t\tSELECT import_key, scope_id, ${CREATION_CONTENT_SQL},\n\t\t${publicKeySql}, ${fingerprintSql},\n\t\t? FROM memory_items WHERE id = ?`).run(new Date().toISOString(), memoryId);\n}\n\n/** The inbound write path, not peer-supplied clocks/origins, records permanent negative proof. */\nexport function recordForeignMemoryRevision(\n\tdb: Database,\n\tentityId: string,\n\twritePath: \"replication\" | \"bootstrap\" | \"import\",\n): void {\n\tif (!db.inTransaction) throw new Error(\"memory_source_transaction_required\");\n\tif (!hasRecordedLocalCreation(db, entityId)) return;\n\tensureCreationProvenanceSchema(db);\n\tif (db.prepare(\"SELECT 1 FROM memory_foreign_revisions WHERE entity_id = ?\").get(entityId))\n\t\treturn;\n\tdb.prepare(\n\t\t\"INSERT INTO memory_foreign_revisions(entity_id, write_path, created_at) VALUES (?, ?, ?)\",\n\t).run(entityId, writePath, new Date().toISOString());\n}\n\n/** Preservation evidence only: this must not authorize a read or mutation. */\nexport function hasRecordedLocalCreation(db: Database, entityId: string): boolean {\n\treturn (\n\t\thasTable(db, \"memory_source_bindings\") &&\n\t\tgetVerifiedMemorySource(db, entityId)?.evidence === \"local_creation\"\n\t);\n}\n\n/** Read-only SQL, using primary-key lookups for both creation and negative facts. */\nexport function matchingLocalCreationClause(db: Database): string | null {\n\tif (!hasTable(db, \"memory_local_creation_snapshots\") || !hasTable(db, \"memory_foreign_revisions\"))\n\t\treturn null;\n\tlet keyMatchSql = \"creation.source_public_key IS NULL\";\n\tif (hasTable(db, \"sync_device\"))\n\t\tkeyMatchSql = `(creation.source_public_key IS NULL OR EXISTS (SELECT 1 FROM sync_device creation_device\n\t\t\tWHERE creation_device.device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = creation.entity_id)\n\t\t\tAND creation_device.public_key = creation.source_public_key\n\t\t\tAND creation_device.fingerprint = creation.source_fingerprint))`;\n\treturn `EXISTS (SELECT 1 FROM memory_local_creation_snapshots creation\n\t\tWHERE creation.entity_id = memory_items.import_key\n\t\tAND creation.scope_id IS memory_items.scope_id\n\t\tAND creation.content_json = ${CREATION_CONTENT_SQL}\n\t\tAND ${keyMatchSql}\n\t\tAND NOT EXISTS (SELECT 1 FROM memory_foreign_revisions foreign_revision\n\t\t\tWHERE foreign_revision.entity_id = creation.entity_id))`;\n}\n\nexport function hasMatchingLocalCreation(\n\tdb: Database,\n\tentityId: string,\n\tsourceIds: readonly string[],\n\toptions: { memoryId?: number } = {},\n): boolean {\n\tif (!sourceIds.length) return false;\n\tif (options.memoryId !== undefined && !Number.isSafeInteger(options.memoryId)) return false;\n\tconst clause = matchingLocalCreationClause(db);\n\tif (!clause) return false;\n\tconst binding = getVerifiedMemorySource(db, entityId);\n\tif (binding?.evidence !== \"local_creation\" || !sourceIds.includes(binding.sourceDeviceId))\n\t\treturn false;\n\tif (options.memoryId !== undefined)\n\t\treturn (\n\t\t\tdb\n\t\t\t\t.prepare(`SELECT 1 FROM memory_items WHERE id = ? AND import_key = ? AND ${clause}`)\n\t\t\t\t.get(options.memoryId, entityId) !== undefined\n\t\t);\n\treturn (\n\t\tdb.prepare(`SELECT 1 FROM memory_items WHERE import_key = ? AND ${clause}`).get(entityId) !==\n\t\tundefined\n\t);\n}\n","import { homedir } from \"node:os\";\n\nexport function codememHomeDir(): string {\n\treturn process.env.HOME?.trim() || homedir();\n}\n","/**\n * OpenCode provider configuration loading and resolution.\n *\n * Mirrors codemem/observer_config.py — reads ~/.config/opencode/opencode.json{c},\n * resolves custom provider settings (base URL, headers, API keys), and expands\n * environment variable / file placeholders in config values.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tcloseSync,\n\texistsSync,\n\tfchmodSync,\n\tfchownSync,\n\tfsyncSync,\n\tftruncateSync,\n\tlstatSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\treadlinkSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { codememHomeDir } from \"./home.js\";\n\n// ---------------------------------------------------------------------------\n// JSONC helpers\n// ---------------------------------------------------------------------------\n\n/** Strip JavaScript-style `//` line comments and `/* ... */` block comments from JSONC text. */\nexport function stripJsonComments(text: string): string {\n\tconst result: string[] = [];\n\tlet inString = false;\n\tlet escapeNext = false;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst char = text.charAt(i);\n\t\tif (escapeNext) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && inString) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = !inString;\n\t\t\tresult.push(char);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!inString && char === \"/\" && i + 1 < text.length) {\n\t\t\tconst next = text.charAt(i + 1);\n\t\t\tif (next === \"/\") {\n\t\t\t\t// Line comment — skip until newline\n\t\t\t\tlet j = i + 2;\n\t\t\t\twhile (j < text.length && text.charAt(j) !== \"\\n\") j++;\n\t\t\t\ti = j - 1; // outer loop will increment\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (next === \"*\") {\n\t\t\t\t// Block comment — skip until */\n\t\t\t\tlet j = i + 2;\n\t\t\t\twhile (j < text.length - 1) {\n\t\t\t\t\tif (text.charAt(j) === \"*\" && text.charAt(j + 1) === \"/\") {\n\t\t\t\t\t\tj += 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\ti = j - 1; // outer loop will increment\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tresult.push(char);\n\t}\n\treturn result.join(\"\");\n}\n\n/** Remove trailing commas before `]` or `}` (outside strings). */\nexport function stripTrailingCommas(text: string): string {\n\tconst result: string[] = [];\n\tlet inString = false;\n\tlet escapeNext = false;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst char = text.charAt(i);\n\t\tif (escapeNext) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && inString) {\n\t\t\tresult.push(char);\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = !inString;\n\t\t\tresult.push(char);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!inString && char === \",\") {\n\t\t\t// Look ahead past whitespace for a closing bracket/brace\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < text.length && /\\s/.test(text.charAt(j))) j++;\n\t\t\tif (j < text.length && (text.charAt(j) === \"]\" || text.charAt(j) === \"}\")) {\n\t\t\t\tcontinue; // skip the trailing comma\n\t\t\t}\n\t\t}\n\t\tresult.push(char);\n\t}\n\treturn result.join(\"\");\n}\n\n// ---------------------------------------------------------------------------\n// Config loading\n// ---------------------------------------------------------------------------\n\n/** Load OpenCode config from `~/.config/opencode/opencode.json{c}`. */\nexport function loadOpenCodeConfig(): Record<string, unknown> {\n\tconst configDir = join(codememHomeDir(), \".config\", \"opencode\");\n\tconst candidates = [join(configDir, \"opencode.json\"), join(configDir, \"opencode.jsonc\")];\n\n\tconst configPath = candidates.find((p) => existsSync(p));\n\tif (!configPath) return {};\n\n\tlet text: string;\n\ttry {\n\t\ttext = readFileSync(configPath, \"utf-8\");\n\t} catch {\n\t\treturn {};\n\t}\n\n\t// Try plain JSON first\n\ttry {\n\t\treturn JSON.parse(text) as Record<string, unknown>;\n\t} catch {\n\t\t// fall through to JSONC\n\t}\n\n\ttry {\n\t\tconst cleaned = stripTrailingCommas(stripJsonComments(text));\n\t\treturn JSON.parse(cleaned) as Record<string, unknown>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n/** Expand `~/...` paths like Python's `Path(...).expanduser()`. */\nexport function expandUserPath(value: string): string {\n\treturn value.startsWith(\"~/\") ? join(codememHomeDir(), value.slice(2)) : value;\n}\n\nfunction isSafeWorkspaceId(value: string): boolean {\n\treturn /^[A-Za-z0-9._:-]+$/.test(value) && !/^\\.+$/.test(value);\n}\n\nexport function getWorkspaceCodememConfigPath(workspaceId: string): string {\n\tconst trimmed = workspaceId.trim();\n\tif (!trimmed || !isSafeWorkspaceId(trimmed)) {\n\t\tthrow new Error(`Invalid workspace id for config path: ${workspaceId}`);\n\t}\n\treturn join(codememHomeDir(), \".codemem\", \"workspaces\", trimmed, \"config\", \"codemem.json\");\n}\n\nexport function getWorkspaceScopedCodememConfigPath(): string | null {\n\tconst runtimeRoot = process.env.CODEMEM_RUNTIME_ROOT?.trim();\n\tif (runtimeRoot) {\n\t\tconst expandedRoot = expandUserPath(runtimeRoot);\n\t\tif (isAbsolute(expandedRoot)) {\n\t\t\treturn join(expandedRoot, \"config\", \"codemem.json\");\n\t\t}\n\t\t// Invalid/relative runtime root — fall through to workspace-id lookup\n\t}\n\n\tconst workspaceId = process.env.CODEMEM_WORKSPACE_ID?.trim();\n\tif (!workspaceId) return null;\n\tif (!isSafeWorkspaceId(workspaceId)) return null;\n\treturn getWorkspaceCodememConfigPath(workspaceId);\n}\n\nfunction getLegacyCodememConfigPath(): string {\n\tconst configDir = join(codememHomeDir(), \".config\", \"codemem\");\n\tconst candidates = [join(configDir, \"config.json\"), join(configDir, \"config.jsonc\")];\n\treturn candidates.find((p) => existsSync(p)) ?? join(configDir, \"config.json\");\n}\n\nfunction getCodememConfigWritePath(): string {\n\treturn resolveCodememConfigPath(undefined, \"write\").resolved.path;\n}\n\nexport function readWorkspaceCodememConfigFile(workspaceId: string): Record<string, unknown> {\n\treturn readCodememConfigFileAtPath(getWorkspaceCodememConfigPath(workspaceId));\n}\n\n/** Env var overrides matching Python's CONFIG_ENV_OVERRIDES. */\nexport const CODEMEM_CONFIG_ENV_OVERRIDES: Record<string, string> = {\n\tactor_id: \"CODEMEM_ACTOR_ID\",\n\tactor_display_name: \"CODEMEM_ACTOR_DISPLAY_NAME\",\n\tclaude_command: \"CODEMEM_CLAUDE_COMMAND\",\n\tcodex_command: \"CODEMEM_CODEX_COMMAND\",\n\tobserver_provider: \"CODEMEM_OBSERVER_PROVIDER\",\n\tobserver_model: \"CODEMEM_OBSERVER_MODEL\",\n\tobserver_temperature: \"CODEMEM_OBSERVER_TEMPERATURE\",\n\tobserver_openai_use_responses: \"CODEMEM_OBSERVER_OPENAI_USE_RESPONSES\",\n\tobserver_max_output_tokens: \"CODEMEM_OBSERVER_MAX_OUTPUT_TOKENS\",\n\tobserver_reasoning_effort: \"CODEMEM_OBSERVER_REASONING_EFFORT\",\n\tobserver_reasoning_summary: \"CODEMEM_OBSERVER_REASONING_SUMMARY\",\n\tobserver_tier_routing_enabled: \"CODEMEM_OBSERVER_TIER_ROUTING_ENABLED\",\n\tobserver_simple_provider: \"CODEMEM_OBSERVER_SIMPLE_PROVIDER\",\n\tobserver_simple_model: \"CODEMEM_OBSERVER_SIMPLE_MODEL\",\n\tobserver_simple_temperature: \"CODEMEM_OBSERVER_SIMPLE_TEMPERATURE\",\n\tobserver_rich_provider: \"CODEMEM_OBSERVER_RICH_PROVIDER\",\n\tobserver_rich_model: \"CODEMEM_OBSERVER_RICH_MODEL\",\n\tobserver_rich_temperature: \"CODEMEM_OBSERVER_RICH_TEMPERATURE\",\n\tobserver_rich_reasoning_effort: \"CODEMEM_OBSERVER_RICH_REASONING_EFFORT\",\n\tobserver_rich_reasoning_summary: \"CODEMEM_OBSERVER_RICH_REASONING_SUMMARY\",\n\tobserver_rich_max_output_tokens: \"CODEMEM_OBSERVER_RICH_MAX_OUTPUT_TOKENS\",\n\tobserver_output_mode: \"CODEMEM_OBSERVER_OUTPUT_MODE\",\n\tobserver_base_url: \"CODEMEM_OBSERVER_BASE_URL\",\n\tobserver_runtime: \"CODEMEM_OBSERVER_RUNTIME\",\n\tobserver_auth_source: \"CODEMEM_OBSERVER_AUTH_SOURCE\",\n\tobserver_auth_file: \"CODEMEM_OBSERVER_AUTH_FILE\",\n\tobserver_auth_command: \"CODEMEM_OBSERVER_AUTH_COMMAND\",\n\tobserver_auth_timeout_ms: \"CODEMEM_OBSERVER_AUTH_TIMEOUT_MS\",\n\tobserver_auth_cache_ttl_s: \"CODEMEM_OBSERVER_AUTH_CACHE_TTL_S\",\n\tobserver_headers: \"CODEMEM_OBSERVER_HEADERS\",\n\tobserver_max_chars: \"CODEMEM_OBSERVER_MAX_CHARS\",\n\tobserver_max_tokens: \"CODEMEM_OBSERVER_MAX_TOKENS\",\n\tpack_observation_limit: \"CODEMEM_PACK_OBSERVATION_LIMIT\",\n\tpack_session_limit: \"CODEMEM_PACK_SESSION_LIMIT\",\n\tsync_enabled: \"CODEMEM_SYNC_ENABLED\",\n\tsync_device_name: \"CODEMEM_SYNC_DEVICE_NAME\",\n\tsync_host: \"CODEMEM_SYNC_HOST\",\n\tsync_port: \"CODEMEM_SYNC_PORT\",\n\tsync_interval_s: \"CODEMEM_SYNC_INTERVAL_S\",\n\tsync_mdns: \"CODEMEM_SYNC_MDNS\",\n\tsync_advertise: \"CODEMEM_SYNC_ADVERTISE\",\n\tsync_coordinator_url: \"CODEMEM_SYNC_COORDINATOR_URL\",\n\tsync_coordinator_group: \"CODEMEM_SYNC_COORDINATOR_GROUP\",\n\tsync_coordinator_groups: \"CODEMEM_SYNC_COORDINATOR_GROUPS\",\n\tsync_coordinator_timeout_s: \"CODEMEM_SYNC_COORDINATOR_TIMEOUT_S\",\n\tsync_coordinator_presence_ttl_s: \"CODEMEM_SYNC_COORDINATOR_PRESENCE_TTL_S\",\n\tsync_coordinator_admin_secret: \"CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET\",\n\tsync_retention_enabled: \"CODEMEM_SYNC_RETENTION_ENABLED\",\n\tsync_retention_max_age_days: \"CODEMEM_SYNC_RETENTION_MAX_AGE_DAYS\",\n\tsync_retention_max_size_mb: \"CODEMEM_SYNC_RETENTION_MAX_SIZE_MB\",\n\tsync_retention_interval_s: \"CODEMEM_SYNC_RETENTION_INTERVAL_S\",\n\tsync_retention_max_runtime_ms: \"CODEMEM_SYNC_RETENTION_MAX_RUNTIME_MS\",\n\tsync_retention_max_ops_per_pass: \"CODEMEM_SYNC_RETENTION_MAX_OPS_PER_PASS\",\n\tsync_projects_include: \"CODEMEM_SYNC_PROJECTS_INCLUDE\",\n\tsync_projects_exclude: \"CODEMEM_SYNC_PROJECTS_EXCLUDE\",\n\tsync_ops_limit: \"CODEMEM_SYNC_OPS_LIMIT\",\n\traw_events_sweeper_interval_s: \"CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_S\",\n\traw_events_retention_enabled: \"CODEMEM_RAW_EVENTS_RETENTION_ENABLED\",\n\traw_events_retention_max_age_days: \"CODEMEM_RAW_EVENTS_RETENTION_MAX_AGE_DAYS\",\n};\n\n/** Normalize a configured sidecar command from argv or a shell-style string. */\nexport function coerceObserverCommand(value: unknown): string[] | null {\n\tif (value == null) return null;\n\tif (Array.isArray(value)) {\n\t\tconst parts = value.filter((item): item is string => {\n\t\t\treturn typeof item === \"string\" && item.trim() !== \"\";\n\t\t});\n\t\treturn parts.length > 0 ? parts : null;\n\t}\n\tif (typeof value !== \"string\") return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(trimmed) as unknown;\n\t\tif (Array.isArray(parsed) && parsed.every((item) => typeof item === \"string\")) {\n\t\t\tconst parts = parsed.filter((item) => item.trim() !== \"\");\n\t\t\treturn parts.length > 0 ? parts : null;\n\t\t}\n\t} catch {\n\t\t// Non-JSON command strings use the same whitespace splitting as existing config.\n\t}\n\tconst parts = trimmed.split(/\\s+/).filter((item) => item !== \"\");\n\treturn parts.length > 0 ? parts : null;\n}\n\n// ---------------------------------------------------------------------------\n// Unified config path resolver with full traceability\n// ---------------------------------------------------------------------------\n\nexport type ConfigPathSource =\n\t| \"cli-flag\"\n\t| \"env-codemem-config\"\n\t| \"env-runtime-root\"\n\t| \"env-workspace-id\"\n\t| \"legacy-global\";\n\nexport interface ConfigPathResolution {\n\tpath: string;\n\tsource: ConfigPathSource;\n\treason: string;\n\texists: boolean;\n\t/** Whether this candidate is structurally valid (absolute path, safe workspace id, etc.). */\n\tvalid: boolean;\n}\n\nexport interface ConfigResolutionResult {\n\tresolved: ConfigPathResolution;\n\tfallbackChain: ConfigPathResolution[];\n}\n\n/**\n * Resolve the codemem config path with full traceability.\n *\n * Every candidate in the precedence chain is evaluated and recorded.\n * The `resolved` field is the winner; `fallbackChain` holds all rejected candidates\n * with a reason string explaining why each was skipped.\n *\n * @param cliConfigPath - explicit --config flag value (highest precedence)\n * @param mode - 'read' checks existence and falls back; 'write' takes first match\n */\nexport function resolveCodememConfigPath(\n\tcliConfigPath?: string,\n\tmode: \"read\" | \"write\" = \"read\",\n): ConfigResolutionResult {\n\tconst candidates: ConfigPathResolution[] = [];\n\n\t// 1. CLI flag (highest precedence)\n\tif (cliConfigPath?.trim()) {\n\t\tconst path = expandUserPath(cliConfigPath.trim());\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"cli-flag\",\n\t\t\treason: `--config ${cliConfigPath}`,\n\t\t\texists: existsSync(path),\n\t\t\tvalid: true,\n\t\t});\n\t}\n\n\t// 2. CODEMEM_CONFIG env\n\tconst envConfig = process.env.CODEMEM_CONFIG?.trim();\n\tif (envConfig) {\n\t\tconst path = expandUserPath(envConfig);\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"env-codemem-config\",\n\t\t\treason: `CODEMEM_CONFIG='${envConfig}'`,\n\t\t\texists: existsSync(path),\n\t\t\tvalid: true,\n\t\t});\n\t}\n\n\t// 3. CODEMEM_RUNTIME_ROOT env (must be absolute after expandUser)\n\tconst runtimeRoot = process.env.CODEMEM_RUNTIME_ROOT?.trim();\n\tif (runtimeRoot) {\n\t\tconst expandedRoot = expandUserPath(runtimeRoot);\n\t\tconst absolute = isAbsolute(expandedRoot);\n\t\tconst path = join(expandedRoot, \"config\", \"codemem.json\");\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"env-runtime-root\",\n\t\t\treason: absolute\n\t\t\t\t? `CODEMEM_RUNTIME_ROOT='${runtimeRoot}'`\n\t\t\t\t: `CODEMEM_RUNTIME_ROOT='${runtimeRoot}' is relative, not absolute`,\n\t\t\texists: absolute ? existsSync(path) : false,\n\t\t\tvalid: absolute,\n\t\t});\n\t}\n\n\t// 4. CODEMEM_WORKSPACE_ID env (must pass isSafeWorkspaceId)\n\tconst workspaceId = process.env.CODEMEM_WORKSPACE_ID?.trim();\n\tif (workspaceId) {\n\t\tconst safe = isSafeWorkspaceId(workspaceId);\n\t\tconst path = safe\n\t\t\t? getWorkspaceCodememConfigPath(workspaceId)\n\t\t\t: join(codememHomeDir(), \".codemem\", \"workspaces\", workspaceId, \"config\", \"codemem.json\");\n\t\tcandidates.push({\n\t\t\tpath,\n\t\t\tsource: \"env-workspace-id\",\n\t\t\treason: safe\n\t\t\t\t? `CODEMEM_WORKSPACE_ID='${workspaceId}'`\n\t\t\t\t: `CODEMEM_WORKSPACE_ID='${workspaceId}' failed safety check`,\n\t\t\texists: safe ? existsSync(path) : false,\n\t\t\tvalid: safe,\n\t\t});\n\t}\n\n\t// 5. Legacy global config (~/.config/codemem/config.json{c})\n\tconst legacyPath = getLegacyCodememConfigPath();\n\tcandidates.push({\n\t\tpath: legacyPath,\n\t\tsource: \"legacy-global\",\n\t\treason: \"legacy global config\",\n\t\texists: existsSync(legacyPath),\n\t\tvalid: true,\n\t});\n\n\t// Explicit overrides (cli-flag, env-codemem-config) are authoritative:\n\t// they win in both read and write mode regardless of file existence.\n\t// This matches the original getCodememConfigPath behavior where\n\t// CODEMEM_CONFIG is returned immediately without an existence check.\n\tconst isAuthoritative = (c: ConfigPathResolution): boolean =>\n\t\tc.source === \"cli-flag\" || c.source === \"env-codemem-config\";\n\n\t// Select the winner based on mode.\n\t// Validity is determined structurally via the `valid` flag on each candidate,\n\t// not by inspecting the `reason` string.\n\tlet resolvedIndex: number;\n\tif (mode === \"write\") {\n\t\t// Write mode: first valid candidate regardless of existence\n\t\tresolvedIndex = candidates.findIndex((c) => c.valid);\n\t} else {\n\t\t// Read mode: authoritative sources win immediately; otherwise first existing candidate\n\t\tconst authoritativeIndex = candidates.findIndex((c) => isAuthoritative(c) && c.valid);\n\t\tif (authoritativeIndex >= 0) {\n\t\t\tresolvedIndex = authoritativeIndex;\n\t\t} else {\n\t\t\tconst existingIndex = candidates.findIndex((c) => c.valid && c.exists);\n\t\t\t// If none exist, fall back to first valid candidate (matches getCodememConfigPath behavior)\n\t\t\tresolvedIndex = existingIndex >= 0 ? existingIndex : candidates.findIndex((c) => c.valid);\n\t\t}\n\t}\n\n\t// Should always find at least the legacy candidate, but guard anyway\n\tif (resolvedIndex < 0) resolvedIndex = candidates.length - 1;\n\n\tconst resolved = candidates[resolvedIndex] ?? candidates[candidates.length - 1];\n\tif (!resolved) {\n\t\tthrow new Error(\"No config path candidates were generated\");\n\t}\n\tconst fallbackChain = candidates.filter((_, i) => i !== resolvedIndex);\n\n\t// Annotate skipped candidates with why they were not selected\n\tfor (const entry of fallbackChain) {\n\t\tif (entry.source === \"env-runtime-root\" && entry.reason.includes(\"is relative\")) {\n\t\t\t// Already has a descriptive reason\n\t\t} else if (\n\t\t\tentry.source === \"env-workspace-id\" &&\n\t\t\tentry.reason.includes(\"failed safety check\")\n\t\t) {\n\t\t\t// Already has a descriptive reason\n\t\t} else if (mode === \"read\" && !entry.exists) {\n\t\t\tentry.reason += \" (does not exist)\";\n\t\t}\n\t}\n\n\treturn { resolved, fallbackChain };\n}\n\n/**\n * Resolve codemem config path with precedence:\n * 1. explicit CODEMEM_CONFIG override\n * 2. workspace-scoped config via CODEMEM_RUNTIME_ROOT or CODEMEM_WORKSPACE_ID\n * 3. legacy global config under ~/.config/codemem/\n */\nexport function getCodememConfigPath(): string {\n\treturn resolveCodememConfigPath(undefined, \"read\").resolved.path;\n}\n\n/** Read codemem config file with the same JSON/JSONC behavior as Python. */\nexport function readCodememConfigFile(): Record<string, unknown> {\n\tconst configPath = getCodememConfigPath();\n\treturn readCodememConfigFileAtPath(configPath);\n}\n\nexport function readCodememConfigFileAtPath(configPath: string): Record<string, unknown> {\n\tconst resolvedPath = expandUserPath(configPath);\n\tif (!existsSync(resolvedPath)) return {};\n\n\tlet text: string;\n\ttry {\n\t\ttext = readFileSync(resolvedPath, \"utf-8\");\n\t} catch {\n\t\treturn {};\n\t}\n\n\tif (!text.trim()) return {};\n\n\ttry {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\treturn parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t: {};\n\t} catch {\n\t\t// fall through to JSONC\n\t}\n\n\ttry {\n\t\tconst cleaned = stripTrailingCommas(stripJsonComments(text));\n\t\tconst parsed = JSON.parse(cleaned) as unknown;\n\t\treturn parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t: {};\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nexport type CodememConfigReadOutcome =\n\t| { status: \"missing\"; path: string; revision: \"missing\" }\n\t| {\n\t\t\tstatus: \"valid\";\n\t\t\tpath: string;\n\t\t\tdata: Record<string, unknown>;\n\t\t\trevision: string;\n\t\t\tmode: number;\n\t\t\tuid: number;\n\t\t\tgid: number;\n\t\t\tctimeNs: bigint;\n\t\t\tdev: bigint;\n\t\t\tino: bigint;\n\t }\n\t| { status: \"invalid\"; path: string; reason: \"empty\" | \"non_object\" | \"parse_error\" }\n\t| { status: \"unreadable\"; path: string };\n\nexport type CodememConfigMutationResult = {\n\tpath: string;\n\tmutationPath: string;\n\tdata: Record<string, unknown>;\n\trevision: string;\n};\n\nexport type ConfigFileMetadata = { mode: number; uid: number; gid: number };\ntype ConfigFileIdentity = ConfigFileMetadata & {\n\tctimeNs: bigint;\n\tdev: bigint;\n\tino: bigint;\n};\n\nexport class CodememConfigMutationError extends Error {\n\treadonly code: \"busy\" | \"changed\" | \"invalid\" | \"unreadable\";\n\n\tconstructor(code: CodememConfigMutationError[\"code\"], message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CodememConfigMutationError\";\n\t\tthis.code = code;\n\t}\n}\n\ntype AtomicConfigFileOperations = {\n\topen: typeof openSync;\n\tclose: typeof closeSync;\n\tchown?: typeof fchownSync;\n\tchmod: typeof fchmodSync;\n\ttruncate?: typeof ftruncateSync;\n\tsync: typeof fsyncSync;\n\twrite: typeof writeSync;\n\trename: typeof renameSync;\n\tunlink: typeof unlinkSync;\n\tseedMetadata?: (sourcePath: string, destinationFd: number) => boolean;\n};\n\ntype ConfigLockCleanupOperations = Pick<AtomicConfigFileOperations, \"close\" | \"unlink\">;\n\nlet gnuCopyAvailable: boolean | undefined;\n\nfunction hasGnuCopy(): boolean {\n\tif (gnuCopyAvailable !== undefined) return gnuCopyAvailable;\n\ttry {\n\t\texecFileSync(\"/bin/cp\", [\"--version\"], { stdio: \"ignore\" });\n\t\tgnuCopyAvailable = true;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\tgnuCopyAvailable = false;\n\t\t\treturn gnuCopyAvailable;\n\t\t}\n\t\tif (error instanceof Error && \"status\" in error && typeof error.status === \"number\") {\n\t\t\tgnuCopyAvailable = false;\n\t\t\treturn gnuCopyAvailable;\n\t\t}\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t\"Cannot update config because extended access metadata support could not be checked.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\treturn gnuCopyAvailable;\n}\n\nfunction clearMacOsReplacementFlags(destinationFd: number): void {\n\texecFileSync(\"/usr/bin/chflags\", [\"0\", \"/dev/fd/3\"], {\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\", destinationFd],\n\t});\n}\n\nfunction seedConfigReplacementMetadata(sourcePath: string, destinationFd: number): boolean {\n\tlet args: string[] | undefined;\n\tlet env: NodeJS.ProcessEnv | undefined;\n\tif (process.platform === \"darwin\") {\n\t\targs = [\"-p\", sourcePath, \"/dev/fd/3\"];\n\t\tenv = { ...process.env };\n\t\tdelete env.COPYFILE_DISABLE;\n\t} else if (process.platform === \"linux\" && hasGnuCopy()) {\n\t\targs = [\"--preserve=mode,ownership,xattr\", \"--\", sourcePath, \"/proc/self/fd/3\"];\n\t}\n\tif (!args) return false;\n\n\ttry {\n\t\texecFileSync(\"/bin/cp\", args, {\n\t\t\tenv,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\", destinationFd],\n\t\t});\n\t\tif (process.platform === \"darwin\") clearMacOsReplacementFlags(destinationFd);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\ttry {\n\t\t\t\tclearMacOsReplacementFlags(destinationFd);\n\t\t\t} catch {\n\t\t\t\t// Preserve the metadata-copy failure; cleanup will retry unlinking the temp file.\n\t\t\t}\n\t\t}\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t`Cannot update config because extended access metadata from ${sourcePath} could not be preserved.`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nconst atomicConfigFileOperations: AtomicConfigFileOperations = {\n\topen: openSync,\n\tclose: closeSync,\n\tchown: fchownSync,\n\tchmod: fchmodSync,\n\ttruncate: ftruncateSync,\n\tsync: fsyncSync,\n\twrite: writeSync,\n\trename: renameSync,\n\tunlink: unlinkSync,\n\tseedMetadata: seedConfigReplacementMetadata,\n};\n\nconst configLockCleanupOperations: ConfigLockCleanupOperations = {\n\tclose: closeSync,\n\tunlink: unlinkSync,\n};\n\nfunction configRevision(text: string): string {\n\treturn createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\nfunction parseConfigText(\n\ttext: string,\n):\n\t| { status: \"valid\"; data: Record<string, unknown> }\n\t| { status: \"invalid\"; reason: \"empty\" | \"non_object\" | \"parse_error\" } {\n\tif (!text.trim()) return { status: \"invalid\", reason: \"empty\" };\n\tfor (const candidate of [text, stripTrailingCommas(stripJsonComments(text))]) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(candidate) as unknown;\n\t\t\tif (parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\t\treturn { status: \"valid\", data: parsed as Record<string, unknown> };\n\t\t\t}\n\t\t\treturn { status: \"invalid\", reason: \"non_object\" };\n\t\t} catch {\n\t\t\t// Try JSONC before reporting invalid syntax.\n\t\t}\n\t}\n\treturn { status: \"invalid\", reason: \"parse_error\" };\n}\n\n/** Read a config for mutation without treating damaged input as an empty object. */\nexport function readCodememConfigFileForMutation(configPath?: string): CodememConfigReadOutcome {\n\tconst path = configPath ? expandUserPath(configPath) : getCodememConfigWritePath();\n\tif (!existsSync(path)) return { status: \"missing\", path, revision: \"missing\" };\n\tlet text: string;\n\tlet metadata: ConfigFileIdentity;\n\ttry {\n\t\ttext = readFileSync(path, \"utf8\");\n\t\tconst stats = statSync(path, { bigint: true });\n\t\tmetadata = {\n\t\t\tmode: Number(stats.mode & 0o777n),\n\t\t\tuid: Number(stats.uid),\n\t\t\tgid: Number(stats.gid),\n\t\t\tctimeNs: stats.ctimeNs,\n\t\t\tdev: stats.dev,\n\t\t\tino: stats.ino,\n\t\t};\n\t} catch {\n\t\treturn { status: \"unreadable\", path };\n\t}\n\tconst parsed = parseConfigText(text);\n\tif (parsed.status === \"invalid\") return { ...parsed, path };\n\treturn { ...parsed, path, revision: configRevision(text), ...metadata };\n}\n\nfunction unlinkIfPresent(path: string, unlink: typeof unlinkSync): void {\n\ttry {\n\t\tunlink(path);\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? String(error.code) : \"\";\n\t\tif (code !== \"ENOENT\") throw error;\n\t}\n}\n\nfunction cleanupReplacementTempFile(\n\ttempPath: string,\n\tunlink: typeof unlinkSync,\n\trenameCommitted: boolean,\n): void {\n\ttry {\n\t\tunlinkIfPresent(tempPath, unlink);\n\t} catch (error) {\n\t\tif (!renameCommitted) throw error;\n\t}\n}\n\nfunction resolveConfigMutationTarget(path: string): string {\n\tconst seen = new Set<string>();\n\tlet current = path;\n\twhile (true) {\n\t\tif (seen.has(current)) {\n\t\t\tthrow new CodememConfigMutationError(\n\t\t\t\t\"unreadable\",\n\t\t\t\t`Cannot update config because ${path} contains a symbolic-link cycle.`,\n\t\t\t);\n\t\t}\n\t\tseen.add(current);\n\t\ttry {\n\t\t\treturn realpathSync(current);\n\t\t} catch {\n\t\t\t// Follow broken link chains until reaching the intended missing target.\n\t\t}\n\t\ttry {\n\t\t\tif (lstatSync(current).isSymbolicLink()) {\n\t\t\t\tconst target = readlinkSync(current);\n\t\t\t\tcurrent = isAbsolute(target) ? target : resolve(dirname(current), target);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn current;\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\treturn join(realpathSync(dirname(current)), basename(current));\n\t\t\t} catch {\n\t\t\t\treturn current;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction syncConfigDirectory(targetPath: string, operations: AtomicConfigFileOperations): void {\n\tlet directoryFd: number | null = null;\n\ttry {\n\t\tdirectoryFd = operations.open(dirname(targetPath), \"r\");\n\t\toperations.sync(directoryFd);\n\t} catch {\n\t\t// The rename already committed. Directory sync is best-effort on filesystems\n\t\t// that reject or fail it, so callers must not mistake this for an uncommitted save.\n\t} finally {\n\t\tif (directoryFd != null) {\n\t\t\ttry {\n\t\t\t\toperations.close(directoryFd);\n\t\t\t} catch {\n\t\t\t\t// Closing after a committed rename cannot safely turn success into failure.\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction writeCompleteConfig(\n\tfd: number,\n\ttext: string,\n\twrite: AtomicConfigFileOperations[\"write\"],\n): void {\n\tconst bytes = Buffer.from(text, \"utf8\");\n\tlet offset = 0;\n\twhile (offset < bytes.length) {\n\t\tconst written = write(fd, bytes, offset, bytes.length - offset, offset);\n\t\tif (written === 0) throw new Error(\"Config replacement write made no progress\");\n\t\toffset += written;\n\t}\n}\n\n/** Internal fault-injection seam used by config persistence tests. */\nexport function atomicReplaceConfigFile(\n\ttargetPath: string,\n\ttext: string,\n\tmetadata: ConfigFileMetadata | number | undefined,\n\toperations: AtomicConfigFileOperations = atomicConfigFileOperations,\n\tverifyBeforeRename?: () => void,\n\t{ followSymlink = true }: { followSymlink?: boolean } = {},\n): void {\n\tconst replacementPath = followSymlink ? resolveConfigMutationTarget(targetPath) : targetPath;\n\tconst tempPath = `${replacementPath}.tmp-${process.pid}-${randomUUID()}`;\n\tlet tempFd: number | null = null;\n\tlet renameCommitted = false;\n\ttry {\n\t\tconst mode = typeof metadata === \"number\" ? metadata : metadata?.mode;\n\t\ttempFd = operations.open(tempPath, \"wx\", mode ?? 0o600);\n\t\tconst seededMetadata =\n\t\t\ttypeof metadata === \"object\" && operations.seedMetadata?.(replacementPath, tempFd) === true;\n\t\tif (seededMetadata) {\n\t\t\tif (!operations.truncate) throw new Error(\"Seeded config replacement requires truncate\");\n\t\t\toperations.truncate(tempFd, 0);\n\t\t}\n\t\tif (typeof metadata === \"object\" && process.platform !== \"win32\") {\n\t\t\toperations.chown?.(tempFd, metadata.uid, metadata.gid);\n\t\t}\n\t\tif (mode != null) operations.chmod(tempFd, mode);\n\t\twriteCompleteConfig(tempFd, text, operations.write);\n\t\toperations.sync(tempFd);\n\t\tconst completedFd = tempFd;\n\t\ttempFd = null;\n\t\toperations.close(completedFd);\n\t\tverifyBeforeRename?.();\n\t\toperations.rename(tempPath, replacementPath);\n\t\trenameCommitted = true;\n\t\tsyncConfigDirectory(replacementPath, operations);\n\t} finally {\n\t\ttry {\n\t\t\tif (tempFd != null) operations.close(tempFd);\n\t\t} finally {\n\t\t\tcleanupReplacementTempFile(tempPath, operations.unlink, renameCommitted);\n\t\t}\n\t}\n}\n\nfunction assertMutationInput(outcome: CodememConfigReadOutcome): Record<string, unknown> {\n\tif (outcome.status === \"missing\") return {};\n\tif (outcome.status === \"valid\") return outcome.data;\n\tif (outcome.status === \"unreadable\") {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t`Cannot update config because ${outcome.path} could not be read.`,\n\t\t);\n\t}\n\tthrow new CodememConfigMutationError(\n\t\t\"invalid\",\n\t\t`Cannot update config because ${outcome.path} is not a valid JSON object.`,\n\t);\n}\n\nfunction currentRevision(path: string): string | \"missing\" | \"unreadable\" {\n\tif (!existsSync(path)) return \"missing\";\n\ttry {\n\t\treturn configRevision(readFileSync(path, \"utf8\"));\n\t} catch {\n\t\treturn \"unreadable\";\n\t}\n}\n\nfunction currentMetadata(path: string): ConfigFileIdentity | \"missing\" | \"unreadable\" {\n\tif (!existsSync(path)) return \"missing\";\n\ttry {\n\t\tconst stats = statSync(path, { bigint: true });\n\t\treturn {\n\t\t\tmode: Number(stats.mode & 0o777n),\n\t\t\tuid: Number(stats.uid),\n\t\t\tgid: Number(stats.gid),\n\t\t\tctimeNs: stats.ctimeNs,\n\t\t\tdev: stats.dev,\n\t\t\tino: stats.ino,\n\t\t};\n\t} catch {\n\t\treturn \"unreadable\";\n\t}\n}\n\nfunction configIdentityMatches(\n\tcurrent: ReturnType<typeof currentMetadata>,\n\texpected: ConfigFileIdentity,\n): boolean {\n\treturn (\n\t\ttypeof current !== \"string\" &&\n\t\tconfigMetadataMatches(current, expected) &&\n\t\tcurrent.ctimeNs === expected.ctimeNs &&\n\t\tcurrent.dev === expected.dev &&\n\t\tcurrent.ino === expected.ino\n\t);\n}\n\nfunction configMetadataMatches(\n\tcurrent: ReturnType<typeof currentMetadata>,\n\texpected: ConfigFileMetadata,\n): boolean {\n\treturn (\n\t\ttypeof current !== \"string\" &&\n\t\tcurrent.mode === expected.mode &&\n\t\tcurrent.uid === expected.uid &&\n\t\tcurrent.gid === expected.gid\n\t);\n}\n\nfunction configMetadata(outcome: CodememConfigReadOutcome): ConfigFileMetadata | undefined {\n\tif (outcome.status !== \"valid\") return undefined;\n\treturn { mode: outcome.mode, uid: outcome.uid, gid: outcome.gid };\n}\n\nfunction acquireConfigLock(targetPath: string): { fd: number; path: string } {\n\tconst path = `${targetPath}.lock`;\n\ttry {\n\t\treturn { fd: openSync(path, \"wx\", 0o600), path };\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? String(error.code) : \"\";\n\t\tif (code === \"EEXIST\") {\n\t\t\tthrow new CodememConfigMutationError(\n\t\t\t\t\"busy\",\n\t\t\t\t`Cannot update config because another writer is updating ${targetPath}. Retry the save; if no save is active, remove the stale lock at ${path}.`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"unreadable\",\n\t\t\t`Cannot update config because its writer lock could not be created at ${path}.`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nfunction releaseConfigLock(\n\tlock: { fd: number; path: string },\n\toperations: ConfigLockCleanupOperations,\n): void {\n\tlet firstError: unknown;\n\ttry {\n\t\toperations.close(lock.fd);\n\t} catch (error) {\n\t\tfirstError = error;\n\t}\n\ttry {\n\t\tunlinkIfPresent(lock.path, operations.unlink);\n\t} catch (error) {\n\t\tfirstError ??= error;\n\t}\n\tif (firstError !== undefined) throw firstError;\n}\n\nfunction releaseConfigLocks(\n\tlocks: Array<{ fd: number; path: string }>,\n\toperations: ConfigLockCleanupOperations = configLockCleanupOperations,\n): void {\n\tlet firstError: unknown;\n\tfor (const lock of locks.reverse()) {\n\t\ttry {\n\t\t\treleaseConfigLock(lock, operations);\n\t\t} catch (error) {\n\t\t\tfirstError ??= error;\n\t\t}\n\t}\n\tif (firstError !== undefined) throw firstError;\n}\n\nfunction releaseConfigLocksAfterMutation(\n\tlocks: Array<{ fd: number; path: string }>,\n\tcommitted: boolean,\n\toperations: ConfigLockCleanupOperations,\n): void {\n\ttry {\n\t\treleaseConfigLocks(locks, operations);\n\t} catch (error) {\n\t\tif (!committed) throw error;\n\t}\n}\n\nfunction acquireConfigLocks(targetPaths: string[]): Array<{ fd: number; path: string }> {\n\tconst orderedPaths = [...new Set(targetPaths)].sort((left, right) => {\n\t\tif (left < right) return -1;\n\t\tif (left > right) return 1;\n\t\treturn 0;\n\t});\n\tconst locks: Array<{ fd: number; path: string }> = [];\n\ttry {\n\t\tfor (const path of orderedPaths) {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\tlocks.push(acquireConfigLock(path));\n\t\t}\n\t\treturn locks;\n\t} catch (error) {\n\t\ttry {\n\t\t\treleaseConfigLocks(locks);\n\t\t} catch {\n\t\t\t// Preserve the acquisition failure after attempting every cleanup.\n\t\t}\n\t\tthrow error;\n\t}\n}\n\ntype ConfigMutationOptions = {\n\texpectedMutationPath?: string;\n\texpectedRevision?: string;\n\tfallbackReadPath?: string;\n\tlockCleanupOperations?: ConfigLockCleanupOperations;\n};\n\nfunction acquireConfigMutationLocks(\n\ttargetPath: string,\n\tusesImplicitPath: boolean,\n\toptions: ConfigMutationOptions,\n): {\n\tpreliminaryTarget: CodememConfigReadOutcome;\n\tfallbackReadPath: string | undefined;\n\ttargetMutationPath: string;\n\tfallbackMutationPath: string | undefined;\n\tlocks: Array<{ fd: number; path: string }>;\n} {\n\tfor (let attempt = 0; attempt < 3; attempt += 1) {\n\t\tconst preliminaryTarget = readCodememConfigFileForMutation(targetPath);\n\t\tconst fallbackReadPath =\n\t\t\toptions.fallbackReadPath ?? (usesImplicitPath ? getCodememConfigPath() : undefined);\n\t\tconst targetMutationPath = options.expectedMutationPath\n\t\t\t? expandUserPath(options.expectedMutationPath)\n\t\t\t: resolveConfigMutationTarget(targetPath);\n\t\tconst fallbackMutationPath =\n\t\t\tpreliminaryTarget.status === \"missing\" && fallbackReadPath != null\n\t\t\t\t? resolveConfigMutationTarget(expandUserPath(fallbackReadPath))\n\t\t\t\t: undefined;\n\t\tconst locks = acquireConfigLocks([targetMutationPath]);\n\t\tconst targetIdentityStable = resolveConfigMutationTarget(targetPath) === targetMutationPath;\n\t\tconst fallbackIdentityStable =\n\t\t\tfallbackMutationPath === undefined ||\n\t\t\tresolveConfigMutationTarget(expandUserPath(fallbackReadPath ?? targetPath)) ===\n\t\t\t\tfallbackMutationPath;\n\t\tif (targetIdentityStable && fallbackIdentityStable) {\n\t\t\treturn {\n\t\t\t\tpreliminaryTarget,\n\t\t\t\tfallbackReadPath,\n\t\t\t\ttargetMutationPath,\n\t\t\t\tfallbackMutationPath,\n\t\t\t\tlocks,\n\t\t\t};\n\t\t}\n\t\treleaseConfigLocks(locks);\n\t}\n\tthrow new CodememConfigMutationError(\n\t\t\"changed\",\n\t\t`Cannot update config because ${targetPath} changed before the save. Retry the save.`,\n\t);\n}\n\nfunction assertTargetDidNotDisappear(\n\tpreliminaryTarget: CodememConfigReadOutcome,\n\toutcome: CodememConfigReadOutcome,\n\ttargetPath: string,\n): void {\n\tif (preliminaryTarget.status === \"missing\" || outcome.status !== \"missing\") return;\n\tthrow new CodememConfigMutationError(\n\t\t\"changed\",\n\t\t`Cannot update config because ${targetPath} changed before the save. Retry the save.`,\n\t);\n}\n\nfunction mutationInputOutcome(\n\ttarget: CodememConfigReadOutcome,\n\ttargetPath: string,\n\tfallbackReadPath: string | undefined,\n): CodememConfigReadOutcome {\n\tif (target.status !== \"missing\") return target;\n\tconst readPath = fallbackReadPath ?? targetPath;\n\treturn readPath === targetPath ? target : readCodememConfigFileForMutation(readPath);\n}\n\nfunction verifyConfigMutation(input: {\n\ttargetPath: string;\n\ttargetMutationPath: string;\n\texpectedRevision: string;\n\texpectedMetadata: ConfigFileMetadata | undefined;\n\texpectedIdentity: ConfigFileIdentity | undefined;\n\tfallbackReadPath: string | undefined;\n\tfallbackMutationPath: string | undefined;\n\tinputOutcome: CodememConfigReadOutcome;\n\tinputRevision: string;\n}): void {\n\tconst observedMetadata = currentMetadata(input.targetMutationPath);\n\tif (\n\t\tresolveConfigMutationTarget(input.targetPath) !== input.targetMutationPath ||\n\t\tcurrentRevision(input.targetMutationPath) !== input.expectedRevision ||\n\t\t(input.expectedMetadata !== undefined &&\n\t\t\t!configMetadataMatches(observedMetadata, input.expectedMetadata)) ||\n\t\t(input.expectedIdentity !== undefined &&\n\t\t\t!configIdentityMatches(observedMetadata, input.expectedIdentity))\n\t) {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"changed\",\n\t\t\t`Cannot update config because ${input.targetPath} changed during the save. Retry the save.`,\n\t\t);\n\t}\n\tif (\n\t\tinput.fallbackMutationPath !== undefined &&\n\t\tresolveConfigMutationTarget(expandUserPath(input.fallbackReadPath ?? input.targetPath)) !==\n\t\t\tinput.fallbackMutationPath\n\t) {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"changed\",\n\t\t\t`Cannot update config because ${input.fallbackReadPath} changed during the save. Retry the save.`,\n\t\t);\n\t}\n\tif (\n\t\tinput.inputOutcome.path !== input.targetMutationPath &&\n\t\tcurrentRevision(input.inputOutcome.path) !== input.inputRevision\n\t) {\n\t\tthrow new CodememConfigMutationError(\n\t\t\t\"changed\",\n\t\t\t`Cannot update config because ${input.inputOutcome.path} changed during the save. Retry the save.`,\n\t\t);\n\t}\n}\n\nfunction assertExpectedRevision(targetPath: string, actual: string, expected?: string): void {\n\tif (expected == null || actual === expected) return;\n\tthrow new CodememConfigMutationError(\n\t\t\"changed\",\n\t\t`Cannot update config because ${targetPath} changed before the save. Retry the save.`,\n\t);\n}\n\nfunction expectedConfigState(\n\toutcome: CodememConfigReadOutcome,\n\ttargetPath: string,\n\texpectedRevisionOption?: string,\n): { expectedRevision: string; expectedIdentity: ConfigFileIdentity | undefined } {\n\tconst expectedRevision = outcome.status === \"valid\" ? outcome.revision : \"missing\";\n\tassertExpectedRevision(targetPath, expectedRevision, expectedRevisionOption);\n\treturn {\n\t\texpectedRevision,\n\t\texpectedIdentity:\n\t\t\toutcome.status === \"valid\"\n\t\t\t\t? {\n\t\t\t\t\t\tmode: outcome.mode,\n\t\t\t\t\t\tuid: outcome.uid,\n\t\t\t\t\t\tgid: outcome.gid,\n\t\t\t\t\t\tctimeNs: outcome.ctimeNs,\n\t\t\t\t\t\tdev: outcome.dev,\n\t\t\t\t\t\tino: outcome.ino,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t};\n}\n\nfunction commitConfigMutation(\n\tinput: Parameters<typeof verifyConfigMutation>[0] & {\n\t\tmetadata: ConfigFileMetadata | undefined;\n\t\ttext: string;\n\t},\n): void {\n\tatomicReplaceConfigFile(\n\t\tinput.targetMutationPath,\n\t\tinput.text,\n\t\tinput.metadata,\n\t\tatomicConfigFileOperations,\n\t\t() => verifyConfigMutation(input),\n\t);\n}\n\n/** Serialize a read-modify-write config update across cooperating processes. */\nexport function mutateCodememConfigFile(\n\tmutator: (\n\t\tdata: Record<string, unknown>,\n\t\toutcome: CodememConfigReadOutcome,\n\t) => Record<string, unknown> | undefined,\n\tconfigPath?: string,\n\toptions: ConfigMutationOptions = {},\n): CodememConfigMutationResult {\n\tconst targetPath = configPath ? expandUserPath(configPath) : getCodememConfigWritePath();\n\tconst { preliminaryTarget, fallbackReadPath, targetMutationPath, fallbackMutationPath, locks } =\n\t\tacquireConfigMutationLocks(targetPath, configPath == null, options);\n\tlet committed = false;\n\ttry {\n\t\tconst outcome = readCodememConfigFileForMutation(targetMutationPath);\n\t\tassertTargetDidNotDisappear(preliminaryTarget, outcome, targetPath);\n\t\tconst readPath = fallbackMutationPath ?? fallbackReadPath;\n\t\tconst inputOutcome = mutationInputOutcome(outcome, targetMutationPath, readPath);\n\t\tconst { expectedRevision, expectedIdentity } = expectedConfigState(\n\t\t\toutcome,\n\t\t\ttargetPath,\n\t\t\toptions.expectedRevision,\n\t\t);\n\t\tconst current = { ...assertMutationInput(inputOutcome) };\n\t\tconst data = mutator(current, outcome);\n\t\tif (data === undefined) {\n\t\t\treturn {\n\t\t\t\tpath: targetPath,\n\t\t\t\tmutationPath: targetMutationPath,\n\t\t\t\tdata: current,\n\t\t\t\trevision: expectedRevision,\n\t\t\t};\n\t\t}\n\t\tconst inputRevision =\n\t\t\tinputOutcome.status === \"valid\" ? inputOutcome.revision : inputOutcome.status;\n\t\tconst text = `${JSON.stringify(data, null, 2)}\\n`;\n\t\tcommitConfigMutation({\n\t\t\ttargetPath,\n\t\t\ttargetMutationPath,\n\t\t\ttext,\n\t\t\tmetadata: configMetadata(outcome),\n\t\t\texpectedRevision,\n\t\t\texpectedMetadata: configMetadata(outcome),\n\t\t\texpectedIdentity,\n\t\t\tfallbackReadPath,\n\t\t\tfallbackMutationPath,\n\t\t\tinputOutcome,\n\t\t\tinputRevision,\n\t\t});\n\t\tcommitted = true;\n\t\treturn {\n\t\t\tpath: targetPath,\n\t\t\tmutationPath: targetMutationPath,\n\t\t\tdata,\n\t\t\trevision: configRevision(text),\n\t\t};\n\t} finally {\n\t\treleaseConfigLocksAfterMutation(\n\t\t\tlocks,\n\t\t\tcommitted,\n\t\t\toptions.lockCleanupOperations ?? configLockCleanupOperations,\n\t\t);\n\t}\n}\n\n/** Delete a config only when it still has the expected revision. */\nexport function deleteCodememConfigFile(\n\tconfigPath: string,\n\texpectedRevision: string,\n\texpectedMutationPath?: string,\n\tlockCleanupOperations: ConfigLockCleanupOperations = configLockCleanupOperations,\n): void {\n\tconst targetPath = expandUserPath(configPath);\n\tconst replacementPath = expectedMutationPath ?? resolveConfigMutationTarget(targetPath);\n\tconst lock = acquireConfigLock(replacementPath);\n\tlet committed = false;\n\ttry {\n\t\tif (\n\t\t\tresolveConfigMutationTarget(targetPath) !== replacementPath ||\n\t\t\tcurrentRevision(replacementPath) !== expectedRevision\n\t\t) {\n\t\t\tthrow new CodememConfigMutationError(\n\t\t\t\t\"changed\",\n\t\t\t\t`Cannot restore config because ${targetPath} changed after the save.`,\n\t\t\t);\n\t\t}\n\t\tunlinkSync(replacementPath);\n\t\tcommitted = true;\n\t\tsyncConfigDirectory(replacementPath, atomicConfigFileOperations);\n\t} finally {\n\t\treleaseConfigLocksAfterMutation([lock], committed, lockCleanupOperations);\n\t}\n}\n\n/** Persist the codemem config file as normalized JSON using atomic replacement. */\nexport function writeCodememConfigFile(data: Record<string, unknown>, configPath?: string): string {\n\treturn mutateCodememConfigFile(() => data, configPath).path;\n}\n\nexport function writeWorkspaceCodememConfigFile(\n\tworkspaceId: string,\n\tdata: Record<string, unknown>,\n): string {\n\treturn writeCodememConfigFile(data, getWorkspaceCodememConfigPath(workspaceId));\n}\n\n// Match loadObserverConfig's nullish string precedence, including empty strings.\nconst OBSERVER_STRING_ENV_KEYS = new Set([\n\t\"observer_provider\",\n\t\"observer_model\",\n\t\"observer_runtime\",\n\t\"observer_base_url\",\n\t\"observer_simple_provider\",\n\t\"observer_simple_model\",\n\t\"observer_rich_provider\",\n\t\"observer_rich_model\",\n\t\"observer_reasoning_effort\",\n\t\"observer_reasoning_summary\",\n\t\"observer_rich_reasoning_effort\",\n\t\"observer_rich_reasoning_summary\",\n\t\"observer_auth_source\",\n\t\"observer_auth_file\",\n]);\n\nfunction parseObserverJsonEnv(key: string, value: string): unknown {\n\tconst isCommand = key === \"observer_auth_command\";\n\tif (!value.trim()) return isCommand ? [] : {};\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (isCommand) {\n\t\t\tif (Array.isArray(parsed) && parsed.every((item) => typeof item === \"string\")) return parsed;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed;\n\t} catch {\n\t\t// Invalid values retain the saved configuration, so do not claim env control.\n\t}\n\treturn undefined;\n}\n\nfunction parseConfigEnvOverride(key: string, value: string): unknown {\n\tif (OBSERVER_STRING_ENV_KEYS.has(key)) return value;\n\tswitch (key) {\n\t\tcase \"observer_temperature\":\n\t\tcase \"observer_simple_temperature\":\n\t\tcase \"observer_rich_temperature\":\n\t\tcase \"observer_rich_max_output_tokens\":\n\t\tcase \"observer_max_output_tokens\": {\n\t\t\tconst number = Number(value);\n\t\t\treturn Number.isFinite(number) ? number : undefined;\n\t\t}\n\t\tcase \"observer_max_chars\":\n\t\tcase \"observer_max_tokens\":\n\t\tcase \"observer_auth_timeout_ms\":\n\t\tcase \"observer_auth_cache_ttl_s\": {\n\t\t\tconst number = Number.parseInt(value, 10);\n\t\t\treturn Number.isFinite(number) ? number : undefined;\n\t\t}\n\t\tcase \"observer_tier_routing_enabled\":\n\t\tcase \"observer_openai_use_responses\":\n\t\t\treturn value === \"1\" || value === \"true\";\n\t\tcase \"observer_output_mode\":\n\t\t\treturn [\"auto\", \"json_schema\", \"legacy_xml\"].includes(value) ? value : undefined;\n\t\tcase \"claude_command\":\n\t\tcase \"codex_command\":\n\t\t\treturn coerceObserverCommand(value) ?? undefined;\n\t\tcase \"observer_headers\":\n\t\tcase \"observer_auth_command\":\n\t\t\treturn parseObserverJsonEnv(key, value);\n\t\tdefault:\n\t\t\treturn value === \"\" ? undefined : value;\n\t}\n}\n\n/** Parsed active overrides; omitted entries fall back to saved configuration. */\nexport function getCodememEnvOverrideValues(): Record<string, unknown> {\n\tconst values: Record<string, unknown> = {};\n\tfor (const [key, envVar] of Object.entries(CODEMEM_CONFIG_ENV_OVERRIDES)) {\n\t\tconst raw = process.env[envVar];\n\t\tif (raw === undefined) continue;\n\t\tconst value = parseConfigEnvOverride(key, raw);\n\t\tif (value !== undefined) values[key] = value;\n\t}\n\treturn values;\n}\n\n/** Return env vars that actually override saved codemem config values. */\nexport function getCodememEnvOverrides(): Record<string, string> {\n\tconst overrides: Record<string, string> = {};\n\tfor (const key of Object.keys(getCodememEnvOverrideValues())) {\n\t\tconst envVar = CODEMEM_CONFIG_ENV_OVERRIDES[key];\n\t\tif (envVar) overrides[key] = envVar;\n\t}\n\treturn overrides;\n}\n\n// ---------------------------------------------------------------------------\n// Provider helpers\n// ---------------------------------------------------------------------------\n\ntype AnyRecord = Record<string, unknown>;\n\nfunction asRecord(value: unknown): AnyRecord | null {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as AnyRecord)\n\t\t: null;\n}\n\n/** Get provider-specific config block from the opencode config. */\nexport function getOpenCodeProviderConfig(provider: string): AnyRecord {\n\tconst config = loadOpenCodeConfig();\n\tconst providerConfig = asRecord(config.provider);\n\tif (!providerConfig) return {};\n\tconst data = asRecord(providerConfig[provider]);\n\treturn data ?? {};\n}\n\n/** True when the opencode config has a provider block for this provider name. */\nexport function hasOpenCodeProviderConfig(provider: string): boolean {\n\treturn Object.keys(getOpenCodeProviderConfig(provider)).length > 0;\n}\n\n/** List all custom provider keys from the opencode config. */\nexport function listCustomProviders(): Set<string> {\n\tconst config = loadOpenCodeConfig();\n\tconst providerConfig = asRecord(config.provider);\n\tif (!providerConfig) return new Set();\n\treturn new Set(Object.keys(providerConfig));\n}\n\nconst BUILTIN_MODEL_PREFIX_PROVIDERS = new Set([\"openai\", \"anthropic\", \"opencode\"]);\n\nfunction extractProviderPrefix(value: unknown): string | null {\n\tif (typeof value !== \"string\" || !value.includes(\"/\")) return null;\n\tconst prefix = value.split(\"/\")[0]?.trim().toLowerCase();\n\treturn prefix ? prefix : null;\n}\n\nexport function listConfiguredOpenCodeProviders(): Set<string> {\n\tconst providers = listCustomProviders();\n\tconst config = loadOpenCodeConfig();\n\tfor (const key of [\"model\", \"small_model\"]) {\n\t\tconst prefix = extractProviderPrefix(config[key]);\n\t\tif (prefix) providers.add(prefix);\n\t}\n\treturn providers;\n}\n\nexport function listObserverProviderOptions(): string[] {\n\tconst providers = listConfiguredOpenCodeProviders();\n\tfor (const provider of BUILTIN_MODEL_PREFIX_PROVIDERS) providers.add(provider);\n\treturn Array.from(providers).sort((a, b) => a.localeCompare(b));\n}\n\nexport function resolveBuiltInProviderFromModel(model: string): string | null {\n\tconst prefix = extractProviderPrefix(model);\n\treturn prefix && BUILTIN_MODEL_PREFIX_PROVIDERS.has(prefix) ? prefix : null;\n}\n\nexport function resolveBuiltInProviderDefaultModel(provider: string): string | null {\n\tif (provider === \"openai\") return \"gpt-6-luna\";\n\tif (provider === \"anthropic\") return \"claude-haiku-4-5\";\n\tif (provider === \"opencode\") return \"opencode/gpt-6-luna\";\n\treturn null;\n}\n\nexport function resolveBuiltInProviderModel(\n\tprovider: string,\n\tmodelName: string,\n): [baseUrl: string | null, modelId: string | null, headers: Record<string, string>] {\n\tif (provider !== \"opencode\") {\n\t\treturn [null, modelName || resolveBuiltInProviderDefaultModel(provider), {}];\n\t}\n\tconst name = modelName || resolveBuiltInProviderDefaultModel(provider) || \"\";\n\tconst prefix = `${provider}/`;\n\tconst shortName = name.toLowerCase().startsWith(prefix) ? name.slice(prefix.length) : name;\n\treturn [\"https://opencode.ai/zen/v1\", shortName || null, {}];\n}\n\n/** Extract provider prefix from a model string like `\"myprovider/model-name\"`. */\nexport function resolveCustomProviderFromModel(\n\tmodel: string,\n\tproviders: Set<string>,\n): string | null {\n\tif (!model?.includes(\"/\")) return null;\n\tconst prefix = model.split(\"/\")[0] ?? \"\";\n\tif (!prefix) return null;\n\tif (providers.has(prefix)) return prefix;\n\tconst normalizedPrefix = prefix.toLowerCase();\n\treturn [...providers].find((provider) => provider.toLowerCase() === normalizedPrefix) ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Placeholder resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Expand `$ENV_VAR` / `${ENV_VAR}` references and `{file:/path}` placeholders.\n *\n * Environment variable expansion mirrors Python's `os.path.expandvars`.\n * File placeholders read the file content and substitute it inline.\n */\nexport function resolvePlaceholder(value: string): string {\n\tconst expanded = expandEnvVars(value);\n\treturn resolveFilePlaceholder(expanded);\n}\n\n/** Expand `$VAR` and `${VAR}` environment variable references. */\nfunction expandEnvVars(value: string): string {\n\tlet result = \"\";\n\tfor (let i = 0; i < value.length; i++) {\n\t\tif (value[i] !== \"$\" || i === value.length - 1) {\n\t\t\tresult += value[i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (value[i + 1] === \"{\") {\n\t\t\tconst end = value.indexOf(\"}\", i + 2);\n\t\t\tif (end > i + 2) {\n\t\t\t\tconst name = value.slice(i + 2, end);\n\t\t\t\tresult += process.env[name] ?? value.slice(i, end + 1);\n\t\t\t\ti = end;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tconst start = i + 1;\n\t\tlet end = start;\n\t\twhile (end < value.length) {\n\t\t\tconst code = value.charCodeAt(end);\n\t\t\tconst isLetter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\t\t\tconst isDigit = code >= 48 && code <= 57;\n\t\t\tif (!isLetter && !isDigit && code !== 95) break;\n\t\t\tend++;\n\t\t}\n\t\tconst name = value.slice(start, end);\n\t\tif (!name || !Number.isNaN(Number(name[0]))) {\n\t\t\tresult += \"$\";\n\t\t\tcontinue;\n\t\t}\n\t\tresult += process.env[name] ?? value.slice(i, end);\n\t\ti = end - 1;\n\t}\n\treturn result;\n}\n\n/** Expand `{file:path}` placeholders by reading the referenced file. */\nfunction resolveFilePlaceholder(value: string): string {\n\tif (!value.includes(\"{file:\")) return value;\n\tlet result = \"\";\n\tlet index = 0;\n\twhile (index < value.length) {\n\t\tconst start = value.indexOf(\"{file:\", index);\n\t\tif (start < 0) {\n\t\t\tresult += value.slice(index);\n\t\t\tbreak;\n\t\t}\n\t\tconst end = value.indexOf(\"}\", start + 6);\n\t\tif (end < 0) {\n\t\t\tresult += value.slice(index);\n\t\t\tbreak;\n\t\t}\n\t\tresult += value.slice(index, start);\n\t\tconst match = value.slice(start, end + 1);\n\t\tconst rawPath = value.slice(start + 6, end);\n\t\tconst trimmed = rawPath.trim();\n\t\tif (!trimmed) {\n\t\t\tresult += match;\n\t\t\tindex = end + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst expanded = expandEnvVars(trimmed);\n\t\tconst resolved = expanded.startsWith(\"~\")\n\t\t\t? `${codememHomeDir()}${expanded.slice(1)}`\n\t\t\t: expanded;\n\t\ttry {\n\t\t\tresult += readFileSync(resolved, \"utf-8\").trim();\n\t\t} catch {\n\t\t\tresult += match;\n\t\t}\n\t\tindex = end + 1;\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// Provider option extraction\n// ---------------------------------------------------------------------------\n\n/** Extract the `options` sub-object from a provider config block. */\nexport function getProviderOptions(providerConfig: AnyRecord): AnyRecord {\n\tconst options = asRecord(providerConfig.options);\n\treturn options ?? {};\n}\n\n/** Extract `baseURL` / `baseUrl` / `base_url` from provider config. */\nexport function getProviderBaseUrl(providerConfig: AnyRecord): string | null {\n\tconst options = getProviderOptions(providerConfig);\n\t// Use || (not ??) so empty strings fall through to the next candidate (matches Python's `or`)\n\tconst baseUrl = options.baseURL || options.baseUrl || options.base_url || providerConfig.base_url;\n\treturn typeof baseUrl === \"string\" && baseUrl ? baseUrl : null;\n}\n\n/** Extract and resolve headers (with placeholder expansion) from provider config. */\nexport function getProviderHeaders(providerConfig: AnyRecord): Record<string, string> {\n\tconst options = getProviderOptions(providerConfig);\n\tconst headers = asRecord(options.headers);\n\tif (!headers) return {};\n\tconst parsed: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (typeof key !== \"string\" || typeof value !== \"string\") continue;\n\t\tparsed[key] = resolvePlaceholder(value);\n\t}\n\treturn parsed;\n}\n\n/** Extract API key from provider config (direct value or env-var reference). */\nexport function getProviderApiKey(providerConfig: AnyRecord): string | null {\n\tconst options = getProviderOptions(providerConfig);\n\t// Use || (not ??) so empty strings fall through (matches Python's `or`)\n\tconst apiKey = options.apiKey || providerConfig.apiKey;\n\tif (typeof apiKey === \"string\" && apiKey) {\n\t\treturn resolvePlaceholder(apiKey);\n\t}\n\tconst apiKeyEnv = (options.apiKeyEnv ?? options.api_key_env) as string | undefined;\n\tif (typeof apiKeyEnv === \"string\" && apiKeyEnv) {\n\t\tconst value = process.env[apiKeyEnv];\n\t\tif (value) return value;\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Custom provider model resolution\n// ---------------------------------------------------------------------------\n\n/** Find the default model for a custom provider. */\nexport function resolveCustomProviderDefaultModel(provider: string): string | null {\n\tconst providerConfig = getOpenCodeProviderConfig(provider);\n\tconst options = getProviderOptions(providerConfig);\n\tconst defaultModel =\n\t\toptions.defaultModel ??\n\t\toptions.default_model ??\n\t\tproviderConfig.defaultModel ??\n\t\tproviderConfig.default_model;\n\tif (typeof defaultModel === \"string\" && defaultModel) {\n\t\treturn defaultModel.startsWith(`${provider}/`) ? defaultModel : `${provider}/${defaultModel}`;\n\t}\n\tconst models = asRecord(providerConfig.models);\n\tif (models) {\n\t\tconst firstKey = Object.keys(models)[0];\n\t\tif (typeof firstKey === \"string\" && firstKey) {\n\t\t\treturn `${provider}/${firstKey}`;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Resolve base_url, model_id, and headers for a custom provider model.\n *\n * Returns `[baseUrl, modelId, headers]`.\n */\nexport function resolveCustomProviderModel(\n\tprovider: string,\n\tmodelName: string,\n): [baseUrl: string | null, modelId: string | null, headers: Record<string, string>] {\n\tconst providerConfig = getOpenCodeProviderConfig(provider);\n\tconst baseUrl = getProviderBaseUrl(providerConfig);\n\tconst headers = getProviderHeaders(providerConfig);\n\n\tlet name = modelName;\n\tif (!name) {\n\t\tname = resolveCustomProviderDefaultModel(provider) ?? \"\";\n\t}\n\n\tconst prefix = `${provider}/`;\n\tconst shortName = name.toLowerCase().startsWith(prefix.toLowerCase())\n\t\t? name.slice(prefix.length)\n\t\t: name;\n\n\tconst models = asRecord(providerConfig.models);\n\tlet modelId: string | null = shortName;\n\tif (models) {\n\t\tconst modelConfig = asRecord(models[shortName]);\n\t\tif (modelConfig && typeof modelConfig.id === \"string\") {\n\t\t\tmodelId = modelConfig.id;\n\t\t}\n\t}\n\n\tif (typeof modelId !== \"string\" || !modelId) {\n\t\tmodelId = null;\n\t}\n\n\treturn [baseUrl, modelId, headers];\n}\n","import type { Database } from \"better-sqlite3\";\nimport * as sqliteVec from \"sqlite-vec\";\n\n/** Current schema version this TS runtime was built against. */\nexport const SCHEMA_VERSION = 21;\n\nexport const REQUIRED_TABLES = [\n\t\"memory_items\",\n\t\"sessions\",\n\t\"artifacts\",\n\t\"raw_events\",\n\t\"raw_event_sessions\",\n\t\"usage_events\",\n] as const;\n\nexport const REQUIRED_BOOTSTRAPPED_TABLES = [\n\t...REQUIRED_TABLES,\n\t\"memory_fts\",\n\t\"coordinator_enrollment_reconciliation_issues\",\n\t// The legacy_team_setup_* tables are deliberately NOT listed: they are\n\t// created additively by `ensureLegacyTeamSetupDraftSchema` on every\n\t// connection path. Listing them would make a valid older bootstrapped\n\t// schema look partial and skip WAL/pragma connection setup for the first\n\t// post-upgrade connection.\n] as const;\n\n/** Check if embeddings are disabled via environment variable. */\nexport function isEmbeddingDisabled(): boolean {\n\tconst val = process.env.CODEMEM_EMBEDDING_DISABLED?.toLowerCase();\n\treturn val === \"1\" || val === \"true\" || val === \"yes\";\n}\n\n/** Load sqlite-vec and verify that the extension is callable. */\nexport function loadSqliteVec(db: Database): void {\n\tif (isEmbeddingDisabled()) return;\n\tsqliteVec.load(db);\n\tconst row = db.prepare(\"SELECT vec_version() AS v\").get() as { v: string } | undefined;\n\tif (!row?.v) throw new Error(\"sqlite-vec loaded but version check failed\");\n}\n\n/** Read the schema `user_version` pragma, returning zero for an empty database. */\nexport function getSchemaVersion(db: Database): number {\n\tconst row = db.pragma(\"user_version\", { simple: true });\n\treturn typeof row === \"number\" ? row : 0;\n}\n\nconst IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS: ReadonlyArray<{ name: string; create: string }> = [\n\t{\n\t\tname: \"trg_identity_devices_assignment_version\",\n\t\tcreate: `CREATE TRIGGER trg_identity_devices_assignment_version\n\tAFTER UPDATE OF identity_id ON identity_devices\n\tWHEN NEW.identity_id <> OLD.identity_id\n\tBEGIN\n\t\tUPDATE identity_devices\n\t\tSET assignment_version = OLD.assignment_version + 1\n\t\tWHERE device_id = NEW.device_id;\n\tEND`,\n\t},\n\t{\n\t\tname: \"trg_identity_devices_purge_decisions\",\n\t\tcreate: `CREATE TRIGGER trg_identity_devices_purge_decisions\n\tAFTER DELETE ON identity_devices\n\tBEGIN\n\t\tDELETE FROM policy_team_device_decisions WHERE device_id = OLD.device_id;\n\tEND`,\n\t},\n];\n\nexport const IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL = IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS.map(\n\t({ name, create }) => `DROP TRIGGER IF EXISTS ${name};\\n${create};`,\n).join(\"\\n\");\n\nfunction normalizedSql(sql: string): string {\n\treturn sql.replace(/\\s+/g, \" \").trim();\n}\n\n/** True when both security triggers exist with exactly the expected definitions. */\nexport function identityDeviceAssignmentTriggersCurrent(db: Database): boolean {\n\tconst lookup = db.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?\");\n\treturn IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS.every(({ name, create }) => {\n\t\tconst row = lookup.get(name) as { sql?: string | null } | undefined;\n\t\treturn typeof row?.sql === \"string\" && normalizedSql(row.sql) === normalizedSql(create);\n\t});\n}\n","import type { Database } from \"./db.js\";\n\nexport function ensureMemoryRetirementDeliverySchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_retirement_deliveries (\n\t\tcontrol_id TEXT NOT NULL,\n\t\tpeer_device_id TEXT NOT NULL,\n\t\tentity_id TEXT NOT NULL,\n\t\tsource_device_id TEXT NOT NULL,\n\t\tretired_scope_id TEXT NOT NULL,\n\t\tacknowledged_at TEXT,\n\t\tPRIMARY KEY (control_id, peer_device_id)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_memory_retirement_deliveries_pending\n\t\tON memory_retirement_deliveries(peer_device_id, source_device_id, acknowledged_at, control_id);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_peer_trust (\n\t\tlocal_device_id TEXT NOT NULL,\n\t\tpeer_device_id TEXT NOT NULL,\n\t\tpublic_key TEXT NOT NULL,\n\t\tpinned_fingerprint TEXT NOT NULL,\n\t\tPRIMARY KEY (local_device_id, peer_device_id)\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_receipts (\n\t\tcontrol_id TEXT PRIMARY KEY,\n\t\tsource_device_id TEXT NOT NULL,\n\t\treceived_at TEXT NOT NULL\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_reset_receivers (\n\t\treset_id TEXT PRIMARY KEY, source_device_id TEXT NOT NULL, source_public_key TEXT NOT NULL,\n\t\tlocal_device_id TEXT NOT NULL, boundary TEXT NOT NULL, next_offset INTEGER NOT NULL DEFAULT 0,\n\t\tcomplete INTEGER NOT NULL DEFAULT 0, last_page_digest TEXT\n\t);\n\tCREATE TABLE IF NOT EXISTS memory_retirement_reset_manifests (\n\t\treset_id TEXT NOT NULL, peer_device_id TEXT NOT NULL, source_device_id TEXT NOT NULL,\n\t\tboundary TEXT NOT NULL, controls_json TEXT NOT NULL,\n\t\tPRIMARY KEY(reset_id, peer_device_id, source_device_id)\n\t);`);\n}\n","import type { Database } from \"./db.js\";\nimport {\n\tassertVerifiedMemorySource,\n\tverifyAuthenticatedMemorySource,\n} from \"./memory-source-identity.js\";\n\n/** Internal prerequisite; no wire capability or production retirement caller is enabled. */\nexport function ensureMemoryScopeRetirementSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_scope_retirements (\n\t\tentity_id TEXT NOT NULL,\n\t\tsource_device_id TEXT NOT NULL,\n\t\tretired_scope_id TEXT NOT NULL,\n\t\tretired_at TEXT NOT NULL,\n\t\tPRIMARY KEY (entity_id, retired_scope_id)\n\t);\n\tCREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_update\n\tBEFORE UPDATE ON memory_scope_retirements\n\tBEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_delete\n\tBEFORE DELETE ON memory_scope_retirements\n\tBEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;\n\tCREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_replace\n\tBEFORE INSERT ON memory_scope_retirements\n\tWHEN EXISTS (SELECT 1 FROM memory_scope_retirements WHERE entity_id = NEW.entity_id AND retired_scope_id = NEW.retired_scope_id)\n\tBEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;`);\n}\n\n/** Payload-free control: no destination, recipients, memory content, or clock. */\nexport interface MemoryScopeRetirement {\n\tentityId: string;\n\tsourceDeviceId: string;\n\tretiredScopeId: string;\n}\n\nfunction validateRetirement(input: MemoryScopeRetirement): void {\n\tfor (const value of [input.entityId, input.sourceDeviceId, input.retiredScopeId]) {\n\t\tif (\n\t\t\ttypeof value !== \"string\" ||\n\t\t\t!value ||\n\t\t\tvalue.length > 1500 ||\n\t\t\tvalue !== value.trim() ||\n\t\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t\t)\n\t\t\tthrow new Error(\"memory_retirement_invalid\");\n\t}\n}\n\n/** No foreign keys: row erasure, scope cleanup and log compaction must retain this fence. */\nexport function isMemoryScopeRetired(\n\tdb: Database,\n\tentityId: string,\n\tscopeId: string | null,\n): boolean {\n\tif (!scopeId) return false;\n\treturn Boolean(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM memory_scope_retirements WHERE entity_id = ? AND retired_scope_id = ?\",\n\t\t\t)\n\t\t\t.get(entityId, scopeId),\n\t);\n}\n\nexport function assertMemoryScopeNotRetired(db: Database, entityId: string, scopeId: string): void {\n\tif (isMemoryScopeRetired(db, entityId, scopeId)) throw new Error(\"memory_scope_retired\");\n}\n\nexport function hasMemoryScopeRetirement(db: Database, entityId: string): boolean {\n\treturn Boolean(\n\t\tdb.prepare(\"SELECT 1 FROM memory_scope_retirements WHERE entity_id = ? LIMIT 1\").get(entityId),\n\t);\n}\n\n/**\n * Caller MUST supply a successfully authenticated transport device identity (or the\n * actual local device for a local move), never an op sender, payload origin or form field.\n * The caller transaction must also perform the move/cleanup; this primitive only fences.\n * An absent qualified identity is verifiable by its namespace owner. A legacy UUID is not.\n */\nexport function recordMemoryScopeRetirement(\n\tdb: Database,\n\tinput: MemoryScopeRetirement,\n\toptions: { authenticatedSourceDeviceId: string; now: string },\n): void {\n\tvalidateRetirement(input);\n\tif (options.authenticatedSourceDeviceId !== input.sourceDeviceId)\n\t\tthrow new Error(\"memory_retirement_sender_mismatch\");\n\tif (!db.inTransaction) throw new Error(\"memory_retirement_transaction_required\");\n\tverifyAuthenticatedMemorySource(db, {\n\t\tentityId: input.entityId,\n\t\tverifiedPeerDeviceId: options.authenticatedSourceDeviceId,\n\t});\n\tassertVerifiedMemorySource(db, input.entityId, input.sourceDeviceId);\n\tif (isMemoryScopeRetired(db, input.entityId, input.retiredScopeId)) return;\n\tdb.prepare(`INSERT INTO memory_scope_retirements(entity_id, source_device_id, retired_scope_id, retired_at)\n\t\tVALUES (?, ?, ?, ?)`).run(\n\t\tinput.entityId,\n\t\tinput.sourceDeviceId,\n\t\tinput.retiredScopeId,\n\t\toptions.now,\n\t);\n}\n","import type { Database } from \"./db.js\";\nimport { ensureMemoryRetirementDeliverySchema } from \"./memory-retirement-delivery-schema.js\";\nimport { ensureMemoryScopeRetirementSchema } from \"./memory-scope-retirement.js\";\nimport { ensureMemorySourceIdentitySchema } from \"./memory-source-identity.js\";\n\nexport function ensureMemoryOwnershipSchemas(db: Database): void {\n\tensureMemorySourceIdentitySchema(db);\n\tensureMemoryScopeRetirementSchema(db);\n\tensureMemoryRetirementDeliverySchema(db);\n\tdb.exec(`CREATE TABLE IF NOT EXISTS memory_ownership_recoveries (\n\t\toperation_id TEXT PRIMARY KEY,\n\t\tactor_id TEXT NOT NULL,\n\t\tdevice_id TEXT NOT NULL,\n\t\trequest_json TEXT NOT NULL,\n\t\treviewed_digest TEXT NOT NULL,\n\t\tresult_json TEXT NOT NULL,\n\t\tcreated_at TEXT NOT NULL\n\t);`);\n}\n","import type { Database } from \"./db.js\";\n\nexport interface RepositoryWorkspaceEvidence {\n\tcwd: string;\n\trecordedIdentitiesJson: string;\n\tfilesystemIdentity: string | null;\n\tfilesystemAnchor: string | null;\n\tanchorMtimeNs: string | null;\n\tcheckedAtMs: number;\n}\n\ninterface RepositoryDiscoveryState {\n\tsource_revision: number;\n\tindexed_revision: number;\n}\n\nfunction discoveryTriggerCount(db: Database): number {\n\treturn db\n\t\t.prepare(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND name IN (\n\t\t\t'trg_repository_discovery_session_insert',\n\t\t\t'trg_repository_discovery_session_update',\n\t\t\t'trg_repository_discovery_session_delete'\n\t\t)`)\n\t\t.pluck()\n\t\t.get() as number;\n}\n\nexport function ensureRepositoryDiscoveryIndex(db: Database): void {\n\tdb.exec(\"SAVEPOINT repository_discovery_repair\");\n\ttry {\n\t\trepairRepositoryDiscoveryIndex(db);\n\t\tdb.exec(\"RELEASE repository_discovery_repair\");\n\t} catch (error) {\n\t\tdb.exec(\"ROLLBACK TO repository_discovery_repair; RELEASE repository_discovery_repair\");\n\t\tthrow error;\n\t}\n}\n\nfunction repairRepositoryDiscoveryIndex(db: Database): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS repository_discovery_state (\n\t\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\t\tsource_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\tindexed_revision INTEGER NOT NULL DEFAULT -1\n\t\t);\n\t\tINSERT OR IGNORE INTO repository_discovery_state(id) VALUES (1);\n\t`);\n\t// Acquire the write lock before checking for missing schema, so no session\n\t// mutation can slip between invalidation and trigger recreation.\n\tdb.prepare(\n\t\t\"UPDATE repository_discovery_state SET indexed_revision = indexed_revision WHERE id = 1\",\n\t).run();\n\tconst evidenceTableExists = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'repository_workspace_evidence'\",\n\t\t)\n\t\t.get();\n\tif (discoveryTriggerCount(db) !== 3 || !evidenceTableExists) {\n\t\t// Missing triggers may have missed writes, and a missing evidence table has\n\t\t// lost its rows. Invalidate in-memory and on-disk snapshots before repair.\n\t\tdb.prepare(`UPDATE repository_discovery_state\n\t\t\t\tSET source_revision = source_revision + 1, indexed_revision = -1 WHERE id = 1`).run();\n\t}\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS repository_workspace_evidence (\n\t\t\tcwd TEXT PRIMARY KEY,\n\t\t\trecorded_identities_json TEXT NOT NULL,\n\t\t\tfilesystem_identity TEXT,\n\t\t\tfilesystem_anchor TEXT,\n\t\t\tanchor_mtime_ns TEXT,\n\t\t\tchecked_at_ms INTEGER NOT NULL\n\t\t);\n\t\tCREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_insert\n\t\tAFTER INSERT ON sessions BEGIN\n\t\t\tUPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n\t\tEND;\n\t\tCREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_update\n\t\tAFTER UPDATE OF cwd, git_remote, metadata_json ON sessions BEGIN\n\t\t\tUPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n\t\tEND;\n\t\tCREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_delete\n\t\tAFTER DELETE ON sessions BEGIN\n\t\t\tUPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n\t\tEND;\n\t`);\n}\n\nexport function repositoryDiscoveryRevision(db: Database): number | null {\n\ttry {\n\t\tif (discoveryTriggerCount(db) !== 3) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT source_revision FROM repository_discovery_state WHERE id = 1\")\n\t\t\t.get() as { source_revision: number } | undefined;\n\t\treturn row?.source_revision ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function loadRepositoryDiscoveryEvidence(\n\tdb: Database,\n): RepositoryWorkspaceEvidence[] | null {\n\ttry {\n\t\treturn db.transaction(() => {\n\t\t\tconst state = db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT source_revision, indexed_revision FROM repository_discovery_state WHERE id = 1\",\n\t\t\t\t)\n\t\t\t\t.get() as RepositoryDiscoveryState | undefined;\n\t\t\tif (!state || state.source_revision !== state.indexed_revision) return null;\n\t\t\treturn db\n\t\t\t\t.prepare(`SELECT cwd, recorded_identities_json AS recordedIdentitiesJson,\n\t\t\t\tfilesystem_identity AS filesystemIdentity, filesystem_anchor AS filesystemAnchor,\n\t\t\t\tanchor_mtime_ns AS anchorMtimeNs, checked_at_ms AS checkedAtMs\n\t\t\t\tFROM repository_workspace_evidence ORDER BY cwd`)\n\t\t\t\t.all() as RepositoryWorkspaceEvidence[];\n\t\t})();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function replaceRepositoryDiscoveryEvidence(\n\tdb: Database,\n\texpectedRevision: number,\n\trows: RepositoryWorkspaceEvidence[],\n): boolean {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (repositoryDiscoveryRevision(db) !== expectedRevision) return false;\n\t\t\tdb.prepare(\"DELETE FROM repository_workspace_evidence\").run();\n\t\t\tconst insert = db.prepare(`INSERT INTO repository_workspace_evidence(\n\t\t\tcwd, recorded_identities_json, filesystem_identity, filesystem_anchor,\n\t\t\tanchor_mtime_ns, checked_at_ms\n\t\t) VALUES (?, ?, ?, ?, ?, ?)`);\n\t\t\tfor (const row of rows) {\n\t\t\t\tinsert.run(\n\t\t\t\t\trow.cwd,\n\t\t\t\t\trow.recordedIdentitiesJson,\n\t\t\t\t\trow.filesystemIdentity,\n\t\t\t\t\trow.filesystemAnchor,\n\t\t\t\t\trow.anchorMtimeNs,\n\t\t\t\t\trow.checkedAtMs,\n\t\t\t\t);\n\t\t\t}\n\t\t\tdb.prepare(\"UPDATE repository_discovery_state SET indexed_revision = ? WHERE id = 1\").run(\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\treturn true;\n\t\t})\n\t\t.immediate();\n}\n","import type { MemoryResult } from \"./types.js\";\n\ntype SummaryLikeInput = {\n\tkind?: string | null;\n\tmetadata?: unknown;\n};\n\nfunction parseMetadataObject(value: unknown): Record<string, unknown> {\n\tif (!value) return {};\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(value) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\t\treturn parsed as Record<string, unknown>;\n\t\t\t}\n\t\t\treturn {};\n\t\t} catch {\n\t\t\treturn {};\n\t\t}\n\t}\n\tif (typeof value === \"object\" && !Array.isArray(value)) {\n\t\treturn value as Record<string, unknown>;\n\t}\n\treturn {};\n}\n\nexport function getSummaryMetadata(metadata: unknown): Record<string, unknown> {\n\treturn parseMetadataObject(metadata);\n}\n\n/** SQL equivalent of isSummaryLikeMemory for a trusted memory-items table alias. */\nexport function summaryLikeSqlPredicate(\n\talias: \"memory_items\" | \"mi\" | \"\" = \"memory_items\",\n): string {\n\tconst prefix = alias ? `${alias}.` : \"\";\n\tconst kind = `${prefix}kind`;\n\tconst metadata = `${prefix}metadata_json`;\n\treturn `(\n\t\tLOWER(TRIM(COALESCE(${kind}, ''))) = 'session_summary'\n\t\tOR CASE WHEN json_valid(COALESCE(${metadata}, '')) = 1 THEN (\n\t\t\tCOALESCE(json_type(${metadata}, '$.is_summary') = 'true', 0)\n\t\t\tOR LOWER(TRIM(COALESCE(json_extract(${metadata}, '$.source'), ''))) = 'observer_summary'\n\t\t) ELSE 0 END\n\t)`;\n}\n\nexport function isSummaryLikeMemory(input: SummaryLikeInput): boolean {\n\tconst kindValue = String(input.kind ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (kindValue === \"session_summary\") return true;\n\tconst metadata = getSummaryMetadata(input.metadata);\n\tif (metadata.is_summary === true) return true;\n\treturn (\n\t\tString(metadata.source ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase() === \"observer_summary\"\n\t);\n}\n\nexport function summaryContinuityFilter(summarySessionId?: number | null): {\n\tclauses: string[];\n\tparams: number[];\n} {\n\tif (summarySessionId === undefined) return { clauses: [], params: [] };\n\tconst predicate = summaryLikeSqlPredicate();\n\tif (summarySessionId === null) return { clauses: [`NOT ${predicate}`], params: [] };\n\treturn {\n\t\tclauses: [`(NOT ${predicate} OR memory_items.session_id = ?)`],\n\t\tparams: [summarySessionId],\n\t};\n}\n\nexport function isNativeSessionSummaryMemory(input: SummaryLikeInput): boolean {\n\tconst kindValue = String(input.kind ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (kindValue !== \"session_summary\") return false;\n\tconst metadata = getSummaryMetadata(input.metadata);\n\tif (metadata.is_summary === true) return false;\n\treturn (\n\t\tString(metadata.source ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase() !== \"observer_summary\"\n\t);\n}\n\nexport function canonicalMemoryKind(kind: string | null | undefined, metadata?: unknown): string {\n\tconst normalized = String(kind ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (isSummaryLikeMemory({ kind: normalized, metadata })) return \"session_summary\";\n\treturn normalized || \"change\";\n}\n\nexport function canonicalizeMemoryResultKind<T extends Pick<MemoryResult, \"kind\" | \"metadata\">>(\n\titem: T,\n): T {\n\treturn {\n\t\t...item,\n\t\tkind: canonicalMemoryKind(item.kind, item.metadata),\n\t};\n}\n","/**\n * AUTO-GENERATED by scripts/generate-test-schema.ts\n *\n * Do not edit manually. Regenerate with:\n * pnpm --filter @codemem/core run generate:test-schema\n */\n\nexport const TEST_SCHEMA_BASE_DDL =\n\t\"CREATE TABLE IF NOT EXISTS `device_identity_binding_commits` (\\n\\t`commit_digest` text PRIMARY KEY NOT NULL,\\n\\t`reviewed_inventory_digest` text NOT NULL,\\n\\t`request_json` text NOT NULL,\\n\\t`outcomes_json` text NOT NULL,\\n\\t`write_count` integer NOT NULL,\\n\\t`decided_by_identity_id` text NOT NULL,\\n\\t`decided_by_device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `device_identity_binding_audit` (\\n\\t`event_id` text PRIMARY KEY NOT NULL,\\n\\t`commit_digest` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`previous_identity_id` text,\\n\\t`target_identity_id` text NOT NULL,\\n\\t`action` text NOT NULL,\\n\\t`previous_assignment_version` integer,\\n\\t`resulting_assignment_version` integer NOT NULL,\\n\\t`decided_by_identity_id` text NOT NULL,\\n\\t`decided_by_device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\tFOREIGN KEY (`commit_digest`) REFERENCES `device_identity_binding_commits`(`commit_digest`) ON UPDATE no action ON DELETE no action\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_device_identity_binding_audit_commit_device` ON `device_identity_binding_audit` (`commit_digest`,`device_id`);\\nCREATE INDEX IF NOT EXISTS `idx_device_identity_binding_audit_device_created` ON `device_identity_binding_audit` (`device_id`,`created_at`,`event_id`);\\nCREATE TABLE IF NOT EXISTS `sessions` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`started_at` text NOT NULL,\\n\\t`ended_at` text,\\n\\t`cwd` text,\\n\\t`project` text,\\n\\t`git_remote` text,\\n\\t`git_branch` text,\\n\\t`user` text,\\n\\t`tool_version` text,\\n\\t`metadata_json` text,\\n\\t`import_key` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_sessions_started_id` ON `sessions` (`started_at`,`id`);\\nCREATE TABLE IF NOT EXISTS `replication_scopes` (\\n\\t`scope_id` text PRIMARY KEY NOT NULL,\\n\\t`label` text NOT NULL,\\n\\t`kind` text DEFAULT 'user' NOT NULL,\\n\\t`authority_type` text DEFAULT 'local' NOT NULL,\\n\\t`coordinator_id` text,\\n\\t`group_id` text,\\n\\t`manifest_issuer_device_id` text,\\n\\t`membership_epoch` integer DEFAULT 0 NOT NULL,\\n\\t`manifest_hash` text,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_status` ON `replication_scopes` (`status`);\\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_authority_group` ON `replication_scopes` (`coordinator_id`,`group_id`);\\nCREATE TABLE IF NOT EXISTS `project_scope_mappings` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`workspace_identity` text,\\n\\t`project_pattern` text NOT NULL,\\n\\t`scope_id` text NOT NULL,\\n\\t`priority` integer DEFAULT 0 NOT NULL,\\n\\t`source` text DEFAULT 'user' NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_workspace_priority` ON `project_scope_mappings` (`workspace_identity`,`priority`);\\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_pattern_priority` ON `project_scope_mappings` (`project_pattern`,`priority`);\\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_scope` ON `project_scope_mappings` (`scope_id`);\\nCREATE TABLE IF NOT EXISTS `scope_memberships` (\\n\\t`scope_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`role` text DEFAULT 'member' NOT NULL,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`membership_epoch` integer DEFAULT 0 NOT NULL,\\n\\t`coordinator_id` text,\\n\\t`group_id` text,\\n\\t`manifest_issuer_device_id` text,\\n\\t`manifest_hash` text,\\n\\t`signed_manifest_json` text,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`scope_id`, `device_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_device_status` ON `scope_memberships` (`device_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_scope_status` ON `scope_memberships` (`scope_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_authority_group` ON `scope_memberships` (`coordinator_id`,`group_id`);\\nCREATE TABLE IF NOT EXISTS `artifacts` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer NOT NULL,\\n\\t`kind` text NOT NULL,\\n\\t`path` text,\\n\\t`content_text` text,\\n\\t`content_hash` text,\\n\\t`created_at` text NOT NULL,\\n\\t`metadata_json` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_artifacts_session_kind` ON `artifacts` (`session_id`,`kind`);\\nCREATE TABLE IF NOT EXISTS `memory_items` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer NOT NULL,\\n\\t`kind` text NOT NULL,\\n\\t`title` text NOT NULL,\\n\\t`subtitle` text,\\n\\t`body_text` text NOT NULL,\\n\\t`confidence` real DEFAULT 0.5,\\n\\t`tags_text` text DEFAULT '',\\n\\t`active` integer DEFAULT 1,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\t`metadata_json` text,\\n\\t`actor_id` text,\\n\\t`actor_display_name` text,\\n\\t`visibility` text,\\n\\t`workspace_id` text,\\n\\t`workspace_kind` text,\\n\\t`origin_device_id` text,\\n\\t`origin_source` text,\\n\\t`trust_state` text,\\n\\t`facts` text,\\n\\t`narrative` text,\\n\\t`concepts` text,\\n\\t`files_read` text,\\n\\t`files_modified` text,\\n\\t`user_prompt_id` integer,\\n\\t`prompt_number` integer,\\n\\t`deleted_at` text,\\n\\t`rev` integer DEFAULT 0,\\n\\t`dedup_key` text,\\n\\t`import_key` text,\\n\\t`scope_id` text,\\n\\t`project` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_active_created` ON `memory_items` (`active`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_created_id` ON `memory_items` (`created_at`,`id`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_origin_device_active` ON `memory_items` (`origin_device_id`,`active`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_session` ON `memory_items` (`session_id`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_project` ON `memory_items` (`project`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_visibility_created` ON `memory_items` (`scope_id`,`visibility`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_backfill_pending` ON `memory_items` (`id`) WHERE scope_id IS NULL OR scope_id = '';\\nCREATE INDEX IF NOT EXISTS `idx_memory_items_dedup_key_active_created` ON `memory_items` (`dedup_key`,`active`,`created_at`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_memory_items_same_session_dedup_unique` ON `memory_items` (`session_id`,`kind`,`visibility`,`workspace_id`,`dedup_key`) WHERE active = 1 AND dedup_key IS NOT NULL;\\nCREATE TABLE IF NOT EXISTS `memory_file_refs` (\\n\\t`memory_id` integer NOT NULL,\\n\\t`file_path` text NOT NULL,\\n\\t`relation` text NOT NULL,\\n\\tPRIMARY KEY(`memory_id`, `file_path`, `relation`),\\n\\tFOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_memory_file_refs_path` ON `memory_file_refs` (`file_path`);\\nCREATE TABLE IF NOT EXISTS `memory_concept_refs` (\\n\\t`memory_id` integer NOT NULL,\\n\\t`concept` text NOT NULL,\\n\\tPRIMARY KEY(`memory_id`, `concept`),\\n\\tFOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_memory_concept_refs_concept` ON `memory_concept_refs` (`concept`);\\nCREATE TABLE IF NOT EXISTS `usage_events` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer,\\n\\t`event` text NOT NULL,\\n\\t`tokens_read` integer DEFAULT 0,\\n\\t`tokens_written` integer DEFAULT 0,\\n\\t`tokens_saved` integer DEFAULT 0,\\n\\t`created_at` text NOT NULL,\\n\\t`metadata_json` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_usage_events_event_created` ON `usage_events` (`event`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_usage_events_session` ON `usage_events` (`session_id`);\\nCREATE TABLE IF NOT EXISTS `retrieval_attempts` (\\n\\t`attempt_id` text PRIMARY KEY NOT NULL,\\n\\t`contract_version` integer NOT NULL,\\n\\t`surface` text NOT NULL,\\n\\t`trigger` text NOT NULL,\\n\\t`started_at` text NOT NULL,\\n\\t`completed_at` text,\\n\\t`retrieval_status` text NOT NULL,\\n\\t`delivery_status` text NOT NULL,\\n\\t`candidate_count` integer NOT NULL,\\n\\t`selected_count` integer NOT NULL,\\n\\t`persisted_candidate_count` integer NOT NULL,\\n\\t`recorder_version` text NOT NULL,\\n\\t`session_id` integer,\\n\\t`source` text,\\n\\t`stream_id` text,\\n\\t`source_session_id` text,\\n\\t`prompt_number` integer,\\n\\t`request_id` text,\\n\\t`raw_event_start_seq` integer,\\n\\t`raw_event_end_seq` integer,\\n\\t`experiment_id` text,\\n\\t`experiment_cell_id` text,\\n\\t`evaluation_checkout_id` text,\\n\\t`evaluation_fixture_id` text,\\n\\t`evaluation_seed` integer,\\n\\t`latency_ms` integer,\\n\\t`project` text,\\n\\t`scope_id` text,\\n\\t`mode` text,\\n\\t`limit_requested` integer,\\n\\t`token_budget` integer,\\n\\t`output_tokens` integer,\\n\\t`working_set_file_count` integer,\\n\\t`working_set_files_json` text,\\n\\t`query_hash_sha256` text,\\n\\t`query_char_count` integer,\\n\\t`query_token_estimate` integer,\\n\\t`filter_summary_json` text,\\n\\t`failure_code` text,\\n\\t`failure_stage` text,\\n\\t`trace_version` integer,\\n\\t`automatic_recall_json` text,\\n\\t`automatic_recall_key` text,\\n\\t`retention_until` text,\\n\\t`retention_pinned` integer DEFAULT 0 NOT NULL,\\n\\t`retention_finalized_at` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_session_started` ON `retrieval_attempts` (`session_id`,`started_at`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_attempts_automatic_recall_key` ON `retrieval_attempts` (`automatic_recall_key`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_source_stream_started` ON `retrieval_attempts` (`source`,`stream_id`,`started_at`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_retention` ON `retrieval_attempts` (`retention_pinned`,`retention_until`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_started` ON `retrieval_attempts` (`started_at`,`attempt_id`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_surface_started` ON `retrieval_attempts` (`surface`,`started_at`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_attempts_request_identity` ON `retrieval_attempts` (`source`,`surface`,`request_id`) WHERE request_id IS NOT NULL;\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_experiment_cell` ON `retrieval_attempts` (`experiment_id`,`experiment_cell_id`);\\nCREATE TABLE IF NOT EXISTS `retrieval_exposures` (\\n\\t`exposure_id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`attempt_id` text NOT NULL,\\n\\t`memory_id` integer,\\n\\t`memory_import_key` text,\\n\\t`origin_device_id` text,\\n\\t`rank` integer NOT NULL,\\n\\t`disposition` text NOT NULL,\\n\\t`section` text,\\n\\t`handoff_status` text NOT NULL,\\n\\t`memory_rev` integer,\\n\\t`memory_updated_at` text,\\n\\t`memory_scope_id` text,\\n\\t`memory_kind` text,\\n\\t`memory_active` integer,\\n\\t`memory_deleted_at` text,\\n\\t`score_summary_json` text,\\n\\t`reason_codes_json` text,\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `retrieval_attempts`(`attempt_id`) ON UPDATE no action ON DELETE cascade,\\n\\tFOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE set null\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_exposures_attempt_rank` ON `retrieval_exposures` (`attempt_id`,`rank`);\\nCREATE INDEX IF NOT EXISTS `idx_retrieval_exposures_memory` ON `retrieval_exposures` (`memory_id`);\\nCREATE TABLE IF NOT EXISTS `outcome_evidence` (\\n\\t`evidence_id` text PRIMARY KEY NOT NULL,\\n\\t`contract_version` integer NOT NULL,\\n\\t`dimension` text NOT NULL,\\n\\t`evidence_type` text NOT NULL,\\n\\t`source_class` text NOT NULL,\\n\\t`observed_at` text NOT NULL,\\n\\t`producer` text NOT NULL,\\n\\t`producer_version` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`value_type` text,\\n\\t`value_integer` integer,\\n\\t`value_real` real,\\n\\t`value_unit` text,\\n\\t`session_id` integer,\\n\\t`source` text,\\n\\t`stream_id` text,\\n\\t`source_session_id` text,\\n\\t`prompt_number` integer,\\n\\t`raw_event_start_seq` integer,\\n\\t`raw_event_end_seq` integer,\\n\\t`experiment_id` text,\\n\\t`experiment_cell_id` text,\\n\\t`window_start_at` text,\\n\\t`window_end_at` text,\\n\\t`references_json` text,\\n\\t`retention_until` text,\\n\\t`retention_pinned` integer DEFAULT 0 NOT NULL,\\n\\t`retention_finalized_at` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_observed_id` ON `outcome_evidence` (`observed_at`,`evidence_id`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_session_observed` ON `outcome_evidence` (`session_id`,`observed_at`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_source_stream_observed` ON `outcome_evidence` (`source`,`stream_id`,`observed_at`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_type_observed` ON `outcome_evidence` (`evidence_type`,`observed_at`);\\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_retention` ON `outcome_evidence` (`retention_pinned`,`retention_until`);\\nCREATE TABLE IF NOT EXISTS `attribution_assessments` (\\n\\t`assessment_id` text PRIMARY KEY NOT NULL,\\n\\t`contract_version` integer NOT NULL,\\n\\t`subject_type` text NOT NULL,\\n\\t`attempt_id` text NOT NULL,\\n\\t`exposure_id` integer,\\n\\t`dimension` text NOT NULL,\\n\\t`impact_label` text NOT NULL,\\n\\t`basis` text NOT NULL,\\n\\t`confidence_level` text NOT NULL,\\n\\t`method` text NOT NULL,\\n\\t`method_version` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`claim_type` text DEFAULT 'observational' NOT NULL,\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `retrieval_attempts`(`attempt_id`) ON UPDATE no action ON DELETE cascade,\\n\\tFOREIGN KEY (`exposure_id`) REFERENCES `retrieval_exposures`(`exposure_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_attempt_created` ON `attribution_assessments` (`attempt_id`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_label_created` ON `attribution_assessments` (`impact_label`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_exposure` ON `attribution_assessments` (`exposure_id`);\\nCREATE TABLE IF NOT EXISTS `attribution_assessment_evidence` (\\n\\t`assessment_id` text NOT NULL,\\n\\t`evidence_id` text NOT NULL,\\n\\tPRIMARY KEY(`assessment_id`, `evidence_id`),\\n\\tFOREIGN KEY (`assessment_id`) REFERENCES `attribution_assessments`(`assessment_id`) ON UPDATE no action ON DELETE cascade,\\n\\tFOREIGN KEY (`evidence_id`) REFERENCES `outcome_evidence`(`evidence_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessment_evidence_evidence` ON `attribution_assessment_evidence` (`evidence_id`,`assessment_id`);\\nCREATE TABLE IF NOT EXISTS `raw_events` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`event_id` text,\\n\\t`event_seq` integer NOT NULL,\\n\\t`event_type` text NOT NULL,\\n\\t`ts_wall_ms` integer,\\n\\t`ts_mono_ms` real,\\n\\t`payload_json` text NOT NULL,\\n\\t`capture_context_json` text,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_seq` ON `raw_events` (`source`,`stream_id`,`event_seq`);\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_event_id` ON `raw_events` (`source`,`stream_id`,`event_id`);\\nCREATE INDEX IF NOT EXISTS `idx_raw_events_session_seq` ON `raw_events` (`opencode_session_id`,`event_seq`);\\nCREATE INDEX IF NOT EXISTS `idx_raw_events_created` ON `raw_events` (`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_raw_events_capture_context` ON `raw_events` (`source`,`stream_id`,`event_seq`) WHERE \\\"raw_events\\\".\\\"capture_context_json\\\" IS NOT NULL;\\nCREATE TABLE IF NOT EXISTS `raw_event_sessions` (\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`cwd` text,\\n\\t`project` text,\\n\\t`started_at` text,\\n\\t`last_seen_ts_wall_ms` integer,\\n\\t`last_received_event_seq` integer DEFAULT -1 NOT NULL,\\n\\t`last_flushed_event_seq` integer DEFAULT -1 NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`source`, `stream_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_raw_event_sessions_pending_updated` ON `raw_event_sessions` (`updated_at`) WHERE \\\"raw_event_sessions\\\".\\\"last_received_event_seq\\\" > \\\"raw_event_sessions\\\".\\\"last_flushed_event_seq\\\";\\nCREATE TABLE IF NOT EXISTS `opencode_sessions` (\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`session_id` integer,\\n\\t`created_at` text NOT NULL,\\n\\tPRIMARY KEY(`source`, `stream_id`),\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_opencode_sessions_session` ON `opencode_sessions` (`session_id`);\\nCREATE TABLE IF NOT EXISTS `pi_import_state` (\\n\\t`file_path` text PRIMARY KEY NOT NULL,\\n\\t`size_bytes` integer NOT NULL,\\n\\t`mtime_ms` real NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `raw_event_flush_batches` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`source` text DEFAULT 'opencode' NOT NULL,\\n\\t`stream_id` text DEFAULT '' NOT NULL,\\n\\t`opencode_session_id` text NOT NULL,\\n\\t`start_event_seq` integer NOT NULL,\\n\\t`end_event_seq` integer NOT NULL,\\n\\t`extractor_version` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`error_message` text,\\n\\t`error_type` text,\\n\\t`observer_provider` text,\\n\\t`observer_model` text,\\n\\t`observer_runtime` text,\\n\\t`observer_auth_source` text,\\n\\t`observer_auth_type` text,\\n\\t`observer_error_code` text,\\n\\t`observer_error_message` text,\\n\\t`attempt_count` integer DEFAULT 0 NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_flush_batches_source_stream_seq_ver` ON `raw_event_flush_batches` (`source`,`stream_id`,`start_event_seq`,`end_event_seq`,`extractor_version`);\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_session_created` ON `raw_event_flush_batches` (`opencode_session_id`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`);\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_observer_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`) WHERE \\\"raw_event_flush_batches\\\".\\\"observer_provider\\\" IS NOT NULL;\\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_capture_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`) WHERE \\\"raw_event_flush_batches\\\".\\\"observer_provider\\\" IS NULL;\\nCREATE TABLE IF NOT EXISTS `user_prompts` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer,\\n\\t`project` text,\\n\\t`prompt_text` text NOT NULL,\\n\\t`prompt_number` integer,\\n\\t`created_at` text NOT NULL,\\n\\t`created_at_epoch` integer NOT NULL,\\n\\t`metadata_json` text,\\n\\t`import_key` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_session` ON `user_prompts` (`session_id`);\\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_project` ON `user_prompts` (`project`);\\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_epoch` ON `user_prompts` (`created_at_epoch`);\\nCREATE TABLE IF NOT EXISTS `session_summaries` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`session_id` integer,\\n\\t`project` text,\\n\\t`request` text,\\n\\t`investigated` text,\\n\\t`learned` text,\\n\\t`completed` text,\\n\\t`next_steps` text,\\n\\t`notes` text,\\n\\t`files_read` text,\\n\\t`files_edited` text,\\n\\t`prompt_number` integer,\\n\\t`created_at` text NOT NULL,\\n\\t`created_at_epoch` integer NOT NULL,\\n\\t`metadata_json` text,\\n\\t`import_key` text,\\n\\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_session` ON `session_summaries` (`session_id`);\\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_project` ON `session_summaries` (`project`);\\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_epoch` ON `session_summaries` (`created_at_epoch`);\\nCREATE TABLE IF NOT EXISTS `replication_ops` (\\n\\t`op_id` text PRIMARY KEY NOT NULL,\\n\\t`entity_type` text NOT NULL,\\n\\t`entity_id` text NOT NULL,\\n\\t`op_type` text NOT NULL,\\n\\t`payload_json` text,\\n\\t`clock_rev` integer NOT NULL,\\n\\t`clock_updated_at` text NOT NULL,\\n\\t`clock_device_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`scope_id` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_created` ON `replication_ops` (`created_at`,`op_id`);\\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_entity` ON `replication_ops` (`entity_type`,`entity_id`);\\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_scope_created` ON `replication_ops` (`scope_id`,`created_at`,`op_id`);\\nCREATE TABLE IF NOT EXISTS `replication_cursors` (\\n\\t`peer_device_id` text PRIMARY KEY NOT NULL,\\n\\t`last_applied_cursor` text,\\n\\t`last_acked_cursor` text,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `replication_cursors_v2` (\\n\\t`peer_device_id` text NOT NULL,\\n\\t`scope_id` text NOT NULL,\\n\\t`last_applied_cursor` text,\\n\\t`last_acked_cursor` text,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`peer_device_id`, `scope_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_replication_cursors_v2_scope` ON `replication_cursors_v2` (`scope_id`);\\nCREATE TABLE IF NOT EXISTS `sync_peers` (\\n\\t`peer_device_id` text PRIMARY KEY NOT NULL,\\n\\t`name` text,\\n\\t`pinned_fingerprint` text,\\n\\t`public_key` text,\\n\\t`addresses_json` text,\\n\\t`manual_addresses_json` text,\\n\\t`last_success_address` text,\\n\\t`claimed_local_actor` integer DEFAULT 0 NOT NULL,\\n\\t`actor_id` text,\\n\\t`projects_include_json` text,\\n\\t`projects_exclude_json` text,\\n\\t`created_at` text NOT NULL,\\n\\t`last_seen_at` text,\\n\\t`last_sync_at` text,\\n\\t`last_error` text,\\n\\t`runtime_version` text,\\n\\t`runtime_version_observed_at` text,\\n\\t`highest_observed_direct_signature_version` integer,\\n\\t`discovered_via_coordinator_id` text,\\n\\t`discovered_via_group_id` text,\\n\\t`trust_provenance` text,\\n\\t`pending_bootstrap_grant_id` text\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_nonces` (\\n\\t`nonce` text PRIMARY KEY NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_device` (\\n\\t`device_id` text PRIMARY KEY NOT NULL,\\n\\t`public_key` text NOT NULL,\\n\\t`fingerprint` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_attempts` (\\n\\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`peer_device_id` text NOT NULL,\\n\\t`started_at` text NOT NULL,\\n\\t`finished_at` text,\\n\\t`ok` integer NOT NULL,\\n\\t`ops_in` integer NOT NULL,\\n\\t`ops_out` integer NOT NULL,\\n\\t`error` text,\\n\\t`local_sync_capability` text,\\n\\t`peer_sync_capability` text,\\n\\t`negotiated_sync_capability` text,\\n\\t`failure_category` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_peer_started` ON `sync_attempts` (`peer_device_id`,`started_at`);\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_occurred` ON `sync_attempts` (CASE WHEN \\\"finished_at\\\" IS NULL THEN \\\"started_at\\\" ELSE \\\"finished_at\\\" END,`id`);\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_error_occurred` ON `sync_attempts` (CASE WHEN \\\"finished_at\\\" IS NULL THEN \\\"started_at\\\" ELSE \\\"finished_at\\\" END,`id`) WHERE \\\"sync_attempts\\\".\\\"ok\\\" = 0;\\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_success_occurred` ON `sync_attempts` (CASE WHEN \\\"finished_at\\\" IS NULL THEN \\\"started_at\\\" ELSE \\\"finished_at\\\" END,`id`) WHERE \\\"sync_attempts\\\".\\\"ok\\\" <> 0;\\nCREATE TABLE IF NOT EXISTS `sync_scope_rejections` (\\n\\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`peer_device_id` text,\\n\\t`op_id` text NOT NULL,\\n\\t`entity_type` text NOT NULL,\\n\\t`entity_id` text NOT NULL,\\n\\t`scope_id` text,\\n\\t`reason` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_peer_created` ON `sync_scope_rejections` (`peer_device_id`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_scope_created` ON `sync_scope_rejections` (`scope_id`,`created_at`);\\nCREATE TABLE IF NOT EXISTS `sync_daemon_state` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`last_error` text,\\n\\t`last_traceback` text,\\n\\t`last_error_at` text,\\n\\t`last_ok_at` text,\\n\\t`phase` text\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_reset_state` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`snapshot_id` text NOT NULL,\\n\\t`baseline_cursor` text,\\n\\t`retained_floor_cursor` text,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_reset_state_v2` (\\n\\t`scope_id` text PRIMARY KEY NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`snapshot_id` text NOT NULL,\\n\\t`baseline_cursor` text,\\n\\t`retained_floor_cursor` text,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `sync_retention_state_v2` (\\n\\t`scope_id` text PRIMARY KEY NOT NULL,\\n\\t`last_run_at` text,\\n\\t`last_duration_ms` integer,\\n\\t`last_deleted_ops` integer DEFAULT 0 NOT NULL,\\n\\t`last_estimated_bytes_before` integer,\\n\\t`last_estimated_bytes_after` integer,\\n\\t`retained_floor_cursor` text,\\n\\t`last_error` text,\\n\\t`last_error_at` text\\n);\\n\\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_samples` (\\n\\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`inserted_events` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_invalid` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_duplicate` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_conflict` integer DEFAULT 0 NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_stats` (\\n\\t`id` integer PRIMARY KEY NOT NULL,\\n\\t`inserted_events` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_events` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_invalid` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_duplicate` integer DEFAULT 0 NOT NULL,\\n\\t`skipped_conflict` integer DEFAULT 0 NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `coordinator_group_preferences` (\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`projects_include_json` text,\\n\\t`projects_exclude_json` text,\\n\\t`auto_seed_scope` integer DEFAULT 1 NOT NULL,\\n\\t`default_space_scope_id` text,\\n\\t`auto_grant_default_space_on_join` integer DEFAULT 0 NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`coordinator_id`, `group_id`)\\n);\\n\\nCREATE TABLE IF NOT EXISTS `actors` (\\n\\t`actor_id` text PRIMARY KEY NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`is_local` integer DEFAULT 0 NOT NULL,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`merged_into_actor_id` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_actors_is_local` ON `actors` (`is_local`);\\nCREATE INDEX IF NOT EXISTS `idx_actors_status` ON `actors` (`status`);\\nCREATE TABLE IF NOT EXISTS `recipient_policy_review_resolutions` (\\n\\t`review_item_id` text NOT NULL,\\n\\t`source_fingerprint` text NOT NULL,\\n\\t`decision` text NOT NULL,\\n\\t`decision_input_json` text NOT NULL,\\n\\t`preview_json` text NOT NULL,\\n\\t`decided_by_identity_id` text NOT NULL,\\n\\t`decided_by_device_id` text NOT NULL,\\n\\t`resolved_at` text NOT NULL,\\n\\tPRIMARY KEY(`review_item_id`, `source_fingerprint`)\\n);\\n\\nCREATE TABLE IF NOT EXISTS `coordinator_enrollment_reconciliation_issues` (\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`kind` text NOT NULL,\\n\\t`reference_id` text NOT NULL,\\n\\t`code` text NOT NULL,\\n\\t`status` text DEFAULT 'open' NOT NULL,\\n\\t`first_seen_at` text NOT NULL,\\n\\t`last_seen_at` text NOT NULL,\\n\\t`resolved_at` text,\\n\\t`occurrence_count` integer DEFAULT 1 NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`coordinator_id`, `group_id`, `kind`, `reference_id`, `code`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_coordinator_enrollment_issues_boundary_status` ON `coordinator_enrollment_reconciliation_issues` (`coordinator_id`,`group_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_coordinator_enrollment_issues_status_recent` ON `coordinator_enrollment_reconciliation_issues` (`status`,`last_seen_at`,`resolved_at`);\\nCREATE TABLE IF NOT EXISTS `policy_teams` (\\n\\t`team_id` text PRIMARY KEY NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`device_eligibility_mode` text DEFAULT 'person_all_devices' NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `policy_teams_idempotency_key_unique` ON `policy_teams` (`idempotency_key`);\\nCREATE TABLE IF NOT EXISTS `policy_team_memberships` (\\n\\t`team_id` text NOT NULL,\\n\\t`identity_id` text NOT NULL,\\n\\t`role` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`team_id`, `identity_id`)\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `policy_team_memberships_idempotency_key_unique` ON `policy_team_memberships` (`idempotency_key`);\\nCREATE INDEX IF NOT EXISTS `idx_policy_team_memberships_identity_status` ON `policy_team_memberships` (`identity_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `policy_team_device_decisions` (\\n\\t`team_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`decision` text NOT NULL,\\n\\t`assignment_version` integer DEFAULT 0 NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`team_id`, `device_id`),\\n\\tFOREIGN KEY (`team_id`) REFERENCES `policy_teams`(`team_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_policy_team_device_decisions_device` ON `policy_team_device_decisions` (`device_id`);\\nCREATE TABLE IF NOT EXISTS `identity_devices` (\\n\\t`device_id` text PRIMARY KEY NOT NULL,\\n\\t`identity_id` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`assignment_version` integer DEFAULT 0 NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `identity_devices_idempotency_key_unique` ON `identity_devices` (`idempotency_key`);\\nCREATE INDEX IF NOT EXISTS `idx_identity_devices_identity_status` ON `identity_devices` (`identity_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `project_recipients` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`recipient_kind` text NOT NULL,\\n\\t`recipient_id` text NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`provenance` text NOT NULL,\\n\\t`policy_revision` text NOT NULL,\\n\\t`migration_state` text NOT NULL,\\n\\t`source_fingerprint` text,\\n\\t`idempotency_key` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`canonical_project_identity`, `recipient_kind`, `recipient_id`)\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `project_recipients_idempotency_key_unique` ON `project_recipients` (`idempotency_key`);\\nCREATE INDEX IF NOT EXISTS `idx_project_recipients_project_status` ON `project_recipients` (`canonical_project_identity`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_project_recipients_recipient_status` ON `project_recipients` (`recipient_kind`,`recipient_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_drafts` (\\n\\t`attempt_id` text PRIMARY KEY NOT NULL,\\n\\t`candidate_id` text NOT NULL,\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`state` text DEFAULT 'needs_setup' NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`roster_fingerprint` text NOT NULL,\\n\\t`projection_fingerprint` text NOT NULL,\\n\\t`finish_digest` text,\\n\\t`safe_error_code` text,\\n\\t`completed_team_id` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\t`completed_at` text,\\n\\t`superseded_at` text\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_candidate_state` ON `legacy_team_setup_drafts` (`candidate_id`,`state`,`created_at`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_state_updated` ON `legacy_team_setup_drafts` (`state`,`updated_at`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_finish_digest` ON `legacy_team_setup_drafts` (`finish_digest`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_completions` (\\n\\t`attempt_id` text NOT NULL,\\n\\t`finish_digest` text NOT NULL,\\n\\t`candidate_ref` text NOT NULL,\\n\\t`confirmed_access_delta_digest` text NOT NULL,\\n\\t`completed_team_id` text NOT NULL,\\n\\t`response_json` text NOT NULL,\\n\\t`completed_at` text NOT NULL,\\n\\t`created_at` text NOT NULL\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_legacy_team_setup_completions_attempt_finish` ON `legacy_team_setup_completions` (`attempt_id`,`finish_digest`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_completions_exact_replay` ON `legacy_team_setup_completions` (`candidate_ref`,`attempt_id`,`finish_digest`,`confirmed_access_delta_digest`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_draft_devices` (\\n\\t`attempt_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`device_ref` text NOT NULL,\\n\\t`key_fingerprint` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`enabled` integer NOT NULL,\\n\\t`existing_identity_id` text,\\n\\t`existing_assignment_version` integer,\\n\\t`verified_evidence_kind` text,\\n\\t`identity_evidence` text,\\n\\t`decision` text DEFAULT 'unresolved' NOT NULL,\\n\\t`target_identity_id` text,\\n\\t`expected_assignment_kind` text,\\n\\t`expected_assignment_version` integer,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`attempt_id`, `device_id`),\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `legacy_team_setup_drafts`(`attempt_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_legacy_team_setup_devices_attempt_ref` ON `legacy_team_setup_draft_devices` (`attempt_id`,`device_ref`);\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_devices_attempt_decision` ON `legacy_team_setup_draft_devices` (`attempt_id`,`decision`);\\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_draft_projects` (\\n\\t`attempt_id` text NOT NULL,\\n\\t`project_ref` text NOT NULL,\\n\\t`source_project_identity` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`source_fingerprint` text NOT NULL,\\n\\t`resolution_kind` text DEFAULT 'unresolved' NOT NULL,\\n\\t`resolved_project_identity` text,\\n\\t`target_scope_id` text,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`attempt_id`, `project_ref`),\\n\\tFOREIGN KEY (`attempt_id`) REFERENCES `legacy_team_setup_drafts`(`attempt_id`) ON UPDATE no action ON DELETE cascade\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_projects_attempt_resolution` ON `legacy_team_setup_draft_projects` (`attempt_id`,`resolution_kind`);\\nCREATE TABLE IF NOT EXISTS `recipient_managed_project_projections` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`display_name` text NOT NULL,\\n\\t`managed_scope_id` text NOT NULL,\\n\\t`coordinator_id` text NOT NULL,\\n\\t`group_id` text NOT NULL,\\n\\t`recipient_identity_id` text NOT NULL,\\n\\t`accepting_device_id` text NOT NULL,\\n\\t`source_operation_id` text NOT NULL,\\n\\t`reviewed_project_set_digest` text NOT NULL,\\n\\t`status` text DEFAULT 'active' NOT NULL,\\n\\t`accepted_at` text NOT NULL,\\n\\t`revoked_at` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`source_operation_id`, `canonical_project_identity`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_recipient_managed_projects_identity_status` ON `recipient_managed_project_projections` (`recipient_identity_id`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_recipient_managed_projects_scope_authority` ON `recipient_managed_project_projections` (`managed_scope_id`,`coordinator_id`,`group_id`,`status`);\\nCREATE TABLE IF NOT EXISTS `recipient_policy_authority_states` (\\n\\t`canonical_project_identity` text PRIMARY KEY NOT NULL,\\n\\t`authority_state` text DEFAULT 'legacy' NOT NULL,\\n\\t`generation` integer DEFAULT 0 NOT NULL,\\n\\t`desired_devices_digest` text,\\n\\t`current_devices_digest` text,\\n\\t`stable_parity_evidence_digest` text,\\n\\t`stable_parity_passed_at` text,\\n\\t`fresh_snapshot_fingerprint` text,\\n\\t`fresh_snapshot_observed_at` text,\\n\\t`safe_error_code` text,\\n\\t`state_changed_at` text NOT NULL,\\n\\t`last_error_at` text,\\n\\t`attempt_count` integer DEFAULT 0 NOT NULL,\\n\\t`last_attempt_at` text,\\n\\t`wake_epoch` integer DEFAULT 0 NOT NULL,\\n\\t`last_completed_at` text,\\n\\t`lease_owner` text,\\n\\t`lease_acquired_at` text,\\n\\t`lease_expires_at` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL\\n);\\n\\nCREATE TABLE IF NOT EXISTS `recipient_policy_reconciliation_steps` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`step_key` text NOT NULL,\\n\\t`effect_id` text NOT NULL,\\n\\t`payload_digest` text NOT NULL,\\n\\t`status` text DEFAULT 'pending' NOT NULL,\\n\\t`attempt_count` integer DEFAULT 0 NOT NULL,\\n\\t`started_at` text,\\n\\t`completed_at` text,\\n\\t`last_attempt_at` text,\\n\\t`safe_error_code` text,\\n\\t`error_at` text,\\n\\t`lease_owner` text,\\n\\t`lease_acquired_at` text,\\n\\t`lease_expires_at` text,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`canonical_project_identity`, `generation`, `step_key`)\\n);\\n\\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_effect` ON `recipient_policy_reconciliation_steps` (`effect_id`);\\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_status` ON `recipient_policy_reconciliation_steps` (`canonical_project_identity`,`status`);\\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_pending_refresh` ON `recipient_policy_reconciliation_steps` (`canonical_project_identity`,`generation`,`step_key`) WHERE \\\"recipient_policy_reconciliation_steps\\\".\\\"status\\\" IN ('pending', 'running', 'failed') AND \\\"recipient_policy_reconciliation_steps\\\".\\\"step_key\\\" GLOB 'refresh-after-revocations-v2:*';\\nCREATE TABLE IF NOT EXISTS `recipient_policy_deny_overlays` (\\n\\t`canonical_project_identity` text NOT NULL,\\n\\t`scope_id` text NOT NULL,\\n\\t`device_id` text NOT NULL,\\n\\t`generation` integer NOT NULL,\\n\\t`reason_code` text NOT NULL,\\n\\t`created_at` text NOT NULL,\\n\\t`updated_at` text NOT NULL,\\n\\tPRIMARY KEY(`canonical_project_identity`, `scope_id`, `device_id`)\\n);\\n\\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_deny_overlays_scope_device` ON `recipient_policy_deny_overlays` (`scope_id`,`device_id`);\";\n","import type { Database } from \"better-sqlite3\";\n\nconst INDEX_NAME = \"idx_usage_events_public_aggregate_cover\";\n\n/** Keep dashboard aggregates on the small index instead of decoding metadata on every read. */\nexport function ensureUsageEventsAggregateIndex(db: Database): void {\n\tif (db.readonly) return;\n\ttry {\n\t\tif (db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?\").get(INDEX_NAME))\n\t\t\treturn;\n\t\t// Match classifiedUsageSql's JSON expression and public-row predicate exactly.\n\t\t// Built-in JSON functions keep the derived index writable by older clients.\n\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_usage_events_public_aggregate_cover\n\t\t\tON usage_events (\n\t\t\t\tevent,\n\t\t\t\tCASE WHEN json_valid(metadata_json)\n\t\t\t\t\tTHEN json_extract(metadata_json, '$.token_usage.source') ELSE NULL END,\n\t\t\t\ttokens_read, tokens_written, tokens_saved, session_id\n\t\t\t)\n\t\t\tWHERE event != 'observer_recovery_scope_denial'\n\t\t\t\tAND event NOT GLOB 'observer_recovery_call_clock:*'`);\n\t} catch {\n\t\t// Optional access path: locked, query-only and partial legacy schemas keep\n\t\t// their existing aggregate queries and retry on the next writable open.\n\t}\n}\n","import type { Database } from \"better-sqlite3\";\n\nconst TRIGGERS = [\n\t[\"insert\", \"AFTER INSERT\", \"\"],\n\t[\"delete\", \"AFTER DELETE\", \"\"],\n\t[\n\t\t\"update\",\n\t\t// UPDATE OF id misses writes through rowid/_rowid_/oid aliases.\n\t\t\"AFTER UPDATE\",\n\t\t\"WHEN OLD.id IS NOT NEW.id OR OLD.title IS NOT NEW.title OR OLD.body_text IS NOT NEW.body_text OR OLD.active IS NOT NEW.active\",\n\t],\n].map(([suffix, event, condition]) => ({\n\tname: `vector_corpus_epoch_${suffix}`,\n\tsql: `CREATE TRIGGER vector_corpus_epoch_${suffix} ${event} ON memory_items ${condition}\n\tBEGIN UPDATE vector_corpus_epoch SET epoch = epoch + 1 WHERE id = 1; END`,\n}));\n\nfunction hasCurrentTriggers(db: Database): boolean {\n\tconst select = db.prepare(\"SELECT sql FROM sqlite_schema WHERE type = 'trigger' AND name = ?\");\n\treturn TRIGGERS.every(\n\t\t({ name, sql }) => (select.get(name) as { sql: string } | undefined)?.sql === sql,\n\t);\n}\n\n/** Ordinary-table triggers also observe writes from older application versions. */\nexport function ensureVectorCorpusEpoch(db: Database): void {\n\tif (db.readonly) return;\n\ttry {\n\t\tinstallVectorCorpusEpoch(db);\n\t} catch {\n\t\t// Optional derived state: minimal/query-only/locked handles retain the\n\t\t// conservative mutation fence. The installation transaction rolls back.\n\t}\n}\n\nfunction installVectorCorpusEpoch(db: Database): void {\n\tconst columns = db.prepare(\"PRAGMA table_info(memory_items)\").all() as { name: string }[];\n\tif (![\"id\", \"title\", \"body_text\", \"active\"].every((name) => columns.some((c) => c.name === name)))\n\t\treturn;\n\tif (readVectorCorpusFence(db).epoch !== null) return;\n\tdb.transaction(() => {\n\t\tdb.exec(\n\t\t\t\"CREATE TABLE IF NOT EXISTS vector_corpus_epoch (id INTEGER PRIMARY KEY CHECK (id = 1), epoch INTEGER NOT NULL CHECK (typeof(epoch) = 'integer' AND epoch >= 0))\",\n\t\t);\n\t\tconst initialized = db\n\t\t\t.prepare(\"INSERT OR IGNORE INTO vector_corpus_epoch VALUES (1, 0)\")\n\t\t\t.run().changes;\n\t\tif (!initialized && hasCurrentTriggers(db)) return;\n\t\tfor (const { name, sql } of TRIGGERS) {\n\t\t\tdb.exec(`DROP TRIGGER IF EXISTS ${name}`);\n\t\t\tdb.exec(sql);\n\t\t}\n\t\tdb.exec(\"UPDATE vector_corpus_epoch SET epoch = epoch + 1 WHERE id = 1\");\n\t}).immediate();\n}\n\n/** Compare both fields: repairing a deleted counter row can repeat an epoch. */\nexport type VectorCorpusFence = { schemaVersion: number; epoch: string | null };\n\nexport function readVectorCorpusFence(db: Database): VectorCorpusFence {\n\tconst schemaVersion = Number(db.pragma(\"schema_version\", { simple: true }));\n\ttry {\n\t\tif (!hasCurrentTriggers(db)) return { schemaVersion, epoch: null };\n\t\tconst row = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT CAST(epoch AS TEXT) AS epoch FROM vector_corpus_epoch WHERE id = 1 AND typeof(epoch) = 'integer' AND epoch >= 0\",\n\t\t\t)\n\t\t\t.get() as { epoch: string } | undefined;\n\t\treturn { schemaVersion, epoch: row?.epoch ?? null };\n\t} catch {\n\t\t// Minimal/legacy schemas retain the conservative global mutation fence.\n\t\treturn { schemaVersion, epoch: null };\n\t}\n}\n","import type { Database } from \"better-sqlite3\";\nimport {\n\tgetSchemaVersion,\n\tIDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL,\n\tisEmbeddingDisabled,\n\tloadSqliteVec,\n\tREQUIRED_BOOTSTRAPPED_TABLES,\n\tSCHEMA_VERSION,\n} from \"./database-runtime-primitives.js\";\nimport { ensureMemoryOwnershipSchemas } from \"./memory-ownership-recovery-schema.js\";\nimport { summaryLikeSqlPredicate } from \"./summary-memory.js\";\nimport { TEST_SCHEMA_BASE_DDL } from \"./test-schema.generated.js\";\nimport { ensureUsageEventsAggregateIndex } from \"./usage-aggregate-index.js\";\nimport { ensureVectorCorpusEpoch } from \"./vector-corpus-epoch.js\";\n\n/** Additive derived index; the existence check keeps later opens read-only here. */\nexport function ensureMemoryAggregateIndex(db: Database): void {\n\tif (db.readonly || !tableExists(db, \"memory_items\")) return;\n\tif (\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_memory_items_scope_aggregates'\",\n\t\t\t)\n\t\t\t.get()\n\t)\n\t\treturn;\n\t// Partial legacy schemas may not have gained these additive columns yet.\n\tif (!columnExists(db, \"memory_items\", \"scope_id\") || !columnExists(db, \"memory_items\", \"project\"))\n\t\treturn;\n\t// SQLite matches expression indexes syntactically. Use the same safe JSON\n\t// classifier as reads, without table qualifiers (not allowed in index DDL).\n\ttry {\n\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_memory_items_scope_aggregates\n\t\t\tON memory_items(scope_id, active, session_id, TRIM(tags_text) != '',\n\t\t\t\t${summaryLikeSqlPredicate(\"\")}, project)`);\n\t} catch {\n\t\t// Optional derived index: a locked/partial legacy DB retains ordinary reads\n\t\t// and retries on its next writable open, like the other paging indexes.\n\t}\n}\n\nconst RETRIEVAL_EXPOSURE_DETACH_UNAVAILABLE_MEMORY_DDL = `\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_unavailable_memory\nAFTER INSERT ON retrieval_exposures\nWHEN NEW.memory_id IS NOT NULL AND NOT EXISTS (\n\tSELECT 1 FROM memory_items\n\tWHERE memory_items.id = NEW.memory_id\n\t AND memory_items.active != 0\n\t AND memory_items.deleted_at IS NULL\n\t AND (\n\t\t(\n\t\t\tNEW.memory_import_key IS NOT NULL\n\t\t\tAND TRIM(NEW.memory_import_key) != ''\n\t\t\tAND import_key IS NOT NULL\n\t\t\tAND TRIM(import_key) != ''\n\t\t\tAND NEW.memory_import_key = import_key\n\t\t\tAND (\n\t\t\t\tNEW.origin_device_id IS NULL\n\t\t\t\tOR TRIM(NEW.origin_device_id) = ''\n\t\t\t\tOR (\n\t\t\t\t\torigin_device_id IS NOT NULL\n\t\t\t\t\tAND TRIM(origin_device_id) != ''\n\t\t\t\t\tAND NEW.origin_device_id = origin_device_id\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\tOR (\n\t\t\t(NEW.memory_import_key IS NULL OR TRIM(NEW.memory_import_key) = '')\n\t\t\tAND NEW.memory_rev = rev\n\t\t\tAND julianday(NEW.memory_updated_at) IS NOT NULL\n\t\t\tAND julianday(updated_at) IS NOT NULL\n\t\t\tAND julianday(NEW.memory_updated_at) = julianday(updated_at)\n\t\t\tAND NEW.memory_scope_id IS scope_id\n\t\t\tAND NEW.memory_kind = kind\n\t\t\tAND NEW.memory_active = active\n\t\t\tAND NEW.memory_deleted_at IS deleted_at\n\t\t)\n\t )\n)\nBEGIN\n\tUPDATE retrieval_exposures SET memory_id = NULL WHERE exposure_id = NEW.exposure_id;\nEND;\n`;\n\nconst RETRIEVAL_LEDGER_DDL = `\nCREATE TABLE IF NOT EXISTS retrieval_attempts (\n\tattempt_id TEXT PRIMARY KEY NOT NULL,\n\tcontract_version INTEGER NOT NULL,\n\tsurface TEXT NOT NULL,\n\ttrigger TEXT NOT NULL,\n\tstarted_at TEXT NOT NULL,\n\tcompleted_at TEXT,\n\tretrieval_status TEXT NOT NULL,\n\tdelivery_status TEXT NOT NULL,\n\tcandidate_count INTEGER NOT NULL,\n\tselected_count INTEGER NOT NULL,\n\tpersisted_candidate_count INTEGER NOT NULL,\n\trecorder_version TEXT NOT NULL,\n\tsession_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n\tsource TEXT,\n\tstream_id TEXT,\n\tsource_session_id TEXT,\n\tprompt_number INTEGER,\n\trequest_id TEXT,\n\traw_event_start_seq INTEGER,\n\traw_event_end_seq INTEGER,\n\texperiment_id TEXT,\n\texperiment_cell_id TEXT,\n\tevaluation_checkout_id TEXT,\n\tevaluation_fixture_id TEXT,\n\tevaluation_seed INTEGER,\n\tlatency_ms INTEGER,\n\tproject TEXT,\n\tscope_id TEXT,\n\tmode TEXT,\n\tlimit_requested INTEGER,\n\ttoken_budget INTEGER,\n\toutput_tokens INTEGER,\n\tworking_set_file_count INTEGER,\n\tworking_set_files_json TEXT,\n\tquery_hash_sha256 TEXT,\n\tquery_char_count INTEGER,\n\tquery_token_estimate INTEGER,\n\tfilter_summary_json TEXT,\n\tfailure_code TEXT,\n\tfailure_stage TEXT,\n\ttrace_version INTEGER,\n\tautomatic_recall_json TEXT,\n\tautomatic_recall_key TEXT,\n\tretention_until TEXT,\n\tretention_pinned INTEGER NOT NULL DEFAULT 0,\n\tretention_finalized_at TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_session_started\n\tON retrieval_attempts(session_id, started_at);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_source_stream_started\n\tON retrieval_attempts(source, stream_id, started_at);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_retention\n\tON retrieval_attempts(retention_pinned, retention_until);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_started\n\tON retrieval_attempts(started_at, attempt_id);\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_surface_started\n\tON retrieval_attempts(surface, started_at);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_attempts_request_identity\n\tON retrieval_attempts(source, surface, request_id) WHERE request_id IS NOT NULL;\nCREATE INDEX IF NOT EXISTS idx_retrieval_attempts_experiment_cell\n\tON retrieval_attempts(experiment_id, experiment_cell_id);\n\nCREATE TABLE IF NOT EXISTS retrieval_exposures (\n\texposure_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n\tattempt_id TEXT NOT NULL REFERENCES retrieval_attempts(attempt_id) ON DELETE CASCADE,\n\tmemory_id INTEGER REFERENCES memory_items(id) ON DELETE SET NULL,\n\tmemory_import_key TEXT,\n\torigin_device_id TEXT,\n\trank INTEGER NOT NULL,\n\tdisposition TEXT NOT NULL,\n\tsection TEXT,\n\thandoff_status TEXT NOT NULL,\n\tmemory_rev INTEGER,\n\tmemory_updated_at TEXT,\n\tmemory_scope_id TEXT,\n\tmemory_kind TEXT,\n\tmemory_active INTEGER,\n\tmemory_deleted_at TEXT,\n\tscore_summary_json TEXT,\n\treason_codes_json TEXT\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_exposures_attempt_rank\n\tON retrieval_exposures(attempt_id, rank);\nCREATE INDEX IF NOT EXISTS idx_retrieval_exposures_memory\n\tON retrieval_exposures(memory_id);\n\nCREATE TABLE IF NOT EXISTS outcome_evidence (\n\tevidence_id TEXT PRIMARY KEY NOT NULL,\n\tcontract_version INTEGER NOT NULL,\n\tdimension TEXT NOT NULL,\n\tevidence_type TEXT NOT NULL,\n\tsource_class TEXT NOT NULL,\n\tobserved_at TEXT NOT NULL,\n\tproducer TEXT NOT NULL,\n\tproducer_version TEXT NOT NULL,\n\tstatus TEXT NOT NULL,\n\tvalue_type TEXT,\n\tvalue_integer INTEGER,\n\tvalue_real REAL,\n\tvalue_unit TEXT,\n\tsession_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n\tsource TEXT,\n\tstream_id TEXT,\n\tsource_session_id TEXT,\n\tprompt_number INTEGER,\n\traw_event_start_seq INTEGER,\n\traw_event_end_seq INTEGER,\n\texperiment_id TEXT,\n\texperiment_cell_id TEXT,\n\twindow_start_at TEXT,\n\twindow_end_at TEXT,\n\treferences_json TEXT,\n\tretention_until TEXT,\n\tretention_pinned INTEGER NOT NULL DEFAULT 0,\n\tretention_finalized_at TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_observed_id\n\tON outcome_evidence(observed_at, evidence_id);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_session_observed\n\tON outcome_evidence(session_id, observed_at);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_source_stream_observed\n\tON outcome_evidence(source, stream_id, observed_at);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_type_observed\n\tON outcome_evidence(evidence_type, observed_at);\nCREATE INDEX IF NOT EXISTS idx_outcome_evidence_retention\n\tON outcome_evidence(retention_pinned, retention_until);\n\nCREATE TABLE IF NOT EXISTS attribution_assessments (\n\tassessment_id TEXT PRIMARY KEY NOT NULL,\n\tcontract_version INTEGER NOT NULL,\n\tsubject_type TEXT NOT NULL,\n\tattempt_id TEXT NOT NULL REFERENCES retrieval_attempts(attempt_id) ON DELETE CASCADE,\n\texposure_id INTEGER REFERENCES retrieval_exposures(exposure_id) ON DELETE CASCADE,\n\tdimension TEXT NOT NULL,\n\timpact_label TEXT NOT NULL,\n\tbasis TEXT NOT NULL,\n\tconfidence_level TEXT NOT NULL,\n\tmethod TEXT NOT NULL,\n\tmethod_version TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL,\n\tclaim_type TEXT NOT NULL DEFAULT 'observational'\n);\n\nCREATE INDEX IF NOT EXISTS idx_attribution_assessments_attempt_created\n\tON attribution_assessments(attempt_id, created_at);\nCREATE INDEX IF NOT EXISTS idx_attribution_assessments_label_created\n\tON attribution_assessments(impact_label, created_at);\nCREATE INDEX IF NOT EXISTS idx_attribution_assessments_exposure\n\tON attribution_assessments(exposure_id);\n\nCREATE TABLE IF NOT EXISTS attribution_assessment_evidence (\n\tassessment_id TEXT NOT NULL REFERENCES attribution_assessments(assessment_id) ON DELETE CASCADE,\n\tevidence_id TEXT NOT NULL REFERENCES outcome_evidence(evidence_id) ON DELETE CASCADE,\n\tPRIMARY KEY (assessment_id, evidence_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_attribution_assessment_evidence_evidence\n\tON attribution_assessment_evidence(evidence_id, assessment_id);\n\n-- Intentionally handwritten: Drizzle models tables/indexes but not SQLite triggers.\n-- This keeps soft deletion aligned with the FK's physical-delete SET NULL behavior.\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_deleted_memory\nAFTER UPDATE OF active, deleted_at ON memory_items\nWHEN NEW.active = 0 OR NEW.deleted_at IS NOT NULL\nBEGIN\n\tUPDATE retrieval_exposures SET memory_id = NULL WHERE memory_id = NEW.id;\nEND;\n\n-- Foreign keys are checked when the INSERT statement finishes, after AFTER\n-- triggers run, so unavailable or identity-mismatched references can be detached\n-- without losing the immutable exposure snapshot.\n-- Keyless/privacy-redacted linkage requires every memory snapshot field to match.\n-- This narrows, but cannot eliminate, the risk of linking a reused numeric ID.\n${RETRIEVAL_EXPOSURE_DETACH_UNAVAILABLE_MEMORY_DDL}\n\n-- Defensive identity check for callers that disable foreign-key enforcement\n-- while replacing memory rows. Normal writable connections keep foreign keys on,\n-- so ON DELETE SET NULL detaches the link before an ID can be reused.\n-- There is intentionally no keyless fallback here: replacement cannot prove\n-- continuity with a previously linked memory.\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_reused_memory_id\nAFTER INSERT ON memory_items\nWHEN EXISTS (SELECT 1 FROM retrieval_exposures WHERE memory_id = NEW.id)\nBEGIN\n\tUPDATE retrieval_exposures\n\tSET memory_id = NULL\n\tWHERE memory_id = NEW.id\n\t AND (\n\t\tCOALESCE(NEW.active, 0) = 0\n\t\tOR NEW.deleted_at IS NOT NULL\n\t\tOR memory_import_key IS NULL\n\t\tOR TRIM(memory_import_key) = ''\n\t\tOR NEW.import_key IS NULL\n\t\tOR TRIM(NEW.import_key) = ''\n\t\tOR memory_import_key != NEW.import_key\n\t\tOR (\n\t\t\torigin_device_id IS NOT NULL\n\t\t\tAND TRIM(origin_device_id) != ''\n\t\t\tAND (\n\t\t\t\tNEW.origin_device_id IS NULL\n\t\t\t\tOR TRIM(NEW.origin_device_id) = ''\n\t\t\t\tOR origin_device_id != NEW.origin_device_id\n\t\t\t)\n\t\t)\n\t );\nEND;\n`;\n\nconst RETRIEVAL_LEDGER_SCHEMA_OBJECTS = [\n\t\"retrieval_attempts\",\n\t\"retrieval_exposures\",\n\t\"outcome_evidence\",\n\t\"attribution_assessments\",\n\t\"attribution_assessment_evidence\",\n\t\"idx_retrieval_attempts_session_started\",\n\t\"idx_retrieval_attempts_source_stream_started\",\n\t\"idx_retrieval_attempts_retention\",\n\t\"idx_retrieval_attempts_started\",\n\t\"idx_retrieval_attempts_surface_started\",\n\t\"idx_retrieval_attempts_request_identity\",\n\t\"idx_retrieval_attempts_experiment_cell\",\n\t\"idx_retrieval_exposures_attempt_rank\",\n\t\"idx_retrieval_exposures_memory\",\n\t\"idx_outcome_evidence_observed_id\",\n\t\"idx_outcome_evidence_session_observed\",\n\t\"idx_outcome_evidence_source_stream_observed\",\n\t\"idx_outcome_evidence_type_observed\",\n\t\"idx_outcome_evidence_retention\",\n\t\"idx_attribution_assessments_attempt_created\",\n\t\"idx_attribution_assessments_label_created\",\n\t\"idx_attribution_assessments_exposure\",\n\t\"idx_attribution_assessment_evidence_evidence\",\n\t\"trg_retrieval_exposures_detach_deleted_memory\",\n\t\"trg_retrieval_exposures_detach_unavailable_memory\",\n\t\"trg_retrieval_exposures_detach_reused_memory_id\",\n] as const;\n\nconst LEGACY_TEAM_SETUP_DRAFT_DDL = `\nCREATE TABLE IF NOT EXISTS legacy_team_setup_drafts (\n\tattempt_id TEXT PRIMARY KEY NOT NULL,\n\tcandidate_id TEXT NOT NULL,\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tstate TEXT NOT NULL DEFAULT 'needs_setup',\n\tdisplay_name TEXT NOT NULL,\n\troster_fingerprint TEXT NOT NULL,\n\tprojection_fingerprint TEXT NOT NULL,\n\tfinish_digest TEXT,\n\tsafe_error_code TEXT,\n\tcompleted_team_id TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tcompleted_at TEXT,\n\tsuperseded_at TEXT\n);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_candidate_state\n\tON legacy_team_setup_drafts(candidate_id, state, created_at);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_state_updated\n\tON legacy_team_setup_drafts(state, updated_at);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_finish_digest\n\tON legacy_team_setup_drafts(finish_digest);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_completions (\n\tattempt_id TEXT NOT NULL,\n\tfinish_digest TEXT NOT NULL,\n\tcandidate_ref TEXT NOT NULL,\n\tconfirmed_access_delta_digest TEXT NOT NULL,\n\tcompleted_team_id TEXT NOT NULL,\n\tresponse_json TEXT NOT NULL,\n\tcompleted_at TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_legacy_team_setup_completions_attempt_finish\n\tON legacy_team_setup_completions(attempt_id, finish_digest);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_completions_exact_replay\n\tON legacy_team_setup_completions(\n\t\tcandidate_ref,\n\t\tattempt_id,\n\t\tfinish_digest,\n\t\tconfirmed_access_delta_digest\n\t);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_draft_devices (\n\tattempt_id TEXT NOT NULL REFERENCES legacy_team_setup_drafts(attempt_id) ON DELETE CASCADE,\n\tdevice_id TEXT NOT NULL,\n\tdevice_ref TEXT NOT NULL,\n\tkey_fingerprint TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tenabled INTEGER NOT NULL,\n\texisting_identity_id TEXT,\n\texisting_assignment_version INTEGER,\n\tverified_evidence_kind TEXT,\n\tidentity_evidence TEXT,\n\tdecision TEXT NOT NULL DEFAULT 'unresolved',\n\ttarget_identity_id TEXT,\n\texpected_assignment_kind TEXT,\n\texpected_assignment_version INTEGER,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (attempt_id, device_id)\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_legacy_team_setup_devices_attempt_ref\n\tON legacy_team_setup_draft_devices(attempt_id, device_ref);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_devices_attempt_decision\n\tON legacy_team_setup_draft_devices(attempt_id, decision);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_draft_projects (\n\tattempt_id TEXT NOT NULL REFERENCES legacy_team_setup_drafts(attempt_id) ON DELETE CASCADE,\n\tproject_ref TEXT NOT NULL,\n\tsource_project_identity TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tsource_fingerprint TEXT NOT NULL,\n\tresolution_kind TEXT NOT NULL DEFAULT 'unresolved',\n\tresolved_project_identity TEXT,\n\ttarget_scope_id TEXT,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (attempt_id, project_ref)\n);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_projects_attempt_resolution\n\tON legacy_team_setup_draft_projects(attempt_id, resolution_kind);\n`;\n\nexport function ensureLegacyTeamSetupDraftSchema(db: Database): void {\n\tdb.exec(LEGACY_TEAM_SETUP_DRAFT_DDL);\n\tconst finishDigestIndex = db\n\t\t.prepare(\n\t\t\t`SELECT \"unique\" AS is_unique\n\t\t\t FROM pragma_index_list('legacy_team_setup_drafts')\n\t\t\t WHERE name = 'idx_legacy_team_setup_drafts_finish_digest'\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get() as { is_unique?: number } | undefined;\n\tif (finishDigestIndex?.is_unique === 1) {\n\t\tdb.exec(`\n\t\t\tDROP INDEX idx_legacy_team_setup_drafts_finish_digest;\n\t\t\tCREATE INDEX idx_legacy_team_setup_drafts_finish_digest\n\t\t\t\tON legacy_team_setup_drafts(finish_digest);\n\t\t`);\n\t}\n\tfor (const [table, column, definition] of [\n\t\t[\"legacy_team_setup_drafts\", \"safe_error_code\", \"TEXT\"],\n\t\t[\"legacy_team_setup_drafts\", \"completed_team_id\", \"TEXT\"],\n\t\t[\"legacy_team_setup_draft_devices\", \"verified_evidence_kind\", \"TEXT\"],\n\t\t[\"legacy_team_setup_draft_devices\", \"identity_evidence\", \"TEXT\"],\n\t\t[\"legacy_team_setup_draft_projects\", \"target_scope_id\", \"TEXT\"],\n\t] as const) {\n\t\tif (!columnExists(db, table, column)) {\n\t\t\tdb.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);\n\t\t}\n\t}\n\t// Every open, not just when the column is added: an older process may still\n\t// write unmarked drafts, and a crash could split the ALTER from the backfill.\n\tbackfillOpenDraftIdentityEvidence(db);\n}\n\nconst OPEN_DRAFT_DEVICES = `identity_evidence IS NULL AND attempt_id IN (\n\tSELECT attempt_id FROM legacy_team_setup_drafts WHERE state IN ('needs_setup', 'in_progress'))`;\n\n/**\n * Drafts still open at upgrade would otherwise upload other devices' local\n * records as ownership. Mark them now. Completed drafts stay unmarked so\n * republishing reproduces the bytes the coordinator already stored. Without\n * exactly one known running device, every row is a label (fail closed).\n */\nfunction backfillOpenDraftIdentityEvidence(db: Database): void {\n\t// Read first: opening an up-to-date database must not need the write lock.\n\tconst pending = db\n\t\t.prepare(`SELECT 1 FROM legacy_team_setup_draft_devices WHERE ${OPEN_DRAFT_DEVICES} LIMIT 1`)\n\t\t.get();\n\tif (!pending) return;\n\ttry {\n\t\tdb.exec(`UPDATE legacy_team_setup_draft_devices\n\t\t\tSET identity_evidence = CASE WHEN device_id IS (\n\t\t\t\tSELECT CASE WHEN COUNT(*) = 1 THEN MAX(device_id) END FROM sync_device\n\t\t\t) THEN 'self' ELSE 'label' END\n\t\t\tWHERE ${OPEN_DRAFT_DEVICES}`);\n\t} catch {\n\t\tdb.exec(`UPDATE legacy_team_setup_draft_devices SET identity_evidence = 'label'\n\t\t\tWHERE ${OPEN_DRAFT_DEVICES}`);\n\t}\n}\n\nconst SCHEMA_AUX_DDL = `\n${RETRIEVAL_LEDGER_DDL}\n\n${LEGACY_TEAM_SETUP_DRAFT_DDL}\n\nCREATE TABLE IF NOT EXISTS policy_team_device_decisions (\n\tteam_id TEXT NOT NULL REFERENCES policy_teams(team_id) ON DELETE CASCADE,\n\tdevice_id TEXT NOT NULL,\n\tdecision TEXT NOT NULL,\n\tassignment_version INTEGER NOT NULL DEFAULT 0,\n\tprovenance TEXT NOT NULL,\n\trevision TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (team_id, device_id)\n);\nCREATE INDEX IF NOT EXISTS idx_policy_team_device_decisions_device\n\tON policy_team_device_decisions(device_id);\n\nCREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);\n\nCREATE TABLE IF NOT EXISTS sync_peer_signature_state (\n\tpeer_device_id TEXT PRIMARY KEY NOT NULL,\n\thighest_observed_direct_signature_version INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS coordinator_enrollment_reconciliation_issues (\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tkind TEXT NOT NULL,\n\treference_id TEXT NOT NULL,\n\tcode TEXT NOT NULL,\n\tstatus TEXT NOT NULL DEFAULT 'open',\n\tfirst_seen_at TEXT NOT NULL,\n\tlast_seen_at TEXT NOT NULL,\n\tresolved_at TEXT,\n\toccurrence_count INTEGER NOT NULL DEFAULT 1,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (coordinator_id, group_id, kind, reference_id, code)\n);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_boundary_status\n\tON coordinator_enrollment_reconciliation_issues(coordinator_id, group_id, status);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_status_recent\n\tON coordinator_enrollment_reconciliation_issues(status, last_seen_at, resolved_at);\n\nCREATE TABLE IF NOT EXISTS recipient_policy_review_resolutions (\n\treview_item_id TEXT NOT NULL,\n\tsource_fingerprint TEXT NOT NULL,\n\tdecision TEXT NOT NULL,\n\tdecision_input_json TEXT NOT NULL,\n\tpreview_json TEXT NOT NULL,\n\tdecided_by_identity_id TEXT NOT NULL,\n\tdecided_by_device_id TEXT NOT NULL,\n\tresolved_at TEXT NOT NULL,\n\tPRIMARY KEY (review_item_id, source_fingerprint)\n);\n\nCREATE TABLE IF NOT EXISTS device_identity_binding_commits (\n\tcommit_digest TEXT PRIMARY KEY NOT NULL,\n\treviewed_inventory_digest TEXT NOT NULL,\n\trequest_json TEXT NOT NULL,\n\toutcomes_json TEXT NOT NULL,\n\twrite_count INTEGER NOT NULL,\n\tdecided_by_identity_id TEXT NOT NULL,\n\tdecided_by_device_id TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS device_identity_binding_audit (\n\tevent_id TEXT PRIMARY KEY NOT NULL,\n\tcommit_digest TEXT NOT NULL REFERENCES device_identity_binding_commits(commit_digest),\n\tdevice_id TEXT NOT NULL,\n\tprevious_identity_id TEXT,\n\ttarget_identity_id TEXT NOT NULL,\n\taction TEXT NOT NULL,\n\tprevious_assignment_version INTEGER,\n\tresulting_assignment_version INTEGER NOT NULL,\n\tdecided_by_identity_id TEXT NOT NULL,\n\tdecided_by_device_id TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_device_identity_binding_audit_commit_device\n\tON device_identity_binding_audit(commit_digest, device_id);\nCREATE INDEX IF NOT EXISTS idx_device_identity_binding_audit_device_created\n\tON device_identity_binding_audit(device_id, created_at, event_id);\n\nCREATE TABLE IF NOT EXISTS recipient_policy_authority_states (\n\tcanonical_project_identity TEXT PRIMARY KEY NOT NULL,\n\tauthority_state TEXT NOT NULL DEFAULT 'legacy',\n\tgeneration INTEGER NOT NULL DEFAULT 0,\n\tdesired_devices_digest TEXT,\n\tcurrent_devices_digest TEXT,\n\tstable_parity_evidence_digest TEXT,\n\tstable_parity_passed_at TEXT,\n\tfresh_snapshot_fingerprint TEXT,\n\tfresh_snapshot_observed_at TEXT,\n\tsafe_error_code TEXT,\n\tstate_changed_at TEXT NOT NULL,\n\tlast_error_at TEXT,\n\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\tlast_attempt_at TEXT,\n\twake_epoch INTEGER NOT NULL DEFAULT 0,\n\tlast_completed_at TEXT,\n\tlease_owner TEXT,\n\tlease_acquired_at TEXT,\n\tlease_expires_at TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS recipient_policy_reconciliation_steps (\n\tcanonical_project_identity TEXT NOT NULL,\n\tgeneration INTEGER NOT NULL,\n\tstep_key TEXT NOT NULL,\n\teffect_id TEXT NOT NULL,\n\tpayload_digest TEXT NOT NULL,\n\tstatus TEXT NOT NULL DEFAULT 'pending',\n\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\tstarted_at TEXT,\n\tcompleted_at TEXT,\n\tlast_attempt_at TEXT,\n\tsafe_error_code TEXT,\n\terror_at TEXT,\n\tlease_owner TEXT,\n\tlease_acquired_at TEXT,\n\tlease_expires_at TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (canonical_project_identity, generation, step_key)\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_effect\n\tON recipient_policy_reconciliation_steps(effect_id);\nCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_status\n\tON recipient_policy_reconciliation_steps(canonical_project_identity, status);\nCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_pending_refresh\n\tON recipient_policy_reconciliation_steps(canonical_project_identity, generation, step_key)\n\tWHERE status IN ('pending', 'running', 'failed')\n\tAND step_key GLOB 'refresh-after-revocations-v2:*';\nCREATE TABLE IF NOT EXISTS recipient_policy_deny_overlays (\n\tcanonical_project_identity TEXT NOT NULL,\n\tscope_id TEXT NOT NULL,\n\tdevice_id TEXT NOT NULL,\n\tgeneration INTEGER NOT NULL,\n\treason_code TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (canonical_project_identity, scope_id, device_id)\n);\nCREATE INDEX IF NOT EXISTS idx_recipient_policy_deny_overlays_scope_device\n\tON recipient_policy_deny_overlays(scope_id, device_id);\n\nCREATE TABLE IF NOT EXISTS recipient_managed_project_projections (\n\tcanonical_project_identity TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tmanaged_scope_id TEXT NOT NULL,\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\trecipient_identity_id TEXT NOT NULL,\n\taccepting_device_id TEXT NOT NULL,\n\tsource_operation_id TEXT NOT NULL,\n\treviewed_project_set_digest TEXT NOT NULL,\n\tstatus TEXT NOT NULL DEFAULT 'active',\n\taccepted_at TEXT NOT NULL,\n\trevoked_at TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (source_operation_id, canonical_project_identity)\n);\nCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_identity_status\n\tON recipient_managed_project_projections(recipient_identity_id, status);\nCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_scope_authority\n\tON recipient_managed_project_projections(managed_scope_id, coordinator_id, group_id, status);\n\nCREATE TABLE IF NOT EXISTS share_operations (\n\toperation_id TEXT PRIMARY KEY NOT NULL,\n\tstate TEXT NOT NULL,\n\tinviter_actor_id TEXT NOT NULL,\n\tinviter_device_ids_json TEXT NOT NULL,\n\tperson_id TEXT NOT NULL,\n\tperson_kind TEXT NOT NULL,\n\tpending_person_operation_id TEXT,\n\tteammate_name TEXT NOT NULL,\n\thistory_policy TEXT NOT NULL,\n\treviewed_project_set_digest TEXT NOT NULL,\n\tcoordinator_group_id TEXT NOT NULL,\n\tcoordinator_invite_id TEXT,\n\tinvite_token_digest TEXT NOT NULL,\n\tinvite_expires_at TEXT NOT NULL,\n\trecipient_actor_id TEXT,\n\trecipient_display_name TEXT,\n\trecipient_device_id TEXT,\n\trecipient_device_display_name TEXT,\n\trecipient_public_key TEXT,\n\trecipient_fingerprint TEXT,\n\tacceptance_consumed_at TEXT,\n\ttrust_state TEXT,\n\tbootstrap_grant_id TEXT,\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_share_operations_state_updated\n\tON share_operations(state, updated_at);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_invite_digest\n\tON share_operations(invite_token_digest);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_pending_person_operation\n\tON share_operations(pending_person_operation_id)\n\tWHERE pending_person_operation_id IS NOT NULL;\nCREATE TABLE IF NOT EXISTS share_operation_projects (\n\toperation_id TEXT NOT NULL,\n\tcanonical_project_identity TEXT NOT NULL,\n\tdisplay_name TEXT NOT NULL,\n\tidentity_source TEXT NOT NULL,\n\texisting_memory_count INTEGER NOT NULL,\n\tordinal INTEGER NOT NULL,\n\tPRIMARY KEY (operation_id, canonical_project_identity)\n);\nCREATE TABLE IF NOT EXISTS share_operation_steps (\n\toperation_id TEXT NOT NULL,\n\tstep_key TEXT NOT NULL,\n\teffect_id TEXT NOT NULL,\n\tstatus TEXT NOT NULL,\n\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\tstarted_at TEXT,\n\tcompleted_at TEXT,\n\tlast_attempt_at TEXT,\n\tsafe_error_code TEXT,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (operation_id, step_key)\n);\n\nCREATE TABLE IF NOT EXISTS sync_retention_state (\n\tid INTEGER PRIMARY KEY,\n\tlast_run_at TEXT,\n\tlast_duration_ms INTEGER,\n\tlast_deleted_ops INTEGER NOT NULL DEFAULT 0,\n\tlast_estimated_bytes_before INTEGER,\n\tlast_estimated_bytes_after INTEGER,\n\tretained_floor_cursor TEXT,\n\tlast_error TEXT,\n\tlast_error_at TEXT\n);\n\nCREATE TABLE IF NOT EXISTS maintenance_jobs (\n\tkind TEXT PRIMARY KEY,\n\ttitle TEXT NOT NULL,\n\tstatus TEXT NOT NULL,\n\tmessage TEXT,\n\tprogress_current INTEGER NOT NULL DEFAULT 0,\n\tprogress_total INTEGER,\n\tprogress_unit TEXT NOT NULL DEFAULT 'items',\n\tmetadata_json TEXT,\n\tstarted_at TEXT,\n\tupdated_at TEXT NOT NULL,\n\tfinished_at TEXT,\n\terror TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated\n\tON maintenance_jobs(status, updated_at);\n\nCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\tpeer_device_id TEXT,\n\top_id TEXT NOT NULL,\n\tentity_type TEXT NOT NULL,\n\tentity_id TEXT NOT NULL,\n\tscope_id TEXT,\n\treason TEXT NOT NULL,\n\tcreated_at TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n\tON sync_scope_rejections(peer_device_id, created_at);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n\tON sync_scope_rejections(scope_id, created_at);\n\n-- import_key is the primary lookup key from replication_ops.entity_id back to\n-- the source memory. The scope-backfill runner's selectReplicationOpScopeCandidates\n-- query joins on it for every unstamped op; without this index a Pi 4 with\n-- ~17k memories and ~35k ops scans the full memory_items table on every batch\n-- tick. The partial WHERE clause keeps the index small (most rows have\n-- import_key set; the few that don't aren't searchable anyway).\nCREATE INDEX IF NOT EXISTS idx_memory_items_import_key\n\tON memory_items(import_key)\n\tWHERE import_key IS NOT NULL;\n\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n\ttitle, body_text, tags_text,\n\tcontent='memory_items',\n\tcontent_rowid='id'\n);\n\nCREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN\n\tINSERT INTO memory_fts(rowid, title, body_text, tags_text)\n\tVALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_au;\nCREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN\n\tINSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n\tVALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n\tINSERT INTO memory_fts(rowid, title, body_text, tags_text)\n\tVALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_ad;\nCREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN\n\tINSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n\tVALUES('delete', old.id, old.title, old.body_text, old.tags_text);\nEND;\n\nCREATE TABLE IF NOT EXISTS memory_file_refs (\n\tmemory_id INTEGER NOT NULL,\n\tfile_path TEXT NOT NULL,\n\trelation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n\tPRIMARY KEY (memory_id, file_path, relation),\n\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_file_refs_path\n\tON memory_file_refs(file_path);\n\nCREATE TABLE IF NOT EXISTS memory_concept_refs (\n\tmemory_id INTEGER NOT NULL,\n\tconcept TEXT NOT NULL,\n\tPRIMARY KEY (memory_id, concept),\n\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept\n\tON memory_concept_refs(concept);\n\nCREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tprojects_include_json TEXT,\n\tprojects_exclude_json TEXT,\n\tauto_seed_scope INTEGER NOT NULL DEFAULT 1,\n\tdefault_space_scope_id TEXT,\n\tauto_grant_default_space_on_join INTEGER NOT NULL DEFAULT 0,\n\tupdated_at TEXT NOT NULL,\n\tPRIMARY KEY (coordinator_id, group_id)\n);\n\nCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\tcoordinator_id TEXT NOT NULL,\n\tgroup_id TEXT NOT NULL,\n\tlast_refresh_at TEXT NOT NULL,\n\tlast_success_at TEXT,\n\tlast_error TEXT,\n\tupdated_at TEXT NOT NULL,\n\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\tPRIMARY KEY (coordinator_id, group_id)\n);\n`;\n\n/**\n * DDL for the sqlite-vec `memory_vectors` virtual table. Drizzle cannot model\n * virtual tables driven by a loadable extension, so this lives alongside the\n * other aux DDL and is executed through `ensureVectorSchema` (which first\n * makes sure the `vec0` module is actually loaded on the connection).\n *\n * Columns mirror the Python `_ensure_vector_schema` helper in `codemem/db.py`.\n * The embedding width (384) matches the default BAAI/bge-small-en-v1.5 model\n * and the existing vectors tests; changing it requires rebuilding existing\n * vector rows via the migration helper.\n */\nconst MEMORY_VECTORS_DDL = `\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_vectors USING vec0(\n\tembedding float[384],\n\tmemory_id INTEGER,\n\tchunk_index INTEGER,\n\tcontent_hash TEXT,\n\tmodel TEXT\n);\n`;\n\n/**\n * Create the `memory_vectors` sqlite-vec virtual table on `db` if it does not\n * already exist. No-op when embeddings are disabled via\n * `CODEMEM_EMBEDDING_DISABLED`, matching the Python backend's behavior.\n *\n * This function is safe to call from any bootstrap path — it probes for\n * `vec_version()` first and only attempts to load the sqlite-vec extension if\n * it is not already present on the connection. That avoids double-loading when\n * callers (like `MemoryStore`) have already called `loadSqliteVec` directly.\n */\nexport function ensureVectorSchema(db: Database): void {\n\tif (isEmbeddingDisabled()) return;\n\ttry {\n\t\tif (!isSqliteVecLoaded(db)) {\n\t\t\tloadSqliteVec(db);\n\t\t}\n\t\tdb.exec(MEMORY_VECTORS_DDL);\n\t} catch {\n\t\treturn;\n\t}\n}\n\nfunction isSqliteVecLoaded(db: Database): boolean {\n\ttry {\n\t\tconst row = db.prepare(\"SELECT vec_version() AS v\").get() as { v?: string } | undefined;\n\t\treturn typeof row?.v === \"string\" && row.v.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function bootstrapSchema(db: Database): void {\n\tdb.transaction(() => {\n\t\tdb.exec(TEST_SCHEMA_BASE_DDL);\n\t\tdb.exec(SCHEMA_AUX_DDL);\n\t\tensureLegacyTeamSetupDraftSchema(db);\n\t\tensureRawEventCaptureContextSchema(db);\n\t\tensurePolicyTeamDeviceEligibilityColumns(db);\n\t\tensureSyncPeerSignatureStateSchema(db);\n\t\tensureSyncPeerManualAddressesColumn(db);\n\t\tensureSyncPeerLastSuccessAddressColumn(db);\n\t\tensureRetrievalAttemptColumns(db);\n\t\tensureOutcomeEvidenceColumns(db);\n\t\tensureMemoryOwnershipSchemas(db);\n\t\tensureMemoryAggregateIndex(db);\n\t\tensureUsageEventsAggregateIndex(db);\n\t\tensureVectorCorpusEpoch(db);\n\t\tassertBootstrapTablesCreated(db);\n\t\tdb.pragma(`user_version = ${SCHEMA_VERSION}`);\n\t}).immediate();\n\n\t// sqlite-vec support is optional/best-effort. Keep it outside the core\n\t// bootstrap transaction so an unavailable extension cannot produce a\n\t// half-successful core schema, and cannot prevent first-run stats/setup.\n\tensureVectorSchema(db);\n}\n\nfunction ensureSyncPeerManualAddressesColumn(db: Database): void {\n\tif (!columnExists(db, \"sync_peers\", \"manual_addresses_json\")) {\n\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN manual_addresses_json TEXT\");\n\t}\n}\n\nfunction ensureSyncPeerLastSuccessAddressColumn(db: Database): void {\n\tif (!columnExists(db, \"sync_peers\", \"last_success_address\")) {\n\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN last_success_address TEXT\");\n\t}\n}\n\nfunction ensurePolicyTeamDeviceEligibilityColumns(db: Database): void {\n\tif (!columnExists(db, \"policy_teams\", \"device_eligibility_mode\")) {\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE policy_teams ADD COLUMN device_eligibility_mode TEXT NOT NULL DEFAULT 'person_all_devices'\",\n\t\t);\n\t}\n\tif (!columnExists(db, \"identity_devices\", \"assignment_version\")) {\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE identity_devices ADD COLUMN assignment_version INTEGER NOT NULL DEFAULT 0\",\n\t\t);\n\t}\n\tif (!columnExists(db, \"policy_team_device_decisions\", \"assignment_version\")) {\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE policy_team_device_decisions ADD COLUMN assignment_version INTEGER NOT NULL DEFAULT 0\",\n\t\t);\n\t}\n\tensureIdentityDeviceAssignmentVersionTriggers(db);\n}\n\n/** Add sticky direct-peer signature state without requiring a schema-version bump. */\nexport function ensureSyncPeerDirectSignatureVersionColumn(db: Database): void {\n\tif (!tableExists(db, \"sync_peers\")) return;\n\tif (columnExists(db, \"sync_peers\", \"highest_observed_direct_signature_version\")) return;\n\ttry {\n\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN highest_observed_direct_signature_version INTEGER\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\tif (\n\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\tcolumnExists(db, \"sync_peers\", \"highest_observed_direct_signature_version\")\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Keep signature downgrade protection outside deletable peer trust rows.\n *\n * The copy is advancing-only so this repair can run on every open, including\n * databases whose compatibility marker was written before this table existed.\n */\nexport function ensureSyncPeerSignatureStateSchema(db: Database): void {\n\tif (!tableExists(db, \"sync_peers\")) return;\n\tensureSyncPeerDirectSignatureVersionColumn(db);\n\tif (!tableExists(db, \"sync_peer_signature_state\")) {\n\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_peer_signature_state (\n\t\t\t\tpeer_device_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\thighest_observed_direct_signature_version INTEGER NOT NULL\n\t\t\t);\n\t\t`);\n\t}\n\t// Every CLI command opens the store, so only take the write lock when a\n\t// peer's recorded version is actually ahead of the preserved state.\n\tconst pending = db\n\t\t.prepare(\n\t\t\t`SELECT 1 FROM sync_peers AS peer\n\t\t\t LEFT JOIN sync_peer_signature_state AS state USING (peer_device_id)\n\t\t\t WHERE peer.highest_observed_direct_signature_version IS NOT NULL\n\t\t\t AND (state.peer_device_id IS NULL\n\t\t\t OR state.highest_observed_direct_signature_version\n\t\t\t < peer.highest_observed_direct_signature_version)\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get();\n\tif (!pending) return;\n\tdb.exec(`\n\t\tINSERT INTO sync_peer_signature_state(\n\t\t\tpeer_device_id, highest_observed_direct_signature_version\n\t\t)\n\t\tSELECT peer_device_id, highest_observed_direct_signature_version\n\t\tFROM sync_peers\n\t\tWHERE highest_observed_direct_signature_version IS NOT NULL\n\t\tON CONFLICT(peer_device_id) DO UPDATE SET\n\t\t\thighest_observed_direct_signature_version = excluded.highest_observed_direct_signature_version\n\t\tWHERE sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t< excluded.highest_observed_direct_signature_version;\n\t`);\n}\n\nfunction ensureIdentityDeviceAssignmentVersionTriggers(db: Database): void {\n\tdb.exec(IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL);\n}\n\n/** Add the local-only retrieval ledger to an already initialized database. */\nexport function ensureRetrievalLedgerSchema(db: Database): void {\n\tif (!tableExists(db, \"sessions\") || !tableExists(db, \"memory_items\")) return;\n\tensureMemoryItemsDeletedAtColumn(db);\n\t// Contract-v1 cleanup is explicit and bounded by retention/privacy selectors.\n\t// Remove the earlier global orphan trigger even when every table/index already exists.\n\tdb.exec(\"DROP TRIGGER IF EXISTS trg_attribution_evidence_delete_orphan\");\n\tif (\n\t\t!columnExists(db, \"memory_items\", \"import_key\") ||\n\t\t!columnExists(db, \"memory_items\", \"origin_device_id\")\n\t) {\n\t\treturn;\n\t}\n\tconst placeholders = RETRIEVAL_LEDGER_SCHEMA_OBJECTS.map(() => \"?\").join(\", \");\n\tconst row = db\n\t\t.prepare(`SELECT COUNT(*) AS count FROM sqlite_master WHERE name IN (${placeholders})`)\n\t\t.get(...RETRIEVAL_LEDGER_SCHEMA_OBJECTS) as { count?: number } | undefined;\n\tif (row?.count !== RETRIEVAL_LEDGER_SCHEMA_OBJECTS.length) {\n\t\t// Replay the idempotent DDL only after detecting an interrupted migration.\n\t\tdb.exec(RETRIEVAL_LEDGER_DDL);\n\t}\n\tensureRetrievalExposureDetachUnavailableMemoryTrigger(db);\n\tensureRetrievalAttemptColumns(db);\n\tensureOutcomeEvidenceColumns(db);\n}\n\nfunction ensureRetrievalExposureDetachUnavailableMemoryTrigger(db: Database): void {\n\tconst sql = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'trg_retrieval_exposures_detach_unavailable_memory'\",\n\t\t)\n\t\t.pluck()\n\t\t.get() as string | undefined;\n\tif (\n\t\tsql?.includes(\"NEW.memory_import_key IS NOT NULL\") &&\n\t\tsql.includes(\"NEW.memory_import_key = import_key\") &&\n\t\tsql.includes(\"NEW.origin_device_id = origin_device_id\") &&\n\t\tsql.includes(\"NEW.memory_rev = rev\") &&\n\t\tsql.includes(\"julianday(NEW.memory_updated_at) = julianday(updated_at)\")\n\t) {\n\t\treturn;\n\t}\n\tdb.transaction(() => {\n\t\tdb.exec(`\n\t\t\tDROP TRIGGER IF EXISTS trg_retrieval_exposures_detach_unavailable_memory;\n\t\t\t${RETRIEVAL_EXPOSURE_DETACH_UNAVAILABLE_MEMORY_DDL}\n\t\t`);\n\t}).immediate();\n}\n\nfunction ensureMemoryItemsDeletedAtColumn(db: Database): void {\n\tif (columnExists(db, \"memory_items\", \"deleted_at\")) return;\n\ttry {\n\t\t// Existing rows become NULL, preserving active rows while leaving legacy\n\t\t// active=0 rows unavailable without inventing a deletion timestamp.\n\t\tdb.exec(\"ALTER TABLE memory_items ADD COLUMN deleted_at TEXT\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\tif (\n\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\tcolumnExists(db, \"memory_items\", \"deleted_at\")\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction ensureRetrievalAttemptColumns(db: Database): void {\n\tfor (const [name, definition] of [\n\t\t[\"evaluation_checkout_id\", \"TEXT\"],\n\t\t[\"evaluation_fixture_id\", \"TEXT\"],\n\t\t[\"evaluation_seed\", \"INTEGER\"],\n\t\t[\"retention_finalized_at\", \"TEXT\"],\n\t\t[\"automatic_recall_json\", \"TEXT\"],\n\t\t[\"automatic_recall_key\", \"TEXT\"],\n\t] as const) {\n\t\tconst exists = db\n\t\t\t.prepare(\"SELECT 1 FROM pragma_table_info('retrieval_attempts') WHERE name = ? LIMIT 1\")\n\t\t\t.get(name);\n\t\tif (exists === undefined) {\n\t\t\tdb.exec(`ALTER TABLE retrieval_attempts ADD COLUMN ${name} ${definition}`);\n\t\t}\n\t}\n\tdb.exec(\n\t\t\"CREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_attempts_automatic_recall_key ON retrieval_attempts(automatic_recall_key)\",\n\t);\n}\n\nfunction ensureOutcomeEvidenceColumns(db: Database): void {\n\tif (columnExists(db, \"outcome_evidence\", \"retention_finalized_at\")) return;\n\ttry {\n\t\tdb.exec(\"ALTER TABLE outcome_evidence ADD COLUMN retention_finalized_at TEXT\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\tif (\n\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\tcolumnExists(db, \"outcome_evidence\", \"retention_finalized_at\")\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction assertBootstrapTablesCreated(db: Database): void {\n\tconst missing = REQUIRED_BOOTSTRAPPED_TABLES.filter((table) => !tableExists(db, table));\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Schema bootstrap failed; missing required tables: ${missing.join(\", \")}`);\n\t}\n}\n\nfunction isSafeEmptyDatabase(db: Database): boolean {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS count\n\t\t\t FROM sqlite_master\n\t\t\t WHERE name NOT LIKE 'sqlite\\\\_%' ESCAPE '\\\\'`,\n\t\t)\n\t\t.get() as { count?: number } | undefined;\n\treturn (row?.count ?? 0) === 0;\n}\n\nfunction tableExists(db: Database, table: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1\")\n\t\t.get(table);\n\treturn row !== undefined;\n}\n\nfunction columnExists(db: Database, table: string, column: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1\")\n\t\t.get(table, column);\n\treturn row !== undefined;\n}\n\n/** Additive only: old event IDs, payloads and provenance remain untouched. */\nexport function ensureRawEventCaptureContextSchema(db: Database): void {\n\tif (isReadonlyDatabase(db) || !tableExists(db, \"raw_events\")) return;\n\tconst indexExists = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_raw_events_capture_context'\",\n\t\t)\n\t\t.get();\n\tif (columnExists(db, \"raw_events\", \"capture_context_json\") && indexExists) return;\n\tdb.transaction(() => {\n\t\tif (!columnExists(db, \"raw_events\", \"capture_context_json\")) {\n\t\t\tdb.exec(\"ALTER TABLE raw_events ADD COLUMN capture_context_json TEXT\");\n\t\t}\n\t\tif (\n\t\t\t[\"source\", \"stream_id\", \"event_seq\"].every((column) => columnExists(db, \"raw_events\", column))\n\t\t) {\n\t\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_raw_events_capture_context\n\t\t\t\tON raw_events(source, stream_id, event_seq) WHERE capture_context_json IS NOT NULL`);\n\t\t}\n\t}).immediate();\n}\n\n/**\n * Run `bootstrapSchema` on a database only if it's still at the unbootstrapped\n * state (`user_version === 0`). `connect()` now calls this by default for\n * writable handles, but explicit callers may still use it directly. Idempotent:\n * already-initialized databases are left untouched.\n */\nexport function ensureSchemaBootstrapped(db: Database): void {\n\tif (!isReadonlyDatabase(db) && canAutoBootstrapSchema(db)) {\n\t\tbootstrapSchema(db);\n\t}\n}\n\nexport function canAutoBootstrapSchema(db: Database): boolean {\n\treturn getSchemaVersion(db) === 0 && isSafeEmptyDatabase(db);\n}\n\nfunction isReadonlyDatabase(db: Database): boolean {\n\treturn (db as { readonly?: boolean }).readonly === true;\n}\n","/**\n * Database connection and schema primitives for the codemem store.\n *\n * Owns the `connect()` helper (pragmas, WAL mode, sqlite-vec loading, legacy\n * path migration) and the schema-version introspection helpers\n * (`getSchemaVersion`, `assertSchemaReady`, `ensureAdditiveSchemaCompatibility`,\n * `ensurePlannerStats`). Schema bootstrap DDL lives in `schema-bootstrap.ts`;\n * `connect()` now enforces the fresh-database bootstrap invariant.\n */\n\nimport {\n\tcloseSync,\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport type { Database as DatabaseType } from \"better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport {\n\tgetSchemaVersion,\n\tIDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL,\n\tidentityDeviceAssignmentTriggersCurrent,\n\tREQUIRED_BOOTSTRAPPED_TABLES,\n\tREQUIRED_TABLES,\n\tSCHEMA_VERSION,\n} from \"./database-runtime-primitives.js\";\nimport { ensureMemoryOwnershipSchemas } from \"./memory-ownership-recovery-schema.js\";\nimport { expandUserPath } from \"./observer-config.js\";\nimport { ensureRepositoryDiscoveryIndex } from \"./repository-discovery-index.js\";\nimport {\n\tcanAutoBootstrapSchema,\n\tensureLegacyTeamSetupDraftSchema,\n\tensureMemoryAggregateIndex,\n\tensureRawEventCaptureContextSchema,\n\tensureRetrievalLedgerSchema,\n\tensureSchemaBootstrapped,\n\tensureSyncPeerSignatureStateSchema,\n} from \"./schema-bootstrap.js\";\nimport { ensureUsageEventsAggregateIndex } from \"./usage-aggregate-index.js\";\nimport { ensureVectorCorpusEpoch } from \"./vector-corpus-epoch.js\";\n\nexport {\n\tgetSchemaVersion,\n\tIDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL,\n\tisEmbeddingDisabled,\n\tloadSqliteVec,\n\tREQUIRED_BOOTSTRAPPED_TABLES,\n\tSCHEMA_VERSION,\n} from \"./database-runtime-primitives.js\";\n// Re-export the Database type for consumers\nexport type { DatabaseType as Database };\n\n/**\n * Minimum schema version the TS runtime can operate with.\n * Per the coexistence contract (docs/plans/2026-03-15-db-coexistence-contract.md),\n * TS must tolerate additive newer schemas. It only hard-fails if the schema is\n * too old to have the tables/columns it needs.\n */\nexport const MIN_COMPATIBLE_SCHEMA = 6;\n\n/** Marker file written after the first successful TS access to a DB. */\nconst TS_MARKER = \".codemem-ts-accessed\";\n\n/** Lock file to avoid concurrent first-access backups. */\nconst TS_BACKUP_LOCK = \".codemem-ts-backup.lock\";\n\n/** Consider a backup lock stale after 15 minutes. */\nconst TS_BACKUP_LOCK_STALE_MS = 15 * 60 * 1000;\n\ninterface BackupLockAcquireResult {\n\tfd: number | null;\n\tcontention: boolean;\n}\n\nfunction acquireBackupLock(lockPath: string): BackupLockAcquireResult {\n\tmkdirSync(dirname(lockPath), { recursive: true });\n\ttry {\n\t\treturn { fd: openSync(lockPath, \"wx\"), contention: false };\n\t} catch (err) {\n\t\tconst code = err && typeof err === \"object\" ? (err as NodeJS.ErrnoException).code : undefined;\n\t\tif (code === \"EEXIST\") {\n\t\t\tlet stale = false;\n\t\t\ttry {\n\t\t\t\tconst ageMs = Date.now() - statSync(lockPath).mtimeMs;\n\t\t\t\tstale = Number.isFinite(ageMs) && ageMs > TS_BACKUP_LOCK_STALE_MS;\n\t\t\t} catch {\n\t\t\t\t// If we can't read lock metadata, treat as live contention.\n\t\t\t}\n\n\t\t\tif (!stale) {\n\t\t\t\treturn { fd: null, contention: true };\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tunlinkSync(lockPath);\n\t\t\t} catch (unlinkErr) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[codemem] Warning: failed to clear stale backup lock at ${lockPath}:`,\n\t\t\t\t\tunlinkErr,\n\t\t\t\t);\n\t\t\t\treturn { fd: null, contention: false };\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn { fd: openSync(lockPath, \"wx\"), contention: false };\n\t\t\t} catch (retryErr) {\n\t\t\t\tconst retryCode =\n\t\t\t\t\tretryErr && typeof retryErr === \"object\"\n\t\t\t\t\t\t? (retryErr as NodeJS.ErrnoException).code\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (retryCode === \"EEXIST\") {\n\t\t\t\t\treturn { fd: null, contention: true };\n\t\t\t\t}\n\t\t\t\tconsole.error(`[codemem] Warning: failed to acquire backup lock at ${lockPath}:`, retryErr);\n\t\t\t\treturn { fd: null, contention: false };\n\t\t\t}\n\t\t}\n\n\t\tconsole.error(`[codemem] Warning: failed to acquire backup lock at ${lockPath}:`, err);\n\t\treturn { fd: null, contention: false };\n\t}\n}\n\n/** Default database path — matches Python's DEFAULT_DB_PATH. */\nexport const DEFAULT_DB_PATH = join(homedir(), \".codemem\", \"mem.sqlite\");\n\n/**\n * Resolve the database path from explicit arg → CODEMEM_DB env → default.\n * All TS entry points should use this instead of hardcoding fallback logic.\n */\nexport function resolveDbPath(explicit?: string): string {\n\tif (explicit) return expandUserPath(explicit);\n\tconst envPath = process.env.CODEMEM_DB;\n\tif (envPath) return expandUserPath(envPath);\n\treturn DEFAULT_DB_PATH;\n}\n\n/** Legacy database paths that may exist from older installs. */\nconst LEGACY_DB_PATHS = [\n\tjoin(homedir(), \".codemem.sqlite\"),\n\tjoin(homedir(), \".opencode-mem.sqlite\"),\n];\n\n/** WAL sidecar extensions for a SQLite database file. */\nconst SIDECAR_EXTENSIONS = [\"-wal\", \"-shm\"];\n\n/**\n * Move a file and its WAL sidecars to a new location.\n * Falls back to copy+delete if rename fails (cross-device).\n */\nfunction moveWithSidecars(src: string, dst: string): void {\n\tmkdirSync(dirname(dst), { recursive: true });\n\tconst pairs: [string, string][] = [\n\t\t[src, dst],\n\t\t...SIDECAR_EXTENSIONS.map((ext): [string, string] => [src + ext, dst + ext]),\n\t];\n\tfor (const [srcPath, dstPath] of pairs) {\n\t\tif (!existsSync(srcPath)) continue;\n\t\ttry {\n\t\t\trenameSync(srcPath, dstPath);\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tcopyFileSync(srcPath, dstPath);\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(srcPath);\n\t\t\t\t} catch {\n\t\t\t\t\t// Best effort — original left in place\n\t\t\t\t}\n\t\t\t} catch (copyErr) {\n\t\t\t\t// TOCTOU: source vanished between existsSync and copy (concurrent migration).\n\t\t\t\t// If target now exists, another process already migrated — that's fine.\n\t\t\t\tif (existsSync(dstPath)) continue;\n\t\t\t\tthrow copyErr;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Migrate legacy database paths to the current default location.\n *\n * Only runs when dbPath is the DEFAULT_DB_PATH and doesn't already exist.\n * Matches Python's migrate_legacy_default_db in db.py.\n */\nexport function migrateLegacyDbPath(dbPath: string): void {\n\tif (dbPath !== DEFAULT_DB_PATH) return;\n\tif (existsSync(dbPath)) return;\n\n\tfor (const legacyPath of LEGACY_DB_PATHS) {\n\t\tif (!existsSync(legacyPath)) continue;\n\t\tmoveWithSidecars(legacyPath, dbPath);\n\t\treturn;\n\t}\n}\n\n/**\n * Open a better-sqlite3 connection with the standard codemem pragmas.\n *\n * Migrates legacy DB paths if needed, creates parent directories,\n * sets WAL mode, busy timeout, foreign keys, and bootstraps the schema when\n * opening a brand-new or otherwise uninitialized writable database.\n */\nexport function connect(dbPath: string = DEFAULT_DB_PATH): DatabaseType {\n\tmigrateLegacyDbPath(dbPath);\n\tmkdirSync(dirname(dbPath), { recursive: true });\n\tconst db = new Database(dbPath);\n\ttry {\n\t\t// Match Python's connect() pragmas exactly\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\tconst configureWal = canAutoBootstrapSchema(db) || hasBootstrappedCodememSchema(db);\n\n\t\tensureSchemaBootstrapped(db);\n\t\tif (!configureWal) return db;\n\n\t\t// In-memory databases cannot use WAL (SQLite reports \"memory\") and have\n\t\t// no cross-process readers, so skip the pragma and its warning.\n\t\tif (!db.memory) {\n\t\t\tconst journalMode = db.pragma(\"journal_mode = WAL\", { simple: true }) as string;\n\t\t\tif (journalMode.toLowerCase() !== \"wal\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`Failed to enable WAL mode (got ${journalMode}). Concurrent access may not work correctly.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tdb.pragma(\"synchronous = NORMAL\");\n\n\t\t// Read tuning for large (multi-GB) databases. The SQLite defaults — a\n\t\t// ~2 MiB page cache and no mmap — force repeated disk/page-cache reads of\n\t\t// B-tree interior pages on every non-trivial query. A 64 MiB cache, 1 GiB\n\t\t// memory-mapped I/O, and in-memory temp B-trees cut that cost. These are\n\t\t// per-connection and must be set here (they do not persist in the file).\n\t\tdb.pragma(\"cache_size = -65536\");\n\t\tdb.pragma(\"mmap_size = 1073741824\");\n\t\tdb.pragma(\"temp_store = MEMORY\");\n\n\t\treturn db;\n\t} catch (error) {\n\t\tdb.close();\n\t\tthrow error;\n\t}\n}\n\n/**\n * Open an EXISTING database read-only.\n *\n * Unlike {@link connect}, this never creates the parent directory, never opens\n * for writing, and never enables WAL or runs schema bootstrap — so it works on\n * read-only snapshots and read-only directories (e.g. a copied audit snapshot).\n * Read-tuning pragmas are still applied because they are per-connection and do\n * not write to the file. Schema readiness is validated read-only.\n */\nexport interface ReadOnlyConnectionOptions {\n\twarn?: (message: string) => void;\n}\n\nexport function connectReadOnly(\n\tdbPath: string = DEFAULT_DB_PATH,\n\toptions: ReadOnlyConnectionOptions = {},\n): DatabaseType {\n\tconst db = new Database(dbPath, { readonly: true, fileMustExist: true });\n\ttry {\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\t// Read tuning only — safe on a read-only connection (per-connection state).\n\t\tdb.pragma(\"cache_size = -65536\");\n\t\tdb.pragma(\"mmap_size = 1073741824\");\n\t\tdb.pragma(\"temp_store = MEMORY\");\n\t\tassertSchemaReadyReadOnly(db, options.warn);\n\t\treturn db;\n\t} catch (error) {\n\t\tdb.close();\n\t\tthrow error;\n\t}\n}\n\n/**\n * Validate schema readiness without any writes (no bootstrap, no migration).\n * Mirrors {@link assertSchemaReady} but is safe on read-only connections.\n */\nexport function assertSchemaReadyReadOnly(\n\tdb: DatabaseType,\n\twarn: (message: string) => void = console.warn,\n): void {\n\tconst version = getSchemaVersion(db);\n\tif (version === 0) {\n\t\tthrow new Error(\n\t\t\t\"Database schema is not initialized (read-only open). \" +\n\t\t\t\t\"Point at an initialized codemem database.\",\n\t\t);\n\t}\n\tif (version < MIN_COMPATIBLE_SCHEMA) {\n\t\tthrow new Error(\n\t\t\t`Database schema version ${version} is older than minimum compatible (${MIN_COMPATIBLE_SCHEMA}).`,\n\t\t);\n\t}\n\tif (version > SCHEMA_VERSION) {\n\t\twarn(\n\t\t\t`Database schema version ${version} is newer than this TS runtime (${SCHEMA_VERSION}). ` +\n\t\t\t\t\"Running in read-only compatibility mode.\",\n\t\t);\n\t}\n\tconst missing = REQUIRED_TABLES.filter((t) => !tableExists(db, t));\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Required tables missing: ${missing.join(\", \")}. ` +\n\t\t\t\t\"The database may be corrupt or from an incompatible version.\",\n\t\t);\n\t}\n}\n\nfunction hasBootstrappedCodememSchema(db: DatabaseType): boolean {\n\treturn REQUIRED_BOOTSTRAPPED_TABLES.every((table) => tableExists(db, table));\n}\n\nfunction hasPlannerStats(db: DatabaseType): boolean {\n\ttry {\n\t\treturn !!db.prepare(\"SELECT 1 FROM sqlite_stat1 LIMIT 1\").pluck().get();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Keep SQLite planner statistics healthy for FTS-heavy queries.\n *\n * We always run PRAGMA optimize as a cheap maintenance hint. If planner\n * statistics have never been collected and the core search tables exist,\n * bootstrap them with ANALYZE so Node SQLite picks stable FTS query plans.\n */\nexport function ensurePlannerStats(db: DatabaseType): void {\n\t// Statistics are only a planner hint. Never wait on another writer for\n\t// them: skip this open and let a later open refresh them.\n\twithoutBusyWait(db, () => {\n\t\tdb.pragma(\"optimize\");\n\n\t\tif (hasPlannerStats(db)) return;\n\t\tif (!tableExists(db, \"memory_items\") || !tableExists(db, \"memory_fts\")) return;\n\n\t\tdb.exec(\"ANALYZE\");\n\t\tdb.pragma(\"optimize\");\n\t});\n}\n\nfunction isSqliteBusy(error: unknown): boolean {\n\tconst code = (error as { code?: unknown } | null)?.code;\n\treturn code === \"SQLITE_BUSY\" || code === \"SQLITE_LOCKED\";\n}\n\n/** Refresh planner hints if the database is free; never waits on another writer. */\nexport function optimizeWithoutWaiting(db: DatabaseType): void {\n\twithoutBusyWait(db, () => db.pragma(\"optimize\"));\n}\n\n/** Run optional write work without waiting on locks; skip it if the database is busy. */\nfunction withoutBusyWait(db: DatabaseType, work: () => void): void {\n\tconst previous = db.pragma(\"busy_timeout\", { simple: true }) as number;\n\tdb.pragma(\"busy_timeout = 0\");\n\ttry {\n\t\twork();\n\t} catch (error) {\n\t\tif (!isSqliteBusy(error)) throw error;\n\t} finally {\n\t\tdb.pragma(`busy_timeout = ${Number(previous) || 0}`);\n\t}\n}\n\n/**\n * Create a timestamped backup of the database on first TS access.\n *\n * The backup file is named `mem.sqlite.pre-ts-YYYYMMDDTHHMMSS.bak` and placed\n * next to the original. A marker file prevents repeated backups. This ensures\n * users can recover if the TS runtime introduces bugs that corrupt the DB\n * during the migration period.\n */\nexport function backupOnFirstAccess(dbPath: string): void {\n\tconst markerPath = join(dirname(dbPath), TS_MARKER);\n\tif (existsSync(markerPath)) return;\n\n\t// Find the actual DB file to back up. It may be at the target path already,\n\t// or at a legacy location that migrateLegacyDbPath() will move later.\n\t// Back up whichever exists BEFORE migration runs.\n\tlet sourceDbPath = dbPath;\n\tif (!existsSync(dbPath)) {\n\t\t// Check legacy locations — same order as migrateLegacyDbPath()\n\t\tconst legacyPaths = [\n\t\t\tjoin(dirname(dbPath), \"..\", \".codemem.sqlite\"),\n\t\t\tjoin(dirname(dbPath), \"..\", \".opencode-mem.sqlite\"),\n\t\t];\n\t\tconst legacyPath = legacyPaths.find((p) => existsSync(p));\n\t\tif (legacyPath) {\n\t\t\tsourceDbPath = legacyPath;\n\t\t} else {\n\t\t\treturn; // Fresh DB, nothing to back up\n\t\t}\n\t}\n\n\tconst lockPath = join(dirname(dbPath), TS_BACKUP_LOCK);\n\tconst { fd: lockFd, contention } = acquireBackupLock(lockPath);\n\tif (contention) {\n\t\t// Another process is handling first-access backup.\n\t\treturn;\n\t}\n\n\tconst writeMarker = (): void => {\n\t\ttry {\n\t\t\tmkdirSync(dirname(markerPath), { recursive: true });\n\t\t\twriteFileSync(markerPath, new Date().toISOString(), \"utf-8\");\n\t\t} catch {\n\t\t\t// Non-fatal — worst case we attempt backup again later.\n\t\t}\n\t};\n\n\tconst hasViableExistingBackup = (): boolean => {\n\t\tlet sourceSize = 0;\n\t\ttry {\n\t\t\tsourceSize = statSync(sourceDbPath).size;\n\t\t} catch {\n\t\t\tsourceSize = 0;\n\t\t}\n\t\tconst minViableSize = sourceSize > 0 ? Math.floor(sourceSize * 0.9) : 1;\n\t\tconst prefix = `${basename(sourceDbPath)}.pre-ts-`;\n\t\ttry {\n\t\t\tconst entries = readdirSync(dirname(sourceDbPath));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (!entry.startsWith(prefix) || !entry.endsWith(\".bak\")) continue;\n\t\t\t\tconst fullPath = join(dirname(sourceDbPath), entry);\n\t\t\t\ttry {\n\t\t\t\t\tif (statSync(fullPath).size >= minViableSize) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore races while inspecting backup candidates.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore directory read errors — proceed with normal backup path.\n\t\t}\n\t\treturn false;\n\t};\n\n\tconst ts = new Date().toISOString().replace(/[:.]/g, \"\").slice(0, 15);\n\tconst backupPath = `${sourceDbPath}.pre-ts-${ts}.bak`;\n\tlet backupSucceeded = false;\n\ttry {\n\t\tif (existsSync(markerPath)) return;\n\t\tif (hasViableExistingBackup()) {\n\t\t\twriteMarker();\n\t\t\treturn;\n\t\t}\n\n\t\tcopyFileSync(sourceDbPath, backupPath);\n\t\t// Also back up WAL/SHM if present (they contain uncommitted data)\n\t\tconst walPath = `${sourceDbPath}-wal`;\n\t\tconst shmPath = `${sourceDbPath}-shm`;\n\t\tif (existsSync(walPath)) copyFileSync(walPath, `${backupPath}-wal`);\n\t\tif (existsSync(shmPath)) copyFileSync(shmPath, `${backupPath}-shm`);\n\t\tconsole.error(`[codemem] First TS access — backed up database to ${backupPath}`);\n\t\tbackupSucceeded = true;\n\t} catch (err) {\n\t\tconsole.error(`[codemem] Warning: failed to create backup at ${backupPath}:`, err);\n\t\t// Continue — backup failure shouldn't prevent operation, but don't write marker\n\t} finally {\n\t\tif (lockFd != null) {\n\t\t\ttry {\n\t\t\t\tcloseSync(lockFd);\n\t\t\t} catch {\n\t\t\t\t// Ignore close errors.\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tunlinkSync(lockPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore lock cleanup errors.\n\t\t\t}\n\t\t}\n\t}\n\n\t// Only write marker after backup succeeds — a transient failure should\n\t// retry on next access, not permanently suppress the safety net.\n\tif (backupSucceeded) {\n\t\twriteMarker();\n\t}\n}\n\n/**\n * Verify the database schema is initialized and compatible.\n *\n * Empty writable first-run handles are bootstrapped here as a final safety net,\n * even though `connect()` already does the same. A few lower-level maintenance\n * and integration paths call this assertion after receiving an existing database\n * handle, so keeping the bootstrap invariant here prevents one entry point from\n * requiring a manual `codemem db init` while another works automatically.\n *\n * Per the coexistence contract: TS tolerates additive newer schemas (Python may\n * have run migrations that add tables/columns the TS runtime doesn't know about).\n * TS only hard-fails if:\n * - Schema is still uninitialized after a bootstrap attempt (version 0)\n * - Schema is too old (below MIN_COMPATIBLE_SCHEMA)\n * - Required tables are missing\n * - FTS5 index is missing (needed for search)\n *\n * Warns (but continues) if schema is newer than SCHEMA_VERSION — the additive\n * changes are assumed safe per the coexistence contract.\n */\nexport function assertSchemaReady(db: DatabaseType): void {\n\tensureSchemaBootstrapped(db);\n\tconst version = getSchemaVersion(db);\n\tif (version === 0) {\n\t\tthrow new Error(\n\t\t\t\"Database schema is not initialized. \" +\n\t\t\t\t\"Initialize the SQLite database with the current TypeScript runtime before retrying.\",\n\t\t);\n\t}\n\tif (version < MIN_COMPATIBLE_SCHEMA) {\n\t\tthrow new Error(\n\t\t\t`Database schema version ${version} is older than minimum compatible (${MIN_COMPATIBLE_SCHEMA}). ` +\n\t\t\t\t\"Upgrade the database schema with the current TypeScript runtime before retrying.\",\n\t\t);\n\t}\n\tif (version > SCHEMA_VERSION) {\n\t\tconsole.warn(\n\t\t\t`Database schema version ${version} is newer than this TS runtime (${SCHEMA_VERSION}). ` +\n\t\t\t\t\"Running in compatibility mode — additive schema changes are tolerated.\",\n\t\t);\n\t}\n\n\t// Validate required tables exist (catches corrupt or partially migrated DBs)\n\tconst missing = REQUIRED_TABLES.filter((t) => !tableExists(db, t));\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Required tables missing: ${missing.join(\", \")}. ` +\n\t\t\t\t\"The database may be corrupt or from an incompatible version.\",\n\t\t);\n\t}\n\n\t// FTS5 index is required for search\n\tif (!tableExists(db, \"memory_fts\")) {\n\t\tthrow new Error(\n\t\t\t\"FTS5 index (memory_fts) is missing. \" +\n\t\t\t\t\"Rebuild the database schema with the current TypeScript runtime before retrying.\",\n\t\t);\n\t}\n}\n\n/** Check if a table exists in the database. */\nexport function tableExists(db: DatabaseType, table: string): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(table);\n\treturn row !== undefined;\n}\n\n/** Check if a column exists in a table. */\nexport function columnExists(db: DatabaseType, table: string, column: string): boolean {\n\tif (!tableExists(db, table)) return false;\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1\")\n\t\t.get(table, column);\n\treturn row !== undefined;\n}\n\nfunction addColumnIfMissing(\n\tdb: DatabaseType,\n\ttable: string,\n\tname: string,\n\tdefinition: string,\n): void {\n\tif (columnExists(db, table, name)) return;\n\ttry {\n\t\tdb.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${definition}`);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\tif (message.includes(\"duplicate column name\") && columnExists(db, table, name)) {\n\t\t\treturn;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nconst RECIPIENT_POLICY_DEVICE_ELIGIBILITY_COMPATIBILITY_ERROR =\n\t\"recipient_policy_device_eligibility_schema_incompatible\";\n\nfunction ensureIdentityDeviceAssignmentVersionTriggers(db: DatabaseType): void {\n\tif (\n\t\t!tableExists(db, \"identity_devices\") ||\n\t\t!columnExists(db, \"identity_devices\", \"identity_id\") ||\n\t\t!columnExists(db, \"identity_devices\", \"assignment_version\") ||\n\t\t!tableExists(db, \"policy_team_device_decisions\") ||\n\t\t!columnExists(db, \"policy_team_device_decisions\", \"device_id\")\n\t) {\n\t\treturn;\n\t}\n\t// Rewriting needs the write lock; skip it when both triggers are already\n\t// current so read-only opens do not block behind long write transactions.\n\tif (identityDeviceAssignmentTriggersCurrent(db)) return;\n\tdb.transaction(() => db.exec(IDENTITY_DEVICE_ASSIGNMENT_TRIGGERS_DDL)).immediate();\n}\n\nfunction ensureDeviceIdentityBindingAuditSchema(db: DatabaseType): void {\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS device_identity_binding_commits (\n\t\t\tcommit_digest TEXT PRIMARY KEY NOT NULL,\n\t\t\treviewed_inventory_digest TEXT NOT NULL,\n\t\t\trequest_json TEXT NOT NULL,\n\t\t\toutcomes_json TEXT NOT NULL,\n\t\t\twrite_count INTEGER NOT NULL,\n\t\t\tdecided_by_identity_id TEXT NOT NULL,\n\t\t\tdecided_by_device_id TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS device_identity_binding_audit (\n\t\t\tevent_id TEXT PRIMARY KEY NOT NULL,\n\t\t\tcommit_digest TEXT NOT NULL REFERENCES device_identity_binding_commits(commit_digest),\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tprevious_identity_id TEXT,\n\t\t\ttarget_identity_id TEXT NOT NULL,\n\t\t\taction TEXT NOT NULL,\n\t\t\tprevious_assignment_version INTEGER,\n\t\t\tresulting_assignment_version INTEGER NOT NULL,\n\t\t\tdecided_by_identity_id TEXT NOT NULL,\n\t\t\tdecided_by_device_id TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_device_identity_binding_audit_commit_device\n\t\t\tON device_identity_binding_audit(commit_digest, device_id);\n\t\tCREATE INDEX IF NOT EXISTS idx_device_identity_binding_audit_device_created\n\t\t\tON device_identity_binding_audit(device_id, created_at, event_id);\n\t`);\n}\n\n/**\n * Create the (created_at, id) keyset index that vector backfill paging relies on.\n * Runs unconditionally rather than inside the SCHEMA_VERSION-gated compat block:\n * databases already marked at the current SCHEMA_VERSION would otherwise skip it\n * forever and keep paying the temporary-sort cost during inactive backfills.\n */\nfunction ensureMemoryItemsPagingIndex(db: DatabaseType): void {\n\tif (!tableExists(db, \"memory_items\")) return;\n\ttry {\n\t\tdb.exec(\n\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_created_id ON memory_items(created_at, id)\",\n\t\t);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\n/**\n * Create the (started_at, id) keyset index that newest-first candidate scans\n * rely on (listProjectScopeCandidates). Same rationale as the memory_items\n * paging index: run unconditionally so databases already at the current\n * SCHEMA_VERSION pick it up instead of re-sorting sessions on every page.\n */\nfunction ensureSessionsPagingIndex(db: DatabaseType): void {\n\tif (!tableExists(db, \"sessions\")) return;\n\ttry {\n\t\tdb.exec(\"CREATE INDEX IF NOT EXISTS idx_sessions_started_id ON sessions(started_at, id)\");\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction ensureSyncAttemptsDiagnosticIndexes(db: DatabaseType): void {\n\tif (!tableExists(db, \"sync_attempts\")) return;\n\ttry {\n\t\tdb.exec(`\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_attempts_occurred\n\t\t\t\tON sync_attempts(\n\t\t\t\t\tCASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n\t\t\t\t\tid\n\t\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_attempts_error_occurred\n\t\t\t\tON sync_attempts(\n\t\t\t\t\tCASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n\t\t\t\t\tid\n\t\t\t\t)\n\t\t\t\tWHERE ok = 0;\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_attempts_success_occurred\n\t\t\t\tON sync_attempts(\n\t\t\t\t\tCASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n\t\t\t\t\tid\n\t\t\t\t)\n\t\t\t\tWHERE ok <> 0;\n\t\t`);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction ensureRawEventSessionsPendingIndex(db: DatabaseType): void {\n\tif (!tableExists(db, \"raw_event_sessions\")) return;\n\ttry {\n\t\tdb.exec(`CREATE INDEX IF NOT EXISTS idx_raw_event_sessions_pending_updated\n\t\t\tON raw_event_sessions(updated_at)\n\t\t\tWHERE last_received_event_seq > last_flushed_event_seq`);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction ensureFlushBatchDiagnosticIndexes(db: DatabaseType): void {\n\tif (!tableExists(db, \"raw_event_flush_batches\")) return;\n\ttry {\n\t\tdb.exec(`\n\t\t\tCREATE INDEX IF NOT EXISTS idx_flush_batches_observer_status_updated\n\t\t\t\tON raw_event_flush_batches(status, updated_at)\n\t\t\t\tWHERE observer_provider IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS idx_flush_batches_capture_status_updated\n\t\t\t\tON raw_event_flush_batches(status, updated_at)\n\t\t\t\tWHERE observer_provider IS NULL;\n\t\t`);\n\t} catch {\n\t\t// Keep additive compatibility best-effort for index creation.\n\t}\n}\n\nfunction assertRecipientPolicyDeviceEligibilityCompatibility(db: DatabaseType): void {\n\tconst recipientPolicySchemaPresent = [\n\t\t\"policy_teams\",\n\t\t\"policy_team_memberships\",\n\t\t\"identity_devices\",\n\t\t\"project_recipients\",\n\t\t\"policy_team_device_decisions\",\n\t].some((table) => tableExists(db, table));\n\tif (!recipientPolicySchemaPresent) return;\n\n\tconst missing: string[] = [];\n\tfor (const [table, column] of [\n\t\t[\"policy_teams\", \"device_eligibility_mode\"],\n\t\t[\"identity_devices\", \"assignment_version\"],\n\t] as const) {\n\t\ttry {\n\t\t\tif (!columnExists(db, table, column)) missing.push(`${table}.${column}`);\n\t\t} catch {\n\t\t\tmissing.push(`${table}.${column}`);\n\t\t}\n\t}\n\tfor (const column of [\"team_id\", \"device_id\", \"decision\", \"assignment_version\"]) {\n\t\ttry {\n\t\t\tif (!columnExists(db, \"policy_team_device_decisions\", column)) {\n\t\t\t\tmissing.push(`policy_team_device_decisions.${column}`);\n\t\t\t}\n\t\t} catch {\n\t\t\tmissing.push(`policy_team_device_decisions.${column}`);\n\t\t}\n\t}\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`${RECIPIENT_POLICY_DEVICE_ELIGIBILITY_COMPATIBILITY_ERROR}:${missing.join(\",\")}`,\n\t\t);\n\t}\n}\n\n/**\n * Repair display-only peer version metadata independently of the compatibility\n * marker because these additive columns intentionally do not bump the schema.\n */\nfunction ensureSyncPeerRuntimeVersionColumns(db: DatabaseType): void {\n\tif (!tableExists(db, \"sync_peers\")) return;\n\taddColumnIfMissing(db, \"sync_peers\", \"runtime_version\", \"TEXT\");\n\taddColumnIfMissing(db, \"sync_peers\", \"runtime_version_observed_at\", \"TEXT\");\n}\n\n/** Add the structured sync-attempt failure category without a schema-version bump. */\nexport function ensureSyncAttemptFailureCategoryColumn(db: DatabaseType): void {\n\tif (!tableExists(db, \"sync_attempts\")) return;\n\taddColumnIfMissing(db, \"sync_attempts\", \"failure_category\", \"TEXT\");\n}\n\n/** Persist a direct-peer signature version only when it advances the peer's observed maximum. */\nexport function recordHighestObservedDirectSignatureVersion(\n\tdb: DatabaseType,\n\tpeerDeviceId: string,\n\tversion: number,\n): boolean {\n\tif (!Number.isSafeInteger(version) || version < 1) {\n\t\tthrow new RangeError(\"Direct signature version must be a positive safe integer\");\n\t}\n\treturn db.transaction(() => {\n\t\tconst result = db\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO sync_peer_signature_state(\n\t\t\t\t\tpeer_device_id, highest_observed_direct_signature_version\n\t\t\t\t )\n\t\t\t\t SELECT ?, ?\n\t\t\t\t WHERE EXISTS (\n\t\t\t\t\tSELECT 1 FROM sync_peers WHERE peer_device_id = ?\n\t\t\t\t )\n\t\t\t\t ON CONFLICT(peer_device_id) DO UPDATE SET\n\t\t\t\t\thighest_observed_direct_signature_version = excluded.highest_observed_direct_signature_version\n\t\t\t\t WHERE sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t\t\t< excluded.highest_observed_direct_signature_version`,\n\t\t\t)\n\t\t\t.run(peerDeviceId, version, peerDeviceId);\n\t\t// Retain the additive column as a compatibility mirror for older runtimes.\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers\n\t\t\t SET highest_observed_direct_signature_version = ?\n\t\t\t WHERE peer_device_id = ?\n\t\t\t AND (\n\t\t\t\t highest_observed_direct_signature_version IS NULL\n\t\t\t\t OR highest_observed_direct_signature_version < ?\n\t\t\t )`,\n\t\t).run(version, peerDeviceId, version);\n\t\treturn result.changes > 0;\n\t})();\n}\n\n/**\n * Has the additive compatibility shim already run for the current SCHEMA_VERSION?\n *\n * Fail-safe: returns false on any error (including a missing\n * `schema_compat_state` table) so the shim re-runs rather than skipping needed\n * additive DDL on uncertainty. Keyed on SCHEMA_VERSION so a future runtime with\n * a higher SCHEMA_VERSION (and new additive DDL) sees the older marker and\n * re-applies.\n */\nfunction schemaCompatAlreadyApplied(db: DatabaseType): boolean {\n\ttry {\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT applied_schema_version AS v FROM schema_compat_state WHERE id = 1 LIMIT 1\")\n\t\t\t.get() as { v: number } | undefined;\n\t\treturn typeof row?.v === \"number\" && row.v >= SCHEMA_VERSION;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Record that the additive compatibility shim has been applied for the current\n * SCHEMA_VERSION. Fail-open: a failed mark just means the shim re-runs on the\n * next open, which is harmless because the DDL is idempotent.\n */\nfunction markSchemaCompatApplied(db: DatabaseType): void {\n\ttry {\n\t\tdb.prepare(\n\t\t\t`INSERT INTO schema_compat_state(id, applied_schema_version, applied_at)\n\t\t\t VALUES (1, ?, ?)\n\t\t\t ON CONFLICT(id) DO UPDATE SET\n\t\t\t\t applied_schema_version = excluded.applied_schema_version,\n\t\t\t\t applied_at = excluded.applied_at`,\n\t\t).run(SCHEMA_VERSION, new Date().toISOString());\n\t} catch {\n\t\t// Fail-open: a missed mark only costs one extra idempotent re-run.\n\t}\n}\n\n/**\n * Backfill the denormalized memory_items.project column from sessions.project.\n *\n * Runs on EVERY store open (not gated behind the schema-compat marker) because\n * moveMemoryProject edits sessions.project and relies on this backfill plus a\n * reader-fallback to propagate the new project to legacy rows whose project is\n * still NULL. Idempotent — only touches rows where project IS NULL.\n */\nfunction backfillMemoryItemProject(db: DatabaseType): void {\n\ttry {\n\t\t// Only take the write lock when some row can actually gain a project.\n\t\tconst pending = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT 1 FROM memory_items AS m\n\t\t\t\t JOIN sessions AS s ON s.id = m.session_id\n\t\t\t\t WHERE m.project IS NULL AND s.project IS NOT NULL\n\t\t\t\t LIMIT 1`,\n\t\t\t)\n\t\t\t.get();\n\t\tif (!pending) return;\n\t\tdb.exec(`UPDATE memory_items\n\t\t\t SET project = (\n\t\t\t\t SELECT s.project FROM sessions s\n\t\t\t\t WHERE s.id = memory_items.session_id\n\t\t\t )\n\t\t\t WHERE project IS NULL`);\n\t} catch {\n\t\t// Best-effort backfill — readers fall back to sessions.project\n\t\t// when memory_items.project is null.\n\t}\n}\n\n/**\n * Apply additive compatibility fixes for legacy TS-era schemas.\n *\n * These are safe, one-way `ALTER TABLE ... ADD COLUMN` updates used to\n * prevent runtime failures when older local databases are missing columns\n * introduced in later releases.\n *\n * The ~39 idempotent DDL statements are gated behind a `schema_compat_state`\n * marker so steady-state opens skip them: each database runs the shim once\n * (idempotent — a fresh DB's statements are all no-ops), records the marker,\n * and skips thereafter. We deliberately do NOT short-circuit on\n * `user_version >= SCHEMA_VERSION`: additive columns (e.g. memory_items.project)\n * have been added over time WITHOUT bumping SCHEMA_VERSION, so a database can\n * report user_version=SCHEMA_VERSION yet still lack a column the shim adds —\n * the version is not proof the shim ran. Only the marker is. The project\n * backfill still runs on every open regardless of the gate.\n */\nfunction indexColumns(db: DatabaseType, indexName: string): string[] {\n\tconst quoted = indexName.replaceAll('\"', '\"\"');\n\treturn (db.prepare(`PRAGMA index_info(\"${quoted}\")`).all() as Array<{ name?: string }>)\n\t\t.map((row) => String(row.name ?? \"\"))\n\t\t.filter(Boolean);\n}\n\nconst SHARE_OPERATION_EFFECT_ID_INDEX_SQL =\n\t\"CREATE INDEX idx_share_operation_steps_effect_id_nonempty ON share_operation_steps(effect_id) WHERE effect_id <> ''\";\n\nfunction normalizedIndexSql(sql: string): string {\n\treturn sql\n\t\t.replace(/\\s+/g, \" \")\n\t\t.replace(/\\s*\\(\\s*/g, \"(\")\n\t\t.replace(/\\s*\\)\\s*/g, \") \")\n\t\t.trim();\n}\n\n/** True when the partial index exists with exactly the expected definition. */\nfunction shareOperationEffectIdIndexCurrent(db: DatabaseType): boolean {\n\tconst row = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type = 'index' AND name = 'idx_share_operation_steps_effect_id_nonempty'\",\n\t\t)\n\t\t.get() as { sql?: string | null } | undefined;\n\treturn (\n\t\ttypeof row?.sql === \"string\" &&\n\t\tnormalizedIndexSql(row.sql) === normalizedIndexSql(SHARE_OPERATION_EFFECT_ID_INDEX_SQL)\n\t);\n}\n\nfunction repairShareOperationEffectIdIndex(db: DatabaseType): void {\n\tif (\n\t\t!tableExists(db, \"share_operation_steps\") ||\n\t\t!columnExists(db, \"share_operation_steps\", \"effect_id\")\n\t) {\n\t\treturn;\n\t}\n\tconst indexes = db.prepare(\"PRAGMA index_list('share_operation_steps')\").all() as Array<{\n\t\tname: string;\n\t\tunique: number;\n\t}>;\n\tconst hasInlineUniqueEffectId = indexes.some(\n\t\t(index) =>\n\t\t\tindex.unique === 1 &&\n\t\t\tindex.name !== \"idx_share_operation_steps_effect_id_nonempty\" &&\n\t\t\tindexColumns(db, index.name).join(\",\") === \"effect_id\",\n\t);\n\tif (hasInlineUniqueEffectId) {\n\t\tdb.transaction(() => {\n\t\t\tdb.exec(`\n\t\t\t\tDROP INDEX IF EXISTS idx_share_operation_steps_effect_id_nonempty;\n\t\t\t\tALTER TABLE share_operation_steps RENAME TO share_operation_steps_unique_legacy;\n\t\t\t\tCREATE TABLE share_operation_steps (\n\t\t\t\t\toperation_id TEXT NOT NULL,\n\t\t\t\t\tstep_key TEXT NOT NULL,\n\t\t\t\t\teffect_id TEXT NOT NULL,\n\t\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\t\tstarted_at TEXT,\n\t\t\t\t\tcompleted_at TEXT,\n\t\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\t\tsafe_error_code TEXT,\n\t\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (operation_id, step_key)\n\t\t\t\t);\n\t\t\t\tINSERT INTO share_operation_steps(\n\t\t\t\t\toperation_id, step_key, effect_id, status, attempt_count, started_at,\n\t\t\t\t\tcompleted_at, last_attempt_at, safe_error_code, updated_at\n\t\t\t\t) SELECT operation_id, step_key, effect_id, status, attempt_count, started_at,\n\t\t\t\t\tcompleted_at, last_attempt_at, safe_error_code, updated_at\n\t\t\t\tFROM share_operation_steps_unique_legacy;\n\t\t\t\tDROP TABLE share_operation_steps_unique_legacy;\n\t\t\t`);\n\t\t})();\n\t}\n\t// Rebuilding the index takes the write lock; skip it only when the stored\n\t// definition, including its WHERE clause, matches exactly.\n\tif (!hasInlineUniqueEffectId && shareOperationEffectIdIndexCurrent(db)) return;\n\tdb.exec(`\n\t\tDROP INDEX IF EXISTS idx_share_operation_steps_effect_id_nonempty;\n\t\tCREATE INDEX IF NOT EXISTS idx_share_operation_steps_effect_id_nonempty\n\t\t\tON share_operation_steps(effect_id)\n\t\t\tWHERE effect_id <> '';\n\t`);\n}\n\nlet retrievalLedgerSchemaWarningEmitted = false;\n\nfunction ensureOptionalRetrievalLedgerSchema(db: DatabaseType): void {\n\t// This remains outside the compatibility marker gate so a partial legacy\n\t// database can gain its base tables before a later open creates the ledger.\n\ttry {\n\t\tensureRetrievalLedgerSchema(db);\n\t} catch {\n\t\t// The ledger is optional local derived state. A malformed/locked optional\n\t\t// ledger must not prevent the existing store from opening.\n\t\tif (!retrievalLedgerSchemaWarningEmitted) {\n\t\t\tretrievalLedgerSchemaWarningEmitted = true;\n\t\t\tconsole.warn(\n\t\t\t\t\"[codemem] Retrieval evidence storage is unavailable; continuing without attribution data.\",\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction ensureRecipientPolicyAdditiveColumns(db: DatabaseType): void {\n\tfor (const [table, name, definition] of [\n\t\t[\"policy_teams\", \"device_eligibility_mode\", \"TEXT NOT NULL DEFAULT 'person_all_devices'\"],\n\t\t[\"identity_devices\", \"assignment_version\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t[\"policy_team_device_decisions\", \"assignment_version\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t] as const) {\n\t\ttry {\n\t\t\taddColumnIfMissing(db, table, name, definition);\n\t\t} catch {\n\t\t\t// Continue repairing independent recipient-policy columns.\n\t\t}\n\t}\n}\n\nfunction ensureRecipientPolicyWakeColumn(db: DatabaseType): void {\n\t// Earlier compatibility markers could be written after this column failed to\n\t// upgrade. Repair on every open and fail before advancing schema markers.\n\tif (!tableExists(db, \"recipient_policy_authority_states\")) return;\n\taddColumnIfMissing(\n\t\tdb,\n\t\t\"recipient_policy_authority_states\",\n\t\t\"wake_epoch\",\n\t\t\"INTEGER NOT NULL DEFAULT 0\",\n\t);\n}\n\nfunction ensureAlwaysOnSchemaCompatibility(db: DatabaseType): void {\n\tensureVectorCorpusEpoch(db);\n\tif (tableExists(db, \"sync_peers\") && !columnExists(db, \"sync_peers\", \"manual_addresses_json\")) {\n\t\ttry {\n\t\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN manual_addresses_json TEXT\");\n\t\t} catch (error) {\n\t\t\tif (!columnExists(db, \"sync_peers\", \"manual_addresses_json\")) throw error;\n\t\t}\n\t}\n\tif (tableExists(db, \"sync_peers\") && !columnExists(db, \"sync_peers\", \"last_success_address\")) {\n\t\ttry {\n\t\t\tdb.exec(\"ALTER TABLE sync_peers ADD COLUMN last_success_address TEXT\");\n\t\t} catch (error) {\n\t\t\tif (!columnExists(db, \"sync_peers\", \"last_success_address\")) throw error;\n\t\t}\n\t}\n\tensureMemoryOwnershipSchemas(db);\n\tensureOptionalRetrievalLedgerSchema(db);\n\ttry {\n\t\tensureRepositoryDiscoveryIndex(db);\n\t} catch {\n\t\t// Derived discovery evidence is optional; stamping retains its full-scan path.\n\t}\n\tensureRecipientPolicyWakeColumn(db);\n\t// Always run: current-marker databases may predate these no-version-bump\n\t// columns, so the schema_compat_state gate cannot prove they exist.\n\tensureSyncPeerRuntimeVersionColumns(db);\n\tensureSyncAttemptFailureCategoryColumn(db);\n\tensureRawEventCaptureContextSchema(db);\n\tensureSyncPeerSignatureStateSchema(db);\n\tensureDeviceIdentityBindingAuditSchema(db);\n\tensureLegacyTeamSetupDraftSchema(db);\n\tensureMemoryItemsPagingIndex(db);\n\tensureSessionsPagingIndex(db);\n\tensureSyncAttemptsDiagnosticIndexes(db);\n\tensureRawEventSessionsPendingIndex(db);\n}\n\nexport function ensureAdditiveSchemaCompatibility(db: DatabaseType): void {\n\tensureAlwaysOnSchemaCompatibility(db);\n\tapplyAdditiveSchemaCompatibility(db);\n\t// Current-marker databases also need this index, but legacy columns must\n\t// exist before its first creation. Later opens only check sqlite_master.\n\tensureMemoryAggregateIndex(db);\n\tensureUsageEventsAggregateIndex(db);\n}\n\nfunction applyAdditiveSchemaCompatibility(db: DatabaseType): void {\n\tconst compatAlreadyApplied = schemaCompatAlreadyApplied(db);\n\tif (!compatAlreadyApplied) {\n\t\t// IMPORTANT: any NEW DDL added to this gated block REQUIRES bumping\n\t\t// SCHEMA_VERSION. The \"already applied\" marker keys on SCHEMA_VERSION, so\n\t\t// without a bump, legacy DBs already marked at the current version would\n\t\t// skip the new DDL forever.\n\t\t// Marker table must exist before we can mark; create it first.\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\t\tCREATE TABLE IF NOT EXISTS schema_compat_state (\n\t\t\t\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\t\t\t\tapplied_schema_version INTEGER NOT NULL,\n\t\t\t\t\tapplied_at TEXT NOT NULL\n\t\t\t\t)\n\t\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for the marker table.\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS coordinator_enrollment_reconciliation_issues (\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\treference_id TEXT NOT NULL,\n\t\t\t\tcode TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'open',\n\t\t\t\tfirst_seen_at TEXT NOT NULL,\n\t\t\t\tlast_seen_at TEXT NOT NULL,\n\t\t\t\tresolved_at TEXT,\n\t\t\t\toccurrence_count INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (coordinator_id, group_id, kind, reference_id, code)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_boundary_status\n\t\t\t\tON coordinator_enrollment_reconciliation_issues(coordinator_id, group_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_status_recent\n\t\t\t\tON coordinator_enrollment_reconciliation_issues(status, last_seen_at, resolved_at);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_review_resolutions (\n\t\t\t\treview_item_id TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT NOT NULL,\n\t\t\t\tdecision TEXT NOT NULL,\n\t\t\t\tdecision_input_json TEXT NOT NULL,\n\t\t\t\tpreview_json TEXT NOT NULL,\n\t\t\t\tdecided_by_identity_id TEXT NOT NULL,\n\t\t\t\tdecided_by_device_id TEXT NOT NULL,\n\t\t\t\tresolved_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (review_item_id, source_fingerprint)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS policy_teams (\n\t\t\t\tteam_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tdevice_eligibility_mode TEXT NOT NULL DEFAULT 'person_all_devices',\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS policy_team_memberships (\n\t\t\t\tteam_id TEXT NOT NULL,\n\t\t\t\tidentity_id TEXT NOT NULL,\n\t\t\t\trole TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (team_id, identity_id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS identity_devices (\n\t\t\t\tdevice_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tidentity_id TEXT NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tassignment_version INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS policy_team_device_decisions (\n\t\t\t\tteam_id TEXT NOT NULL REFERENCES policy_teams(team_id) ON DELETE CASCADE,\n\t\t\t\tdevice_id TEXT NOT NULL,\n\t\t\t\tdecision TEXT NOT NULL,\n\t\t\t\tassignment_version INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\trevision TEXT NOT NULL,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (team_id, device_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_policy_team_device_decisions_device\n\t\t\t\tON policy_team_device_decisions(device_id);\n\t\t\tCREATE TABLE IF NOT EXISTS project_recipients (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\trecipient_kind TEXT NOT NULL,\n\t\t\t\trecipient_id TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovenance TEXT NOT NULL,\n\t\t\t\tpolicy_revision TEXT NOT NULL,\n\t\t\t\tmigration_state TEXT NOT NULL,\n\t\t\t\tsource_fingerprint TEXT,\n\t\t\t\tidempotency_key TEXT NOT NULL UNIQUE,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (canonical_project_identity, recipient_kind, recipient_id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_authority_states (\n\t\t\t\tcanonical_project_identity TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tauthority_state TEXT NOT NULL DEFAULT 'legacy',\n\t\t\t\tgeneration INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tdesired_devices_digest TEXT,\n\t\t\t\tcurrent_devices_digest TEXT,\n\t\t\t\tstable_parity_evidence_digest TEXT,\n\t\t\t\tstable_parity_passed_at TEXT,\n\t\t\t\tfresh_snapshot_fingerprint TEXT,\n\t\t\t\tfresh_snapshot_observed_at TEXT,\n\t\t\t\tsafe_error_code TEXT,\n\t\t\t\tstate_changed_at TEXT NOT NULL,\n\t\t\t\tlast_error_at TEXT,\n\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\twake_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_completed_at TEXT,\n\t\t\t\tlease_owner TEXT,\n\t\t\t\tlease_acquired_at TEXT,\n\t\t\t\tlease_expires_at TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_reconciliation_steps (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\tstep_key TEXT NOT NULL,\n\t\t\t\teffect_id TEXT NOT NULL,\n\t\t\t\tpayload_digest TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'pending',\n\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tstarted_at TEXT,\n\t\t\t\tcompleted_at TEXT,\n\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\tsafe_error_code TEXT,\n\t\t\t\terror_at TEXT,\n\t\t\t\tlease_owner TEXT,\n\t\t\t\tlease_acquired_at TEXT,\n\t\t\t\tlease_expires_at TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (canonical_project_identity, generation, step_key)\n\t\t\t);\n\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_effect\n\t\t\t\tON recipient_policy_reconciliation_steps(effect_id);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_status\n\t\t\t\tON recipient_policy_reconciliation_steps(canonical_project_identity, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_pending_refresh\n\t\t\t\tON recipient_policy_reconciliation_steps(canonical_project_identity, generation, step_key)\n\t\t\t\tWHERE status IN ('pending', 'running', 'failed')\n\t\t\t\tAND step_key GLOB 'refresh-after-revocations-v2:*';\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_policy_deny_overlays (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tdevice_id TEXT NOT NULL,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\treason_code TEXT NOT NULL,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (canonical_project_identity, scope_id, device_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_policy_deny_overlays_scope_device\n\t\t\t\tON recipient_policy_deny_overlays(scope_id, device_id);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_policy_team_memberships_identity_status\n\t\t\t\tON policy_team_memberships(identity_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_identity_devices_identity_status\n\t\t\t\tON identity_devices(identity_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_recipients_project_status\n\t\t\t\tON project_recipients(canonical_project_identity, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_recipients_recipient_status\n\t\t\t\tON project_recipients(recipient_kind, recipient_id, status);\n\t\t\tCREATE TABLE IF NOT EXISTS recipient_managed_project_projections (\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tmanaged_scope_id TEXT NOT NULL,\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\trecipient_identity_id TEXT NOT NULL,\n\t\t\t\taccepting_device_id TEXT NOT NULL,\n\t\t\t\tsource_operation_id TEXT NOT NULL,\n\t\t\t\treviewed_project_set_digest TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\t\taccepted_at TEXT NOT NULL,\n\t\t\t\trevoked_at TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (source_operation_id, canonical_project_identity)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_identity_status\n\t\t\t\tON recipient_managed_project_projections(recipient_identity_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_scope_authority\n\t\t\t\tON recipient_managed_project_projections(\n\t\t\t\t\tmanaged_scope_id, coordinator_id, group_id, status\n\t\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS share_operations (\n\t\t\t\toperation_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tstate TEXT NOT NULL,\n\t\t\t\tinviter_actor_id TEXT NOT NULL,\n\t\t\t\tinviter_device_ids_json TEXT NOT NULL,\n\t\t\t\tperson_id TEXT NOT NULL,\n\t\t\t\tperson_kind TEXT NOT NULL,\n\t\t\t\tpending_person_operation_id TEXT,\n\t\t\t\tteammate_name TEXT NOT NULL,\n\t\t\t\thistory_policy TEXT NOT NULL,\n\t\t\t\treviewed_project_set_digest TEXT NOT NULL,\n\t\t\t\tcoordinator_group_id TEXT NOT NULL,\n\t\t\t\tcoordinator_invite_id TEXT,\n\t\t\t\tinvite_token_digest TEXT NOT NULL,\n\t\t\t\tinvite_expires_at TEXT NOT NULL,\n\t\t\t\trecipient_actor_id TEXT,\n\t\t\t\trecipient_display_name TEXT,\n\t\t\t\trecipient_device_id TEXT,\n\t\t\t\trecipient_device_display_name TEXT,\n\t\t\t\trecipient_public_key TEXT,\n\t\t\t\trecipient_fingerprint TEXT,\n\t\t\t\tacceptance_consumed_at TEXT,\n\t\t\t\ttrust_state TEXT,\n\t\t\t\tbootstrap_grant_id TEXT,\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS share_operation_projects (\n\t\t\t\toperation_id TEXT NOT NULL,\n\t\t\t\tcanonical_project_identity TEXT NOT NULL,\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\tidentity_source TEXT NOT NULL,\n\t\t\t\texisting_memory_count INTEGER NOT NULL,\n\t\t\t\tordinal INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (operation_id, canonical_project_identity)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS share_operation_steps (\n\t\t\t\toperation_id TEXT NOT NULL,\n\t\t\t\tstep_key TEXT NOT NULL,\n\t\t\t\teffect_id TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tattempt_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tstarted_at TEXT,\n\t\t\t\tcompleted_at TEXT,\n\t\t\t\tlast_attempt_at TEXT,\n\t\t\t\tsafe_error_code TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (operation_id, step_key)\n\t\t\t);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for additive share-operation state.\n\t\t}\n\t\tensureRecipientPolicyAdditiveColumns(db);\n\t\tconst shareOperationColumns = [\n\t\t\t[\"state\", \"TEXT NOT NULL DEFAULT 'waiting_for_acceptance'\"],\n\t\t\t[\"inviter_actor_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"inviter_device_ids_json\", \"TEXT NOT NULL DEFAULT '[]'\"],\n\t\t\t[\"person_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"person_kind\", \"TEXT NOT NULL DEFAULT 'pending'\"],\n\t\t\t[\"pending_person_operation_id\", \"TEXT\"],\n\t\t\t[\"teammate_name\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"history_policy\", \"TEXT NOT NULL DEFAULT 'existing_and_future'\"],\n\t\t\t[\"reviewed_project_set_digest\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"coordinator_group_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"coordinator_invite_id\", \"TEXT\"],\n\t\t\t[\"invite_token_digest\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"invite_expires_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"recipient_actor_id\", \"TEXT\"],\n\t\t\t[\"recipient_display_name\", \"TEXT\"],\n\t\t\t[\"recipient_device_id\", \"TEXT\"],\n\t\t\t[\"recipient_device_display_name\", \"TEXT\"],\n\t\t\t[\"recipient_public_key\", \"TEXT\"],\n\t\t\t[\"recipient_fingerprint\", \"TEXT\"],\n\t\t\t[\"acceptance_consumed_at\", \"TEXT\"],\n\t\t\t[\"trust_state\", \"TEXT\"],\n\t\t\t[\"bootstrap_grant_id\", \"TEXT\"],\n\t\t\t[\"created_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t[\"updated_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t] as const;\n\t\tfor (const [name, definition] of shareOperationColumns) {\n\t\t\ttry {\n\t\t\t\taddColumnIfMissing(db, \"share_operations\", name, definition);\n\t\t\t} catch {\n\t\t\t\t// Continue repairing independent additive columns.\n\t\t\t}\n\t\t}\n\t\tfor (const [table, columns] of [\n\t\t\t[\n\t\t\t\t\"share_operation_projects\",\n\t\t\t\t[\n\t\t\t\t\t[\"display_name\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t\t[\"identity_source\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t\t[\"existing_memory_count\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t\t\t\t[\"ordinal\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t\t\t],\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"share_operation_steps\",\n\t\t\t\t[\n\t\t\t\t\t[\"effect_id\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t\t[\"status\", \"TEXT NOT NULL DEFAULT 'pending'\"],\n\t\t\t\t\t[\"attempt_count\", \"INTEGER NOT NULL DEFAULT 0\"],\n\t\t\t\t\t[\"started_at\", \"TEXT\"],\n\t\t\t\t\t[\"completed_at\", \"TEXT\"],\n\t\t\t\t\t[\"last_attempt_at\", \"TEXT\"],\n\t\t\t\t\t[\"safe_error_code\", \"TEXT\"],\n\t\t\t\t\t[\"updated_at\", \"TEXT NOT NULL DEFAULT ''\"],\n\t\t\t\t],\n\t\t\t],\n\t\t] as const) {\n\t\t\tfor (const [name, definition] of columns) {\n\t\t\t\ttry {\n\t\t\t\t\taddColumnIfMissing(db, table, name, definition);\n\t\t\t\t} catch {\n\t\t\t\t\t// Continue repairing independent additive columns.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\t\tCREATE INDEX IF NOT EXISTS idx_share_operations_state_updated\n\t\t\t\t\tON share_operations(state, updated_at);\n\t\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_invite_digest\n\t\t\t\t\tON share_operations(invite_token_digest);\n\t\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_pending_person_operation\n\t\t\t\t\tON share_operations(pending_person_operation_id)\n\t\t\t\t\tWHERE pending_person_operation_id IS NOT NULL;\n\t\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for additive share-operation indexes.\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_reset_state (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\t\tbaseline_cursor TEXT,\n\t\t\t\tretained_floor_cursor TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t)\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tpeer_device_id TEXT,\n\t\t\t\top_id TEXT NOT NULL,\n\t\t\t\tentity_type TEXT NOT NULL,\n\t\t\t\tentity_id TEXT NOT NULL,\n\t\t\t\tscope_id TEXT,\n\t\t\t\treason TEXT NOT NULL,\n\t\t\t\tcreated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n\t\t\t\tON sync_scope_rejections(peer_device_id, created_at);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n\t\t\t\tON sync_scope_rejections(scope_id, created_at);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive diagnostics.\n\t\t}\n\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS sync_reset_state_v2 (\n\t\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tgeneration INTEGER NOT NULL,\n\t\t\t\tsnapshot_id TEXT NOT NULL,\n\t\t\t\tbaseline_cursor TEXT,\n\t\t\t\tretained_floor_cursor TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\n\t\t\tCREATE TABLE IF NOT EXISTS sync_retention_state_v2 (\n\t\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tlast_run_at TEXT,\n\t\t\t\tlast_duration_ms INTEGER,\n\t\t\t\tlast_deleted_ops INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_estimated_bytes_before INTEGER,\n\t\t\t\tlast_estimated_bytes_after INTEGER,\n\t\t\t\tretained_floor_cursor TEXT,\n\t\t\t\tlast_error TEXT,\n\t\t\t\tlast_error_at TEXT\n\t\t\t);\n\n\t\t\tCREATE TABLE IF NOT EXISTS replication_cursors_v2 (\n\t\t\t\tpeer_device_id TEXT NOT NULL,\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tlast_applied_cursor TEXT,\n\t\t\t\tlast_acked_cursor TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (peer_device_id, scope_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_replication_cursors_v2_scope\n\t\t\t\tON replication_cursors_v2(scope_id);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\n\t\tif (tableExists(db, \"sync_reset_state\") && tableExists(db, \"sync_reset_state_v2\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(`\n\t\t\t\tINSERT OR IGNORE INTO sync_reset_state_v2\n\t\t\t\t\t(scope_id, generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at)\n\t\t\t\tSELECT 'local-default', generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at\n\t\t\t\tFROM sync_reset_state\n\t\t\t\tWHERE id = 1\n\t\t\t`);\n\t\t\t} catch {\n\t\t\t\t// Best-effort bridge from legacy singleton state.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"sync_retention_state\") && tableExists(db, \"sync_retention_state_v2\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(`\n\t\t\t\tINSERT OR IGNORE INTO sync_retention_state_v2\n\t\t\t\t\t(\n\t\t\t\t\t\tscope_id,\n\t\t\t\t\t\tlast_run_at,\n\t\t\t\t\t\tlast_duration_ms,\n\t\t\t\t\t\tlast_deleted_ops,\n\t\t\t\t\t\tlast_estimated_bytes_before,\n\t\t\t\t\t\tlast_estimated_bytes_after,\n\t\t\t\t\t\tretained_floor_cursor,\n\t\t\t\t\t\tlast_error,\n\t\t\t\t\t\tlast_error_at\n\t\t\t\t\t)\n\t\t\t\tSELECT\n\t\t\t\t\t'local-default',\n\t\t\t\t\tlast_run_at,\n\t\t\t\t\tlast_duration_ms,\n\t\t\t\t\tlast_deleted_ops,\n\t\t\t\t\tlast_estimated_bytes_before,\n\t\t\t\t\tlast_estimated_bytes_after,\n\t\t\t\t\tretained_floor_cursor,\n\t\t\t\t\tlast_error,\n\t\t\t\t\tlast_error_at\n\t\t\t\tFROM sync_retention_state\n\t\t\t\tWHERE id = 1\n\t\t\t`);\n\t\t\t} catch {\n\t\t\t\t// Best-effort bridge from legacy singleton state.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"replication_cursors\") && tableExists(db, \"replication_cursors_v2\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(`\n\t\t\t\tINSERT OR IGNORE INTO replication_cursors_v2\n\t\t\t\t\t(peer_device_id, scope_id, last_applied_cursor, last_acked_cursor, updated_at)\n\t\t\t\tSELECT peer_device_id, 'local-default', last_applied_cursor, last_acked_cursor, updated_at\n\t\t\t\tFROM replication_cursors\n\t\t\t`);\n\t\t\t} catch {\n\t\t\t\t// Best-effort bridge from legacy peer-level cursors.\n\t\t\t}\n\t\t}\n\n\t\t// Add phase column to sync_daemon_state for rebootstrap safety gate.\n\t\tif (tableExists(db, \"sync_daemon_state\") && !columnExists(db, \"sync_daemon_state\", \"phase\")) {\n\t\t\ttry {\n\t\t\t\tdb.exec(\"ALTER TABLE sync_daemon_state ADD COLUMN phase TEXT\");\n\t\t\t} catch {\n\t\t\t\t// Race-safe: another process may have added it first.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"memory_items\")) {\n\t\t\t// idx_memory_items_created_id is created unconditionally by\n\t\t\t// ensureMemoryItemsPagingIndex so already-current databases also get it.\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_origin_device_active ON memory_items(origin_device_id, active)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\tif (!columnExists(db, \"memory_items\", \"dedup_key\")) {\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(\"ALTER TABLE memory_items ADD COLUMN dedup_key TEXT\");\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tconst duplicateColumn = message.includes(\"duplicate column name\");\n\t\t\t\t\tif (!(duplicateColumn && columnExists(db, \"memory_items\", \"dedup_key\"))) {\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_dedup_key_active_created ON memory_items(dedup_key, active, created_at)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_items_same_session_dedup_unique ON memory_items(session_id, kind, visibility, workspace_id, dedup_key) WHERE active = 1 AND dedup_key IS NOT NULL\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\taddColumnIfMissing(db, \"memory_items\", \"scope_id\", \"TEXT\");\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_scope_visibility_created ON memory_items(scope_id, visibility, created_at)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_memory_items_scope_backfill_pending ON memory_items(id) WHERE scope_id IS NULL OR scope_id = ''\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\t// Denormalized project column: created here so the Projects read model can\n\t\t\t// read directly from memory_items without joining through sessions (which\n\t\t\t// carry device-local cwd and don't replicate). The actual NULL backfill\n\t\t\t// runs unconditionally via backfillMemoryItemProject() on every open below.\n\t\t\taddColumnIfMissing(db, \"memory_items\", \"project\", \"TEXT\");\n\t\t\ttry {\n\t\t\t\tdb.exec(\"CREATE INDEX IF NOT EXISTS idx_memory_items_project ON memory_items(project)\");\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\n\t\t\t// Drop legacy memory_items indexes that no longer back any query, only\n\t\t\t// adding write amplification on databases created by older schemas. The\n\t\t\t// current schema never creates these. `visibility`/`workspace_kind` are\n\t\t\t// low-cardinality and only ever appear as secondary predicates already\n\t\t\t// covered by composite indexes (e.g. idx_memory_items_scope_visibility_created,\n\t\t\t// idx_memory_items_same_session_dedup_unique); `user_prompt_id` is unused\n\t\t\t// as a filter (and is all-NULL in practice).\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t`DROP INDEX IF EXISTS idx_memory_items_visibility;\n\t\t\t\t DROP INDEX IF EXISTS idx_memory_items_workspace_kind;\n\t\t\t\t DROP INDEX IF EXISTS idx_memory_items_user_prompt_id;`,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Best-effort cleanup of legacy indexes.\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"replication_ops\")) {\n\t\t\taddColumnIfMissing(db, \"replication_ops\", \"scope_id\", \"TEXT\");\n\t\t\ttry {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_replication_ops_scope_created ON replication_ops(scope_id, created_at, op_id)\",\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Keep additive compatibility best-effort for index creation.\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS replication_scopes (\n\t\t\t\tscope_id TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tlabel TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL DEFAULT 'user',\n\t\t\t\tauthority_type TEXT NOT NULL DEFAULT 'local',\n\t\t\t\tcoordinator_id TEXT,\n\t\t\t\tgroup_id TEXT,\n\t\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tmanifest_hash TEXT,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_replication_scopes_status\n\t\t\t\tON replication_scopes(status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_replication_scopes_authority_group\n\t\t\t\tON replication_scopes(coordinator_id, group_id);\n\n\t\t\tCREATE TABLE IF NOT EXISTS project_scope_mappings (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tworkspace_identity TEXT,\n\t\t\t\tproject_pattern TEXT NOT NULL,\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tpriority INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tsource TEXT NOT NULL DEFAULT 'user',\n\t\t\t\tcreated_at TEXT NOT NULL,\n\t\t\t\tupdated_at TEXT NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_scope_mappings_workspace_priority\n\t\t\t\tON project_scope_mappings(workspace_identity, priority);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_scope_mappings_pattern_priority\n\t\t\t\tON project_scope_mappings(project_pattern, priority);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_project_scope_mappings_scope\n\t\t\t\tON project_scope_mappings(scope_id);\n\n\t\t\tCREATE TABLE IF NOT EXISTS scope_memberships (\n\t\t\t\tscope_id TEXT NOT NULL,\n\t\t\t\tdevice_id TEXT NOT NULL,\n\t\t\t\trole TEXT NOT NULL DEFAULT 'member',\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tcoordinator_id TEXT,\n\t\t\t\tgroup_id TEXT,\n\t\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\t\tmanifest_hash TEXT,\n\t\t\t\tsigned_manifest_json TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (scope_id, device_id)\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_scope_memberships_device_status\n\t\t\t\tON scope_memberships(device_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_scope_memberships_scope_status\n\t\t\t\tON scope_memberships(scope_id, status);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_scope_memberships_authority_group\n\t\t\t\tON scope_memberships(coordinator_id, group_id);\n\n\t\t\tCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\tlast_refresh_at TEXT NOT NULL,\n\t\t\t\tlast_success_at TEXT,\n\t\t\t\tlast_error TEXT,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t\t);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive scope metadata.\n\t\t}\n\n\t\t// Junction tables for structured file/concept references on memories.\n\t\t// Added in schema v7; existing v6 databases need these created additively.\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS memory_file_refs (\n\t\t\t\tmemory_id INTEGER NOT NULL,\n\t\t\t\tfile_path TEXT NOT NULL,\n\t\t\t\trelation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n\t\t\t\tPRIMARY KEY (memory_id, file_path, relation),\n\t\t\t\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_memory_file_refs_path ON memory_file_refs(file_path);\n\n\t\t\tCREATE TABLE IF NOT EXISTS memory_concept_refs (\n\t\t\t\tmemory_id INTEGER NOT NULL,\n\t\t\t\tconcept TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (memory_id, concept),\n\t\t\t\tFOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept ON memory_concept_refs(concept);\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\n\t\t// Multi-team coordinator groups (v1) — additive columns + preferences table.\n\t\t// Existing databases acquire these so peer enrollment can record the group\n\t\t// it came from, and so per-group scope templates can be stored locally.\n\t\tif (tableExists(db, \"sync_peers\")) {\n\t\t\tfor (const name of [\n\t\t\t\t\"discovered_via_coordinator_id\",\n\t\t\t\t\"discovered_via_group_id\",\n\t\t\t\t\"trust_provenance\",\n\t\t\t\t\"pending_bootstrap_grant_id\",\n\t\t\t]) {\n\t\t\t\tif (columnExists(db, \"sync_peers\", name)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(`ALTER TABLE sync_peers ADD COLUMN ${name} TEXT`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tif (message.includes(\"duplicate column name\") && columnExists(db, \"sync_peers\", name)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (tableExists(db, \"sync_attempts\")) {\n\t\t\tfor (const name of [\n\t\t\t\t\"local_sync_capability\",\n\t\t\t\t\"peer_sync_capability\",\n\t\t\t\t\"negotiated_sync_capability\",\n\t\t\t]) {\n\t\t\t\tif (columnExists(db, \"sync_attempts\", name)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(`ALTER TABLE sync_attempts ADD COLUMN ${name} TEXT`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tif (\n\t\t\t\t\t\tmessage.includes(\"duplicate column name\") &&\n\t\t\t\t\t\tcolumnExists(db, \"sync_attempts\", name)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n\t\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\t\tgroup_id TEXT NOT NULL,\n\t\t\t\tprojects_include_json TEXT,\n\t\t\t\tprojects_exclude_json TEXT,\n\t\t\t\tauto_seed_scope INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tdefault_space_scope_id TEXT,\n\t\t\t\tauto_grant_default_space_on_join INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t\t)\n\t\t`);\n\t\t} catch {\n\t\t\t// Keep compatibility shim fail-open for optional additive tables.\n\t\t}\n\t\tfor (const { name, ddl } of [\n\t\t\t{ name: \"default_space_scope_id\", ddl: \"TEXT\" },\n\t\t\t{ name: \"auto_grant_default_space_on_join\", ddl: \"INTEGER NOT NULL DEFAULT 0\" },\n\t\t]) {\n\t\t\tif (columnExists(db, \"coordinator_group_preferences\", name)) continue;\n\t\t\ttry {\n\t\t\t\tdb.exec(`ALTER TABLE coordinator_group_preferences ADD COLUMN ${name} ${ddl}`);\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\tif (message.includes(\"duplicate column name\")) continue;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\tif (tableExists(db, \"raw_event_flush_batches\")) {\n\t\t\tconst additiveColumns: Array<{ name: string; ddl: string }> = [\n\t\t\t\t{ name: \"error_message\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"error_type\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_provider\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_model\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_runtime\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_auth_source\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_auth_type\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_error_code\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"observer_error_message\", ddl: \"TEXT\" },\n\t\t\t\t{ name: \"attempt_count\", ddl: \"INTEGER NOT NULL DEFAULT 0\" },\n\t\t\t];\n\n\t\t\tfor (const { name, ddl } of additiveColumns) {\n\t\t\t\tif (columnExists(db, \"raw_event_flush_batches\", name)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tdb.exec(`ALTER TABLE raw_event_flush_batches ADD COLUMN ${name} ${ddl}`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message.toLowerCase() : \"\";\n\t\t\t\t\tconst duplicateColumn = message.includes(\"duplicate column name\");\n\t\t\t\t\tif (duplicateColumn && columnExists(db, \"raw_event_flush_batches\", name)) {\n\t\t\t\t\t\t// Another process may have raced and added the column first.\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst recipientPolicyTablesReady = [\n\t\t\t\"coordinator_enrollment_reconciliation_issues\",\n\t\t\t\"policy_teams\",\n\t\t\t\"policy_team_memberships\",\n\t\t\t\"policy_team_device_decisions\",\n\t\t\t\"identity_devices\",\n\t\t\t\"project_recipients\",\n\t\t\t\"recipient_managed_project_projections\",\n\t\t\t\"recipient_policy_authority_states\",\n\t\t\t\"recipient_policy_reconciliation_steps\",\n\t\t\t\"recipient_policy_deny_overlays\",\n\t\t].every((table) => tableExists(db, table));\n\t\tconst currentVersion = getSchemaVersion(db);\n\t\tif (recipientPolicyTablesReady && currentVersion > 0 && currentVersion < SCHEMA_VERSION) {\n\t\t\tdb.pragma(`user_version = ${SCHEMA_VERSION}`);\n\t\t}\n\t}\n\t// Run after the gated legacy-column repair so one open can both add\n\t// observer_provider and install its partial diagnostic indexes. This remains\n\t// outside the marker gate for current-marker databases missing only indexes.\n\tensureFlushBatchDiagnosticIndexes(db);\n\t// Intentionally fail the whole connect path: no runtime surface may open a\n\t// partially upgraded authorization schema and discover the drift via raw SELECTs.\n\tassertRecipientPolicyDeviceEligibilityCompatibility(db);\n\t// Reinstall outside the compatibility marker so a missing or stale security\n\t// trigger self-heals before any authorization reader can use the connection.\n\tensureIdentityDeviceAssignmentVersionTriggers(db);\n\tif (!compatAlreadyApplied) markSchemaCompatApplied(db);\n\ttry {\n\t\trepairShareOperationEffectIdIndex(db);\n\t} catch {\n\t\t// Keep compatibility shim fail-open for interrupted or partial legacy schemas.\n\t}\n\n\t// Always runs (not gated): moveMemoryProject relies on this backfill +\n\t// reader-fallback to propagate sessions.project edits to legacy NULL rows.\n\tbackfillMemoryItemProject(db);\n}\n\n/** Safely parse a JSON string, returning {} on failure. */\nexport function fromJson(text: string | null | undefined): Record<string, unknown> {\n\tif (!text) return {};\n\ttry {\n\t\tconst parsed = JSON.parse(text);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\treturn {};\n\t\t}\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\tconsole.warn(`[codemem] fromJson: invalid JSON (${text.slice(0, 80)}...)`);\n\t\treturn {};\n\t}\n}\n\n/**\n * Parse a JSON string strictly — throws on invalid input.\n *\n * Use in mutation paths (replication apply, import) where silently\n * returning {} would mask data corruption. Read paths should use\n * fromJson() which is forgiving.\n */\nexport function fromJsonStrict(text: string | null | undefined): Record<string, unknown> {\n\tif (!text) return {};\n\tconst parsed = JSON.parse(text);\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(\n\t\t\t`fromJsonStrict: expected object, got ${Array.isArray(parsed) ? \"array\" : typeof parsed}`,\n\t\t);\n\t}\n\treturn parsed as Record<string, unknown>;\n}\n\n/** Serialize a value to JSON, defaulting null/undefined to \"{}\". */\nexport function toJson(data: unknown): string {\n\tif (data == null) return \"{}\";\n\treturn JSON.stringify(data);\n}\n\n/**\n * Serialize a value to JSON, preserving null as SQL NULL.\n *\n * Use this for columns that store JSON arrays (facts, concepts, files_read,\n * files_modified) where NULL means \"no data\" and \"{}\" would be corruption.\n * Also normalizes empty objects ({}) to null — Python's from_json returns {}\n * for empty DB values, so imported exports carry {} instead of null.\n * Use `toJson` for metadata_json where \"{}\" is the correct empty default.\n */\nexport function toJsonNullable(data: unknown): string | null {\n\tif (data == null) return null;\n\t// Normalize empty objects to null — these are never valid array column values\n\tif (\n\t\ttypeof data === \"object\" &&\n\t\t!Array.isArray(data) &&\n\t\tObject.keys(data as object).length === 0\n\t) {\n\t\treturn null;\n\t}\n\treturn JSON.stringify(data);\n}\n","/**\n * Drizzle ORM schema for the codemem SQLite database.\n */\n\nimport { sql } from \"drizzle-orm\";\nimport {\n\tindex,\n\tinteger,\n\tprimaryKey,\n\treal,\n\tsqliteTable,\n\ttext,\n\tuniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\n\nexport const sessions = sqliteTable(\n\t\"sessions\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tstarted_at: text(\"started_at\").notNull(),\n\t\tended_at: text(\"ended_at\"),\n\t\tcwd: text(\"cwd\"),\n\t\tproject: text(\"project\"),\n\t\tgit_remote: text(\"git_remote\"),\n\t\tgit_branch: text(\"git_branch\"),\n\t\tuser: text(\"user\"),\n\t\ttool_version: text(\"tool_version\"),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\timport_key: text(\"import_key\"),\n\t},\n\t(table) => [\n\t\t// Keyset paging for newest-first candidate scans (listProjectScopeCandidates).\n\t\tindex(\"idx_sessions_started_id\").on(table.started_at, table.id),\n\t],\n);\n\nexport type Session = typeof sessions.$inferSelect;\nexport type NewSession = typeof sessions.$inferInsert;\n\nexport const replicationScopes = sqliteTable(\n\t\"replication_scopes\",\n\t{\n\t\tscope_id: text(\"scope_id\").primaryKey(),\n\t\tlabel: text(\"label\").notNull(),\n\t\tkind: text(\"kind\").notNull().default(\"user\"),\n\t\tauthority_type: text(\"authority_type\").notNull().default(\"local\"),\n\t\tcoordinator_id: text(\"coordinator_id\"),\n\t\tgroup_id: text(\"group_id\"),\n\t\tmanifest_issuer_device_id: text(\"manifest_issuer_device_id\"),\n\t\tmembership_epoch: integer(\"membership_epoch\").notNull().default(0),\n\t\tmanifest_hash: text(\"manifest_hash\"),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tindex(\"idx_replication_scopes_status\").on(table.status),\n\t\tindex(\"idx_replication_scopes_authority_group\").on(table.coordinator_id, table.group_id),\n\t],\n);\n\nexport type ReplicationScope = typeof replicationScopes.$inferSelect;\nexport type NewReplicationScope = typeof replicationScopes.$inferInsert;\n\nexport const projectScopeMappings = sqliteTable(\n\t\"project_scope_mappings\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tworkspace_identity: text(\"workspace_identity\"),\n\t\tproject_pattern: text(\"project_pattern\").notNull(),\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tpriority: integer(\"priority\").notNull().default(0),\n\t\tsource: text(\"source\").notNull().default(\"user\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tindex(\"idx_project_scope_mappings_workspace_priority\").on(\n\t\t\ttable.workspace_identity,\n\t\t\ttable.priority,\n\t\t),\n\t\tindex(\"idx_project_scope_mappings_pattern_priority\").on(table.project_pattern, table.priority),\n\t\tindex(\"idx_project_scope_mappings_scope\").on(table.scope_id),\n\t],\n);\n\nexport type ProjectScopeMapping = typeof projectScopeMappings.$inferSelect;\nexport type NewProjectScopeMapping = typeof projectScopeMappings.$inferInsert;\n\nexport const scopeMemberships = sqliteTable(\n\t\"scope_memberships\",\n\t{\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\trole: text(\"role\").notNull().default(\"member\"),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\tmembership_epoch: integer(\"membership_epoch\").notNull().default(0),\n\t\tcoordinator_id: text(\"coordinator_id\"),\n\t\tgroup_id: text(\"group_id\"),\n\t\tmanifest_issuer_device_id: text(\"manifest_issuer_device_id\"),\n\t\tmanifest_hash: text(\"manifest_hash\"),\n\t\tsigned_manifest_json: text(\"signed_manifest_json\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.scope_id, table.device_id] }),\n\t\tindex(\"idx_scope_memberships_device_status\").on(table.device_id, table.status),\n\t\tindex(\"idx_scope_memberships_scope_status\").on(table.scope_id, table.status),\n\t\tindex(\"idx_scope_memberships_authority_group\").on(table.coordinator_id, table.group_id),\n\t],\n);\n\nexport type ScopeMembership = typeof scopeMemberships.$inferSelect;\nexport type NewScopeMembership = typeof scopeMemberships.$inferInsert;\n\nexport const artifacts = sqliteTable(\n\t\"artifacts\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tkind: text(\"kind\").notNull(),\n\t\tpath: text(\"path\"),\n\t\tcontent_text: text(\"content_text\"),\n\t\tcontent_hash: text(\"content_hash\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t},\n\t(table) => [index(\"idx_artifacts_session_kind\").on(table.session_id, table.kind)],\n);\n\nexport type Artifact = typeof artifacts.$inferSelect;\nexport type NewArtifact = typeof artifacts.$inferInsert;\n\nexport const memoryItems = sqliteTable(\n\t\"memory_items\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tkind: text(\"kind\").notNull(),\n\t\ttitle: text(\"title\").notNull(),\n\t\tsubtitle: text(\"subtitle\"),\n\t\tbody_text: text(\"body_text\").notNull(),\n\t\tconfidence: real(\"confidence\").default(0.5),\n\t\ttags_text: text(\"tags_text\").default(\"\"),\n\t\tactive: integer(\"active\").default(1),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\tactor_id: text(\"actor_id\"),\n\t\tactor_display_name: text(\"actor_display_name\"),\n\t\tvisibility: text(\"visibility\"),\n\t\tworkspace_id: text(\"workspace_id\"),\n\t\tworkspace_kind: text(\"workspace_kind\"),\n\t\torigin_device_id: text(\"origin_device_id\"),\n\t\torigin_source: text(\"origin_source\"),\n\t\ttrust_state: text(\"trust_state\"),\n\t\tfacts: text(\"facts\"),\n\t\tnarrative: text(\"narrative\"),\n\t\tconcepts: text(\"concepts\"),\n\t\tfiles_read: text(\"files_read\"),\n\t\tfiles_modified: text(\"files_modified\"),\n\t\tuser_prompt_id: integer(\"user_prompt_id\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\tdeleted_at: text(\"deleted_at\"),\n\t\trev: integer(\"rev\").default(0),\n\t\tdedup_key: text(\"dedup_key\"),\n\t\timport_key: text(\"import_key\"),\n\t\tscope_id: text(\"scope_id\"),\n\t\t// Denormalized project name. Carries the originating session's project\n\t\t// across sync boundaries so cross-device memories surface under their\n\t\t// real project identity instead of an inferred placeholder. Backfilled\n\t\t// from sessions.project for legacy rows during migration. May be null\n\t\t// when the originating session had no project.\n\t\tproject: text(\"project\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_memory_items_active_created\").on(table.active, table.created_at),\n\t\tindex(\"idx_memory_items_created_id\").on(table.created_at, table.id),\n\t\tindex(\"idx_memory_items_origin_device_active\").on(table.origin_device_id, table.active),\n\t\tindex(\"idx_memory_items_session\").on(table.session_id),\n\t\tindex(\"idx_memory_items_project\").on(table.project),\n\t\tindex(\"idx_memory_items_scope_visibility_created\").on(\n\t\t\ttable.scope_id,\n\t\t\ttable.visibility,\n\t\t\ttable.created_at,\n\t\t),\n\t\tindex(\"idx_memory_items_scope_backfill_pending\")\n\t\t\t.on(table.id)\n\t\t\t.where(sql`scope_id IS NULL OR scope_id = ''`),\n\t\tindex(\"idx_memory_items_dedup_key_active_created\").on(\n\t\t\ttable.dedup_key,\n\t\t\ttable.active,\n\t\t\ttable.created_at,\n\t\t),\n\t\tuniqueIndex(\"idx_memory_items_same_session_dedup_unique\")\n\t\t\t.on(table.session_id, table.kind, table.visibility, table.workspace_id, table.dedup_key)\n\t\t\t.where(sql`active = 1 AND dedup_key IS NOT NULL`),\n\t],\n);\n\nexport type MemoryItem = typeof memoryItems.$inferSelect;\nexport type NewMemoryItem = typeof memoryItems.$inferInsert;\n\nexport const memoryFileRefs = sqliteTable(\n\t\"memory_file_refs\",\n\t{\n\t\tmemory_id: integer(\"memory_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => memoryItems.id, { onDelete: \"cascade\" }),\n\t\tfile_path: text(\"file_path\").notNull(),\n\t\trelation: text(\"relation\").notNull(), // 'read' | 'modified'\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.memory_id, table.file_path, table.relation] }),\n\t\tindex(\"idx_memory_file_refs_path\").on(table.file_path),\n\t],\n);\n\nexport type MemoryFileRef = typeof memoryFileRefs.$inferSelect;\nexport type NewMemoryFileRef = typeof memoryFileRefs.$inferInsert;\n\nexport const memoryConceptRefs = sqliteTable(\n\t\"memory_concept_refs\",\n\t{\n\t\tmemory_id: integer(\"memory_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => memoryItems.id, { onDelete: \"cascade\" }),\n\t\tconcept: text(\"concept\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.memory_id, table.concept] }),\n\t\tindex(\"idx_memory_concept_refs_concept\").on(table.concept),\n\t],\n);\n\nexport type MemoryConceptRef = typeof memoryConceptRefs.$inferSelect;\nexport type NewMemoryConceptRef = typeof memoryConceptRefs.$inferInsert;\n\nexport const usageEvents = sqliteTable(\n\t\"usage_events\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"set null\",\n\t\t}),\n\t\tevent: text(\"event\").notNull(),\n\t\ttokens_read: integer(\"tokens_read\").default(0),\n\t\ttokens_written: integer(\"tokens_written\").default(0),\n\t\ttokens_saved: integer(\"tokens_saved\").default(0),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_usage_events_event_created\").on(table.event, table.created_at),\n\t\tindex(\"idx_usage_events_session\").on(table.session_id),\n\t],\n);\n\nexport type UsageEvent = typeof usageEvents.$inferSelect;\nexport type NewUsageEvent = typeof usageEvents.$inferInsert;\n\nexport const retrievalAttempts = sqliteTable(\n\t\"retrieval_attempts\",\n\t{\n\t\tattempt_id: text(\"attempt_id\").primaryKey(),\n\t\tcontract_version: integer(\"contract_version\").notNull(),\n\t\tsurface: text(\"surface\").notNull(),\n\t\ttrigger: text(\"trigger\").notNull(),\n\t\tstarted_at: text(\"started_at\").notNull(),\n\t\tcompleted_at: text(\"completed_at\"),\n\t\tretrieval_status: text(\"retrieval_status\").notNull(),\n\t\tdelivery_status: text(\"delivery_status\").notNull(),\n\t\tcandidate_count: integer(\"candidate_count\").notNull(),\n\t\tselected_count: integer(\"selected_count\").notNull(),\n\t\tpersisted_candidate_count: integer(\"persisted_candidate_count\").notNull(),\n\t\trecorder_version: text(\"recorder_version\").notNull(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tsource: text(\"source\"),\n\t\tstream_id: text(\"stream_id\"),\n\t\tsource_session_id: text(\"source_session_id\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\trequest_id: text(\"request_id\"),\n\t\traw_event_start_seq: integer(\"raw_event_start_seq\"),\n\t\traw_event_end_seq: integer(\"raw_event_end_seq\"),\n\t\texperiment_id: text(\"experiment_id\"),\n\t\texperiment_cell_id: text(\"experiment_cell_id\"),\n\t\tevaluation_checkout_id: text(\"evaluation_checkout_id\"),\n\t\tevaluation_fixture_id: text(\"evaluation_fixture_id\"),\n\t\tevaluation_seed: integer(\"evaluation_seed\"),\n\t\tlatency_ms: integer(\"latency_ms\"),\n\t\tproject: text(\"project\"),\n\t\tscope_id: text(\"scope_id\"),\n\t\tmode: text(\"mode\"),\n\t\tlimit_requested: integer(\"limit_requested\"),\n\t\ttoken_budget: integer(\"token_budget\"),\n\t\toutput_tokens: integer(\"output_tokens\"),\n\t\tworking_set_file_count: integer(\"working_set_file_count\"),\n\t\tworking_set_files_json: text(\"working_set_files_json\"),\n\t\tquery_hash_sha256: text(\"query_hash_sha256\"),\n\t\tquery_char_count: integer(\"query_char_count\"),\n\t\tquery_token_estimate: integer(\"query_token_estimate\"),\n\t\tfilter_summary_json: text(\"filter_summary_json\"),\n\t\tfailure_code: text(\"failure_code\"),\n\t\tfailure_stage: text(\"failure_stage\"),\n\t\ttrace_version: integer(\"trace_version\"),\n\t\tautomatic_recall_json: text(\"automatic_recall_json\"),\n\t\tautomatic_recall_key: text(\"automatic_recall_key\"),\n\t\tretention_until: text(\"retention_until\"),\n\t\tretention_pinned: integer(\"retention_pinned\").notNull().default(0),\n\t\tretention_finalized_at: text(\"retention_finalized_at\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_retrieval_attempts_session_started\").on(table.session_id, table.started_at),\n\t\tuniqueIndex(\"idx_retrieval_attempts_automatic_recall_key\").on(table.automatic_recall_key),\n\t\tindex(\"idx_retrieval_attempts_source_stream_started\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.started_at,\n\t\t),\n\t\tindex(\"idx_retrieval_attempts_retention\").on(table.retention_pinned, table.retention_until),\n\t\tindex(\"idx_retrieval_attempts_started\").on(table.started_at, table.attempt_id),\n\t\tindex(\"idx_retrieval_attempts_surface_started\").on(table.surface, table.started_at),\n\t\tuniqueIndex(\"idx_retrieval_attempts_request_identity\")\n\t\t\t.on(table.source, table.surface, table.request_id)\n\t\t\t.where(sql`request_id IS NOT NULL`),\n\t\tindex(\"idx_retrieval_attempts_experiment_cell\").on(\n\t\t\ttable.experiment_id,\n\t\t\ttable.experiment_cell_id,\n\t\t),\n\t],\n);\n\nexport type RetrievalAttempt = typeof retrievalAttempts.$inferSelect;\nexport type NewRetrievalAttempt = typeof retrievalAttempts.$inferInsert;\n\nexport const retrievalExposures = sqliteTable(\n\t\"retrieval_exposures\",\n\t{\n\t\texposure_id: integer(\"exposure_id\").primaryKey({ autoIncrement: true }),\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => retrievalAttempts.attempt_id, { onDelete: \"cascade\" }),\n\t\tmemory_id: integer(\"memory_id\").references(() => memoryItems.id, { onDelete: \"set null\" }),\n\t\tmemory_import_key: text(\"memory_import_key\"),\n\t\torigin_device_id: text(\"origin_device_id\"),\n\t\trank: integer(\"rank\").notNull(),\n\t\tdisposition: text(\"disposition\").notNull(),\n\t\tsection: text(\"section\"),\n\t\thandoff_status: text(\"handoff_status\").notNull(),\n\t\tmemory_rev: integer(\"memory_rev\"),\n\t\tmemory_updated_at: text(\"memory_updated_at\"),\n\t\tmemory_scope_id: text(\"memory_scope_id\"),\n\t\tmemory_kind: text(\"memory_kind\"),\n\t\tmemory_active: integer(\"memory_active\"),\n\t\tmemory_deleted_at: text(\"memory_deleted_at\"),\n\t\tscore_summary_json: text(\"score_summary_json\"),\n\t\treason_codes_json: text(\"reason_codes_json\"),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_retrieval_exposures_attempt_rank\").on(table.attempt_id, table.rank),\n\t\tindex(\"idx_retrieval_exposures_memory\").on(table.memory_id),\n\t],\n);\n\nexport type RetrievalExposure = typeof retrievalExposures.$inferSelect;\nexport type NewRetrievalExposure = typeof retrievalExposures.$inferInsert;\n\nexport const outcomeEvidence = sqliteTable(\n\t\"outcome_evidence\",\n\t{\n\t\tevidence_id: text(\"evidence_id\").primaryKey(),\n\t\tcontract_version: integer(\"contract_version\").notNull(),\n\t\tdimension: text(\"dimension\").notNull(),\n\t\tevidence_type: text(\"evidence_type\").notNull(),\n\t\tsource_class: text(\"source_class\").notNull(),\n\t\tobserved_at: text(\"observed_at\").notNull(),\n\t\tproducer: text(\"producer\").notNull(),\n\t\tproducer_version: text(\"producer_version\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tvalue_type: text(\"value_type\"),\n\t\tvalue_integer: integer(\"value_integer\"),\n\t\tvalue_real: real(\"value_real\"),\n\t\tvalue_unit: text(\"value_unit\"),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, { onDelete: \"cascade\" }),\n\t\tsource: text(\"source\"),\n\t\tstream_id: text(\"stream_id\"),\n\t\tsource_session_id: text(\"source_session_id\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\traw_event_start_seq: integer(\"raw_event_start_seq\"),\n\t\traw_event_end_seq: integer(\"raw_event_end_seq\"),\n\t\texperiment_id: text(\"experiment_id\"),\n\t\texperiment_cell_id: text(\"experiment_cell_id\"),\n\t\twindow_start_at: text(\"window_start_at\"),\n\t\twindow_end_at: text(\"window_end_at\"),\n\t\treferences_json: text(\"references_json\"),\n\t\tretention_until: text(\"retention_until\"),\n\t\tretention_pinned: integer(\"retention_pinned\").notNull().default(0),\n\t\tretention_finalized_at: text(\"retention_finalized_at\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_outcome_evidence_observed_id\").on(table.observed_at, table.evidence_id),\n\t\tindex(\"idx_outcome_evidence_session_observed\").on(table.session_id, table.observed_at),\n\t\tindex(\"idx_outcome_evidence_source_stream_observed\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.observed_at,\n\t\t),\n\t\tindex(\"idx_outcome_evidence_type_observed\").on(table.evidence_type, table.observed_at),\n\t\tindex(\"idx_outcome_evidence_retention\").on(table.retention_pinned, table.retention_until),\n\t],\n);\n\nexport type OutcomeEvidence = typeof outcomeEvidence.$inferSelect;\nexport type NewOutcomeEvidence = typeof outcomeEvidence.$inferInsert;\n\nexport const attributionAssessments = sqliteTable(\n\t\"attribution_assessments\",\n\t{\n\t\tassessment_id: text(\"assessment_id\").primaryKey(),\n\t\tcontract_version: integer(\"contract_version\").notNull(),\n\t\tsubject_type: text(\"subject_type\").notNull(),\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => retrievalAttempts.attempt_id, { onDelete: \"cascade\" }),\n\t\texposure_id: integer(\"exposure_id\").references(() => retrievalExposures.exposure_id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tdimension: text(\"dimension\").notNull(),\n\t\timpact_label: text(\"impact_label\").notNull(),\n\t\tbasis: text(\"basis\").notNull(),\n\t\tconfidence_level: text(\"confidence_level\").notNull(),\n\t\tmethod: text(\"method\").notNull(),\n\t\tmethod_version: text(\"method_version\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tclaim_type: text(\"claim_type\").notNull().default(\"observational\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_attribution_assessments_attempt_created\").on(table.attempt_id, table.created_at),\n\t\tindex(\"idx_attribution_assessments_label_created\").on(table.impact_label, table.created_at),\n\t\tindex(\"idx_attribution_assessments_exposure\").on(table.exposure_id),\n\t],\n);\n\nexport type AttributionAssessment = typeof attributionAssessments.$inferSelect;\nexport type NewAttributionAssessment = typeof attributionAssessments.$inferInsert;\n\nexport const attributionAssessmentEvidence = sqliteTable(\n\t\"attribution_assessment_evidence\",\n\t{\n\t\tassessment_id: text(\"assessment_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => attributionAssessments.assessment_id, { onDelete: \"cascade\" }),\n\t\tevidence_id: text(\"evidence_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => outcomeEvidence.evidence_id, { onDelete: \"cascade\" }),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.assessment_id, table.evidence_id] }),\n\t\tindex(\"idx_attribution_assessment_evidence_evidence\").on(\n\t\t\ttable.evidence_id,\n\t\t\ttable.assessment_id,\n\t\t),\n\t],\n);\n\nexport type AttributionAssessmentEvidence = typeof attributionAssessmentEvidence.$inferSelect;\nexport type NewAttributionAssessmentEvidence = typeof attributionAssessmentEvidence.$inferInsert;\n\nexport const maintenanceJobs = sqliteTable(\n\t\"maintenance_jobs\",\n\t{\n\t\tkind: text(\"kind\").primaryKey(),\n\t\ttitle: text(\"title\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tmessage: text(\"message\"),\n\t\tprogress_current: integer(\"progress_current\").notNull().default(0),\n\t\tprogress_total: integer(\"progress_total\"),\n\t\tprogress_unit: text(\"progress_unit\").notNull().default(\"items\"),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\tstarted_at: text(\"started_at\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t\tfinished_at: text(\"finished_at\"),\n\t\terror: text(\"error\"),\n\t},\n\t(table) => [index(\"idx_maintenance_jobs_status_updated\").on(table.status, table.updated_at)],\n);\n\nexport type MaintenanceJob = typeof maintenanceJobs.$inferSelect;\nexport type NewMaintenanceJob = typeof maintenanceJobs.$inferInsert;\n\nexport const rawEvents = sqliteTable(\n\t\"raw_events\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tevent_id: text(\"event_id\"),\n\t\tevent_seq: integer(\"event_seq\").notNull(),\n\t\tevent_type: text(\"event_type\").notNull(),\n\t\tts_wall_ms: integer(\"ts_wall_ms\"),\n\t\tts_mono_ms: real(\"ts_mono_ms\"),\n\t\tpayload_json: text(\"payload_json\").notNull(),\n\t\tcapture_context_json: text(\"capture_context_json\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_raw_events_source_stream_seq\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.event_seq,\n\t\t),\n\t\tuniqueIndex(\"idx_raw_events_source_stream_event_id\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.event_id,\n\t\t),\n\t\tindex(\"idx_raw_events_session_seq\").on(table.opencode_session_id, table.event_seq),\n\t\tindex(\"idx_raw_events_created\").on(table.created_at),\n\t\tindex(\"idx_raw_events_capture_context\")\n\t\t\t.on(table.source, table.stream_id, table.event_seq)\n\t\t\t.where(sql`${table.capture_context_json} IS NOT NULL`),\n\t],\n);\n\nexport type RawEvent = typeof rawEvents.$inferSelect;\nexport type NewRawEvent = typeof rawEvents.$inferInsert;\n\nexport const rawEventSessions = sqliteTable(\n\t\"raw_event_sessions\",\n\t{\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tcwd: text(\"cwd\"),\n\t\tproject: text(\"project\"),\n\t\tstarted_at: text(\"started_at\"),\n\t\tlast_seen_ts_wall_ms: integer(\"last_seen_ts_wall_ms\"),\n\t\tlast_received_event_seq: integer(\"last_received_event_seq\").notNull().default(-1),\n\t\tlast_flushed_event_seq: integer(\"last_flushed_event_seq\").notNull().default(-1),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.source, table.stream_id] }),\n\t\tindex(\"idx_raw_event_sessions_pending_updated\")\n\t\t\t.on(table.updated_at)\n\t\t\t.where(sql`${table.last_received_event_seq} > ${table.last_flushed_event_seq}`),\n\t],\n);\n\nexport type RawEventSession = typeof rawEventSessions.$inferSelect;\nexport type NewRawEventSession = typeof rawEventSessions.$inferInsert;\n\nexport const piImportState = sqliteTable(\"pi_import_state\", {\n\tfile_path: text(\"file_path\").primaryKey(),\n\tsize_bytes: integer(\"size_bytes\").notNull(),\n\tmtime_ms: real(\"mtime_ms\").notNull(),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type PiImportStateRow = typeof piImportState.$inferSelect;\nexport type NewPiImportStateRow = typeof piImportState.$inferInsert;\n\nexport const opencodeSessions = sqliteTable(\n\t\"opencode_sessions\",\n\t{\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.source, table.stream_id] }),\n\t\tindex(\"idx_opencode_sessions_session\").on(table.session_id),\n\t],\n);\n\nexport type OpencodeSession = typeof opencodeSessions.$inferSelect;\nexport type NewOpencodeSession = typeof opencodeSessions.$inferInsert;\n\nexport const rawEventFlushBatches = sqliteTable(\n\t\"raw_event_flush_batches\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsource: text(\"source\").notNull().default(\"opencode\"),\n\t\tstream_id: text(\"stream_id\").notNull().default(\"\"),\n\t\topencode_session_id: text(\"opencode_session_id\").notNull(),\n\t\tstart_event_seq: integer(\"start_event_seq\").notNull(),\n\t\tend_event_seq: integer(\"end_event_seq\").notNull(),\n\t\textractor_version: text(\"extractor_version\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\terror_message: text(\"error_message\"),\n\t\terror_type: text(\"error_type\"),\n\t\tobserver_provider: text(\"observer_provider\"),\n\t\tobserver_model: text(\"observer_model\"),\n\t\tobserver_runtime: text(\"observer_runtime\"),\n\t\tobserver_auth_source: text(\"observer_auth_source\"),\n\t\tobserver_auth_type: text(\"observer_auth_type\"),\n\t\tobserver_error_code: text(\"observer_error_code\"),\n\t\tobserver_error_message: text(\"observer_error_message\"),\n\t\tattempt_count: integer(\"attempt_count\").notNull().default(0),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_flush_batches_source_stream_seq_ver\").on(\n\t\t\ttable.source,\n\t\t\ttable.stream_id,\n\t\t\ttable.start_event_seq,\n\t\t\ttable.end_event_seq,\n\t\t\ttable.extractor_version,\n\t\t),\n\t\tindex(\"idx_flush_batches_session_created\").on(table.opencode_session_id, table.created_at),\n\t\tindex(\"idx_flush_batches_status_updated\").on(table.status, table.updated_at),\n\t\tindex(\"idx_flush_batches_observer_status_updated\")\n\t\t\t.on(table.status, table.updated_at)\n\t\t\t.where(sql`${table.observer_provider} IS NOT NULL`),\n\t\tindex(\"idx_flush_batches_capture_status_updated\")\n\t\t\t.on(table.status, table.updated_at)\n\t\t\t.where(sql`${table.observer_provider} IS NULL`),\n\t],\n);\n\nexport type RawEventFlushBatch = typeof rawEventFlushBatches.$inferSelect;\nexport type NewRawEventFlushBatch = typeof rawEventFlushBatches.$inferInsert;\n\nexport const userPrompts = sqliteTable(\n\t\"user_prompts\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tproject: text(\"project\"),\n\t\tprompt_text: text(\"prompt_text\").notNull(),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tcreated_at_epoch: integer(\"created_at_epoch\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\timport_key: text(\"import_key\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_user_prompts_session\").on(table.session_id),\n\t\tindex(\"idx_user_prompts_project\").on(table.project),\n\t\tindex(\"idx_user_prompts_epoch\").on(table.created_at_epoch),\n\t],\n);\n\nexport type UserPrompt = typeof userPrompts.$inferSelect;\nexport type NewUserPrompt = typeof userPrompts.$inferInsert;\n\nexport const sessionSummaries = sqliteTable(\n\t\"session_summaries\",\n\t{\n\t\tid: integer(\"id\").primaryKey(),\n\t\tsession_id: integer(\"session_id\").references(() => sessions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tproject: text(\"project\"),\n\t\trequest: text(\"request\"),\n\t\tinvestigated: text(\"investigated\"),\n\t\tlearned: text(\"learned\"),\n\t\tcompleted: text(\"completed\"),\n\t\tnext_steps: text(\"next_steps\"),\n\t\tnotes: text(\"notes\"),\n\t\tfiles_read: text(\"files_read\"),\n\t\tfiles_edited: text(\"files_edited\"),\n\t\tprompt_number: integer(\"prompt_number\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tcreated_at_epoch: integer(\"created_at_epoch\").notNull(),\n\t\tmetadata_json: text(\"metadata_json\"),\n\t\timport_key: text(\"import_key\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_session_summaries_session\").on(table.session_id),\n\t\tindex(\"idx_session_summaries_project\").on(table.project),\n\t\tindex(\"idx_session_summaries_epoch\").on(table.created_at_epoch),\n\t],\n);\n\nexport type SessionSummary = typeof sessionSummaries.$inferSelect;\nexport type NewSessionSummary = typeof sessionSummaries.$inferInsert;\n\nexport const replicationOps = sqliteTable(\n\t\"replication_ops\",\n\t{\n\t\top_id: text(\"op_id\").primaryKey(),\n\t\tentity_type: text(\"entity_type\").notNull(),\n\t\tentity_id: text(\"entity_id\").notNull(),\n\t\top_type: text(\"op_type\").notNull(),\n\t\tpayload_json: text(\"payload_json\"),\n\t\tclock_rev: integer(\"clock_rev\").notNull(),\n\t\tclock_updated_at: text(\"clock_updated_at\").notNull(),\n\t\tclock_device_id: text(\"clock_device_id\").notNull(),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tscope_id: text(\"scope_id\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_replication_ops_created\").on(table.created_at, table.op_id),\n\t\tindex(\"idx_replication_ops_entity\").on(table.entity_type, table.entity_id),\n\t\tindex(\"idx_replication_ops_scope_created\").on(table.scope_id, table.created_at, table.op_id),\n\t],\n);\n\nexport type ReplicationOp = typeof replicationOps.$inferSelect;\nexport type NewReplicationOp = typeof replicationOps.$inferInsert;\n\nexport const replicationCursors = sqliteTable(\"replication_cursors\", {\n\tpeer_device_id: text(\"peer_device_id\").primaryKey(),\n\tlast_applied_cursor: text(\"last_applied_cursor\"),\n\tlast_acked_cursor: text(\"last_acked_cursor\"),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type ReplicationCursor = typeof replicationCursors.$inferSelect;\nexport type NewReplicationCursor = typeof replicationCursors.$inferInsert;\n\nexport const replicationCursorsV2 = sqliteTable(\n\t\"replication_cursors_v2\",\n\t{\n\t\tpeer_device_id: text(\"peer_device_id\").notNull(),\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tlast_applied_cursor: text(\"last_applied_cursor\"),\n\t\tlast_acked_cursor: text(\"last_acked_cursor\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.peer_device_id, table.scope_id] }),\n\t\tindex(\"idx_replication_cursors_v2_scope\").on(table.scope_id),\n\t],\n);\n\nexport type ReplicationCursorV2 = typeof replicationCursorsV2.$inferSelect;\nexport type NewReplicationCursorV2 = typeof replicationCursorsV2.$inferInsert;\n\nexport const syncPeers = sqliteTable(\"sync_peers\", {\n\tpeer_device_id: text(\"peer_device_id\").primaryKey(),\n\tname: text(\"name\"),\n\tpinned_fingerprint: text(\"pinned_fingerprint\"),\n\tpublic_key: text(\"public_key\"),\n\taddresses_json: text(\"addresses_json\"),\n\tmanual_addresses_json: text(\"manual_addresses_json\"),\n\tlast_success_address: text(\"last_success_address\"),\n\tclaimed_local_actor: integer(\"claimed_local_actor\").notNull().default(0),\n\tactor_id: text(\"actor_id\"),\n\tprojects_include_json: text(\"projects_include_json\"),\n\tprojects_exclude_json: text(\"projects_exclude_json\"),\n\tcreated_at: text(\"created_at\").notNull(),\n\tlast_seen_at: text(\"last_seen_at\"),\n\tlast_sync_at: text(\"last_sync_at\"),\n\tlast_error: text(\"last_error\"),\n\truntime_version: text(\"runtime_version\"),\n\truntime_version_observed_at: text(\"runtime_version_observed_at\"),\n\thighest_observed_direct_signature_version: integer(\"highest_observed_direct_signature_version\"),\n\tdiscovered_via_coordinator_id: text(\"discovered_via_coordinator_id\"),\n\tdiscovered_via_group_id: text(\"discovered_via_group_id\"),\n\ttrust_provenance: text(\"trust_provenance\"),\n\tpending_bootstrap_grant_id: text(\"pending_bootstrap_grant_id\"),\n});\n\nexport type SyncPeer = typeof syncPeers.$inferSelect;\nexport type NewSyncPeer = typeof syncPeers.$inferInsert;\n\nexport const syncPeerSignatureState = sqliteTable(\"sync_peer_signature_state\", {\n\tpeer_device_id: text(\"peer_device_id\").primaryKey(),\n\thighest_observed_direct_signature_version: integer(\n\t\t\"highest_observed_direct_signature_version\",\n\t).notNull(),\n});\n\nexport type SyncPeerSignatureState = typeof syncPeerSignatureState.$inferSelect;\nexport type NewSyncPeerSignatureState = typeof syncPeerSignatureState.$inferInsert;\n\nexport const syncNonces = sqliteTable(\"sync_nonces\", {\n\tnonce: text(\"nonce\").primaryKey(),\n\tdevice_id: text(\"device_id\").notNull(),\n\tcreated_at: text(\"created_at\").notNull(),\n});\n\nexport type SyncNonce = typeof syncNonces.$inferSelect;\nexport type NewSyncNonce = typeof syncNonces.$inferInsert;\n\nexport const syncDevice = sqliteTable(\"sync_device\", {\n\tdevice_id: text(\"device_id\").primaryKey(),\n\tpublic_key: text(\"public_key\").notNull(),\n\tfingerprint: text(\"fingerprint\").notNull(),\n\tcreated_at: text(\"created_at\").notNull(),\n});\n\nexport type SyncDevice = typeof syncDevice.$inferSelect;\nexport type NewSyncDevice = typeof syncDevice.$inferInsert;\n\nexport const syncAttempts = sqliteTable(\n\t\"sync_attempts\",\n\t{\n\t\tid: integer(\"id\").primaryKey({ autoIncrement: true }),\n\t\tpeer_device_id: text(\"peer_device_id\").notNull(),\n\t\tstarted_at: text(\"started_at\").notNull(),\n\t\tfinished_at: text(\"finished_at\"),\n\t\tok: integer(\"ok\").notNull(),\n\t\tops_in: integer(\"ops_in\").notNull(),\n\t\tops_out: integer(\"ops_out\").notNull(),\n\t\terror: text(\"error\"),\n\t\tlocal_sync_capability: text(\"local_sync_capability\"),\n\t\tpeer_sync_capability: text(\"peer_sync_capability\"),\n\t\tnegotiated_sync_capability: text(\"negotiated_sync_capability\"),\n\t\tfailure_category: text(\"failure_category\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_sync_attempts_peer_started\").on(table.peer_device_id, table.started_at),\n\t\tindex(\"idx_sync_attempts_occurred\").on(\n\t\t\tsql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`,\n\t\t\ttable.id,\n\t\t),\n\t\tindex(\"idx_sync_attempts_error_occurred\")\n\t\t\t.on(\n\t\t\t\tsql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`,\n\t\t\t\ttable.id,\n\t\t\t)\n\t\t\t.where(sql`${table.ok} = 0`),\n\t\tindex(\"idx_sync_attempts_success_occurred\")\n\t\t\t.on(\n\t\t\t\tsql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`,\n\t\t\t\ttable.id,\n\t\t\t)\n\t\t\t.where(sql`${table.ok} <> 0`),\n\t],\n);\n\nexport type SyncAttempt = typeof syncAttempts.$inferSelect;\nexport type NewSyncAttempt = typeof syncAttempts.$inferInsert;\n\nexport const syncScopeRejections = sqliteTable(\n\t\"sync_scope_rejections\",\n\t{\n\t\tid: integer(\"id\").primaryKey({ autoIncrement: true }),\n\t\tpeer_device_id: text(\"peer_device_id\"),\n\t\top_id: text(\"op_id\").notNull(),\n\t\tentity_type: text(\"entity_type\").notNull(),\n\t\tentity_id: text(\"entity_id\").notNull(),\n\t\tscope_id: text(\"scope_id\"),\n\t\treason: text(\"reason\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tindex(\"idx_sync_scope_rejections_peer_created\").on(table.peer_device_id, table.created_at),\n\t\tindex(\"idx_sync_scope_rejections_scope_created\").on(table.scope_id, table.created_at),\n\t],\n);\n\nexport type SyncScopeRejection = typeof syncScopeRejections.$inferSelect;\nexport type NewSyncScopeRejection = typeof syncScopeRejections.$inferInsert;\n\nexport const syncDaemonState = sqliteTable(\"sync_daemon_state\", {\n\tid: integer(\"id\").primaryKey(),\n\tlast_error: text(\"last_error\"),\n\tlast_traceback: text(\"last_traceback\"),\n\tlast_error_at: text(\"last_error_at\"),\n\tlast_ok_at: text(\"last_ok_at\"),\n\tphase: text(\"phase\"),\n});\n\nexport type SyncDaemonState = typeof syncDaemonState.$inferSelect;\nexport type NewSyncDaemonState = typeof syncDaemonState.$inferInsert;\n\nexport const syncResetState = sqliteTable(\"sync_reset_state\", {\n\tid: integer(\"id\").primaryKey(),\n\tgeneration: integer(\"generation\").notNull(),\n\tsnapshot_id: text(\"snapshot_id\").notNull(),\n\tbaseline_cursor: text(\"baseline_cursor\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type SyncResetState = typeof syncResetState.$inferSelect;\nexport type NewSyncResetState = typeof syncResetState.$inferInsert;\n\nexport const syncResetStateV2 = sqliteTable(\"sync_reset_state_v2\", {\n\tscope_id: text(\"scope_id\").primaryKey(),\n\tgeneration: integer(\"generation\").notNull(),\n\tsnapshot_id: text(\"snapshot_id\").notNull(),\n\tbaseline_cursor: text(\"baseline_cursor\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type SyncResetStateV2 = typeof syncResetStateV2.$inferSelect;\nexport type NewSyncResetStateV2 = typeof syncResetStateV2.$inferInsert;\n\nexport const syncRetentionState = sqliteTable(\"sync_retention_state\", {\n\tid: integer(\"id\").primaryKey(),\n\tlast_run_at: text(\"last_run_at\"),\n\tlast_duration_ms: integer(\"last_duration_ms\"),\n\tlast_deleted_ops: integer(\"last_deleted_ops\").notNull().default(0),\n\tlast_estimated_bytes_before: integer(\"last_estimated_bytes_before\"),\n\tlast_estimated_bytes_after: integer(\"last_estimated_bytes_after\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tlast_error: text(\"last_error\"),\n\tlast_error_at: text(\"last_error_at\"),\n});\n\nexport type SyncRetentionState = typeof syncRetentionState.$inferSelect;\nexport type NewSyncRetentionState = typeof syncRetentionState.$inferInsert;\n\nexport const syncRetentionStateV2 = sqliteTable(\"sync_retention_state_v2\", {\n\tscope_id: text(\"scope_id\").primaryKey(),\n\tlast_run_at: text(\"last_run_at\"),\n\tlast_duration_ms: integer(\"last_duration_ms\"),\n\tlast_deleted_ops: integer(\"last_deleted_ops\").notNull().default(0),\n\tlast_estimated_bytes_before: integer(\"last_estimated_bytes_before\"),\n\tlast_estimated_bytes_after: integer(\"last_estimated_bytes_after\"),\n\tretained_floor_cursor: text(\"retained_floor_cursor\"),\n\tlast_error: text(\"last_error\"),\n\tlast_error_at: text(\"last_error_at\"),\n});\n\nexport type SyncRetentionStateV2 = typeof syncRetentionStateV2.$inferSelect;\nexport type NewSyncRetentionStateV2 = typeof syncRetentionStateV2.$inferInsert;\n\nexport const rawEventIngestSamples = sqliteTable(\"raw_event_ingest_samples\", {\n\tid: integer(\"id\").primaryKey({ autoIncrement: true }),\n\tcreated_at: text(\"created_at\").notNull(),\n\tinserted_events: integer(\"inserted_events\").notNull().default(0),\n\tskipped_invalid: integer(\"skipped_invalid\").notNull().default(0),\n\tskipped_duplicate: integer(\"skipped_duplicate\").notNull().default(0),\n\tskipped_conflict: integer(\"skipped_conflict\").notNull().default(0),\n});\n\nexport type RawEventIngestSample = typeof rawEventIngestSamples.$inferSelect;\nexport type NewRawEventIngestSample = typeof rawEventIngestSamples.$inferInsert;\n\nexport const rawEventIngestStats = sqliteTable(\"raw_event_ingest_stats\", {\n\tid: integer(\"id\").primaryKey(),\n\tinserted_events: integer(\"inserted_events\").notNull().default(0),\n\tskipped_events: integer(\"skipped_events\").notNull().default(0),\n\tskipped_invalid: integer(\"skipped_invalid\").notNull().default(0),\n\tskipped_duplicate: integer(\"skipped_duplicate\").notNull().default(0),\n\tskipped_conflict: integer(\"skipped_conflict\").notNull().default(0),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type RawEventIngestStat = typeof rawEventIngestStats.$inferSelect;\nexport type NewRawEventIngestStat = typeof rawEventIngestStats.$inferInsert;\n\nexport const coordinatorGroupPreferences = sqliteTable(\n\t\"coordinator_group_preferences\",\n\t{\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\tprojects_include_json: text(\"projects_include_json\"),\n\t\tprojects_exclude_json: text(\"projects_exclude_json\"),\n\t\tauto_seed_scope: integer(\"auto_seed_scope\").notNull().default(1),\n\t\tdefault_space_scope_id: text(\"default_space_scope_id\"),\n\t\tauto_grant_default_space_on_join: integer(\"auto_grant_default_space_on_join\")\n\t\t\t.notNull()\n\t\t\t.default(0),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tpk: primaryKey({ columns: [table.coordinator_id, table.group_id] }),\n\t}),\n);\n\nexport type CoordinatorGroupPreferences = typeof coordinatorGroupPreferences.$inferSelect;\nexport type NewCoordinatorGroupPreferences = typeof coordinatorGroupPreferences.$inferInsert;\n\nexport const actors = sqliteTable(\n\t\"actors\",\n\t{\n\t\tactor_id: text(\"actor_id\").primaryKey(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tis_local: integer(\"is_local\").notNull().default(0),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\tmerged_into_actor_id: text(\"merged_into_actor_id\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tisLocalIdx: index(\"idx_actors_is_local\").on(table.is_local),\n\t\tstatusIdx: index(\"idx_actors_status\").on(table.status),\n\t}),\n);\n\nexport type Actor = typeof actors.$inferSelect;\nexport type NewActor = typeof actors.$inferInsert;\n\nexport const recipientPolicyReviewResolutions = sqliteTable(\n\t\"recipient_policy_review_resolutions\",\n\t{\n\t\treview_item_id: text(\"review_item_id\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\").notNull(),\n\t\tdecision: text(\"decision\").notNull(),\n\t\tdecision_input_json: text(\"decision_input_json\").notNull(),\n\t\tpreview_json: text(\"preview_json\").notNull(),\n\t\tdecided_by_identity_id: text(\"decided_by_identity_id\").notNull(),\n\t\tdecided_by_device_id: text(\"decided_by_device_id\").notNull(),\n\t\tresolved_at: text(\"resolved_at\").notNull(),\n\t},\n\t(table) => [primaryKey({ columns: [table.review_item_id, table.source_fingerprint] })],\n);\n\nexport type RecipientPolicyReviewResolution = typeof recipientPolicyReviewResolutions.$inferSelect;\nexport type NewRecipientPolicyReviewResolution =\n\ttypeof recipientPolicyReviewResolutions.$inferInsert;\n\nexport const coordinatorEnrollmentReconciliationIssues = sqliteTable(\n\t\"coordinator_enrollment_reconciliation_issues\",\n\t{\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\tkind: text(\"kind\").notNull(),\n\t\treference_id: text(\"reference_id\").notNull(),\n\t\tcode: text(\"code\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"open\"),\n\t\tfirst_seen_at: text(\"first_seen_at\").notNull(),\n\t\tlast_seen_at: text(\"last_seen_at\").notNull(),\n\t\tresolved_at: text(\"resolved_at\"),\n\t\toccurrence_count: integer(\"occurrence_count\").notNull().default(1),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.coordinator_id, table.group_id, table.kind, table.reference_id, table.code],\n\t\t}),\n\t\tindex(\"idx_coordinator_enrollment_issues_boundary_status\").on(\n\t\t\ttable.coordinator_id,\n\t\t\ttable.group_id,\n\t\t\ttable.status,\n\t\t),\n\t\tindex(\"idx_coordinator_enrollment_issues_status_recent\").on(\n\t\t\ttable.status,\n\t\t\ttable.last_seen_at,\n\t\t\ttable.resolved_at,\n\t\t),\n\t],\n);\n\nexport type CoordinatorEnrollmentReconciliationIssue =\n\ttypeof coordinatorEnrollmentReconciliationIssues.$inferSelect;\nexport type NewCoordinatorEnrollmentReconciliationIssue =\n\ttypeof coordinatorEnrollmentReconciliationIssues.$inferInsert;\n\nexport const policyTeams = sqliteTable(\"policy_teams\", {\n\tteam_id: text(\"team_id\").primaryKey(),\n\tdisplay_name: text(\"display_name\").notNull(),\n\tstatus: text(\"status\").notNull(),\n\tdevice_eligibility_mode: text(\"device_eligibility_mode\").notNull().default(\"person_all_devices\"),\n\tprovenance: text(\"provenance\").notNull(),\n\trevision: text(\"revision\").notNull(),\n\tmigration_state: text(\"migration_state\").notNull(),\n\tsource_fingerprint: text(\"source_fingerprint\"),\n\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\tcreated_at: text(\"created_at\").notNull(),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type PolicyTeam = typeof policyTeams.$inferSelect;\nexport type NewPolicyTeam = typeof policyTeams.$inferInsert;\n\nexport const policyTeamMemberships = sqliteTable(\n\t\"policy_team_memberships\",\n\t{\n\t\tteam_id: text(\"team_id\").notNull(),\n\t\tidentity_id: text(\"identity_id\").notNull(),\n\t\trole: text(\"role\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\trevision: text(\"revision\").notNull(),\n\t\tmigration_state: text(\"migration_state\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\"),\n\t\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tpk: primaryKey({ columns: [table.team_id, table.identity_id] }),\n\t\tidentityStatusIdx: index(\"idx_policy_team_memberships_identity_status\").on(\n\t\t\ttable.identity_id,\n\t\t\ttable.status,\n\t\t),\n\t}),\n);\n\nexport type PolicyTeamMembership = typeof policyTeamMemberships.$inferSelect;\nexport type NewPolicyTeamMembership = typeof policyTeamMemberships.$inferInsert;\n\nexport const policyTeamDeviceDecisions = sqliteTable(\n\t\"policy_team_device_decisions\",\n\t{\n\t\tteam_id: text(\"team_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => policyTeams.team_id, { onDelete: \"cascade\" }),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tdecision: text(\"decision\").notNull(),\n\t\tassignment_version: integer(\"assignment_version\").notNull().default(0),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\trevision: text(\"revision\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.team_id, table.device_id] }),\n\t\tindex(\"idx_policy_team_device_decisions_device\").on(table.device_id),\n\t],\n);\n\nexport type PolicyTeamDeviceDecisionRow = typeof policyTeamDeviceDecisions.$inferSelect;\nexport type NewPolicyTeamDeviceDecisionRow = typeof policyTeamDeviceDecisions.$inferInsert;\n\nexport const identityDevices = sqliteTable(\n\t\"identity_devices\",\n\t{\n\t\tdevice_id: text(\"device_id\").primaryKey(),\n\t\tidentity_id: text(\"identity_id\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\trevision: text(\"revision\").notNull(),\n\t\tmigration_state: text(\"migration_state\").notNull(),\n\t\tassignment_version: integer(\"assignment_version\").notNull().default(0),\n\t\tsource_fingerprint: text(\"source_fingerprint\"),\n\t\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tidentityStatusIdx: index(\"idx_identity_devices_identity_status\").on(\n\t\t\ttable.identity_id,\n\t\t\ttable.status,\n\t\t),\n\t}),\n);\n\nexport type IdentityDevice = typeof identityDevices.$inferSelect;\nexport type NewIdentityDevice = typeof identityDevices.$inferInsert;\n\nexport const deviceIdentityBindingCommits = sqliteTable(\"device_identity_binding_commits\", {\n\tcommit_digest: text(\"commit_digest\").primaryKey(),\n\treviewed_inventory_digest: text(\"reviewed_inventory_digest\").notNull(),\n\trequest_json: text(\"request_json\").notNull(),\n\toutcomes_json: text(\"outcomes_json\").notNull(),\n\twrite_count: integer(\"write_count\").notNull(),\n\tdecided_by_identity_id: text(\"decided_by_identity_id\").notNull(),\n\tdecided_by_device_id: text(\"decided_by_device_id\").notNull(),\n\tcreated_at: text(\"created_at\").notNull(),\n});\n\nexport const deviceIdentityBindingAudit = sqliteTable(\n\t\"device_identity_binding_audit\",\n\t{\n\t\tevent_id: text(\"event_id\").primaryKey(),\n\t\tcommit_digest: text(\"commit_digest\")\n\t\t\t.notNull()\n\t\t\t.references(() => deviceIdentityBindingCommits.commit_digest),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tprevious_identity_id: text(\"previous_identity_id\"),\n\t\ttarget_identity_id: text(\"target_identity_id\").notNull(),\n\t\taction: text(\"action\").notNull(),\n\t\tprevious_assignment_version: integer(\"previous_assignment_version\"),\n\t\tresulting_assignment_version: integer(\"resulting_assignment_version\").notNull(),\n\t\tdecided_by_identity_id: text(\"decided_by_identity_id\").notNull(),\n\t\tdecided_by_device_id: text(\"decided_by_device_id\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_device_identity_binding_audit_commit_device\").on(\n\t\t\ttable.commit_digest,\n\t\t\ttable.device_id,\n\t\t),\n\t\tindex(\"idx_device_identity_binding_audit_device_created\").on(\n\t\t\ttable.device_id,\n\t\t\ttable.created_at,\n\t\t\ttable.event_id,\n\t\t),\n\t],\n);\n\nexport const projectRecipients = sqliteTable(\n\t\"project_recipients\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\trecipient_kind: text(\"recipient_kind\").notNull(),\n\t\trecipient_id: text(\"recipient_id\").notNull(),\n\t\tstatus: text(\"status\").notNull(),\n\t\tprovenance: text(\"provenance\").notNull(),\n\t\tpolicy_revision: text(\"policy_revision\").notNull(),\n\t\tmigration_state: text(\"migration_state\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\"),\n\t\tidempotency_key: text(\"idempotency_key\").notNull().unique(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => ({\n\t\tpk: primaryKey({\n\t\t\tcolumns: [table.canonical_project_identity, table.recipient_kind, table.recipient_id],\n\t\t}),\n\t\tprojectStatusIdx: index(\"idx_project_recipients_project_status\").on(\n\t\t\ttable.canonical_project_identity,\n\t\t\ttable.status,\n\t\t),\n\t\trecipientStatusIdx: index(\"idx_project_recipients_recipient_status\").on(\n\t\t\ttable.recipient_kind,\n\t\t\ttable.recipient_id,\n\t\t\ttable.status,\n\t\t),\n\t}),\n);\n\nexport type ProjectRecipient = typeof projectRecipients.$inferSelect;\nexport type NewProjectRecipient = typeof projectRecipients.$inferInsert;\n\nexport const legacyTeamSetupDrafts = sqliteTable(\n\t\"legacy_team_setup_drafts\",\n\t{\n\t\tattempt_id: text(\"attempt_id\").primaryKey(),\n\t\tcandidate_id: text(\"candidate_id\").notNull(),\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\tstate: text(\"state\").notNull().default(\"needs_setup\"),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\troster_fingerprint: text(\"roster_fingerprint\").notNull(),\n\t\tprojection_fingerprint: text(\"projection_fingerprint\").notNull(),\n\t\tfinish_digest: text(\"finish_digest\"),\n\t\tsafe_error_code: text(\"safe_error_code\"),\n\t\tcompleted_team_id: text(\"completed_team_id\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t\tcompleted_at: text(\"completed_at\"),\n\t\tsuperseded_at: text(\"superseded_at\"),\n\t},\n\t(table) => [\n\t\tindex(\"idx_legacy_team_setup_drafts_candidate_state\").on(\n\t\t\ttable.candidate_id,\n\t\t\ttable.state,\n\t\t\ttable.created_at,\n\t\t),\n\t\tindex(\"idx_legacy_team_setup_drafts_state_updated\").on(table.state, table.updated_at),\n\t\tindex(\"idx_legacy_team_setup_drafts_finish_digest\").on(table.finish_digest),\n\t],\n);\n\nexport type LegacyTeamSetupDraft = typeof legacyTeamSetupDrafts.$inferSelect;\nexport type NewLegacyTeamSetupDraft = typeof legacyTeamSetupDrafts.$inferInsert;\n\nexport const legacyTeamSetupCompletions = sqliteTable(\n\t\"legacy_team_setup_completions\",\n\t{\n\t\tattempt_id: text(\"attempt_id\").notNull(),\n\t\tfinish_digest: text(\"finish_digest\").notNull(),\n\t\tcandidate_ref: text(\"candidate_ref\").notNull(),\n\t\tconfirmed_access_delta_digest: text(\"confirmed_access_delta_digest\").notNull(),\n\t\tcompleted_team_id: text(\"completed_team_id\").notNull(),\n\t\tresponse_json: text(\"response_json\").notNull(),\n\t\tcompleted_at: text(\"completed_at\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t},\n\t(table) => [\n\t\tuniqueIndex(\"idx_legacy_team_setup_completions_attempt_finish\").on(\n\t\t\ttable.attempt_id,\n\t\t\ttable.finish_digest,\n\t\t),\n\t\tindex(\"idx_legacy_team_setup_completions_exact_replay\").on(\n\t\t\ttable.candidate_ref,\n\t\t\ttable.attempt_id,\n\t\t\ttable.finish_digest,\n\t\t\ttable.confirmed_access_delta_digest,\n\t\t),\n\t],\n);\n\nexport type LegacyTeamSetupCompletion = typeof legacyTeamSetupCompletions.$inferSelect;\nexport type NewLegacyTeamSetupCompletion = typeof legacyTeamSetupCompletions.$inferInsert;\n\nexport const legacyTeamSetupDraftDevices = sqliteTable(\n\t\"legacy_team_setup_draft_devices\",\n\t{\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => legacyTeamSetupDrafts.attempt_id, { onDelete: \"cascade\" }),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tdevice_ref: text(\"device_ref\").notNull(),\n\t\tkey_fingerprint: text(\"key_fingerprint\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tenabled: integer(\"enabled\", { mode: \"boolean\" }).notNull(),\n\t\texisting_identity_id: text(\"existing_identity_id\"),\n\t\texisting_assignment_version: integer(\"existing_assignment_version\"),\n\t\tverified_evidence_kind: text(\"verified_evidence_kind\"),\n\t\tidentity_evidence: text(\"identity_evidence\"),\n\t\tdecision: text(\"decision\").notNull().default(\"unresolved\"),\n\t\ttarget_identity_id: text(\"target_identity_id\"),\n\t\texpected_assignment_kind: text(\"expected_assignment_kind\"),\n\t\texpected_assignment_version: integer(\"expected_assignment_version\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.attempt_id, table.device_id] }),\n\t\tuniqueIndex(\"idx_legacy_team_setup_devices_attempt_ref\").on(table.attempt_id, table.device_ref),\n\t\tindex(\"idx_legacy_team_setup_devices_attempt_decision\").on(table.attempt_id, table.decision),\n\t],\n);\n\nexport type LegacyTeamSetupDraftDevice = typeof legacyTeamSetupDraftDevices.$inferSelect;\nexport type NewLegacyTeamSetupDraftDevice = typeof legacyTeamSetupDraftDevices.$inferInsert;\n\nexport const legacyTeamSetupDraftProjects = sqliteTable(\n\t\"legacy_team_setup_draft_projects\",\n\t{\n\t\tattempt_id: text(\"attempt_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => legacyTeamSetupDrafts.attempt_id, { onDelete: \"cascade\" }),\n\t\tproject_ref: text(\"project_ref\").notNull(),\n\t\tsource_project_identity: text(\"source_project_identity\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tsource_fingerprint: text(\"source_fingerprint\").notNull(),\n\t\tresolution_kind: text(\"resolution_kind\").notNull().default(\"unresolved\"),\n\t\tresolved_project_identity: text(\"resolved_project_identity\"),\n\t\ttarget_scope_id: text(\"target_scope_id\"),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({ columns: [table.attempt_id, table.project_ref] }),\n\t\tindex(\"idx_legacy_team_setup_projects_attempt_resolution\").on(\n\t\t\ttable.attempt_id,\n\t\t\ttable.resolution_kind,\n\t\t),\n\t],\n);\n\nexport type LegacyTeamSetupDraftProject = typeof legacyTeamSetupDraftProjects.$inferSelect;\nexport type NewLegacyTeamSetupDraftProject = typeof legacyTeamSetupDraftProjects.$inferInsert;\n\nexport const recipientManagedProjectProjections = sqliteTable(\n\t\"recipient_managed_project_projections\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\tdisplay_name: text(\"display_name\").notNull(),\n\t\tmanaged_scope_id: text(\"managed_scope_id\").notNull(),\n\t\tcoordinator_id: text(\"coordinator_id\").notNull(),\n\t\tgroup_id: text(\"group_id\").notNull(),\n\t\trecipient_identity_id: text(\"recipient_identity_id\").notNull(),\n\t\taccepting_device_id: text(\"accepting_device_id\").notNull(),\n\t\tsource_operation_id: text(\"source_operation_id\").notNull(),\n\t\treviewed_project_set_digest: text(\"reviewed_project_set_digest\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"active\"),\n\t\taccepted_at: text(\"accepted_at\").notNull(),\n\t\trevoked_at: text(\"revoked_at\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.source_operation_id, table.canonical_project_identity],\n\t\t}),\n\t\tindex(\"idx_recipient_managed_projects_identity_status\").on(\n\t\t\ttable.recipient_identity_id,\n\t\t\ttable.status,\n\t\t),\n\t\tindex(\"idx_recipient_managed_projects_scope_authority\").on(\n\t\t\ttable.managed_scope_id,\n\t\t\ttable.coordinator_id,\n\t\t\ttable.group_id,\n\t\t\ttable.status,\n\t\t),\n\t],\n);\n\nexport type RecipientManagedProjectProjection =\n\ttypeof recipientManagedProjectProjections.$inferSelect;\nexport type NewRecipientManagedProjectProjection =\n\ttypeof recipientManagedProjectProjections.$inferInsert;\n\nexport const recipientPolicyAuthorityStates = sqliteTable(\"recipient_policy_authority_states\", {\n\tcanonical_project_identity: text(\"canonical_project_identity\").primaryKey(),\n\tauthority_state: text(\"authority_state\").notNull().default(\"legacy\"),\n\tgeneration: integer(\"generation\").notNull().default(0),\n\tdesired_devices_digest: text(\"desired_devices_digest\"),\n\tcurrent_devices_digest: text(\"current_devices_digest\"),\n\tstable_parity_evidence_digest: text(\"stable_parity_evidence_digest\"),\n\tstable_parity_passed_at: text(\"stable_parity_passed_at\"),\n\tfresh_snapshot_fingerprint: text(\"fresh_snapshot_fingerprint\"),\n\tfresh_snapshot_observed_at: text(\"fresh_snapshot_observed_at\"),\n\tsafe_error_code: text(\"safe_error_code\"),\n\tstate_changed_at: text(\"state_changed_at\").notNull(),\n\tlast_error_at: text(\"last_error_at\"),\n\tattempt_count: integer(\"attempt_count\").notNull().default(0),\n\tlast_attempt_at: text(\"last_attempt_at\"),\n\twake_epoch: integer(\"wake_epoch\").notNull().default(0),\n\tlast_completed_at: text(\"last_completed_at\"),\n\tlease_owner: text(\"lease_owner\"),\n\tlease_acquired_at: text(\"lease_acquired_at\"),\n\tlease_expires_at: text(\"lease_expires_at\"),\n\tcreated_at: text(\"created_at\").notNull(),\n\tupdated_at: text(\"updated_at\").notNull(),\n});\n\nexport type RecipientPolicyAuthorityStateRow = typeof recipientPolicyAuthorityStates.$inferSelect;\nexport type NewRecipientPolicyAuthorityStateRow =\n\ttypeof recipientPolicyAuthorityStates.$inferInsert;\n\nexport const recipientPolicyReconciliationSteps = sqliteTable(\n\t\"recipient_policy_reconciliation_steps\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\tgeneration: integer(\"generation\").notNull(),\n\t\tstep_key: text(\"step_key\").notNull(),\n\t\teffect_id: text(\"effect_id\").notNull(),\n\t\tpayload_digest: text(\"payload_digest\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"pending\"),\n\t\tattempt_count: integer(\"attempt_count\").notNull().default(0),\n\t\tstarted_at: text(\"started_at\"),\n\t\tcompleted_at: text(\"completed_at\"),\n\t\tlast_attempt_at: text(\"last_attempt_at\"),\n\t\tsafe_error_code: text(\"safe_error_code\"),\n\t\terror_at: text(\"error_at\"),\n\t\tlease_owner: text(\"lease_owner\"),\n\t\tlease_acquired_at: text(\"lease_acquired_at\"),\n\t\tlease_expires_at: text(\"lease_expires_at\"),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.canonical_project_identity, table.generation, table.step_key],\n\t\t}),\n\t\tuniqueIndex(\"idx_recipient_policy_reconciliation_steps_effect\").on(table.effect_id),\n\t\tindex(\"idx_recipient_policy_reconciliation_steps_status\").on(\n\t\t\ttable.canonical_project_identity,\n\t\t\ttable.status,\n\t\t),\n\t\tindex(\"idx_recipient_policy_reconciliation_steps_pending_refresh\")\n\t\t\t.on(table.canonical_project_identity, table.generation, table.step_key)\n\t\t\t.where(\n\t\t\t\tsql`${table.status} IN ('pending', 'running', 'failed') AND ${table.step_key} GLOB 'refresh-after-revocations-v2:*'`,\n\t\t\t),\n\t],\n);\n\nexport type RecipientPolicyReconciliationStep =\n\ttypeof recipientPolicyReconciliationSteps.$inferSelect;\nexport type NewRecipientPolicyReconciliationStep =\n\ttypeof recipientPolicyReconciliationSteps.$inferInsert;\n\nexport const recipientPolicyDenyOverlays = sqliteTable(\n\t\"recipient_policy_deny_overlays\",\n\t{\n\t\tcanonical_project_identity: text(\"canonical_project_identity\").notNull(),\n\t\tscope_id: text(\"scope_id\").notNull(),\n\t\tdevice_id: text(\"device_id\").notNull(),\n\t\tgeneration: integer(\"generation\").notNull(),\n\t\treason_code: text(\"reason_code\").notNull(),\n\t\tcreated_at: text(\"created_at\").notNull(),\n\t\tupdated_at: text(\"updated_at\").notNull(),\n\t},\n\t(table) => [\n\t\tprimaryKey({\n\t\t\tcolumns: [table.canonical_project_identity, table.scope_id, table.device_id],\n\t\t}),\n\t\tindex(\"idx_recipient_policy_deny_overlays_scope_device\").on(table.scope_id, table.device_id),\n\t],\n);\n\nexport type RecipientPolicyDenyOverlay = typeof recipientPolicyDenyOverlays.$inferSelect;\nexport type NewRecipientPolicyDenyOverlay = typeof recipientPolicyDenyOverlays.$inferInsert;\n\nexport const schema = {\n\tdeviceIdentityBindingCommits,\n\tdeviceIdentityBindingAudit,\n\tsessions,\n\treplicationScopes,\n\tprojectScopeMappings,\n\tscopeMemberships,\n\tartifacts,\n\tmemoryItems,\n\tmemoryFileRefs,\n\tmemoryConceptRefs,\n\tusageEvents,\n\tretrievalAttempts,\n\tretrievalExposures,\n\toutcomeEvidence,\n\tattributionAssessments,\n\tattributionAssessmentEvidence,\n\trawEvents,\n\trawEventSessions,\n\topencodeSessions,\n\tpiImportState,\n\trawEventFlushBatches,\n\tuserPrompts,\n\tsessionSummaries,\n\treplicationOps,\n\treplicationCursors,\n\treplicationCursorsV2,\n\tsyncPeers,\n\tsyncNonces,\n\tsyncDevice,\n\tsyncAttempts,\n\tsyncScopeRejections,\n\tsyncDaemonState,\n\tsyncResetState,\n\tsyncResetStateV2,\n\tsyncRetentionStateV2,\n\trawEventIngestSamples,\n\trawEventIngestStats,\n\tcoordinatorGroupPreferences,\n\tactors,\n\trecipientPolicyReviewResolutions,\n\tcoordinatorEnrollmentReconciliationIssues,\n\tpolicyTeams,\n\tpolicyTeamMemberships,\n\tpolicyTeamDeviceDecisions,\n\tidentityDevices,\n\tprojectRecipients,\n\tlegacyTeamSetupDrafts,\n\tlegacyTeamSetupCompletions,\n\tlegacyTeamSetupDraftDevices,\n\tlegacyTeamSetupDraftProjects,\n\trecipientManagedProjectProjections,\n\trecipientPolicyAuthorityStates,\n\trecipientPolicyReconciliationSteps,\n\trecipientPolicyDenyOverlays,\n};\n","/**\n * Device identity management for the codemem sync system.\n *\n * Handles Ed25519 keypair generation, fingerprinting, and optional\n * keychain storage. Ported from codemem/sync_identity.py.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { connect as connectDb, resolveDbPath } from \"./db.js\";\nimport { codememHomeDir } from \"./home.js\";\nimport { adoptLocalCapture, hasPendingLocalCapture } from \"./memory-local-capture.js\";\nimport { readCodememConfigFile } from \"./observer-config.js\";\nimport * as schema from \"./schema.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst PRIVATE_KEY_NAME = \"device.key\";\nconst PUBLIC_KEY_NAME = \"device.key.pub\";\nconst KEYCHAIN_SERVICE = \"codemem-sync\";\n\nfunction defaultKeysDir(): string {\n\treturn join(codememHomeDir(), \".config\", \"codemem\", \"keys\");\n}\n\n// ---------------------------------------------------------------------------\n// Fingerprint\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Key store mode\n// ---------------------------------------------------------------------------\n\nfunction keyStoreMode(): \"file\" | \"keychain\" {\n\tconst env = process.env.CODEMEM_SYNC_KEY_STORE?.toLowerCase();\n\tif (env === \"keychain\") return \"keychain\";\n\treturn \"file\";\n}\n\n// ---------------------------------------------------------------------------\n// CLI availability helpers\n// ---------------------------------------------------------------------------\n\nfunction cliAvailable(cmd: string): boolean {\n\ttry {\n\t\texecFileSync(\"which\", [cmd], { stdio: \"pipe\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Keychain storage (platform-specific)\n// ---------------------------------------------------------------------------\n\nfunction warnKeychainLimitations(): void {\n\tif (process.platform !== \"darwin\") return;\n\tif (keyStoreMode() !== \"keychain\") return;\n\tif (process.env.CODEMEM_SYNC_KEYCHAIN_WARN === \"0\") return;\n\tconsole.warn(\n\t\t\"[codemem] keychain storage on macOS uses the `security` CLI and may expose the key in process arguments.\",\n\t);\n}\n\n/** Store a private key in the OS keychain. Returns true on success. */\nexport function storePrivateKeyKeychain(privateKey: Buffer, deviceId: string): boolean {\n\tif (process.platform === \"linux\") {\n\t\tif (!cliAvailable(\"secret-tool\")) return false;\n\t\ttry {\n\t\t\texecFileSync(\n\t\t\t\t\"secret-tool\",\n\t\t\t\t[\"store\", \"--label\", \"codemem sync key\", \"service\", KEYCHAIN_SERVICE, \"account\", deviceId],\n\t\t\t\t{ input: privateKey, stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (process.platform === \"darwin\") {\n\t\tif (!cliAvailable(\"security\")) return false;\n\t\ttry {\n\t\t\texecFileSync(\n\t\t\t\t\"security\",\n\t\t\t\t[\n\t\t\t\t\t\"add-generic-password\",\n\t\t\t\t\t\"-a\",\n\t\t\t\t\tdeviceId,\n\t\t\t\t\t\"-s\",\n\t\t\t\t\tKEYCHAIN_SERVICE,\n\t\t\t\t\t\"-w\",\n\t\t\t\t\tprivateKey.toString(\"utf-8\"),\n\t\t\t\t\t\"-U\",\n\t\t\t\t],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Load a private key from the OS keychain. Returns null if unavailable. */\nexport function loadPrivateKeyKeychain(deviceId: string): Buffer | null {\n\tif (process.platform === \"linux\") {\n\t\tif (!cliAvailable(\"secret-tool\")) return null;\n\t\ttry {\n\t\t\tconst out = execFileSync(\n\t\t\t\t\"secret-tool\",\n\t\t\t\t[\"lookup\", \"service\", KEYCHAIN_SERVICE, \"account\", deviceId],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn Buffer.from(out);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (process.platform === \"darwin\") {\n\t\tif (!cliAvailable(\"security\")) return null;\n\t\ttry {\n\t\t\tconst out = execFileSync(\n\t\t\t\t\"security\",\n\t\t\t\t[\"find-generic-password\", \"-a\", deviceId, \"-s\", KEYCHAIN_SERVICE, \"-w\"],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn Buffer.from(out);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Key path resolution\n// ---------------------------------------------------------------------------\n\n/** Resolve private and public key file paths. */\nexport function resolveKeyPaths(keysDir?: string): [string, string] {\n\tconst dir = keysDir ?? defaultKeysDir();\n\treturn [join(dir, PRIVATE_KEY_NAME), join(dir, PUBLIC_KEY_NAME)];\n}\n\n// ---------------------------------------------------------------------------\n// Key file I/O\n// ---------------------------------------------------------------------------\n\n/** Read the public key from disk. Returns null if missing or empty. */\nexport function loadPublicKey(keysDir?: string): string | null {\n\tconst [, publicPath] = resolveKeyPaths(keysDir);\n\tif (!existsSync(publicPath)) return null;\n\tconst content = readFileSync(publicPath, \"utf-8\").trim();\n\treturn content || null;\n}\n\n/**\n * Read the private key from disk with keychain fallback. When dbPath identifies an\n * enrolled device, only a key matching that stored identity is returned.\n */\nexport function loadPrivateKey(\n\tkeysDir?: string,\n\tdbPath?: string,\n\tdeviceId?: string,\n): Buffer | null {\n\tconst storedIdentity = dbPath === undefined ? null : loadStoredDeviceIdentity(dbPath);\n\treturn loadPrivateKeyForIdentity(keysDir, deviceId, storedIdentity, () =>\n\t\tdbPath === undefined && !deviceId ? loadStoredDeviceIdentity() : storedIdentity,\n\t);\n}\n\nfunction loadPrivateKeyForIdentity(\n\tkeysDir: string | undefined,\n\tdeviceId: string | undefined,\n\tstoredIdentity: StoredDeviceIdentity | null,\n\tkeychainIdentity: () => StoredDeviceIdentity | null,\n): Buffer | null {\n\tconst [privatePath] = resolveKeyPaths(keysDir);\n\tconst privateKeyFile = readPrivateKeyFile(privatePath);\n\tconst privateKeyFromFile = isUsableEd25519PrivateKey(privateKeyFile.value)\n\t\t? privateKeyFile.value\n\t\t: null;\n\tif (storedIdentity && deviceId && storedIdentity.deviceId !== deviceId) return null;\n\tif (\n\t\tprivateKeyFromFile &&\n\t\t(!storedIdentity || privateKeyMatchesStoredIdentity(privateKeyFromFile, storedIdentity))\n\t) {\n\t\treturn privateKeyFromFile;\n\t}\n\tif (keyStoreMode() === \"keychain\") {\n\t\tconst identity = keychainIdentity();\n\t\tconst resolvedDeviceId = deviceId ?? identity?.deviceId;\n\t\tif (resolvedDeviceId) {\n\t\t\tconst keychainValue = loadPrivateKeyKeychain(resolvedDeviceId);\n\t\t\tif (\n\t\t\t\tisUsableEd25519PrivateKey(keychainValue) &&\n\t\t\t\t(!identity || privateKeyMatchesStoredIdentity(keychainValue, identity))\n\t\t\t) {\n\t\t\t\treturn keychainValue;\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\ninterface StoredDeviceIdentity {\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\n/** Read-only counterpart of signing-key selection, using the caller's connection.\n * Derives public bytes from the actual private key; never generates or repairs keys. */\nexport function loadRuntimeSigningPublicKey(\n\tdb: Database,\n\toptions: { deviceId: string; keysDir?: string },\n): string | null {\n\ttry {\n\t\tconst rows = db\n\t\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t\t.all() as Array<{ device_id: string; public_key: string; fingerprint: string }>;\n\t\tconst row = rows[0];\n\t\tif (rows.length !== 1 || !row || row.device_id !== options.deviceId) return null;\n\t\tconst identity = {\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t};\n\t\tconst privateKey = loadPrivateKeyForIdentity(\n\t\t\toptions.keysDir,\n\t\t\toptions.deviceId,\n\t\t\tidentity,\n\t\t\t() => identity,\n\t\t);\n\t\treturn privateKey ? derivePublicKey(privateKey) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Load the enrolled identity from the database for identity-aware key selection. */\nfunction loadStoredDeviceIdentity(dbPath?: string): StoredDeviceIdentity | null {\n\tconst path = resolveDbPath(dbPath);\n\tif (!existsSync(path)) return null;\n\tconst conn = connectDb(path);\n\ttry {\n\t\tconst d = drizzle(conn, { schema });\n\t\tconst row = d\n\t\t\t.select({\n\t\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\t\tpublic_key: schema.syncDevice.public_key,\n\t\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t\t})\n\t\t\t.from(schema.syncDevice)\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t};\n\t} finally {\n\t\tconn.close();\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Key generation & validation\n// ---------------------------------------------------------------------------\n\nfunction canonicalEd25519PublicKey(publicKey: string): string | null {\n\tconst [keyType, keyData] = publicKey.trim().split(/\\s+/);\n\tif (keyType !== \"ssh-ed25519\" || !keyData) return null;\n\treturn `${keyType} ${keyData}`;\n}\n\nfunction publicKeyLooksValid(publicKey: string): boolean {\n\treturn canonicalEd25519PublicKey(publicKey) !== null;\n}\n\nfunction backupInvalidKeyFile(path: string, stamp: string): void {\n\tif (!existsSync(path)) return;\n\tconst backupPath = join(dirname(path), `${basename(path)}.invalid-${stamp}`);\n\trenameSync(path, backupPath);\n}\n\n/**\n * Generate an Ed25519 keypair using Node's native crypto.\n * Stores private key as PEM (PKCS8), public key as SSH format for compatibility.\n */\nexport function generateKeypair(privatePath: string, publicPath: string): void {\n\tmkdirSync(dirname(privatePath), { recursive: true });\n\tif (existsSync(privatePath) && existsSync(publicPath)) return;\n\n\tif (existsSync(privatePath) && !existsSync(publicPath)) {\n\t\t// Private key exists but public is missing — derive public from private\n\t\ttry {\n\t\t\tconst privKeyObj = loadPrivateKeyObject(privatePath);\n\t\t\tconst pubKeyObj = createPublicKey(privKeyObj);\n\t\t\tconst sshPub = pubKeyObj.export({ type: \"spki\", format: \"der\" });\n\t\t\tconst sshPubStr = derToSshEd25519(sshPub);\n\t\t\tif (sshPubStr && publicKeyLooksValid(sshPubStr)) {\n\t\t\t\twriteFileSync(publicPath, `${sshPubStr}\\n`, { mode: 0o644 });\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Derivation failed — fall through to full regeneration with backup\n\t\t}\n\t\t// Back up the orphaned private key before regenerating\n\t\tconst stamp = new Date().toISOString().replace(/[:.]/g, \"\");\n\t\trenameSync(privatePath, `${privatePath}.orphan-${stamp}`);\n\t}\n\n\tconst { publicKey, privateKey } = generateKeyPairSync(\"ed25519\");\n\n\t// Export private key as PEM (PKCS8)\n\tconst privatePem = privateKey.export({ type: \"pkcs8\", format: \"pem\" }) as string;\n\twriteFileSync(privatePath, privatePem, { mode: 0o600 });\n\n\t// Export public key as SSH wire format: \"ssh-ed25519 <base64>\"\n\tconst pubDer = publicKey.export({ type: \"spki\", format: \"der\" });\n\tconst sshPub = derToSshEd25519(pubDer);\n\tif (!sshPub) {\n\t\tthrow new Error(\"failed to convert public key to SSH format\");\n\t}\n\twriteFileSync(publicPath, `${sshPub}\\n`, { mode: 0o644 });\n}\n\n/**\n * Convert a DER-encoded SPKI Ed25519 public key to SSH wire format.\n * The last 32 bytes of the DER are the raw Ed25519 public key.\n */\nfunction derToSshEd25519(spkiDer: Buffer): string | null {\n\t// Ed25519 SPKI DER is 44 bytes: 12-byte header + 32-byte key\n\tif (spkiDer.length !== 44) return null;\n\tconst rawKey = spkiDer.subarray(spkiDer.length - 32);\n\n\t// SSH wire format: string \"ssh-ed25519\" + string <32-byte key>\n\tconst keyType = Buffer.from(\"ssh-ed25519\");\n\tconst buf = Buffer.alloc(4 + keyType.length + 4 + rawKey.length);\n\tlet offset = 0;\n\tbuf.writeUInt32BE(keyType.length, offset);\n\toffset += 4;\n\tkeyType.copy(buf, offset);\n\toffset += keyType.length;\n\tbuf.writeUInt32BE(rawKey.length, offset);\n\toffset += 4;\n\trawKey.copy(buf, offset);\n\n\treturn `ssh-ed25519 ${buf.toString(\"base64\")}`;\n}\n\n/**\n * Load a private key that may be in OpenSSH format (existing keys) or\n * PKCS8 PEM format (newly generated keys). Node's createPrivateKey\n * handles both transparently.\n */\nfunction loadPrivateKeyObject(privatePath: string): ReturnType<typeof createPrivateKey> {\n\treturn loadPrivateKeyObjectFromBytes(readFileSync(privatePath));\n}\n\nfunction loadPrivateKeyObjectFromBytes(raw: Buffer): ReturnType<typeof createPrivateKey> {\n\t// Try PKCS8 PEM first (our generated format), then OpenSSH\n\ttry {\n\t\treturn createPrivateKey(raw);\n\t} catch {\n\t\treturn createPrivateKey({ key: raw, format: \"pem\", type: \"pkcs8\" });\n\t}\n}\n\nfunction derivePublicKey(privateKey: Buffer): string {\n\tconst privateKeyObject = loadPrivateKeyObjectFromBytes(privateKey);\n\tif (privateKeyObject.asymmetricKeyType !== \"ed25519\") {\n\t\tthrow new Error(\"private key is not Ed25519\");\n\t}\n\tconst publicKeyObject = createPublicKey(privateKeyObject);\n\tconst publicKeyDer = publicKeyObject.export({ type: \"spki\", format: \"der\" });\n\tconst publicKey = derToSshEd25519(publicKeyDer);\n\tif (!publicKey || !publicKeyLooksValid(publicKey)) {\n\t\tthrow new Error(\"failed to derive public key\");\n\t}\n\treturn publicKey;\n}\n\nfunction isUsableEd25519PrivateKey(privateKey: Buffer | null): privateKey is Buffer {\n\tif (!privateKey) return false;\n\ttry {\n\t\tderivePublicKey(privateKey);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ntype PrivateKeyFileRead =\n\t| { status: \"available\"; value: Buffer }\n\t| { status: \"missing\" | \"unreadable\"; value: null };\n\nfunction readPrivateKeyFile(privatePath: string): PrivateKeyFileRead {\n\ttry {\n\t\tif (!existsSync(privatePath)) return { status: \"missing\", value: null };\n\t\treturn { status: \"available\", value: readFileSync(privatePath) };\n\t} catch {\n\t\treturn { status: \"unreadable\", value: null };\n\t}\n}\n\nfunction privateKeyMatchesStoredIdentity(\n\tprivateKey: Buffer,\n\tidentity: StoredDeviceIdentity,\n): boolean {\n\tconst storedPublicKey = canonicalEd25519PublicKey(identity.publicKey);\n\tif (!storedPublicKey || fingerprintPublicKey(identity.publicKey) !== identity.fingerprint) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn canonicalEd25519PublicKey(derivePublicKey(privateKey)) === storedPublicKey;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport type DeviceIdentityErrorCode =\n\t| \"device_identity_private_key_missing\"\n\t| \"device_identity_private_key_invalid\"\n\t| \"device_identity_key_mismatch\";\n\nexport class DeviceIdentityError extends Error {\n\treadonly code: DeviceIdentityErrorCode;\n\n\tconstructor(code: DeviceIdentityErrorCode, detail: string) {\n\t\tsuper(`${code}: ${detail}`);\n\t\tthis.name = \"DeviceIdentityError\";\n\t\tthis.code = code;\n\t}\n}\n\nfunction existingIdentityError(code: DeviceIdentityErrorCode, detail: string): DeviceIdentityError {\n\treturn new DeviceIdentityError(code, detail);\n}\n\n/** Validate that an existing keypair is consistent. */\nexport function validateExistingKeypair(privatePath: string, publicPath: string): boolean {\n\tif (!existsSync(privatePath) || !existsSync(publicPath)) return false;\n\tconst publicKey = readFileSync(publicPath, \"utf-8\").trim();\n\tif (!publicKey || !publicKeyLooksValid(publicKey)) return false;\n\ttry {\n\t\tconst privKeyObj = loadPrivateKeyObject(privatePath);\n\t\tconst pubKeyObj = createPublicKey(privKeyObj);\n\t\tconst pubDer = pubKeyObj.export({ type: \"spki\", format: \"der\" });\n\t\tconst derived = derToSshEd25519(pubDer);\n\t\tif (!derived || !publicKeyLooksValid(derived)) return false;\n\t\t// Auto-fix mismatched public key file\n\t\tif (canonicalEd25519PublicKey(derived) !== canonicalEd25519PublicKey(publicKey)) {\n\t\t\twriteFileSync(publicPath, `${derived}\\n`, \"utf-8\");\n\t\t}\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Main entry: ensure device identity\n// ---------------------------------------------------------------------------\n\nexport interface EnsureDeviceIdentityOptions {\n\tkeysDir?: string;\n\tdeviceId?: string;\n}\n\n/** Device identity ensure boundary; constructors and ordinary memory reads do not associate. */\nfunction adoptPendingCaptureForEnsuredIdentity(\n\tdb: Database,\n\tdeviceId: string,\n\tpublicKey: string,\n): void {\n\tif (!hasPendingLocalCapture(db)) return;\n\tconst configuredDevice = process.env.CODEMEM_DEVICE_ID?.trim();\n\tif (configuredDevice && configuredDevice !== deviceId) return;\n\tconst config = readCodememConfigFile();\n\tlet configuredActor = typeof config.actor_id === \"string\" ? config.actor_id.trim() : undefined;\n\tif (Object.hasOwn(process.env, \"CODEMEM_ACTOR_ID\"))\n\t\tconfiguredActor = process.env.CODEMEM_ACTOR_ID?.trim();\n\ttry {\n\t\tdb.transaction(() =>\n\t\t\tadoptLocalCapture(db, deviceId, {\n\t\t\t\texpectedPublicKey: publicKey,\n\t\t\t\tactorId: configuredActor || `local:${deviceId}`,\n\t\t\t\truntimeDeviceId: deviceId,\n\t\t\t}),\n\t\t).immediate();\n\t} catch (error) {\n\t\t// Only the plain actor conflict is nonfatal; SQLite/key failures propagate.\n\t\tif (\n\t\t\t!(error instanceof Error) ||\n\t\t\terror.constructor !== Error ||\n\t\t\terror.message !== \"device_adoption_actor_conflict\"\n\t\t)\n\t\t\tthrow error;\n\t}\n}\n\n/**\n * Ensure this device has a keypair and a row in the sync_device table.\n *\n * Returns [deviceId, fingerprint]. Creates keys and DB row if missing,\n * validates and repairs if existing.\n */\nexport function ensureDeviceIdentity(\n\tdb: Database,\n\toptions?: EnsureDeviceIdentityOptions,\n): [string, string] {\n\tconst keysDir = options?.keysDir ?? defaultKeysDir();\n\tconst [privatePath, publicPath] = resolveKeyPaths(keysDir);\n\twarnKeychainLimitations();\n\n\t// Check for existing device row\n\tconst d = drizzle(db, { schema });\n\tconst row = deviceRowForEnsure(db);\n\tconst existingDeviceId = row?.device_id ?? \"\";\n\tconst existingPublicKey = row?.public_key ?? \"\";\n\tconst existingFingerprint = row?.fingerprint ?? \"\";\n\n\tif (existingDeviceId) {\n\t\tconst privateKeyFile = readPrivateKeyFile(privatePath);\n\t\tconst validPrivateKeyFromFile = isUsableEd25519PrivateKey(privateKeyFile.value)\n\t\t\t? privateKeyFile.value\n\t\t\t: null;\n\t\tconst storedIdentity: StoredDeviceIdentity = {\n\t\t\tdeviceId: existingDeviceId,\n\t\t\tpublicKey: existingPublicKey,\n\t\t\tfingerprint: existingFingerprint,\n\t\t};\n\n\t\tconst fileMatchesStoredIdentity =\n\t\t\tvalidPrivateKeyFromFile !== null &&\n\t\t\tprivateKeyMatchesStoredIdentity(validPrivateKeyFromFile, storedIdentity);\n\t\tconst privateKeyFromKeychain =\n\t\t\t!fileMatchesStoredIdentity && keyStoreMode() === \"keychain\"\n\t\t\t\t? loadPrivateKeyKeychain(existingDeviceId)\n\t\t\t\t: null;\n\t\tconst validPrivateKeyFromKeychain = isUsableEd25519PrivateKey(privateKeyFromKeychain)\n\t\t\t? privateKeyFromKeychain\n\t\t\t: null;\n\t\tconst keychainMatchesStoredIdentity =\n\t\t\tvalidPrivateKeyFromKeychain !== null &&\n\t\t\tprivateKeyMatchesStoredIdentity(validPrivateKeyFromKeychain, storedIdentity);\n\t\tconst privateKey = fileMatchesStoredIdentity\n\t\t\t? validPrivateKeyFromFile\n\t\t\t: keychainMatchesStoredIdentity\n\t\t\t\t? validPrivateKeyFromKeychain\n\t\t\t\t: null;\n\t\tif (!privateKey) {\n\t\t\tif (validPrivateKeyFromFile || validPrivateKeyFromKeychain) {\n\t\t\t\tthrow existingIdentityError(\n\t\t\t\t\t\"device_identity_key_mismatch\",\n\t\t\t\t\t\"the restored private key does not match the peer identity stored in the database\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow existingIdentityError(\n\t\t\t\tprivateKeyFile.status !== \"missing\" || privateKeyFromKeychain\n\t\t\t\t\t? \"device_identity_private_key_invalid\"\n\t\t\t\t\t: \"device_identity_private_key_missing\",\n\t\t\t\tprivateKeyFile.status !== \"missing\" || privateKeyFromKeychain\n\t\t\t\t\t? \"the restored private key is unreadable or unsupported; restore the original Ed25519 key material\"\n\t\t\t\t\t: \"the database contains an existing peer identity but its private key is unavailable; restore the original key material with the database\",\n\t\t\t);\n\t\t}\n\n\t\tlet derivedPublicKey: string;\n\t\ttry {\n\t\t\tderivedPublicKey = derivePublicKey(privateKey);\n\t\t} catch {\n\t\t\tthrow existingIdentityError(\n\t\t\t\t\"device_identity_private_key_invalid\",\n\t\t\t\t\"the restored private key is unreadable or unsupported; restore the original Ed25519 key material\",\n\t\t\t);\n\t\t}\n\t\tconst storedPublicKey = canonicalEd25519PublicKey(existingPublicKey);\n\t\tif (\n\t\t\t!storedPublicKey ||\n\t\t\tcanonicalEd25519PublicKey(derivedPublicKey) !== storedPublicKey ||\n\t\t\tfingerprintPublicKey(existingPublicKey) !== existingFingerprint\n\t\t) {\n\t\t\tthrow existingIdentityError(\n\t\t\t\t\"device_identity_key_mismatch\",\n\t\t\t\t\"the restored private key does not match the peer identity stored in the database\",\n\t\t\t);\n\t\t}\n\n\t\tconst publicKeyOnDisk = loadPublicKey(keysDir);\n\t\tif (publicKeyOnDisk !== existingPublicKey) {\n\t\t\tmkdirSync(dirname(publicPath), { recursive: true });\n\t\t\twriteFileSync(publicPath, `${existingPublicKey}\\n`, { mode: 0o644 });\n\t\t}\n\t\tif (keyStoreMode() === \"keychain\" && fileMatchesStoredIdentity) {\n\t\t\tstorePrivateKeyKeychain(privateKey, existingDeviceId);\n\t\t}\n\t\tadoptPendingCaptureForEnsuredIdentity(db, existingDeviceId, derivedPublicKey);\n\t\treturn [existingDeviceId, existingFingerprint];\n\t}\n\n\t// Validate or regenerate keys\n\tlet keysReady = existsSync(privatePath) && existsSync(publicPath);\n\tif (keysReady && !validateExistingKeypair(privatePath, publicPath)) {\n\t\tconst stamp = new Date()\n\t\t\t.toISOString()\n\t\t\t.replace(/[-:T.Z]/g, \"\")\n\t\t\t.slice(0, 20);\n\t\tbackupInvalidKeyFile(privatePath, stamp);\n\t\tbackupInvalidKeyFile(publicPath, stamp);\n\t\tkeysReady = false;\n\t}\n\tif (!keysReady) {\n\t\tgenerateKeypair(privatePath, publicPath);\n\t}\n\n\tconst publicKey = readFileSync(publicPath, \"utf-8\").trim();\n\tif (!publicKey) {\n\t\tthrow new Error(\"public key missing\");\n\t}\n\tconst fingerprint = fingerprintPublicKey(publicKey);\n\tconst now = new Date().toISOString();\n\n\t// Insert new device row\n\tconst resolvedDeviceId = options?.deviceId ?? randomUUID();\n\tdb.transaction(() => {\n\t\td.insert(schema.syncDevice)\n\t\t\t.values({ device_id: resolvedDeviceId, public_key: publicKey, fingerprint, created_at: now })\n\t\t\t.run();\n\t\tadoptPendingCaptureForEnsuredIdentity(db, resolvedDeviceId, publicKey);\n\t})();\n\tif (keyStoreMode() === \"keychain\") {\n\t\tconst privateKey = existsSync(privatePath) ? readFileSync(privatePath) : null;\n\t\tif (privateKey) {\n\t\t\tstorePrivateKeyKeychain(privateKey, resolvedDeviceId);\n\t\t}\n\t}\n\treturn [resolvedDeviceId, fingerprint];\n}\n\nfunction deviceRowForEnsure(db: Database) {\n\treturn drizzle(db, { schema })\n\t\t.select({\n\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\tpublic_key: schema.syncDevice.public_key,\n\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t})\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, lstatSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport type { Database } from \"./db.js\";\n\nexport interface GitRepositoryIdentity {\n\tidentity: string;\n\troot: string | null;\n\tsource: \"git_remote\" | \"git_common_dir\";\n}\n\nexport const REPOSITORY_IDENTITY_METADATA_KEY = \"codemem_repository_identity\";\n\n/**\n * SQL expression for the recorded repository identity in a metadata JSON\n * column, or NULL. Read queries select this instead of the whole column: few\n * sessions record the key, and the substring check skips JSON parsing for the\n * rest.\n */\nexport function repositoryIdentitySql(column: string): string {\n\tconst path = `'$.${REPOSITORY_IDENTITY_METADATA_KEY}'`;\n\treturn `CASE\n\t\tWHEN instr(${column}, '${REPOSITORY_IDENTITY_METADATA_KEY}') = 0 THEN NULL\n\t\tWHEN json_valid(${column}) THEN\n\t\t\tCASE WHEN json_type(${column}, ${path}) = 'text' THEN json_extract(${column}, ${path}) END\n\tEND`;\n}\n\n/**\n * Recorded repository identities keyed by session id, for the few sessions\n * that recorded one. Lets per-memory queries join by session id instead of\n * evaluating session metadata once per memory row.\n */\nexport function recordedRepositoryIdentitiesBySession(db: Database): Map<number, string> {\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`SELECT id, ${repositoryIdentitySql(\"metadata_json\")} AS repository_identity\n\t\t\t FROM sessions\n\t\t\t WHERE instr(metadata_json, '${REPOSITORY_IDENTITY_METADATA_KEY}') > 0`,\n\t\t)\n\t\t.all() as Array<{ id: number; repository_identity: string | null }>;\n\tconst identities = new Map<number, string>();\n\tfor (const row of rows) {\n\t\tconst identity = row.repository_identity?.trim();\n\t\tif (identity) identities.set(row.id, identity);\n\t}\n\treturn identities;\n}\n\nexport function repositoryIdentityFromMetadata(\n\tmetadataJson: string | null | undefined,\n): string | null {\n\tif (!metadataJson) return null;\n\ttry {\n\t\tconst metadata = JSON.parse(metadataJson) as Record<string, unknown>;\n\t\tconst value = metadata[REPOSITORY_IDENTITY_METADATA_KEY];\n\t\treturn typeof value === \"string\" && value.trim() ? value.trim() : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction normalizePathLike(value: string): string {\n\treturn value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\") || value.trim();\n}\n\nfunction normalizeRemoteIdentity(value: string, repositoryRoot: string): string | null {\n\tconst remote = value.trim();\n\tif (!remote) return null;\n\tif (/^[a-z][a-z0-9+.-]*:\\/\\//iu.test(remote)) {\n\t\ttry {\n\t\t\tconst url = new URL(remote);\n\t\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") url.username = \"\";\n\t\t\turl.password = \"\";\n\t\t\turl.search = \"\";\n\t\t\turl.hash = \"\";\n\t\t\treturn normalizePathLike(url.toString());\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (/^[A-Za-z]:[\\\\/]/u.test(remote) || !remote.includes(\":\")) {\n\t\treturn normalizePathLike(resolve(repositoryRoot, remote));\n\t}\n\tconst scpRemote = remote.match(/^((?:[^/@:]+@)?[^/:]+):(.+)$/u);\n\tif (!scpRemote?.[1] || !scpRemote[2]) return null;\n\treturn `${scpRemote[1]}:${normalizePathLike(scpRemote[2])}`;\n}\n\nexport function projectBasename(value: string): string {\n\tlet normalized = value.replaceAll(\"\\\\\", \"/\");\n\twhile (normalized.endsWith(\"/\")) normalized = normalized.slice(0, -1);\n\tif (!normalized) return \"\";\n\tconst parts = normalized.split(\"/\");\n\treturn parts[parts.length - 1] ?? \"\";\n}\n\nfunction escapeSqlLikePattern(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n\nexport function projectColumnClause(\n\tcolumnExpr: string,\n\tproject: string,\n): { clause: string; params: string[] } {\n\tconst trimmed = project.trim();\n\tif (!trimmed) return { clause: \"\", params: [] };\n\tconst value = /[\\\\/]/.test(trimmed) ? projectBasename(trimmed) : trimmed;\n\tif (!value) return { clause: \"\", params: [] };\n\tconst escaped = escapeSqlLikePattern(value);\n\treturn {\n\t\tclause: `(${columnExpr} = ? OR ${columnExpr} LIKE ? ESCAPE '\\\\' OR ${columnExpr} LIKE ? ESCAPE '\\\\')`,\n\t\tparams: [value, `%/${escaped}`, `%\\\\${escaped}`],\n\t};\n}\n\nexport function projectClause(project: string): { clause: string; params: string[] } {\n\treturn projectColumnClause(\"sessions.project\", project);\n}\n\nexport function projectMatchesFilter(\n\tprojectFilter: string | null | undefined,\n\titemProject: string | null | undefined,\n): boolean {\n\tif (!projectFilter) return true;\n\tif (!itemProject) return false;\n\tconst normalizedFilter = projectFilter.trim().replaceAll(\"\\\\\", \"/\");\n\tif (!normalizedFilter) return true;\n\tconst filterValue = normalizedFilter.includes(\"/\")\n\t\t? projectBasename(normalizedFilter)\n\t\t: normalizedFilter;\n\tconst normalizedProject = itemProject.replaceAll(\"\\\\\", \"/\");\n\treturn normalizedProject === filterValue || normalizedProject.endsWith(`/${filterValue}`);\n}\n\nfunction findGitAnchor(startCwd: string): string | null {\n\tlet current = resolve(startCwd);\n\twhile (true) {\n\t\tconst gitPath = resolve(current, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\tconst gitDirectory = gitDirectoryFromMarker(current, gitPath);\n\t\t\tif (!gitDirectory) return current;\n\t\t\tconst layout = gitDirectoryLayout(gitDirectory);\n\t\t\treturn layout.isLinkedWorktree && basename(layout.commonDirectory) === \".git\"\n\t\t\t\t? dirname(layout.commonDirectory)\n\t\t\t\t: current;\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return null;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction gitDirectoryFromMarker(repositoryRoot: string, gitPath: string): string | null {\n\ttry {\n\t\tconst pathInfo = lstatSync(gitPath);\n\t\tif (pathInfo.isDirectory()) return gitPath;\n\t\tif (pathInfo.isSymbolicLink() && statSync(gitPath).isDirectory()) return realpathSync(gitPath);\n\t\tconst text = readFileSync(gitPath, \"utf8\").trim();\n\t\tif (!text.startsWith(\"gitdir:\")) return null;\n\t\treturn resolve(repositoryRoot, text.slice(\"gitdir:\".length).trim());\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction gitDirectoryLayout(gitDirectory: string): {\n\tcommonDirectory: string;\n\tisLinkedWorktree: boolean;\n} {\n\ttry {\n\t\tconst marker = readFileSync(resolve(gitDirectory, \"commondir\"), \"utf8\").trim();\n\t\tif (marker) return { commonDirectory: resolve(gitDirectory, marker), isLinkedWorktree: true };\n\t} catch {\n\t\t// Normal repositories use their own .git directory as the common directory.\n\t}\n\treturn { commonDirectory: gitDirectory, isLinkedWorktree: false };\n}\n\nfunction originRemote(commonDirectory: string, repositoryRoot: string): string | null {\n\ttry {\n\t\tconst value = execFileSync(\n\t\t\t\"git\",\n\t\t\t[\n\t\t\t\t\"config\",\n\t\t\t\t\"--file\",\n\t\t\t\tresolve(commonDirectory, \"config\"),\n\t\t\t\t\"--includes\",\n\t\t\t\t\"--get\",\n\t\t\t\t\"remote.origin.url\",\n\t\t\t],\n\t\t\t{ encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"], timeout: 2_000 },\n\t\t).trim();\n\t\treturn normalizeRemoteIdentity(value, repositoryRoot);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Resolve a location-independent identity for a live Git repository or linked worktree. */\nexport function resolveGitRepositoryIdentity(cwd: string): GitRepositoryIdentity | null {\n\tlet current = resolve(cwd);\n\twhile (true) {\n\t\tconst gitPath = resolve(current, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\tconst gitDirectory = gitDirectoryFromMarker(current, gitPath);\n\t\t\tif (!gitDirectory) return null;\n\t\t\tconst layout = gitDirectoryLayout(gitDirectory);\n\t\t\tconst { commonDirectory } = layout;\n\t\t\tconst normalizedCommonDirectory = normalizePathLike(commonDirectory);\n\t\t\tconst root =\n\t\t\t\tlayout.isLinkedWorktree && basename(normalizedCommonDirectory) === \".git\"\n\t\t\t\t\t? dirname(commonDirectory)\n\t\t\t\t\t: current;\n\t\t\tconst remote = originRemote(commonDirectory, root);\n\t\t\tif (remote) return { identity: remote, root, source: \"git_remote\" };\n\t\t\treturn {\n\t\t\t\tidentity: normalizedCommonDirectory,\n\t\t\t\troot,\n\t\t\t\tsource: \"git_common_dir\",\n\t\t\t};\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return null;\n\t\tcurrent = parent;\n\t}\n}\n\nexport function resolveProject(cwd: string, override?: string | null): string | null {\n\tif (override != null) {\n\t\tconst trimmed = override.trim();\n\t\treturn trimmed || null;\n\t}\n\tconst gitAnchor = findGitAnchor(cwd);\n\tif (gitAnchor) {\n\t\treturn basename(gitAnchor);\n\t}\n\treturn basename(resolve(cwd));\n}\n\n/**\n * Resolve the working-tree root for a directory by walking up to the nearest\n * `.git` marker and returning the directory that contains it. Returns null when\n * no repository is found.\n *\n * Unlike `resolveProject` (which follows a linked worktree's gitdir back to the\n * primary checkout for a stable project name), this returns the *current*\n * worktree root so repo-root files like AGENTS.md are read from the worktree\n * actually being used, not another checkout.\n */\nexport function resolveProjectRoot(cwd: string): string | null {\n\tlet current = resolve(cwd);\n\twhile (true) {\n\t\tif (existsSync(resolve(current, \".git\"))) return current;\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return null;\n\t\tcurrent = parent;\n\t}\n}\n","import type { Database } from \"better-sqlite3\";\nimport { AUTH_BROWSER_TXN_SCHEMA_SQL } from \"./coordinator-auth-browser-transaction-contract.js\";\n\nconst TABLE = \"coordinator_auth_browser_transactions\";\nconst REBUILT_TABLE = \"coordinator_auth_browser_transactions_owner_upgrade\";\nconst [tableSql, remainder = \"\"] = AUTH_BROWSER_TXN_SCHEMA_SQL.split(\n\t\"CREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created\",\n);\nconst indexSql =\n\t`CREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created${remainder}`.split(\n\t\t\"CREATE TABLE IF NOT EXISTS coordinator_auth_signin_purge_floors\",\n\t)[0];\n\n/** Run only in a transaction: preserves every old column and all uniqueness constraints. */\nexport const AUTH_BROWSER_OWNER_PURPOSE_UPGRADE_SQL = `\n${tableSql?.replace(TABLE, REBUILT_TABLE)}\nINSERT INTO ${REBUILT_TABLE} SELECT * FROM ${TABLE};\nDROP TABLE ${TABLE};\nALTER TABLE ${REBUILT_TABLE} RENAME TO ${TABLE};\n${indexSql}\n`;\n\n/** Atomic upgrade preserves same-table indexes/triggers; foreign dependents can abort it. */\nexport function upgradeAuthBrowserOwnerPurposeSchema(db: Database): void {\n\tconst present = db\n\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(TABLE) as { sql: string } | undefined;\n\tif (!present || present.sql.includes(\"'owner_enroll'\")) return;\n\t// Recheck after reserving the write lock in case another connection upgraded first.\n\tdb.transaction(() => {\n\t\tconst table = db\n\t\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t\t.get(TABLE) as { sql: string } | undefined;\n\t\tif (!table || table.sql.includes(\"'owner_enroll'\")) return;\n\t\tconst objects = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT name, sql FROM sqlite_master WHERE tbl_name = ? AND type IN ('index','trigger') AND sql IS NOT NULL\",\n\t\t\t)\n\t\t\t.all(TABLE) as { name: string; sql: string }[];\n\t\tdb.exec(AUTH_BROWSER_OWNER_PURPOSE_UPGRADE_SQL);\n\t\tfor (const object of objects) {\n\t\t\tconst recreated = db.prepare(\"SELECT 1 FROM sqlite_master WHERE name = ?\").get(object.name);\n\t\t\tif (!recreated) db.exec(object.sql);\n\t\t}\n\t}).immediate();\n}\n","/** Inert ledger schema: only future verified, atomic enrollment writes may populate it. */\nexport const COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_ownership_bindings (\n device_id TEXT PRIMARY KEY NOT NULL CHECK(\n typeof(device_id) = 'text' AND length(trim(device_id)) > 0 AND instr(device_id, char(0)) = 0),\n key_id TEXT NOT NULL UNIQUE CHECK(\n typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^a-f0-9]*'\n AND instr(key_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK(\n typeof(identity_id) = 'text' AND length(trim(identity_id)) > 0 AND instr(identity_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK(\n typeof(coordinator_id) = 'text' AND length(trim(coordinator_id)) > 0 AND instr(coordinator_id, char(0)) = 0),\n binding_id TEXT NOT NULL UNIQUE CHECK(\n typeof(binding_id) = 'text' AND length(trim(binding_id)) > 0 AND instr(binding_id, char(0)) = 0),\n provenance TEXT NOT NULL CHECK(\n typeof(provenance) = 'text' AND provenance IN ('owner_enrollment', 'reviewed_legacy_migration')),\n source_ref TEXT NOT NULL CHECK(\n typeof(source_ref) = 'text' AND length(trim(source_ref)) > 0 AND instr(source_ref, char(0)) = 0),\n bound_at TEXT NOT NULL CHECK(\n typeof(bound_at) = 'text' AND length(trim(bound_at)) > 0 AND instr(bound_at, char(0)) = 0)\n);\n\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_insert_collision\nBEFORE INSERT ON coordinator_device_ownership_bindings\nWHEN EXISTS (\n SELECT 1 FROM coordinator_device_ownership_bindings\n WHERE rowid = NEW.rowid OR device_id = NEW.device_id OR key_id = NEW.key_id\n OR binding_id = NEW.binding_id\n)\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_collision');\nEND;\n\n-- An automatic rowid reads as -1 before insert; positive rowids keep that from matching a row.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_rowid\nAFTER INSERT ON coordinator_device_ownership_bindings\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_immutable_update\nBEFORE UPDATE ON coordinator_device_ownership_bindings\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_immutable');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_immutable_delete\nBEFORE DELETE ON coordinator_device_ownership_bindings\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_immutable');\nEND;\n`;\n\n/**\n * Earlier installs have a collision trigger that ignores rowid, so INSERT OR\n * REPLACE with an existing rowid could delete a binding without firing its\n * DELETE trigger. Returns the SQL that replaces it, or null when current.\n */\nexport function upgradeDeviceOwnershipTriggersSql(\n\texistingTriggerSql: string | null,\n): string | null {\n\tif (!existingTriggerSql || existingTriggerSql.includes(\"rowid = NEW.rowid\")) return null;\n\treturn \"DROP TRIGGER IF EXISTS coordinator_device_ownership_insert_collision;\";\n}\n","/**\n * BetterSqliteCoordinatorStore — SQLite-backed state for the coordinator relay server.\n *\n * The coordinator is a cloud relay that manages group membership, device\n * enrollment, presence, invites, and join requests for sync between devices.\n *\n * This store uses its OWN database (separate from the main codemem DB) and\n * owns its own schema — the TS side creates tables directly.\n *\n * Ported from codemem/coordinator_store.py.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Database as DatabaseType } from \"better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\tCONNECTION_SCHEMA_PRESENCE_SQL,\n\ttype ConnectionSchemaState,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { AccountLinkStatusOperations } from \"./coordinator-account-link-status.js\";\nimport { AccountOwnerTargetOperations } from \"./coordinator-account-owner-target.js\";\nimport {\n\tAUTH_ACCOUNT_PROFILE_SCHEMA_SQL,\n\tAuthAccountProfileOperations,\n\ttype CoordinatorAuthAccountProfileInput,\n} from \"./coordinator-auth-account-profile.js\";\nimport { upgradeAuthBrowserOwnerPurposeSchema } from \"./coordinator-auth-browser-schema-upgrade.js\";\nimport {\n\tAUTH_BROWSER_TXN_SCHEMA_SQL,\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\tCoordinatorAuthBrowserTransactions,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n} from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\tAUTH_CONTROLLER_ACTIVE_SQL,\n\tAUTH_CONTROLLER_CONFLICT_SQL,\n\tAUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_INSERT_SQL,\n\tAUTH_CONTROLLER_RETRY_ACTIVE_SQL,\n\tAUTH_CONTROLLER_RETRY_ELIGIBLE_SQL,\n\tAUTH_CONTROLLER_REVOKE_SQL,\n\tAUTH_CONTROLLER_SCHEMA_SQL,\n\tauthControllerAuthorityValues,\n\tauthControllerConflictValues,\n\tauthControllerInsertValues,\n\tauthControllerRetryActiveValues,\n\tauthControllerRetryEligibleValues,\n\tauthControllerRetryResult,\n\tauthControllerReviewSql,\n\tauthControllerSubjectOwnerConflictValues,\n\tauthControllerUnavailableResult,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerCreateResult,\n\ttype CoordinatorAuthControllerReviewInput,\n\ttype CoordinatorAuthControllerSubjectOwnerInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n\tisAuthControllerUniqueError,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistoryInput,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport { AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL } from \"./coordinator-auth-controller-owner.js\";\nimport { COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL } from \"./coordinator-auth-device-claim-schema.js\";\nimport {\n\ttype AuthLinkBackend,\n\tAuthLinkOperations,\n\ttype AuthLinkStatement,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_BROWSER_START_COLUMN_SQL,\n\tAUTH_LINK_SCHEMA_SQL,\n\ttype CoordinatorAuthLinkClaimInput,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkConfirmInput,\n\ttype CoordinatorAuthLinkCreateInput,\n\ttype CoordinatorAuthLinkFailInput,\n\ttype CoordinatorAuthLinkFinalizeInput,\n\ttype CoordinatorAuthLinkMaintenanceOptions,\n\ttype CoordinatorAuthLinkOidcInput,\n\ttype CoordinatorAuthLinkOptions,\n\ttype CoordinatorAuthLinkRequester,\n} from \"./coordinator-auth-link-contract.js\";\nimport { AUTH_LINK_PROFILE_SCHEMA_SQL } from \"./coordinator-auth-link-profile.js\";\nimport {\n\tAUTH_SCHEMA_READINESS_SQL,\n\tAUTH_SCHEMA_READY_COUNT,\n\tassertCoordinatorAuthSchema,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\twithCoordinatorAuthSchema,\n} from \"./coordinator-auth-schema.js\";\nimport { AuthSessionOperations } from \"./coordinator-auth-session.js\";\nimport {\n\tAUTH_SESSION_RETENTION_COLUMN_SQL,\n\tAUTH_SESSION_SCHEMA_SQL,\n\ttype CoordinatorAuthAccountSignInInput,\n\ttype CoordinatorAuthBoundLinkSessionRedeemInput,\n\ttype CoordinatorAuthLinkSessionRedeemInput,\n\ttype CoordinatorAuthSessionPurgeOptions,\n\ttype CoordinatorAuthSessionScope,\n} from \"./coordinator-auth-session-contract.js\";\nimport {\n\tBOOTSTRAP_AUTHORIZATION_SOURCE_SQL,\n\ttype BootstrapAuthorizationRow,\n\tbootstrapAuthorizationDecision,\n\tbootstrapAuthorizationResult,\n\tbootstrapAuthorizationSourceError,\n\tcaptureBootstrapAuthorizationInput,\n\trejectBootstrapAuthorization,\n} from \"./coordinator-bootstrap-grant-authorization.js\";\nimport {\n\tBOOTSTRAP_PARTICIPANT_SOURCE_SQL,\n\tBOOTSTRAP_PARTICIPANTS_REVOKED_SQL,\n\tBOOTSTRAP_RAW_INSERT_SQL,\n\ttype BootstrapParticipantSource,\n\tbootstrapRawInsertValues,\n\tcaptureBootstrapParticipantSource,\n} from \"./coordinator-bootstrap-grant-issuance.js\";\nimport {\n\tCOORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL,\n\tupgradeDeviceOwnershipTriggersSql,\n} from \"./coordinator-device-ownership-schema.js\";\nimport {\n\tCOORDINATOR_DEVICE_REBIND_SCHEMA_SQL,\n\treadDeviceRebindBackend,\n\trebindAttemptsNeedSelfBindRebuild,\n\trebuildRebindAttemptsForSelfBindSql,\n\tupgradePreReleaseRebindAttemptsSql,\n} from \"./coordinator-device-rebind-schema.js\";\nimport {\n\ttype CoordinatorCreateDeviceRevocationInput,\n\ttype CoordinatorListDeviceRevocationsInput,\n\ttype CoordinatorRecordAuthorizedNonceInput,\n\tDEVICE_REVOCATION_SCHEMA_SQL,\n\tDEVICE_REVOCATION_SUBJECT_EXISTS_SQL,\n\tDeviceRevocationOperations,\n} from \"./coordinator-device-revocation.js\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_OWNERSHIP_COLUMNS,\n\twithEnrollmentOwnership,\n} from \"./coordinator-enrollment-ownership.js\";\nimport {\n\ttype CoordinatorIdentityGroupGrant,\n\ttype CoordinatorIdentityGroupGrantIssueInput,\n\ttype CoordinatorIdentityGroupGrantIssueResult,\n\ttype CoordinatorIdentityGroupGrantRevokeInput,\n\ttype CoordinatorIdentityGroupGrantScope,\n\tcaptureIdentityGroupGrantInput,\n\tIDENTITY_GROUP_GRANT_INSERT_SQL,\n\tIDENTITY_GROUP_GRANT_LIST_SQL,\n\tIDENTITY_GROUP_GRANT_RETRY_SQL,\n\tIDENTITY_GROUP_GRANT_REVOKE_SQL,\n\tIDENTITY_GROUP_GRANT_SCHEMA_SQL,\n\tIDENTITY_GROUP_GRANT_SOURCE_SQL,\n} from \"./coordinator-identity-group-grant.js\";\nimport { joinReviewGuardEvidence } from \"./coordinator-join-review-guards.js\";\nimport {\n\tcaptureLegacyCompletionOwnerProof,\n\tlegacyCompletionOwnerProofSql,\n} from \"./coordinator-legacy-completion-owner-proof.js\";\nimport {\n\tassertLegacyDeviceScope,\n\tcaptureLegacyEnrollment,\n\tcaptureLegacyEnrollmentPublicKey,\n\tcaptureLegacyProjectInviteInput,\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_DEVICE_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_WRITE_SQL,\n\tlegacyDeviceAuthorizationFailure,\n\tlegacyDeviceDenial,\n\tlegacyDeviceWriteChanges,\n\tlegacyProjectInviteOwnershipEvidence,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport {\n\tLEGACY_OWNER_INPUT_SQL,\n\tLEGACY_OWNER_KEYS_SQL,\n\tLEGACY_OWNER_SOURCE_CURRENT_SQL,\n\tlegacyCompletionWriteResult,\n\tlegacyOwnerKeyMetadata,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionScopeBinding,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionScopeBindings,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\nimport {\n\ttype NegativeOwnerConsistency,\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerConsistency,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport { OwnerResolutionReviewOperations } from \"./coordinator-owner-resolution-review.js\";\nimport {\n\tCAPTURE_PEER_ENROLLMENTS_SQL,\n\ttype CapturedPeerEnrollment,\n\tcapturePeerEnrollments,\n\tREAD_CURRENT_PEERS_SQL,\n\trequirePeerDiscoveryRows,\n} from \"./coordinator-peer-discovery.js\";\nimport { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport {\n\tprepareRecipientOwnerConsistency,\n\trecipientOwnerWriteSql,\n\tvalidateRecipientOwnerInput,\n} from \"./coordinator-recipient-owner-consistency.js\";\nimport { ResolvedAccountOwnerStatusOperations } from \"./coordinator-resolved-account-owner-status.js\";\nimport {\n\ttype CapturedScopeMember,\n\tcaptureScopeAuthorizationInput,\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\tparseScopeAuthorizationMembers,\n\tREAD_SCOPE_AUTHORIZATION_SQL,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeAuthorizationInput,\n\tCoordinatorScopeAuthorizationResult,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tclean,\n\tinspectCoordinatorRecipientInvite as inspectInvite,\n\tmergeCoordinatorAddresses,\n\tnormalizeCoordinatorAuditLimit,\n\tnormalizeCoordinatorBootstrapGrantInput,\n\tnormalizeCoordinatorBootstrapGrantRequest,\n\tnormalizeCoordinatorCreateScopeInput,\n\tnormalizeCoordinatorGrantScopeMembershipInput,\n\tnormalizeCoordinatorInviteMetadata,\n\tnormalizeCoordinatorUpdateScopeInput,\n\tnormalizeEpoch,\n} from \"./coordinator-store-input-rules.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport const DEFAULT_COORDINATOR_DB_PATH = join(homedir(), \".codemem\", \"coordinator.sqlite\");\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\treturn randomBytes(bytes).toString(\"base64url\").replace(/=+$/, \"\");\n}\n\nfunction tokenDigest(token: string): string {\n\treturn createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction insertMembershipAuditSync(\n\tdb: DatabaseType,\n\tinput: {\n\t\teffectId: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tcurrent: CoordinatorScopeMembership;\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): void {\n\tdb.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n\t\tinput.effectId,\n\t\tinput.action,\n\t\tinput.current.scope_id,\n\t\tinput.current.device_id,\n\t\tinput.current.role,\n\t\tinput.current.status,\n\t\tinput.current.membership_epoch,\n\t\tinput.previous?.role ?? null,\n\t\tinput.previous?.status ?? null,\n\t\tinput.previous?.membership_epoch ?? null,\n\t\tinput.current.coordinator_id,\n\t\tinput.current.group_id,\n\t\tinput.actorType,\n\t\tinput.actorId,\n\t\tinput.current.manifest_hash,\n\t\tinput.createdAt,\n\t);\n}\n\nfunction getMembershipEffectReceiptSync(\n\tdb: DatabaseType,\n\teffectId: string,\n): CoordinatorMembershipEffectReceipt | null {\n\tconst row = db\n\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t.get(effectId);\n\treturn row ? rowToRecord<CoordinatorMembershipEffectReceipt>(row) : null;\n}\n\nfunction insertMembershipEffectReceiptSync(\n\tdb: DatabaseType,\n\tinput: {\n\t\teffectId: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\trequestJson: string;\n\t\tapplied: boolean;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tmembership: CoordinatorScopeMembership | null;\n\t\tcreatedAt: string;\n\t},\n): void {\n\tdb.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n\t\tinput.effectId,\n\t\tinput.action,\n\t\tinput.requestJson,\n\t\tinput.applied ? 1 : 0,\n\t\tinput.scopeId,\n\t\tinput.deviceId,\n\t\tinput.membership?.role ?? null,\n\t\tinput.membership?.status ?? null,\n\t\tinput.membership?.membership_epoch ?? null,\n\t\tinput.membership?.coordinator_id ?? null,\n\t\tinput.membership?.group_id ?? null,\n\t\tinput.membership?.manifest_issuer_device_id ?? null,\n\t\tinput.membership?.manifest_hash ?? null,\n\t\tinput.membership?.signed_manifest_json ?? null,\n\t\tinput.membership?.updated_at ?? null,\n\t\tinput.createdAt,\n\t);\n}\n\nfunction assertScopeMembershipDeviceEnrolled(\n\tdb: DatabaseType,\n\tgroupId: string | null,\n\tdeviceId: string,\n): void {\n\tif (!groupId) return;\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1\")\n\t\t.get(groupId, deviceId);\n\tif (!row) {\n\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t}\n}\n\nfunction insertBootstrapGrantSync(\n\tdb: DatabaseType,\n\topts: CoordinatorCreateBootstrapGrantInput,\n\trequestedGrantId?: string,\n\trequestedCreatedAt?: string,\n\tauthorization?: { sql: string; values: (string | null)[]; assertAuthorized: () => void },\n): CoordinatorBootstrapGrant {\n\tconst normalized = normalizeCoordinatorBootstrapGrantInput(opts);\n\tconst grantId = requestedGrantId ?? tokenUrlSafe(12);\n\tconst createdAt = requestedCreatedAt ?? nowISO();\n\tconst result = db\n\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t) SELECT ?, ?, ?, ?, ?, ?, ?, NULL WHERE ${authorization?.sql ?? \"1\"}`)\n\t\t.run(\n\t\t\tgrantId,\n\t\t\tnormalized.groupId,\n\t\t\tnormalized.seedDeviceId,\n\t\t\tnormalized.workerDeviceId,\n\t\t\tnormalized.expiresAt,\n\t\t\tcreatedAt,\n\t\t\tnormalized.createdBy,\n\t\t\t...(authorization?.values ?? []),\n\t\t);\n\tif (authorization && result.changes === 0) {\n\t\tauthorization.assertAuthorized();\n\t\tthrow new Error(\"invite_acceptance_incomplete\");\n\t}\n\tconst row = db\n\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t.get(grantId);\n\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n}\n\nfunction upgradeAuthSessionRetentionSchema(db: DatabaseType): void {\n\tconst present = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_session_receipts') WHERE name = 'purge_eligible'\",\n\t\t)\n\t\t.get();\n\tif (present) return;\n\tdb.transaction(() => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_auth_session_receipts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\tif (columns.length === 0 || columns.some((column) => column.name === \"purge_eligible\")) return;\n\t\tdb.exec(\n\t\t\t`ALTER TABLE coordinator_auth_session_receipts ADD COLUMN ${AUTH_SESSION_RETENTION_COLUMN_SQL}`,\n\t\t);\n\t}).immediate();\n}\n\nfunction upgradeAuthLinkBrowserStartSchema(db: DatabaseType): void {\n\tconst present = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_link_attempts') WHERE name = 'browser_start_hash'\",\n\t\t)\n\t\t.get();\n\tif (present) return;\n\tdb.transaction(() => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_auth_link_attempts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\tif (columns.length === 0 || columns.some((column) => column.name === \"browser_start_hash\"))\n\t\t\treturn;\n\t\tdb.exec(\n\t\t\t`ALTER TABLE coordinator_auth_link_attempts ADD COLUMN ${AUTH_LINK_BROWSER_START_COLUMN_SQL}`,\n\t\t);\n\t}).immediate();\n}\n\nfunction initializeDeviceLedgerSchemas(db: DatabaseType): void {\n\tupgradeDeviceOwnershipTriggers(db);\n\tdb.exec(COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL);\n\tdb.exec(DEVICE_REVOCATION_SCHEMA_SQL);\n\t// Optional owner storage never forces an upgrade of a legacy/direct coordinator.\n\t// Do not install new-column triggers on an existing pre-0034 table either.\n\tconst ownerTable = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_owner_enrollment_attempts'\",\n\t\t)\n\t\t.get();\n\tif (!ownerTable) db.exec(COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL);\n\t// Additive rebind storage (ADR 0005 Section 8). Only an empty pre-release\n\t// attempts table is recreated; see upgradePreReleaseRebindAttemptsSql.\n\tupgradePreReleaseRebindAttempts(db);\n\tupgradeRebindAttemptsForSelfBind(db);\n\tdb.exec(COORDINATOR_DEVICE_REBIND_SCHEMA_SQL);\n}\n\nconst REBIND_ATTEMPTS_SQL =\n\t\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_device_rebind_attempts'\";\n\nconst OWNERSHIP_COLLISION_TRIGGER_SQL =\n\t\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'coordinator_device_ownership_insert_collision'\";\n\n/** Reads first; replaces an outdated trigger and recreates it in one transaction. */\nfunction upgradeDeviceOwnershipTriggers(db: DatabaseType): void {\n\tconst plan = () =>\n\t\tupgradeDeviceOwnershipTriggersSql(\n\t\t\t(db.prepare(OWNERSHIP_COLLISION_TRIGGER_SQL).pluck().get() as string | undefined) ?? null,\n\t\t);\n\tif (!plan()) return;\n\tdb.transaction(() => {\n\t\tconst upgrade = plan();\n\t\tif (!upgrade) return;\n\t\tdb.exec(upgrade);\n\t\tdb.exec(COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL);\n\t}).immediate();\n}\n\n/** Reads first; rebuilds an attempts table that forbids self-binds, keeping its rows. */\nfunction upgradeRebindAttemptsForSelfBind(db: DatabaseType): void {\n\tconst needed = () =>\n\t\trebindAttemptsNeedSelfBindRebuild(\n\t\t\t(db.prepare(REBIND_ATTEMPTS_SQL).pluck().get() as string | undefined) ?? null,\n\t\t);\n\tif (!needed()) return;\n\tdb.transaction(() => {\n\t\tif (needed()) db.exec(rebuildRebindAttemptsForSelfBindSql());\n\t}).immediate();\n}\n\n/** Reads first, so opening an up-to-date database takes no write lock. */\nfunction upgradePreReleaseRebindAttempts(db: DatabaseType): void {\n\tconst plan = () => {\n\t\tconst existing = db.prepare(REBIND_ATTEMPTS_SQL).pluck().get() as string | undefined;\n\t\tif (!existing) return null;\n\t\tconst rows = db\n\t\t\t.prepare(\"SELECT count(*) FROM coordinator_device_rebind_attempts\")\n\t\t\t.pluck()\n\t\t\t.get() as number;\n\t\treturn upgradePreReleaseRebindAttemptsSql(existing, rows);\n\t};\n\tif (!plan()) return;\n\tdb.transaction(() => {\n\t\tconst upgrade = plan();\n\t\tif (upgrade) db.exec(upgrade);\n\t}).immediate();\n}\n\nfunction initializeAuthBrowserSchema(db: DatabaseType): void {\n\tupgradeAuthBrowserOwnerPurposeSchema(db);\n\tdb.exec(AUTH_BROWSER_TXN_SCHEMA_SQL);\n}\n\nfunction initializeAuthLinkSchema(db: DatabaseType): void {\n\tconst ready = db.prepare(AUTH_SCHEMA_READINESS_SQL).get() as { ready: number };\n\tif (ready.ready === AUTH_SCHEMA_READY_COUNT) return;\n\tconst existing = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type='table' AND name='coordinator_auth_link_attempts'\",\n\t\t)\n\t\t.get() as { sql: string } | undefined;\n\tif (existing && !existing.sql.includes(\"authority_kind\")) {\n\t\tupgradeAuthLinkBrowserStartSchema(db);\n\t\tdb.exec(AUTH_LINK_SCHEMA_SQL);\n\t\treturn;\n\t}\n\tdb.transaction(() => {\n\t\tupgradeAuthLinkBrowserStartSchema(db);\n\t\tdb.exec(AUTH_LINK_SCHEMA_SQL);\n\t\tconst explicit = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_link_attempts') WHERE name = 'authority_kind'\",\n\t\t\t)\n\t\t\t.get();\n\t\tif (explicit) db.exec(COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL);\n\t}).immediate();\n}\n\nfunction initializeOptionalAuthSchema(db: DatabaseType): void {\n\tif ((db.prepare(CONNECTION_SCHEMA_PRESENCE_SQL).get() as { present: number }).present) return;\n\tdb.exec(AUTH_CONTROLLER_SCHEMA_SQL);\n\tinitializeAuthLinkSchema(db);\n\tupgradeAuthSessionRetentionSchema(db);\n\tdb.exec(AUTH_SESSION_SCHEMA_SQL);\n\tdb.exec(AUTH_ACCOUNT_PROFILE_SCHEMA_SQL);\n\tdb.exec(AUTH_LINK_PROFILE_SCHEMA_SQL);\n\tinitializeAuthBrowserSchema(db);\n}\nfunction initializeSchema(db: DatabaseType): void {\n\tdb.exec(IDENTITY_GROUP_GRANT_SCHEMA_SQL);\n\tinitializeDeviceLedgerSchemas(db);\n\tinitializeOptionalAuthSchema(db);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS groups (\n\t\t\tgroup_id TEXT PRIMARY KEY,\n\t\t\tdisplay_name TEXT,\n\t\t\tarchived_at TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS enrolled_devices (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tpublic_key TEXT NOT NULL,\n\t\t\tfingerprint TEXT NOT NULL,\n\t\t\tidentity_id TEXT,\n\t\t\tdisplay_name TEXT,\n\t\t\tenabled INTEGER NOT NULL DEFAULT 1,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (group_id, device_id)\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS presence_records (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\taddresses_json TEXT NOT NULL,\n\t\t\tlast_seen_at TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcapabilities_json TEXT NOT NULL DEFAULT '{}',\n\t\t\tPRIMARY KEY (group_id, device_id)\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS request_nonces (\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tnonce TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (device_id, nonce)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_request_nonces_created_at\n\t\t\tON request_nonces(created_at);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_invites (\n\t\t\tinvite_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\ttoken TEXT NOT NULL UNIQUE,\n\t\t\tpolicy TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tcreated_by TEXT,\n\t\t\tteam_name_snapshot TEXT,\n\t\t\trevoked_at TEXT,\n\t\t\toperation_id TEXT,\n\t\t\treviewed_project_set_digest TEXT,\n\t\t\ttoken_digest TEXT,\n\t\t\tinviter_actor_id TEXT,\n\t\t\tinviter_display_name TEXT,\n\t\t\tinviter_device_id TEXT,\n\t\t\tpending_person_id TEXT,\n\t\t\tproject_summaries_json TEXT,\n\t\t\tproject_intent_json TEXT,\n\t\t\tconsumed_at TEXT,\n\t\t\tbound_device_id TEXT,\n\t\t\tbound_public_key TEXT,\n\t\t\tbound_fingerprint TEXT,\n\t\t\trecipient_actor_id TEXT,\n\t\t\trecipient_display_name TEXT,\n\t\t\trecipient_device_display_name TEXT,\n\t\t\ttrust_state TEXT,\n\t\t\tbootstrap_grant_id TEXT,\n\t\t\tinvite_kind TEXT,\n\t\t\tpolicy_team_id TEXT,\n\t\t\ttarget_identity_id TEXT,\n\t\t\tassigned_identity_id TEXT,\n\t\t\treviewed_preview_digest TEXT,\n\t\t\treviewed_intent_json TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_join_requests (\n\t\t\trequest_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tpublic_key TEXT NOT NULL,\n\t\t\tfingerprint TEXT NOT NULL,\n\t\t\tdisplay_name TEXT,\n\t\t\ttoken TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\treviewed_at TEXT,\n\t\t\treviewed_by TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_reciprocal_approvals (\n\t\t\trequest_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\trequesting_device_id TEXT NOT NULL,\n\t\t\trequested_device_id TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tresolved_at TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_bootstrap_grants (\n\t\t\tgrant_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tseed_device_id TEXT NOT NULL,\n\t\t\tworker_device_id TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tcreated_by TEXT,\n\t\t\trevoked_at TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scopes (\n\t\t\tscope_id TEXT PRIMARY KEY,\n\t\t\tlabel TEXT NOT NULL,\n\t\t\tkind TEXT NOT NULL DEFAULT 'user',\n\t\t\tauthority_type TEXT NOT NULL DEFAULT 'coordinator',\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\tmanifest_hash TEXT,\n\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scopes_status\n\t\t\tON coordinator_scopes(status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scopes_authority_group\n\t\t\tON coordinator_scopes(coordinator_id, group_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_memberships (\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT NOT NULL DEFAULT 'member',\n\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tsigned_manifest_json TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (scope_id, device_id)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_device_status\n\t\t\tON coordinator_scope_memberships(device_id, status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_scope_status\n\t\t\tON coordinator_scope_memberships(scope_id, status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_authority_group\n\t\t\tON coordinator_scope_memberships(coordinator_id, group_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_membership_audit_log (\n\t\t\tevent_id INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\teffect_id TEXT,\n\t\t\taction TEXT NOT NULL,\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tmembership_epoch INTEGER NOT NULL,\n\t\t\tprevious_role TEXT,\n\t\t\tprevious_status TEXT,\n\t\t\tprevious_membership_epoch INTEGER,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tactor_type TEXT,\n\t\t\tactor_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_scope_created\n\t\t\tON coordinator_scope_membership_audit_log(scope_id, created_at, event_id);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_device_created\n\t\t\tON coordinator_scope_membership_audit_log(device_id, created_at, event_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_membership_effect_receipts (\n\t\t\teffect_id TEXT PRIMARY KEY,\n\t\t\taction TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),\n\t\t\trequest_json TEXT NOT NULL,\n\t\t\toutcome_applied INTEGER NOT NULL CHECK (outcome_applied IN (0, 1)),\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT,\n\t\t\tstatus TEXT,\n\t\t\tmembership_epoch INTEGER,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tsigned_manifest_json TEXT,\n\t\t\tupdated_at TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_legacy_team_completions (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tcandidate_ref TEXT NOT NULL,\n\t\t\tmanifest_version INTEGER NOT NULL CHECK (manifest_version = 1),\n\t\t\tmanifest_json TEXT NOT NULL,\n\t\t\tcompleted_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (group_id, candidate_ref)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_legacy_team_completions_group\n\t\t\tON coordinator_legacy_team_completions(group_id, completed_at, candidate_ref);\n\t`);\n\ttry {\n\t\tdb.prepare(\n\t\t\t\"ALTER TABLE coordinator_scope_membership_audit_log ADD COLUMN effect_id TEXT\",\n\t\t).run();\n\t} catch {\n\t\t// already exists\n\t}\n\tdb.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_effect\n\t\tON coordinator_scope_membership_audit_log(effect_id) WHERE effect_id IS NOT NULL`);\n\ttry {\n\t\tdb.prepare(\"ALTER TABLE groups ADD COLUMN archived_at TEXT\").run();\n\t} catch {\n\t\t// already exists\n\t}\n\ttry {\n\t\tdb.prepare(\"ALTER TABLE enrolled_devices ADD COLUMN identity_id TEXT\").run();\n\t} catch {\n\t\t// already exists\n\t}\n\tfor (const column of [\n\t\t\"operation_id\",\n\t\t\"reviewed_project_set_digest\",\n\t\t\"token_digest\",\n\t\t\"inviter_actor_id\",\n\t\t\"inviter_display_name\",\n\t\t\"inviter_device_id\",\n\t\t\"pending_person_id\",\n\t\t\"project_summaries_json\",\n\t\t\"project_intent_json\",\n\t\t\"consumed_at\",\n\t\t\"bound_device_id\",\n\t\t\"bound_public_key\",\n\t\t\"bound_fingerprint\",\n\t\t\"recipient_actor_id\",\n\t\t\"recipient_display_name\",\n\t\t\"recipient_device_display_name\",\n\t\t\"trust_state\",\n\t\t\"bootstrap_grant_id\",\n\t\t\"invite_kind\",\n\t\t\"policy_team_id\",\n\t\t\"target_identity_id\",\n\t\t\"assigned_identity_id\",\n\t\t\"reviewed_preview_digest\",\n\t\t\"reviewed_intent_json\",\n\t]) {\n\t\ttry {\n\t\t\tdb.prepare(`ALTER TABLE coordinator_invites ADD COLUMN ${column} TEXT`).run();\n\t\t} catch {\n\t\t\t// already exists\n\t\t}\n\t}\n\tdb.exec(\n\t\t`CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_invites_operation_id\n\t\t\tON coordinator_invites(operation_id) WHERE operation_id IS NOT NULL;\n\t\t CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_invites_token_digest\n\t\t\tON coordinator_invites(token_digest) WHERE token_digest IS NOT NULL;\n\t\t CREATE INDEX IF NOT EXISTS idx_coordinator_invites_group_created\n\t\t\tON coordinator_invites(group_id, created_at DESC);\n\t\t UPDATE coordinator_invites\n\t\t\tSET invite_kind = CASE WHEN operation_id IS NOT NULL THEN 'project_share' ELSE 'legacy_enrollment' END\n\t\t\tWHERE invite_kind IS NULL;`,\n\t);\n}\n\nexport function connectCoordinator(\n\tpath?: string,\n\toptions: { existingOnly?: boolean } = {},\n): DatabaseType {\n\tconst dbPath = path ?? DEFAULT_COORDINATOR_DB_PATH;\n\tif (options.existingOnly) {\n\t\tconst db = new Database(dbPath, { fileMustExist: true });\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\treturn db;\n\t}\n\tmkdirSync(dirname(dbPath), { recursive: true });\n\tconst db = new Database(dbPath);\n\tdb.pragma(\"foreign_keys = ON\");\n\tdb.pragma(\"busy_timeout = 5000\");\n\tdb.pragma(\"journal_mode = WAL\");\n\tdb.pragma(\"synchronous = NORMAL\");\n\tinitializeSchema(db);\n\treturn db;\n}\n\nfunction enrollmentRevocationKeyId(publicKey: string): string | null {\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(publicKey);\n\tif (parsed.kind !== \"ed25519\") return null;\n\treturn createHash(\"sha256\").update(parsed.blob).digest(\"hex\");\n}\n\nexport class BetterSqliteCoordinatorStore implements CoordinatorStore {\n\t/** The raw backend, without the auth schema wrapper. */\n\tprivate readonly schemaBackend: AuthLinkBackend;\n\tprivate readonly accountChangeBackend: AuthLinkBackend;\n\tprivate readonly accountChangesCapability: AccountChangeOperations;\n\treadonly path: string;\n\treadonly db: DatabaseType;\n\tprivate readonly authLinks: AuthLinkOperations;\n\treadonly assertAuthSchemaReady: () => Promise<void>;\n\tprivate readonly accountLinkStatus: AccountLinkStatusOperations;\n\tprivate readonly accountOwnerTarget: AccountOwnerTargetOperations;\n\tprivate readonly deviceRevocations: DeviceRevocationOperations;\n\tprivate readonly authSessions: AuthSessionOperations;\n\tprivate readonly authAccountProfiles: AuthAccountProfileOperations;\n\tprivate readonly authBrowserTransactions: CoordinatorAuthBrowserTransactions;\n\n\tconstructor(\n\t\tpath?: string,\n\t\toptions: CoordinatorAuthLinkOptions & { existingOnly?: boolean } = {},\n\t) {\n\t\tthis.path = path ?? DEFAULT_COORDINATOR_DB_PATH;\n\t\tthis.db = connectCoordinator(this.path, options);\n\t\tthis.deviceRevocations = new DeviceRevocationOperations(\n\t\t\t{\n\t\t\t\tall: async (statement) => ({\n\t\t\t\t\tresults: this.db.prepare(statement.sql).all(...statement.values),\n\t\t\t\t}),\n\t\t\t\tbatch: async (statements) =>\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\t\tstatements.map((statement) => {\n\t\t\t\t\t\t\t\tconst prepared = this.db.prepare(statement.sql);\n\t\t\t\t\t\t\t\tif (statement.read) return { results: prepared.all(...statement.values) };\n\t\t\t\t\t\t\t\treturn { meta: { changes: prepared.run(...statement.values).changes } };\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.immediate(),\n\t\t\t},\n\t\t\toptions.authClock,\n\t\t);\n\t\tconst rawAuthBackend: AuthLinkBackend = {\n\t\t\tall: async <T>(statement: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(statement.sql).all(...statement.values) as T[],\n\t\t\tfirst: async <T>(statement: AuthLinkStatement) =>\n\t\t\t\t(this.db.prepare(statement.sql).get(...statement.values) as T | undefined) ?? null,\n\t\t\trun: async (statement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.transaction(() => this.db.prepare(statement.sql).run(...statement.values).changes)\n\t\t\t\t\t.immediate(),\n\t\t\tbatch: async (statements) => {\n\t\t\t\treturn this.db\n\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\tstatements.map(\n\t\t\t\t\t\t\t(statement) => this.db.prepare(statement.sql).run(...statement.values).changes,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.immediate();\n\t\t\t},\n\t\t};\n\t\tthis.assertAuthSchemaReady = () => assertCoordinatorAuthSchema(rawAuthBackend);\n\t\tthis.schemaBackend = rawAuthBackend;\n\t\tconst authBackend = withCoordinatorAuthSchema(rawAuthBackend);\n\t\tthis.accountChangeBackend = withCoordinatorAuthSchema(rawAuthBackend, { connections: true });\n\t\tthis.accountChangesCapability = new AccountChangeOperations(\n\t\t\tthis.accountChangeBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t\tthis.authLinks = new AuthLinkOperations(authBackend, options.authClock);\n\t\tthis.accountLinkStatus = new AccountLinkStatusOperations(authBackend, options.authClock);\n\t\tthis.accountOwnerTarget = new AccountOwnerTargetOperations(authBackend, this);\n\t\tthis.authSessions = new AuthSessionOperations(authBackend, options.authClock);\n\t\tthis.authAccountProfiles = new AuthAccountProfileOperations(authBackend, options.authClock);\n\t\tthis.authBrowserTransactions = new CoordinatorAuthBrowserTransactions(\n\t\t\tauthBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t}\n\t/** ADR 0005 Section 8 rebind storage; null before its tables exist. */\n\treadDeviceRebindBackend(): Promise<AuthLinkBackend | null> {\n\t\treturn readDeviceRebindBackend(this.schemaBackend);\n\t}\n\t/** Explicit capability: legacy V2 remains usable without enabling management. */\n\tasync getAccountChanges(): Promise<AccountChangeOperations> {\n\t\tawait this.accountChangeBackend.first({ sql: \"SELECT 1\", values: [] });\n\t\treturn this.accountChangesCapability;\n\t}\n\treadAccountConnectionSchemaState(): Promise<ConnectionSchemaState> {\n\t\treturn readConnectionSchemaState(this.schemaBackend);\n\t}\n\t/** One fresh startup lookup; returned operations still check every SQL entry. */\n\tasync readAccountChangeCapability(): Promise<AccountChangeOperations | null> {\n\t\tconst state = await this.readAccountConnectionSchemaState();\n\t\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\t\treturn state === \"ready\" ? this.accountChangesCapability : null;\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionPurpose(input, config);\n\t}\n\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionActivity(input, config);\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.startAuthBrowserTransaction(input, config);\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.consumeAuthBrowserTransaction(input, config);\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.resolveAuthLinkBrowserTransaction(input, config);\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t) {\n\t\treturn this.authBrowserTransactions.cancelAuthSigninBrowserTransaction(input, scope);\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.retireAuthBrowserTransactions(config, options);\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.purgeAuthSigninBrowserTransactions(scope, options);\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.maintainAuthBrowserTransactions(scope, options);\n\t}\n\n\tasync redeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSession(input, config);\n\t}\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSessionWithBrowserTransaction(input, config);\n\t}\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.preserveAuthLinkSessionCompletion(input, config);\n\t}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninSessions(scope, options);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninReceipts(scope, options);\n\t}\n\tasync signInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.signInWithAuthAccount(input, config);\n\t}\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.signInWithConsumedBrowserTransaction(input, config);\n\t}\n\tasync readAuthSession(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authSessions.readAuthSession(credentialHash, config);\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authAccountProfiles.recordAuthAccountProfile(input, config);\n\t}\n\tasync readAuthSessionAccount(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authAccountProfiles.readAuthSessionAccount(credentialHash, config);\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t) {\n\t\treturn this.authAccountProfiles.clearRevokedAuthAccountProfile(input, scope);\n\t}\n\tasync signOutAuthSession(credentialHash: string, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.signOutAuthSession(credentialHash, scope);\n\t}\n\tasync revokeAuthAccountLink(input: { linkId: string }, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.revokeAuthAccountLink(input, scope);\n\t}\n\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t) {\n\t\treturn this.authLinks.maintainAuthLinkAttempts(config, options);\n\t}\n\treadAccountLinkStatus(...args: Parameters<AccountLinkStatusOperations[\"readAccountLinkStatus\"]>) {\n\t\treturn this.accountLinkStatus.readAccountLinkStatus(...args);\n\t}\n\treadAccountOwnerTarget(\n\t\t...args: Parameters<AccountOwnerTargetOperations[\"readAccountOwnerTarget\"]>\n\t) {\n\t\treturn this.accountOwnerTarget.readAccountOwnerTarget(...args);\n\t}\n\treadResolvedAccountOwnerStatus(\n\t\t...args: Parameters<ResolvedAccountOwnerStatusOperations[\"readResolvedAccountOwnerStatus\"]>\n\t) {\n\t\treturn new ResolvedAccountOwnerStatusOperations({\n\t\t\t...this.accountChangeBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t}).readResolvedAccountOwnerStatus(...args);\n\t}\n\tprivate ownerResolutionReviews(): OwnerResolutionReviewOperations {\n\t\treturn new OwnerResolutionReviewOperations({\n\t\t\t...this.schemaBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\trun: async ({ sql, values }) => this.db.prepare(sql).run(...values).changes,\n\t\t\tbatch: async (statements) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\tstatements.map(({ sql, values }) => {\n\t\t\t\t\t\t\tconst statement = this.db.prepare(sql);\n\t\t\t\t\t\t\tif (statement.reader) {\n\t\t\t\t\t\t\t\tstatement.all(...values);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn statement.run(...values).changes;\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.immediate(),\n\t\t});\n\t}\n\tpreviewOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"previewOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().previewOwnerResolutionReview(...args);\n\t}\n\tconfirmOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"confirmOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().confirmOwnerResolutionReview(...args);\n\t}\n\treadAuthDeviceClaimReadiness(\n\t\t...args: Parameters<AccountLinkStatusOperations[\"readAuthDeviceClaimReadiness\"]>\n\t) {\n\t\treturn this.accountLinkStatus.readAuthDeviceClaimReadiness(...args);\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.createAuthLinkAttempt(input, config);\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.claimAuthLinkAttempt(input, config);\n\t}\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.recordAuthLinkOidcVerified(input, config);\n\t}\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.confirmAuthLinkAttempt(input, config);\n\t}\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readAuthLinkCompletionDestination(input, config);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.finalizeAuthLinkAttempt(input, config);\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.failAuthLinkAttempt(input, config);\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.getAuthLinkAttemptStatus(attemptId, requester, config);\n\t}\n\n\tprivate enrollDeviceSync(groupId: string, opts: CoordinatorEnrollDeviceInput): void {\n\t\tconst { deviceId, publicKey, fingerprint, identityId, displayName } = captureLegacyEnrollment(\n\t\t\tgroupId,\n\t\t\topts,\n\t\t);\n\t\ttry {\n\t\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t.get(groupId, deviceId) ?? null,\n\t\t\t);\n\t\t\tconst keyId = enrollmentRevocationKeyId(publicKey);\n\t\t\tconst currentKeyId =\n\t\t\t\tcurrentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey);\n\t\t\tconst source = [currentPublicKey, groupId, deviceId, groupId, deviceId, currentPublicKey];\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_WRITE_SQL)\n\t\t\t\t.run(\n\t\t\t\t\tgroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tidentityId ?? null,\n\t\t\t\t\tdisplayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\t...source,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\tcurrentPublicKey,\n\t\t\t\t);\n\t\t\tif (legacyDeviceWriteChanges({ meta: result }) === 1) return;\n\t\t\tconst denial = this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_DENIAL_SQL)\n\t\t\t\t.get(deviceId, keyId, deviceId, keyId, deviceId, currentKeyId, ...source);\n\t\t\tthrow new Error(legacyDeviceDenial(denial));\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.db.close();\n\t}\n\n\tasync issueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"attestationId\"]);\n\t\tif (!captured) return { kind: \"rejected\", error: \"invalid_grant_input\" };\n\t\ttry {\n\t\t\treturn this.db\n\t\t\t\t.transaction((): CoordinatorIdentityGroupGrantIssueResult => {\n\t\t\t\t\tconst source = this.db\n\t\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_SOURCE_SQL)\n\t\t\t\t\t\t.get(captured.coordinatorId, captured.attestationId) as\n\t\t\t\t\t\t| CoordinatorEnrollment\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (!source) return { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\t\t\tconst authority = [\n\t\t\t\t\t\tcaptured.coordinatorId,\n\t\t\t\t\t\tcaptured.attestationId,\n\t\t\t\t\t\tsource.group_id,\n\t\t\t\t\t\tsource.device_id,\n\t\t\t\t\t\tsource.public_key,\n\t\t\t\t\t\tsource.fingerprint,\n\t\t\t\t\t\tsource.identity_id,\n\t\t\t\t\t\tsource.device_id,\n\t\t\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t\t\t];\n\t\t\t\t\tconst grant = this.db\n\t\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_INSERT_SQL)\n\t\t\t\t\t\t.get(nowISO(), ...authority) as CoordinatorIdentityGroupGrant | undefined;\n\t\t\t\t\tif (grant) return { kind: \"created\", grant };\n\t\t\t\t\tconst existing = this.db.prepare(IDENTITY_GROUP_GRANT_RETRY_SQL).get(...authority) as\n\t\t\t\t\t\t| CoordinatorIdentityGroupGrant\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (existing) return { kind: \"existing\", grant: existing };\n\t\t\t\t\treturn { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tasync listIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"identityId\"]);\n\t\tif (!captured) throw new Error(\"invalid_grant_input\");\n\t\treturn this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_LIST_SQL)\n\t\t\t.all(captured.coordinatorId, captured.identityId) as CoordinatorIdentityGroupGrant[];\n\t}\n\n\tasync revokeIdentityGroupGrant(\n\t\tinput: CoordinatorIdentityGroupGrantRevokeInput,\n\t): Promise<boolean> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\n\t\t\t\"coordinatorId\",\n\t\t\t\"identityId\",\n\t\t\t\"groupId\",\n\t\t\t\"expectedRevision\",\n\t\t]);\n\t\tif (!captured) return false;\n\t\treturn (\n\t\t\tthis.db\n\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_REVOKE_SQL)\n\t\t\t\t.run(\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tcaptured.coordinatorId,\n\t\t\t\t\tcaptured.identityId,\n\t\t\t\t\tcaptured.groupId,\n\t\t\t\t\tcaptured.expectedRevision,\n\t\t\t\t).changes > 0\n\t\t);\n\t}\n\n\tasync createAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review) return { kind: \"rejected\", error: \"invalid_review_input\" };\n\t\tconst conflict = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_CONFLICT_SQL)\n\t\t\t.get(...authControllerConflictValues(review)) as\n\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t| undefined;\n\t\tconst hasConflict = conflict !== undefined;\n\t\tconst consistency = hasConflict ? null : await this.prepareAuthControllerConsistency(review);\n\t\tif (!hasConflict && !consistency) return authControllerUnavailableResult(review);\n\t\tlet retryAfterPinChange = false;\n\t\tconst result = this.db\n\t\t\t.transaction((): CoordinatorAuthControllerCreateResult => {\n\t\t\t\tconst source = this.db\n\t\t\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\tif (!source) return authControllerUnavailableResult(review);\n\t\t\t\tconst authority = authControllerAuthorityValues(\n\t\t\t\t\tsource,\n\t\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t\t);\n\t\t\t\tif (hasConflict) return this.resolveAuthControllerRetrySync(review, authority);\n\t\t\t\ttry {\n\t\t\t\t\tconst statement = withNegativeOwnerConsistency(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_INSERT_SQL, review),\n\t\t\t\t\t\t\tvalues: authControllerInsertValues(review, nowISO(), authority),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tconsistency ?? { sql: \"SELECT 0 AS matches\", values: [] },\n\t\t\t\t\t);\n\t\t\t\t\tconst inserted = this.db.prepare(statement.sql).run(...statement.values);\n\t\t\t\t\tif (inserted.changes === 0) {\n\t\t\t\t\t\tretryAfterPinChange = true;\n\t\t\t\t\t\treturn authControllerUnavailableResult(review);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!isAuthControllerUniqueError(error)) throw error;\n\t\t\t\t\treturn this.resolveAuthControllerRetrySync(review, authority);\n\t\t\t\t}\n\t\t\t\tconst attestation = this.getActiveAuthControllerAttestationSync(\n\t\t\t\t\treview.coordinatorId,\n\t\t\t\t\treview.attestationId,\n\t\t\t\t\tauthority,\n\t\t\t\t);\n\t\t\t\tif (!attestation) throw new Error(\"auth_controller_persistence_incomplete\");\n\t\t\t\treturn { kind: \"created\", attestation };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (!retryAfterPinChange) return result;\n\t\treturn this.retryAuthControllerAfterPinChange(review);\n\t}\n\n\tprivate async retryAuthControllerAfterPinChange(\n\t\treview: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\t// The winner changes the evidence pin. Recapture without accepting new conflicts.\n\t\tconst retryConsistency = await this.prepareAuthControllerConsistency(review);\n\t\tif (!retryConsistency) return authControllerUnavailableResult(review);\n\t\treturn this.db\n\t\t\t.transaction((): CoordinatorAuthControllerCreateResult => {\n\t\t\t\tconst pin = this.db.prepare(retryConsistency.sql).get(...retryConsistency.values) as\n\t\t\t\t\t| { matches: number }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (pin?.matches !== 1) return authControllerUnavailableResult(review);\n\t\t\t\tconst source = this.db\n\t\t\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\tif (!source) return authControllerUnavailableResult(review);\n\t\t\t\treturn this.resolveAuthControllerRetrySync(\n\t\t\t\t\treview,\n\t\t\t\t\tauthControllerAuthorityValues(source, enrollmentRevocationKeyId(source.public_key)),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate prepareAuthControllerConsistency(review: CoordinatorAuthControllerReviewInput) {\n\t\treturn prepareNegativeOwnerConsistency(\n\t\t\t{\n\t\t\t\tfirst: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t(this.db.prepare(sql).get(...values) as T | undefined) ?? null,\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t},\n\t\t\t{\n\t\t\t\t...review,\n\t\t\t\townerIdentityId: review.identityId,\n\t\t\t\tenrollment: { groupId: review.groupId },\n\t\t\t\tverifiedHistory: review.verifiedSnapshot?.legacyHistory,\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate resolveAuthControllerRetrySync(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t\tauthority: (string | null)[],\n\t): CoordinatorAuthControllerCreateResult {\n\t\tif (\n\t\t\t!this.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL, input))\n\t\t\t\t.get(...authControllerRetryEligibleValues(input, authority))\n\t\t)\n\t\t\treturn {\n\t\t\t\tkind: \"rejected\",\n\t\t\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t\t\t};\n\t\tconst row = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_CONFLICT_SQL)\n\t\t\t.get(...authControllerConflictValues(input)) as\n\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t| undefined;\n\t\tconst result = authControllerRetryResult(input, row ?? null);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tconst active = this.getActiveAuthControllerAttestationSync(\n\t\t\tinput.coordinatorId,\n\t\t\tinput.attestationId,\n\t\t\tauthority,\n\t\t);\n\t\tif (!active) return { kind: \"rejected\", error: \"enrollment_mismatch\" };\n\t\treturn { kind: \"existing\", attestation: active };\n\t}\n\n\tprivate getActiveAuthControllerAttestationSync(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t\tauthority?: (string | null)[],\n\t): CoordinatorAuthControllerAttestation | null {\n\t\tif (!authority) {\n\t\t\tconst source = this.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL)\n\t\t\t\t.get(coordinatorId, attestationId) as CoordinatorEnrollment | undefined;\n\t\t\tif (!source) return null;\n\t\t\tauthority = authControllerAuthorityValues(\n\t\t\t\tsource,\n\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\t(this.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_ACTIVE_SQL)\n\t\t\t\t.get(coordinatorId, attestationId, ...authority) as\n\t\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t\t| undefined) ?? null\n\t\t);\n\t}\n\n\tasync getActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return null;\n\t\treturn this.getActiveAuthControllerAttestationSync(coordinatorId, attestationId);\n\t}\n\n\tasync readAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review?.verifiedSnapshot?.accountOwnerTarget) return null;\n\t\tconst source = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t);\n\t\treturn (\n\t\t\t(this.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, review))\n\t\t\t\t.get(...authControllerRetryActiveValues(review, authority)) as\n\t\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t\t| undefined) ?? null\n\t\t);\n\t}\n\n\tasync hasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean> {\n\t\treturn !!this.db\n\t\t\t.prepare(AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL)\n\t\t\t.get(...authControllerSubjectOwnerConflictValues(input));\n\t}\n\n\tasync revokeAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<boolean> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return false;\n\t\treturn (\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_REVOKE_SQL).run(nowISO(), coordinatorId, attestationId)\n\t\t\t\t.changes > 0\n\t\t);\n\t}\n\n\tasync createGroup(groupId: string, displayName?: string | null): Promise<void> {\n\t\tthis.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.run(groupId, displayName ?? null, nowISO());\n\t}\n\n\tasync getGroup(groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t)\n\t\t\t.get(groupId);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t)\n\t\t\t.all()\n\t\t\t.map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(groupId: string, displayName: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t.run(displayName, groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync archiveGroup(groupId: string, archivedAt = nowISO()): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t.run(archivedAt, groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync unarchiveGroup(groupId: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\n\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t)\n\t\t\t.run(groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync enrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst input = captureLegacyEnrollment(groupId, opts);\n\t\ttry {\n\t\t\tthis.db.transaction(() => this.enrollDeviceSync(groupId, input)).immediate();\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync listEnrolledDevices(\n\t\tgroupId: string,\n\t\tincludeDisabled = false,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\treturn withEnrollmentOwnership(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}, ${ENROLLMENT_OWNERSHIP_COLUMNS}\n\t\t\t\t FROM enrolled_devices\n\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t.all(groupId)\n\t\t\t\t.map(rowToEnrollmentWithPresence),\n\t\t);\n\t}\n\n\tasync getEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t FROM enrolled_devices\n\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t.get(groupId, deviceId);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t.run(displayName, groupId, deviceId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync setDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean> {\n\t\tassertLegacyDeviceScope(groupId, deviceId);\n\t\tif (typeof enabled !== \"boolean\") throw new Error(\"invalid_input\");\n\t\tif (enabled) {\n\t\t\ttry {\n\t\t\t\treturn this.db\n\t\t\t\t\t.transaction(() => {\n\t\t\t\t\t\tconst enrollment = this.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.get(groupId, deviceId) as { public_key: string } | undefined;\n\t\t\t\t\t\tif (!enrollment) return false;\n\t\t\t\t\t\tconst publicKey = enrollment.public_key;\n\t\t\t\t\t\tif (typeof publicKey !== \"string\")\n\t\t\t\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\t\t\tconst keyId = enrollmentRevocationKeyId(publicKey);\n\t\t\t\t\t\tconst result = this.db\n\t\t\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = 1\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ?\n\t\t\t\t\t\tAND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\t\t\tAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`)\n\t\t\t\t\t\t\t.run(groupId, deviceId, publicKey, deviceId, keyId, deviceId, keyId);\n\t\t\t\t\t\tif (legacyDeviceWriteChanges({ meta: result }) === 1) return true;\n\t\t\t\t\t\tconst denial = legacyDeviceDenial(\n\t\t\t\t\t\t\tthis.db.prepare(LEGACY_DEVICE_DENIAL_SQL).get(deviceId, keyId, deviceId, keyId),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (denial === \"device_ownership_requires_verified_identity\") throw new Error(denial);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t})\n\t\t\t\t\t.immediate();\n\t\t\t} catch (error) {\n\t\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t\t}\n\t\t}\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t.run(enabled ? 1 : 0, groupId, deviceId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync removeDevice(groupId: string, deviceId: string): Promise<boolean> {\n\t\t// Atomic: a partial failure must not leave presence/approval rows\n\t\t// orphaned against a still-enrolled device (or vice versa).\n\t\tconst removeAll = this.db.transaction(() => {\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.run(groupId, deviceId);\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.run(groupId, deviceId, deviceId);\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.run(groupId, deviceId);\n\t\t\treturn result.changes > 0;\n\t\t});\n\t\treturn removeAll();\n\t}\n\n\tasync recordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean> {\n\t\ttry {\n\t\t\tthis.db\n\t\t\t\t.prepare(\"INSERT INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\")\n\t\t\t\t.run(deviceId, nonce, createdAt);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync createDeviceRevocation(input: CoordinatorCreateDeviceRevocationInput) {\n\t\treturn this.deviceRevocations.createDeviceRevocation(input);\n\t}\n\n\tasync listDeviceRevocations(input: CoordinatorListDeviceRevocationsInput) {\n\t\treturn this.deviceRevocations.listDeviceRevocations(input);\n\t}\n\n\tasync recordAuthorizedNonce(input: CoordinatorRecordAuthorizedNonceInput) {\n\t\treturn this.deviceRevocations.recordAuthorizedNonce(input);\n\t}\n\n\tasync cleanupNonces(cutoff: string): Promise<void> {\n\t\tthis.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").run(cutoff);\n\t}\n\n\tasync createInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\t// Normalize to canonical UTC ISO so the lexicographic `expires_at > ?`\n\t\t// comparison in getInviteByToken is sound.\n\t\tconst expiresAt = normalizeInviteExpiresAt(opts.expiresAt);\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = tokenDigest(token);\n\t\tconst group = await this.getGroup(opts.groupId);\n\t\tconst operationId = clean(opts.operationId);\n\t\tconst reviewedProjectSetDigest = clean(opts.reviewedProjectSetDigest);\n\t\tconst metadata = await normalizeCoordinatorInviteMetadata(opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = (): CoordinatorInvite | null => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = this.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t.get(operationId) as CoordinatorInvite | undefined;\n\t\t\tif (!existing) return null;\n\t\t\t// Project bearer tokens remain retrievable only until first consume so an\n\t\t\t// interrupted create can return the same invite. Consume replaces the\n\t\t\t// plaintext with a non-secret marker; later create retries must not emit it.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== opts.groupId ||\n\t\t\t\texisting.policy !== opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== clean(opts.inviterActorId) ||\n\t\t\t\texisting.inviter_display_name !== clean(opts.inviterDisplayName) ||\n\t\t\t\texisting.inviter_device_id !== clean(opts.inviterDeviceId) ||\n\t\t\t\texisting.pending_person_id !== clean(opts.pendingPersonId) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(opts.projectSummaries ? JSON.stringify(opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(opts.projectIntent ? JSON.stringify(opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn existing;\n\t\t};\n\t\tconst renewOperationInvite = (existing: CoordinatorInvite): CoordinatorInvite => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t.run(\n\t\t\t\t\ttoken,\n\t\t\t\t\tdigest,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\topts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\texisting.token,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\tconst renewed = readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = readOperationInvite();\n\t\t\tif (existing) return renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.run(\n\t\t\t\t\tinviteId,\n\t\t\t\t\topts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\topts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\topts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tclean(opts.inviterActorId),\n\t\t\t\t\tclean(opts.inviterDisplayName),\n\t\t\t\t\tclean(opts.inviterDeviceId),\n\t\t\t\t\tclean(opts.pendingPersonId),\n\t\t\t\t\topts.projectSummaries ? JSON.stringify(opts.projectSummaries) : null,\n\t\t\t\t\topts.projectIntent ? JSON.stringify(opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = readOperationInvite();\n\t\t\t\tif (existing) return renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t.get(inviteId);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByOperationId(\n\t\tgroupId: string,\n\t\toperationId: string,\n\t): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites WHERE group_id = ? AND operation_id = ?`)\n\t\t\t.get(groupId, operationId);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByToken(token: string): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites\n\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t AND expires_at > ?`)\n\t\t\t.get(tokenDigest(token), token, new Date().toISOString());\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t)\n\t\t\t.get(tokenDigest(token), token);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await inspectInvite(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tprivate validateRecipientInviteParticipants(\n\t\tinvite: CoordinatorInvite,\n\t\topts: Pick<\n\t\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t\t>,\n\t): (string | null)[] {\n\t\tconst existingEnrollment = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id !== null &&\n\t\t\t\t\texistingEnrollment.identity_id !== opts.identityId))\n\t\t)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t// The immediate transaction keeps both participants unchanged through grant recovery.\n\t\tconst inviterEnrollment = invite.inviter_device_id\n\t\t\t? (this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t: undefined;\n\t\tconst subjects = [\n\t\t\topts.deviceId,\n\t\t\tenrollmentRevocationKeyId(opts.publicKey),\n\t\t\tinvite.inviter_device_id ?? null,\n\t\t\tinviterEnrollment ? enrollmentRevocationKeyId(inviterEnrollment.public_key) : null,\n\t\t];\n\t\tconst revoked = this.db\n\t\t\t.prepare(`SELECT 1 WHERE ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`)\n\t\t\t.get(...subjects);\n\t\tif (revoked) throw new Error(\"device_revoked\");\n\t\treturn subjects;\n\t}\n\n\tprivate getRecipientInviteById(inviteId: string): CoordinatorInvite {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t.get(inviteId) as CoordinatorInvite;\n\t}\n\n\tprivate getRecipientInviteBootstrapGrant(grantId: string): CoordinatorBootstrapGrant | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id,\n\t\t\texpires_at, created_at, created_by, revoked_at FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t.get(grantId) as CoordinatorBootstrapGrant | undefined;\n\t\treturn row ?? null;\n\t}\n\n\tprivate assertRecipientInviteAuthorized(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tsubjects: (string | null)[],\n\t): void {\n\t\tthis.validateRecipientInviteParticipants(invite, opts);\n\t\ttry {\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}) AS revoked,\n\t\t\t\t(${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}) AS owned`)\n\t\t\t\t.get(...subjects, ...subjects.slice(0, 2)) as\n\t\t\t\t| { revoked: number; owned: number }\n\t\t\t\t| undefined;\n\t\t\tif (\n\t\t\t\t!row ||\n\t\t\t\t(\"success\" in row && row.success === false) ||\n\t\t\t\t[row.revoked, row.owned].some((value) => value !== 0 && value !== 1)\n\t\t\t)\n\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\t\tif (row.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tprivate recipientInviteAuthorization(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tsubjects: (string | null)[],\n\t) {\n\t\treturn {\n\t\t\tsql: `NOT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL})`,\n\t\t\tvalues: [...subjects, ...subjects.slice(0, 2)],\n\t\t\tassertAuthorized: () => this.assertRecipientInviteAuthorized(invite, opts, subjects),\n\t\t};\n\t}\n\n\tasync consumeRecipientInvite(\n\t\tinput: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst opts = { ...input };\n\t\tconst consumedAt = normalizeInviteExpiresAt(opts.now);\n\t\tconst deviceDisplayName = opts.deviceDisplayName ?? null;\n\t\tvalidateRecipientOwnerInput(opts);\n\t\tconst preflightInvite = await this.getInviteByTokenForInspection(opts.token);\n\t\tconst preflightInspection = preflightInvite ? await inspectInvite(preflightInvite) : null;\n\t\tconst consistency = await prepareRecipientOwnerConsistency(\n\t\t\t{\n\t\t\t\t...this.schemaBackend,\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t},\n\t\t\topts,\n\t\t);\n\t\treturn this.db\n\t\t\t.transaction((): CoordinatorRecipientInviteAcceptance => {\n\t\t\t\tconst invite = this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(tokenDigest(opts.token), opts.token) as CoordinatorInvite | undefined;\n\t\t\t\tif (\n\t\t\t\t\t!invite ||\n\t\t\t\t\t!preflightInspection ||\n\t\t\t\t\tinvite.invite_id !== preflightInvite?.invite_id ||\n\t\t\t\t\tinvite.reviewed_intent_json !== preflightInvite.reviewed_intent_json ||\n\t\t\t\t\tinvite.reviewed_preview_digest !== preflightInvite.reviewed_preview_digest ||\n\t\t\t\t\tinvite.policy_team_id !== preflightInvite.policy_team_id ||\n\t\t\t\t\tinvite.target_identity_id !== preflightInvite.target_identity_id ||\n\t\t\t\t\tinvite.assigned_identity_id !== preflightInvite.assigned_identity_id ||\n\t\t\t\t\tpreflightInspection.kind !== opts.inviteKind ||\n\t\t\t\t\tinvite.revoked_at\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_invalid\");\n\t\t\t\t}\n\t\t\t\tconst group = this.db\n\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\tif (!group) throw new Error(\"group_not_found\");\n\t\t\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(consumedAt)) {\n\t\t\t\t\tthrow new Error(\"invite_expired\");\n\t\t\t\t}\n\t\t\t\tif (fingerprintPublicKey(opts.publicKey) !== opts.fingerprint) {\n\t\t\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t\t\t}\n\t\t\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(preflightInspection);\n\t\t\t\tif (authoritativeIdentityId !== opts.identityId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst sameBinding =\n\t\t\t\t\tinvite.bound_device_id === opts.deviceId &&\n\t\t\t\t\tinvite.bound_public_key === opts.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === opts.fingerprint;\n\t\t\t\tif (invite.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\t\t\tif (invite.consumed_at && invite.recipient_actor_id !== authoritativeIdentityId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst participantSubjects = this.validateRecipientInviteParticipants(invite, opts);\n\t\t\t\tconst authorization = this.recipientInviteAuthorization(invite, opts, participantSubjects);\n\t\t\t\tconst { sql: authorizationSql, values: authorizationValues } = authorization;\n\t\t\t\tthis.assertRecipientInviteAuthorized(invite, opts, participantSubjects);\n\t\t\t\tthis.assertRecipientOwnerPin(consistency);\n\t\t\t\tconst retained = consistency.retainedRecheck;\n\t\t\t\tconst changed = this.consumeRecipientOwnerToken(invite, opts, {\n\t\t\t\t\tauthorization,\n\t\t\t\t\tconsistency,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t});\n\t\t\t\tlet pendingPin = retained;\n\t\t\t\tconst saved = this.getRecipientInviteById(invite.invite_id);\n\t\t\t\tif (\n\t\t\t\t\tsaved.bound_device_id !== opts.deviceId ||\n\t\t\t\t\tsaved.bound_public_key !== opts.publicKey ||\n\t\t\t\t\tsaved.bound_fingerprint !== opts.fingerprint\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t\t\t}\n\t\t\t\tif (saved.recipient_actor_id !== authoritativeIdentityId)\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\tif (changed === 1) {\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t\t\t\t`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?, 1, ?\n\t\t\t\t\tWHERE ${authorizationSql}\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`,\n\t\t\t\t\t\t\t\tretained,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t...retained.values,\n\t\t\t\t\t\t\tinvite.group_id,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\t...authorizationValues,\n\t\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tpendingPin = this.repairRecipientOwnerIdentity(invite, opts, {\n\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\tconsistency,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthis.assertRecipientInviteAuthorized(invite, opts, participantSubjects);\n\t\t\t\tthis.validateAcceptedRecipientOwner(invite, opts);\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tif (\n\t\t\t\t\tpreflightInspection.kind === \"add_device\" &&\n\t\t\t\t\tinvite.inviter_device_id &&\n\t\t\t\t\t!invite.bootstrap_grant_id &&\n\t\t\t\t\tnew Date(invite.expires_at) > new Date(consumedAt)\n\t\t\t\t) {\n\t\t\t\t\tconst seed = this.db\n\t\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined;\n\t\t\t\t\tif (seed) {\n\t\t\t\t\t\tconst grantId = tokenUrlSafe(12);\n\t\t\t\t\t\tconst claimed = this.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\t trust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\t\t\t WHERE invite_id = ? AND bootstrap_grant_id IS NULL AND ${authorizationSql}`,\n\t\t\t\t\t\t\t\t\tpendingPin,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(...pendingPin.values, grantId, invite.invite_id, ...authorizationValues);\n\t\t\t\t\t\tif (claimed.changes === 1) {\n\t\t\t\t\t\t\tbootstrapGrant = insertBootstrapGrantSync(\n\t\t\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tgroupId: invite.group_id,\n\t\t\t\t\t\t\t\t\tseedDeviceId: seed.device_id,\n\t\t\t\t\t\t\t\t\tworkerDeviceId: opts.deviceId,\n\t\t\t\t\t\t\t\t\texpiresAt: invite.expires_at,\n\t\t\t\t\t\t\t\t\tcreatedBy: authoritativeIdentityId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst savedWithGrant = this.getRecipientInviteById(invite.invite_id);\n\t\t\t\tif (!bootstrapGrant && savedWithGrant.bootstrap_grant_id) {\n\t\t\t\t\tbootstrapGrant = this.getRecipientInviteBootstrapGrant(savedWithGrant.bootstrap_grant_id);\n\t\t\t\t}\n\t\t\t\t// Trigger effects belong to this transaction too; denial rolls back all acceptance writes.\n\t\t\t\tthis.assertRecipientInviteAuthorized(savedWithGrant, opts, participantSubjects);\n\t\t\t\tthis.assertRecipientOwnerPin(pendingPin);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\t\t\tinvite: savedWithGrant,\n\t\t\t\t\treviewed_intent: preflightInspection.reviewed_intent,\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate repairRecipientOwnerIdentity(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\toptions: { authorization: AuthLinkStatement; consistency: NegativeOwnerConsistency },\n\t): AuthLinkStatement {\n\t\tconst { authorization, consistency } = options;\n\t\tconst repaired = this.db\n\t\t\t.prepare(\n\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t`UPDATE enrolled_devices SET identity_id = ?\n\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\t\tAND public_key = ? AND fingerprint = ? AND ${authorization.sql}`,\n\t\t\t\t\tconsistency,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.run(\n\t\t\t\t...consistency.values,\n\t\t\t\topts.identityId,\n\t\t\t\tinvite.group_id,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\t...authorization.values,\n\t\t\t);\n\t\t// A zero-row repair does not consume the initial owner evidence.\n\t\treturn repaired.changes === 1 ? consistency.retainedRecheck : consistency;\n\t}\n\n\tprivate validateAcceptedRecipientOwner(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t) {\n\t\tconst enrollment = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (\n\t\t\tenrollment.public_key !== opts.publicKey ||\n\t\t\tenrollment.fingerprint !== opts.fingerprint ||\n\t\t\tenrollment.identity_id !== opts.identityId\n\t\t)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t}\n\n\tprivate assertRecipientOwnerPin(\n\t\tpredicate: AuthLinkStatement | null,\n\t): asserts predicate is AuthLinkStatement {\n\t\tif (\n\t\t\t!predicate ||\n\t\t\t(this.db.prepare(predicate.sql).get(...predicate.values) as { matches: number } | undefined)\n\t\t\t\t?.matches !== 1\n\t\t)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\n\tprivate consumeRecipientOwnerToken(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\toptions: {\n\t\t\tauthorization: AuthLinkStatement;\n\t\t\tconsistency: AuthLinkStatement;\n\t\t\tconsumedAt: string;\n\t\t},\n\t) {\n\t\tif (invite.consumed_at) return 0;\n\t\tconst { authorization, consistency, consumedAt } = options;\n\t\treturn this.db\n\t\t\t.prepare(\n\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?, recipient_display_name = ?, recipient_device_display_name = ?\n WHERE invite_id = ? AND consumed_at IS NULL AND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id AND g.archived_at IS NULL)\n AND ${authorization.sql}`,\n\t\t\t\t\tconsistency,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.run(\n\t\t\t\t...consistency.values,\n\t\t\t\t`consumed:${invite.invite_id}`,\n\t\t\t\tconsumedAt,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\topts.identityId,\n\t\t\t\topts.recipientDisplayName ?? null,\n\t\t\t\topts.deviceDisplayName ?? null,\n\t\t\t\tinvite.invite_id,\n\t\t\t\tconsumedAt,\n\t\t\t\topts.inviteKind,\n\t\t\t\t...authorization.values,\n\t\t\t).changes;\n\t}\n\n\tprivate prepareProjectInviteGuards(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t) {\n\t\tconst current = this.db\n\t\t\t.prepare(`SELECT public_key FROM enrolled_devices\n\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t.get(invite.group_id, opts.deviceId);\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(current ?? null);\n\t\tconst inviter = invite.inviter_device_id\n\t\t\t? (this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t: undefined;\n\t\tconst incomingKeyId = enrollmentRevocationKeyId(opts.publicKey);\n\t\tconst evidence = projectInviteGuardEvidence(invite, opts, inviter ?? null, {\n\t\t\trecipient: incomingKeyId,\n\t\t\tinviter: inviter ? enrollmentRevocationKeyId(inviter.public_key) : null,\n\t\t});\n\t\tconst guard = legacyProjectInviteOwnershipEvidence(evidence, opts.deviceId, {\n\t\t\tincoming: incomingKeyId,\n\t\t\tcurrent: currentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey),\n\t\t});\n\t\ttry {\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked,\n\t\t\t(${guard.ownershipSql}) AS owned`)\n\t\t\t\t.get(...guard.revocationValues, ...guard.ownershipValues) as\n\t\t\t\t| { revoked: number; owned: number }\n\t\t\t\t| undefined;\n\t\t\tif (!row || [row.revoked, row.owned].some((value) => value !== 0 && value !== 1))\n\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\t\tif (row.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t\tthis.validateRecipientInviteParticipants(invite, {\n\t\t\t...opts,\n\t\t\tidentityId: opts.recipientActorId,\n\t\t});\n\t\treturn guard;\n\t}\n\n\tprivate assertProjectInviteEligible(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t\tguard: ReturnType<BetterSqliteCoordinatorStore[\"prepareProjectInviteGuards\"]>,\n\t): void {\n\t\tconst state = this.db\n\t\t\t.prepare(`SELECT i.revoked_at, g.group_id, g.archived_at\n\t\t\tFROM coordinator_invites i LEFT JOIN groups g ON g.group_id = i.group_id\n\t\t\tWHERE i.invite_id = ?`)\n\t\t\t.get(invite.invite_id) as\n\t\t\t| {\n\t\t\t\t\trevoked_at: string | null;\n\t\t\t\t\tgroup_id: string | null;\n\t\t\t\t\tarchived_at: string | null;\n\t\t\t }\n\t\t\t| undefined;\n\t\tif (!state || state.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (!state.group_id) throw new Error(\"group_not_found\");\n\t\tif (state.archived_at) throw new Error(\"group_archived\");\n\t\tthis.prepareProjectInviteGuards(invite, opts);\n\t\tconst eligible = this.db\n\t\t\t.prepare(`SELECT 1 WHERE ${guard.boundEligibilitySql}`)\n\t\t\t.get(...guard.boundEligibilityValues);\n\t\tif (!eligible) throw new Error(\"invite_acceptance_incomplete\");\n\t}\n\n\tasync consumeProjectInvite(\n\t\tinput: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tconst opts = captureLegacyProjectInviteInput(input);\n\t\tconst consumedAt = normalizeInviteExpiresAt(opts.now);\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tlet invite = this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(tokenDigest(opts.token), opts.token) as CoordinatorInvite | undefined;\n\t\t\t\tif (!invite?.operation_id || !invite.project_intent_json || invite.revoked_at) {\n\t\t\t\t\tthrow new Error(\"invite_invalid\");\n\t\t\t\t}\n\t\t\t\tconst group = this.db\n\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\tif (!group) throw new Error(\"group_not_found\");\n\t\t\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\t\t\tif (invite.operation_id !== opts.operationId) throw new Error(\"invite_invalid\");\n\t\t\t\tif (fingerprintPublicKey(opts.publicKey) !== opts.fingerprint) {\n\t\t\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t\t\t}\n\t\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(consumedAt)) {\n\t\t\t\t\tthrow new Error(\"invite_expired\");\n\t\t\t\t}\n\t\t\t\tconst sameBinding =\n\t\t\t\t\tinvite.bound_device_id === opts.deviceId &&\n\t\t\t\t\tinvite.bound_public_key === opts.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === opts.fingerprint;\n\t\t\t\tif (invite.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\t\t\tif (\n\t\t\t\t\tinvite.consumed_at &&\n\t\t\t\t\t(invite.recipient_actor_id !== opts.recipientActorId ||\n\t\t\t\t\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\t\t\t\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName)\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst guard = this.prepareProjectInviteGuards(invite, opts);\n\t\t\t\tlet accepted = false;\n\t\t\t\tif (!invite.consumed_at) {\n\t\t\t\t\tconst changed = this.db\n\t\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\t\tWHERE invite_id = ? AND consumed_at IS NULL\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\t\tAND ${guard.eligibilitySql}`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t`consumed:${invite.invite_id}`,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\topts.recipientActorId,\n\t\t\t\t\t\t\topts.recipientDisplayName,\n\t\t\t\t\t\t\topts.deviceDisplayName,\n\t\t\t\t\t\t\tinvite.invite_id,\n\t\t\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t\t);\n\t\t\t\t\taccepted = changed.changes === 1;\n\t\t\t\t\tinvite = this.db\n\t\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t\t\t.get(invite.invite_id) as CoordinatorInvite;\n\t\t\t\t\tif (!accepted) {\n\t\t\t\t\t\tconst currentGroup = this.db\n\t\t\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\t\t\tif (currentGroup?.archived_at) throw new Error(\"group_archived\");\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\t\t\t\t\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\t\t\t\t\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.recipient_actor_id !== opts.recipientActorId ||\n\t\t\t\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\t\t\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\n\t\t\t\tif (accepted) {\n\t\t\t\t\tthis.assertProjectInviteEligible(invite, opts, guard);\n\t\t\t\t\tthis.enrollDeviceSync(invite.group_id, {\n\t\t\t\t\t\tdeviceId: opts.deviceId,\n\t\t\t\t\t\tpublicKey: opts.publicKey,\n\t\t\t\t\t\tfingerprint: opts.fingerprint,\n\t\t\t\t\t\tidentityId: opts.recipientActorId,\n\t\t\t\t\t\tdisplayName: opts.deviceDisplayName,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\t\t\t\t\t\tAND public_key = ? AND fingerprint = ? AND ${guard.boundEligibilitySql}`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\topts.recipientActorId,\n\t\t\t\t\t\t\tinvite.group_id,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst seed = invite.inviter_device_id\n\t\t\t\t\t? (this.db\n\t\t\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t\t\t: undefined;\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tif (\n\t\t\t\t\tseed &&\n\t\t\t\t\t!invite.bootstrap_grant_id &&\n\t\t\t\t\tnew Date(invite.expires_at) > new Date(consumedAt)\n\t\t\t\t) {\n\t\t\t\t\tconst grantId = tokenUrlSafe(12);\n\t\t\t\t\tconst claimed = this.db\n\t\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE invite_id = ? AND bootstrap_grant_id IS NULL AND bound_device_id = ?\n\t\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t\t\t.run(grantId, invite.invite_id, opts.deviceId, ...guard.boundEligibilityValues);\n\t\t\t\t\tif (claimed.changes === 1) {\n\t\t\t\t\t\tbootstrapGrant = insertBootstrapGrantSync(\n\t\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tgroupId: invite.group_id,\n\t\t\t\t\t\t\t\tseedDeviceId: seed.device_id,\n\t\t\t\t\t\t\t\tworkerDeviceId: opts.deviceId,\n\t\t\t\t\t\t\t\texpiresAt: invite.expires_at,\n\t\t\t\t\t\t\t\tcreatedBy: invite.inviter_actor_id,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst saved = this.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t\t.get(invite.invite_id) as CoordinatorInvite;\n\t\t\t\tconst enrollment = this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\t// Trigger effects are inside the immediate transaction; denial rolls back every write.\n\t\t\t\tthis.assertProjectInviteEligible(saved, opts, guard);\n\t\t\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\t\t\tif (enrollment.identity_id !== opts.recipientActorId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tif (!bootstrapGrant && saved.bootstrap_grant_id) {\n\t\t\t\t\tbootstrapGrant =\n\t\t\t\t\t\t(this.db\n\t\t\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\t\tcreated_at, created_by, revoked_at FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t\t\t\t.get(saved.bootstrap_grant_id) as CoordinatorBootstrapGrant | undefined) ?? null;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: accepted ? (\"accepted\" as const) : (\"existing\" as const),\n\t\t\t\t\tinvite: saved,\n\t\t\t\t\tenrollment,\n\t\t\t\t\tseed_enrollment: seed ?? null,\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tasync listInvites(groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t.all(groupId)\n\t\t\t.map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\topts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.run(\n\t\t\t\trequestId,\n\t\t\t\topts.groupId,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\topts.displayName ?? null,\n\t\t\t\topts.token,\n\t\t\t\tnow,\n\t\t\t);\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t.get(requestId);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(groupId: string, status = \"pending\"): Promise<CoordinatorJoinRequest[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t.all(groupId, status)\n\t\t\t.map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\topts = {\n\t\t\t...opts,\n\t\t\tbootstrapGrant: opts.bootstrapGrant ? { ...opts.bootstrapGrant } : opts.bootstrapGrant,\n\t\t};\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst row = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t.get(opts.requestId) as (CoordinatorJoinRequest & { public_key: string }) | undefined;\n\t\t\t\tif (!row) return null;\n\t\t\t\tif (row.status !== \"pending\")\n\t\t\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t\t\tconst bootstrapGrantRequest = normalizeCoordinatorBootstrapGrantRequest(\n\t\t\t\t\topts.bootstrapGrant,\n\t\t\t\t);\n\t\t\t\tconst reviewedAt = nowISO();\n\t\t\t\tconst nextStatus = opts.approved ? \"approved\" : \"denied\";\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tconst guard = opts.approved\n\t\t\t\t\t? this.prepareJoinApprovalSync(row, bootstrapGrantRequest)\n\t\t\t\t\t: null;\n\t\t\t\tconst transition = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\tWHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.run(nextStatus, reviewedAt, opts.reviewedBy ?? null, opts.requestId);\n\t\t\t\tif (transition.changes !== 1) throw new Error(\"join_review_incomplete\");\n\t\t\t\tif (guard) {\n\t\t\t\t\tbootstrapGrant = this.applyJoinApprovalSync(\n\t\t\t\t\t\trow,\n\t\t\t\t\t\tguard,\n\t\t\t\t\t\tbootstrapGrantRequest,\n\t\t\t\t\t\treviewedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst updated = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t.get(opts.requestId);\n\t\t\t\tif (!updated) throw new Error(\"join_review_incomplete\");\n\t\t\t\treturn {\n\t\t\t\t\t...rowToRecord<CoordinatorJoinRequestReviewResult>(updated),\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate prepareJoinApprovalSync(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tbootstrap: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t) {\n\t\tlet seed: CoordinatorEnrollment | null = null;\n\t\tif (bootstrap) {\n\t\t\tseed =\n\t\t\t\t(this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT * FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(row.group_id, bootstrap.seedDeviceId) as CoordinatorEnrollment | undefined) ?? null;\n\t\t\tif (!seed) throw new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\tif (seed.device_id === row.device_id)\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t}\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.get(row.group_id, row.device_id) ?? null,\n\t\t);\n\t\tconst guard = joinReviewGuardEvidence(\n\t\t\trow,\n\t\t\tseed,\n\t\t\t{\n\t\t\t\trecipient: enrollmentRevocationKeyId(row.public_key),\n\t\t\t\tseed: seed ? enrollmentRevocationKeyId(seed.public_key) : null,\n\t\t\t\tcurrent: currentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey),\n\t\t\t},\n\t\t\tcurrentPublicKey,\n\t\t);\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\treturn guard;\n\t}\n\n\tprivate assertJoinApprovalCurrentSync(guard: ReturnType<typeof joinReviewGuardEvidence>) {\n\t\tif (this.db.prepare(`SELECT 1 WHERE ${guard.revocationSql}`).get(...guard.revocationValues))\n\t\t\tthrow new Error(\"device_revoked\");\n\t\tlet owned: unknown;\n\t\ttry {\n\t\t\towned = this.db.prepare(`SELECT 1 WHERE ${guard.ownershipSql}`).get(...guard.ownershipValues);\n\t\t} catch {\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t}\n\t\tif (owned) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\tif (!this.db.prepare(`SELECT 1 WHERE ${guard.eligibilitySql}`).get(...guard.eligibilityValues))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n\n\tprivate applyJoinApprovalSync(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\tbootstrap: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t\treviewedAt: string,\n\t) {\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tif (!this.db.prepare(`SELECT 1 WHERE ${guard.sourceSql}`).get(...guard.sourceValues))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\tthis.enrollDeviceSync(row.group_id, {\n\t\t\tdeviceId: row.device_id,\n\t\t\tfingerprint: row.fingerprint,\n\t\t\tpublicKey: row.public_key,\n\t\t\tdisplayName: (row.display_name ?? \"\").trim() || null,\n\t\t});\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tconst grant = bootstrap\n\t\t\t? insertBootstrapGrantSync(this.db, {\n\t\t\t\t\t...bootstrap,\n\t\t\t\t\tgroupId: row.group_id,\n\t\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t\t})\n\t\t\t: null;\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tconst complete = this.db\n\t\t\t.prepare(`SELECT 1 FROM coordinator_join_requests jr\n\t\t\tJOIN enrolled_devices e ON e.group_id = jr.group_id AND e.device_id = jr.device_id\n\t\t\tWHERE jr.request_id = ? AND jr.status = 'approved' AND jr.reviewed_at = ?\n\t\t\tAND e.public_key = ? AND e.fingerprint = ? AND e.enabled = 1`)\n\t\t\t.get(row.request_id, reviewedAt, row.public_key, row.fingerprint);\n\t\tif (!complete) throw new Error(\"join_review_incomplete\");\n\t\treturn grant;\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = String(opts.groupId ?? \"\").trim();\n\t\tconst requestingDeviceId = String(opts.requestingDeviceId ?? \"\").trim();\n\t\tconst requestedDeviceId = String(opts.requestedDeviceId ?? \"\").trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\treturn this.db.transaction(() => {\n\t\t\tconst now = nowISO();\n\t\t\tif (hasExpectedIncomingRequestId) {\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.run(now, expectedIncomingRequestId, groupId, requestedDeviceId, requestingDeviceId);\n\t\t\t\tif (result.changes !== 1) {\n\t\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t\t}\n\t\t\t\tconst completed = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.get(expectedIncomingRequestId);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tconst existing = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ?\n\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t LIMIT 1`)\n\t\t\t\t.get(groupId, requestingDeviceId, requestedDeviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\t\t}\n\t\t\tconst reverse = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ?\n\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t LIMIT 1`)\n\t\t\t\t.get(groupId, requestedDeviceId, requestingDeviceId);\n\t\t\tif (reverse) {\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?`)\n\t\t\t\t\t.run(now, (reverse as CoordinatorReciprocalApproval).request_id);\n\t\t\t\tconst completed = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.get((reverse as CoordinatorReciprocalApproval).request_id);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tconst requestId = tokenUrlSafe(12);\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.run(requestId, groupId, requestingDeviceId, requestedDeviceId, now);\n\t\t\tconst created = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.get(requestId);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t\t})();\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst input = normalizeCoordinatorBootstrapGrantInput(opts);\n\t\ttry {\n\t\t\treturn this.db\n\t\t\t\t.transaction(() => {\n\t\t\t\t\tconst revoked = this.db.prepare(BOOTSTRAP_PARTICIPANTS_REVOKED_SQL);\n\t\t\t\t\tif (revoked.get(input.seedDeviceId, null, input.workerDeviceId, null)) {\n\t\t\t\t\t\tthrow new Error(\"device_revoked\");\n\t\t\t\t\t}\n\t\t\t\t\tconst source = this.db.prepare(BOOTSTRAP_PARTICIPANT_SOURCE_SQL);\n\t\t\t\t\tconst seed = captureBootstrapParticipantSource(\n\t\t\t\t\t\t(source.get(input.groupId, input.seedDeviceId) as\n\t\t\t\t\t\t\t| BootstrapParticipantSource\n\t\t\t\t\t\t\t| undefined) ?? null,\n\t\t\t\t\t);\n\t\t\t\t\tconst worker = captureBootstrapParticipantSource(\n\t\t\t\t\t\t(source.get(input.groupId, input.workerDeviceId) as\n\t\t\t\t\t\t\t| BootstrapParticipantSource\n\t\t\t\t\t\t\t| undefined) ?? null,\n\t\t\t\t\t);\n\t\t\t\t\tconst subjects = [\n\t\t\t\t\t\tinput.seedDeviceId,\n\t\t\t\t\t\tseed ? enrollmentRevocationKeyId(seed.public_key) : null,\n\t\t\t\t\t\tinput.workerDeviceId,\n\t\t\t\t\t\tworker ? enrollmentRevocationKeyId(worker.public_key) : null,\n\t\t\t\t\t];\n\t\t\t\t\tif (revoked.get(...subjects)) throw new Error(\"device_revoked\");\n\t\t\t\t\tconst values = bootstrapRawInsertValues(\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\t{ grantId: tokenUrlSafe(12), createdAt: nowISO() },\n\t\t\t\t\t\t{ seed, worker },\n\t\t\t\t\t\tsubjects,\n\t\t\t\t\t);\n\t\t\t\t\tconst row = this.db.prepare(BOOTSTRAP_RAW_INSERT_SQL).get(...values);\n\t\t\t\t\t// A trigger may revoke a participant during insertion; abort the entire transaction.\n\t\t\t\t\tif (revoked.get(...subjects)) throw new Error(\"device_revoked\");\n\t\t\t\t\tif (!row) throw new Error(\"bootstrap_grant_write_incomplete\");\n\t\t\t\t\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"device_revoked\") throw error;\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tprivate getScopeSync(scopeId: string): CoordinatorScope | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t.get(scopeId);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate getScopeMembershipSync(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): CoordinatorScopeMembership | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t.get(scopeId, deviceId);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCoordinatorCreateScopeInput(opts);\n\t\tif (this.getScopeSync(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.run(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t);\n\t\tconst scope = this.getScopeSync(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? this.getScopeSync(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeCoordinatorUpdateScopeInput(opts, existing);\n\t\tthis.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.run(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t);\n\t\treturn this.getScopeSync(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`)\n\t\t\t.all(...params)\n\t\t\t.map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync getScopeAuthorization(\n\t\traw: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureScopeAuthorizationInput(raw);\n\t\t\treturn this.db\n\t\t\t\t.transaction((): CoordinatorScopeAuthorizationResult => {\n\t\t\t\t\tconst scope = this.getScopeSync(input.scopeId);\n\t\t\t\t\tif (!scope) return { kind: \"rejected\", error: \"scope_not_found\" };\n\t\t\t\t\trequireScopeAuthorizationRecord(scope, SCOPE_FIELDS);\n\t\t\t\t\tconst error = scopeAuthorizationError(scope, input.groupId);\n\t\t\t\t\tif (error) return { kind: \"rejected\", error };\n\t\t\t\t\tconst group = this.db\n\t\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t\t.get(input.groupId) as { archived_at: string | null } | undefined;\n\t\t\t\t\tif (!group) return { kind: \"rejected\", error: \"scope_source_mismatch\" };\n\t\t\t\t\tif (group.archived_at !== null) return { kind: \"rejected\", error: \"group_archived\" };\n\t\t\t\t\tconst members = this.captureScopeAuthorizationMembers(scope, input.groupId);\n\t\t\t\t\tconst current = this.db\n\t\t\t\t\t\t.prepare(READ_SCOPE_AUTHORIZATION_SQL)\n\t\t\t\t\t\t.get(JSON.stringify([scope]), JSON.stringify(members)) as\n\t\t\t\t\t\t| (CoordinatorScope & { members_json: string })\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (!current) return { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t\t\t\trequireScopeAuthorizationRecord(current, SCOPE_FIELDS);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"authorized\",\n\t\t\t\t\t\tauthorizationVersion: 1,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tmembers: parseScopeAuthorizationMembers(current.members_json, members),\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\treturn { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t}\n\t}\n\n\tprivate captureScopeAuthorizationMembers(\n\t\tscope: CoordinatorScope,\n\t\tgroupId: string,\n\t): CapturedScopeMember[] {\n\t\tconst memberships = this.db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT * FROM coordinator_scope_memberships WHERE scope_id = ? ORDER BY device_id ASC\",\n\t\t\t)\n\t\t\t.all(scope.scope_id) as CoordinatorScopeMembership[];\n\t\tconst captured: Array<Omit<CapturedScopeMember, \"keyId\">> = [];\n\t\tfor (const membership of memberships) {\n\t\t\trequireScopeAuthorizationRecord(membership, [\"status\"]);\n\t\t\tif (membership.status !== \"active\") continue;\n\t\t\trequireScopeAuthorizationRecord(membership, MEMBERSHIP_FIELDS);\n\t\t\tif (!isCurrentScopeMember(scope, membership)) continue;\n\t\t\tconst enrollment = this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${ENROLLMENT_FIELDS.join(\", \")} FROM enrolled_devices WHERE group_id = ? AND device_id = ?`,\n\t\t\t\t)\n\t\t\t\t.get(groupId, membership.device_id) as CoordinatorEnrollment | undefined;\n\t\t\tif (!enrollment) continue;\n\t\t\trequireScopeAuthorizationRecord(enrollment, ENROLLMENT_FIELDS);\n\t\t\tif (enrollment.enabled !== 1) continue;\n\t\t\tcaptured.push({ membership: { ...membership }, enrollment: { ...enrollment } });\n\t\t}\n\t\t// Capture the complete source set before any hash hook can change another tuple.\n\t\treturn captured.flatMap((member) => {\n\t\t\tconst keyId = enrollmentRevocationKeyId(member.enrollment.public_key);\n\t\t\treturn keyId === null ? [] : [{ ...member, keyId }];\n\t\t});\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst grantScopeMembershipTransaction = () => {\n\t\t\tconst receipt = getMembershipEffectReceiptSync(this.db, effectId);\n\t\t\tif (receipt) {\n\t\t\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\t\t\treturn membershipFromEffectReceipt(receipt);\n\t\t\t}\n\t\t\tconst scopeId = clean(opts.scopeId);\n\t\t\tconst deviceId = clean(opts.deviceId);\n\t\t\tconst scope = scopeId ? this.getScopeSync(scopeId) : null;\n\t\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\t\tconst existing = scopeId && deviceId ? this.getScopeMembershipSync(scopeId, deviceId) : null;\n\t\t\tconst normalized = normalizeCoordinatorGrantScopeMembershipInput(opts, scope, existing);\n\t\t\tassertScopeMembershipDeviceEnrolled(this.db, normalized.groupId, normalized.deviceId);\n\t\t\tconst now = nowISO();\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\t\trole = excluded.role,\n\t\t\t\t\t\tstatus = 'active',\n\t\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t\t OR (\n\t\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t\t )`)\n\t\t\t\t.run(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\tif (result.changes <= 0) {\n\t\t\t\tthrow new Error(\"scope membership grant was not applied.\");\n\t\t\t}\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.get(normalized.scopeId, normalized.deviceId);\n\t\t\tconst membership = rowToRecord<CoordinatorScopeMembership>(row);\n\t\t\tinsertMembershipAuditSync(this.db, {\n\t\t\t\teffectId,\n\t\t\t\taction: \"grant\",\n\t\t\t\tcurrent: membership,\n\t\t\t\tprevious: existing,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\teffectId,\n\t\t\t\taction: \"grant\",\n\t\t\t\trequestJson,\n\t\t\t\tapplied: true,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tmembership,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t\treturn membership;\n\t\t};\n\t\treturn this.db.transaction(grantScopeMembershipTransaction).immediate();\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst receipt = getMembershipEffectReceiptSync(this.db, effectId);\n\t\t\t\tif (receipt) {\n\t\t\t\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\t\t\t\treturn receipt.outcome_applied === 1;\n\t\t\t\t}\n\t\t\t\tconst membershipEpoch =\n\t\t\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\t\t\tconst requestedGroupId = clean(opts.groupId);\n\t\t\t\tconst scope = requestedGroupId ? this.getScopeSync(scopeId) : null;\n\t\t\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t\t\t}\n\t\t\t\tconst existing = this.getScopeMembershipSync(scopeId, deviceId);\n\t\t\t\tconst now = nowISO();\n\t\t\t\tif (!existing) {\n\t\t\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\t\t\teffectId,\n\t\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\t\trequestJson,\n\t\t\t\t\t\tapplied: false,\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tmembership: null,\n\t\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\t});\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (membershipEpoch != null && membershipEpoch <= existing.membership_epoch) {\n\t\t\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t\t\t}\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\t\tclean(opts.manifestHash),\n\t\t\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\texisting.membership_epoch,\n\t\t\t\t\t\texisting.status,\n\t\t\t\t\t);\n\t\t\t\tif (result.changes <= 0) return false;\n\t\t\t\tconst membership = this.getScopeMembershipSync(scopeId, deviceId);\n\t\t\t\tif (!membership) throw new Error(\"scope membership revoke was not applied.\");\n\t\t\t\tinsertMembershipAuditSync(this.db, {\n\t\t\t\t\teffectId,\n\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\tcurrent: membership,\n\t\t\t\t\tprevious: existing,\n\t\t\t\t\tactorType: clean(opts.actorType),\n\t\t\t\t\tactorId: clean(opts.actorId),\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t});\n\t\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\t\teffectId,\n\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\trequestJson,\n\t\t\t\t\tapplied: true,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembership,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t.all(normalizedScopeId)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedDeviceId = clean(deviceId);\n\t\tif (!normalizedDeviceId) throw new Error(\"deviceId is required.\");\n\t\t// Served by idx_coordinator_scope_memberships_device_status.\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE device_id = ? ${statusWhere}\n\t\t\t\t ORDER BY scope_id ASC`)\n\t\t\t.all(normalizedDeviceId)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeCoordinatorAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn this.db\n\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t LIMIT ?`)\n\t\t\t.all(...params)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t.get(grantId);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync getBootstrapGrantAuthorization(\n\t\traw: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureBootstrapAuthorizationInput(raw);\n\t\t\treturn this.db\n\t\t\t\t.transaction(() => {\n\t\t\t\t\tconst source = this.db.prepare(BOOTSTRAP_AUTHORIZATION_SOURCE_SQL).get(input.grantId) as\n\t\t\t\t\t\t| BootstrapAuthorizationRow\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tconst sourceError = bootstrapAuthorizationSourceError(input, source ?? null);\n\t\t\t\t\tif (sourceError) return rejectBootstrapAuthorization(sourceError);\n\t\t\t\t\tif (!source) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t\t\t\tconst captured = { ...source };\n\t\t\t\t\tconst decision = bootstrapAuthorizationDecision(input, captured, {\n\t\t\t\t\t\tseed:\n\t\t\t\t\t\t\tcaptured.seed_enrollment_public_key === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: enrollmentRevocationKeyId(captured.seed_enrollment_public_key),\n\t\t\t\t\t\tworker:\n\t\t\t\t\t\t\tcaptured.worker_enrollment_public_key === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: enrollmentRevocationKeyId(captured.worker_enrollment_public_key),\n\t\t\t\t\t});\n\t\t\t\t\tconst current = this.db.prepare(decision.sql).get(...decision.values) as\n\t\t\t\t\t\t| BootstrapAuthorizationRow\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\treturn bootstrapAuthorizationResult(current ?? null);\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t}\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t.all(groupId)\n\t\t\t.map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t WHERE grant_id = ?`)\n\t\t\t.run(revokedAt, grantId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = String(opts.status ?? \"pending\").trim() || \"pending\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t.all(opts.groupId, opts.deviceId, status)\n\t\t\t.map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync createLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst group = await this.getGroup(normalizedGroupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst manifestJson = canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest);\n\t\tconst normalized = JSON.parse(manifestJson) as CoordinatorLegacyTeamCompletionManifestV1;\n\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(normalized);\n\t\tconst existing = this.readStoredLegacyCompletion(normalizedGroupId, normalized.candidate_ref);\n\t\tif (existing)\n\t\t\treturn legacyCompletionWriteResult(existing.manifest_json, manifestJson, \"existing\");\n\t\tconst coordinatorId = await this.requireLegacyTeamCompletionSources(\n\t\t\tnormalizedGroupId,\n\t\t\tnormalized,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst ownerProof = await this.prepareLegacyTeamCompletionOwnerProof(\n\t\t\tnormalizedGroupId,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst { result, stored, denial } = this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`${LEGACY_OWNER_INPUT_SQL}${ownerProof.ctes}\n\t\t\tINSERT OR IGNORE INTO coordinator_legacy_team_completions(\n\t\t\t\tgroup_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n\t\t\t) SELECT ?, ?, ?, ?, ?, ?\n\t\t\t FROM groups\n\t\t\t WHERE group_id = ? AND archived_at IS NULL\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1\n\t\t\t FROM json_each(?, '$.project_mappings') AS requested\n\t\t\t LEFT JOIN coordinator_scopes AS scope\n\t\t\t ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t AND scope.coordinator_id = ?\n\t\t\t AND scope.group_id = ?\n\t\t\t\t AND scope.status = 'active'\n\t\t\t WHERE scope.scope_id IS NULL\n\t\t\t )\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t WHERE enrolled.group_id = ?\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n\t\t\t AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n\t\t\t AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n\t\t\t )\n\t\t\t )\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t WHERE json_extract(requested.value, '$.decision') = 'included'\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t WHERE enrolled.group_id = ?\n\t\t\t AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n\t\t\t AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n\t\t\t AND enrolled.enabled = 1\n\t\t\t )\n\t\t\t ) AND ${LEGACY_OWNER_SOURCE_CURRENT_SQL}\n\t\t\t\t AND (${ownerProof.currentSql}) AND (${ownerProof.compatibleSql})`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\t...ownerProof.values,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tnormalized.candidate_ref,\n\t\t\t\t\t\tnormalized.version,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tnormalized.completed_at,\n\t\t\t\t\t\tnowISO(),\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t);\n\t\t\t\tconst stored = this.readStoredLegacyCompletion(normalizedGroupId, normalized.candidate_ref);\n\t\t\t\tconst denial = stored\n\t\t\t\t\t? null\n\t\t\t\t\t: (this.db.prepare(ownerProof.denialSql).get(...ownerProof.values) as { denial: string });\n\t\t\t\treturn { result, stored, denial };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (!stored) {\n\t\t\tawait this.requireLegacyTeamCompletionSources(normalizedGroupId, normalized, manifestJson);\n\t\t\tif (denial?.denial === \"completion_conflict\") {\n\t\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t\t}\n\t\t\tthrow new Error(\"completion_manifest_unavailable\");\n\t\t}\n\t\treturn legacyCompletionWriteResult(\n\t\t\tstored.manifest_json,\n\t\t\tmanifestJson,\n\t\t\tresult.changes === 1 ? \"created\" : \"existing\",\n\t\t);\n\t}\n\n\tprivate readStoredLegacyCompletion(groupId: string, candidateRef: string) {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t.get(groupId, candidateRef) as { manifest_json: string } | undefined;\n\t}\n\n\tprivate async prepareLegacyTeamCompletionOwnerProof(groupId: string, manifestJson: string) {\n\t\tconst keyMetadata = await legacyOwnerKeyMetadata(\n\t\t\tthis.db.prepare(LEGACY_OWNER_KEYS_SQL).all(manifestJson, groupId) as { public_key: string }[],\n\t\t);\n\t\tconst proof = legacyCompletionOwnerProofSql(\n\t\t\tawait captureLegacyCompletionOwnerProof({\n\t\t\t\tbackend: {\n\t\t\t\t\t...this.schemaBackend,\n\t\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t\t},\n\t\t\t\tgroupId,\n\t\t\t\tmanifestJson,\n\t\t\t\tkeyMetadata,\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\t...proof,\n\t\t\tvalues: [manifestJson, groupId, keyMetadata, ...proof.values],\n\t\t\tdenialSql: `${LEGACY_OWNER_INPUT_SQL}${proof.ctes}\n\t\t SELECT CASE WHEN NOT (${LEGACY_OWNER_SOURCE_CURRENT_SQL}) OR NOT (${proof.currentSql})\n\t\t THEN 'completion_manifest_unavailable'\n\t\t WHEN NOT (${proof.compatibleSql}) THEN 'completion_conflict'\n\t\t ELSE 'completion_manifest_unavailable' END AS denial`,\n\t\t};\n\t}\n\n\tprivate async requireLegacyTeamCompletionSources(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tmanifestJson: string,\n\t): Promise<string | null> {\n\t\tconst group = await this.getGroup(groupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst bindings = this.db\n\t\t\t.prepare(`SELECT DISTINCT requested.scope_id, scope.authority_type,\n\t\t\t\tscope.coordinator_id, scope.group_id, scope.status\n\t\t\t FROM (SELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\tFROM json_each(?, '$.project_mappings')) AS requested\n\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t.all(manifestJson) as CoordinatorLegacyTeamCompletionScopeBinding[];\n\t\treturn requireCoordinatorLegacyTeamCompletionScopeBindings(manifest, groupId, bindings);\n\t}\n\n\tasync getLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tconst normalizedCandidateRef =\n\t\t\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef(candidateRef);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t.get(normalizedGroupId, normalizedCandidateRef) as { manifest_json: string } | undefined;\n\t\treturn row\n\t\t\t? normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json))\n\t\t\t: null;\n\t}\n\n\tasync listLegacyTeamCompletions(\n\t\tgroupIds: string[],\n\t): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t\tconst normalizedGroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(groupIds);\n\t\tif (normalizedGroupIds.length === 0) return [];\n\t\tconst placeholders = normalizedGroupIds.map(() => \"?\").join(\", \");\n\t\tconst stats = this.db\n\t\t\t.prepare(`SELECT\n\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\tFROM coordinator_legacy_team_completions\n\t\t\tWHERE group_id IN (${placeholders})`)\n\t\t\t.get(...normalizedGroupIds) as {\n\t\t\trecord_count: number;\n\t\t\tbatch_bytes: number;\n\t\t\tmax_manifest_bytes: number;\n\t\t};\n\t\tif (\n\t\t\tstats.record_count > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS ||\n\t\t\tstats.batch_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES ||\n\t\t\tstats.max_manifest_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t\t) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst rows = this.db\n\t\t\t.prepare(`WITH completion_stats AS (\n\t\t\t\tSELECT\n\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id IN (${placeholders})\n\t\t\t)\n\t\t\tSELECT completions.group_id, completions.manifest_json\n\t\t\tFROM coordinator_legacy_team_completions AS completions\n\t\t\tCROSS JOIN completion_stats\n\t\t\tWHERE completions.group_id IN (${placeholders})\n\t\t\t\t AND completion_stats.record_count <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS}\n\t\t\t\t AND completion_stats.batch_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES}\n\t\t\t\t AND completion_stats.max_manifest_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t AND LENGTH(completions.manifest_json) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\tORDER BY completions.group_id, completions.completed_at, completions.candidate_ref\n\t\t\t\tLIMIT ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1}`)\n\t\t\t.all(...normalizedGroupIds, ...normalizedGroupIds) as Array<{\n\t\t\tgroup_id: string;\n\t\t\tmanifest_json: string;\n\t\t}>;\n\t\tif (rows.length === 0 && stats.record_count > 0) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst batchBytes = rows.reduce(\n\t\t\t(total, row) =>\n\t\t\t\ttotal + Buffer.byteLength(row.group_id) + Buffer.byteLength(row.manifest_json),\n\t\t\t0,\n\t\t);\n\t\tif (batchBytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\treturn rows.map((row) => ({\n\t\t\tgroup_id: row.group_id,\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json)),\n\t\t}));\n\t}\n\n\tasync captureAuthControllerLegacyHistory(input: ControllerHistoryInput) {\n\t\treturn captureControllerHistory(\n\t\t\tinput,\n\t\t\tasync <T>(sql: string, values: string[]) => this.db.prepare(sql).all(...values) as T[],\n\t\t);\n\t}\n\n\tasync upsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeCoordinatorAddresses([], opts.addresses);\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.run(\n\t\t\t\topts.groupId,\n\t\t\t\topts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(opts.capabilities ?? {}),\n\t\t\t);\n\t\treturn {\n\t\t\tgroup_id: opts.groupId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\tgroupId: string,\n\t\trequestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\ttry {\n\t\t\treturn this.readGroupPeers(groupId, requestingDeviceId);\n\t\t} catch {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n\n\tprivate readGroupPeers(groupId: string, requestingDeviceId: string): CoordinatorPeerRecord[] {\n\t\tconst now = new Date();\n\t\tconst rows = this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst captured = capturePeerEnrollments(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(CAPTURE_PEER_ENROLLMENTS_SQL)\n\t\t\t\t\t\t.all(groupId, requestingDeviceId) as CapturedPeerEnrollment[],\n\t\t\t\t);\n\t\t\t\tconst candidates = captured.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tkeyId: enrollmentRevocationKeyId(row.public_key),\n\t\t\t\t}));\n\t\t\t\treturn requirePeerDiscoveryRows(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(READ_CURRENT_PEERS_SQL)\n\t\t\t\t\t\t.all(JSON.stringify(candidates), groupId, requestingDeviceId),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.immediate();\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeCoordinatorAddresses(\n\t\t\t\t\t\t[],\n\t\t\t\t\t\tJSON.parse((row.addresses_json as string) || \"[]\") as string[],\n\t\t\t\t\t);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse((row.capabilities_json as string) || \"{}\") as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\tunknown\n\t\t\t\t>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","import { getCodememEnvOverrides, readCodememConfigFile } from \"./observer-config.js\";\n\ntype ConfigRecord = Record<string, unknown>;\n\nfunction clean(value: unknown): string {\n\treturn typeof value === \"string\" ? value.trim() : \"\";\n}\n\nfunction parseIntOr(value: unknown, fallback: number): number {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return Math.trunc(value);\n\tif (typeof value === \"string\" && /^-?\\d+$/.test(value.trim()))\n\t\treturn Number.parseInt(value.trim(), 10);\n\treturn fallback;\n}\n\nfunction parseBoolOr(value: unknown, fallback: boolean): boolean {\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\tif ([\"1\", \"true\", \"yes\", \"on\"].includes(normalized)) return true;\n\t\tif ([\"0\", \"false\", \"no\", \"off\"].includes(normalized)) return false;\n\t}\n\treturn fallback;\n}\n\nfunction parseStringList(value: unknown): string[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.filter((item): item is string => typeof item === \"string\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t}\n\tif (typeof value === \"string\") {\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t}\n\treturn [];\n}\n\nexport interface CoordinatorSyncConfig {\n\tsyncEnabled: boolean;\n\tsyncHost: string;\n\tsyncPort: number;\n\tsyncIntervalS: number;\n\tsyncAdvertise: string;\n\tsyncMdns: boolean;\n\tsyncRetentionEnabled: boolean;\n\tsyncRetentionMaxAgeDays: number;\n\tsyncRetentionMaxSizeMb: number;\n\tsyncRetentionIntervalS: number;\n\tsyncRetentionMaxRuntimeMs: number;\n\tsyncRetentionMaxOpsPerPass: number;\n\trawEventsRetentionEnabled: boolean;\n\t/** Whether raw_events_retention_enabled was explicitly set (file or env), so\n\t * callers can treat an explicit `false` as authoritative over legacy knobs. */\n\trawEventsRetentionConfigured: boolean;\n\trawEventsRetentionMaxAgeDays: number;\n\tsyncProjectsInclude: string[];\n\tsyncProjectsExclude: string[];\n\tsyncOpsLimit: number;\n\tsyncCoordinatorUrl: string;\n\tsyncCoordinatorGroup: string;\n\tsyncCoordinatorGroups: string[];\n\tsyncCoordinatorTimeoutS: number;\n\tsyncCoordinatorPresenceTtlS: number;\n\tsyncCoordinatorAdminSecret: string;\n}\n\nexport function readCoordinatorSyncConfig(config?: ConfigRecord): CoordinatorSyncConfig {\n\tconst raw = { ...(config ?? readCodememConfigFile()) } as ConfigRecord;\n\tconst envOverrides = getCodememEnvOverrides();\n\tfor (const key of Object.keys(envOverrides)) {\n\t\tconst value = process.env[envOverrides[key] as string];\n\t\tif (value != null) raw[key] = value;\n\t}\n\tconst syncCoordinatorGroup = clean(raw.sync_coordinator_group);\n\tconst syncCoordinatorGroups = parseStringList(raw.sync_coordinator_groups);\n\tif (syncCoordinatorGroups.length === 0 && syncCoordinatorGroup) {\n\t\tsyncCoordinatorGroups.push(syncCoordinatorGroup);\n\t}\n\treturn {\n\t\tsyncEnabled: parseBoolOr(raw.sync_enabled, false),\n\t\tsyncHost: clean(raw.sync_host) || \"0.0.0.0\",\n\t\tsyncPort: parseIntOr(raw.sync_port, 7337),\n\t\tsyncIntervalS: parseIntOr(raw.sync_interval_s, 120),\n\t\tsyncAdvertise: clean(raw.sync_advertise) || \"auto\",\n\t\tsyncMdns: parseBoolOr(raw.sync_mdns, false),\n\t\tsyncRetentionEnabled: parseBoolOr(raw.sync_retention_enabled, false),\n\t\tsyncRetentionMaxAgeDays: Math.max(1, parseIntOr(raw.sync_retention_max_age_days, 30)),\n\t\tsyncRetentionMaxSizeMb: Math.max(1, parseIntOr(raw.sync_retention_max_size_mb, 512)),\n\t\tsyncRetentionIntervalS: Math.max(5, parseIntOr(raw.sync_retention_interval_s, 300)),\n\t\tsyncRetentionMaxRuntimeMs: Math.max(100, parseIntOr(raw.sync_retention_max_runtime_ms, 2000)),\n\t\tsyncRetentionMaxOpsPerPass: Math.max(1, parseIntOr(raw.sync_retention_max_ops_per_pass, 5000)),\n\t\trawEventsRetentionEnabled: parseBoolOr(raw.raw_events_retention_enabled, false),\n\t\trawEventsRetentionConfigured: raw.raw_events_retention_enabled !== undefined,\n\t\trawEventsRetentionMaxAgeDays: Math.max(\n\t\t\t1,\n\t\t\tparseIntOr(raw.raw_events_retention_max_age_days, 90),\n\t\t),\n\t\tsyncProjectsInclude: parseStringList(raw.sync_projects_include),\n\t\tsyncProjectsExclude: parseStringList(raw.sync_projects_exclude),\n\t\tsyncOpsLimit: Math.max(1, Math.min(1000, parseIntOr(raw.sync_ops_limit, 500))),\n\t\tsyncCoordinatorUrl: clean(raw.sync_coordinator_url),\n\t\tsyncCoordinatorGroup,\n\t\tsyncCoordinatorGroups,\n\t\tsyncCoordinatorTimeoutS: parseIntOr(raw.sync_coordinator_timeout_s, 3),\n\t\tsyncCoordinatorPresenceTtlS: parseIntOr(raw.sync_coordinator_presence_ttl_s, 180),\n\t\tsyncCoordinatorAdminSecret: clean(raw.sync_coordinator_admin_secret),\n\t};\n}\n\nexport function coordinatorEnabled(config: CoordinatorSyncConfig): boolean {\n\treturn Boolean(config.syncCoordinatorUrl && config.syncCoordinatorGroups.length > 0);\n}\n","import type { Database } from \"./db.js\";\nimport type { RecipientPolicyDenyOverlayRecord } from \"./recipient-policy-reconciliation.js\";\n\nexport function denyOverlayRow(row: Record<string, unknown>): RecipientPolicyDenyOverlayRecord {\n\treturn {\n\t\tcanonicalProjectIdentity: String(row.canonical_project_identity),\n\t\tscopeId: String(row.scope_id),\n\t\tdeviceId: String(row.device_id),\n\t\tgeneration: Number(row.generation),\n\t\treasonCode: String(row.reason_code),\n\t\tcreatedAt: String(row.created_at),\n\t\tupdatedAt: String(row.updated_at),\n\t};\n}\n\n/** Any deny for the pair applies, including ambiguous legacy project overlays. */\nexport function getAnyRecipientPolicyDenyOverlayForScopeDevice(\n\tdb: Database,\n\tinput: { scopeId: string; deviceId: string },\n): RecipientPolicyDenyOverlayRecord | null {\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT * FROM recipient_policy_deny_overlays\n\t\t\t WHERE scope_id = ? AND device_id = ?\n\t\t\t ORDER BY canonical_project_identity\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(input.scopeId, input.deviceId) as Record<string, unknown> | undefined;\n\treturn row ? denyOverlayRow(row) : null;\n}\n","import { createHash } from \"node:crypto\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport interface ScopeMembershipCatalog {\n\tversion: 1;\n\titems: CoordinatorScope[];\n}\n\nexport interface ScopeMembershipSnapshot {\n\tauthorization_version: 1;\n\tscope: CoordinatorScope;\n\titems: Array<{\n\t\tmembership: CoordinatorScopeMembership;\n\t\tenrollment: CoordinatorEnrollment;\n\t\tkey_id: string;\n\t}>;\n}\n\nfunction requireEnvelope(raw: unknown, versionField: string): Record<string, unknown> {\n\tif (!raw || typeof raw !== \"object\" || Array.isArray(raw))\n\t\tthrow new Error(\"Invalid current scope snapshot.\");\n\tconst envelope = raw as Record<string, unknown>;\n\tif (envelope[versionField] !== 1 || !Array.isArray(envelope.items))\n\t\tthrow new Error(\"Current scope snapshot version 1 and items required.\");\n\treturn envelope;\n}\n\nfunction requireScope(raw: unknown, groupId: string): CoordinatorScope {\n\trequireScopeAuthorizationRecord(raw, SCOPE_FIELDS);\n\tconst scope = raw as CoordinatorScope;\n\tif (scopeAuthorizationError(scope, groupId)) throw new Error(\"Invalid scope source or status.\");\n\treturn scope;\n}\n\nexport function normalizeScopeCatalog(raw: unknown, groupId: string): CoordinatorScope[] {\n\tconst envelope = requireEnvelope(raw, \"version\");\n\tconst scopes = (envelope.items as unknown[]).map((item) => requireScope(item, groupId));\n\tif (new Set(scopes.map((scope) => scope.scope_id)).size !== scopes.length)\n\t\tthrow new Error(\"Duplicate scope in catalog.\");\n\treturn scopes;\n}\n\nfunction copyFields<T extends object>(value: T, fields: readonly (keyof T)[]): T {\n\treturn Object.fromEntries(fields.map((field) => [field, value[field]])) as T;\n}\n\nfunction requireMember(\n\traw: unknown,\n\tscope: CoordinatorScope,\n): ScopeMembershipSnapshot[\"items\"][number] {\n\tif (!raw || typeof raw !== \"object\" || Array.isArray(raw))\n\t\tthrow new Error(\"Invalid current scope member.\");\n\tconst member = raw as ScopeMembershipSnapshot[\"items\"][number];\n\trequireScopeAuthorizationRecord(member.membership, MEMBERSHIP_FIELDS);\n\trequireScopeAuthorizationRecord(member.enrollment, ENROLLMENT_FIELDS);\n\tconst { membership, enrollment } = member;\n\t// Legacy fingerprints are stored tuple evidence; canonical identity comes from the key blob.\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(enrollment.public_key);\n\tif (\n\t\t!isCurrentScopeMember(scope, membership) ||\n\t\tenrollment.enabled !== 1 ||\n\t\tenrollment.group_id !== scope.group_id ||\n\t\tenrollment.device_id !== membership.device_id ||\n\t\tparsed.kind !== \"ed25519\" ||\n\t\tcreateHash(\"sha256\").update(parsed.blob).digest(\"hex\") !== member.key_id\n\t)\n\t\tthrow new Error(\"Current scope member evidence mismatch.\");\n\treturn {\n\t\tmembership: copyFields(membership, MEMBERSHIP_FIELDS),\n\t\tenrollment: copyFields(enrollment, ENROLLMENT_FIELDS),\n\t\tkey_id: member.key_id,\n\t};\n}\n\nexport function normalizeScopeSnapshot(\n\traw: unknown,\n\tcatalogScope: CoordinatorScope,\n\tgroupId: string,\n\tcoordinatorId: string,\n): {\n\tscope: CoordinatorScope;\n\tmemberships: CoordinatorScopeMembership[];\n\tsourceCoordinatorId: string | null;\n\tevidence: ScopeMembershipSnapshot;\n} {\n\tconst envelope = requireEnvelope(raw, \"authorization_version\");\n\tconst source = requireScope(envelope.scope, groupId);\n\tif (\n\t\tsource.scope_id !== catalogScope.scope_id ||\n\t\tsource.membership_epoch < catalogScope.membership_epoch ||\n\t\tsource.coordinator_id !== catalogScope.coordinator_id\n\t)\n\t\tthrow new Error(\"Current scope snapshot source mismatch.\");\n\tconst members = (envelope.items as unknown[]).map((item) => requireMember(item, source));\n\tif (new Set(members.map((member) => member.membership.device_id)).size !== members.length)\n\t\tthrow new Error(\"Duplicate device in current scope snapshot.\");\n\t// The configured cache authority can be a URL, not the server's coordinator ID.\n\tconst capturedScope = copyFields(source, SCOPE_FIELDS);\n\tconst scope = { ...capturedScope, coordinator_id: coordinatorId };\n\tconst memberships = members.map((member) => ({\n\t\t...member.membership,\n\t\tcoordinator_id: coordinatorId,\n\t\tgroup_id: groupId,\n\t}));\n\treturn {\n\t\tscope,\n\t\tmemberships,\n\t\tsourceCoordinatorId: source.coordinator_id,\n\t\tevidence: { authorization_version: 1, scope: capturedScope, items: members },\n\t};\n}\n","import { createHash } from \"node:crypto\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport type { CoordinatorScope, CoordinatorScopeMembership } from \"./coordinator-store-contract.js\";\nimport type { Database } from \"./db.js\";\nimport {\n\tnormalizeScopeSnapshot,\n\ttype ScopeMembershipSnapshot,\n} from \"./scope-membership-snapshot.js\";\n\ntype Batch = ReturnType<typeof normalizeScopeSnapshot>;\ntype Authority = { coordinatorId: string; groupId: string };\ntype EvidenceRow = { scope_id: string; device_id: string; evidence_json: string };\n\n// Deliberately excludes presentation labels and timestamps, not authority facts.\nconst SCOPE_AUTHORITY_FIELDS = [\n\t\"scope_id\",\n\t\"kind\",\n\t\"authority_type\",\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"membership_epoch\",\n\t\"manifest_hash\",\n\t\"status\",\n] as const;\nconst MEMBER_AUTHORITY_FIELDS = [\n\t\"scope_id\",\n\t\"device_id\",\n\t\"role\",\n\t\"status\",\n\t\"membership_epoch\",\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"manifest_hash\",\n\t\"signed_manifest_json\",\n] as const;\n\nexport function scopeEvidenceTableExists(db: Database): boolean {\n\treturn !!db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(\"scope_membership_authorization_evidence\");\n}\n\nfunction ensureEvidenceTable(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS scope_membership_authorization_evidence (\n\t\tcoordinator_id TEXT NOT NULL, group_id TEXT NOT NULL,\n\t\tscope_id TEXT NOT NULL, device_id TEXT NOT NULL, evidence_json TEXT NOT NULL,\n\t\tPRIMARY KEY (coordinator_id, group_id, scope_id, device_id)\n\t)`);\n}\n\nfunction sameFields<T>(left: T, right: T, fields: readonly (keyof T)[]): boolean {\n\treturn fields.every((field) => left[field] === right[field]);\n}\n\nfunction matchesRows(\n\tbatch: Batch,\n\tscope: CoordinatorScope,\n\tmember: CoordinatorScopeMembership,\n): boolean {\n\tconst captured = batch.memberships[0];\n\tif (!captured) return false;\n\treturn (\n\t\tsameFields(batch.scope, scope, SCOPE_AUTHORITY_FIELDS) &&\n\t\tbatch.memberships.length === 1 &&\n\t\tsameFields(captured, member, MEMBER_AUTHORITY_FIELDS)\n\t);\n}\n\nfunction parseEvidence(raw: string, authority: Authority): Batch | null {\n\ttry {\n\t\tconst snapshot = JSON.parse(raw) as ScopeMembershipSnapshot;\n\t\tconst batch = normalizeScopeSnapshot(\n\t\t\tsnapshot,\n\t\t\tsnapshot.scope,\n\t\t\tauthority.groupId,\n\t\t\tauthority.coordinatorId,\n\t\t);\n\t\treturn batch.evidence.items.length === 1 ? batch : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction singleMemberEvidence(batch: Batch, index: number): ScopeMembershipSnapshot {\n\tconst item = batch.evidence.items[index];\n\tif (!item) throw new Error(\"Scope authorization evidence unavailable.\");\n\treturn { ...batch.evidence, items: [item] };\n}\n\n/** Called only inside the whole-group cache transaction; never backfills historical rows. */\nexport function reconcileScopeAuthorizationEvidence(\n\tdb: Database,\n\tbatches: Batch[],\n\tauthority: Authority,\n\toptions: { removalOnly: boolean },\n): void {\n\tif (options.removalOnly) {\n\t\tpruneEvidence(db, batches, authority);\n\t\treturn;\n\t}\n\tensureEvidenceTable(db);\n\tdb.prepare(\n\t\t\"DELETE FROM scope_membership_authorization_evidence WHERE coordinator_id = ? AND group_id = ?\",\n\t).run(authority.coordinatorId, authority.groupId);\n\tconst insert = db.prepare(`INSERT INTO scope_membership_authorization_evidence\n\t\t(coordinator_id, group_id, scope_id, device_id, evidence_json) VALUES (?, ?, ?, ?, ?)`);\n\tfor (const batch of batches) {\n\t\tfor (const [index, member] of batch.memberships.entries()) {\n\t\t\tinsert.run(\n\t\t\t\tauthority.coordinatorId,\n\t\t\t\tauthority.groupId,\n\t\t\t\tbatch.scope.scope_id,\n\t\t\t\tmember.device_id,\n\t\t\t\tJSON.stringify(singleMemberEvidence(batch, index)),\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction sameProof(previous: Batch, current: Batch): boolean {\n\tconst oldItem = previous.evidence.items[0];\n\tconst item = current.evidence.items[0];\n\tconst member = current.memberships[0];\n\tif (!oldItem || !item || !member) return false;\n\treturn (\n\t\tmatchesRows(previous, current.scope, member) &&\n\t\tprevious.sourceCoordinatorId === current.sourceCoordinatorId &&\n\t\toldItem.key_id === item.key_id &&\n\t\tsameFields(oldItem.membership, item.membership, MEMBER_AUTHORITY_FIELDS) &&\n\t\tsameFields(oldItem.enrollment, item.enrollment, [\n\t\t\t\"group_id\",\n\t\t\t\"device_id\",\n\t\t\t\"fingerprint\",\n\t\t\t\"enabled\",\n\t\t])\n\t);\n}\n\nfunction pruneEvidence(db: Database, batches: Batch[], authority: Authority): void {\n\tif (!scopeEvidenceTableExists(db)) return;\n\tconst rows = db\n\t\t.prepare(`SELECT scope_id, device_id, evidence_json\n\t\tFROM scope_membership_authorization_evidence WHERE coordinator_id = ? AND group_id = ?`)\n\t\t.all(authority.coordinatorId, authority.groupId) as EvidenceRow[];\n\tconst remove = db.prepare(`DELETE FROM scope_membership_authorization_evidence\n\t\tWHERE coordinator_id = ? AND group_id = ? AND scope_id = ? AND device_id = ?`);\n\tfor (const row of rows) {\n\t\tconst batch = batches.find((item) => item.scope.scope_id === row.scope_id);\n\t\tconst index =\n\t\t\tbatch?.memberships.findIndex((member) => member.device_id === row.device_id) ?? -1;\n\t\tconst old = parseEvidence(row.evidence_json, authority);\n\t\tconst current =\n\t\t\tbatch && index >= 0\n\t\t\t\t? normalizeScopeSnapshot(\n\t\t\t\t\t\tsingleMemberEvidence(batch, index),\n\t\t\t\t\t\tbatch.evidence.scope,\n\t\t\t\t\t\tauthority.groupId,\n\t\t\t\t\t\tauthority.coordinatorId,\n\t\t\t\t\t)\n\t\t\t\t: null;\n\t\tif (!old || !current || !sameProof(old, current))\n\t\t\tremove.run(authority.coordinatorId, authority.groupId, row.scope_id, row.device_id);\n\t}\n}\n\n/** Evidence is not a lease: freshness policy remains with the caller. Malformed storage denies. */\nexport function getRetainedScopeAuthorizationKey(\n\tdb: Database,\n\tscope: CoordinatorScope,\n\tmember: CoordinatorScopeMembership,\n\texpectedPublicKey?: string,\n): string | null {\n\ttry {\n\t\tif (!scope.coordinator_id || !scope.group_id || !scopeEvidenceTableExists(db)) return null;\n\t\tconst authority = { coordinatorId: scope.coordinator_id, groupId: scope.group_id };\n\t\tconst row = db\n\t\t\t.prepare(`SELECT evidence_json FROM scope_membership_authorization_evidence\n\t\t\tWHERE coordinator_id = ? AND group_id = ? AND scope_id = ? AND device_id = ?`)\n\t\t\t.get(authority.coordinatorId, authority.groupId, scope.scope_id, member.device_id) as\n\t\t\t| EvidenceRow\n\t\t\t| undefined;\n\t\tconst proof = row && parseEvidence(row.evidence_json, authority);\n\t\tif (!proof || !matchesRows(proof, scope, member)) return null;\n\t\tconst keyId = proof.evidence.items[0]?.key_id;\n\t\tif (!keyId) return null;\n\t\tif (expectedPublicKey !== undefined) {\n\t\t\tconst parsed = parseSshEd25519PublicKeyForRevocation(expectedPublicKey);\n\t\t\tif (\n\t\t\t\tparsed.kind !== \"ed25519\" ||\n\t\t\t\tcreateHash(\"sha256\").update(parsed.blob).digest(\"hex\") !== keyId\n\t\t\t)\n\t\t\t\treturn null;\n\t\t}\n\t\treturn keyId;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","/**\n * Sync authentication: request signing, verification, and nonce management.\n *\n * Uses Node's native Ed25519 crypto for sign/verify and SHA-256 canonical\n * request hashing. No ssh-keygen shelling.\n */\n\nimport {\n\tcreateHash,\n\tcreatePrivateKey,\n\tcreatePublicKey,\n\trandomBytes,\n\tsign,\n\tverify,\n} from \"node:crypto\";\nimport { lt } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { loadPrivateKey } from \"./sync-identity.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Signature version. v1 = SSHSIG format (ssh-keygen era), v2 = raw Ed25519.\n *\n * v2 is a breaking change: Python peers using `ssh-keygen -Y verify` cannot\n * verify v2 signatures. Once all peers run the TS runtime, v1 support can\n * be removed. During migration, the verifier accepts both versions.\n */\nexport const SIGNATURE_VERSION = \"v2\";\n\n/** Direct-peer-only recipient-bound signature version. */\nexport const DIRECT_PEER_SIGNATURE_VERSION = \"v3\";\n\nfunction isValidRecipientId(recipientId: string): boolean {\n\treturn (\n\t\tBoolean(recipientId.trim()) && recipientId === recipientId.trim() && !/[\\r\\n]/.test(recipientId)\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Canonical request\n// ---------------------------------------------------------------------------\n\n/**\n * Build a canonical request buffer for signing/verification.\n *\n * SHA-256 hashes the body, then joins method/path/timestamp/nonce/bodyHash\n * with newlines and returns the UTF-8 encoded result.\n */\nexport function buildCanonicalRequest(\n\tmethod: string,\n\tpathWithQuery: string,\n\ttimestamp: string,\n\tnonce: string,\n\tbodyBytes: Buffer,\n): Buffer {\n\tconst bodyHash = createHash(\"sha256\").update(bodyBytes).digest(\"hex\");\n\tconst canonical = [method.toUpperCase(), pathWithQuery, timestamp, nonce, bodyHash].join(\"\\n\");\n\treturn Buffer.from(canonical, \"utf-8\");\n}\n\n/**\n * Build the direct-peer v3 canonical request without changing the v2 bytes.\n * The recipient is the sixth field so the signature cannot be replayed to a\n * different peer.\n */\nexport function buildDirectPeerCanonicalRequest(\n\tmethod: string,\n\tpathWithQuery: string,\n\ttimestamp: string,\n\tnonce: string,\n\tbodyBytes: Buffer,\n\trecipientId: string,\n): Buffer {\n\tif (!isValidRecipientId(recipientId)) {\n\t\tthrow new Error(\"recipientId must be a non-empty single-line value\");\n\t}\n\treturn Buffer.concat([\n\t\tbuildCanonicalRequest(method, pathWithQuery, timestamp, nonce, bodyBytes),\n\t\tBuffer.from(`\\n${recipientId}`, \"utf-8\"),\n\t]);\n}\n\n// ---------------------------------------------------------------------------\n// Sign\n// ---------------------------------------------------------------------------\n\nexport interface SignRequestOptions {\n\tmethod: string;\n\turl: string;\n\tbodyBytes: Buffer;\n\tkeysDir?: string;\n\tdeviceId?: string;\n\tdbPath?: string;\n\ttimestamp?: string;\n\tnonce?: string;\n}\n\nexport interface SignedRequestHeaders {\n\t\"X-Opencode-Timestamp\": string;\n\t\"X-Opencode-Nonce\": string;\n\t\"X-Opencode-Signature\": string;\n}\n\ninterface SigningKeyOptions {\n\tkeysDir?: string;\n\tdeviceId?: string;\n\tdbPath?: string;\n}\n\nfunction requestPath(url: string): string {\n\tconst parsed = new URL(url);\n\treturn `${parsed.pathname || \"/\"}${parsed.search}`;\n}\n\nfunction signCanonicalRequest(canonical: Buffer, options: SigningKeyOptions): string {\n\tconst keyData = loadPrivateKey(options.keysDir, options.dbPath, options.deviceId);\n\tif (!keyData) throw new Error(\"private key missing\");\n\n\tlet privateKeyObj: ReturnType<typeof createPrivateKey>;\n\ttry {\n\t\tprivateKeyObj = createPrivateKey(keyData);\n\t} catch {\n\t\tprivateKeyObj = createPrivateKey({ key: keyData, format: \"pem\", type: \"pkcs8\" });\n\t}\n\treturn sign(null, canonical, privateKeyObj).toString(\"base64\");\n}\n\n/**\n * Sign an HTTP request and return the auth headers.\n *\n * Uses Node's native Ed25519 crypto.sign() — no ssh-keygen shelling.\n * Returns X-Opencode-Timestamp, X-Opencode-Nonce, X-Opencode-Signature headers.\n */\nexport function signRequest(options: SignRequestOptions): SignedRequestHeaders {\n\tconst ts = options.timestamp ?? String(Math.floor(Date.now() / 1000));\n\tconst nonceValue = options.nonce ?? randomBytes(16).toString(\"hex\");\n\n\tconst path = requestPath(options.url);\n\tconst canonical = buildCanonicalRequest(options.method, path, ts, nonceValue, options.bodyBytes);\n\tconst signature = signCanonicalRequest(canonical, options);\n\n\treturn {\n\t\t\"X-Opencode-Timestamp\": ts,\n\t\t\"X-Opencode-Nonce\": nonceValue,\n\t\t\"X-Opencode-Signature\": `${SIGNATURE_VERSION}:${signature}`,\n\t};\n}\n\nexport interface SignDirectPeerRequestOptions\n\textends Omit<SignRequestOptions, \"timestamp\" | \"nonce\"> {\n\trecipientId: string;\n\ttimestamp: string;\n\tnonce: string;\n}\n\nexport interface DirectPeerSignatureHeaders {\n\t\"X-Codemem-Recipient\": string;\n\t\"X-Codemem-Signature\": string;\n}\n\n/** Sign the isolated recipient-bound v3 material for a direct-peer request. */\nexport function signDirectPeerRequest(\n\toptions: SignDirectPeerRequestOptions,\n): DirectPeerSignatureHeaders {\n\tconst path = requestPath(options.url);\n\tconst canonical = buildDirectPeerCanonicalRequest(\n\t\toptions.method,\n\t\tpath,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t\toptions.recipientId,\n\t);\n\tconst signature = signCanonicalRequest(canonical, options);\n\n\treturn {\n\t\t\"X-Codemem-Recipient\": options.recipientId,\n\t\t\"X-Codemem-Signature\": `${DIRECT_PEER_SIGNATURE_VERSION}:${signature}`,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Verify\n// ---------------------------------------------------------------------------\n\nexport interface VerifySignatureOptions {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Buffer;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n\ttimeWindowS?: number;\n}\n\nfunction isFreshTimestamp(timestamp: string, timeWindowS: number): boolean {\n\tif (!/^\\d+$/.test(timestamp)) return false;\n\tconst seconds = Number.parseInt(timestamp, 10);\n\treturn Math.abs(Math.floor(Date.now() / 1000) - seconds) <= timeWindowS;\n}\n\nfunction decodeStrictBase64(encoded: string): Buffer | undefined {\n\tif (!encoded) return undefined;\n\tconst decoded = Buffer.from(encoded, \"base64\");\n\treturn decoded.toString(\"base64\") === encoded ? decoded : undefined;\n}\n\n/**\n * Verify a signed request.\n *\n * Checks timestamp freshness, signature version prefix, then uses\n * Node's native crypto.verify() with the sender's Ed25519 public key.\n */\nexport function verifySignature(options: VerifySignatureOptions): boolean {\n\tconst timeWindow = options.timeWindowS ?? DEFAULT_TIME_WINDOW_S;\n\n\tif (!isFreshTimestamp(options.timestamp, timeWindow)) return false;\n\n\t// Validate signature version prefix — accept both v1 and v2 during migration\n\tconst ACCEPTED_VERSIONS = [\"v1\", \"v2\"];\n\tconst colonIdx = options.signature.indexOf(\":\");\n\tif (colonIdx < 1) return false;\n\tconst sigVersion = options.signature.slice(0, colonIdx);\n\tif (!ACCEPTED_VERSIONS.includes(sigVersion)) return false;\n\n\tconst signatureBytes = decodeStrictBase64(options.signature.slice(colonIdx + 1));\n\tif (!signatureBytes) return false;\n\n\tconst canonical = buildCanonicalRequest(\n\t\toptions.method,\n\t\toptions.pathWithQuery,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t);\n\n\ttry {\n\t\tconst publicKeyObj = sshEd25519ToPublicKey(options.publicKey);\n\t\treturn verify(null, canonical, publicKeyObj, signatureBytes);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport interface VerifyDirectPeerSignatureOptions {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Buffer;\n\ttimestamp: string;\n\tnonce: string;\n\trecipientId?: string;\n\texpectedRecipientId: string;\n\tsignature?: string;\n\tpublicKey: string;\n\ttimeWindowS?: number;\n}\n\nexport type DirectPeerSignatureVerification =\n\t| { status: \"absent\" }\n\t| {\n\t\t\tstatus: \"invalid\";\n\t\t\treason:\n\t\t\t\t| \"incomplete_material\"\n\t\t\t\t| \"malformed_recipient\"\n\t\t\t\t| \"invalid_timestamp\"\n\t\t\t\t| \"unsupported_version\"\n\t\t\t\t| \"invalid_signature\"\n\t\t\t\t| \"recipient_mismatch\";\n\t }\n\t| { status: \"valid\"; version: \"v3\" };\n\n/**\n * Verify direct-peer v3 material with an explicit absent/invalid distinction.\n * Callers may permit legacy v2 only for `absent`; any `invalid` result must fail\n * closed rather than falling back to the accompanying v2 signature.\n */\nexport function verifyDirectPeerSignature(\n\toptions: VerifyDirectPeerSignatureOptions,\n): DirectPeerSignatureVerification {\n\tconst recipientId = options.recipientId === \"\" ? undefined : options.recipientId;\n\tconst signature = options.signature === \"\" ? undefined : options.signature;\n\tif (recipientId === undefined && signature === undefined) {\n\t\treturn { status: \"absent\" };\n\t}\n\tif (!recipientId || !signature) {\n\t\treturn { status: \"invalid\", reason: \"incomplete_material\" };\n\t}\n\tif (!isValidRecipientId(recipientId)) {\n\t\treturn { status: \"invalid\", reason: \"malformed_recipient\" };\n\t}\n\tconst timeWindow = options.timeWindowS ?? DEFAULT_TIME_WINDOW_S;\n\tif (!isFreshTimestamp(options.timestamp, timeWindow)) {\n\t\treturn { status: \"invalid\", reason: \"invalid_timestamp\" };\n\t}\n\n\tconst prefix = `${DIRECT_PEER_SIGNATURE_VERSION}:`;\n\tif (!signature.startsWith(prefix)) {\n\t\treturn { status: \"invalid\", reason: \"unsupported_version\" };\n\t}\n\tconst signatureBytes = decodeStrictBase64(signature.slice(prefix.length));\n\tif (!signatureBytes) {\n\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t}\n\n\tconst canonical = buildDirectPeerCanonicalRequest(\n\t\toptions.method,\n\t\toptions.pathWithQuery,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t\trecipientId,\n\t);\n\ttry {\n\t\tconst publicKeyObj = sshEd25519ToPublicKey(options.publicKey);\n\t\tif (!verify(null, canonical, publicKeyObj, signatureBytes)) {\n\t\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t\t}\n\t} catch {\n\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t}\n\tif (recipientId !== options.expectedRecipientId) {\n\t\treturn { status: \"invalid\", reason: \"recipient_mismatch\" };\n\t}\n\treturn {\n\t\tstatus: \"valid\",\n\t\tversion: DIRECT_PEER_SIGNATURE_VERSION,\n\t};\n}\n\n/**\n * Parse an SSH ed25519 public key string into a Node crypto KeyObject.\n *\n * SSH format: \"ssh-ed25519 <base64-wire-format>\"\n * Wire format: uint32 key-type-len + key-type + uint32 key-data-len + key-data\n */\nfunction sshEd25519ToPublicKey(sshPub: string): ReturnType<typeof createPublicKey> {\n\tconst parts = sshPub.trim().split(/\\s+/);\n\tconst [keyType, keyData] = parts;\n\tif (keyType !== \"ssh-ed25519\" || !keyData) {\n\t\tthrow new Error(\"not an ssh-ed25519 key\");\n\t}\n\tconst wireFormat = Buffer.from(keyData, \"base64\");\n\n\t// Read key type length\n\tif (wireFormat.length < 4) throw new Error(\"truncated wire format\");\n\tconst typeLen = wireFormat.readUInt32BE(0);\n\tconst typeEnd = 4 + typeLen;\n\tif (wireFormat.length < typeEnd + 4) throw new Error(\"truncated wire format\");\n\n\t// Read key data length\n\tconst keyLen = wireFormat.readUInt32BE(typeEnd);\n\tconst keyStart = typeEnd + 4;\n\tif (wireFormat.length < keyStart + keyLen) throw new Error(\"truncated wire format\");\n\tconst rawKey = wireFormat.subarray(keyStart, keyStart + keyLen);\n\n\tif (rawKey.length !== 32) throw new Error(`unexpected Ed25519 key length: ${rawKey.length}`);\n\n\t// Wrap raw 32-byte key in SPKI DER: 12-byte Ed25519 header + 32-byte key\n\tconst ed25519SpkiPrefix = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n\tconst spkiDer = Buffer.concat([ed25519SpkiPrefix, rawKey]);\n\n\treturn createPublicKey({ key: spkiDer, format: \"der\", type: \"spki\" });\n}\n\n// ---------------------------------------------------------------------------\n// Auth headers (convenience)\n// ---------------------------------------------------------------------------\n\nexport interface BuildAuthHeadersOptions {\n\tdeviceId: string;\n\tmethod: string;\n\turl: string;\n\tbodyBytes: Buffer;\n\tbootstrapGrantId?: string;\n\tkeysDir?: string;\n\tdbPath?: string;\n\ttimestamp?: string;\n\tnonce?: string;\n}\n\nexport type AuthHeaders = Record<string, string> &\n\tSignedRequestHeaders & {\n\t\t\"X-Opencode-Device\": string;\n\t};\n\n/**\n * Build full auth headers including device ID and request signature.\n */\nexport function buildAuthHeaders(options: BuildAuthHeadersOptions): AuthHeaders {\n\treturn {\n\t\t\"X-Opencode-Device\": options.deviceId,\n\t\t...(options.bootstrapGrantId ? { \"X-Codemem-Bootstrap-Grant\": options.bootstrapGrantId } : {}),\n\t\t...signRequest({\n\t\t\tmethod: options.method,\n\t\t\turl: options.url,\n\t\t\tbodyBytes: options.bodyBytes,\n\t\t\tkeysDir: options.keysDir,\n\t\t\tdeviceId: options.deviceId,\n\t\t\tdbPath: options.dbPath,\n\t\t\ttimestamp: options.timestamp,\n\t\t\tnonce: options.nonce,\n\t\t}),\n\t};\n}\n\nexport interface BuildDirectPeerAuthHeadersOptions extends BuildAuthHeadersOptions {\n\trecipientId: string;\n}\n\nexport type DirectPeerAuthHeaders = AuthHeaders & DirectPeerSignatureHeaders;\n\n/** Build dual v2 + recipient-bound v3 headers for direct-peer requests only. */\nexport function buildDirectPeerAuthHeaders(\n\toptions: BuildDirectPeerAuthHeadersOptions,\n): DirectPeerAuthHeaders {\n\tconst legacyHeaders = buildAuthHeaders(options);\n\tconst directHeaders = signDirectPeerRequest({\n\t\tmethod: options.method,\n\t\turl: options.url,\n\t\tbodyBytes: options.bodyBytes,\n\t\trecipientId: options.recipientId,\n\t\tkeysDir: options.keysDir,\n\t\tdeviceId: options.deviceId,\n\t\tdbPath: options.dbPath,\n\t\ttimestamp: legacyHeaders[\"X-Opencode-Timestamp\"],\n\t\tnonce: legacyHeaders[\"X-Opencode-Nonce\"],\n\t});\n\n\treturn {\n\t\t...legacyHeaders,\n\t\t...directHeaders,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Nonce management\n// ---------------------------------------------------------------------------\n\n/**\n * Record a nonce to prevent replay attacks.\n *\n * Returns true on success, false if the nonce was already recorded\n * (duplicate = potential replay).\n */\nexport function recordNonce(\n\tdb: Database,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): boolean {\n\tconst d = drizzle(db, { schema });\n\ttry {\n\t\td.insert(schema.syncNonces).values({ nonce, device_id: deviceId, created_at: createdAt }).run();\n\t\treturn true;\n\t} catch (err: unknown) {\n\t\tif (err instanceof Error && err.message.includes(\"UNIQUE constraint failed\")) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n/**\n * Remove nonces older than the given cutoff timestamp.\n */\nexport function cleanupNonces(db: Database, cutoff: string): void {\n\tconst d = drizzle(db, { schema });\n\td.delete(schema.syncNonces).where(lt(schema.syncNonces.created_at, cutoff)).run();\n}\n","/**\n * Sync HTTP client: JSON request helper using Node.js built-in fetch.\n *\n * Async counterpart to the synchronous Python http.client implementation.\n * Ported from codemem/sync/http_client.py.\n */\n\n// ---------------------------------------------------------------------------\n// URL helpers\n// ---------------------------------------------------------------------------\n\nfunction stripTrailingSlashes(value: string): string {\n\tlet end = value.length;\n\twhile (end > 0 && value.charCodeAt(end - 1) === 47) end--;\n\treturn end === value.length ? value : value.slice(0, end);\n}\n\nfunction hasUrlScheme(value: string): boolean {\n\tconst separator = value.indexOf(\"://\");\n\tif (separator <= 0) return false;\n\tconst first = value.charCodeAt(0);\n\tif (!((first >= 65 && first <= 90) || (first >= 97 && first <= 122))) return false;\n\tfor (let i = 1; i < separator; i++) {\n\t\tconst code = value.charCodeAt(i);\n\t\tconst isLetter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\t\tconst isDigit = code >= 48 && code <= 57;\n\t\tif (!isLetter && !isDigit && code !== 43 && code !== 45 && code !== 46) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Normalize a peer address into a base URL.\n *\n * Adds `http://` when no scheme is present, trims whitespace and trailing slashes.\n */\nexport function buildBaseUrl(address: string): string {\n\tconst trimmed = stripTrailingSlashes(address.trim());\n\tif (!trimmed) return \"\";\n\t// Check for an existing scheme (e.g. http://, https://)\n\tif (hasUrlScheme(trimmed)) return trimmed;\n\treturn `http://${trimmed}`;\n}\n\n// ---------------------------------------------------------------------------\n// JSON request\n// ---------------------------------------------------------------------------\n\nexport interface RequestJsonOptions {\n\theaders?: Record<string, string>;\n\tbody?: Record<string, unknown>;\n\tbodyBytes?: Uint8Array;\n\ttimeoutS?: number;\n\tmaxResponseBytes?: number;\n\tredirect?: \"error\";\n}\n\nfunction isolateDirectPeerConnection(headers: Record<string, string>): Record<string, string> {\n\tconst isDirectPeer = Object.keys(headers).some(\n\t\t(name) => name.toLowerCase() === \"x-codemem-recipient\",\n\t);\n\tif (!isDirectPeer) return headers;\n\n\t// Sync preparation can block expiry callbacks past a peer's idle deadline.\n\t// Close reads too, so a later write cannot reuse their expired connection.\n\treturn {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(headers).filter(([name]) => name.toLowerCase() !== \"connection\"),\n\t\t),\n\t\tConnection: \"close\",\n\t};\n}\n\nfunction requestRedirectPolicy(\n\theaders: Record<string, string>,\n\tredirect?: \"error\",\n): \"error\" | \"follow\" {\n\tconst carriesAdminCredential = Object.keys(headers).some(\n\t\t(name) => name.toLowerCase() === \"x-codemem-coordinator-admin\",\n\t);\n\tif (carriesAdminCredential) return \"error\";\n\treturn redirect ?? \"follow\";\n}\n\nfunction buildRequestHeaders(options: {\n\theaders?: Record<string, string>;\n\tbodyBytes?: Uint8Array;\n}): Record<string, string> {\n\tconst headers: Record<string, string> = { Accept: \"application/json\" };\n\tif (options.bodyBytes != null) {\n\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\theaders[\"Content-Length\"] = String(options.bodyBytes.byteLength);\n\t}\n\tif (options.headers) Object.assign(headers, options.headers);\n\treturn headers;\n}\n\n/**\n * Send an HTTP request and parse the JSON response.\n *\n * Returns `[statusCode, parsedBody]`. The body is null when the response\n * has no content. Non-JSON responses are returned as `{ error: \"non_json_response: ...\" }`.\n */\nexport async function requestJson(\n\tmethod: string,\n\turl: string,\n\toptions: RequestJsonOptions = {},\n): Promise<[status: number, body: Record<string, unknown> | null]> {\n\tconst { headers, body, timeoutS = 3 } = options;\n\tlet { bodyBytes } = options;\n\n\tif (bodyBytes == null && body != null) {\n\t\tbodyBytes = new TextEncoder().encode(JSON.stringify(body));\n\t}\n\n\tconst requestHeaders = buildRequestHeaders({ headers, bodyBytes });\n\tconst requestBody = (bodyBytes ?? null) as RequestInit[\"body\"] | null;\n\n\tconst response = await fetch(url, {\n\t\tmethod,\n\t\theaders: isolateDirectPeerConnection(requestHeaders),\n\t\tbody: requestBody,\n\t\tredirect: requestRedirectPolicy(requestHeaders, options.redirect),\n\t\tsignal: AbortSignal.timeout(Math.round(timeoutS * 1_000)),\n\t});\n\n\tlet raw: string;\n\tif (options.maxResponseBytes != null && response.body) {\n\t\tconst declaredLength = Number(response.headers.get(\"content-length\"));\n\t\tif (Number.isFinite(declaredLength) && declaredLength > options.maxResponseBytes) {\n\t\t\tawait response.body.cancel();\n\t\t\treturn [response.status, { error: \"response_too_large\" }];\n\t\t}\n\t\tconst reader = response.body.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\tlet totalBytes = 0;\n\t\traw = \"\";\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\ttotalBytes += value.byteLength;\n\t\t\t\tif (totalBytes > options.maxResponseBytes) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn [response.status, { error: \"response_too_large\" }];\n\t\t\t\t}\n\t\t\t\traw += decoder.decode(value, { stream: true });\n\t\t\t}\n\t\t\traw += decoder.decode();\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t} else {\n\t\traw = await response.text();\n\t}\n\tif (!raw) return [response.status, null];\n\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(raw);\n\t} catch {\n\t\tconst snippet = raw.slice(0, 240).trim();\n\t\treturn [\n\t\t\tresponse.status,\n\t\t\t{ error: snippet ? `non_json_response: ${snippet}` : \"non_json_response\" },\n\t\t];\n\t}\n\n\tif (typeof payload === \"object\" && payload !== null && !Array.isArray(payload)) {\n\t\treturn [response.status, payload as Record<string, unknown>];\n\t}\n\treturn [\n\t\tresponse.status,\n\t\t{ error: `unexpected_json_type: ${Array.isArray(payload) ? \"array\" : typeof payload}` },\n\t];\n}\n","import { BetterSqliteCoordinatorStore, DEFAULT_COORDINATOR_DB_PATH } from \"./coordinator-store.js\";\nimport type { CoordinatorScope, CoordinatorScopeMembership } from \"./coordinator-store-contract.js\";\nimport {\n\ttype CoordinatorSyncConfig,\n\tcoordinatorEnabled,\n\treadCoordinatorSyncConfig,\n} from \"./coordinator-sync-config.js\";\nimport type { Database } from \"./db.js\";\nimport { getAnyRecipientPolicyDenyOverlayForScopeDevice } from \"./recipient-policy-deny-overlay.js\";\nimport {\n\tgetRetainedScopeAuthorizationKey,\n\treconcileScopeAuthorizationEvidence,\n} from \"./scope-membership-evidence.js\";\nimport {\n\texplainScopeMembershipRevocation,\n\ttype ScopeMembershipEpochStatus,\n\ttype ScopeMembershipRevocationNotice,\n\tscopeMembershipEpochStatus,\n} from \"./scope-membership-semantics.js\";\nimport {\n\tnormalizeScopeCatalog,\n\tnormalizeScopeSnapshot,\n\ttype ScopeMembershipCatalog,\n\ttype ScopeMembershipSnapshot,\n} from \"./scope-membership-snapshot.js\";\nimport { buildAuthHeaders } from \"./sync-auth.js\";\nimport { buildBaseUrl, requestJson } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity } from \"./sync-identity.js\";\n\nexport const DEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS = 60_000;\n\nexport type ScopeMembershipCacheFreshness = \"fresh\" | \"stale\" | \"unknown\";\n\nexport type ScopeMembershipAuthorizationState =\n\t| \"authorized\"\n\t| \"not_authorized\"\n\t| \"revoked\"\n\t| \"stale_epoch\"\n\t| \"policy_denied\"\n\t| \"scope_unknown\"\n\t| \"scope_inactive\";\n\nexport interface ScopeMembershipCacheAuthority {\n\tcoordinatorId: string;\n\tgroupId: string;\n}\n\nexport interface ScopeMembershipCacheState extends ScopeMembershipCacheAuthority {\n\tlast_refresh_at: string;\n\tlast_success_at: string | null;\n\tlast_error: string | null;\n\tupdated_at: string;\n}\n\nexport interface CachedScopeMembership extends CoordinatorScopeMembership {\n\tscope: CoordinatorScope | null;\n}\n\nexport interface CachedDeviceScopeMemberships {\n\tdeviceId: string;\n\tfreshness: ScopeMembershipCacheFreshness;\n\tmemberships: CachedScopeMembership[];\n\tcacheStates: ScopeMembershipCacheState[];\n}\n\nexport interface CachedScopeAuthorization {\n\tdeviceId: string;\n\tscopeId: string;\n\tauthorized: boolean;\n\tstate: ScopeMembershipAuthorizationState;\n\tfreshness: ScopeMembershipCacheFreshness;\n\tepoch: ScopeMembershipEpochStatus;\n\trevocation: ScopeMembershipRevocationNotice | null;\n\tmembership: CoordinatorScopeMembership | null;\n\tscope: CoordinatorScope | null;\n\tcacheStates: ScopeMembershipCacheState[];\n}\n\nexport interface EffectiveCachedScopeAuthorization extends CachedScopeAuthorization {\n\tkeyId: string | null;\n}\n\nexport interface ScopeMembershipCacheFetchers {\n\tlistScopes(groupId: string): Promise<ScopeMembershipCatalog>;\n\tgetScopeSnapshot(groupId: string, scopeId: string): Promise<ScopeMembershipSnapshot>;\n}\n\nexport interface RefreshScopeMembershipCacheOptions {\n\tgroupIds: string[];\n\tcoordinatorId?: string | null;\n\tremoteUrl?: string | null;\n\tadminSecret?: string | null;\n\t/** @deprecated The refresh database is taken from refreshScopeMembershipCache(db, opts). */\n\tdb?: Database;\n\tkeysDir?: string | null;\n\tdbPath?: string;\n\t/** Separate local coordinator storage; dbPath remains the memory/signing database. */\n\tcoordinatorDbPath?: string;\n\tnow?: Date;\n\tfetchers?: ScopeMembershipCacheFetchers;\n}\n\nexport interface RefreshScopeMembershipCacheGroupResult {\n\tgroupId: string;\n\tstatus: \"refreshed\" | \"stale\";\n\tscopeCount: number;\n\tmembershipCount: number;\n\terror: string | null;\n}\n\nexport interface RefreshScopeMembershipCacheResult {\n\tstatus: \"refreshed\" | \"partial\" | \"stale\" | \"skipped\";\n\tcoordinatorId: string | null;\n\tgroups: RefreshScopeMembershipCacheGroupResult[];\n}\n\ninterface ScopeMembershipCacheLookupOptions {\n\tnow?: Date;\n\tmaxAgeMs?: number;\n\tauthority?: ScopeMembershipCacheAuthority | null;\n}\n\ninterface JoinedMembershipRow extends CoordinatorScopeMembership {\n\tscope_label: string | null;\n\tscope_kind: string | null;\n\tscope_authority_type: string | null;\n\tscope_coordinator_id: string | null;\n\tscope_group_id: string | null;\n\tscope_manifest_issuer_device_id: string | null;\n\tscope_membership_epoch: number | null;\n\tscope_manifest_hash: string | null;\n\tscope_status: string | null;\n\tscope_created_at: string | null;\n\tscope_updated_at: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction nowIso(now?: Date): string {\n\treturn (now ?? new Date()).toISOString();\n}\n\nfunction groupIds(input: string[]): string[] {\n\treturn [...new Set(input.map((item) => item.trim()).filter(Boolean))].toSorted();\n}\n\nfunction authorityId(remoteUrl: string | null | undefined): string {\n\tconst remote = clean(remoteUrl);\n\tif (!remote) return \"local\";\n\ttry {\n\t\treturn buildBaseUrl(remote);\n\t} catch {\n\t\treturn remote;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\tif (error instanceof Error) return error.message;\n\treturn String(error ?? \"unknown\");\n}\n\nexport function ensureScopeMembershipCacheStateTable(db: Database): void {\n\tif (hasRefreshRevision(db)) return;\n\t// Recheck under the write lock: another process may have upgraded the cache.\n\tdb.transaction(() => {\n\t\tif (hasRefreshRevision(db)) return;\n\t\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tlast_refresh_at TEXT NOT NULL,\n\t\t\tlast_success_at TEXT,\n\t\t\tlast_error TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t)\n\t`);\n\t\tif (!hasRefreshRevision(db))\n\t\t\tdb.exec(\n\t\t\t\t\"ALTER TABLE scope_membership_cache_state ADD COLUMN refresh_revision INTEGER NOT NULL DEFAULT 0\",\n\t\t\t);\n\t}).immediate();\n}\n\nfunction hasRefreshRevision(db: Database): boolean {\n\treturn !!db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info('scope_membership_cache_state') WHERE name = ?\")\n\t\t.get(\"refresh_revision\");\n}\n\n/** Local write ordering only; neither a membership epoch nor a permission lease. */\nfunction readRefreshRevision(db: Database, authority: ScopeMembershipCacheAuthority): number {\n\tconst row = db\n\t\t.prepare(`SELECT refresh_revision FROM scope_membership_cache_state\n\t\tWHERE coordinator_id = ? AND group_id = ?`)\n\t\t.get(authority.coordinatorId, authority.groupId) as { refresh_revision: number } | undefined;\n\tconst revision = row ? row.refresh_revision : 0;\n\tif (!Number.isSafeInteger(revision) || revision < 0 || revision >= Number.MAX_SAFE_INTEGER)\n\t\tthrow new Error(\"Scope membership cache revision unavailable.\");\n\treturn revision;\n}\n\nfunction coordinatorUrl(opts: RefreshScopeMembershipCacheOptions): string {\n\tconst remote = clean(opts.remoteUrl);\n\tif (!remote) throw new Error(\"Coordinator URL required.\");\n\treturn buildBaseUrl(remote);\n}\n\nfunction signedCoordinatorGet(\n\tdb: Database,\n\turl: string,\n\tkeysDir?: string | null,\n\tdbPath?: string,\n): Promise<Record<string, unknown> | null> {\n\tconst [deviceId] = ensureDeviceIdentity(db, { keysDir: keysDir ?? undefined });\n\tconst bodyBytes = Buffer.alloc(0);\n\tconst headers = buildAuthHeaders({\n\t\tdeviceId,\n\t\tmethod: \"GET\",\n\t\turl,\n\t\tbodyBytes,\n\t\tkeysDir: keysDir ?? undefined,\n\t\tdbPath,\n\t});\n\treturn requestJson(\"GET\", url, {\n\t\theaders,\n\t}).then(([status, payload]) => {\n\t\tif (status < 200 || status >= 300) {\n\t\t\tthrow new Error(`Coordinator membership snapshot failed (${status})`);\n\t\t}\n\t\treturn payload;\n\t});\n}\n\nfunction authenticatedFetchers(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): ScopeMembershipCacheFetchers {\n\tconst baseUrl = coordinatorUrl(opts);\n\treturn {\n\t\tlistScopes: async (groupId) => {\n\t\t\tconst url = `${baseUrl}/v1/scopes?group_id=${encodeURIComponent(groupId)}`;\n\t\t\treturn (await signedCoordinatorGet(\n\t\t\t\tdb,\n\t\t\t\turl,\n\t\t\t\topts.keysDir,\n\t\t\t\topts.dbPath,\n\t\t\t)) as unknown as ScopeMembershipCatalog;\n\t\t},\n\t\tgetScopeSnapshot: async (groupId, scopeId) => {\n\t\t\tconst url = `${baseUrl}/v1/scopes/${encodeURIComponent(scopeId)}/members?group_id=${encodeURIComponent(groupId)}`;\n\t\t\treturn (await signedCoordinatorGet(\n\t\t\t\tdb,\n\t\t\t\turl,\n\t\t\t\topts.keysDir,\n\t\t\t\topts.dbPath,\n\t\t\t)) as unknown as ScopeMembershipSnapshot;\n\t\t},\n\t};\n}\n\nfunction defaultFetchers(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): ScopeMembershipCacheFetchers {\n\tif (clean(opts.remoteUrl)) return authenticatedFetchers(db, opts);\n\treturn {\n\t\tlistScopes: (groupId) =>\n\t\t\twithLocalCoordinator(opts, async (store) => ({\n\t\t\t\tversion: 1,\n\t\t\t\titems: await store.listScopes({ groupId }),\n\t\t\t})),\n\t\tgetScopeSnapshot: (groupId, scopeId) =>\n\t\t\twithLocalCoordinator(opts, async (store) => {\n\t\t\t\tconst decision = await store.getScopeAuthorization({ groupId, scopeId });\n\t\t\t\tif (decision.kind !== \"authorized\") throw new Error(decision.error);\n\t\t\t\treturn {\n\t\t\t\t\tauthorization_version: decision.authorizationVersion,\n\t\t\t\t\tscope: decision.scope,\n\t\t\t\t\titems: decision.members.map(({ membership, enrollment, keyId }) => ({\n\t\t\t\t\t\tmembership,\n\t\t\t\t\t\tenrollment,\n\t\t\t\t\t\tkey_id: keyId,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}),\n\t};\n}\n\nasync function withLocalCoordinator<T>(\n\topts: RefreshScopeMembershipCacheOptions,\n\tread: (store: BetterSqliteCoordinatorStore) => Promise<T>,\n): Promise<T> {\n\tconst store = new BetterSqliteCoordinatorStore(\n\t\topts.coordinatorDbPath ?? DEFAULT_COORDINATOR_DB_PATH,\n\t);\n\ttry {\n\t\treturn await read(store);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nfunction upsertScope(db: Database, scope: CoordinatorScope): void {\n\tdb.prepare(\n\t\t`INSERT INTO replication_scopes(\n\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(scope_id) DO UPDATE SET\n\t\t\tlabel = excluded.label,\n\t\t\tkind = excluded.kind,\n\t\t\tauthority_type = excluded.authority_type,\n\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\tgroup_id = excluded.group_id,\n\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\tstatus = excluded.status,\n\t\t\tupdated_at = excluded.updated_at\n\t\tWHERE excluded.membership_epoch >= replication_scopes.membership_epoch`,\n\t).run(\n\t\tscope.scope_id,\n\t\tscope.label,\n\t\tscope.kind,\n\t\tscope.authority_type,\n\t\tscope.coordinator_id,\n\t\tscope.group_id,\n\t\tscope.manifest_issuer_device_id,\n\t\tscope.membership_epoch,\n\t\tscope.manifest_hash,\n\t\tscope.status,\n\t\tscope.created_at,\n\t\tscope.updated_at,\n\t);\n}\n\nfunction placeholders(count: number): string {\n\treturn Array.from({ length: count }, () => \"?\").join(\", \");\n}\n\nfunction reconcileScopeMembershipSnapshot(\n\tdb: Database,\n\tbatch: CurrentScopeBatch,\n\tauthority: ScopeMembershipCacheAuthority,\n\ttimestamp: string,\n): void {\n\tconst { scope, memberships, sourceCoordinatorId } = batch;\n\t// The authorized scope-members endpoint returns the complete membership list\n\t// that is active at the current epoch, so absence is fail-closed here.\n\tconst deviceIds = memberships.map((membership) => membership.device_id);\n\tconst deviceFilter =\n\t\tdeviceIds.length > 0 ? `AND device_id NOT IN (${placeholders(deviceIds.length)})` : \"\";\n\tdb.prepare(\n\t\t`UPDATE scope_memberships\n\t\t SET status = 'revoked',\n\t\t\t membership_epoch = CASE WHEN membership_epoch > ? THEN membership_epoch ELSE ? END,\n\t\t\t coordinator_id = ?,\n\t\t\t group_id = ?,\n\t\t\t updated_at = ?\n\t\t WHERE scope_id = ?\n\t\t\t AND COALESCE(coordinator_id, ?) IN (?, ?)\n\t\t\t AND COALESCE(group_id, ?) = ?\n\t\t\t AND status != 'revoked'\n\t\t\t ${deviceFilter}`,\n\t).run(\n\t\tscope.membership_epoch,\n\t\tscope.membership_epoch,\n\t\tauthority.coordinatorId,\n\t\tauthority.groupId,\n\t\ttimestamp,\n\t\tscope.scope_id,\n\t\tauthority.coordinatorId,\n\t\tauthority.coordinatorId,\n\t\tsourceCoordinatorId,\n\t\tauthority.groupId,\n\t\tauthority.groupId,\n\t\t...deviceIds,\n\t);\n}\n\nfunction reconcileGroupScopeSnapshot(\n\tdb: Database,\n\tauthority: ScopeMembershipCacheAuthority,\n\tscopes: CoordinatorScope[],\n\ttimestamp: string,\n): void {\n\tconst scopeIds = scopes.map((scope) => scope.scope_id);\n\tconst scopeFilter =\n\t\tscopeIds.length > 0 ? `AND scope_id NOT IN (${placeholders(scopeIds.length)})` : \"\";\n\tconst missing = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE coordinator_id = ?\n\t\t\t\t AND group_id = ?\n\t\t\t\t AND status <> 'archived'\n\t\t\t\t ${scopeFilter}`,\n\t\t)\n\t\t.all(authority.coordinatorId, authority.groupId, ...scopeIds) as Array<{ scope_id: string }>;\n\tif (missing.length === 0) return;\n\tconst missingScopeIds = missing.map((row) => row.scope_id);\n\tdb.prepare(\n\t\t`UPDATE replication_scopes\n\t\t SET status = 'archived', updated_at = ?\n\t\t WHERE coordinator_id = ?\n\t\t\t AND group_id = ?\n\t\t\t AND scope_id IN (${placeholders(missingScopeIds.length)})`,\n\t).run(timestamp, authority.coordinatorId, authority.groupId, ...missingScopeIds);\n\t// Enrolled-device scope listings are filtered by the requester's current access.\n\t// Archiving the omitted scope fails closed without poisoning unchanged peer rows\n\t// as revoked; a later visible snapshot can reconcile its full membership list.\n}\n\nexport function upsertCachedScopeMemberships(\n\tdb: Database,\n\tmemberships: CoordinatorScopeMembership[],\n): number {\n\tconst insert = db.prepare(\n\t\t`INSERT INTO scope_memberships(\n\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\trole = excluded.role,\n\t\t\tstatus = excluded.status,\n\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\tgroup_id = excluded.group_id,\n\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\tupdated_at = excluded.updated_at\n\t\tWHERE excluded.membership_epoch > scope_memberships.membership_epoch\n\t\t\tOR (\n\t\t\t\texcluded.membership_epoch = scope_memberships.membership_epoch\n\t\t\t\tAND scope_memberships.status != 'revoked'\n\t\t\t)`,\n\t);\n\tlet count = 0;\n\tdb.transaction(() => {\n\t\tfor (const membership of memberships) {\n\t\t\tinsert.run(\n\t\t\t\tmembership.scope_id,\n\t\t\t\tmembership.device_id,\n\t\t\t\tmembership.role,\n\t\t\t\tmembership.status,\n\t\t\t\tmembership.membership_epoch,\n\t\t\t\tmembership.coordinator_id,\n\t\t\t\tmembership.group_id,\n\t\t\t\tmembership.manifest_issuer_device_id,\n\t\t\t\tmembership.manifest_hash,\n\t\t\t\tmembership.signed_manifest_json,\n\t\t\t\tmembership.updated_at,\n\t\t\t);\n\t\t\tcount += 1;\n\t\t}\n\t})();\n\treturn count;\n}\n\nfunction recordRefreshState(\n\tdb: Database,\n\tinput: ScopeMembershipCacheAuthority & { ok: boolean; error?: string | null; now: string },\n): void {\n\tensureScopeMembershipCacheStateTable(db);\n\treadRefreshRevision(db, input);\n\tconst result = db\n\t\t.prepare(\n\t\t\t`INSERT INTO scope_membership_cache_state(\n\t\t\tcoordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at, refresh_revision\n\t\t) VALUES (?, ?, ?, ?, ?, ?, 1)\n\t\tON CONFLICT(coordinator_id, group_id) DO UPDATE SET\n\t\t\tlast_refresh_at = excluded.last_refresh_at,\n\t\t\tlast_success_at = COALESCE(excluded.last_success_at, scope_membership_cache_state.last_success_at),\n\t\t\tlast_error = excluded.last_error,\n\t\t\tupdated_at = excluded.updated_at,\n\t\t\trefresh_revision = scope_membership_cache_state.refresh_revision + 1\n\t\tWHERE scope_membership_cache_state.refresh_revision < 9007199254740991`,\n\t\t)\n\t\t.run(\n\t\t\tinput.coordinatorId,\n\t\t\tinput.groupId,\n\t\t\tinput.now,\n\t\t\tinput.ok ? input.now : null,\n\t\t\tinput.ok ? null : (input.error ?? \"unknown\"),\n\t\t\tinput.now,\n\t\t);\n\tif (result.changes !== 1) throw new Error(\"Scope membership cache revision unavailable.\");\n}\n\nfunction loadCacheStates(\n\tdb: Database,\n\tauthority?: ScopeMembershipCacheAuthority | null,\n): ScopeMembershipCacheState[] {\n\tif (\n\t\t!db\n\t\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t\t.get(\"scope_membership_cache_state\")\n\t)\n\t\treturn [];\n\tif (authority) {\n\t\treturn db\n\t\t\t.prepare(\n\t\t\t\t`SELECT coordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at\n\t\t\t\t FROM scope_membership_cache_state\n\t\t\t\t WHERE coordinator_id = ? AND group_id = ?`,\n\t\t\t)\n\t\t\t.all(authority.coordinatorId, authority.groupId) as ScopeMembershipCacheState[];\n\t}\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT coordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at\n\t\t\t FROM scope_membership_cache_state\n\t\t\t ORDER BY coordinator_id ASC, group_id ASC`,\n\t\t)\n\t\t.all() as ScopeMembershipCacheState[];\n}\n\nfunction recordRefreshFailure(\n\tdb: Database,\n\tinput: ScopeMembershipCacheAuthority & { error: string; now: string },\n\texpectedRevision: number | undefined,\n): string {\n\tif (expectedRevision === undefined) return \"Scope membership cache revision unavailable.\";\n\ttry {\n\t\tdb.transaction(() => {\n\t\t\t// A delayed failure must not overwrite a newer refresh or advance its revision.\n\t\t\tif (readRefreshRevision(db, input) !== expectedRevision) return;\n\t\t\trecordRefreshState(db, { ...input, ok: false });\n\t\t}).immediate();\n\t\treturn input.error;\n\t} catch {\n\t\treturn \"Scope membership cache refresh state unavailable.\";\n\t}\n}\n\nfunction freshness(\n\tstates: ScopeMembershipCacheState[],\n\toptions: { now?: Date; maxAgeMs?: number },\n): ScopeMembershipCacheFreshness {\n\tif (states.length === 0) return \"unknown\";\n\tif (states.some((state) => clean(state.last_error) != null)) return \"stale\";\n\tconst maxAgeMs = options.maxAgeMs ?? DEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS;\n\tconst nowMs = (options.now ?? new Date()).getTime();\n\treturn states.some((state) => {\n\t\tconst refreshedAt = Date.parse(state.last_success_at ?? \"\");\n\t\treturn !Number.isFinite(refreshedAt) || nowMs - refreshedAt > maxAgeMs;\n\t})\n\t\t? \"stale\"\n\t\t: \"fresh\";\n}\n\nfunction scopeFromJoinedRow(row: JoinedMembershipRow): CoordinatorScope | null {\n\tif (!row.scope_label || !row.scope_kind || !row.scope_authority_type) return null;\n\treturn {\n\t\tscope_id: row.scope_id,\n\t\tlabel: row.scope_label,\n\t\tkind: row.scope_kind,\n\t\tauthority_type: row.scope_authority_type,\n\t\tcoordinator_id: row.scope_coordinator_id,\n\t\tgroup_id: row.scope_group_id,\n\t\tmanifest_issuer_device_id: row.scope_manifest_issuer_device_id,\n\t\tmembership_epoch: row.scope_membership_epoch ?? row.membership_epoch,\n\t\tmanifest_hash: row.scope_manifest_hash,\n\t\tstatus: row.scope_status ?? \"active\",\n\t\tcreated_at: row.scope_created_at ?? row.updated_at,\n\t\tupdated_at: row.scope_updated_at ?? row.updated_at,\n\t};\n}\n\nfunction loadScope(\n\tdb: Database,\n\tscopeId: string,\n\tauthority?: ScopeMembershipCacheAuthority | null,\n): CoordinatorScope | null {\n\tconst authorityFilter = authority ? \" AND coordinator_id = ? AND group_id = ?\" : \"\";\n\tconst params = authority ? [scopeId, authority.coordinatorId, authority.groupId] : [scopeId];\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t FROM replication_scopes\n\t\t\t WHERE scope_id = ?${authorityFilter}\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(...params) as CoordinatorScope | undefined;\n\treturn row ?? null;\n}\n\nfunction membershipFromJoinedRow(row: JoinedMembershipRow): CoordinatorScopeMembership {\n\treturn {\n\t\tscope_id: row.scope_id,\n\t\tdevice_id: row.device_id,\n\t\trole: row.role,\n\t\tstatus: row.status,\n\t\tmembership_epoch: row.membership_epoch,\n\t\tcoordinator_id: row.coordinator_id,\n\t\tgroup_id: row.group_id,\n\t\tmanifest_issuer_device_id: row.manifest_issuer_device_id,\n\t\tmanifest_hash: row.manifest_hash,\n\t\tsigned_manifest_json: row.signed_manifest_json,\n\t\tupdated_at: row.updated_at,\n\t};\n}\n\nfunction joinedMembershipSelect(whereSql: string): string {\n\treturn `SELECT\n\t\tsm.scope_id,\n\t\tsm.device_id,\n\t\tsm.role,\n\t\tsm.status,\n\t\tsm.membership_epoch,\n\t\tsm.coordinator_id,\n\t\tsm.group_id,\n\t\tsm.manifest_issuer_device_id,\n\t\tsm.manifest_hash,\n\t\tsm.signed_manifest_json,\n\t\tsm.updated_at,\n\t\trs.label AS scope_label,\n\t\trs.kind AS scope_kind,\n\t\trs.authority_type AS scope_authority_type,\n\t\trs.coordinator_id AS scope_coordinator_id,\n\t\trs.group_id AS scope_group_id,\n\t\trs.manifest_issuer_device_id AS scope_manifest_issuer_device_id,\n\t\trs.membership_epoch AS scope_membership_epoch,\n\t\trs.manifest_hash AS scope_manifest_hash,\n\t\trs.status AS scope_status,\n\t\trs.created_at AS scope_created_at,\n\t\trs.updated_at AS scope_updated_at\n\tFROM scope_memberships sm\n\tLEFT JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t${whereSql}`;\n}\n\nfunction authorityFromMembership(\n\tmembership: CoordinatorScopeMembership | null,\n\tfallback?: ScopeMembershipCacheAuthority | null,\n): ScopeMembershipCacheAuthority | null {\n\tconst coordinatorId = clean(membership?.coordinator_id) ?? fallback?.coordinatorId;\n\tconst groupId = clean(membership?.group_id) ?? fallback?.groupId;\n\treturn coordinatorId && groupId ? { coordinatorId, groupId } : null;\n}\n\nfunction authorityFromScope(scope: CoordinatorScope | null): ScopeMembershipCacheAuthority | null {\n\tconst coordinatorId = clean(scope?.coordinator_id);\n\tconst groupId = clean(scope?.group_id);\n\treturn coordinatorId && groupId ? { coordinatorId, groupId } : null;\n}\n\nexport async function refreshScopeMembershipCache(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): Promise<RefreshScopeMembershipCacheResult> {\n\tconst groups = groupIds(opts.groupIds);\n\tif (groups.length === 0) return { status: \"skipped\", coordinatorId: null, groups: [] };\n\tconst coordinatorId = clean(opts.coordinatorId) ?? authorityId(opts.remoteUrl);\n\tconst authorityForGroup = (groupId: string): ScopeMembershipCacheAuthority => ({\n\t\tcoordinatorId,\n\t\tgroupId,\n\t});\n\tconst fetchers = opts.fetchers ?? defaultFetchers(db, opts);\n\tconst timestamp = nowIso(opts.now);\n\tconst results: RefreshScopeMembershipCacheGroupResult[] = [];\n\n\tfor (const groupId of groups) {\n\t\tlet expectedRevision: number | undefined;\n\t\ttry {\n\t\t\tconst authority = authorityForGroup(groupId);\n\t\t\tensureScopeMembershipCacheStateTable(db);\n\t\t\texpectedRevision = readRefreshRevision(db, authority);\n\t\t\tconst membershipBatches = await gatherCurrentSnapshots(fetchers, authority);\n\t\t\tconst scopes = membershipBatches.map((batch) => batch.scope);\n\t\t\tconst error = persistCurrentSnapshots(\n\t\t\t\tdb,\n\t\t\t\tmembershipBatches,\n\t\t\t\tauthority,\n\t\t\t\ttimestamp,\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\tconst membershipCount = membershipBatches.reduce(\n\t\t\t\t(count, batch) => count + batch.memberships.length,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\tgroupId,\n\t\t\t\tstatus: error ? \"stale\" : \"refreshed\",\n\t\t\t\tscopeCount: error ? 0 : scopes.length,\n\t\t\t\tmembershipCount: error ? 0 : membershipCount,\n\t\t\t\terror,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = recordRefreshFailure(\n\t\t\t\tdb,\n\t\t\t\t{ coordinatorId, groupId, error: errorMessage(error), now: timestamp },\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\tresults.push({ groupId, status: \"stale\", scopeCount: 0, membershipCount: 0, error: message });\n\t\t}\n\t}\n\n\tconst refreshed = results.filter((result) => result.status === \"refreshed\").length;\n\tlet status: RefreshScopeMembershipCacheResult[\"status\"] = \"partial\";\n\tif (refreshed === results.length) status = \"refreshed\";\n\telse if (refreshed === 0) status = \"stale\";\n\treturn { status, coordinatorId, groups: results };\n}\n\ntype CurrentScopeBatch = ReturnType<typeof normalizeScopeSnapshot>;\n\nasync function gatherCurrentSnapshots(\n\tfetchers: ScopeMembershipCacheFetchers,\n\tauthority: ScopeMembershipCacheAuthority,\n): Promise<CurrentScopeBatch[]> {\n\tconst catalog = normalizeScopeCatalog(\n\t\tawait fetchers.listScopes(authority.groupId),\n\t\tauthority.groupId,\n\t);\n\tconst batches: CurrentScopeBatch[] = [];\n\tfor (const scope of catalog) {\n\t\tconst snapshot = await fetchers.getScopeSnapshot(authority.groupId, scope.scope_id);\n\t\tbatches.push(\n\t\t\tnormalizeScopeSnapshot(snapshot, scope, authority.groupId, authority.coordinatorId),\n\t\t);\n\t}\n\treturn batches;\n}\n\nfunction matchesSnapshotSource(\n\trow: { coordinator_id: string | null; group_id: string | null },\n\tbatch: CurrentScopeBatch,\n): boolean {\n\treturn (\n\t\t(row.group_id === null || row.group_id === batch.scope.group_id) &&\n\t\t(row.coordinator_id === null ||\n\t\t\trow.coordinator_id === batch.scope.coordinator_id ||\n\t\t\trow.coordinator_id === batch.sourceCoordinatorId)\n\t);\n}\n\nfunction requireUnsupersededSnapshot(db: Database, batch: CurrentScopeBatch): boolean {\n\tconst { scope, memberships } = batch;\n\tconst stored = loadScope(db, scope.scope_id);\n\tif (\n\t\tstored &&\n\t\t(stored.membership_epoch > scope.membership_epoch || !matchesSnapshotSource(stored, batch))\n\t)\n\t\tthrow new Error(\"Current scope snapshot conflicts with cached authority or epoch.\");\n\tconst rows = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, status, membership_epoch, coordinator_id, group_id FROM scope_memberships WHERE scope_id = ?\",\n\t\t)\n\t\t.all(scope.scope_id) as CoordinatorScopeMembership[];\n\tconst incoming = new Map(memberships.map((member) => [member.device_id, member]));\n\tlet revivalConflict = false;\n\tfor (const row of rows) {\n\t\tconst member = incoming.get(row.device_id);\n\t\t// Current omissions remove access even when the member advanced beyond the scope epoch.\n\t\tif (\n\t\t\t(member && row.membership_epoch > member.membership_epoch) ||\n\t\t\t!matchesSnapshotSource(row, batch)\n\t\t)\n\t\t\tthrow new Error(\"Current scope snapshot superseded by cached membership.\");\n\t\tif (member && row.status === \"revoked\" && row.membership_epoch === member.membership_epoch)\n\t\t\trevivalConflict = true;\n\t}\n\treturn revivalConflict;\n}\n\nfunction migrateSnapshotMembershipAuthority(db: Database, batch: CurrentScopeBatch): void {\n\tdb.prepare(\n\t\t`UPDATE scope_memberships SET coordinator_id = ?, group_id = ?\n\t\t WHERE scope_id = ? AND COALESCE(group_id, ?) = ?\n\t\t AND COALESCE(coordinator_id, ?) IN (?, ?)`,\n\t).run(\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.scope_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.sourceCoordinatorId,\n\t);\n}\n\nfunction persistCurrentSnapshots(\n\tdb: Database,\n\tbatches: CurrentScopeBatch[],\n\tauthority: ScopeMembershipCacheAuthority,\n\ttimestamp: string,\n\texpectedRevision: number,\n): string | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (readRefreshRevision(db, authority) !== expectedRevision)\n\t\t\t\treturn \"Current scope snapshot superseded by a newer cache refresh.\";\n\t\t\t// Validate every batch before writes, even when an earlier batch cannot revive a row.\n\t\t\tconst conflicts = batches.map((batch) => requireUnsupersededSnapshot(db, batch));\n\t\t\tconst error = conflicts.some(Boolean)\n\t\t\t\t? \"Current scope snapshot cannot revive cached revoked membership at the same epoch.\"\n\t\t\t\t: null;\n\t\t\tfor (const batch of batches) {\n\t\t\t\tif (!error) {\n\t\t\t\t\tupsertScope(db, batch.scope);\n\t\t\t\t\tmigrateSnapshotMembershipAuthority(db, batch);\n\t\t\t\t\tupsertCachedScopeMemberships(db, batch.memberships);\n\t\t\t\t}\n\t\t\t\treconcileScopeMembershipSnapshot(db, batch, authority, timestamp);\n\t\t\t}\n\t\t\treconcileGroupScopeSnapshot(\n\t\t\t\tdb,\n\t\t\t\tauthority,\n\t\t\t\tbatches.map((batch) => batch.scope),\n\t\t\t\ttimestamp,\n\t\t\t);\n\t\t\ttry {\n\t\t\t\treconcileScopeAuthorizationEvidence(db, batches, authority, {\n\t\t\t\t\tremovalOnly: error !== null,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"Scope authorization evidence unavailable.\");\n\t\t\t}\n\t\t\trecordRefreshState(db, { ...authority, ok: error === null, error, now: timestamp });\n\t\t\treturn error;\n\t\t})\n\t\t.immediate();\n}\n\nexport async function refreshConfiguredScopeMembershipCache(\n\tdb: Database,\n\tconfig?: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string | null; dbPath?: string },\n): Promise<RefreshScopeMembershipCacheResult> {\n\tconst syncConfig = config ?? readCoordinatorSyncConfig();\n\tif (!coordinatorEnabled(syncConfig)) {\n\t\treturn { status: \"skipped\", coordinatorId: null, groups: [] };\n\t}\n\treturn refreshScopeMembershipCache(db, {\n\t\tgroupIds: syncConfig.syncCoordinatorGroups,\n\t\tcoordinatorId: authorityId(syncConfig.syncCoordinatorUrl),\n\t\tremoteUrl: syncConfig.syncCoordinatorUrl,\n\t\tadminSecret: syncConfig.syncCoordinatorAdminSecret,\n\t\tkeysDir: options?.keysDir ?? null,\n\t\tdbPath: options?.dbPath,\n\t});\n}\n\nexport function listCachedScopesForDevice(\n\tdb: Database,\n\tdeviceId: string,\n\topts: ScopeMembershipCacheLookupOptions = {},\n): CachedDeviceScopeMemberships {\n\tconst cleanDeviceId = clean(deviceId);\n\tif (!cleanDeviceId) throw new Error(\"device_id is required.\");\n\tconst params: string[] = [cleanDeviceId];\n\tconst authorityFilter = opts.authority\n\t\t? \" AND COALESCE(sm.coordinator_id, rs.coordinator_id) = ? AND COALESCE(sm.group_id, rs.group_id) = ?\"\n\t\t: \"\";\n\tif (opts.authority) params.push(opts.authority.coordinatorId, opts.authority.groupId);\n\tconst rows = db\n\t\t.prepare(\n\t\t\t`${joinedMembershipSelect(\n\t\t\t\t`WHERE sm.device_id = ? AND sm.status = 'active' AND rs.scope_id IS NOT NULL AND rs.status = 'active' AND sm.membership_epoch >= rs.membership_epoch${authorityFilter}`,\n\t\t\t)} ORDER BY sm.scope_id ASC`,\n\t\t)\n\t\t.all(...params) as JoinedMembershipRow[];\n\tconst cacheStates = loadCacheStates(db, opts.authority ?? null);\n\tconst memberships = rows.filter(\n\t\t(row) =>\n\t\t\tgetAnyRecipientPolicyDenyOverlayForScopeDevice(db, {\n\t\t\t\tscopeId: row.scope_id,\n\t\t\t\tdeviceId: cleanDeviceId,\n\t\t\t}) == null,\n\t);\n\treturn {\n\t\tdeviceId: cleanDeviceId,\n\t\tfreshness: freshness(cacheStates, opts),\n\t\tmemberships: memberships.map((row) => ({\n\t\t\t...membershipFromJoinedRow(row),\n\t\t\tscope: scopeFromJoinedRow(row),\n\t\t})),\n\t\tcacheStates,\n\t};\n}\n\nexport function getCachedScopeAuthorization(\n\tdb: Database,\n\tinput: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions,\n): CachedScopeAuthorization {\n\tif (!clean(input.deviceId) || !clean(input.scopeId))\n\t\tthrow new Error(\"device_id and scope_id are required.\");\n\treturn readCachedScopeAuthorization(db, input);\n}\n\n/** Managed access needs a current-refresh proof, not merely historical cache rows.\n * This read neither creates evidence nor refreshes permissions or adds an expiry. */\nexport function getEffectiveCachedScopeAuthorization(\n\tdb: Database,\n\tinput: {\n\t\tdeviceId: string;\n\t\tscopeId: string;\n\t\texpectedPublicKey?: string;\n\t} & ScopeMembershipCacheLookupOptions,\n): EffectiveCachedScopeAuthorization {\n\tconst cached = readCachedScopeAuthorization(db, input);\n\tif (!cached.authorized || cached.scope?.authority_type !== \"coordinator\")\n\t\treturn { ...cached, keyId: null };\n\tconst keyId =\n\t\tcached.membership &&\n\t\tgetRetainedScopeAuthorizationKey(db, cached.scope, cached.membership, input.expectedPublicKey);\n\tif (!keyId) return { ...cached, authorized: false, state: \"not_authorized\", keyId: null };\n\treturn { ...cached, keyId };\n}\n\nfunction readCachedScopeAuthorization(\n\tdb: Database,\n\tinput: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions,\n): CachedScopeAuthorization {\n\tconst deviceId = clean(input.deviceId);\n\tconst scopeId = clean(input.scopeId);\n\tif (!deviceId || !scopeId) throw new Error(\"device_id and scope_id are required.\");\n\tconst { membership, scope } = readCachedScopeRows(db, { ...input, deviceId, scopeId });\n\tconst authority = authorityFromMembership(\n\t\tmembership,\n\t\tinput.authority ?? authorityFromScope(scope),\n\t);\n\tconst cacheStates = loadCacheStates(db, authority);\n\tconst epoch = scopeMembershipEpochStatus({\n\t\tmembershipEpoch: membership?.membership_epoch ?? null,\n\t\trequiredEpoch: scope?.membership_epoch ?? null,\n\t});\n\tconst state = cachedScopeDecisionState({\n\t\tmembership,\n\t\tscope,\n\t\tepoch,\n\t\tpolicyDenied: !!getAnyRecipientPolicyDenyOverlayForScopeDevice(db, { deviceId, scopeId }),\n\t});\n\tlet revocation: ScopeMembershipRevocationNotice | null = null;\n\tif (state === \"revoked\" && membership)\n\t\trevocation = explainScopeMembershipRevocation({\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tmembershipEpoch: membership.membership_epoch,\n\t\t});\n\treturn {\n\t\tdeviceId,\n\t\tscopeId,\n\t\tauthorized: state === \"authorized\",\n\t\tstate,\n\t\tfreshness: freshness(cacheStates, input),\n\t\tepoch,\n\t\trevocation,\n\t\tmembership,\n\t\tscope,\n\t\tcacheStates,\n\t};\n}\n\nfunction readCachedScopeRows(\n\tdb: Database,\n\tinput: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions,\n): { membership: CoordinatorScopeMembership | null; scope: CoordinatorScope | null } {\n\tconst authorityFilter = input.authority\n\t\t? \" AND COALESCE(sm.coordinator_id, rs.coordinator_id) = ? AND COALESCE(sm.group_id, rs.group_id) = ?\"\n\t\t: \"\";\n\tconst params = input.authority\n\t\t? [input.deviceId, input.scopeId, input.authority.coordinatorId, input.authority.groupId]\n\t\t: [input.deviceId, input.scopeId];\n\tconst row = db\n\t\t.prepare(\n\t\t\t`${joinedMembershipSelect(`WHERE sm.device_id = ? AND sm.scope_id = ?${authorityFilter} LIMIT 1`)}`,\n\t\t)\n\t\t.get(...params) as JoinedMembershipRow | undefined;\n\tconst membership = row ? membershipFromJoinedRow(row) : null;\n\tconst scope = row\n\t\t? scopeFromJoinedRow(row)\n\t\t: loadScope(db, input.scopeId, input.authority ?? null);\n\treturn { membership, scope };\n}\n\nfunction cachedScopeDecisionState(input: {\n\tmembership: CoordinatorScopeMembership | null;\n\tscope: CoordinatorScope | null;\n\tepoch: ScopeMembershipEpochStatus;\n\tpolicyDenied: boolean;\n}): ScopeMembershipAuthorizationState {\n\tconst { membership, scope, epoch, policyDenied } = input;\n\tif (policyDenied) return \"policy_denied\";\n\tif (!membership) return \"not_authorized\";\n\tif (membership.status === \"revoked\") return \"revoked\";\n\tif (scope?.status && scope.status !== \"active\") return \"scope_inactive\";\n\tif (!scope) return \"scope_unknown\";\n\tif (epoch.stale) return \"stale_epoch\";\n\treturn membership.status === \"active\" ? \"authorized\" : \"not_authorized\";\n}\n","const matchesDot = (character: string): boolean =>\n\t![\"\\n\", \"\\r\", \"\\u2028\", \"\\u2029\"].includes(character);\n\nfunction matchesSingle(token: string, character: string): boolean {\n\treturn token === \"?\" ? matchesDot(character) : token === character;\n}\n\nfunction advanceWildcardRow(previous: Uint8Array, token: string, characters: string[]): Uint8Array {\n\tconst next = new Uint8Array(characters.length + 1);\n\tif (token === \"*\") next[0] = previous[0] ?? 0;\n\tfor (let index = 1; index <= characters.length; index += 1) {\n\t\tconst character = characters[index - 1] ?? \"\";\n\t\tif (token === \"*\") {\n\t\t\tnext[index] = previous[index] || (next[index - 1] && matchesDot(character)) ? 1 : 0;\n\t\t} else if (matchesSingle(token, character)) {\n\t\t\tnext[index] = previous[index - 1] ?? 0;\n\t\t}\n\t}\n\treturn next;\n}\n\n/** Match the legacy wildcard language without exploring wildcard partitions.\n * Each pattern/input pair is visited once: O(pattern × input) time,\n * O(pattern + input) space for tokens and the current/previous rows.\n * Scope resolution historically used UTF-16 units; recipient projection used /u.\n */\nexport function matchesWildcard(\n\tidentity: string,\n\tpattern: string,\n\toptions: { unicode: boolean },\n): boolean {\n\tconst characters = options.unicode ? Array.from(identity) : identity.split(\"\");\n\tconst tokens = options.unicode ? Array.from(pattern) : pattern.split(\"\");\n\tlet previous: Uint8Array = new Uint8Array(characters.length + 1);\n\tprevious[0] = 1;\n\tfor (const token of tokens) {\n\t\tprevious = advanceWildcardRow(previous, token, characters);\n\t}\n\treturn previous[characters.length] === 1;\n}\n","import { resolve } from \"node:path\";\nimport type { Database } from \"better-sqlite3\";\nimport { cleanProjectIdentity } from \"./project-identity.js\";\nimport { getEffectiveCachedScopeAuthorization } from \"./scope-membership-cache.js\";\nimport { matchesWildcard } from \"./wildcard-match.js\";\nimport {\n\ttype CanonicalWorkspaceIdentity,\n\tcanonicalWorkspaceIdentity,\n\ttype WorkspaceIdentityInput,\n} from \"./workspace-identity.js\";\n\nexport {\n\ttype CanonicalWorkspaceIdentity,\n\tcanonicalWorkspaceIdentity,\n\ttype WorkspaceIdentityInput,\n\ttype WorkspaceIdentitySource,\n} from \"./workspace-identity.js\";\n\nexport const LOCAL_DEFAULT_SCOPE_ID = \"local-default\";\n\n/**\n * Scope id used by the conservative migration backfill for legacy shared\n * memories that cannot yet be assigned to a concrete team/org scope. Single\n * source of truth: filters.ts and scope-backfill.ts re-import this so the\n * read-visibility predicate and the backfill agree on one literal.\n */\nexport const LEGACY_SHARED_REVIEW_SCOPE_ID = \"legacy-shared-review\";\n\n/**\n * Upper bound on how many scope ids we will inline into the index-eligible\n * `scope_id IN (...)` fast path (one bound parameter each). Larger sets use\n * a single JSON array parameter instead of exceeding SQLite's variable limit.\n */\nexport const MAX_SCOPE_IN_PARAMS = 500;\n\nexport interface ScopeMapping {\n\tid?: number | null;\n\tworkspace_identity?: string | null;\n\tproject_pattern: string;\n\tscope_id: string;\n\tpriority?: number | null;\n\tupdated_at?: string | null;\n\tsource?: string | null;\n}\n\nexport type ScopeResolutionReason =\n\t| \"explicit_override\"\n\t| \"exact_mapping\"\n\t| \"pattern_mapping\"\n\t| \"local_default\";\n\nexport interface ScopeResolution {\n\tscopeId: string;\n\treason: ScopeResolutionReason;\n\tworkspaceIdentity: CanonicalWorkspaceIdentity;\n\tmapping: ScopeMapping | null;\n\tmatchedPattern: string | null;\n}\n\nexport interface ResolveProjectScopeInput extends WorkspaceIdentityInput {\n\tallowRepositoryCwdFallback?: boolean;\n\texplicitScopeId?: string | null;\n\tmappings?: ScopeMapping[];\n\tlocalDefaultScopeId?: string;\n}\n\ninterface MappingCandidate {\n\tmapping: ScopeMapping;\n\tspecificity: number;\n\tmatchedPattern: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction normalizeSlash(value: string): string {\n\tconst normalized = value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\");\n\treturn normalized || value.trim();\n}\n\nfunction normalizeCwd(cwd: string): string {\n\t// Callers should pass an already-realpathed session cwd when symlink\n\t// resolution matters; this pure helper only normalizes path syntax.\n\treturn normalizeSlash(resolve(cwd));\n}\n\nfunction normalizeMappingIdentity(value: string | null | undefined): string | null {\n\tconst cleaned = clean(value);\n\treturn cleaned ? normalizeSlash(cleaned) : null;\n}\n\nfunction isBasenameOnlyPattern(pattern: string): boolean {\n\treturn !/[\\\\/:]/.test(pattern);\n}\n\nfunction patternSpecificity(pattern: string): number {\n\treturn pattern.replace(/[*?]/g, \"\").length;\n}\n\nfunction matchesPattern(identity: string, pattern: string): boolean {\n\tconst normalizedPattern = normalizeSlash(pattern);\n\tif (!normalizedPattern || isBasenameOnlyPattern(normalizedPattern)) return false;\n\tif (!/[*?]/.test(normalizedPattern)) return identity === normalizedPattern;\n\treturn matchesWildcard(identity, normalizedPattern, { unicode: false });\n}\n\nfunction candidatePriority(candidate: MappingCandidate): number {\n\treturn candidate.mapping.priority ?? 0;\n}\n\nfunction candidateUpdatedAt(candidate: MappingCandidate): number {\n\tconst updatedAt = clean(candidate.mapping.updated_at);\n\tif (!updatedAt) return 0;\n\tconst time = Date.parse(updatedAt);\n\treturn Number.isFinite(time) ? time : 0;\n}\n\nfunction compareCandidates(a: MappingCandidate, b: MappingCandidate): number {\n\treturn (\n\t\tcandidatePriority(b) - candidatePriority(a) ||\n\t\tb.specificity - a.specificity ||\n\t\tcandidateUpdatedAt(b) - candidateUpdatedAt(a) ||\n\t\t(b.mapping.id ?? 0) - (a.mapping.id ?? 0) ||\n\t\ta.mapping.scope_id.localeCompare(b.mapping.scope_id)\n\t);\n}\n\nfunction bestCandidate(candidates: MappingCandidate[]): MappingCandidate | null {\n\treturn candidates.toSorted(compareCandidates)[0] ?? null;\n}\n\nfunction exactMappingIdentities(\n\tinput: ResolveProjectScopeInput,\n\tworkspaceIdentity: CanonicalWorkspaceIdentity,\n): string[] {\n\tconst identities = [workspaceIdentity.value];\n\tif (input.allowRepositoryCwdFallback === false) return identities;\n\tif (\n\t\tworkspaceIdentity.source !== \"git_repository\" &&\n\t\tworkspaceIdentity.source !== \"git_remote\" &&\n\t\tworkspaceIdentity.source !== \"git_remote_branch\"\n\t) {\n\t\treturn identities;\n\t}\n\tconst cwd = cleanProjectIdentity(input.cwd);\n\tif (cwd) identities.push(normalizeCwd(cwd));\n\treturn identities;\n}\n\nfunction patternMappingIdentities(\n\tinput: ResolveProjectScopeInput,\n\tworkspaceIdentity: CanonicalWorkspaceIdentity,\n): string[] {\n\tconst identities = [workspaceIdentity.value];\n\tif (input.allowRepositoryCwdFallback === false) return identities;\n\tif (\n\t\tworkspaceIdentity.source !== \"git_repository\" &&\n\t\tworkspaceIdentity.source !== \"git_remote\" &&\n\t\tworkspaceIdentity.source !== \"git_remote_branch\"\n\t) {\n\t\treturn identities;\n\t}\n\tconst cwd = cleanProjectIdentity(input.cwd);\n\tif (cwd) identities.push(normalizeCwd(cwd));\n\treturn identities;\n}\n\nfunction bestExactMapping(mappings: ScopeMapping[], identities: string[]): MappingCandidate | null {\n\tfor (const identity of identities) {\n\t\tconst candidate = bestCandidate(\n\t\t\tmappings\n\t\t\t\t.filter((mapping) => normalizeMappingIdentity(mapping.workspace_identity) === identity)\n\t\t\t\t.map((mapping) => ({ mapping, matchedPattern: null, specificity: identity.length })),\n\t\t);\n\t\tif (candidate) return candidate;\n\t}\n\treturn null;\n}\n\nfunction bestPatternMapping(\n\tmappings: ScopeMapping[],\n\tidentities: string[],\n): MappingCandidate | null {\n\treturn bestCandidate(\n\t\tidentities.flatMap((identity) =>\n\t\t\tmappings.flatMap((mapping): MappingCandidate[] => {\n\t\t\t\tif (clean(mapping.workspace_identity)) return [];\n\t\t\t\tconst projectPattern = clean(mapping.project_pattern);\n\t\t\t\tif (!projectPattern || !matchesPattern(identity, projectPattern)) return [];\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tmapping,\n\t\t\t\t\t\tmatchedPattern: normalizeSlash(projectPattern),\n\t\t\t\t\t\tspecificity: patternSpecificity(projectPattern),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}),\n\t\t),\n\t);\n}\n\nexport function scopeIdsMatchingProjectPatterns(\n\tmappings: ScopeMapping[],\n\tworkspaceIdentities: Iterable<string>,\n): Set<string> {\n\tconst identities = [...workspaceIdentities].map(normalizeSlash);\n\tconst scopeIds = new Set<string>();\n\tfor (const mapping of mappings) {\n\t\tif (clean(mapping.workspace_identity)) continue;\n\t\tconst projectPattern = clean(mapping.project_pattern);\n\t\tif (\n\t\t\t!projectPattern ||\n\t\t\t!identities.some((identity) => matchesPattern(identity, projectPattern))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tscopeIds.add(mapping.scope_id);\n\t}\n\treturn scopeIds;\n}\n\nexport function resolveProjectScope(input: ResolveProjectScopeInput): ScopeResolution {\n\tconst workspaceIdentity = canonicalWorkspaceIdentity(input);\n\tconst explicitScopeId = clean(input.explicitScopeId);\n\tif (explicitScopeId) {\n\t\treturn {\n\t\t\tscopeId: explicitScopeId,\n\t\t\treason: \"explicit_override\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\tif (workspaceIdentity.source === \"unmapped\") {\n\t\treturn {\n\t\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\t\treason: \"local_default\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst mappings = input.mappings ?? [];\n\tconst exactIdentities = exactMappingIdentities(input, workspaceIdentity);\n\tconst exact = bestExactMapping(mappings, exactIdentities);\n\tif (exact) {\n\t\treturn {\n\t\t\tscopeId: exact.mapping.scope_id,\n\t\t\treason: \"exact_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: exact.mapping,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst pattern = bestPatternMapping(mappings, patternMappingIdentities(input, workspaceIdentity));\n\tif (pattern) {\n\t\treturn {\n\t\t\tscopeId: pattern.mapping.scope_id,\n\t\t\treason: \"pattern_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: pattern.mapping,\n\t\t\tmatchedPattern: pattern.matchedPattern,\n\t\t};\n\t}\n\n\treturn {\n\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\treason: \"local_default\",\n\t\tworkspaceIdentity,\n\t\tmapping: null,\n\t\tmatchedPattern: null,\n\t};\n}\n\nexport interface ScopeVisibilityOptions {\n\t/** Public key of the runtime's actual signing key, not an enrolled DB row. */\n\texpectedPublicKey?: string;\n\t/** Read-only key loader, called once only when coordinator candidates exist. */\n\tloadExpectedPublicKey?: () => string | undefined;\n}\n\nfunction resolveVisibilityPublicKey(\n\tmemberScopes: Array<{ scope_id: string | null; authority_type: string }>,\n\toptions: ScopeVisibilityOptions,\n): string | undefined {\n\tif (options.expectedPublicKey != null) return options.expectedPublicKey;\n\tif (!memberScopes.some((row) => row.scope_id != null && row.authority_type === \"coordinator\"))\n\t\treturn undefined;\n\treturn options.loadExpectedPublicKey?.();\n}\n\n/**\n * Resolve readable scopes once per request. Coordinator membership SQL lists\n * candidates only; retained proof must match the supplied actual signing key.\n * Unknown scopes deny, while local/manual/invite scopes retain existing rules.\n * NULL scopes remain the filter's dedicated local-default branch.\n */\nexport function resolveVisibleScopeIds(\n\tdb: Database,\n\tdeviceId: string,\n\toptions: ScopeVisibilityOptions = {},\n): string[] {\n\tconst visible = new Set<string>([\"\", LOCAL_DEFAULT_SCOPE_ID, LEGACY_SHARED_REVIEW_SCOPE_ID]);\n\tconst localScopes = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'local'`,\n\t\t)\n\t\t.all() as Array<{ scope_id: string | null }>;\n\tfor (const row of localScopes) {\n\t\tif (row.scope_id != null) visible.add(row.scope_id);\n\t}\n\tconst memberScopes = db\n\t\t.prepare(\n\t\t\t`SELECT sm.scope_id AS scope_id, rs.authority_type\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch`,\n\t\t)\n\t\t.all(deviceId) as Array<{ scope_id: string | null; authority_type: string }>;\n\tconst expectedPublicKey = resolveVisibilityPublicKey(memberScopes, options);\n\tfor (const row of memberScopes) {\n\t\tif (row.scope_id == null) continue;\n\t\tif ([\"local\", \"manual\", \"invite\"].includes(row.authority_type)) {\n\t\t\tvisible.add(row.scope_id);\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.authority_type !== \"coordinator\") continue;\n\t\tif (!expectedPublicKey?.trim()) continue;\n\t\tconst authorization = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId,\n\t\t\tscopeId: row.scope_id,\n\t\t\texpectedPublicKey,\n\t\t});\n\t\tif (!authorization.authorized) continue;\n\t\tvisible.add(row.scope_id);\n\t}\n\treturn [...visible];\n}\n","/**\n * Filter builder for memory_items queries.\n *\n * Mirrors Python's _extend_memory_filter_clauses in codemem/store/search.py.\n * Builds WHERE clause fragments and parameter arrays from a MemoryFilters object.\n */\n\nimport type { Database } from \"./db.js\";\nimport { matchingLocalCreationClause } from \"./memory-creation-provenance.js\";\nimport { localCreationSourceIds } from \"./memory-local-capture.js\";\nimport { projectColumnClause } from \"./project.js\";\nimport {\n\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tMAX_SCOPE_IN_PARAMS,\n\tresolveVisibleScopeIds,\n} from \"./scope-resolution.js\";\nimport type { MemoryFilters } from \"./types.js\";\n\nexport interface OwnershipFilterContext {\n\tactorId: string;\n\tdeviceId: string;\n\tclaimedDeviceIds?: string[];\n\tlegacyActorIds?: string[];\n\t/**\n\t * Apply the local read boundary for replication scopes. This is opt-in so\n\t * low-level filter unit tests and non-memory callers can keep using the pure\n\t * filter builder, while store/search paths can make scope visibility a hard\n\t * invariant.\n\t */\n\tenforceScopeVisibility?: boolean;\n\t/**\n\t * Pre-resolved set of scope_ids this device may read (see\n\t * `resolveVisibleScopeIds` in scope-resolution.ts). When present, scope visibility is\n\t * enforced with an index-eligible `scope_id IN (...)` predicate instead of\n\t * the per-row EXISTS subqueries. Without this set, scopeVisibilityDb resolves\n\t * the same decisions. Without either, SQL can grant only unmanaged access.\n\t */\n\tvisibleScopeIds?: readonly string[];\n\tscopeVisibilityDb?: Database;\n\t/** Public key of the actual runtime signing key; managed reads deny without it. */\n\texpectedPublicKey?: string;\n\t/** Lazy read-only actual-key loader; used only for managed scope candidates. */\n\tloadExpectedPublicKey?: () => string | undefined;\n}\n\nexport interface FilterResult {\n\tclauses: string[];\n\tparams: unknown[];\n\tjoinSessions: boolean;\n}\n\n/**\n * Normalize a filter value that may be a single string or an array of strings\n * into a clean, non-empty array of trimmed strings.\n */\nexport function normalizeFilterStrings(value: string | string[] | undefined | null): string[] {\n\tif (value == null) return [];\n\tconst items = Array.isArray(value) ? value : [value];\n\tconst seen = new Set<string>();\n\tconst normalized: string[] = [];\n\tfor (const item of items) {\n\t\tconst candidate = String(item).trim();\n\t\tif (!candidate || seen.has(candidate)) continue;\n\t\tseen.add(candidate);\n\t\tnormalized.push(candidate);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeWorkspaceKinds(value: string | string[] | undefined | null): string[] {\n\treturn normalizeFilterStrings(value)\n\t\t.map((raw) => raw.toLowerCase())\n\t\t.filter(\n\t\t\t(raw, idx, arr) => (raw === \"personal\" || raw === \"shared\") && arr.indexOf(raw) === idx,\n\t\t);\n}\n\nexport function normalizeVisibilityValues(value: string | string[] | undefined | null): string[] {\n\treturn normalizeFilterStrings(value)\n\t\t.map((raw) => raw.toLowerCase())\n\t\t.filter((raw, idx, arr) => (raw === \"private\" || raw === \"shared\") && arr.indexOf(raw) === idx);\n}\n\nexport function normalizeTrustStates(value: string | string[] | undefined | null): string[] {\n\treturn normalizeFilterStrings(value)\n\t\t.map((raw) => raw.toLowerCase())\n\t\t.filter(\n\t\t\t(raw, idx, arr) =>\n\t\t\t\t(raw === \"trusted\" || raw === \"legacy_unknown\" || raw === \"unreviewed\") &&\n\t\t\t\tarr.indexOf(raw) === idx,\n\t\t);\n}\n\n/**\n * Add IN / NOT IN clauses for a multi-value filter column.\n * Mirrors Python's _add_multi_value_filter.\n */\nfunction addMultiValueFilter(\n\tclauses: string[],\n\tparams: unknown[],\n\tcolumn: string,\n\tincludeValues: string[],\n\texcludeValues: string[],\n): void {\n\tif (includeValues.length > 0) {\n\t\tconst placeholders = includeValues.map(() => \"?\").join(\", \");\n\t\tclauses.push(`${column} IN (${placeholders})`);\n\t\tparams.push(...includeValues);\n\t}\n\tif (excludeValues.length > 0) {\n\t\tconst placeholders = excludeValues.map(() => \"?\").join(\", \");\n\t\tclauses.push(`(${column} IS NULL OR ${column} NOT IN (${placeholders}))`);\n\t\tparams.push(...excludeValues);\n\t}\n}\n\nfunction cleanUniqueStrings(value: string[] | undefined): string[] {\n\treturn [...new Set((value ?? []).map((item) => item.trim()).filter(Boolean))];\n}\n\n// Mirror MemoryStore.buildOwnershipPredicate(): prefer the top-level column,\n// then fall back to the metadata_json copy, and finally normalize a missing\n// owner to '' (never NULL) so the `theirs` (NOT ...) comparison stays null-safe.\nfunction ownershipColumnSql(column: string, jsonPath: string): string {\n\treturn `COALESCE(\n\tNULLIF(TRIM(memory_items.${column}), ''),\n\tNULLIF(TRIM(CASE\n\t\tWHEN json_valid(COALESCE(memory_items.metadata_json, ''))\n\t\tTHEN COALESCE(json_extract(memory_items.metadata_json, '${jsonPath}'), '')\n\t\tELSE ''\n\tEND), ''),\n\t''\n)`;\n}\n\nconst OWNERSHIP_ACTOR_SQL = ownershipColumnSql(\"actor_id\", \"$.actor_id\");\nconst OWNERSHIP_ORIGIN_DEVICE_SQL = ownershipColumnSql(\"origin_device_id\", \"$.origin_device_id\");\n\nfunction ownershipPredicateSql(context: OwnershipFilterContext): {\n\tclause: string;\n\tparams: string[];\n} {\n\tconst alternatives: string[] = [];\n\tconst params: string[] = [];\n\t// Guard blank identity: an empty actorId/deviceId must NOT match every\n\t// ownerless row (mirrors the falsy checks in\n\t// MemoryStore.buildOwnershipPredicate()). Skip the equality alternative\n\t// when the value is empty rather than emitting `<expr> = ''`.\n\tconst actorId = context.actorId.trim();\n\tif (actorId) {\n\t\talternatives.push(`${OWNERSHIP_ACTOR_SQL} = ?`);\n\t\tparams.push(actorId);\n\t}\n\tconst deviceId = context.deviceId.trim();\n\tif (deviceId) {\n\t\talternatives.push(`${OWNERSHIP_ORIGIN_DEVICE_SQL} = ?`);\n\t\tparams.push(deviceId);\n\t}\n\tconst claimedDeviceIds = cleanUniqueStrings(context.claimedDeviceIds);\n\tif (claimedDeviceIds.length > 0) {\n\t\talternatives.push(\n\t\t\t`${OWNERSHIP_ORIGIN_DEVICE_SQL} IN (${claimedDeviceIds.map(() => \"?\").join(\", \")})`,\n\t\t);\n\t\tparams.push(...claimedDeviceIds);\n\t}\n\tconst legacyActorIds = cleanUniqueStrings(context.legacyActorIds);\n\tif (legacyActorIds.length > 0) {\n\t\talternatives.push(`${OWNERSHIP_ACTOR_SQL} IN (${legacyActorIds.map(() => \"?\").join(\", \")})`);\n\t\tparams.push(...legacyActorIds);\n\t}\n\t// No usable owner identity → nothing is \"mine\" (and `theirs` = everything).\n\tif (alternatives.length === 0) return { clause: \"(0 = 1)\", params };\n\treturn { clause: `(${alternatives.join(\" OR \")})`, params };\n}\n\nfunction localCreationSourcesForFilter(\n\tcontext: OwnershipFilterContext,\n\tvisibleScopeIds: readonly string[] | undefined,\n): string[] {\n\tconst db = context.scopeVisibilityDb;\n\tif (!db || !visibleScopeIds) return [];\n\tconst creationClause = matchingLocalCreationClause(db);\n\tif (!creationClause) return [];\n\tif (\n\t\t!db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_source_bindings'\",\n\t\t\t)\n\t\t\t.get()\n\t)\n\t\treturn [];\n\t// Open the signing key only when matching creation evidence needs history access.\n\tconst candidate = db\n\t\t.prepare(`SELECT 1 FROM memory_source_bindings msb\n\t\tJOIN memory_items ON memory_items.import_key = msb.entity_id\n\t\tWHERE msb.evidence = 'local_creation' AND ${creationClause}\n\t\tAND NOT EXISTS (SELECT 1 FROM json_each(?) visible WHERE visible.value = COALESCE(memory_items.scope_id, '')) LIMIT 1`)\n\t\t.get(JSON.stringify(visibleScopeIds));\n\treturn candidate ? localCreationSourceIds(db, context.deviceId.trim(), context) : [];\n}\n\nfunction addScopeVisibilityFilter(\n\tclauses: string[],\n\tparams: unknown[],\n\tcontext: OwnershipFilterContext | undefined,\n\tresolvedBranches?: FilterResult[],\n): void {\n\tif (!context?.enforceScopeVisibility) return;\n\tconst deviceId = context.deviceId.trim();\n\tif (!deviceId) {\n\t\tclauses.push(\"0 = 1\");\n\t\treturn;\n\t}\n\t// Blank/NULL scope_id is treated as local-default for read visibility.\n\t// Migration backfill promotes legacy rows to explicit scopes asynchronously,\n\t// but until that completes those rows must remain visible to their owning\n\t// device exactly the way local-default rows are.\n\tconst visibleScopeIds =\n\t\tcontext.visibleScopeIds ??\n\t\t(context.scopeVisibilityDb\n\t\t\t? resolveVisibleScopeIds(context.scopeVisibilityDb, deviceId, context)\n\t\t\t: undefined);\n\t// Mutable origin fields cannot prove managed authorship. Retain this legacy\n\t// exception only for explicitly unmanaged scopes, even after membership loss.\n\t// A legacy 'local' origin with an import key may be a foreign replica.\n\tconst unmanagedAuthored = `(memory_items.scope_id IN (\n\t\tSELECT scope_id FROM replication_scopes\n\t\tWHERE authority_type IN ('local', 'manual', 'invite')\n\t) AND ((${OWNERSHIP_ORIGIN_DEVICE_SQL} = ? AND ? <> 'local')\n\t\tOR (${OWNERSHIP_ORIGIN_DEVICE_SQL} = 'local'\n\t\t\tAND COALESCE(TRIM(memory_items.import_key), '') = '')))`;\n\tlet authored = unmanagedAuthored;\n\tconst authoredBranches: FilterResult[] = [\n\t\t{ clauses: [unmanagedAuthored], params: [deviceId, deviceId], joinSessions: false },\n\t];\n\tconst sourceIds = localCreationSourcesForFilter(context, visibleScopeIds);\n\tif (sourceIds.length && context.scopeVisibilityDb) {\n\t\t// Immutable creation history can also remain readable in managed scopes.\n\t\tconst bindingFilter = `msb.evidence = 'local_creation'\n\t\t\tAND msb.source_device_id IN (${sourceIds.map(() => \"?\").join(\", \")})`;\n\t\tconst creationClause = matchingLocalCreationClause(context.scopeVisibilityDb);\n\t\tauthored = `(${authored} OR EXISTS (SELECT 1 FROM memory_source_bindings msb\n\t\t\tWHERE msb.entity_id = memory_items.import_key AND ${bindingFilter}\n\t\t\tAND ${creationClause}))`;\n\t\t// Drive this exceptional branch from creation bindings/import keys rather\n\t\t// than inspecting provenance JSON for every row in every unreadable scope.\n\t\tauthoredBranches.push({\n\t\t\tclauses: [\n\t\t\t\t`memory_items.id IN (SELECT id FROM memory_items\n\t\t\t\t\tWHERE import_key IN (SELECT msb.entity_id FROM memory_source_bindings msb WHERE ${bindingFilter}))`,\n\t\t\t\t`${creationClause}`,\n\t\t\t\t`NOT COALESCE(${unmanagedAuthored}, 0)`,\n\t\t\t],\n\t\t\tparams: [...sourceIds, deviceId, deviceId],\n\t\t\tjoinSessions: false,\n\t\t});\n\t}\n\tif (visibleScopeIds !== undefined) {\n\t\taddResolvedScopeVisibilityFilter(\n\t\t\tclauses,\n\t\t\tparams,\n\t\t\tvisibleScopeIds,\n\t\t\tauthored,\n\t\t\tdeviceId,\n\t\t\tauthoredBranches,\n\t\t\tresolvedBranches,\n\t\t);\n\t\tparams.push(...sourceIds);\n\t\treturn;\n\t}\n\t// DB-less callers cannot validate managed proof. Preserve local/manual/invite\n\t// membership behavior, but never let raw coordinator rows grant permission.\n\tclauses.push(`(\n\t\tCOALESCE(TRIM(memory_items.scope_id), '') IN (?, ?, ?)\n\t\tOR EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM replication_scopes rs\n\t\t\tWHERE rs.scope_id = memory_items.scope_id\n\t\t\t AND rs.status = 'active'\n\t\t\t AND rs.authority_type = 'local'\n\t\t)\n\t\tOR EXISTS (\n\t\t\tSELECT 1\n\t\t\tFROM scope_memberships sm\n\t\t\tJOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\tWHERE sm.scope_id = memory_items.scope_id\n\t\t\t AND sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND rs.authority_type IN ('local', 'manual', 'invite')\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch\n\t\t)\n\t\tOR ${authored}\n\t)`);\n\tparams.push(\n\t\t\"\",\n\t\tLOCAL_DEFAULT_SCOPE_ID,\n\t\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\tdeviceId,\n\t\tdeviceId,\n\t\tdeviceId,\n\t);\n}\n\nfunction addResolvedScopeVisibilityFilter(\n\tclauses: string[],\n\tparams: unknown[],\n\tvisibleScopeIds: readonly string[],\n\tauthored: string,\n\tdeviceId: string,\n\tauthoredBranches: FilterResult[],\n\tresolvedBranches?: FilterResult[],\n): void {\n\tlet scopeClause = \"0 = 1\";\n\tconst scopeParams: unknown[] = [];\n\tif (visibleScopeIds.length > MAX_SCOPE_IN_PARAMS) {\n\t\tscopeClause = \"memory_items.scope_id IN (SELECT value FROM json_each(?))\";\n\t\tscopeParams.push(JSON.stringify(visibleScopeIds));\n\t} else if (visibleScopeIds.length > 0) {\n\t\tscopeClause = `memory_items.scope_id IN (${visibleScopeIds.map(() => \"?\").join(\", \")})`;\n\t\tscopeParams.push(...visibleScopeIds);\n\t}\n\tif (resolvedBranches) {\n\t\t// UNION ALL consumers must not count NULL, visible and authored rows twice.\n\t\t// Keep the full authored predicate, including immutable managed creation proof.\n\t\tresolvedBranches.push(\n\t\t\t{ clauses: [\"memory_items.scope_id IS NULL\"], params: [], joinSessions: false },\n\t\t\t{ clauses: [scopeClause], params: scopeParams, joinSessions: false },\n\t\t\t...authoredBranches.map((branch) => ({\n\t\t\t\tclauses: [\"memory_items.scope_id IS NOT NULL\", `NOT (${scopeClause})`, ...branch.clauses],\n\t\t\t\tparams: [...scopeParams, ...branch.params],\n\t\t\t\tjoinSessions: false,\n\t\t\t})),\n\t\t);\n\t\treturn;\n\t}\n\tparams.push(...scopeParams);\n\tclauses.push(`(memory_items.scope_id IS NULL OR ${scopeClause} OR ${authored})`);\n\tparams.push(deviceId, deviceId);\n}\n\n/**\n * Disjoint equivalents of the central read filter for UNION ALL aggregates.\n * Unresolved/DB-less contexts retain the exact ordinary filter as one branch.\n * Resolve on every call: these branches are not an authorization cache.\n */\nexport function buildFilterBranchesWithContext(\n\tfilters: MemoryFilters | undefined | null,\n\townership?: OwnershipFilterContext,\n): FilterResult[] {\n\tif (ownership?.visibleScopeIds === undefined) {\n\t\treturn [buildFilterClausesWithContext(filters, ownership)];\n\t}\n\tconst branches: FilterResult[] = [];\n\tconst clauses: string[] = [];\n\tconst params: unknown[] = [];\n\taddScopeVisibilityFilter(clauses, params, ownership, branches);\n\tconst common = buildFilterClausesWithContext(\n\t\tfilters,\n\t\townership ? { ...ownership, enforceScopeVisibility: false } : undefined,\n\t);\n\tif (!branches.length) branches.push({ clauses, params, joinSessions: false });\n\treturn branches.map((branch) => ({\n\t\tclauses: [...branch.clauses, ...common.clauses],\n\t\tparams: [...branch.params, ...common.params],\n\t\tjoinSessions: common.joinSessions,\n\t}));\n}\n\n/**\n * Build WHERE clause fragments from a MemoryFilters object.\n *\n * Returns clauses, params, and whether the sessions table must be joined.\n * The caller is responsible for prepending `memory_items.active = 1` or\n * similar base conditions — this function only appends filter-specific clauses.\n */\nexport function buildFilterClauses(filters: MemoryFilters | undefined | null): FilterResult {\n\treturn buildFilterClausesWithContext(filters);\n}\n\nfunction addProjectFilter(project: string | null | undefined, result: FilterResult): void {\n\tif (!project) return;\n\t// Session moves take precedence; redacted sessions fall back to readable memory attribution.\n\tconst filter = projectColumnClause(\"COALESCE(sessions.project, memory_items.project)\", project);\n\tif (!filter.clause) return;\n\tresult.clauses.push(filter.clause);\n\tresult.params.push(...filter.params);\n\tresult.joinSessions = true;\n}\n\nexport function buildFilterClausesWithContext(\n\tfilters: MemoryFilters | undefined | null,\n\townership?: OwnershipFilterContext,\n): FilterResult {\n\tconst result: FilterResult = { clauses: [], params: [], joinSessions: false };\n\tconst { clauses, params } = result;\n\taddScopeVisibilityFilter(clauses, params, ownership);\n\tif (!filters) return result;\n\n\t// Single kind filter — guard against non-string kinds from untyped\n\t// JSON request bodies (a number/bool would otherwise become a broken\n\t// bound parameter).\n\tif (typeof filters.kind === \"string\" && filters.kind) {\n\t\tclauses.push(\"memory_items.kind = ?\");\n\t\tparams.push(filters.kind);\n\t}\n\tif (filters.session_id) {\n\t\tclauses.push(\"memory_items.session_id = ?\");\n\t\tparams.push(filters.session_id);\n\t}\n\tif (filters.since) {\n\t\tclauses.push(\"memory_items.created_at >= ?\");\n\t\tparams.push(filters.since);\n\t}\n\n\tconst ownershipScope = String(filters.ownership_scope ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (ownership && (ownershipScope === \"mine\" || ownershipScope === \"theirs\")) {\n\t\tconst ownedPredicate = ownershipPredicateSql(ownership);\n\t\tif (ownershipScope === \"mine\") {\n\t\t\tclauses.push(ownedPredicate.clause);\n\t\t} else {\n\t\t\tclauses.push(`NOT ${ownedPredicate.clause}`);\n\t\t}\n\t\tparams.push(...ownedPredicate.params);\n\t}\n\n\taddProjectFilter(filters.project, result);\n\n\t// Visibility\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.visibility\",\n\t\tnormalizeVisibilityValues(filters.include_visibility ?? filters.visibility),\n\t\tnormalizeVisibilityValues(filters.exclude_visibility),\n\t);\n\n\t// Replication scope filters. These are an explicit narrowing layer and are\n\t// always intersected with the central scope-visibility gate above when the\n\t// caller enables it.\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.scope_id\",\n\t\tnormalizeFilterStrings(filters.include_scope_ids ?? filters.scope_id),\n\t\tnormalizeFilterStrings(filters.exclude_scope_ids),\n\t);\n\n\t// Workspace IDs\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.workspace_id\",\n\t\tnormalizeFilterStrings(filters.include_workspace_ids),\n\t\tnormalizeFilterStrings(filters.exclude_workspace_ids),\n\t);\n\n\t// Workspace kinds\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.workspace_kind\",\n\t\tnormalizeWorkspaceKinds(filters.include_workspace_kinds),\n\t\tnormalizeWorkspaceKinds(filters.exclude_workspace_kinds),\n\t);\n\n\t// Actor IDs\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.actor_id\",\n\t\tnormalizeFilterStrings(filters.include_actor_ids),\n\t\tnormalizeFilterStrings(filters.exclude_actor_ids),\n\t);\n\n\t// Trust states\n\taddMultiValueFilter(\n\t\tclauses,\n\t\tparams,\n\t\t\"memory_items.trust_state\",\n\t\tnormalizeTrustStates(filters.include_trust_states),\n\t\tnormalizeTrustStates(filters.exclude_trust_states),\n\t);\n\n\treturn result;\n}\n","/**\n * Embedding primitives for semantic search.\n *\n * Ports codemem/semantic.py — text chunking, hashing, and embedding via a\n * pluggable client interface. The default factory lazily loads the optional\n * `@codemem/embeddings` runtime. When it is unavailable the helpers return\n * empty arrays and callers fall back to FTS-only retrieval.\n *\n * Embeddings are always disabled when CODEMEM_EMBEDDING_DISABLED=1.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { isEmbeddingDisabled } from \"./db.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal interface a concrete embedding backend must satisfy. */\nexport interface EmbeddingRuntimeIdentity {\n\treadonly package: \"@huggingface/transformers\";\n\treadonly version: string;\n\treadonly model: string;\n\treadonly revision: string;\n\treadonly requestedRevision?: string;\n\treadonly dtype: \"fp32\";\n\treadonly device: \"cpu\";\n\treadonly pooling: \"mean\";\n\treadonly normalization: \"l2\";\n\treadonly dimensions: number;\n}\n\nexport interface EmbeddingClient {\n\treadonly model: string;\n\treadonly dimensions: number;\n\treadonly identity?: EmbeddingRuntimeIdentity;\n\tembed(texts: string[]): Promise<Float32Array[]>;\n}\n\nexport interface EmbeddingRuntimeRequest {\n\tmodel: string;\n\trevision?: string;\n}\n\nexport type EmbeddingRuntimeFactory = (\n\trequest: EmbeddingRuntimeRequest,\n) => Promise<EmbeddingClient | null>;\n\nexport type EmbeddingRuntimeStatus =\n\t| { state: \"uninitialized\" | \"ready\" | \"disabled\" }\n\t| { state: \"unavailable\"; reason: \"missing_package\" | \"initialization_failed\" | \"no_client\" };\n\ninterface EmbeddingTensor {\n\tdata: ArrayLike<number | bigint>;\n\tdims?: number[];\n}\n\ntype FeatureExtractor = (\n\ttexts: string[],\n\toptions: { pooling: \"mean\"; normalize: true },\n) => Promise<EmbeddingTensor>;\n\nconst EMBEDDING_BATCH_SIZE = 32;\nconst DEFAULT_EMBEDDING_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst EMBEDDING_DIMENSIONS = 384;\nexport const DEFAULT_EMBEDDING_REVISION = \"ea104dacec62c0de699686887e3f920caeb4f3e3\";\n\n/** Copy validated embedding model data into owned Float32 storage. */\nexport function embeddingDataToFloat32(data: ArrayLike<number | bigint>): Float32Array {\n\tconst vector = new Float32Array(data.length);\n\tfor (let index = 0; index < data.length; index++) {\n\t\tconst value = data[index];\n\t\tconst float32Value = typeof value === \"number\" ? Math.fround(value) : Number.NaN;\n\t\tif (!Number.isFinite(float32Value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding model returned non-finite, non-numeric, or unrepresentable tensor data at index ${index}`,\n\t\t\t);\n\t\t}\n\t\tvector[index] = float32Value;\n\t}\n\treturn vector;\n}\n\n/** Split one validated row-major tensor into independently owned vectors. */\nexport function embeddingTensorToFloat32Rows(\n\toutput: EmbeddingTensor,\n\texpectedRows: number,\n\tdimensions: number,\n): Float32Array[] {\n\tif (\n\t\t!Number.isInteger(expectedRows) ||\n\t\texpectedRows <= 0 ||\n\t\t!Number.isInteger(dimensions) ||\n\t\tdimensions <= 0\n\t) {\n\t\tthrow new TypeError(\"Embedding tensor shape expectations must be positive integers\");\n\t}\n\tif (\n\t\toutput.dims?.length !== 2 ||\n\t\toutput.dims[0] !== expectedRows ||\n\t\toutput.dims[1] !== dimensions\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding model returned shape [${output.dims?.join(\", \") ?? \"unknown\"}], expected [${expectedRows}, ${dimensions}]`,\n\t\t);\n\t}\n\tif (output.data.length !== expectedRows * dimensions) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding model returned ${output.data.length} values, expected ${expectedRows * dimensions}`,\n\t\t);\n\t}\n\n\tconst rows = Array.from({ length: expectedRows }, () => new Float32Array(dimensions));\n\tfor (let flatIndex = 0; flatIndex < output.data.length; flatIndex++) {\n\t\tconst value = output.data[flatIndex];\n\t\tconst float32Value = typeof value === \"number\" ? Math.fround(value) : Number.NaN;\n\t\tif (!Number.isFinite(float32Value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding model returned non-finite, non-numeric, or unrepresentable tensor data at index ${flatIndex}`,\n\t\t\t);\n\t\t}\n\t\tconst row = rows[Math.floor(flatIndex / dimensions)];\n\t\tif (!row) throw new TypeError(\"Embedding tensor row calculation failed\");\n\t\trow[flatIndex % dimensions] = float32Value;\n\t}\n\treturn rows;\n}\n\n/** Run array inference in bounded batches while preserving input order. */\nexport async function embedTextBatches(\n\textractor: FeatureExtractor,\n\ttexts: string[],\n\tdimensions: number,\n\tbatchSize = EMBEDDING_BATCH_SIZE,\n): Promise<Float32Array[]> {\n\tif (texts.length === 0) return [];\n\tif (!Number.isInteger(batchSize) || batchSize <= 0) {\n\t\tthrow new TypeError(\"Embedding batch size must be a positive integer\");\n\t}\n\n\tconst vectors: Float32Array[] = [];\n\tfor (let offset = 0; offset < texts.length; offset += batchSize) {\n\t\tconst batch = texts.slice(offset, offset + batchSize);\n\t\tconst output = await extractor(batch, { pooling: \"mean\", normalize: true });\n\t\tvectors.push(...embeddingTensorToFloat32Rows(output, batch.length, dimensions));\n\t}\n\treturn vectors;\n}\n\n// ---------------------------------------------------------------------------\n// Text helpers (ports of semantic.py)\n// ---------------------------------------------------------------------------\n\n/** SHA-256 hex digest of UTF-8 encoded text. */\nexport function hashText(text: string): string {\n\treturn createHash(\"sha256\").update(text, \"utf-8\").digest(\"hex\");\n}\n\n/**\n * Split long text into ≤ `maxChars` chunks, preferring paragraph then\n * sentence boundaries. Matches Python's `chunk_text()`.\n */\nexport function chunkText(text: string, maxChars = 1200): string[] {\n\tconst cleaned = text.trim();\n\tif (!cleaned) return [];\n\tif (cleaned.length <= maxChars) return [cleaned];\n\n\tconst paragraphs = cleaned\n\t\t.split(/\\n{2,}/)\n\t\t.map((p) => p.trim())\n\t\t.filter(Boolean);\n\tconst chunks: string[] = [];\n\tlet buffer: string[] = [];\n\tlet bufferLen = 0;\n\n\tfor (const paragraph of paragraphs) {\n\t\tif (bufferLen + paragraph.length + 2 <= maxChars) {\n\t\t\tbuffer.push(paragraph);\n\t\t\tbufferLen += paragraph.length + 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (buffer.length > 0) {\n\t\t\tchunks.push(buffer.join(\"\\n\\n\"));\n\t\t\tbuffer = [];\n\t\t\tbufferLen = 0;\n\t\t}\n\t\tif (paragraph.length <= maxChars) {\n\t\t\tchunks.push(paragraph);\n\t\t\tcontinue;\n\t\t}\n\t\t// Split long paragraph by sentence\n\t\tconst sentences = paragraph\n\t\t\t.split(/(?<=[.!?])\\s+/)\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter(Boolean);\n\t\tconst sentBuf: string[] = [];\n\t\tlet sentLen = 0;\n\t\tfor (const sentence of sentences) {\n\t\t\t// Hard-split sentences that exceed maxChars on their own\n\t\t\tif (sentence.length > maxChars) {\n\t\t\t\tif (sentBuf.length > 0) {\n\t\t\t\t\tchunks.push(sentBuf.join(\" \"));\n\t\t\t\t\tsentBuf.length = 0;\n\t\t\t\t\tsentLen = 0;\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < sentence.length; i += maxChars) {\n\t\t\t\t\tchunks.push(sentence.slice(i, i + maxChars));\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sentLen + sentence.length + 1 <= maxChars) {\n\t\t\t\tsentBuf.push(sentence);\n\t\t\t\tsentLen += sentence.length + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sentBuf.length > 0) chunks.push(sentBuf.join(\" \"));\n\t\t\tsentBuf.length = 0;\n\t\t\tsentBuf.push(sentence);\n\t\t\tsentLen = sentence.length;\n\t\t}\n\t\tif (sentBuf.length > 0) chunks.push(sentBuf.join(\" \"));\n\t}\n\tif (buffer.length > 0) chunks.push(buffer.join(\"\\n\\n\"));\n\treturn chunks;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy singleton client\n// ---------------------------------------------------------------------------\n\nlet _client: EmbeddingClient | null | undefined;\nlet _clientPromise: Promise<EmbeddingClient | null> | undefined;\nlet _clientRequest: Required<EmbeddingRuntimeRequest> | undefined;\nlet _clientGeneration = 0;\nlet _runtimeWarningEmitted = false;\nlet _runtimeStatus: EmbeddingRuntimeStatus = { state: \"uninitialized\" };\n\nconst defaultEmbeddingRuntimeFactory: EmbeddingRuntimeFactory = async (request) => {\n\tconst { createEmbeddingRuntime } = await import(\"@codemem/embeddings\");\n\tconst client = await createEmbeddingRuntime(request);\n\tif (client && !client.identity) {\n\t\tthrow new TypeError(\n\t\t\t\"Installed @codemem/embeddings is outdated and does not expose runtime identity. Upgrade codemem and @codemem/embeddings together, then restart Codemem.\",\n\t\t);\n\t}\n\treturn client;\n};\nlet embeddingRuntimeFactory = defaultEmbeddingRuntimeFactory;\n\n/** Reset the singleton (for tests). */\nexport function _resetEmbeddingClient(): void {\n\t_client = undefined;\n\t_clientPromise = undefined;\n\t_clientRequest = undefined;\n\t_clientGeneration++;\n\t_runtimeStatus = { state: \"uninitialized\" };\n}\n\n/** Override the embedding runtime factory (for tests). */\nexport function _setEmbeddingRuntimeFactory(factory: EmbeddingRuntimeFactory): void {\n\tembeddingRuntimeFactory = factory;\n\t_resetEmbeddingClient();\n}\n\n/** Restore the default embedding runtime factory (for tests). */\nexport function _resetEmbeddingRuntimeFactory(): void {\n\tembeddingRuntimeFactory = defaultEmbeddingRuntimeFactory;\n\t_runtimeWarningEmitted = false;\n\t_resetEmbeddingClient();\n}\n\nfunction warnEmbeddingRuntimeUnavailable(error: unknown): void {\n\tif (_runtimeWarningEmitted) return;\n\t_runtimeWarningEmitted = true;\n\tif (isMissingEmbeddingRuntimePackage(error)) {\n\t\tconsole.warn(\n\t\t\t\"Semantic search is unavailable. Install @codemem/embeddings and restart Codemem to enable it.\",\n\t\t);\n\t\treturn;\n\t}\n\tconst cause = error instanceof Error ? error.message : String(error);\n\tconsole.warn(`Semantic search is unavailable because the embedding runtime failed: ${cause}`);\n}\n\nfunction isMissingEmbeddingRuntimePackage(error: unknown): boolean {\n\tlet current: unknown = error;\n\tconst seen = new Set<unknown>();\n\twhile (typeof current === \"object\" && current !== null && !seen.has(current)) {\n\t\tseen.add(current);\n\t\tif (\n\t\t\t\"code\" in current &&\n\t\t\tcurrent.code === \"ERR_MODULE_NOT_FOUND\" &&\n\t\t\tcurrent instanceof Error &&\n\t\t\tcurrent.message.includes(\"@codemem/embeddings\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = \"cause\" in current ? current.cause : undefined;\n\t}\n\treturn false;\n}\n\n/** Return process-local runtime state without loading the embedding model. */\nexport function getEmbeddingRuntimeStatus(): EmbeddingRuntimeStatus {\n\treturn _runtimeStatus;\n}\n\nfunction recordEmbeddingRuntimeClient(client: EmbeddingClient | null): void {\n\t_client = client;\n\tif (client) {\n\t\t_runtimeStatus = { state: \"ready\" };\n\t\treturn;\n\t}\n\t_runtimeStatus = { state: \"unavailable\", reason: \"no_client\" };\n\twarnEmbeddingRuntimeUnavailable(\"embedding runtime returned no client\");\n}\n\nasync function createEmbeddingClient(\n\tmodel: string,\n\trevision: string,\n\tgeneration: number,\n): Promise<EmbeddingClient | null> {\n\ttry {\n\t\tconst client = await embeddingRuntimeFactory({ model, revision });\n\t\tif (client) assertEmbeddingRuntimeIdentity(client, model, revision);\n\t\t// A reset while creation was in flight makes this client stale. Resolve\n\t\t// waiters through the live generation so model labels and dimensions agree.\n\t\tif (generation !== _clientGeneration) return getEmbeddingClient();\n\t\trecordEmbeddingRuntimeClient(client);\n\t\treturn client;\n\t} catch (error) {\n\t\t// A stale creation failure must not force current-generation waiters to null.\n\t\tif (generation !== _clientGeneration) return getEmbeddingClient();\n\t\t_client = null;\n\t\t_runtimeStatus = {\n\t\t\tstate: \"unavailable\",\n\t\t\treason: isMissingEmbeddingRuntimePackage(error) ? \"missing_package\" : \"initialization_failed\",\n\t\t};\n\t\twarnEmbeddingRuntimeUnavailable(error);\n\t\treturn null;\n\t} finally {\n\t\tif (generation === _clientGeneration) _clientPromise = undefined;\n\t}\n}\n\n/** Return the configured bare embedding model repository without loading the client. */\nexport function resolveEmbeddingModel(): string {\n\treturn process.env.CODEMEM_EMBEDDING_MODEL || DEFAULT_EMBEDDING_MODEL;\n}\n\n/** Resolve a configured revision without making non-semantic callers throw. */\nexport function tryResolveEmbeddingRevision(\n\tmodel = resolveEmbeddingModel(),\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | null {\n\tconst configuredRevision = env.CODEMEM_EMBEDDING_REVISION?.trim();\n\tif (configuredRevision) return configuredRevision;\n\tif (model === DEFAULT_EMBEDDING_MODEL) return DEFAULT_EMBEDDING_REVISION;\n\treturn null;\n}\n\n/** Resolve the concrete model revision required by vector-producing callers. */\nexport function resolveEmbeddingRevision(\n\tmodel = resolveEmbeddingModel(),\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst revision = tryResolveEmbeddingRevision(model, env);\n\tif (revision) return revision;\n\tthrow new TypeError(\n\t\t\"CODEMEM_EMBEDDING_REVISION is required when CODEMEM_EMBEDDING_MODEL selects a custom model\",\n\t);\n}\n\n/** Return the canonical persisted identity for the v4 embedding contract. */\nexport function resolveEmbeddingVectorIdentityLabel(\n\tmodel = resolveEmbeddingModel(),\n\trevision?: string,\n): string {\n\tif (revision === undefined) {\n\t\tconst configuredRevision = process.env.CODEMEM_EMBEDDING_REVISION?.trim();\n\t\tif (model !== DEFAULT_EMBEDDING_MODEL && !configuredRevision) {\n\t\t\tresolveEmbeddingRevision(model);\n\t\t}\n\t\tif (model !== DEFAULT_EMBEDDING_MODEL || configuredRevision) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Embedding vector identity requires a canonical commit SHA returned by the runtime\",\n\t\t\t);\n\t\t}\n\t\trevision = DEFAULT_EMBEDDING_REVISION;\n\t}\n\tif (!/^[0-9a-f]{40}$/.test(revision)) {\n\t\tthrow new TypeError(\n\t\t\t\"Embedding vector identity requires a canonical commit SHA returned by the runtime\",\n\t\t);\n\t}\n\treturn [\n\t\t\"transformers-v4\",\n\t\t`model=${encodeURIComponent(model)}`,\n\t\t`revision=${encodeURIComponent(revision)}`,\n\t\t\"dtype=fp32\",\n\t\t\"pooling=mean\",\n\t\t\"normalization=l2\",\n\t\t`dimensions=${EMBEDDING_DIMENSIONS}`,\n\t].join(\":\");\n}\n\n/** Construct a persisted vector identity only from runtime-resolved metadata. */\nexport function resolveEmbeddingClientVectorIdentityLabel(client: EmbeddingClient): string {\n\tif (!client.identity) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required to label persisted vectors\");\n\t}\n\treturn resolveEmbeddingVectorIdentityLabel(client.identity.model, client.identity.revision);\n}\n\nexport interface PersistedEmbeddingTarget {\n\ttargetModel?: unknown;\n\trequestedModel?: unknown;\n\trequestedRevision?: unknown;\n}\n\n/** Match a persisted canonical target to the active request, or use the built-in pin. */\nexport function tryResolveEmbeddingVectorIdentityLabel(\n\tpersisted: PersistedEmbeddingTarget = {},\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | null {\n\tconst model = env.CODEMEM_EMBEDDING_MODEL || DEFAULT_EMBEDDING_MODEL;\n\tconst requestedRevision = tryResolveEmbeddingRevision(model, env);\n\tif (\n\t\ttypeof persisted.targetModel === \"string\" &&\n\t\tpersisted.requestedModel === model &&\n\t\tpersisted.requestedRevision === requestedRevision\n\t) {\n\t\treturn persisted.targetModel;\n\t}\n\tif (\n\t\t_client?.identity?.model === model &&\n\t\t_client.identity.requestedRevision === requestedRevision\n\t) {\n\t\treturn resolveEmbeddingClientVectorIdentityLabel(_client);\n\t}\n\tif (\n\t\tmodel === DEFAULT_EMBEDDING_MODEL &&\n\t\trequestedRevision === DEFAULT_EMBEDDING_REVISION &&\n\t\t!env.CODEMEM_EMBEDDING_REVISION?.trim()\n\t) {\n\t\treturn DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL;\n\t}\n\treturn null;\n}\n\nexport const DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL = resolveEmbeddingVectorIdentityLabel(\n\tDEFAULT_EMBEDDING_MODEL,\n\tDEFAULT_EMBEDDING_REVISION,\n);\n\n/** Validate the runtime contract and agreement between a client and its identity. */\nexport function assertEmbeddingClientIdentity(\n\tclient: EmbeddingClient,\n): asserts client is EmbeddingClient & { readonly identity: EmbeddingRuntimeIdentity } {\n\tif (!client.identity) {\n\t\tthrow new TypeError(\"Embedding runtime identity is required\");\n\t}\n\tif (\n\t\ttypeof client.model !== \"string\" ||\n\t\t!client.model.trim() ||\n\t\ttypeof client.identity.model !== \"string\" ||\n\t\t!client.identity.model.trim()\n\t) {\n\t\tthrow new TypeError(\"Embedding client model must be a non-empty string\");\n\t}\n\tconst runtimeMajorVersion = /^(\\d+)\\./.exec(client.identity.version)?.[1];\n\tif (runtimeMajorVersion !== \"4\") {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity mismatch for version: expected major 4, received ${String(client.identity.version)}`,\n\t\t);\n\t}\n\tconst expected = {\n\t\tpackage: \"@huggingface/transformers\",\n\t\tdtype: \"fp32\",\n\t\tdevice: \"cpu\",\n\t\tpooling: \"mean\",\n\t\tnormalization: \"l2\",\n\t\tdimensions: EMBEDDING_DIMENSIONS,\n\t} as const;\n\tfor (const key of Object.keys(expected) as Array<keyof typeof expected>) {\n\t\tif (client.identity[key] !== expected[key]) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Embedding runtime identity mismatch for ${key}: expected ${String(expected[key])}, received ${String(client.identity[key])}`,\n\t\t\t);\n\t\t}\n\t}\n\tif (!/^[0-9a-f]{40}$/.test(client.identity.revision)) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity revision is not a canonical commit SHA: ${client.identity.revision}`,\n\t\t);\n\t}\n\tif (client.model !== client.identity.model) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding client model mismatch: expected ${client.identity.model}, received ${client.model}`,\n\t\t);\n\t}\n\tif (client.dimensions !== client.identity.dimensions) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding client dimensions mismatch: expected ${client.identity.dimensions}, received ${client.dimensions}`,\n\t\t);\n\t}\n}\n\nfunction assertEmbeddingRuntimeIdentity(\n\tclient: EmbeddingClient,\n\tmodel: string,\n\trequestedRevision: string,\n): void {\n\tassertEmbeddingClientIdentity(client);\n\tif (client.identity.model !== model) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity mismatch for model: expected ${model}, received ${client.identity.model}`,\n\t\t);\n\t}\n\tif (client.identity.requestedRevision !== requestedRevision) {\n\t\tthrow new TypeError(\n\t\t\t`Embedding runtime identity requestedRevision mismatch: expected ${requestedRevision}, got ${client.identity.requestedRevision ?? \"missing\"}`,\n\t\t);\n\t}\n}\n\n/**\n * Get the shared embedding client, creating it lazily on first call.\n * Returns null when embeddings are disabled or the runtime is unavailable.\n */\nexport async function getEmbeddingClient(): Promise<EmbeddingClient | null> {\n\tif (isEmbeddingDisabled()) {\n\t\t_client = null;\n\t\t_runtimeStatus = { state: \"disabled\" };\n\t\treturn null;\n\t}\n\tlet model: string;\n\tlet revision: string;\n\ttry {\n\t\tmodel = resolveEmbeddingModel();\n\t\trevision = resolveEmbeddingRevision(model);\n\t} catch (error) {\n\t\twarnEmbeddingRuntimeUnavailable(error);\n\t\treturn null;\n\t}\n\tconst request = { model, revision };\n\tconst requestMatches =\n\t\t_clientRequest?.model === request.model && _clientRequest.revision === request.revision;\n\tif (_client !== undefined && requestMatches) return _client;\n\tif (_clientPromise && requestMatches) return _clientPromise;\n\tif (_client !== undefined || _clientPromise) {\n\t\t_clientGeneration += 1;\n\t\t_client = undefined;\n\t\t_clientPromise = undefined;\n\t}\n\t_clientRequest = request;\n\tconst generation = _clientGeneration;\n\t_clientPromise = createEmbeddingClient(model, revision, generation);\n\treturn _clientPromise;\n}\n\n/**\n * Embed texts using the shared client.\n * Returns an empty array when embeddings are unavailable.\n */\nexport async function embedTexts(\n\ttexts: string[],\n\tresolvedClient?: EmbeddingClient,\n): Promise<Float32Array[]> {\n\tconst client = resolvedClient ?? (await getEmbeddingClient());\n\tif (!client) return [];\n\treturn client.embed(texts);\n}\n\n// ---------------------------------------------------------------------------\n// Serialization helpers (sqlite-vec wire format)\n// ---------------------------------------------------------------------------\n\n/** Serialize a Float32Array to a little-endian Buffer for sqlite-vec. */\nexport function serializeFloat32(vector: Float32Array): Buffer {\n\tconst buf = Buffer.alloc(vector.length * 4);\n\tfor (let i = 0; i < vector.length; i++) {\n\t\tbuf.writeFloatLE(vector[i] ?? 0, i * 4);\n\t}\n\treturn buf;\n}\n","/** Internal query stages shared by inline and worker semantic ranking, not a package API. */\nimport { DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL } from \"./embeddings.js\";\nimport { buildFilterBranchesWithContext, type OwnershipFilterContext } from \"./filters.js\";\nimport type { MaintenanceJobSnapshot } from \"./maintenance-jobs.js\";\nimport { summaryContinuityFilter } from \"./summary-memory.js\";\nimport type { MemoryFilters } from \"./types.js\";\nimport type { SemanticSearchResult, SemanticSearchScopeContext } from \"./vectors.js\";\n\nfunction scopeVisibleFilterContext(context: SemanticSearchScopeContext): OwnershipFilterContext {\n\treturn {\n\t\tactorId: context?.actorId ?? \"\",\n\t\tdeviceId: context?.deviceId ?? \"\",\n\t\tclaimedDeviceIds: context?.claimedDeviceIds ?? [],\n\t\tlegacyActorIds: context?.legacyActorIds ?? [],\n\t\tenforceScopeVisibility: true,\n\t\tvisibleScopeIds: context?.visibleScopeIds,\n\t\tscopeVisibilityDb: context?.scopeVisibilityDb,\n\t\texpectedPublicKey: context?.expectedPublicKey,\n\t\tloadExpectedPublicKey: context?.loadExpectedPublicKey,\n\t};\n}\n\nexport function buildAuthorizedSemanticMemoryIdsQuery(\n\tfilters: MemoryFilters | null,\n\tcontext: SemanticSearchScopeContext,\n\tsummarySessionId: number | null | undefined,\n): { sql: string; params: unknown[] } {\n\tconst branches = buildFilterBranchesWithContext(filters, scopeVisibleFilterContext(context));\n\tconst continuity = summaryContinuityFilter(summarySessionId);\n\tconst queries = branches.map((branch) => {\n\t\tconst join = branch.joinSessions\n\t\t\t? \"JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t\t: \"\";\n\t\tconst clauses = [\"memory_items.active = 1\", ...branch.clauses, ...continuity.clauses];\n\t\treturn `SELECT memory_items.id FROM memory_items ${join}\n\t\t\tWHERE ${clauses.join(\" AND \")}`;\n\t});\n\treturn {\n\t\tsql: queries.join(\" UNION ALL \"),\n\t\tparams: branches.flatMap((branch) => [...branch.params, ...continuity.params]),\n\t};\n}\n\nexport function semanticResult(row: Record<string, unknown>): SemanticSearchResult {\n\treturn {\n\t\tid: Number(row.id),\n\t\tkind: String(row.kind ?? \"observation\"),\n\t\ttitle: String(row.title ?? \"\"),\n\t\tbody_text: String(row.body_text ?? \"\"),\n\t\tconfidence: Number(row.confidence ?? 0),\n\t\ttags_text: String(row.tags_text ?? \"\"),\n\t\tmetadata_json: row.metadata_json == null ? null : String(row.metadata_json),\n\t\tcreated_at: String(row.created_at ?? \"\"),\n\t\tupdated_at: String(row.updated_at ?? \"\"),\n\t\tsession_id: Number(row.session_id),\n\t\tscore: 1.0 / (1.0 + Number(row.distance ?? 0)),\n\t\tdistance: Number(row.distance ?? 0),\n\t\tnarrative: row.narrative == null ? null : String(row.narrative),\n\t\tfacts: row.facts == null ? null : String(row.facts),\n\t};\n}\n\nconst LEGACY_MODEL = \"Xenova/bge-small-en-v1.5\";\n\nfunction resolveLegacyRebuild(options: {\n\tcurrentModel: string;\n\tsourceModel: string;\n\ttargetModel: string | null;\n\tmodels: readonly (string | null)[];\n}): string | null {\n\tif (\n\t\toptions.sourceModel !== LEGACY_MODEL ||\n\t\toptions.targetModel !== DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL ||\n\t\toptions.currentModel !== DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL\n\t)\n\t\treturn null;\n\tif (options.models.includes(options.sourceModel)) return options.sourceModel;\n\tif (options.models.includes(options.currentModel)) return options.currentModel;\n\treturn null;\n}\n\nfunction catalogDefault(currentModel: string, models: readonly (string | null)[]): string | null {\n\tif (currentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL && models.includes(LEGACY_MODEL)) {\n\t\treturn LEGACY_MODEL;\n\t}\n\tif (models.includes(currentModel) && models.every((model) => model === currentModel)) {\n\t\treturn currentModel;\n\t}\n\treturn null;\n}\n\nfunction metadataModel(value: unknown): string | null {\n\treturn typeof value === \"string\" ? value : null;\n}\n\nexport function resolveSemanticSearchModelFromCatalog(\n\tcurrentModel: string,\n\tjob: Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null,\n\tmodels: readonly (string | null)[],\n): string | null {\n\tconst metadata = job?.metadata ?? {};\n\tconst sourceModel = metadataModel(metadata.source_model);\n\tconst targetModel = metadataModel(metadata.target_model);\n\tconst reconciliationTargetCoverageComplete =\n\t\tmetadata.reconciliation_target_coverage_complete === true;\n\tif (models.length === 0) return null;\n\tconst hasCurrentModel = models.includes(currentModel);\n\tif (\n\t\t[\"running\", \"pending\"].includes(job?.status ?? \"\") &&\n\t\treconciliationTargetCoverageComplete &&\n\t\ttargetModel === currentModel\n\t) {\n\t\treturn hasCurrentModel ? currentModel : null;\n\t}\n\tif (\n\t\t[\"running\", \"pending\", \"failed\"].includes(job?.status ?? \"\") &&\n\t\tsourceModel &&\n\t\tsourceModel !== currentModel\n\t) {\n\t\treturn resolveLegacyRebuild({ currentModel, sourceModel, targetModel, models });\n\t}\n\tif (job?.status === \"completed\" && targetModel === currentModel) {\n\t\treturn hasCurrentModel ? currentModel : null;\n\t}\n\treturn catalogDefault(currentModel, models);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"better-sqlite3\";\n\nexport type VectorLayout =\n\t| { kind: \"absent\" }\n\t| { kind: \"legacy\"; physicalName: \"memory_vectors\"; rowidsName: \"memory_vectors_rowids\" }\n\t| { kind: \"v1\"; physicalName: \"memory_vectors_v1\"; rowidsName: \"memory_vectors_v1_rowids\" };\n\nexport const VECTOR_V1_DDL = `CREATE VIRTUAL TABLE memory_vectors_v1 USING vec0(\n\tembedding float[384], memory_id INTEGER, chunk_index INTEGER, content_hash TEXT, model TEXT\n);`;\n\n// Keep the format-v1 catalog/version contract shared with the validated index.\nexport const VALIDATED_VECTOR_SCHEMA_DDL = `\nCREATE TABLE IF NOT EXISTS validated_vector_state (\n id INTEGER PRIMARY KEY CHECK(id=1), generation_id TEXT NOT NULL,\n revision INTEGER NOT NULL, writer_version INTEGER NOT NULL,\n status TEXT NOT NULL, audit_started INTEGER NOT NULL DEFAULT 0,\n known_models TEXT NOT NULL DEFAULT '[]', pending_count INTEGER NOT NULL DEFAULT 0,\n invalid_count INTEGER NOT NULL DEFAULT 0);\nCREATE TABLE IF NOT EXISTS validated_vector_models (\n model_null INTEGER NOT NULL, model_key TEXT NOT NULL, model TEXT,\n count INTEGER NOT NULL CHECK(count>=0), PRIMARY KEY(model_null,model_key));\nCREATE TABLE IF NOT EXISTS validated_vector_versions (\n memory_id INTEGER NOT NULL, model_null INTEGER NOT NULL, model_key TEXT NOT NULL,\n model TEXT, version INTEGER NOT NULL, count INTEGER NOT NULL CHECK(count>=0),\n PRIMARY KEY(memory_id,model_null,model_key));\nCREATE TABLE IF NOT EXISTS validated_vector_rows (\n rowid INTEGER PRIMARY KEY, memory_id INTEGER NOT NULL, model TEXT,\n chunk_index INTEGER NOT NULL, content_hash TEXT, audit_state TEXT NOT NULL, reason TEXT);\nCREATE INDEX IF NOT EXISTS validated_vector_rows_model_memory\n ON validated_vector_rows(model,memory_id);\nCREATE INDEX IF NOT EXISTS validated_vector_rows_state\n ON validated_vector_rows(audit_state,rowid);\nCREATE INDEX IF NOT EXISTS validated_vector_rows_model_state_memory\n ON validated_vector_rows(model,audit_state,memory_id);`;\n\nexport const VECTOR_COMPATIBILITY_DDL = `\nCREATE VIEW memory_vectors AS\n SELECT rowid AS rowid,embedding,memory_id,chunk_index,content_hash,model FROM memory_vectors_v1;\nCREATE TRIGGER memory_vectors_reject_insert INSTEAD OF INSERT ON memory_vectors\n BEGIN SELECT RAISE(ABORT,'vector_writer_upgrade_required'); END;\nCREATE TRIGGER memory_vectors_reject_update INSTEAD OF UPDATE ON memory_vectors\n BEGIN SELECT RAISE(ABORT,'vector_writer_upgrade_required'); END;\nCREATE TRIGGER memory_vectors_compat_delete INSTEAD OF DELETE ON memory_vectors\nBEGIN\n SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM validated_vector_rows WHERE rowid=OLD.rowid\n AND memory_id IS OLD.memory_id AND model IS OLD.model\n AND chunk_index IS OLD.chunk_index AND content_hash IS OLD.content_hash)\n THEN RAISE(ABORT,'vector_index_metadata_missing') END;\n SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM validated_vector_models\n WHERE model_null=(OLD.model IS NULL) AND model_key=COALESCE(OLD.model,'') AND count>0)\n OR NOT EXISTS (SELECT 1 FROM validated_vector_versions WHERE memory_id=OLD.memory_id\n AND model_null=(OLD.model IS NULL) AND model_key=COALESCE(OLD.model,'') AND count>0)\n OR NOT EXISTS (SELECT 1 FROM validated_vector_state WHERE id=1 AND writer_version=1)\n THEN RAISE(ABORT,'vector_index_metadata_missing') END;\n UPDATE validated_vector_models SET count=count-1\n WHERE model_null=(OLD.model IS NULL) AND model_key=COALESCE(OLD.model,'');\n UPDATE validated_vector_versions SET count=count-1,version=version+1\n WHERE memory_id=OLD.memory_id AND model_null=(OLD.model IS NULL)\n AND model_key=COALESCE(OLD.model,'');\n UPDATE validated_vector_state SET revision=revision+1,\n pending_count=pending_count-(SELECT audit_state='pending' FROM validated_vector_rows WHERE rowid=OLD.rowid),\n invalid_count=invalid_count-(SELECT audit_state='invalid' FROM validated_vector_rows WHERE rowid=OLD.rowid)\n WHERE id=1;\n DELETE FROM validated_vector_rows WHERE rowid=OLD.rowid;\n DELETE FROM memory_vectors_v1 WHERE rowid=OLD.rowid;\n UPDATE validated_vector_state SET status=CASE\n WHEN audit_started=0 OR pending_count>0 THEN 'building'\n WHEN invalid_count>0 THEN 'needsrepair' ELSE 'ready' END WHERE id=1;\nEND;`;\n\nconst METADATA_TABLES = [\n\t\"validated_vector_state\",\n\t\"validated_vector_rows\",\n\t\"validated_vector_models\",\n\t\"validated_vector_versions\",\n] as const;\n\nfunction normalizedDdl(sql: string): string {\n\treturn sql.trim().replace(/;$/, \"\").replace(/\\s+/g, \" \");\n}\n\nfunction compatibilityFenceExists(db: Database): boolean {\n\tconst read = db.prepare(\"SELECT sql FROM sqlite_schema WHERE name=?\");\n\tconst names = [\n\t\t\"memory_vectors\",\n\t\t\"memory_vectors_reject_insert\",\n\t\t\"memory_vectors_reject_update\",\n\t\t\"memory_vectors_compat_delete\",\n\t];\n\tconst definitions = VECTOR_COMPATIBILITY_DDL.trim().split(/(?=CREATE (?:VIEW|TRIGGER) )/);\n\treturn names.every((name, index) => {\n\t\tconst row = read.get(name) as { sql: string } | undefined;\n\t\treturn row !== undefined && normalizedDdl(row.sql) === normalizedDdl(definitions[index] ?? \"\");\n\t});\n}\n\n/** Only return identifiers selected from this fixed set, never caller SQL. */\nexport function resolveVectorLayout(db: Database): VectorLayout {\n\tconst objects = db\n\t\t.prepare(\n\t\t\t\"SELECT name,type FROM sqlite_schema WHERE name IN ('memory_vectors','memory_vectors_v1','memory_vectors_v1_rowids')\",\n\t\t)\n\t\t.all() as { name: string; type: string }[];\n\tconst legacy = objects.find((object) => object.name === \"memory_vectors\");\n\tif (legacy?.type === \"table\") {\n\t\tif (objects.some((object) => object.name === \"memory_vectors_v1\"))\n\t\t\tthrow new Error(\"vector_layout_inconsistent\");\n\t\treturn { kind: \"legacy\", physicalName: \"memory_vectors\", rowidsName: \"memory_vectors_rowids\" };\n\t}\n\tif (!objects.length) return { kind: \"absent\" };\n\tconst exists = db.prepare(\"SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?\");\n\tif (\n\t\tlegacy?.type !== \"view\" ||\n\t\t!objects.some((object) => object.name === \"memory_vectors_v1\" && object.type === \"table\") ||\n\t\t!objects.some((object) => object.name === \"memory_vectors_v1_rowids\") ||\n\t\t!METADATA_TABLES.every((name) => exists.get(name))\n\t) {\n\t\tthrow new Error(\"vector_layout_inconsistent\");\n\t}\n\tconst state = db.prepare(\"SELECT writer_version FROM validated_vector_state WHERE id=1\").get() as\n\t\t| { writer_version: number }\n\t\t| undefined;\n\tif (state?.writer_version !== 1) throw new Error(\"validated_index_format_required\");\n\tif (!compatibilityFenceExists(db)) throw new Error(\"vector_layout_writer_fence_missing\");\n\treturn { kind: \"v1\", physicalName: \"memory_vectors_v1\", rowidsName: \"memory_vectors_v1_rowids\" };\n}\n\nexport function vectorStoreExists(db: Database): boolean {\n\ttry {\n\t\treturn resolveVectorLayout(db).kind !== \"absent\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Fresh stores never create the legacy writable name. No imports from db/bootstrap. */\nexport function createEmptyVectorLayout(db: Database): void {\n\tdb.transaction(() => {\n\t\tdb.exec(VECTOR_V1_DDL);\n\t\tdb.exec(VALIDATED_VECTOR_SCHEMA_DDL);\n\t\tdb.prepare(`INSERT INTO validated_vector_state\n\t\t (id,generation_id,revision,writer_version,status,audit_started) VALUES(1,?,0,1,'ready',1)`).run(\n\t\t\trandomUUID(),\n\t\t);\n\t\tdb.exec(VECTOR_COMPATIBILITY_DDL);\n\t}).immediate();\n}\n","/** Exact semantic ranking inside a caller-owned, validated read snapshot. */\nimport { type Database, tableExists } from \"../db.js\";\nimport { DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL } from \"../embeddings.js\";\nimport type { MaintenanceJobSnapshot, MaintenanceJobStatus } from \"../maintenance-jobs.js\";\nimport {\n\tbuildAuthorizedSemanticMemoryIdsQuery,\n\tresolveSemanticSearchModelFromCatalog,\n\tsemanticResult,\n} from \"../semantic-query.js\";\nimport type { MemoryFilters } from \"../types.js\";\nimport { resolveVectorLayout } from \"../vector-layout.js\";\nimport type { SemanticSearchResult, SemanticSearchScopeContext } from \"../vectors.js\";\n\nexport interface PreparedQuery {\n\tmodel: string;\n\tvectors: readonly Float32Array[];\n}\nexport interface VectorRowInput {\n\tmemoryId: number;\n\tchunkIndex: number;\n\tcontentHash: string;\n\tvector: Float32Array;\n}\ntype Rejection = \"shape\" | \"nonfinite\" | \"norm\" | \"model\";\nexport interface RankingRequest {\n\tquery: PreparedQuery;\n\tlimit: number;\n\tfilters: MemoryFilters | null;\n\tcontext: SemanticSearchScopeContext;\n\tsummarySessionId?: number | null;\n}\ninterface Probe {\n\tmodel: string;\n\tk: number;\n\treturned: number;\n\texhausted: boolean;\n\ttailDistance: number | null;\n}\nexport interface RankingResult {\n\tresults: SemanticSearchResult[];\n\tstrategy: \"native\" | \"scalar\";\n\tprobes: readonly Probe[];\n\tfallbackCount: number;\n}\ninterface CandidateScope {\n\tsql: string;\n\tparams: unknown[];\n\tacceptedSql: string;\n\tacceptedParams: string[];\n\trowidSource: \"memory_vectors\" | \"validated_vector_rows\";\n\tvectorTable: \"memory_vectors\" | \"memory_vectors_v1\";\n}\ninterface Neighbor {\n\tid: number;\n\tdistance: number;\n}\n\nexport function requireModel(model: string): void {\n\tif (typeof model !== \"string\" || !model.trim()) throw new TypeError(\"vector_model_required\");\n}\n\nfunction vectorRejection(vector: Float32Array): Rejection | null {\n\tif (!(vector instanceof Float32Array) || vector.length !== 384) return \"shape\";\n\tlet normSquared = 0;\n\tfor (const component of vector) {\n\t\tif (!Number.isFinite(component)) return \"nonfinite\";\n\t\tnormSquared += component * component;\n\t}\n\t// Normalized embeddings have norm ~1. Norm <=2 allows rounding headroom without\n\t// renormalization. For two accepted vectors L2 <=4, squared L2 <=16: float32-safe.\n\tif (normSquared > 4) return \"norm\";\n\treturn null;\n}\n\nexport function vectorBytes(vector: Float32Array): Buffer {\n\tconst rejection = vectorRejection(vector);\n\tif (rejection) throw new TypeError(`invalid_vector_${rejection}`);\n\tconst bytes = Buffer.alloc(384 * 4);\n\tvector.forEach((component, index) => {\n\t\tbytes.writeFloatLE(component, index * 4);\n\t});\n\treturn bytes;\n}\n\nexport function inspectBytes(bytes: Buffer): Rejection | null {\n\tif (!Buffer.isBuffer(bytes) || bytes.length !== 384 * 4) return \"shape\";\n\tconst vector = new Float32Array(384);\n\tfor (let index = 0; index < vector.length; index++) vector[index] = bytes.readFloatLE(index * 4);\n\treturn vectorRejection(vector);\n}\n\nfunction readModelMetadata(json: string | null): Record<string, unknown> | null {\n\ttry {\n\t\tconst value: unknown = JSON.parse(json ?? \"null\");\n\t\tif (value && typeof value === \"object\" && !Array.isArray(value)) {\n\t\t\treturn value as Record<string, unknown>;\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n\nexport function readModelJob(\n\tdb: Database,\n): Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null {\n\tif (!tableExists(db, \"maintenance_jobs\")) return null;\n\tconst row = db\n\t\t.prepare(\"SELECT status, metadata_json FROM maintenance_jobs WHERE kind = ?\")\n\t\t.get(\"vector_model_migration\") as\n\t\t| { status: MaintenanceJobStatus; metadata_json: string | null }\n\t\t| undefined;\n\tif (!row) return null;\n\treturn { status: row.status, metadata: readModelMetadata(row.metadata_json) };\n}\n\nexport function resolveCatalogModels(\n\tcurrentModel: string,\n\tcatalog: Array<string | null>,\n\tjob: Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null,\n): string[] {\n\tconst primary = resolveSemanticSearchModelFromCatalog(currentModel, job, catalog);\n\tif (!primary) return [];\n\tif (\n\t\tprimary === \"Xenova/bge-small-en-v1.5\" &&\n\t\tcurrentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL &&\n\t\tcatalog.includes(currentModel)\n\t) {\n\t\treturn [primary, currentModel];\n\t}\n\treturn [primary];\n}\n\nfunction candidateScope(\n\tdb: Database,\n\trequest: RankingRequest,\n\toptions: { acceptedIds: string | null; indexedRows?: boolean },\n): CandidateScope {\n\tconst authorized = buildAuthorizedSemanticMemoryIdsQuery(\n\t\trequest.filters,\n\t\t{ ...request.context, visibleScopeIds: undefined, scopeVisibilityDb: db },\n\t\trequest.summarySessionId,\n\t);\n\tconst rowidSource = options.indexedRows ? \"validated_vector_rows\" : \"memory_vectors\";\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\tconst vectorTable = layout.physicalName;\n\tconst validitySql = options.indexedRows ? \"AND audit_state='valid'\" : \"\";\n\tif (options.acceptedIds === null) {\n\t\treturn {\n\t\t\t...authorized,\n\t\t\tacceptedSql: validitySql,\n\t\t\tacceptedParams: [],\n\t\t\trowidSource,\n\t\t\tvectorTable,\n\t\t};\n\t}\n\treturn {\n\t\t...authorized,\n\t\tacceptedSql: `${validitySql} AND rowid IN (SELECT value FROM json_each(?))`,\n\t\tacceptedParams: [options.acceptedIds],\n\t\trowidSource,\n\t\tvectorTable,\n\t};\n}\n\nfunction nativeProbe(\n\tdb: Database,\n\toptions: { model: string; scope: CandidateScope; query: Buffer; k: number },\n) {\n\tconst { scope } = options;\n\t// Both constraints belong to vec0's MATCH query, not a joined postfilter.\n\tconst rows = db\n\t\t.prepare(`WITH authorized_ids AS MATERIALIZED (${scope.sql})\n\t\tSELECT memory_id AS id, distance FROM ${scope.vectorTable}\n\t\tWHERE embedding MATCH ? AND k = ? AND model = ?\n\t\tAND rowid IN (\n\t\t\tSELECT rowid FROM ${scope.rowidSource}\n\t\t\tWHERE model = ? AND memory_id IN (SELECT id FROM authorized_ids)\n\t\t\t${scope.acceptedSql}\n\t\t) ORDER BY distance`)\n\t\t.all(\n\t\t\t...scope.params,\n\t\t\toptions.query,\n\t\t\toptions.k,\n\t\t\toptions.model,\n\t\t\toptions.model,\n\t\t\t...scope.acceptedParams,\n\t\t) as Neighbor[];\n\tfor (const row of rows) {\n\t\tif (!Number.isSafeInteger(row.id) || !Number.isFinite(row.distance)) {\n\t\t\tthrow new Error(\"invalid_native_neighbor\");\n\t\t}\n\t}\n\tconst probe: Probe = {\n\t\tmodel: options.model,\n\t\tk: options.k,\n\t\treturned: rows.length,\n\t\t// Exactly k returned may also exhaust a model, but proving that would\n\t\t// require counting every eligible row. Treat it as unknown instead.\n\t\texhausted: rows.length < options.k,\n\t\ttailDistance: rows.at(-1)?.distance ?? null,\n\t};\n\treturn { neighbors: rows, probe };\n}\n\nfunction mergeNeighbors(neighbors: Neighbor[]): Neighbor[] {\n\tconst best = new Map<number, number>();\n\tfor (const { id, distance } of neighbors) {\n\t\tbest.set(id, Math.min(best.get(id) ?? Number.POSITIVE_INFINITY, distance));\n\t}\n\treturn [...best]\n\t\t.map(([id, distance]) => ({ id, distance }))\n\t\t.sort((a, b) => a.distance - b.distance || a.id - b.id);\n}\n\nfunction scalarRank(\n\tdb: Database,\n\toptions: { scope: CandidateScope; models: string[]; query: Buffer; limit: number },\n): Neighbor[] {\n\tconst { scope } = options;\n\treturn db\n\t\t.prepare(`WITH authorized_ids AS MATERIALIZED (${scope.sql})\n\t\tSELECT memory_id AS id, MIN(vec_distance_l2(embedding, ?)) AS distance\n\t\tFROM ${scope.vectorTable} WHERE rowid IN (\n\t\t\tSELECT rowid FROM ${scope.rowidSource}\n\t\t\tWHERE memory_id IN (SELECT id FROM authorized_ids)\n\t\t\tAND model IN (SELECT value FROM json_each(?)) ${scope.acceptedSql}\n\t\t)\n\t\tGROUP BY memory_id ORDER BY distance, memory_id LIMIT ?`)\n\t\t.all(\n\t\t\t...scope.params,\n\t\t\toptions.query,\n\t\t\tJSON.stringify(options.models),\n\t\t\t...scope.acceptedParams,\n\t\t\toptions.limit,\n\t\t) as Neighbor[];\n}\n\nfunction loadPayloads(db: Database, ranked: Neighbor[]): SemanticSearchResult[] {\n\tconst rows = db\n\t\t.prepare(\"SELECT * FROM memory_items WHERE id IN (SELECT value FROM json_each(?))\")\n\t\t.all(JSON.stringify(ranked.map(({ id }) => id))) as Record<string, unknown>[];\n\tconst byId = new Map(rows.map((row) => [Number(row.id), row]));\n\tconst results: SemanticSearchResult[] = [];\n\tfor (const { id, distance } of ranked) {\n\t\tconst row = byId.get(id);\n\t\tif (!row) continue;\n\t\tresults.push(semanticResult({ ...row, distance }));\n\t}\n\treturn results;\n}\n\n/** Internal engine; caller supplies validation evidence and owns the read snapshot. */\nexport function rankPrevalidatedSnapshot(\n\tdb: Database,\n\trequest: RankingRequest,\n\toptions: { models: string[]; acceptedIds: string | null; indexedRows?: boolean },\n): RankingResult {\n\tif (!db.inTransaction) throw new Error(\"ranking_snapshot_required\");\n\tvalidateRankingRequest(request);\n\tconst query = vectorBytes(request.query.vectors[0] as Float32Array);\n\tconst scope = candidateScope(db, request, options);\n\tconst { models } = options;\n\tconst k = Math.min(4096, Math.max(request.limit + 1, 4 * request.limit));\n\tconst outputs = models.map((model) =>\n\t\tnativeProbe(db, {\n\t\t\tmodel,\n\t\t\tscope,\n\t\t\tquery,\n\t\t\tk,\n\t\t}),\n\t);\n\tconst probes = outputs.map((output) => output.probe);\n\tconst merged = mergeNeighbors(outputs.flatMap((output) => output.neighbors));\n\tconst nth = merged[request.limit - 1]?.distance;\n\tconst certified =\n\t\tnth !== undefined &&\n\t\tprobes.every(\n\t\t\t(probe) => probe.exhausted || (probe.tailDistance !== null && probe.tailDistance > nth),\n\t\t);\n\tconst ranked = certified\n\t\t? merged.slice(0, request.limit)\n\t\t: scalarRank(db, { scope, models, query, limit: request.limit });\n\tconst results = loadPayloads(db, ranked);\n\treturn {\n\t\tresults,\n\t\tstrategy: certified ? \"native\" : \"scalar\",\n\t\tprobes,\n\t\tfallbackCount: certified ? 0 : 1,\n\t};\n}\n\nexport function validateRankingRequest(request: RankingRequest): void {\n\tif (!Number.isInteger(request.limit) || request.limit < 1 || request.limit > 200) {\n\t\tthrow new RangeError(\"semantic_limit_must_be_1_to_200\");\n\t}\n\trequireModel(request.query.model);\n\tif (request.query.vectors.length !== 1) throw new TypeError(\"query_vector_count_mismatch\");\n\tif (!request.context?.deviceId?.trim()) throw new Error(\"semantic_search_scope_context_required\");\n}\n","/** Persisted format-v1 metadata. Raw/older writers require invalidation and rebuild. */\nimport { randomUUID } from \"node:crypto\";\nimport { type Database, tableExists } from \"../db.js\";\nimport type { MaintenanceJobSnapshot } from \"../maintenance-jobs.js\";\nimport { readModelJob } from \"./semantic-ranking.js\";\nimport type { AuditStateStatements, CountStatements } from \"./validated-vector-index-statements.js\";\n\nexport interface VectorCatalog {\n\tgenerationId: string;\n\trevision: number;\n\tstatus: \"building\" | \"needsrepair\" | \"ready\";\n\twriterVersion: 1;\n\tmodels: { model: string | null; count: number }[];\n\tmigration: Pick<MaintenanceJobSnapshot, \"status\" | \"metadata\"> | null;\n}\nexport interface CandidateVersion {\n\tmemoryId: number;\n\tmodel: string;\n\tversion: number;\n\tcount: number;\n}\nexport interface State {\n\tgeneration_id: string;\n\trevision: number;\n\tstatus: VectorCatalog[\"status\"];\n\twriter_version: number;\n\taudit_started: number;\n\tknown_models: string;\n\tpending_count: number;\n\tinvalid_count: number;\n}\nexport interface IndexedRow {\n\trowid: number;\n\tmemory_id: number;\n\tmodel: string | null;\n\tchunk_index: number;\n\tcontent_hash: string;\n\taudit_state: \"pending\" | \"valid\" | \"invalid\";\n\treason: string | null;\n}\nexport interface AuditProgress {\n\tcatalog: VectorCatalog;\n\tchecked: number;\n\tremaining: number;\n\tinvalid: number;\n\tdiagnostics: {\n\t\trowid: number;\n\t\treason: string;\n\t\tmemoryId?: number;\n\t\tmodel?: string | null;\n\t\taction?: \"pruned\";\n\t}[];\n}\n\nexport function snapshot<T>(db: Database, read: () => T): T {\n\tif (db.inTransaction) return read();\n\treturn db.transaction(read)();\n}\n\nexport function readState(db: Database): State {\n\tconst state = db.prepare(\"SELECT * FROM validated_vector_state WHERE id = 1\").get() as State;\n\tif (state?.writer_version !== 1) throw new Error(\"validated_index_format_required\");\n\treturn state;\n}\n\nexport function readCatalog(db: Database): VectorCatalog | null {\n\treturn snapshot(db, () => {\n\t\tif (!tableExists(db, \"validated_vector_state\")) return null;\n\t\tconst state = readState(db);\n\t\tconst models = db\n\t\t\t.prepare(`SELECT model, count FROM validated_vector_models\n\t\t\tWHERE count > 0 ORDER BY model_null, model_key`)\n\t\t\t.all() as VectorCatalog[\"models\"];\n\t\treturn {\n\t\t\tgenerationId: state.generation_id,\n\t\t\trevision: state.revision,\n\t\t\tstatus: state.status,\n\t\t\twriterVersion: 1,\n\t\t\tmodels,\n\t\t\tmigration: readModelJob(db),\n\t\t};\n\t});\n}\n\nexport function requireCatalog(db: Database): VectorCatalog {\n\tconst catalog = readCatalog(db);\n\tif (!catalog) throw new Error(\"validated_index_not_initialized\");\n\treturn catalog;\n}\n\n/** Completed audits can supply valid evidence while other derived rows await repair. */\nexport function isSearchableVectorCatalog(\n\tdb: Database,\n\tcatalog: VectorCatalog | null,\n): catalog is VectorCatalog {\n\tif (catalog?.writerVersion !== 1) return false;\n\tif (catalog.status === \"ready\") return catalog.models.some(({ count }) => count > 0);\n\tif (catalog.status !== \"needsrepair\") return false;\n\treturn Boolean(\n\t\tdb.prepare(\"SELECT 1 FROM validated_vector_rows WHERE audit_state='valid' LIMIT 1\").get(),\n\t);\n}\n\nexport function readSearchableModelLabels(\n\tdb: Database,\n\tcatalog: VectorCatalog,\n): Array<string | null> {\n\tconst labels = catalog.models.map(({ model }) => model);\n\tif (catalog.status !== \"needsrepair\") return labels;\n\tconst valid = db.prepare(\n\t\t\"SELECT 1 FROM validated_vector_rows WHERE model IS ? AND audit_state='valid' LIMIT 1\",\n\t);\n\treturn labels.filter((model) => Boolean(valid.get(model)));\n}\n\nexport function requireWriter(version: number): void {\n\tif (version !== 1) throw new TypeError(\"validated_writer_version_required\");\n}\n\nexport function requireGenerationModel(state: State, model: string): void {\n\tif (!state.audit_started) return;\n\tconst knownModels: unknown = JSON.parse(state.known_models);\n\tif (!Array.isArray(knownModels) || !knownModels.includes(model)) {\n\t\tthrow new TypeError(\"vector_model_not_declared_in_generation\");\n\t}\n}\n\nexport function initializeValidatedIndex(\n\tdb: Database,\n\toptions: { allWritersUpgraded: true; writerVersion: 1 },\n): VectorCatalog {\n\tif (options.allWritersUpgraded !== true) throw new TypeError(\"all_writers_must_be_upgraded\");\n\trequireWriter(options.writerVersion);\n\treturn db.transaction(() => {\n\t\tdb.exec(`\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_state (\n\t\t\t id INTEGER PRIMARY KEY CHECK(id=1), generation_id TEXT NOT NULL,\n\t\t\t revision INTEGER NOT NULL, writer_version INTEGER NOT NULL,\n\t\t\t status TEXT NOT NULL, audit_started INTEGER NOT NULL DEFAULT 0,\n\t\t\t known_models TEXT NOT NULL DEFAULT '[]', pending_count INTEGER NOT NULL DEFAULT 0,\n\t\t\t invalid_count INTEGER NOT NULL DEFAULT 0);\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_models (\n\t\t\t model_null INTEGER NOT NULL, model_key TEXT NOT NULL, model TEXT,\n\t\t\t count INTEGER NOT NULL CHECK(count>=0), PRIMARY KEY(model_null,model_key));\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_versions (\n\t\t\t memory_id INTEGER NOT NULL, model_null INTEGER NOT NULL, model_key TEXT NOT NULL,\n\t\t\t model TEXT, version INTEGER NOT NULL, count INTEGER NOT NULL CHECK(count>=0),\n\t\t\t PRIMARY KEY(memory_id,model_null,model_key));\n\t\t\tCREATE TABLE IF NOT EXISTS validated_vector_rows (\n\t\t\t rowid INTEGER PRIMARY KEY, memory_id INTEGER NOT NULL, model TEXT,\n\t\t\t chunk_index INTEGER NOT NULL, content_hash TEXT, audit_state TEXT NOT NULL,\n\t\t\t reason TEXT);\n\t\t\tCREATE INDEX IF NOT EXISTS validated_vector_rows_model_memory\n\t\t\t ON validated_vector_rows(model,memory_id);\n\t\t\tCREATE INDEX IF NOT EXISTS validated_vector_rows_state\n\t\t\t ON validated_vector_rows(audit_state,rowid);\n\t\t\tCREATE INDEX IF NOT EXISTS validated_vector_rows_model_state_memory\n\t\t\t ON validated_vector_rows(model,audit_state,memory_id);\n\t\t`);\n\t\tdb.prepare(`INSERT OR IGNORE INTO validated_vector_state\n\t\t\t(id,generation_id,revision,writer_version,status) VALUES(1,?,0,1,'building')`).run(\n\t\t\trandomUUID(),\n\t\t);\n\t\treturn requireCatalog(db);\n\t})();\n}\n\nexport function invalidateValidatedIndex(db: Database): VectorCatalog {\n\treturn db.transaction(() => {\n\t\treadState(db);\n\t\tdb.prepare(`UPDATE validated_vector_state SET generation_id=?, revision=revision+1,\n\t\t\tstatus='building',audit_started=0 WHERE id=1`).run(randomUUID());\n\t\treturn requireCatalog(db);\n\t})();\n}\n\nexport function refreshStatus(db: Database): void {\n\tdb.exec(`UPDATE validated_vector_state SET status=CASE\n\t\tWHEN audit_started=0 OR pending_count>0 THEN 'building'\n\t\tWHEN invalid_count>0 THEN 'needsrepair' ELSE 'ready' END WHERE id=1`);\n}\n\nexport function finishMutation(db: Database): VectorCatalog {\n\tdb.exec(\"UPDATE validated_vector_state SET revision=revision+1 WHERE id=1\");\n\trefreshStatus(db);\n\treturn requireCatalog(db);\n}\n\nexport function changeCounts(\n\tstatements: CountStatements,\n\tmemoryId: number,\n\tmodel: string | null,\n\tdelta: number,\n): void {\n\tconst nullKey = Number(model === null);\n\tconst key = model ?? \"\";\n\tstatements.insertModel.run(nullKey, key, model);\n\tstatements.updateModelCount.run(delta, nullKey, key);\n\tstatements.insertVersion.run(memoryId, nullKey, key, model);\n\tstatements.updateVersionCount.run(delta, memoryId, nullKey, key);\n}\n\nexport function updateAuditState(\n\tstatements: AuditStateStatements,\n\trow: IndexedRow,\n\tstate: IndexedRow[\"audit_state\"],\n\treason: string | null = null,\n): void {\n\tstatements.updateRowState.run(state, reason, row.rowid);\n\tconst pending = Number(state === \"pending\") - Number(row.audit_state === \"pending\");\n\tconst invalid = Number(state === \"invalid\") - Number(row.audit_state === \"invalid\");\n\tstatements.updateAuditCounts.run(pending, invalid);\n}\n\nexport function progress(\n\tdb: Database,\n\tchecked = 0,\n\tdiagnostics: AuditProgress[\"diagnostics\"] = [],\n): AuditProgress {\n\tconst state = readState(db);\n\treturn {\n\t\tcatalog: requireCatalog(db),\n\t\tchecked,\n\t\tremaining: state.pending_count,\n\t\tinvalid: state.invalid_count,\n\t\tdiagnostics,\n\t};\n}\n\nexport function requireLimit(limit: number): void {\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {\n\t\tthrow new RangeError(\"audit_limit_must_be_1_to_1000\");\n\t}\n}\n\nexport function readCandidateVersions(\n\tdb: Database,\n\toptions: { memoryIds: readonly number[]; models: readonly string[] },\n): CandidateVersion[] {\n\treturn snapshot(db, () => {\n\t\tif (!tableExists(db, \"validated_vector_state\")) return [];\n\t\treadState(db);\n\t\treturn db\n\t\t\t.prepare(`SELECT memory_id AS memoryId,model,version,count FROM validated_vector_versions\n\t\t\tWHERE memory_id IN (SELECT value FROM json_each(?)) AND model_null=0\n\t\t\tAND model_key IN (SELECT value FROM json_each(?)) ORDER BY memory_id,model_key`)\n\t\t\t.all(JSON.stringify(options.memoryIds), JSON.stringify(options.models)) as CandidateVersion[];\n\t});\n}\n","import type { Statement } from \"better-sqlite3\";\nimport type { Database } from \"../db.js\";\nimport { resolveVectorLayout } from \"../vector-layout.js\";\n\nexport type IndexStatement = Statement<unknown[]>;\n\nexport interface CountStatements {\n\tinsertModel: IndexStatement;\n\tupdateModelCount: IndexStatement;\n\tinsertVersion: IndexStatement;\n\tupdateVersionCount: IndexStatement;\n}\n\nexport interface InsertStatements {\n\tcounts: CountStatements;\n\tinsertVector: IndexStatement;\n\tinsertIndexedRow: IndexStatement;\n}\n\nexport interface RemoveStatements {\n\tcounts: CountStatements;\n\tdeleteVector: IndexStatement;\n\tdeleteIndexedRow: IndexStatement;\n\tdecrementAuditCounts: IndexStatement;\n}\n\nexport interface AuditStateStatements {\n\tupdateRowState: IndexStatement;\n\tupdateAuditCounts: IndexStatement;\n}\n\n/** These sets belong to one synchronous operation, never a connection-wide cache. */\nexport function prepareCountStatements(db: Database): CountStatements {\n\treturn {\n\t\tinsertModel:\n\t\t\tdb.prepare(`INSERT OR IGNORE INTO validated_vector_models(model_null,model_key,model,count)\n\t\tVALUES(?,?,?,0)`),\n\t\tupdateModelCount: db.prepare(\n\t\t\t`UPDATE validated_vector_models SET count=count+? WHERE model_null=? AND model_key=?`,\n\t\t),\n\t\tinsertVersion:\n\t\t\tdb.prepare(`INSERT OR IGNORE INTO validated_vector_versions(memory_id,model_null,model_key,model,version,count)\n\t\tVALUES(?,?,?,?,0,0)`),\n\t\tupdateVersionCount:\n\t\t\tdb.prepare(`UPDATE validated_vector_versions SET version=version+1,count=count+?\n\t\tWHERE memory_id=? AND model_null=? AND model_key=?`),\n\t};\n}\n\nexport function prepareInsertStatements(db: Database, counts: CountStatements): InsertStatements {\n\tconst table = physicalVectorTable(db);\n\treturn {\n\t\tcounts,\n\t\tinsertVector: db.prepare(`INSERT INTO ${table}\n\t\t(embedding,memory_id,chunk_index,content_hash,model) VALUES(?,?,?,?,?)`),\n\t\tinsertIndexedRow: db.prepare(`INSERT INTO validated_vector_rows\n\t\t(rowid,memory_id,model,chunk_index,content_hash,audit_state) VALUES(?,?,?,?,?,'valid')`),\n\t};\n}\n\nexport function prepareRemoveStatements(db: Database, counts: CountStatements): RemoveStatements {\n\tconst table = physicalVectorTable(db);\n\treturn {\n\t\tcounts,\n\t\tdeleteVector: db.prepare(`DELETE FROM ${table} WHERE rowid=?`),\n\t\tdeleteIndexedRow: db.prepare(\"DELETE FROM validated_vector_rows WHERE rowid=?\"),\n\t\tdecrementAuditCounts:\n\t\t\tdb.prepare(`UPDATE validated_vector_state SET pending_count=pending_count-?,\n\t\tinvalid_count=invalid_count-? WHERE id=1`),\n\t};\n}\n\nfunction physicalVectorTable(db: Database): \"memory_vectors\" | \"memory_vectors_v1\" {\n\tconst layout = resolveVectorLayout(db);\n\tif (layout.kind === \"absent\") throw new Error(\"vector_table_required\");\n\t// The v1 compatibility view owns legacy-delete bookkeeping and rejects inserts.\n\treturn layout.physicalName;\n}\n\nexport function prepareAuditStateStatements(db: Database): AuditStateStatements {\n\treturn {\n\t\tupdateRowState: db.prepare(\n\t\t\t\"UPDATE validated_vector_rows SET audit_state=?,reason=? WHERE rowid=?\",\n\t\t),\n\t\tupdateAuditCounts: db.prepare(`UPDATE validated_vector_state SET pending_count=pending_count+?,\n\t\tinvalid_count=invalid_count+? WHERE id=1`),\n\t};\n}\n","import type { Database } from \"../db.js\";\nimport { type VectorRowInput, vectorBytes } from \"./semantic-ranking.js\";\nimport {\n\tchangeCounts,\n\tfinishMutation,\n\ttype IndexedRow,\n\treadState,\n\trequireGenerationModel,\n\trequireWriter,\n\ttype VectorCatalog,\n} from \"./validated-vector-index-state.js\";\nimport {\n\ttype IndexStatement,\n\ttype InsertStatements,\n\tprepareCountStatements,\n\tprepareInsertStatements,\n\tprepareRemoveStatements,\n\ttype RemoveStatements,\n} from \"./validated-vector-index-statements.js\";\n\ninterface MemoryModelStatements {\n\trows: IndexStatement;\n\tremove: RemoveStatements;\n}\n\nexport interface ValidatedBatch {\n\twriterVersion: 1;\n\texpectedModel: string;\n\tmodel: string;\n\texpectedCount: number;\n\tmode: \"append\" | \"replace-memory-model\";\n\trows: readonly VectorRowInput[];\n}\n\nexport function requireModel(model: string): void {\n\tif (typeof model !== \"string\" || !model.trim()) throw new TypeError(\"vector_model_required\");\n}\n\nexport function requireVectorMetadata(row: Omit<VectorRowInput, \"vector\">): void {\n\tif (\n\t\t!Number.isSafeInteger(row.memoryId) ||\n\t\trow.memoryId <= 0 ||\n\t\t!Number.isSafeInteger(row.chunkIndex) ||\n\t\trow.chunkIndex < 0 ||\n\t\ttypeof row.contentHash !== \"string\" ||\n\t\t!row.contentHash.trim()\n\t) {\n\t\tthrow new TypeError(\"invalid_vector_metadata\");\n\t}\n}\n\nexport function removeRow(statements: RemoveStatements, row: IndexedRow): void {\n\tstatements.deleteVector.run(BigInt(row.rowid));\n\tstatements.deleteIndexedRow.run(row.rowid);\n\tchangeCounts(statements.counts, row.memory_id, row.model, -1);\n\tstatements.decrementAuditCounts.run(\n\t\tNumber(row.audit_state === \"pending\"),\n\t\tNumber(row.audit_state === \"invalid\"),\n\t);\n}\n\nexport function insertRow(\n\tstatements: InsertStatements,\n\trow: Omit<VectorRowInput, \"vector\">,\n\tmodel: string,\n\tbytes: Buffer,\n): void {\n\tconst result = statements.insertVector.run(\n\t\tbytes,\n\t\tBigInt(row.memoryId),\n\t\tBigInt(row.chunkIndex),\n\t\trow.contentHash,\n\t\tmodel,\n\t);\n\tconst rowid = Number(result.lastInsertRowid);\n\tif (!Number.isSafeInteger(rowid)) throw new RangeError(\"unsafe_vector_rowid\");\n\tstatements.insertIndexedRow.run(rowid, row.memoryId, model, row.chunkIndex, row.contentHash);\n\tchangeCounts(statements.counts, row.memoryId, model, 1);\n}\n\nfunction removeMemoryModel(\n\tstatements: MemoryModelStatements,\n\tmemoryId: number,\n\tmodel: string | null,\n): void {\n\tconst rows = statements.rows.all(model, memoryId) as IndexedRow[];\n\tfor (const row of rows) removeRow(statements.remove, row);\n}\n\nexport function writeValidatedBatch(db: Database, batch: ValidatedBatch): VectorCatalog {\n\trequireWriter(batch.writerVersion);\n\trequireModel(batch.model);\n\tif (batch.expectedModel !== batch.model) throw new TypeError(\"vector_model_mismatch\");\n\tif (!Number.isSafeInteger(batch.expectedCount) || batch.expectedCount !== batch.rows.length) {\n\t\tthrow new TypeError(\"vector_count_mismatch\");\n\t}\n\tif (batch.mode !== \"append\" && batch.mode !== \"replace-memory-model\") {\n\t\tthrow new TypeError(\"invalid_vector_write_mode\");\n\t}\n\tconst prepared = batch.rows.map((row) => {\n\t\trequireVectorMetadata(row);\n\t\treturn { ...row, bytes: vectorBytes(row.vector) };\n\t});\n\treturn db.transaction(() => {\n\t\tconst state = readState(db);\n\t\trequireGenerationModel(state, batch.model);\n\t\tif (batch.mode === \"replace-memory-model\" && !state.audit_started) {\n\t\t\tthrow new Error(\"start_audit_census_required\");\n\t\t}\n\t\tconst counts = prepareCountStatements(db);\n\t\tconst insert = prepareInsertStatements(db, counts);\n\t\tconst sourceExists = db.prepare(\"SELECT 1 FROM memory_items WHERE id=?\");\n\t\tlet removal: MemoryModelStatements | undefined;\n\t\tif (batch.mode === \"replace-memory-model\") {\n\t\t\tremoval = {\n\t\t\t\trows: db.prepare(\"SELECT * FROM validated_vector_rows WHERE model IS ? AND memory_id=?\"),\n\t\t\t\tremove: prepareRemoveStatements(db, counts),\n\t\t\t};\n\t\t}\n\t\tconst ids = new Set(prepared.map((row) => row.memoryId));\n\t\tfor (const id of ids) {\n\t\t\tif (!sourceExists.get(id)) {\n\t\t\t\tthrow new Error(\"vector_source_memory_missing\");\n\t\t\t}\n\t\t\tif (removal) removeMemoryModel(removal, id, batch.model);\n\t\t}\n\t\tfor (const row of prepared) insertRow(insert, row, batch.model, row.bytes);\n\t\treturn finishMutation(db);\n\t})();\n}\n\nexport function deleteValidatedVectors(\n\tdb: Database,\n\toptions: { writerVersion: 1; memoryId: number; model: string | null },\n): VectorCatalog {\n\trequireWriter(options.writerVersion);\n\tif (!Number.isSafeInteger(options.memoryId) || options.memoryId < 1)\n\t\tthrow new TypeError(\"invalid_memory_id\");\n\tif (options.model !== null) requireModel(options.model);\n\treturn db.transaction(() => {\n\t\tif (!readState(db).audit_started) throw new Error(\"start_audit_census_required\");\n\t\tremoveMemoryModel(\n\t\t\t{\n\t\t\t\trows: db.prepare(\"SELECT * FROM validated_vector_rows WHERE model IS ? AND memory_id=?\"),\n\t\t\t\tremove: prepareRemoveStatements(db, prepareCountStatements(db)),\n\t\t\t},\n\t\t\toptions.memoryId,\n\t\t\toptions.model,\n\t\t);\n\t\treturn finishMutation(db);\n\t})();\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Database } from \"../db.js\";\nimport { inspectBytes } from \"./semantic-ranking.js\";\nimport { requireModel, requireVectorMetadata } from \"./validated-vector-index-mutations.js\";\nimport {\n\ttype AuditProgress,\n\tfinishMutation,\n\ttype IndexedRow,\n\tprogress,\n\treadState,\n\trefreshStatus,\n\trequireCatalog,\n\trequireLimit,\n\tupdateAuditState,\n\ttype VectorCatalog,\n} from \"./validated-vector-index-state.js\";\nimport {\n\ttype IndexStatement,\n\tprepareAuditStateStatements,\n} from \"./validated-vector-index-statements.js\";\n\n/** One metadata census per generation; vector blobs are read only by bounded audit batches. */\nexport function startAudit(\n\tdb: Database,\n\toptions: { knownModels: readonly string[] },\n): VectorCatalog {\n\tfor (const model of options.knownModels) requireModel(model);\n\treturn db.transaction(() => {\n\t\treadState(db);\n\t\tdb.exec(`DELETE FROM validated_vector_rows;\n\t\t\tINSERT INTO validated_vector_rows(rowid,memory_id,model,chunk_index,content_hash,audit_state)\n\t\t\t SELECT rowid,memory_id,model,chunk_index,content_hash,'pending' FROM memory_vectors;\n\t\t\tDELETE FROM validated_vector_models;\n\t\t\tINSERT INTO validated_vector_models(model_null,model_key,model,count)\n\t\t\t SELECT model IS NULL,COALESCE(model,''),model,COUNT(*) FROM validated_vector_rows GROUP BY model;\n\t\t\tUPDATE validated_vector_versions SET count=0,version=version+1;\n\t\t\tINSERT INTO validated_vector_versions(memory_id,model_null,model_key,model,version,count)\n\t\t\t SELECT memory_id,model IS NULL,COALESCE(model,''),model,1,COUNT(*)\n\t\t\t FROM validated_vector_rows GROUP BY memory_id,model\n\t\t\t ON CONFLICT(memory_id,model_null,model_key) DO UPDATE SET count=excluded.count;`);\n\t\tdb.prepare(`UPDATE validated_vector_state SET generation_id=?,revision=revision+1,\n\t\t\taudit_started=1,known_models=?,pending_count=(SELECT COUNT(*) FROM validated_vector_rows),\n\t\t\tinvalid_count=0 WHERE id=1`).run(\n\t\t\trandomUUID(),\n\t\t\tJSON.stringify([...new Set(options.knownModels)]),\n\t\t);\n\t\trefreshStatus(db);\n\t\treturn requireCatalog(db);\n\t})();\n}\n\nfunction rowRejection(\n\tstatements: { sourceExists: IndexStatement; vector: IndexStatement },\n\trow: IndexedRow,\n\tknownModels: Set<string>,\n): string | null {\n\tif (row.model === null || !knownModels.has(row.model)) return \"model\";\n\ttry {\n\t\trequireVectorMetadata({\n\t\t\tmemoryId: row.memory_id,\n\t\t\tchunkIndex: row.chunk_index,\n\t\t\tcontentHash: row.content_hash,\n\t\t});\n\t} catch {\n\t\treturn \"metadata\";\n\t}\n\tif (!statements.sourceExists.get(row.memory_id)) return \"metadata\";\n\tconst vector = statements.vector.get(BigInt(row.rowid)) as { embedding: Buffer } | undefined;\n\tif (!vector) throw new Error(\"audit_vector_row_missing_restart_required\");\n\treturn inspectBytes(vector.embedding);\n}\n\nexport function auditBatch(db: Database, options: { limit: number }): AuditProgress {\n\trequireLimit(options.limit);\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst state = readState(db);\n\t\t\tif (!state.audit_started) throw new Error(\"start_audit_required\");\n\t\t\tconst knownModels = new Set<string>(JSON.parse(state.known_models));\n\t\t\tconst rows = db\n\t\t\t\t.prepare(`SELECT * FROM validated_vector_rows\n\t\t\tWHERE audit_state='pending' ORDER BY rowid LIMIT ?`)\n\t\t\t\t.all(options.limit) as IndexedRow[];\n\t\t\tconst reads = {\n\t\t\t\tsourceExists: db.prepare(\"SELECT 1 FROM memory_items WHERE id=?\"),\n\t\t\t\tvector: db.prepare(\"SELECT embedding FROM memory_vectors WHERE rowid=?\"),\n\t\t\t};\n\t\t\tconst auditState = prepareAuditStateStatements(db);\n\t\t\tconst diagnostics: AuditProgress[\"diagnostics\"] = [];\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst reason = rowRejection(reads, row, knownModels);\n\t\t\t\tupdateAuditState(auditState, row, reason ? \"invalid\" : \"valid\", reason);\n\t\t\t\tif (reason) diagnostics.push({ rowid: row.rowid, reason });\n\t\t\t}\n\t\t\tfinishMutation(db);\n\t\t\treturn progress(db, rows.length, diagnostics);\n\t\t})\n\t\t.immediate();\n}\n","import { eq, or } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { columnExists, type Database, tableExists } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nconst SAME_PERSON_BINDING_PROVENANCE = new Set([\n\t\"user_confirmed_identity_setup\",\n\t\"recipient_invite\",\n\t\"exact_project_invite\",\n\t\"review_resolution\",\n]);\n\n/** Shared read-only resolver; authoritative bindings take precedence over legacy claims. */\nexport function resolveSameActorPeerIds(db: Database, actorId: string): string[] {\n\tconst sets = resolveBindings(db, actorId);\n\tif (!sets) return [];\n\tif (!tableExists(db, \"sync_peers\")) return [...sets.deviceIds].sort();\n\tconst hasAliasEvidence = [\"peer_device_id\", \"public_key\", \"pinned_fingerprint\"].every((column) =>\n\t\tcolumnExists(db, \"sync_peers\", column),\n\t);\n\tif (sets.boundDeviceIds.size > 0 && !hasAliasEvidence) return [...sets.deviceIds].sort();\n\tif (sets.boundDeviceIds.size > 0) resolveAliases(db, sets);\n\tconst legacyRows = drizzle(db, { schema })\n\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t.from(schema.syncPeers)\n\t\t.where(or(eq(schema.syncPeers.claimed_local_actor, 1), eq(schema.syncPeers.actor_id, actorId)))\n\t\t.all();\n\tfor (const row of legacyRows) {\n\t\tconst deviceId = String(row.peer_device_id ?? \"\").trim();\n\t\tif (deviceId && !sets.boundDeviceIds.has(deviceId)) sets.deviceIds.add(deviceId);\n\t}\n\treturn [...sets.deviceIds].sort();\n}\n\ntype BindingSets = {\n\tdeviceIds: Set<string>;\n\tboundDeviceIds: Set<string>;\n\tlocallyBoundDeviceIds: Set<string>;\n};\n\nfunction activeActor(db: Database, actorId: string, bindingCount: number): boolean {\n\tif (bindingCount === 0 || !tableExists(db, \"actors\")) return false;\n\tif (\n\t\t![\"actor_id\", \"status\", \"merged_into_actor_id\"].every((column) =>\n\t\t\tcolumnExists(db, \"actors\", column),\n\t\t)\n\t)\n\t\treturn false;\n\tconst actor = db\n\t\t.prepare(\"SELECT status, merged_into_actor_id FROM actors WHERE actor_id = ?\")\n\t\t.get(actorId) as { status: string; merged_into_actor_id: string | null } | undefined;\n\treturn actor?.status === \"active\" && !actor.merged_into_actor_id;\n}\n\nfunction resolveBindings(db: Database, actorId: string): BindingSets | null {\n\tconst sets: BindingSets = {\n\t\tdeviceIds: new Set(),\n\t\tboundDeviceIds: new Set(),\n\t\tlocallyBoundDeviceIds: new Set(),\n\t};\n\tconst hasIdentityBindings =\n\t\ttableExists(db, \"identity_devices\") &&\n\t\t[\"device_id\", \"identity_id\", \"status\", \"provenance\"].every((column) =>\n\t\t\tcolumnExists(db, \"identity_devices\", column),\n\t\t);\n\tif (tableExists(db, \"identity_devices\") && !hasIdentityBindings) return null;\n\tif (!hasIdentityBindings) return sets;\n\tconst bindings = db\n\t\t.prepare(\"SELECT device_id, identity_id, status, provenance FROM identity_devices\")\n\t\t.all() as Array<{\n\t\tdevice_id: string;\n\t\tidentity_id: string;\n\t\tstatus: string;\n\t\tprovenance: string;\n\t}>;\n\tconst localActorIsActive = activeActor(db, actorId, bindings.length);\n\tfor (const binding of bindings) {\n\t\tconst deviceId = String(binding.device_id ?? \"\").trim();\n\t\tif (!deviceId) continue;\n\t\tsets.boundDeviceIds.add(deviceId);\n\t\tif (\n\t\t\tlocalActorIsActive &&\n\t\t\tString(binding.identity_id ?? \"\").trim() === actorId &&\n\t\t\tbinding.status === \"active\" &&\n\t\t\tSAME_PERSON_BINDING_PROVENANCE.has(binding.provenance)\n\t\t) {\n\t\t\tsets.deviceIds.add(deviceId);\n\t\t\tsets.locallyBoundDeviceIds.add(deviceId);\n\t\t}\n\t}\n\treturn sets;\n}\n\ntype PeerEvidence = {\n\tpeer_device_id: string;\n\tpublic_key: string | null;\n\tpinned_fingerprint: string | null;\n};\n\nfunction validatedFingerprint(row: PeerEvidence): string | null {\n\tconst publicKey = String(row.public_key ?? \"\").trim();\n\tconst pinned = String(row.pinned_fingerprint ?? \"\").trim();\n\tif (!publicKey) return pinned || null;\n\tconst derived = fingerprintPublicKey(publicKey);\n\treturn pinned && pinned !== derived ? null : pinned || derived;\n}\n\nfunction provenFingerprint(row: PeerEvidence): string | null {\n\treturn String(row.public_key ?? \"\").trim() ? validatedFingerprint(row) : null;\n}\n\nfunction resolveAliases(db: Database, sets: BindingSets): void {\n\tconst { deviceIds, boundDeviceIds } = sets;\n\tconst peerEvidence = db\n\t\t.prepare(\"SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers\")\n\t\t.all() as PeerEvidence[];\n\tconst { boundFingerprints, locallyBoundFingerprints } = resolveBoundFingerprints(\n\t\tpeerEvidence,\n\t\tsets,\n\t);\n\tfor (const row of peerEvidence) {\n\t\tconst deviceId = String(row.peer_device_id ?? \"\").trim();\n\t\tconst fingerprint = validatedFingerprint(row);\n\t\tif (!deviceId || !fingerprint || !boundFingerprints.has(fingerprint)) continue;\n\t\tconst hasAuthoritativeBinding = boundDeviceIds.has(deviceId);\n\t\tboundDeviceIds.add(deviceId);\n\t\tif (\n\t\t\t!hasAuthoritativeBinding &&\n\t\t\tlocallyBoundFingerprints.has(fingerprint) &&\n\t\t\tprovenFingerprint(row)\n\t\t) {\n\t\t\tdeviceIds.add(deviceId);\n\t\t}\n\t}\n}\n\nfunction resolveBoundFingerprints(peerEvidence: PeerEvidence[], sets: BindingSets) {\n\tconst { boundDeviceIds, locallyBoundDeviceIds } = sets;\n\tconst boundFingerprints = new Set<string>();\n\tconst locallyBoundFingerprints = new Set<string>();\n\tconst conflictingBoundFingerprints = new Set<string>();\n\tfor (const row of peerEvidence) {\n\t\tconst deviceId = String(row.peer_device_id ?? \"\").trim();\n\t\tconst fingerprint = validatedFingerprint(row);\n\t\tif (!deviceId || !fingerprint || !boundDeviceIds.has(deviceId)) continue;\n\t\tboundFingerprints.add(fingerprint);\n\t\tif (locallyBoundDeviceIds.has(deviceId)) {\n\t\t\tif (provenFingerprint(row)) locallyBoundFingerprints.add(fingerprint);\n\t\t} else {\n\t\t\tconflictingBoundFingerprints.add(fingerprint);\n\t\t}\n\t}\n\tfor (const fingerprint of conflictingBoundFingerprints)\n\t\tlocallyBoundFingerprints.delete(fingerprint);\n\treturn { boundFingerprints, locallyBoundFingerprints };\n}\n","/** Persisted vector writer contract and readiness-gated semantic ranking. */\nimport type { Database } from \"../db.js\";\nimport {\n\ttype RankingRequest,\n\ttype RankingResult,\n\trankPrevalidatedSnapshot,\n\tresolveCatalogModels,\n} from \"./semantic-ranking.js\";\nimport {\n\ttype CandidateVersion,\n\tisSearchableVectorCatalog,\n\treadCandidateVersions,\n\treadCatalog,\n\treadSearchableModelLabels,\n\tsnapshot,\n} from \"./validated-vector-index-state.js\";\n\nexport { auditBatch, startAudit } from \"./validated-vector-index-audit.js\";\nexport {\n\tdeleteValidatedVectors,\n\ttype ValidatedBatch,\n\twriteValidatedBatch,\n} from \"./validated-vector-index-mutations.js\";\nexport {\n\ttype AuditProgress,\n\ttype CandidateVersion,\n\tinitializeValidatedIndex,\n\tinvalidateValidatedIndex,\n\tisSearchableVectorCatalog,\n\treadCandidateVersions,\n\treadCatalog,\n\treadSearchableModelLabels,\n\ttype VectorCatalog,\n} from \"./validated-vector-index-state.js\";\n\nexport interface IndexedRanking extends RankingResult {\n\tgenerationId: string;\n\trevision: number;\n\tmodels: string[];\n\tcandidateVersions: CandidateVersion[];\n}\n\n/** Reuses a caller-owned read transaction; no DDL, audit, BLOB hashes or model-catalog vec0 scan. */\nexport function rankValidatedIndex(db: Database, request: RankingRequest): IndexedRanking | null {\n\treturn snapshot(db, () => {\n\t\tconst catalog = readCatalog(db);\n\t\tif (!isSearchableVectorCatalog(db, catalog)) return null;\n\t\tconst models = resolveCatalogModels(\n\t\t\trequest.query.model,\n\t\t\treadSearchableModelLabels(db, catalog),\n\t\t\tcatalog.migration,\n\t\t);\n\t\tif (!models.length) return null;\n\t\tconst ranked = rankPrevalidatedSnapshot(db, request, {\n\t\t\tmodels,\n\t\t\tacceptedIds: null,\n\t\t\tindexedRows: true,\n\t\t});\n\t\tconst candidateVersions = readCandidateVersions(db, {\n\t\t\tmemoryIds: ranked.results.map((row) => row.id),\n\t\t\tmodels,\n\t\t});\n\t\treturn {\n\t\t\t...ranked,\n\t\t\tgenerationId: catalog.generationId,\n\t\t\trevision: catalog.revision,\n\t\t\tmodels,\n\t\t\tcandidateVersions,\n\t\t};\n\t});\n}\n","import { createHash } from \"node:crypto\";\nimport type { Database } from \"../db.js\";\nimport { resolveSameActorPeerIds } from \"../same-actor-peers.js\";\nimport type { AutomaticContext } from \"../types.js\";\nimport type { RankInput, RankOutput } from \"./semantic-worker-protocol.js\";\nimport {\n\tisSearchableVectorCatalog,\n\trankValidatedIndex,\n\treadCatalog,\n} from \"./validated-vector-index.js\";\n\nexport function contentIdentity(row: Record<string, unknown>): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(row)).digest(\"hex\");\n}\n\nexport function summarySessionId(\n\tdb: Database,\n\tcontext: AutomaticContext | null | undefined,\n): number | null | undefined {\n\tif (context === undefined) return undefined;\n\tif (context === null) return null;\n\tconst source = context.source.trim().toLowerCase();\n\tconst streamId = context.hostSessionId.trim();\n\tif (!source || !streamId || streamId.toLowerCase() === \"unknown\") return null;\n\tconst row = db\n\t\t.prepare(\"SELECT session_id FROM opencode_sessions WHERE source = ? AND stream_id = ? LIMIT 1\")\n\t\t.get(source, streamId) as { session_id: number | null } | undefined;\n\treturn row?.session_id ?? null;\n}\n\n/** Authorization, continuity, model selection, ranking and identities share one short read snapshot. */\nexport function rankWorkerInput(db: Database, input: RankInput): RankOutput | null {\n\treturn db.transaction(() => {\n\t\tconst catalog = readCatalog(db);\n\t\tif (!isSearchableVectorCatalog(db, catalog) || catalog.generationId !== input.generationId)\n\t\t\treturn null;\n\t\tconst claimedDeviceIds = resolveSameActorPeerIds(db, input.proof.actorId);\n\t\tconst ranked = rankValidatedIndex(db, {\n\t\t\tquery: { model: input.embeddingIdentity, vectors: [input.embedding] },\n\t\t\tlimit: input.limit,\n\t\t\tfilters: input.filters,\n\t\t\tcontext: {\n\t\t\t\t...input.proof,\n\t\t\t\tclaimedDeviceIds,\n\t\t\t\tlegacyActorIds: claimedDeviceIds.map((id) => `legacy-sync:${id}`),\n\t\t\t\tscopeVisibilityDb: db,\n\t\t\t},\n\t\t\tsummarySessionId: summarySessionId(db, input.automaticContext),\n\t\t});\n\t\tif (!ranked || ranked.generationId !== input.generationId) return null;\n\t\treturn {\n\t\t\tgenerationId: ranked.generationId,\n\t\t\trevision: ranked.revision,\n\t\t\tmodels: ranked.models,\n\t\t\tcandidateVersions: ranked.candidateVersions,\n\t\t\tcandidates: ranked.results.map((row) => {\n\t\t\t\tconst raw = db.prepare(\"SELECT * FROM memory_items WHERE id = ?\").get(row.id) as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\tunknown\n\t\t\t\t>;\n\t\t\t\treturn {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\td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